From svnnotify ¡÷ sourceforge.jp Thu May 1 07:16:24 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 01 May 2008 07:16:24 +0900 Subject: [pal-cvs 3164] [900] set java compiler to 1.4. Message-ID: <1209593784.086640.3724.nullmailer@users.sourceforge.jp> Revision: 900 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=900 Author: shinsuke Date: 2008-05-01 07:16:23 +0900 (Thu, 01 May 2008) Log Message: ----------- set java compiler to 1.4. Modified Paths: -------------- webparts/trunk/.settings/org.eclipse.jdt.core.prefs -------------- next part -------------- Modified: webparts/trunk/.settings/org.eclipse.jdt.core.prefs =================================================================== --- webparts/trunk/.settings/org.eclipse.jdt.core.prefs 2008-04-30 05:09:48 UTC (rev 899) +++ webparts/trunk/.settings/org.eclipse.jdt.core.prefs 2008-04-30 22:16:23 UTC (rev 900) @@ -1,5 +1,15 @@ -#Sat Apr 26 07:08:17 JST 2008 +#Thu May 01 06:26:27 JST 2008 eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.source=1.3 org.eclipse.jdt.core.formatter.align_type_members_on_columns=false org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 From svnnotify ¡÷ sourceforge.jp Thu May 1 07:17:23 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 01 May 2008 07:17:23 +0900 Subject: [pal-cvs 3165] [901] cached content in ProxyServlet. Message-ID: <1209593843.630504.4126.nullmailer@users.sourceforge.jp> Revision: 901 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=901 Author: shinsuke Date: 2008-05-01 07:17:23 +0900 (Thu, 01 May 2008) Log Message: ----------- cached content in ProxyServlet. Modified Paths: -------------- webparts/trunk/.classpath webparts/trunk/webparts-core/pom.xml webparts/trunk/webparts-core/src/main/java/jp/sf/pal/webparts/ProxyServlet.java webparts/trunk/webparts-portlet/pom.xml -------------- next part -------------- Modified: webparts/trunk/.classpath =================================================================== --- webparts/trunk/.classpath 2008-04-30 22:16:23 UTC (rev 900) +++ webparts/trunk/.classpath 2008-04-30 22:17:23 UTC (rev 901) @@ -3,6 +3,7 @@ + Modified: webparts/trunk/webparts-core/pom.xml =================================================================== --- webparts/trunk/webparts-core/pom.xml 2008-04-30 22:16:23 UTC (rev 900) +++ webparts/trunk/webparts-core/pom.xml 2008-04-30 22:17:23 UTC (rev 901) @@ -26,6 +26,11 @@ provided + commons-collections + commons-collections + 3.2.1 + + commons-lang commons-lang 2.4 Modified: webparts/trunk/webparts-core/src/main/java/jp/sf/pal/webparts/ProxyServlet.java =================================================================== --- webparts/trunk/webparts-core/src/main/java/jp/sf/pal/webparts/ProxyServlet.java 2008-04-30 22:16:23 UTC (rev 900) +++ webparts/trunk/webparts-core/src/main/java/jp/sf/pal/webparts/ProxyServlet.java 2008-04-30 22:17:23 UTC (rev 901) @@ -1,23 +1,84 @@ package jp.sf.pal.webparts; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.commons.collections.map.LRUMap; +import org.apache.commons.lang.StringUtils; + public class ProxyServlet extends HttpServlet { private static final long serialVersionUID = -5314394726940661335L; private static final int BLOCK_SIZE = 4096; + private static final int DEFAULT_CACHE_SIZE = 20; + + private static final long DEFAULT_CACHE_TIMEOUT = 60 * 60 * 1000; // 1 hour + + private static final String DEFAULT_HEADER_NAMES = "Content-Type"; + public static final String URL_KEY = "url"; + public static final String MAX_CACHE_SIZE_KEY = "maxCacheSize"; + + public static final String CACHE_TIMEOUT_KEY = "cacheTimeout"; + + public static final String HEADER_NAMES_KEY = "headerNames"; + + protected long cacheTimeout = DEFAULT_CACHE_TIMEOUT; + + protected int maxCacheSize = DEFAULT_CACHE_SIZE; + + protected String[] headerNames; + + protected LRUMap contentCacheMap; + + public void init() throws ServletException { + String cacheTimeoutValue = getServletConfig().getInitParameter( + CACHE_TIMEOUT_KEY); + if (cacheTimeoutValue != null) { + try { + cacheTimeout = Long.parseLong(cacheTimeoutValue); + } catch (NumberFormatException e) { + } + } + + String maxCacheSizeValue = getServletConfig().getInitParameter( + MAX_CACHE_SIZE_KEY); + if (maxCacheSizeValue != null) { + try { + maxCacheSize = Integer.parseInt(maxCacheSizeValue); + } catch (NumberFormatException e) { + } + } + + String headerNamesValue = getServletConfig().getInitParameter( + HEADER_NAMES_KEY); + if (headerNamesValue == null) { + headerNamesValue = DEFAULT_HEADER_NAMES; + } + headerNames = headerNamesValue.split(","); + + contentCacheMap = new LRUMap(maxCacheSize); + } + + public void destroy() { + contentCacheMap = null; + } + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String u = req.getParameter(URL_KEY); @@ -26,17 +87,46 @@ return; } - try { - URL url = new URL(u); - URLConnection uc = url.openConnection(); - drain(uc.getInputStream(), resp.getOutputStream()); - } catch (Exception e) { - resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e - .getMessage()); - return; + ContentCache contentCache = getContentCache(u); + if (contentCache == null) { + // load a content + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try { + URL url = new URL(u); + URLConnection uc = url.openConnection(); + // store a content to a byte array + drain(uc.getInputStream(), baos); + // copy header fields + Map headers = new HashMap(); + Map headerFields = uc.getHeaderFields(); + for (int i = 0; i < headerNames.length; i++) { + headers.put(headerNames[i], headerFields + .get(headerNames[i])); + } + contentCache = new ContentCache(headers, baos.toByteArray(), + System.currentTimeMillis()); + contentCacheMap.put(u, contentCache); + } catch (Exception e) { + resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e + .getMessage()); + return; + } } - // TODO cache + // store headers + Iterator ite = contentCache.getHeaders().entrySet().iterator(); + while (ite.hasNext()) { + Map.Entry entry = (Map.Entry) ite.next(); + if (entry.getValue() instanceof Collection) { + resp.addHeader((String) entry.getKey(), StringUtils.join( + (Collection) entry.getValue(), ",")); + } + } + + // store a content + resp.getOutputStream().write(contentCache.getContent()); + resp.flushBuffer(); + } protected void doPost(HttpServletRequest req, HttpServletResponse resp) @@ -44,6 +134,18 @@ doGet(req, resp); } + protected ContentCache getContentCache(String url) { + ContentCache cache = (ContentCache) contentCacheMap.get(url); + if (cache != null) { + if (System.currentTimeMillis() - cache.getCreatedTime() > cacheTimeout) { + // timeout + return null; + } + return cache; + } + return null; + } + public static void drain(InputStream r, OutputStream w) throws IOException { byte[] bytes = new byte[BLOCK_SIZE]; try { @@ -59,4 +161,43 @@ } } + private static class ContentCache { + private byte[] content; + + private long createdTime; + + private Map headers; + + public ContentCache(Map headers, byte[] content, long createdTime) { + this.headers = headers; + this.content = content; + this.createdTime = createdTime; + } + + public Map getHeaders() { + return headers; + } + + public void setHeaders(Map headers) { + this.headers = headers; + } + + public byte[] getContent() { + return content; + } + + public void setContent(byte[] content) { + this.content = content; + } + + public long getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(long createdTime) { + this.createdTime = createdTime; + } + + } + } Modified: webparts/trunk/webparts-portlet/pom.xml =================================================================== --- webparts/trunk/webparts-portlet/pom.xml 2008-04-30 22:16:23 UTC (rev 900) +++ webparts/trunk/webparts-portlet/pom.xml 2008-04-30 22:17:23 UTC (rev 901) @@ -41,6 +41,11 @@ 1.0.4 + commons-collections + commons-collections + 3.2.1 + + commons-lang commons-lang 2.4 From svnnotify ¡÷ sourceforge.jp Thu May 1 09:35:56 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 01 May 2008 09:35:56 +0900 Subject: [pal-cvs 3166] [902] replace contet type, and check urls. Message-ID: <1209602156.952488.5872.nullmailer@users.sourceforge.jp> Revision: 902 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=902 Author: shinsuke Date: 2008-05-01 09:35:56 +0900 (Thu, 01 May 2008) Log Message: ----------- replace contet type, and check urls. Modified Paths: -------------- webparts/trunk/webparts-core/src/main/java/jp/sf/pal/webparts/ProxyServlet.java webparts/trunk/webparts-portlet/src/main/webapp/WEB-INF/web.xml -------------- next part -------------- Modified: webparts/trunk/webparts-core/src/main/java/jp/sf/pal/webparts/ProxyServlet.java =================================================================== --- webparts/trunk/webparts-core/src/main/java/jp/sf/pal/webparts/ProxyServlet.java 2008-04-30 22:17:23 UTC (rev 901) +++ webparts/trunk/webparts-core/src/main/java/jp/sf/pal/webparts/ProxyServlet.java 2008-05-01 00:35:56 UTC (rev 902) @@ -6,9 +6,11 @@ import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; +import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Map; import javax.servlet.ServletException; @@ -20,6 +22,10 @@ import org.apache.commons.lang.StringUtils; public class ProxyServlet extends HttpServlet { + private static final String NEW_VALUE = "new"; + + private static final String OLD_VALUE = "old"; + private static final long serialVersionUID = -5314394726940661335L; private static final int BLOCK_SIZE = 4096; @@ -28,6 +34,8 @@ private static final long DEFAULT_CACHE_TIMEOUT = 60 * 60 * 1000; // 1 hour + private static final String CONTENT_TYPE = "Content-Type"; + private static final String DEFAULT_HEADER_NAMES = "Content-Type"; public static final String URL_KEY = "url"; @@ -38,12 +46,20 @@ public static final String HEADER_NAMES_KEY = "headerNames"; + public static final String ACCEPT_URLS_KEY = "acceptUrls"; + + public static final String REPLACE_CONTEXT_TYPE_LIST_KEY = "replaceContextTypeList"; + protected long cacheTimeout = DEFAULT_CACHE_TIMEOUT; protected int maxCacheSize = DEFAULT_CACHE_SIZE; protected String[] headerNames; + protected String[] acceptUrls = null; + + protected List replaceContextTypeList = null; + protected LRUMap contentCacheMap; public void init() throws ServletException { @@ -72,6 +88,28 @@ } headerNames = headerNamesValue.split(","); + String acceptUrlsValue = getServletConfig().getInitParameter( + ACCEPT_URLS_KEY); + if (acceptUrlsValue != null) { + acceptUrls = acceptUrlsValue.split(","); + } + + String replacedContextTypeListValue = getServletConfig() + .getInitParameter(REPLACE_CONTEXT_TYPE_LIST_KEY); + if (replacedContextTypeListValue != null) { + replaceContextTypeList = new ArrayList(); + String[] list = replacedContextTypeListValue.split(","); + for (int i = 0; i < list.length; i++) { + String[] pair = list[i].split("="); + if (pair.length == 2) { + Map map = new HashMap(2); + map.put(OLD_VALUE, pair[0]); + map.put(NEW_VALUE, pair[1]); + replaceContextTypeList.add(map); + } + } + } + contentCacheMap = new LRUMap(maxCacheSize); } @@ -87,6 +125,21 @@ return; } + // check url + if (acceptUrls != null) { + boolean valid = false; + for (int i = 0; i < acceptUrls.length; i++) { + if (u.startsWith(acceptUrls[i])) { + valid = true; + } + } + if (!valid) { + resp.sendError(HttpServletResponse.SC_BAD_REQUEST, + "url is not accepted."); + return; + } + } + ContentCache contentCache = getContentCache(u); if (contentCache == null) { // load a content @@ -100,8 +153,27 @@ Map headers = new HashMap(); Map headerFields = uc.getHeaderFields(); for (int i = 0; i < headerNames.length; i++) { - headers.put(headerNames[i], headerFields - .get(headerNames[i])); + if (CONTENT_TYPE.equals(headerNames[i]) + && replaceContextTypeList != null) { + Collection value = (Collection) headerFields + .get(headerNames[i]); + // replace content type + for (int j = 0; j < replaceContextTypeList.size(); j++) { + Map map = (Map) replaceContextTypeList.get(j); + String contentType = uc.getContentType(); + if (contentType != null) { + contentType = StringUtils.replace(contentType, + (String) map.get(OLD_VALUE), + (String) map.get(NEW_VALUE)); + value = new ArrayList(1); + value.add(contentType); + } + } + headers.put(headerNames[i], value); + } else { + headers.put(headerNames[i], headerFields + .get(headerNames[i])); + } } contentCache = new ContentCache(headers, baos.toByteArray(), System.currentTimeMillis()); Modified: webparts/trunk/webparts-portlet/src/main/webapp/WEB-INF/web.xml =================================================================== --- webparts/trunk/webparts-portlet/src/main/webapp/WEB-INF/web.xml 2008-04-30 22:17:23 UTC (rev 901) +++ webparts/trunk/webparts-portlet/src/main/webapp/WEB-INF/web.xml 2008-05-01 00:35:56 UTC (rev 902) @@ -7,6 +7,10 @@ ProxyServlet jp.sf.pal.webparts.ProxyServlet + ProxyServlet From svnnotify ¡÷ sourceforge.jp Thu May 1 17:59:21 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 01 May 2008 17:59:21 +0900 Subject: [pal-cvs 3167] [903] catch an exception. Message-ID: <1209632361.311674.19671.nullmailer@users.sourceforge.jp> Revision: 903 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=903 Author: shinsuke Date: 2008-05-01 17:59:21 +0900 (Thu, 01 May 2008) Log Message: ----------- catch an exception. Modified Paths: -------------- advertising/trunk/pom.xml advertising/trunk/src/main/java/jp/sf/pal/advertising/entity/AdvertisingList.java advertising/trunk/src/main/java/jp/sf/pal/advertising/portlet/AdvertisingPortlet.java -------------- next part -------------- Modified: advertising/trunk/pom.xml =================================================================== --- advertising/trunk/pom.xml 2008-05-01 00:35:56 UTC (rev 902) +++ advertising/trunk/pom.xml 2008-05-01 08:59:21 UTC (rev 903) @@ -3,7 +3,7 @@ 4.0.0 jp.sf.pal advertising - 1.0-SNAPSHOT + 1.0 war Advertising Portlet Modified: advertising/trunk/src/main/java/jp/sf/pal/advertising/entity/AdvertisingList.java =================================================================== --- advertising/trunk/src/main/java/jp/sf/pal/advertising/entity/AdvertisingList.java 2008-05-01 00:35:56 UTC (rev 902) +++ advertising/trunk/src/main/java/jp/sf/pal/advertising/entity/AdvertisingList.java 2008-05-01 08:59:21 UTC (rev 903) @@ -71,6 +71,9 @@ public Advertising getAdvertising() { int size = advertisingList.size(); if (size > 0) { + if (position >= size) { + position = 0; + } Advertising ad = advertisingList.get(position); position++; if (position >= size) { Modified: advertising/trunk/src/main/java/jp/sf/pal/advertising/portlet/AdvertisingPortlet.java =================================================================== --- advertising/trunk/src/main/java/jp/sf/pal/advertising/portlet/AdvertisingPortlet.java 2008-05-01 00:35:56 UTC (rev 902) +++ advertising/trunk/src/main/java/jp/sf/pal/advertising/portlet/AdvertisingPortlet.java 2008-05-01 08:59:21 UTC (rev 903) @@ -36,6 +36,8 @@ * @author Shinsuke Sugaya */ public class AdvertisingPortlet extends GenericPortlet { + private static final String EMPTY_STRING = ""; + /** * Logger for this class */ @@ -111,8 +113,13 @@ AdvertisingList advertisingList = (AdvertisingList) getPortletContext() .getAttribute(SCOPE_PREFIX + advertisingScope); advertisingList.load(); - response.getWriter().print( - advertisingList.getAdvertising().getContent()); + String content = EMPTY_STRING; + try { + content = advertisingList.getAdvertising().getContent(); + } catch (Exception e) { + log.error("Could not load an advertising. ", e); + } + response.getWriter().print(content); response.getWriter().flush(); response.getWriter().close(); } From svnnotify ¡÷ sourceforge.jp Thu May 1 18:17:07 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 01 May 2008 18:17:07 +0900 Subject: [pal-cvs 3168] [904] added UserRegistrationPortlet. Message-ID: <1209633427.211785.1589.nullmailer@users.sourceforge.jp> Revision: 904 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=904 Author: shinsuke Date: 2008-05-01 18:17:07 +0900 (Thu, 01 May 2008) Log Message: ----------- added UserRegistrationPortlet. Modified Paths: -------------- pal-admin/trunk/src/main/webapp/WEB-INF/jetspeed-portlet.xml -------------- next part -------------- Modified: pal-admin/trunk/src/main/webapp/WEB-INF/jetspeed-portlet.xml =================================================================== --- pal-admin/trunk/src/main/webapp/WEB-INF/jetspeed-portlet.xml 2008-05-01 08:59:21 UTC (rev 903) +++ pal-admin/trunk/src/main/webapp/WEB-INF/jetspeed-portlet.xml 2008-05-01 09:17:07 UTC (rev 904) @@ -1,6 +1,6 @@ - + admin PAL Portal Administration Portlets PAL Portal ´ÉÍý¥Ý¡¼¥È¥ì¥Ã¥È From svnnotify ¡÷ sourceforge.jp Fri May 2 11:58:58 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Fri, 02 May 2008 11:58:58 +0900 Subject: [pal-cvs 3172] [908] check guid value. Message-ID: <1209697138.194963.5075.nullmailer@users.sourceforge.jp> Revision: 908 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=908 Author: shinsuke Date: 2008-05-02 11:58:58 +0900 (Fri, 02 May 2008) Log Message: ----------- check guid value. Modified Paths: -------------- pal-admin-ex/trunk/src/main/java/jp/sf/pal/admin/web/registration/PublicPortalForgottenPasswordCompletedPage.java pal-admin-ex/trunk/src/main/java/jp/sf/pal/admin/web/registration/PublicPortalForgottenPasswordPage.java pal-admin-ex/trunk/src/main/java/jp/sf/pal/admin/web/registration/PublicPortalSecretAnswerPage.java -------------- next part -------------- Modified: pal-admin-ex/trunk/src/main/java/jp/sf/pal/admin/web/registration/PublicPortalForgottenPasswordCompletedPage.java =================================================================== --- pal-admin-ex/trunk/src/main/java/jp/sf/pal/admin/web/registration/PublicPortalForgottenPasswordCompletedPage.java 2008-05-02 02:55:32 UTC (rev 907) +++ pal-admin-ex/trunk/src/main/java/jp/sf/pal/admin/web/registration/PublicPortalForgottenPasswordCompletedPage.java 2008-05-02 02:58:58 UTC (rev 908) @@ -17,11 +17,13 @@ import java.io.Serializable; -import org.seasar.framework.log.Logger; +import javax.faces.context.FacesContext; import jp.sf.pal.common.CommonException; import jp.sf.pal.common.util.FacesMessageUtil; +import org.seasar.framework.log.Logger; + public class PublicPortalForgottenPasswordCompletedPage extends AbstractResetPasswordPage implements Serializable { @@ -38,6 +40,12 @@ } public Class prerender() { + // check guid + if (getGuid() == null) { + setGuid((String) FacesContext.getCurrentInstance() + .getExternalContext().getRequestParameterMap().get("guid")); + } + if (getGuid() != null) { try { getUserRegistrationService().updatePassword(this); Modified: pal-admin-ex/trunk/src/main/java/jp/sf/pal/admin/web/registration/PublicPortalForgottenPasswordPage.java =================================================================== --- pal-admin-ex/trunk/src/main/java/jp/sf/pal/admin/web/registration/PublicPortalForgottenPasswordPage.java 2008-05-02 02:55:32 UTC (rev 907) +++ pal-admin-ex/trunk/src/main/java/jp/sf/pal/admin/web/registration/PublicPortalForgottenPasswordPage.java 2008-05-02 02:58:58 UTC (rev 908) @@ -38,8 +38,12 @@ } public Class prerender() { - setGuid((String) FacesContext.getCurrentInstance().getExternalContext() - .getRequestParameterMap().get("guid")); + // check guid + if (getGuid() == null) { + setGuid((String) FacesContext.getCurrentInstance() + .getExternalContext().getRequestParameterMap().get("guid")); + } + if (getGuid() != null) { return PublicPortalForgottenPasswordCompletedPage.class; } Modified: pal-admin-ex/trunk/src/main/java/jp/sf/pal/admin/web/registration/PublicPortalSecretAnswerPage.java =================================================================== --- pal-admin-ex/trunk/src/main/java/jp/sf/pal/admin/web/registration/PublicPortalSecretAnswerPage.java 2008-05-02 02:55:32 UTC (rev 907) +++ pal-admin-ex/trunk/src/main/java/jp/sf/pal/admin/web/registration/PublicPortalSecretAnswerPage.java 2008-05-02 02:58:58 UTC (rev 908) @@ -99,8 +99,12 @@ } public Class prerender() { - setGuid((String) FacesContext.getCurrentInstance().getExternalContext() - .getRequestParameterMap().get("guid")); + // check guid + if (getGuid() == null) { + setGuid((String) FacesContext.getCurrentInstance() + .getExternalContext().getRequestParameterMap().get("guid")); + } + if (getGuid() != null) { return PublicPortalForgottenPasswordCompletedPage.class; } From svnnotify ¡÷ sourceforge.jp Fri May 2 12:06:42 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Fri, 02 May 2008 12:06:42 +0900 Subject: [pal-cvs 3173] [909] replaced with pal-admin Message-ID: <1209697602.894620.16224.nullmailer@users.sourceforge.jp> Revision: 909 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=909 Author: shinsuke Date: 2008-05-02 12:06:42 +0900 (Fri, 02 May 2008) Log Message: ----------- replaced with pal-admin Modified Paths: -------------- pal-admin/trunk/src/main/webapp/WEB-INF/jetspeed-portlet.xml -------------- next part -------------- Modified: pal-admin/trunk/src/main/webapp/WEB-INF/jetspeed-portlet.xml =================================================================== --- pal-admin/trunk/src/main/webapp/WEB-INF/jetspeed-portlet.xml 2008-05-02 02:58:58 UTC (rev 908) +++ pal-admin/trunk/src/main/webapp/WEB-INF/jetspeed-portlet.xml 2008-05-02 03:06:42 UTC (rev 909) @@ -14,7 +14,7 @@ either express or implied. See the License for the specific language governing permissions and limitations under the License. --> - + admin PAL Portal Administration Portlets PAL Portal ´ÉÍý¥Ý¡¼¥È¥ì¥Ã¥È From svnnotify ¡÷ sourceforge.jp Fri May 2 12:07:30 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Fri, 02 May 2008 12:07:30 +0900 Subject: [pal-cvs 3174] [910] 1.1-SNAPSHOT Message-ID: <1209697650.590362.16620.nullmailer@users.sourceforge.jp> Revision: 910 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=910 Author: shinsuke Date: 2008-05-02 12:07:30 +0900 (Fri, 02 May 2008) Log Message: ----------- 1.1-SNAPSHOT Modified Paths: -------------- pal-admin/trunk/pom.xml -------------- next part -------------- Modified: pal-admin/trunk/pom.xml =================================================================== --- pal-admin/trunk/pom.xml 2008-05-02 03:06:42 UTC (rev 909) +++ pal-admin/trunk/pom.xml 2008-05-02 03:07:30 UTC (rev 910) @@ -3,7 +3,7 @@ 4.0.0 jp.sf.pal pal-admin - 1.0 + 1.1-SNAPSHOT war Administration tools for PAL Portal From svnnotify ¡÷ sourceforge.jp Sun May 11 17:42:07 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Sun, 11 May 2008 17:42:07 +0900 Subject: [pal-cvs 3175] [911] set false to a default value for addHtmlTags. Message-ID: <1210495327.684367.30944.nullmailer@users.sourceforge.jp> Revision: 911 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=911 Author: shinsuke Date: 2008-05-11 17:42:07 +0900 (Sun, 11 May 2008) Log Message: ----------- set false to a default value for addHtmlTags. Modified Paths: -------------- libraries/facesdevfilter/trunk/src/main/java/jp/sf/pal/facesdevfilter/FacesDevFilter.java -------------- next part -------------- Modified: libraries/facesdevfilter/trunk/src/main/java/jp/sf/pal/facesdevfilter/FacesDevFilter.java =================================================================== --- libraries/facesdevfilter/trunk/src/main/java/jp/sf/pal/facesdevfilter/FacesDevFilter.java 2008-05-02 03:07:30 UTC (rev 910) +++ libraries/facesdevfilter/trunk/src/main/java/jp/sf/pal/facesdevfilter/FacesDevFilter.java 2008-05-11 08:42:07 UTC (rev 911) @@ -101,7 +101,7 @@ addHtmlTags = false; } } else { - addHtmlTags = true; + addHtmlTags = false; } } From svnnotify ¡÷ sourceforge.jp Sun May 11 17:42:22 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Sun, 11 May 2008 17:42:22 +0900 Subject: [pal-cvs 3176] [912] version 0.2 Message-ID: <1210495342.048055.31008.nullmailer@users.sourceforge.jp> Revision: 912 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=912 Author: shinsuke Date: 2008-05-11 17:42:21 +0900 (Sun, 11 May 2008) Log Message: ----------- version 0.2 Modified Paths: -------------- libraries/facesdevfilter/trunk/pom.xml -------------- next part -------------- Modified: libraries/facesdevfilter/trunk/pom.xml =================================================================== --- libraries/facesdevfilter/trunk/pom.xml 2008-05-11 08:42:07 UTC (rev 911) +++ libraries/facesdevfilter/trunk/pom.xml 2008-05-11 08:42:21 UTC (rev 912) @@ -4,7 +4,7 @@ jp.sf.pal faces-dev-filter jar - 0.2-SNAPSHOT + 0.2 Servlet Filter To Develop Portlet on Servlet Environment http://pal.sourceforge.jp/ 2005 @@ -117,7 +117,7 @@ maven.marevol.com Maven2 Repository on marevol.com - http://www.marevol.com/maven2 + http://maven2.marevol.com/ From svnnotify ¡÷ sourceforge.jp Tue May 13 18:05:27 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Tue, 13 May 2008 18:05:27 +0900 Subject: [pal-cvs 3177] [913] fixed a problem from 887 Message-ID: <1210669527.768259.3646.nullmailer@users.sourceforge.jp> Revision: 913 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=913 Author: shinsuke Date: 2008-05-13 18:05:27 +0900 (Tue, 13 May 2008) Log Message: ----------- fixed a problem from 887 Modified Paths: -------------- pal-portal/trunk/build.properties -------------- next part -------------- Modified: pal-portal/trunk/build.properties =================================================================== --- pal-portal/trunk/build.properties 2008-05-11 08:42:21 UTC (rev 912) +++ pal-portal/trunk/build.properties 2008-05-13 09:05:27 UTC (rev 913) @@ -219,6 +219,7 @@ portal.delete.files=\ src/webapp/WEB-INF/conf/override.properties,\ + portal.delete.directories=\ src/webapp/WEB-INF/pages/,\ src/webapp/desktop-themes/,\ From svnnotify ¡÷ sourceforge.jp Tue May 13 18:05:53 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Tue, 13 May 2008 18:05:53 +0900 Subject: [pal-cvs 3178] [914] fixed logout problem. Message-ID: <1210669553.401351.3780.nullmailer@users.sourceforge.jp> Revision: 914 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=914 Author: shinsuke Date: 2008-05-13 18:05:53 +0900 (Tue, 13 May 2008) Log Message: ----------- fixed logout problem. Modified Paths: -------------- pal-portal/trunk/portal/patches/components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionMonitorImpl.java -------------- next part -------------- Modified: pal-portal/trunk/portal/patches/components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionMonitorImpl.java =================================================================== --- pal-portal/trunk/portal/patches/components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionMonitorImpl.java 2008-05-13 09:05:27 UTC (rev 913) +++ pal-portal/trunk/portal/patches/components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionMonitorImpl.java 2008-05-13 09:05:53 UTC (rev 914) @@ -1,13 +1,17 @@ Index: components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionMonitorImpl.java =================================================================== ---- components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionMonitorImpl.java (¥ê¥Ó¥¸¥ç¥ó 628183) +--- components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionMonitorImpl.java (¥ê¥Ó¥¸¥ç¥ó 648465) +++ components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionMonitorImpl.java (ºî¶È¥³¥Ô¡¼) -@@ -108,7 +108,7 @@ - */ - public void valueUnbound(HttpSessionBindingEvent event) +@@ -110,6 +110,12 @@ { -- if ( session != null ) -+ if ( session != null && session.getAttribute(SESSION_KEY) == null) + if ( session != null ) { ++ try { ++ if (session.getAttribute(SESSION_KEY) != null) { ++ return; ++ } ++ } catch (Exception e) { ++ } PortalSessionsManager manager = getManager(); if (manager != null) + { From svnnotify ¡÷ sourceforge.jp Tue May 13 18:26:27 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Tue, 13 May 2008 18:26:27 +0900 Subject: [pal-cvs 3179] [915] added AuthFilter to authenticate a user from cookie, request parameter and request header. Message-ID: <1210670787.438061.19993.nullmailer@users.sourceforge.jp> Revision: 915 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=915 Author: shinsuke Date: 2008-05-13 18:26:27 +0900 (Tue, 13 May 2008) Log Message: ----------- added AuthFilter to authenticate a user from cookie, request parameter and request header. Added Paths: ----------- pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/ pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/AbstractAuthFilter.java pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/CookieAuthFilter.java pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/RequestHeaderAuthFilter.java pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/RequestParameterAuthFilter.java -------------- next part -------------- Added: pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/AbstractAuthFilter.java =================================================================== --- pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/AbstractAuthFilter.java (rev 0) +++ pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/AbstractAuthFilter.java 2008-05-13 09:26:27 UTC (rev 915) @@ -0,0 +1,201 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package jp.sf.pal.portal.filter; + +import java.io.IOException; +import java.security.Principal; +import java.util.HashSet; +import java.util.Set; + +import javax.security.auth.Subject; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.jetspeed.Jetspeed; +import org.apache.jetspeed.PortalReservedParameters; +import org.apache.jetspeed.administration.PortalAuthenticationConfiguration; +import org.apache.jetspeed.administration.PortalConfiguration; +import org.apache.jetspeed.audit.AuditActivity; +import org.apache.jetspeed.login.LoginConstants; +import org.apache.jetspeed.login.filter.PortalRequestWrapper; +import org.apache.jetspeed.security.SecurityException; +import org.apache.jetspeed.security.SecurityHelper; +import org.apache.jetspeed.security.User; +import org.apache.jetspeed.security.UserManager; +import org.apache.jetspeed.security.UserPrincipal; +import org.apache.jetspeed.security.impl.PrincipalsSet; +import org.apache.jetspeed.security.impl.UserSubjectPrincipalImpl; + +public abstract class AbstractAuthFilter implements Filter { + private static final Log log = LogFactory.getLog(AbstractAuthFilter.class); + + protected String guest = "guest"; + + protected String usernameKey; + + protected String passwordKey; + + protected boolean skipPasswordCheck = false; + + public void init(FilterConfig filterConfig) throws ServletException { + PortalConfiguration config = Jetspeed.getConfiguration(); + if (config != null) { + guest = config.getString("default.user.principal"); + } + + usernameKey = filterConfig.getInitParameter("username.key"); + if (usernameKey == null) { + usernameKey = LoginConstants.USERNAME; + } + passwordKey = filterConfig.getInitParameter("password.key"); + if (passwordKey == null) { + passwordKey = LoginConstants.PASSWORD; + } + String value = filterConfig.getInitParameter("skip.password.check"); + if (value != null && value.equalsIgnoreCase("true")) { + skipPasswordCheck = true; + } + + // debug + if (log.isDebugEnabled()) { + log.debug("usernameKey=" + usernameKey); + log.debug("passwordKey=" + passwordKey); + log.debug("skipPasswordCheck=" + skipPasswordCheck); + } + } + + public void destroy() { + } + + public void doFilter(ServletRequest sRequest, ServletResponse sResponse, + FilterChain filterChain) throws IOException, ServletException { + if (sRequest instanceof HttpServletRequest) { + HttpServletRequest request = (HttpServletRequest) sRequest; + String username = getUsername(request); + if (username != null) { + UserManager userManager = (UserManager) Jetspeed + .getComponentManager().getComponent( + "org.apache.jetspeed.security.UserManager"); + AuditActivity audit = (AuditActivity) Jetspeed + .getComponentManager().getComponent( + "org.apache.jetspeed.audit.AuditActivity"); + + boolean success = true; + if (!skipPasswordCheck) { + // check password + success = userManager.authenticate(username, + getPassword(request)); + } + + if (success) { + audit.logUserActivity(username, request.getRemoteAddr(), + AuditActivity.AUTHENTICATION_SUCCESS, + "PortalFilter"); + PortalAuthenticationConfiguration authenticationConfiguration = (PortalAuthenticationConfiguration) Jetspeed + .getComponentManager() + .getComponent( + "org.apache.jetspeed.administration.PortalAuthenticationConfiguration"); + + if (authenticationConfiguration.isCreateNewSessionOnLogin()) { + // invalidate session + request.getSession().invalidate(); + } + + Subject subject = null; + try { + // load the user info + User user = userManager.getUser(username); + if (user != null) { + subject = user.getSubject(); + } + } catch (SecurityException sex) { + } + + if (subject == null) { + Set principals = new PrincipalsSet(); + UserSubjectPrincipalImpl userPrincipal = new UserSubjectPrincipalImpl( + username); + principals.add(userPrincipal); + subject = new Subject(true, principals, new HashSet(), + new HashSet()); + userPrincipal.setSubject(subject); + } + + Principal principal = SecurityHelper.getPrincipal(subject, + UserPrincipal.class); + sRequest = wrapperRequest(request, subject, principal); + request.getSession().removeAttribute( + LoginConstants.ERRORCODE); + HttpSession session = request.getSession(true); + session.setAttribute( + PortalReservedParameters.SESSION_KEY_SUBJECT, + subject); + } else { + audit.logUserActivity(username, request.getRemoteAddr(), + AuditActivity.AUTHENTICATION_FAILURE, + "PortalFilter"); + request.getSession().setAttribute(LoginConstants.ERRORCODE, + LoginConstants.ERROR_INVALID_PASSWORD); + + // debug + if (log.isDebugEnabled()) { + log.debug("Authentication failure: username=" + + username); + } + } + } else { + Subject subject = (Subject) request.getSession().getAttribute( + PortalReservedParameters.SESSION_KEY_SUBJECT); + if (subject != null) { + Principal principal = SecurityHelper.getPrincipal(subject, + UserPrincipal.class); + if (principal != null + && principal.getName().equals(this.guest)) { + } else { + sRequest = wrapperRequest(request, subject, principal); + } + } + } + + sRequest.setAttribute( + PortalReservedParameters.PORTAL_FILTER_ATTRIBUTE, "true"); + } + + if (filterChain != null) { + filterChain.doFilter(sRequest, sResponse); + } + } + + private ServletRequest wrapperRequest(HttpServletRequest request, + Subject subject, Principal principal) { + PortalRequestWrapper wrapper = new PortalRequestWrapper(request, + subject, principal); + return wrapper; + } + + public abstract String getUsername(HttpServletRequest request); + + public abstract String getPassword(HttpServletRequest request); +} Property changes on: pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/AbstractAuthFilter.java ___________________________________________________________________ Name: svn:eol-style + native Added: pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/CookieAuthFilter.java =================================================================== --- pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/CookieAuthFilter.java (rev 0) +++ pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/CookieAuthFilter.java 2008-05-13 09:26:27 UTC (rev 915) @@ -0,0 +1,28 @@ +package jp.sf.pal.portal.filter; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; + +public class CookieAuthFilter extends AbstractAuthFilter { + + public String getPassword(HttpServletRequest request) { + return getValueFromCookies(request, passwordKey); + } + + public String getUsername(HttpServletRequest request) { + return getValueFromCookies(request, usernameKey); + } + + protected String getValueFromCookies(HttpServletRequest request, String key) { + Cookie[] cookies = request.getCookies(); + if (cookies != null) { + for (int i = 0; i < cookies.length; i++) { + if (key.equals(cookies[i].getName())) { + return cookies[i].getValue(); + } + } + } + return null; + } + +} Property changes on: pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/CookieAuthFilter.java ___________________________________________________________________ Name: svn:eol-style + native Added: pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/RequestHeaderAuthFilter.java =================================================================== --- pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/RequestHeaderAuthFilter.java (rev 0) +++ pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/RequestHeaderAuthFilter.java 2008-05-13 09:26:27 UTC (rev 915) @@ -0,0 +1,15 @@ +package jp.sf.pal.portal.filter; + +import javax.servlet.http.HttpServletRequest; + +public class RequestHeaderAuthFilter extends AbstractAuthFilter { + + public String getPassword(HttpServletRequest request) { + return request.getHeader(passwordKey); + } + + public String getUsername(HttpServletRequest request) { + return request.getHeader(usernameKey); + } + +} Property changes on: pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/RequestHeaderAuthFilter.java ___________________________________________________________________ Name: svn:eol-style + native Added: pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/RequestParameterAuthFilter.java =================================================================== --- pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/RequestParameterAuthFilter.java (rev 0) +++ pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/RequestParameterAuthFilter.java 2008-05-13 09:26:27 UTC (rev 915) @@ -0,0 +1,13 @@ +package jp.sf.pal.portal.filter; + +import javax.servlet.http.HttpServletRequest; + +public class RequestParameterAuthFilter extends AbstractAuthFilter { + public String getUsername(HttpServletRequest request) { + return request.getParameter(usernameKey); + } + + public String getPassword(HttpServletRequest request) { + return request.getParameter(passwordKey); + } +} Property changes on: pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/RequestParameterAuthFilter.java ___________________________________________________________________ Name: svn:eol-style + native From svnnotify ¡÷ sourceforge.jp Thu May 15 08:52:08 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 08:52:08 +0900 Subject: [pal-cvs 3180] [916] added servlet filter to transfer cookie to others. Message-ID: <1210809128.713036.25216.nullmailer@users.sourceforge.jp> Revision: 916 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=916 Author: shinsuke Date: 2008-05-15 08:52:08 +0900 (Thu, 15 May 2008) Log Message: ----------- added servlet filter to transfer cookie to others. Added Paths: ----------- pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/CookieTransferFilter.java -------------- next part -------------- Added: pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/CookieTransferFilter.java =================================================================== --- pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/CookieTransferFilter.java (rev 0) +++ pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/CookieTransferFilter.java 2008-05-14 23:52:08 UTC (rev 916) @@ -0,0 +1,241 @@ +package jp.sf.pal.portal.filter; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.prefs.Preferences; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.jetspeed.Jetspeed; +import org.apache.jetspeed.security.SecurityException; +import org.apache.jetspeed.security.User; +import org.apache.jetspeed.security.UserManager; + +public class CookieTransferFilter implements Filter { + private static final Log log = LogFactory + .getLog(CookieTransferFilter.class); + + private static final String EMPTY_STRING = ""; + + protected static final String IS_TRANSFERRED = "jp.sf.pal.portal.login.TransferredInfo"; + + // see JSR 168 PLT.D + // an username and password are defined as "username" and "password". + // a format of transferrred.info is "=,..". + protected static final String TRANSFERRED_INFO = "transferred.info"; + + protected static final String PATH = "path"; + + protected static final String DOMAIN = "domain"; + + protected static final String MAX_AGE = "max.age"; + + protected static final String SECURE = "secure"; + + protected static final String USERNAME = "username"; + + protected String path; + + protected String domain; + + protected int maxAge = -1; + + protected boolean secure = false; + + protected String usernameKey; + + protected Map transferredInfo; + + public void init(FilterConfig filterConfig) throws ServletException { + + path = filterConfig.getInitParameter(PATH); + domain = filterConfig.getInitParameter(DOMAIN); + String value = filterConfig.getInitParameter(MAX_AGE); + if (value != null) { + try { + maxAge = Integer.parseInt(value); + } catch (NumberFormatException e) { + } + } + value = filterConfig.getInitParameter(SECURE); + if (value != null && value.equalsIgnoreCase("true")) { + secure = true; + } + + transferredInfo = new HashMap(); + value = filterConfig.getInitParameter(TRANSFERRED_INFO); + if (value != null) { + StringTokenizer st = new StringTokenizer(value, ", \t\n\r\f"); + while (st.hasMoreTokens()) { + String pair = st.nextToken(); + int index = pair.indexOf("="); + if (index > 0 && index + 1 < pair.length()) { + String k = pair.substring(0, index); + String v = pair.substring(index + 1); + + if (USERNAME.equals(v)) { + usernameKey = k; + } else { + transferredInfo.put(k, v); + } + } + } + } + + // debug + if (log.isDebugEnabled()) { + log.debug("path=" + path); + log.debug("domain=" + domain); + log.debug("maxAge=" + maxAge); + log.debug("secure=" + secure); + log.debug("transferredInfo=" + transferredInfo); + } + } + + public void destroy() { + path = null; + domain = null; + usernameKey = null; + transferredInfo = null; + } + + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + + if (request instanceof HttpServletRequest + && response instanceof HttpServletResponse) { + HttpServletRequest hRequest = (HttpServletRequest) request; + HttpServletResponse hResponse = (HttpServletResponse) response; + String username = hRequest.getRemoteUser(); + if (username != null) { + if (!checkTransferredInfo(hRequest, false)) { + UserManager userManager = (UserManager) Jetspeed + .getComponentManager().getComponent( + "org.apache.jetspeed.security.UserManager"); + + if (usernameKey != null) { + hResponse.addCookie(createNewCookie(usernameKey, + username)); + } + + if (!transferredInfo.isEmpty()) { + try { + User user = userManager.getUser(username); + Preferences userAttributes = user + .getUserAttributes(); + Iterator itr = transferredInfo.entrySet() + .iterator(); + while (itr.hasNext()) { + Map.Entry entry = (Map.Entry) itr.next(); + String value = userAttributes + .get((String) entry.getValue(), + EMPTY_STRING); + if (!value.equals(EMPTY_STRING)) { + hResponse.addCookie(createNewCookie( + (String) entry.getKey(), value)); + } + } + } catch (SecurityException e) { + log.warn( + "Could not get the user info: " + username, + e); + } + } + + // additional tasks + storeCookies(hRequest, hResponse); + + hRequest.getSession().setAttribute(IS_TRANSFERRED, + Boolean.TRUE); + } + } else { + if (checkTransferredInfo(hRequest, true)) { + + if (usernameKey != null) { + hResponse.addCookie(createExpiredCookie(usernameKey)); + } + + if (!transferredInfo.isEmpty()) { + Iterator itr = transferredInfo.entrySet().iterator(); + while (itr.hasNext()) { + Map.Entry entry = (Map.Entry) itr.next(); + hResponse + .addCookie(createExpiredCookie((String) entry + .getKey())); + } + } + + // additional tasks + removeCookies(hRequest, hResponse); + + hRequest.getSession().setAttribute(IS_TRANSFERRED, + Boolean.FALSE); + } + } + } + + if (chain != null) { + chain.doFilter(request, response); + } + + } + + protected boolean checkTransferredInfo(HttpServletRequest hRequest, + boolean defaultValue) { + HttpSession session = hRequest.getSession(false); + if (session != null) { + Boolean isTransferredInfo = (Boolean) session + .getAttribute(IS_TRANSFERRED); + if (isTransferredInfo != null) { + return isTransferredInfo.booleanValue(); + } + } + return defaultValue; + } + + protected Cookie createNewCookie(String name, String value) { + return createCookie(name, value, maxAge); + } + + protected Cookie createExpiredCookie(String name) { + return createCookie(name, EMPTY_STRING, 0); + } + + private Cookie createCookie(String name, String value, int age) { + Cookie cookie = new Cookie(name, value); + if (domain != null) { + cookie.setDomain(domain); + } + if (path != null) { + cookie.setPath("/"); + } + cookie.setMaxAge(age); + if (secure) { + cookie.setSecure(secure); + } + return cookie; + } + + protected void storeCookies(HttpServletRequest hRequest, + HttpServletResponse hResponse) { + } + + protected void removeCookies(HttpServletRequest hRequest, + HttpServletResponse hResponse) { + } + +} Property changes on: pal-portal/trunk/portal/files/components/portal/src/java/jp/sf/pal/portal/filter/CookieTransferFilter.java ___________________________________________________________________ Name: svn:eol-style + native From svnnotify ¡÷ sourceforge.jp Thu May 15 10:53:32 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 10:53:32 +0900 Subject: [pal-cvs 3181] [917] moved to tags. Message-ID: <1210816412.921103.29193.nullmailer@users.sourceforge.jp> Revision: 917 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=917 Author: shinsuke Date: 2008-05-15 10:53:32 +0900 (Thu, 15 May 2008) Log Message: ----------- moved to tags. Added Paths: ----------- pal-portal/tags/pal-portal-1.0/ Removed Paths: ------------- pal-portal/branches/pal-portal-1.0/ -------------- next part -------------- Copied: pal-portal/tags/pal-portal-1.0 (from rev 916, pal-portal/branches/pal-portal-1.0) From svnnotify ¡÷ sourceforge.jp Thu May 15 10:54:05 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 10:54:05 +0900 Subject: [pal-cvs 3182] [918] moved to tags. Message-ID: <1210816445.589912.30485.nullmailer@users.sourceforge.jp> Revision: 918 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=918 Author: shinsuke Date: 2008-05-15 10:54:05 +0900 (Thu, 15 May 2008) Log Message: ----------- moved to tags. Added Paths: ----------- pal-portal/tags/pal-portal-1.0-beta5/ Removed Paths: ------------- pal-portal/branches/pal-portal-1.0-beta5/ -------------- next part -------------- Copied: pal-portal/tags/pal-portal-1.0-beta5 (from rev 917, pal-portal/branches/pal-portal-1.0-beta5) From svnnotify ¡÷ sourceforge.jp Thu May 15 10:54:50 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 10:54:50 +0900 Subject: [pal-cvs 3183] [919] moved to tags. Message-ID: <1210816490.816477.30987.nullmailer@users.sourceforge.jp> Revision: 919 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=919 Author: shinsuke Date: 2008-05-15 10:54:50 +0900 (Thu, 15 May 2008) Log Message: ----------- moved to tags. Added Paths: ----------- pal-portal/tags/pal-portal-1.0-beta6/ Removed Paths: ------------- pal-portal/branches/palportal-1.0-beta6/ -------------- next part -------------- Copied: pal-portal/tags/pal-portal-1.0-beta6 (from rev 918, pal-portal/branches/palportal-1.0-beta6) From svnnotify ¡÷ sourceforge.jp Thu May 15 10:55:05 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 10:55:05 +0900 Subject: [pal-cvs 3184] [920] moved to tags. Message-ID: <1210816505.688394.31129.nullmailer@users.sourceforge.jp> Revision: 920 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=920 Author: shinsuke Date: 2008-05-15 10:55:05 +0900 (Thu, 15 May 2008) Log Message: ----------- moved to tags. Added Paths: ----------- pal-portal/tags/pal-portal-1.0.1/ Removed Paths: ------------- pal-portal/branches/pal-portal-1.0.1/ -------------- next part -------------- Copied: pal-portal/tags/pal-portal-1.0.1 (from rev 919, pal-portal/branches/pal-portal-1.0.1) From svnnotify ¡÷ sourceforge.jp Thu May 15 10:58:08 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 10:58:08 +0900 Subject: [pal-cvs 3185] [921] created pal-portal 1.x branch(based on Jetspeed 2.1.3) to start 2. 0 project(based on Jetspeed 2.2). Message-ID: <1210816688.327360.1225.nullmailer@users.sourceforge.jp> Revision: 921 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=921 Author: shinsuke Date: 2008-05-15 10:58:08 +0900 (Thu, 15 May 2008) Log Message: ----------- created pal-portal 1.x branch(based on Jetspeed 2.1.3) to start 2.0 project(based on Jetspeed 2.2). Added Paths: ----------- pal-portal/branches/pal-portal-1.x/ -------------- next part -------------- Copied: pal-portal/branches/pal-portal-1.x (from rev 920, pal-portal/trunk) From svnnotify ¡÷ sourceforge.jp Thu May 15 14:21:31 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 14:21:31 +0900 Subject: [pal-cvs 3186] [923] moved to docs directory. Message-ID: <1210828891.497919.28795.nullmailer@users.sourceforge.jp> Revision: 923 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=923 Author: shinsuke Date: 2008-05-15 14:21:31 +0900 (Thu, 15 May 2008) Log Message: ----------- moved to docs directory. Added Paths: ----------- pal-portal/docs/ Removed Paths: ------------- pal-portal/trunk/docs/ -------------- next part -------------- Copied: pal-portal/docs (from rev 922, pal-portal/trunk/docs) From svnnotify ¡÷ sourceforge.jp Thu May 15 14:22:57 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 14:22:57 +0900 Subject: [pal-cvs 3187] [924] created modules. Message-ID: <1210828977.781285.29953.nullmailer@users.sourceforge.jp> Revision: 924 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=924 Author: shinsuke Date: 2008-05-15 14:22:57 +0900 (Thu, 15 May 2008) Log Message: ----------- created modules. Added Paths: ----------- pal-portal/modules/ -------------- next part -------------- From svnnotify ¡÷ sourceforge.jp Thu May 15 14:25:16 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 14:25:16 +0900 Subject: [pal-cvs 3188] [925] created palportal-sso. Message-ID: <1210829116.224193.31329.nullmailer@users.sourceforge.jp> Revision: 925 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=925 Author: shinsuke Date: 2008-05-15 14:25:16 +0900 (Thu, 15 May 2008) Log Message: ----------- created palportal-sso. Added Paths: ----------- pal-portal/modules/palportal-sso/ -------------- next part -------------- From svnnotify ¡÷ sourceforge.jp Thu May 15 14:25:35 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 14:25:35 +0900 Subject: [pal-cvs 3189] [926] created jetspeed-security-glassfish. Message-ID: <1210829135.692391.31414.nullmailer@users.sourceforge.jp> Revision: 926 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=926 Author: shinsuke Date: 2008-05-15 14:25:35 +0900 (Thu, 15 May 2008) Log Message: ----------- created jetspeed-security-glassfish. Added Paths: ----------- pal-portal/modules/jetspeed-security-glassfish/ -------------- next part -------------- From svnnotify ¡÷ sourceforge.jp Thu May 15 14:26:46 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 14:26:46 +0900 Subject: [pal-cvs 3190] [927] moved into modules. Message-ID: <1210829206.075661.32602.nullmailer@users.sourceforge.jp> Revision: 927 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=927 Author: shinsuke Date: 2008-05-15 14:26:45 +0900 (Thu, 15 May 2008) Log Message: ----------- moved into modules. Added Paths: ----------- pal-portal/modules/jetspeed-security-glassfish/trunk/ Removed Paths: ------------- pal-portal/trunk/components/jetspeed-security-glassfish/ -------------- next part -------------- Copied: pal-portal/modules/jetspeed-security-glassfish/trunk (from rev 926, pal-portal/trunk/components/jetspeed-security-glassfish) From svnnotify ¡÷ sourceforge.jp Thu May 15 14:28:07 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 14:28:07 +0900 Subject: [pal-cvs 3191] [928] moved into modules. Message-ID: <1210829287.628260.1356.nullmailer@users.sourceforge.jp> Revision: 928 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=928 Author: shinsuke Date: 2008-05-15 14:28:07 +0900 (Thu, 15 May 2008) Log Message: ----------- moved into modules. Added Paths: ----------- pal-portal/modules/palportal-sso/trunk/ Removed Paths: ------------- pal-portal/trunk/components/palportal-sso/ -------------- next part -------------- Copied: pal-portal/modules/palportal-sso/trunk (from rev 927, pal-portal/trunk/components/palportal-sso) From svnnotify ¡÷ sourceforge.jp Thu May 15 14:34:30 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 14:34:30 +0900 Subject: [pal-cvs 3192] [929] removed Message-ID: <1210829670.272473.5412.nullmailer@users.sourceforge.jp> Revision: 929 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=929 Author: shinsuke Date: 2008-05-15 14:34:30 +0900 (Thu, 15 May 2008) Log Message: ----------- removed Removed Paths: ------------- pal-portal/trunk/components/ -------------- next part -------------- From svnnotify ¡÷ sourceforge.jp Thu May 15 15:08:06 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 15:08:06 +0900 Subject: [pal-cvs 3193] [930] update fckeditor and change to use servlet Message-ID: <1210831686.289706.11693.nullmailer@users.sourceforge.jp> Revision: 930 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=930 Author: sone Date: 2008-05-15 15:08:06 +0900 (Thu, 15 May 2008) Log Message: ----------- update fckeditor and change to use servlet Modified Paths: -------------- pal-wcm/trunk/.classpath pal-wcm/trunk/.project pal-wcm/trunk/pom.xml pal-wcm/trunk/src/main/webapp/WEB-INF/web.xml pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckcontextmenu.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdocumentfragment_gecko.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdocumentfragment_ie.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrange.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrange_gecko.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrange_ie.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckeditingarea.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckelementpath.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckenterkey.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckevents.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckicon.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckiecleanup.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckimagepreloader.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckkeystrokehandler.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckmenublock.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckmenublockpanel.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckmenuitem.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckpanel.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckplugin.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckspecialcombo.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fcktoolbar.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fcktoolbarbreak_gecko.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fcktoolbarbreak_ie.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fcktoolbarbutton.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fcktoolbarbuttonui.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fcktoolbarfontformatcombo.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fcktoolbarfontscombo.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fcktoolbarfontsizecombo.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fcktoolbarpanelbutton.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fcktoolbarspecialcombo.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fcktoolbarstylecombo.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckw3crange.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckxml_gecko.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckxml_ie.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fck_othercommands.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fckfitwindow.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fcknamedcommand.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fckpasteplaintextcommand.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fckpastewordcommand.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fckspellcheckcommand_gecko.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fckspellcheckcommand_ie.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fckstylecommand.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fcktablecommand.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fcktextcolorcommand.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/fckconstants.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/fckeditorapi.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/fckjscoreextensions.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/fckscriptloader.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fck.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fck_contextmenu.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fck_gecko.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fck_ie.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckbrowserinfo.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckcodeformatter.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckcommands.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckconfig.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckdebug.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckdialog.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckdocumentprocessor.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckdomtools.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fcklanguagemanager.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fcklisthandler.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fcklistslib.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckplugins.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckregexlib.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckselection.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckselection_gecko.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckselection_ie.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fcktablehandler.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fcktablehandler_gecko.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fcktablehandler_ie.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fcktoolbaritems.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fcktoolbarset.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fcktools.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fcktools_gecko.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fcktools_ie.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckurlparams.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckxhtml.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckxhtml_gecko.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckxhtml_ie.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckxhtmlentities.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/css/fck_editorarea.css pal-wcm/trunk/src/main/webapp/fckeditor/editor/css/fck_internal.css pal-wcm/trunk/src/main/webapp/fckeditor/editor/css/fck_showtableborders_gecko.css pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/common/fck_dialog_common.css pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/common/fck_dialog_common.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_about.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_anchor.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_button.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_checkbox.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_colorselector.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_docprops/fck_document_preview.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_docprops.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_flash/fck_flash.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_flash/fck_flash_preview.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_flash.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_form.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_hiddenfield.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_image/fck_image.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_image/fck_image_preview.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_image.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_link/fck_link.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_link.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_listprop.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_paste.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_radiobutton.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_replace.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_select/fck_select.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_select.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_smiley.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_source.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_specialchar.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/server-scripts/spellchecker.cfm pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/server-scripts/spellchecker.php pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/server-scripts/spellchecker.pl pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/spellChecker.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/spellerStyle.css pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_table.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_tablecell.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_template.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_textarea.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_textfield.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/fckdebug.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/fckdialog.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/fckeditor.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/fckeditor.original.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/browser.css pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/browser.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/frmactualfolder.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/frmcreatefolder.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/frmfolders.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/frmresourceslist.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/frmresourcetype.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/frmupload.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/js/common.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/js/fckxml.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/js/fckeditorcode_gecko.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/js/fckeditorcode_ie.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/_translationstatus.txt pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/af.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ar.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/bg.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/bn.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/bs.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ca.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/cs.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/da.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/de.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/el.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en-au.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en-ca.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en-uk.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/eo.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/es.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/et.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/eu.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fa.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fi.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fo.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fr.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/gl.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/he.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/hi.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/hr.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/hu.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/it.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ja.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/km.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ko.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/lt.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/lv.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/mn.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ms.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/nb.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/nl.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/no.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/pl.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/pt-br.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/pt.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ro.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ru.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sk.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sl.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sr-latn.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sr.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sv.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/th.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/tr.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/uk.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/vi.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/zh-cn.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/zh.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/autogrow/fckplugin.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/placeholder/fck_placeholder.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/placeholder/fckplugin.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/placeholder/lang/de.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/placeholder/lang/en.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/placeholder/lang/fr.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/placeholder/lang/it.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/placeholder/lang/pl.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/simplecommands/fckplugin.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/tablecommands/fckplugin.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/_fckviewstrips.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/default/fck_dialog.css pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/default/fck_editor.css pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/default/fck_strip.gif pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/office2003/fck_dialog.css pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/office2003/fck_editor.css pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/office2003/fck_strip.gif pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/silver/fck_dialog.css pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/silver/fck_editor.css pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/silver/fck_strip.gif pal-wcm/trunk/src/main/webapp/fckeditor/fckconfig.js pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.afp pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.asp pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.cfc pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.cfm pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.js pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.lasso pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.php pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.pl pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.py pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor_php4.php pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor_php5.php pal-wcm/trunk/src/main/webapp/fckeditor/fckpackager.xml pal-wcm/trunk/src/main/webapp/fckeditor/fckstyles.xml pal-wcm/trunk/src/main/webapp/fckeditor/fcktemplates.xml pal-wcm/trunk/src/main/webapp/fckeditor/license.txt Added Paths: ----------- pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/FCKeditor.java pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/FCKeditorConfigurations.java pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/servlet/FilesaveServlet.java pal-wcm/trunk/src/main/webapp/WEB-INF/lib/ pal-wcm/trunk/src/main/webapp/WEB-INF/lib/FCKeditor-2.3.jar pal-wcm/trunk/src/main/webapp/WEB-INF/lib/commons-fileupload-1.2.1.jar pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdataprocessor.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrangeiterator.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckhtmliterator.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckstyle.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckxml.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fckblockquotecommand.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fckcorestylecommand.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fckindentcommands.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fckjustifycommands.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fcklistcommands.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fckremoveformatcommand.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/commandclasses/fckshowblocks.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckstyles.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/internals/fckundo.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/css/images/block_address.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/css/images/block_blockquote.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/css/images/block_div.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/css/images/block_h1.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/css/images/block_h2.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/css/images/block_h3.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/css/images/block_h4.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/css/images/block_h5.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/css/images/block_h6.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/css/images/block_p.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/css/images/block_pre.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/css/images/fck_plugin.gif pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_about/sponsors/ pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_about/sponsors/spellchecker_net.gif pal-wcm/trunk/src/main/webapp/fckeditor/editor/dtd/ pal-wcm/trunk/src/main/webapp/fckeditor/editor/dtd/fck_dtd_test.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/dtd/fck_xhtml10strict.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/dtd/fck_xhtml10transitional.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/asp/ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/asp/basexml.asp pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/asp/class_upload.asp pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/asp/commands.asp pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/asp/config.asp pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/asp/connector.asp pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/asp/io.asp pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/asp/upload.asp pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/asp/util.asp pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/aspx/ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/aspx/config.ascx pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/aspx/connector.aspx pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/aspx/upload.aspx pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/ImageObject.cfc pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf5_connector.cfm pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf5_upload.cfm pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_basexml.cfm pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_commands.cfm pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_connector.cfm pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_io.cfm pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_upload.cfm pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_util.cfm pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/config.cfm pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/connector.cfm pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/image.cfc pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/upload.cfm pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/lasso/ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/lasso/config.lasso pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/lasso/connector.lasso pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/lasso/upload.lasso pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/basexml.pl pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/commands.pl pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/connector.cgi pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/io.pl pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/upload.cgi pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/upload_fck.pl pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/util.pl pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/basexml.php pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/commands.php pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/config.php pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/connector.php pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/io.php pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/phpcompat.php pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/upload.php pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/util.php pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/config.py pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/connector.py pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckcommands.py pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckconnector.py pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckoutput.py pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckutil.py pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/htaccess.txt pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/upload.py pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/wsgi.py pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/zope.py pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/test.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/uploadtest.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/js/fckadobeair.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fr-ca.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/bbcode/ pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/bbcode/_sample/ pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/bbcode/_sample/sample.config.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/bbcode/_sample/sample.html pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/bbcode/fckplugin.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/dragresizetable/ pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/dragresizetable/fckplugin.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/placeholder/lang/es.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/default/fck_dialog_ie6.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/default/images/dialog.sides.gif pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/default/images/dialog.sides.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/default/images/dialog.sides.rtl.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/default/images/sprites.gif pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/default/images/sprites.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/office2003/fck_dialog_ie6.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/office2003/images/dialog.sides.gif pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/office2003/images/dialog.sides.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/office2003/images/dialog.sides.rtl.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/office2003/images/sprites.gif pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/office2003/images/sprites.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/silver/fck_dialog_ie6.js pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/silver/images/dialog.sides.gif pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/silver/images/dialog.sides.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/silver/images/dialog.sides.rtl.png pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/silver/images/sprites.gif pal-wcm/trunk/src/main/webapp/fckeditor/editor/skins/silver/images/sprites.png pal-wcm/trunk/src/main/webapp/fckeditor/fckutils.cfm pal-wcm/trunk/src/main/webapp/index.jsp -------------- next part -------------- Modified: pal-wcm/trunk/.classpath =================================================================== --- pal-wcm/trunk/.classpath 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/.classpath 2008-05-15 06:08:06 UTC (rev 930) @@ -1,20 +1,20 @@ - + + + + + + + + + + + - - - - - - - - - + - - \ No newline at end of file Modified: pal-wcm/trunk/.project =================================================================== --- pal-wcm/trunk/.project 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/.project 2008-05-15 06:08:06 UTC (rev 930) @@ -5,7 +5,6 @@ org.eclipse.jdt.core.javabuilder - Modified: pal-wcm/trunk/pom.xml =================================================================== --- pal-wcm/trunk/pom.xml 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/pom.xml 2008-05-15 06:08:06 UTC (rev 930) @@ -3,7 +3,7 @@ 4.0.0 jp.sf.pal pal-wcm - 0.3 + 0.4-SNAPSHOT war Web Content Management tools for PAL Portal Added: pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/FCKeditor.java =================================================================== --- pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/FCKeditor.java (rev 0) +++ pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/FCKeditor.java 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,338 @@ +/* + * FCKeditor - The text editor for internet + * Copyright (C) 2003-2005 Frederico Caldeira Knabben + * + * Licensed under the terms of the GNU Lesser General Public License: + * http://www.opensource.org/licenses/lgpl-license.php + * + * For further information visit: + * http://www.fckeditor.net/ + * + * File Name: FCKeditor.java + * FCKeditor control class. + * + * Version: 2.3 + * Modified: 2005-08-11 16:29:00 + * + * File Authors: + * Simone Chiaretta (simo ¡÷ users.sourceforge.net) + */ + + +//package com.fredck.FCKeditor; +package jp.sf.pal.wcm; + +import javax.servlet.http.HttpServletRequest; + +/** + * The main class of the class lib.
+ * It's the container for all properties and the class that generate the output based on browser capabilities and configurations passed by the developer. + * + * @author Simone Chiaretta (simo ¡÷ users.sourceforge.net) + */ +public class FCKeditor { + + private FCKeditorConfigurations oConfig; + private String instanceName; + private String value = ""; + private String basePath; + private String toolbarSet = "Default"; + private String width = "100%"; + private String height = "200"; + + HttpServletRequest request; + + /** + * Get the unique name of the editor + * + * @return name + */ + public String getInstanceName() { + return instanceName; + } + + /** + * Set the unique name of the editor + * + * @param value name + */ + public void setInstanceName(String value) { + instanceName=value; + } + + /** + * Get the initial value to be edited.
+ * In HTML code + * + * @return value + */ + public String getValue() { + return value; + } + + /** + * Set the initial value to be edited.
+ * In HTML code + * + * @param value value + */ + public void setValue(String value) { + this.value=value; + } + + /** + * Get the dir where the FCKeditor files reside on the server + * + * @return path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set the dir where the FCKeditor files reside on the server.
+ *Remarks:
+ *Avoid using relative paths. It is preferable to set the base path starting from the root (/).
+ *Always finish the path with a slash (/). + * + * @param value path + */ + public void setBasePath(String value) { + basePath=value; + } + + /** + * Get the name of the toolbar to display + * + * @return toolbar name + */ + public String getToolbarSet() { + return toolbarSet; + } + + /** + * Set the name of the toolbar to display + * + * @param value toolbar name + */ + public void setToolbarSet(String value) { + toolbarSet=value; + } + + /** + * Get the width of the textarea + * + * @return width + */ + public String getWidth() { + return width; + } + + /** + * Set the width of the textarea + * + * @param value width + */ + public void setWidth(String value) { + width=value; + } + + /** + * Get the height of the textarea + * + * @return height + */ + public String getHeight() { + return height; + } + + /** + * Set the height of the textarea + * + * @param value height + */ + public void setHeight(String value) { + height=value; + } + + + /** + * Get the advanced configuation set.
+ * Adding element to this collection you can override the settings specified in the config.js file. + * + * @return configuration collection + */ + public FCKeditorConfigurations getConfig() { + return oConfig; + } + + /** + * Set the advanced configuation set. + * + * @param value configuration collection + */ + public void setConfig(FCKeditorConfigurations value) { + oConfig=value; + } + + /** + * Initialize the object setting all value to the default ones. + *

+ *

    + *
  • width: 100%
  • + *
  • height: 200
  • + *
  • toolbar name: Default
  • + *
  • basePath: context root + "/FCKeditor/"
  • + *
+ *

+ * + * @param req request object + */ + public FCKeditor(HttpServletRequest req){ + request=req; + basePath = request.getContextPath() + "/FCKeditor/"; + oConfig = new FCKeditorConfigurations() ; + } + + /** + * Initialize the object setting the unique name and then all value to the default ones. + *

+ *

    + *
  • width: 100%
  • + *
  • height: 200
  • + *
  • toolbar name: Default
  • + *
  • basePath: context root + "/FCKeditor/"
  • + *
+ *

+ * + * @param req request object + * @param parInstanceName unique name + */ + public FCKeditor(HttpServletRequest req, String parInstanceName){ + request=req; + basePath = request.getContextPath() + "/FCKeditor/"; + instanceName=parInstanceName; + oConfig = new FCKeditorConfigurations() ; + } + + /** + * Initialize the object setting all basic configurations.
+ * + * The basePath is context root + "/FCKeditor/" + * + * @param req request object + * @param parInstanceName unique name + * @param parWidth width + * @param parHeight height + * @param parToolbarSet toolbarSet name + * @param parValue initial value + */ + public FCKeditor(HttpServletRequest req, String parInstanceName, String parWidth, String parHeight, String parToolbarSet, String parValue){ + request=req; + basePath = request.getContextPath() + "/FCKeditor/"; + instanceName=parInstanceName; + width=parWidth; + height=parHeight; + toolbarSet=parToolbarSet; + value=parValue; + oConfig = new FCKeditorConfigurations() ; + } + + + private boolean isCompatible() { + String userAgent=request.getHeader("user-agent"); + if(userAgent==null) + return false; + userAgent=userAgent.toLowerCase(); + if ((userAgent.indexOf("msie") !=-1) && (userAgent.indexOf("mac") == -1) && (userAgent.indexOf("opera") == -1)) { + if(retrieveBrowserVersion(userAgent)>=5.5) + return true; + } + else if (userAgent.indexOf("applewebkit") != -1){ // safari + if(retrieveBrowserVersion(userAgent) >= 522) + return true; + } + else if (userAgent.indexOf("gecko") !=-1){ + if(retrieveBrowserVersion(userAgent)>=20030210) + return true; + } + return false; + } + + private double retrieveBrowserVersion(String userAgent) { + if(userAgent.indexOf("msie")>-1) { + String str = userAgent.substring(userAgent.indexOf("msie") + 5); + return Double.parseDouble(str.substring(0, str.indexOf(";"))); + } + else if(userAgent.indexOf("applewebkit") != -1){ // safari + String str = userAgent.substring(userAgent.indexOf("applewebkit") + 12); + return Double.parseDouble(str.substring(0,3)); + } + else { + String str = userAgent.substring(userAgent.indexOf("gecko") + 6); + return Double.parseDouble(str.substring(0, 8)); + } + } + + private String HTMLEncode(String txt) { + txt=txt.replaceAll("&","&"); + txt=txt.replaceAll("<","<"); + txt=txt.replaceAll(">",">"); + txt=txt.replaceAll("\"","""); + txt=txt.replaceAll("'","’"); + return txt; + } + + + /** + * Generate the HTML Code for the editor. + *
+ * Evalute the browser capabilities and generate the editor if IE 5.5 or Gecko 20030210 or greater, + * or a simple textarea otherwise. + * + * @return html code + */ + public String create() { + StringBuffer strEditor=new StringBuffer(); + + strEditor.append("
"); + String encodedValue=HTMLEncode(value); + + if(isCompatible()) { + + strEditor.append(""); + + strEditor.append(createConfigHTML()); + strEditor.append(createIFrameHTML()); + + } + else{ + strEditor.append(""); + } + strEditor.append("
"); + return strEditor.toString(); + } + + private String createConfigHTML() { + String configStr=oConfig.getUrlParams(); + + + if(!configStr.equals("")) + configStr=configStr.substring(1); + + return "" ; + } + + private String createIFrameHTML() { + + String sLink=basePath + "editor/fckeditor.html?InstanceName=" + instanceName; + + if (!toolbarSet.equals("")) + sLink+="&Toolbar=" + toolbarSet; + + return ""; + + } + + +} Added: pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/FCKeditorConfigurations.java =================================================================== --- pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/FCKeditorConfigurations.java (rev 0) +++ pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/FCKeditorConfigurations.java 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,66 @@ +/* + * FCKeditor - The text editor for internet + * Copyright (C) 2003-2005 Frederico Caldeira Knabben + * + * Licensed under the terms of the GNU Lesser General Public License: + * http://www.opensource.org/licenses/lgpl-license.php + * + * For further information visit: + * http://www.fckeditor.net/ + * + * File Name: FCKeditorConfigurations.java + * FCKeditor configurations container. + * + * Version: 2.3 + * Modified: 2005-08-11 16:29:00 + * + * File Authors: + * Simone Chiaretta (simo ¡÷ users.sourceforge.net) + */ + + +package jp.sf.pal.wcm; +//package com.fredck.FCKeditor; + +import java.util.*; + +/** + * Contains the configuration settings for the FCKEditor.
+ * Adding element to this collection you can override the settings specified in the config.js file. + * + * @author Simone Chiaretta (simo ¡÷ users.sourceforge.net) + */ +public class FCKeditorConfigurations extends HashMap{ + + /** + * Initialize the configuration collection + */ + public FCKeditorConfigurations() { + super(); + } + + /** + * Generate the url parameter sequence used to pass this configuration to the editor. + * + * + *@return html endocode sequence of configuration parameters + */ + public String getUrlParams() { + StringBuffer osParams = new StringBuffer(); + + for(Iterator i=this.entrySet().iterator();i.hasNext();) { + Map.Entry entry = (Map.Entry) i.next(); + if(entry.getValue()!=null) + osParams.append("&"+encodeConfig(entry.getKey().toString())+"="+encodeConfig(entry.getValue().toString())); + } + return osParams.toString(); + } + + private String encodeConfig(String txt) { + txt=txt.replaceAll("&","%26"); + txt=txt.replaceAll("=","%3D"); + txt=txt.replaceAll("\"","%22"); + return txt; + } + +} Added: pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/servlet/FilesaveServlet.java =================================================================== --- pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/servlet/FilesaveServlet.java (rev 0) +++ pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/servlet/FilesaveServlet.java 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,78 @@ +/* + * Copyright 2005-2007 Portal Application Laboratory Project and the Others. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +package jp.sf.pal.wcm.servlet; + +import java.io.IOException; + +import java.util.*; +import java.io.File; +import java.io.FileWriter; +import java.io.PrintWriter; +import javax.servlet.ServletContext; + +import jp.sf.pal.wcm.*; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author takaaki sone + * + */ +public class FilesaveServlet extends HttpServlet { + @Override + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + Enumeration params = request.getParameterNames(); + String parameter = null; + String reqParam = null; + while (params.hasMoreElements()) { + parameter = (String) params.nextElement(); + reqParam = request.getParameter(parameter); + ServletContext servletContext = getServletContext(); + //String fragID = request.getParameter(PALWcmConstants.FRAGMENT_ID); + String fragID = request.getParameter("fragID"); + //String fragID = "test123"; + String outputFileName = "/content_jp.html"; + String outputFilePath = servletContext + .getRealPath("/WEB-INF/data/" + fragID); + File fragIdDir = new File(outputFilePath); + try { + if (!fragIdDir.exists()) { + if (!fragIdDir.mkdirs()) { + // fail to mkdir + System.err.println("error:cannot mkdir" + + outputFilePath); + } + } + FileWriter fw = new FileWriter(outputFilePath + outputFileName); + PrintWriter writer = new PrintWriter(fw); + writer.println(reqParam); + fw.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + response.sendRedirect("/pal-wcm"); + } + + protected void doPost(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + doGet(request,response); + } +} Added: pal-wcm/trunk/src/main/webapp/WEB-INF/lib/FCKeditor-2.3.jar =================================================================== (Binary files differ) Property changes on: pal-wcm/trunk/src/main/webapp/WEB-INF/lib/FCKeditor-2.3.jar ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Added: pal-wcm/trunk/src/main/webapp/WEB-INF/lib/commons-fileupload-1.2.1.jar =================================================================== (Binary files differ) Property changes on: pal-wcm/trunk/src/main/webapp/WEB-INF/lib/commons-fileupload-1.2.1.jar ___________________________________________________________________ Name: svn:mime-type + application/octet-stream Modified: pal-wcm/trunk/src/main/webapp/WEB-INF/web.xml =================================================================== --- pal-wcm/trunk/src/main/webapp/WEB-INF/web.xml 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/WEB-INF/web.xml 2008-05-15 06:08:06 UTC (rev 930) @@ -32,6 +32,10 @@ FileconnectorServlet jp.sf.pal.wcm.servlet.FileconnectorServlet + + FilesaveServlet + jp.sf.pal.wcm.servlet.FilesaveServlet + FileuploadServlet /fileupload @@ -44,4 +48,8 @@ FileconnectorServlet /fileconnector + + FilesaveServlet + /filesave + Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckcontextmenu.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckcontextmenu.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckcontextmenu.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -23,8 +23,10 @@ var FCKContextMenu = function( parentWindow, langDir ) { - var oPanel = this._Panel = new FCKPanel( parentWindow, true ) ; - oPanel.AppendStyleSheet( FCKConfig.SkinPath + 'fck_editor.css' ) ; + this.CtrlDisable = false ; + + var oPanel = this._Panel = new FCKPanel( parentWindow ) ; + oPanel.AppendStyleSheet( FCKConfig.SkinEditorCSS ) ; oPanel.IsContextMenu = true ; // The FCKTools.DisableSelection doesn't seems to work to avoid dragging of the icons in Mozilla @@ -45,13 +47,22 @@ if ( !FCKBrowserInfo.IsIE ) { this._Document = mouseClickWindow.document ; + if ( FCKBrowserInfo.IsOpera && !( 'oncontextmenu' in document.createElement('foo') ) ) + { + this._Document.addEventListener( 'mousedown', FCKContextMenu_Document_OnMouseDown, false ) ; + this._Document.addEventListener( 'mouseup', FCKContextMenu_Document_OnMouseUp, false ) ; + } this._Document.addEventListener( 'contextmenu', FCKContextMenu_Document_OnContextMenu, false ) ; } } -FCKContextMenu.prototype.AddItem = function( name, label, iconPathOrStripInfoArrayOrIndex, isDisabled ) +/** + The customData parameter is just a value that will be send to the command that is executed, + so it's possible to reuse the same command for several items just by assigning different data for each one. +*/ +FCKContextMenu.prototype.AddItem = function( name, label, iconPathOrStripInfoArrayOrIndex, isDisabled, customData ) { - var oItem = this._MenuBlock.AddItem( name, label, iconPathOrStripInfoArrayOrIndex, isDisabled) ; + var oItem = this._MenuBlock.AddItem( name, label, iconPathOrStripInfoArrayOrIndex, isDisabled, customData ) ; this._Redraw = true ; return oItem ; } @@ -74,8 +85,6 @@ FCKTools.AddEventListenerEx( element, 'contextmenu', FCKContextMenu_AttachedElement_OnContextMenu, this ) ; else element._FCKContextMenu = this ; - -// element.onmouseup = FCKContextMenu_AttachedElement_OnMouseUp ; } function FCKContextMenu_Document_OnContextMenu( e ) @@ -86,20 +95,78 @@ { if ( el._FCKContextMenu ) { + if ( el._FCKContextMenu.CtrlDisable && ( e.ctrlKey || e.metaKey ) ) + return true ; + FCKTools.CancelEvent( e ) ; FCKContextMenu_AttachedElement_OnContextMenu( e, el._FCKContextMenu, el ) ; + return false ; } el = el.parentNode ; } + return true ; } +var FCKContextMenu_OverrideButton ; + +function FCKContextMenu_Document_OnMouseDown( e ) +{ + if( !e || e.button != 2 ) + return false ; + + var el = e.target ; + + while ( el ) + { + if ( el._FCKContextMenu ) + { + if ( el._FCKContextMenu.CtrlDisable && ( e.ctrlKey || e.metaKey ) ) + return true ; + + var overrideButton = FCKContextMenu_OverrideButton ; + if( !overrideButton ) + { + var doc = FCKTools.GetElementDocument( e.target ) ; + overrideButton = FCKContextMenu_OverrideButton = doc.createElement('input') ; + overrideButton.type = 'button' ; + var buttonHolder = doc.createElement('p') ; + doc.body.appendChild( buttonHolder ) ; + buttonHolder.appendChild( overrideButton ) ; + } + + overrideButton.style.cssText = 'position:absolute;top:' + ( e.clientY - 2 ) + + 'px;left:' + ( e.clientX - 2 ) + + 'px;width:5px;height:5px;opacity:0.01' ; + } + el = el.parentNode ; + } + return false ; +} + +function FCKContextMenu_Document_OnMouseUp( e ) +{ + var overrideButton = FCKContextMenu_OverrideButton ; + + if ( overrideButton ) + { + var parent = overrideButton.parentNode ; + parent.parentNode.removeChild( parent ) ; + FCKContextMenu_OverrideButton = undefined ; + + if( e && e.button == 2 ) + { + FCKContextMenu_Document_OnContextMenu( e ) ; + return false ; + } + } + return true ; +} + function FCKContextMenu_AttachedElement_OnContextMenu( ev, fckContextMenu, el ) { -// var iButton = e ? e.which - 1 : event.button ; + if ( fckContextMenu.CtrlDisable && ( ev.ctrlKey || ev.metaKey ) ) + return true ; -// if ( iButton != 2 ) -// return ; - var eTarget = el || this ; if ( fckContextMenu.OnBeforeOpen ) @@ -113,16 +180,29 @@ fckContextMenu._MenuBlock.Create( fckContextMenu._Panel.MainNode ) ; fckContextMenu._Redraw = false ; } - + // This will avoid that the content of the context menu can be dragged in IE // as the content of the panel is recreated we need to do it every time FCKTools.DisableSelection( fckContextMenu._Panel.Document.body ) ; - fckContextMenu._Panel.Show( - ev.pageX || ev.screenX, - ev.pageY || ev.screenY, - ev.currentTarget || null - ) ; + var x = 0 ; + var y = 0 ; + if ( FCKBrowserInfo.IsIE ) + { + x = ev.screenX ; + y = ev.screenY ; + } + else if ( FCKBrowserInfo.IsSafari ) + { + x = ev.clientX ; + y = ev.clientY ; + } + else + { + x = ev.pageX ; + y = ev.pageY ; + } + fckContextMenu._Panel.Show( x, y, ev.currentTarget || null ) ; return false ; } @@ -131,4 +211,4 @@ { contextMenu._Panel.Hide() ; FCKTools.RunFunction( contextMenu.OnItemClick, contextMenu, menuItem ) ; -} \ No newline at end of file +} Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdataprocessor.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdataprocessor.js (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdataprocessor.js 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,119 @@ +?/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * The Data Processor is responsible for transforming the input and output data + * in the editor. For more info: + * http://dev.fckeditor.net/wiki/Components/DataProcessor + * + * The default implementation offers the base XHTML compatibility features of + * FCKeditor. Further Data Processors may be implemented for other purposes. + * + */ + +var FCKDataProcessor = function() +{} + +FCKDataProcessor.prototype = +{ + /* + * Returns a string representing the HTML format of "data". The returned + * value will be loaded in the editor. + * The HTML must be from to , including , and + * eventually the DOCTYPE. + * Note: HTML comments may already be part of the data because of the + * pre-processing made with ProtectedSource. + * @param {String} data The data to be converted in the + * DataProcessor specific format. + */ + ConvertToHtml : function( data ) + { + // The default data processor must handle two different cases depending + // on the FullPage setting. Custom Data Processors will not be + // compatible with FullPage, much probably. + if ( FCKConfig.FullPage ) + { + // Save the DOCTYPE. + FCK.DocTypeDeclaration = data.match( FCKRegexLib.DocTypeTag ) ; + + // Check if the tag is available. + if ( !FCKRegexLib.HasBodyTag.test( data ) ) + data = '' + data + '' ; + + // Check if the tag is available. + if ( !FCKRegexLib.HtmlOpener.test( data ) ) + data = '' + data + '' ; + + // Check if the tag is available. + if ( !FCKRegexLib.HeadOpener.test( data ) ) + data = data.replace( FCKRegexLib.HtmlOpener, '$&' ) ; + + return data ; + } + else + { + var html = + FCKConfig.DocType + + ' 0 && !FCKRegexLib.Html4DocType.test( FCKConfig.DocType ) ) + html += ' style="overflow-y: scroll"' ; + + html += '>' + + '' + + data + + '' ; + + return html ; + } + }, + + /* + * Converts a DOM (sub-)tree to a string in the data format. + * @param {Object} rootNode The node that contains the DOM tree to be + * converted to the data format. + * @param {Boolean} excludeRoot Indicates that the root node must not + * be included in the conversion, only its children. + * @param {Boolean} format Indicates that the data must be formatted + * for human reading. Not all Data Processors may provide it. + */ + ConvertToDataFormat : function( rootNode, excludeRoot, ignoreIfEmptyParagraph, format ) + { + var data = FCKXHtml.GetXHTML( rootNode, !excludeRoot, format ) ; + + if ( ignoreIfEmptyParagraph && FCKRegexLib.EmptyOutParagraph.test( data ) ) + return '' ; + + return data ; + }, + + /* + * Makes any necessary changes to a piece of HTML for insertion in the + * editor selection position. + * @param {String} html The HTML to be fixed. + */ + FixHtml : function( html ) + { + return html ; + } +} ; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdocumentfragment_gecko.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdocumentfragment_gecko.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdocumentfragment_gecko.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -43,4 +43,4 @@ { FCKDomTools.InsertAfterNode( existingNode, this.RootNode ) ; } -} \ No newline at end of file +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdocumentfragment_ie.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdocumentfragment_ie.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdocumentfragment_ie.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -55,4 +55,4 @@ while( ( eLast = eRoot.lastChild ) ) FCKDomTools.InsertAfterNode( existingNode, eRoot.removeChild( eLast ) ) ; } -} ; \ No newline at end of file +} ; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrange.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrange.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrange.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -19,12 +19,13 @@ * == END LICENSE == * * Class for working with a selection range, much like the W3C DOM Range, but - * it is not intented to be an implementation of the W3C interface. + * it is not intended to be an implementation of the W3C interface. */ var FCKDomRange = function( sourceWindow ) { this.Window = sourceWindow ; + this._Cache = {} ; } FCKDomRange.prototype = @@ -32,24 +33,47 @@ _UpdateElementInfo : function() { - if ( !this._Range ) + var innerRange = this._Range ; + + if ( !innerRange ) this.Release( true ) ; else { - var eStart = this._Range.startContainer ; - var eEnd = this._Range.endContainer ; + // For text nodes, the node itself is the StartNode. + var eStart = innerRange.startContainer ; + var eEnd = innerRange.endContainer ; var oElementPath = new FCKElementPath( eStart ) ; - this.StartContainer = oElementPath.LastElement ; + this.StartNode = eStart.nodeType == 3 ? eStart : eStart.childNodes[ innerRange.startOffset ] ; + this.StartContainer = eStart ; this.StartBlock = oElementPath.Block ; this.StartBlockLimit = oElementPath.BlockLimit ; if ( eStart != eEnd ) oElementPath = new FCKElementPath( eEnd ) ; - this.EndContainer = oElementPath.LastElement ; + + // The innerRange.endContainer[ innerRange.endOffset ] is not + // usually part of the range, but the marker for the range end. So, + // let's get the previous available node as the real end. + var eEndNode = eEnd ; + if ( innerRange.endOffset == 0 ) + { + while ( eEndNode && !eEndNode.previousSibling ) + eEndNode = eEndNode.parentNode ; + + if ( eEndNode ) + eEndNode = eEndNode.previousSibling ; + } + else if ( eEndNode.nodeType == 1 ) + eEndNode = eEndNode.childNodes[ innerRange.endOffset - 1 ] ; + + this.EndNode = eEndNode ; + this.EndContainer = eEnd ; this.EndBlock = oElementPath.Block ; this.EndBlockLimit = oElementPath.BlockLimit ; } + + this._Cache = {} ; }, CreateRange : function() @@ -74,12 +98,15 @@ this._UpdateElementInfo() ; return docFrag ; } + return null ; }, CheckIsCollapsed : function() { if ( this._Range ) return this._Range.collapsed ; + + return false ; }, Collapse : function( toStart ) @@ -121,12 +148,20 @@ // is "

^ Text

" (inside ). MoveToElementEditStart : function( targetElement ) { - var child ; + var editableElement ; - while ( ( child = targetElement.firstChild ) && child.nodeType == 1 && FCKListsLib.EmptyElements[ child.nodeName.toLowerCase() ] == null ) - targetElement = child ; + while ( targetElement && targetElement.nodeType == 1 ) + { + if ( FCKDomTools.CheckIsEditable( targetElement ) ) + editableElement = targetElement ; + else if ( editableElement ) + break ; // If we already found an editable element, stop the loop. - this.MoveToElementStart( targetElement ) ; + targetElement = targetElement.firstChild ; + } + + if ( editableElement ) + this.MoveToElementStart( editableElement ) ; }, InsertNode : function( node ) @@ -135,7 +170,7 @@ this._Range.insertNode( node ) ; }, - CheckIsEmpty : function( ignoreEndBRs ) + CheckIsEmpty : function() { if ( this.CheckIsCollapsed() ) return true ; @@ -144,124 +179,250 @@ var eToolDiv = this.Window.document.createElement( 'div' ) ; this._Range.cloneContents().AppendTo( eToolDiv ) ; - FCKDomTools.TrimNode( eToolDiv, ignoreEndBRs ) ; + FCKDomTools.TrimNode( eToolDiv ) ; return ( eToolDiv.innerHTML.length == 0 ) ; }, + /** + * Checks if the start boundary of the current range is "visually" (like a + * selection caret) at the beginning of the block. It means that some + * things could be brefore the range, like spaces or empty inline elements, + * but it would still be considered at the beginning of the block. + */ CheckStartOfBlock : function() { - // Create a clone of the current range. - var oTestRange = this.Clone() ; + var cache = this._Cache ; + var bIsStartOfBlock = cache.IsStartOfBlock ; - // Collapse it to its start point. - oTestRange.Collapse( true ) ; + if ( bIsStartOfBlock != undefined ) + return bIsStartOfBlock ; - // Move the start boundary to the start of the block. - oTestRange.SetStart( oTestRange.StartBlock || oTestRange.StartBlockLimit, 1 ) ; + // Take the block reference. + var block = this.StartBlock || this.StartBlockLimit ; - var bIsStartOfBlock = oTestRange.CheckIsEmpty() ; + var container = this._Range.startContainer ; + var offset = this._Range.startOffset ; + var currentNode ; - oTestRange.Release() ; + if ( offset > 0 ) + { + // First, check the start container. If it is a text node, get the + // substring of the node value before the range offset. + if ( container.nodeType == 3 ) + { + var textValue = container.nodeValue.substr( 0, offset ).Trim() ; - return bIsStartOfBlock ; + // If we have some text left in the container, we are not at + // the end for the block. + if ( textValue.length != 0 ) + return cache.IsStartOfBlock = false ; + } + else + currentNode = container.childNodes[ offset - 1 ] ; + } + + // We'll not have a currentNode if the container was a text node, or + // the offset is zero. + if ( !currentNode ) + currentNode = FCKDomTools.GetPreviousSourceNode( container, true, null, block ) ; + + while ( currentNode ) + { + switch ( currentNode.nodeType ) + { + case 1 : + // It's not an inline element. + if ( !FCKListsLib.InlineChildReqElements[ currentNode.nodeName.toLowerCase() ] ) + return cache.IsStartOfBlock = false ; + + break ; + + case 3 : + // It's a text node with real text. + if ( currentNode.nodeValue.Trim().length > 0 ) + return cache.IsStartOfBlock = false ; + } + + currentNode = FCKDomTools.GetPreviousSourceNode( currentNode, false, null, block ) ; + } + + return cache.IsStartOfBlock = true ; }, + /** + * Checks if the end boundary of the current range is "visually" (like a + * selection caret) at the end of the block. It means that some things + * could be after the range, like spaces, empty inline elements, or a + * single
, but it would still be considered at the end of the block. + */ CheckEndOfBlock : function( refreshSelection ) { - // Create a clone of the current range. - var oTestRange = this.Clone() ; + var isEndOfBlock = this._Cache.IsEndOfBlock ; - // Collapse it to its end point. - oTestRange.Collapse( false ) ; + if ( isEndOfBlock != undefined ) + return isEndOfBlock ; - // Move the end boundary to the end of the block. - oTestRange.SetEnd( oTestRange.EndBlock || oTestRange.EndBlockLimit, 2 ) ; + // Take the block reference. + var block = this.EndBlock || this.EndBlockLimit ; - var bIsEndOfBlock = oTestRange.CheckIsCollapsed() ; - - if ( !bIsEndOfBlock ) + var container = this._Range.endContainer ; + var offset = this._Range.endOffset ; + var currentNode ; + + // First, check the end container. If it is a text node, get the + // substring of the node value after the range offset. + if ( container.nodeType == 3 ) { - // Inserts the contents of the range in a div tag. - var eToolDiv = this.Window.document.createElement( 'div' ) ; - oTestRange._Range.cloneContents().AppendTo( eToolDiv ) ; - FCKDomTools.TrimNode( eToolDiv, true ) ; - - // Find out if we are in an empty tree of inline elements, like - bIsEndOfBlock = true ; - var eLastChild = eToolDiv ; - while ( ( eLastChild = eLastChild.lastChild ) ) + var textValue = container.nodeValue ; + if ( offset < textValue.length ) { - // Check the following: - // 1. Is there more than one node in the parents children? - // 2. Is the node not an element node? - // 3. Is it not a inline element. - if ( eLastChild.previousSibling || eLastChild.nodeType != 1 || FCKListsLib.InlineChildReqElements[ eLastChild.nodeName.toLowerCase() ] == null ) - { - // So we are not in the end of the range. - bIsEndOfBlock = false ; - break ; - } + textValue = textValue.substr( offset ) ; + + // If we have some text left in the container, we are not at + // the end for the block. + if ( textValue.Trim().length != 0 ) + return this._Cache.IsEndOfBlock = false ; } } - - oTestRange.Release() ; + else + currentNode = container.childNodes[ offset ] ; + // We'll not have a currentNode if the container was a text node, of + // the offset is out the container children limits (after it probably). + if ( !currentNode ) + currentNode = FCKDomTools.GetNextSourceNode( container, true, null, block ) ; + + var hadBr = false ; + + while ( currentNode ) + { + switch ( currentNode.nodeType ) + { + case 1 : + var nodeName = currentNode.nodeName.toLowerCase() ; + + // It's an inline element. + if ( FCKListsLib.InlineChildReqElements[ nodeName ] ) + break ; + + // It is the first
found. + if ( nodeName == 'br' && !hadBr ) + { + hadBr = true ; + break ; + } + + return this._Cache.IsEndOfBlock = false ; + + case 3 : + // It's a text node with real text. + if ( currentNode.nodeValue.Trim().length > 0 ) + return this._Cache.IsEndOfBlock = false ; + } + + currentNode = FCKDomTools.GetNextSourceNode( currentNode, false, null, block ) ; + } + if ( refreshSelection ) this.Select() ; - return bIsEndOfBlock ; + return this._Cache.IsEndOfBlock = true ; }, - CreateBookmark : function() + // This is an "intrusive" way to create a bookmark. It includes tags + // in the range boundaries. The advantage of it is that it is possible to + // handle DOM mutations when moving back to the bookmark. + // Attention: the inclusion of nodes in the DOM is a design choice and + // should not be changed as there are other points in the code that may be + // using those nodes to perform operations. See GetBookmarkNode. + // For performance, includeNodes=true if intended to SelectBookmark. + CreateBookmark : function( includeNodes ) { // Create the bookmark info (random IDs). var oBookmark = { - StartId : 'fck_dom_range_start_' + (new Date()).valueOf() + '_' + Math.floor(Math.random()*1000), - EndId : 'fck_dom_range_end_' + (new Date()).valueOf() + '_' + Math.floor(Math.random()*1000) + StartId : (new Date()).valueOf() + Math.floor(Math.random()*1000) + 'S', + EndId : (new Date()).valueOf() + Math.floor(Math.random()*1000) + 'E' } ; var oDoc = this.Window.document ; - var eSpan ; + var eStartSpan ; + var eEndSpan ; var oClone ; // For collapsed ranges, add just the start marker. if ( !this.CheckIsCollapsed() ) { - eSpan = oDoc.createElement( 'span' ) ; - eSpan.id = oBookmark.EndId ; - eSpan.innerHTML = ' ' ; // For IE, it must have something inside, otherwise it may be removed during operations. + eEndSpan = oDoc.createElement( 'span' ) ; + eEndSpan.style.display = 'none' ; + eEndSpan.id = oBookmark.EndId ; + eEndSpan.setAttribute( '_fck_bookmark', true ) ; + // For IE, it must have something inside, otherwise it may be + // removed during DOM operations. +// if ( FCKBrowserInfo.IsIE ) + eEndSpan.innerHTML = ' ' ; + oClone = this.Clone() ; oClone.Collapse( false ) ; - oClone.InsertNode( eSpan ) ; + oClone.InsertNode( eEndSpan ) ; } - eSpan = oDoc.createElement( 'span' ) ; - eSpan.id = oBookmark.StartId ; - eSpan.innerHTML = ' ' ; // For IE, it must have something inside, otherwise it may be removed during operations. + eStartSpan = oDoc.createElement( 'span' ) ; + eStartSpan.style.display = 'none' ; + eStartSpan.id = oBookmark.StartId ; + eStartSpan.setAttribute( '_fck_bookmark', true ) ; + // For IE, it must have something inside, otherwise it may be removed + // during DOM operations. +// if ( FCKBrowserInfo.IsIE ) + eStartSpan.innerHTML = ' ' ; + oClone = this.Clone() ; oClone.Collapse( true ) ; - oClone.InsertNode( eSpan ) ; + oClone.InsertNode( eStartSpan ) ; + if ( includeNodes ) + { + oBookmark.StartNode = eStartSpan ; + oBookmark.EndNode = eEndSpan ; + } + + // Update the range position. + if ( eEndSpan ) + { + this.SetStart( eStartSpan, 4 ) ; + this.SetEnd( eEndSpan, 3 ) ; + } + else + this.MoveToPosition( eStartSpan, 4 ) ; + return oBookmark ; }, + // This one should be a part of a hypothetic "bookmark" object. + GetBookmarkNode : function( bookmark, start ) + { + var doc = this.Window.document ; + + if ( start ) + return bookmark.StartNode || doc.getElementById( bookmark.StartId ) ; + else + return bookmark.EndNode || doc.getElementById( bookmark.EndId ) ; + }, + MoveToBookmark : function( bookmark, preserveBookmark ) { - var oDoc = this.Window.document ; + var eStartSpan = this.GetBookmarkNode( bookmark, true ) ; + var eEndSpan = this.GetBookmarkNode( bookmark, false ) ; - var eStartSpan = oDoc.getElementById( bookmark.StartId ) ; - var eEndSpan = oDoc.getElementById( bookmark.EndId ) ; - this.SetStart( eStartSpan, 3 ) ; if ( !preserveBookmark ) FCKDomTools.RemoveNode( eStartSpan ) ; - // If collapsed, the start span will not be available. + // If collapsed, the end span will not be available. if ( eEndSpan ) { this.SetEnd( eEndSpan, 3 ) ; @@ -271,8 +432,115 @@ } else this.Collapse( true ) ; + + this._UpdateElementInfo() ; }, + // Non-intrusive bookmark algorithm + CreateBookmark2 : function() + { + // If there is no range then get out of here. + // It happens on initial load in Safari #962 and if the editor it's hidden also in Firefox + if ( ! this._Range ) + return { "Start" : 0, "End" : 0 } ; + + // First, we record down the offset values + var bookmark = + { + "Start" : [ this._Range.startOffset ], + "End" : [ this._Range.endOffset ] + } ; + // Since we're treating the document tree as normalized, we need to backtrack the text lengths + // of previous text nodes into the offset value. + var curStart = this._Range.startContainer.previousSibling ; + var curEnd = this._Range.endContainer.previousSibling ; + + // Also note that the node that we use for "address base" would change during backtracking. + var addrStart = this._Range.startContainer ; + var addrEnd = this._Range.endContainer ; + while ( curStart && curStart.nodeType == 3 ) + { + bookmark.Start[0] += curStart.length ; + addrStart = curStart ; + curStart = curStart.previousSibling ; + } + while ( curEnd && curEnd.nodeType == 3 ) + { + bookmark.End[0] += curEnd.length ; + addrEnd = curEnd ; + curEnd = curEnd.previousSibling ; + } + + // If the object pointed to by the startOffset and endOffset are text nodes, we need + // to backtrack and add in the text offset to the bookmark addresses. + if ( addrStart.nodeType == 1 && addrStart.childNodes[bookmark.Start[0]] && addrStart.childNodes[bookmark.Start[0]].nodeType == 3 ) + { + var curNode = addrStart.childNodes[bookmark.Start[0]] ; + var offset = 0 ; + while ( curNode.previousSibling && curNode.previousSibling.nodeType == 3 ) + { + curNode = curNode.previousSibling ; + offset += curNode.length ; + } + addrStart = curNode ; + bookmark.Start[0] = offset ; + } + if ( addrEnd.nodeType == 1 && addrEnd.childNodes[bookmark.End[0]] && addrEnd.childNodes[bookmark.End[0]].nodeType == 3 ) + { + var curNode = addrEnd.childNodes[bookmark.End[0]] ; + var offset = 0 ; + while ( curNode.previousSibling && curNode.previousSibling.nodeType == 3 ) + { + curNode = curNode.previousSibling ; + offset += curNode.length ; + } + addrEnd = curNode ; + bookmark.End[0] = offset ; + } + + // Then, we record down the precise position of the container nodes + // by walking up the DOM tree and counting their childNode index + bookmark.Start = FCKDomTools.GetNodeAddress( addrStart, true ).concat( bookmark.Start ) ; + bookmark.End = FCKDomTools.GetNodeAddress( addrEnd, true ).concat( bookmark.End ) ; + return bookmark; + }, + + MoveToBookmark2 : function( bookmark ) + { + // Reverse the childNode counting algorithm in CreateBookmark2() + var curStart = FCKDomTools.GetNodeFromAddress( this.Window.document, bookmark.Start.slice( 0, -1 ), true ) ; + var curEnd = FCKDomTools.GetNodeFromAddress( this.Window.document, bookmark.End.slice( 0, -1 ), true ) ; + + // Generate the W3C Range object and update relevant data + this.Release( true ) ; + this._Range = new FCKW3CRange( this.Window.document ) ; + var startOffset = bookmark.Start[ bookmark.Start.length - 1 ] ; + var endOffset = bookmark.End[ bookmark.End.length - 1 ] ; + while ( curStart.nodeType == 3 && startOffset > curStart.length ) + { + if ( ! curStart.nextSibling || curStart.nextSibling.nodeType != 3 ) + break ; + startOffset -= curStart.length ; + curStart = curStart.nextSibling ; + } + while ( curEnd.nodeType == 3 && endOffset > curEnd.length ) + { + if ( ! curEnd.nextSibling || curEnd.nextSibling.nodeType != 3 ) + break ; + endOffset -= curEnd.length ; + curEnd = curEnd.nextSibling ; + } + this._Range.setStart( curStart, startOffset ) ; + this._Range.setEnd( curEnd, endOffset ) ; + this._UpdateElementInfo() ; + }, + + MoveToPosition : function( targetElement, position ) + { + this.SetStart( targetElement, position ) ; + this.Collapse( true ) ; + }, + /* * Moves the position of the start boundary of the range to a specific position * relatively to a element. @@ -282,7 +550,7 @@ * 3 = Before Start ^contents * 4 = After End contents^ */ - SetStart : function( targetElement, position ) + SetStart : function( targetElement, position, noInfoUpdate ) { var oRange = this._Range ; if ( !oRange ) @@ -305,7 +573,9 @@ case 4 : // After End contents^ oRange.setStartAfter( targetElement ) ; } - this._UpdateElementInfo() ; + + if ( !noInfoUpdate ) + this._UpdateElementInfo() ; }, /* @@ -317,7 +587,7 @@ * 3 = Before Start ^contents * 4 = After End contents^ */ - SetEnd : function( targetElement, position ) + SetEnd : function( targetElement, position, noInfoUpdate ) { var oRange = this._Range ; if ( !oRange ) @@ -340,7 +610,9 @@ case 4 : // After End contents^ oRange.setEndAfter( targetElement ) ; } - this._UpdateElementInfo() ; + + if ( !noInfoUpdate ) + this._UpdateElementInfo() ; }, Expand : function( unit ) @@ -349,53 +621,95 @@ switch ( unit ) { + // Expand the range to include all inline parent elements if we are + // are in their boundary limits. + // For example (where [ ] are the range limits): + // Before => Some [Some sample text]. + // After => Some [Some sample text]. + case 'inline_elements' : + // Expand the start boundary. + if ( this._Range.startOffset == 0 ) + { + oNode = this._Range.startContainer ; + + if ( oNode.nodeType != 1 ) + oNode = oNode.previousSibling ? null : oNode.parentNode ; + + if ( oNode ) + { + while ( FCKListsLib.InlineNonEmptyElements[ oNode.nodeName.toLowerCase() ] ) + { + this._Range.setStartBefore( oNode ) ; + + if ( oNode != oNode.parentNode.firstChild ) + break ; + + oNode = oNode.parentNode ; + } + } + } + + // Expand the end boundary. + oNode = this._Range.endContainer ; + var offset = this._Range.endOffset ; + + if ( ( oNode.nodeType == 3 && offset >= oNode.nodeValue.length ) || ( oNode.nodeType == 1 && offset >= oNode.childNodes.length ) || ( oNode.nodeType != 1 && oNode.nodeType != 3 ) ) + { + if ( oNode.nodeType != 1 ) + oNode = oNode.nextSibling ? null : oNode.parentNode ; + + if ( oNode ) + { + while ( FCKListsLib.InlineNonEmptyElements[ oNode.nodeName.toLowerCase() ] ) + { + this._Range.setEndAfter( oNode ) ; + + if ( oNode != oNode.parentNode.lastChild ) + break ; + + oNode = oNode.parentNode ; + } + } + } + + break ; + case 'block_contents' : - if ( this.StartBlock ) + case 'list_contents' : + var boundarySet = FCKListsLib.BlockBoundaries ; + if ( unit == 'list_contents' || FCKConfig.EnterMode == 'br' ) + boundarySet = FCKListsLib.ListBoundaries ; + + if ( this.StartBlock && FCKConfig.EnterMode != 'br' && unit == 'block_contents' ) this.SetStart( this.StartBlock, 1 ) ; else { // Get the start node for the current range. oNode = this._Range.startContainer ; - // If it is an element, get the current child node for the range (in the offset). - // If the offset node is not available, the the first one. + // If it is an element, get the node right before of it (in source order). if ( oNode.nodeType == 1 ) { - if ( !( oNode = oNode.childNodes[ this._Range.startOffset ] ) ) - oNode = oNode.firstChild ; + var lastNode = oNode.childNodes[ this._Range.startOffset ] ; + if ( lastNode ) + oNode = FCKDomTools.GetPreviousSourceNode( lastNode, true ) ; + else + oNode = oNode.lastChild || oNode ; } - // Not able to defined the current position. - if ( !oNode ) - return ; - // We must look for the left boundary, relative to the range // start, which is limited by a block element. - while ( true ) + while ( oNode + && ( oNode.nodeType != 1 + || ( oNode != this.StartBlockLimit + && !boundarySet[ oNode.nodeName.toLowerCase() ] ) ) ) { - oSibling = oNode.previousSibling ; - - if ( !oSibling ) - { - // Continue if we are not yet in the block limit (inside a , for example). - if ( oNode.parentNode != this.StartBlockLimit ) - oNode = oNode.parentNode ; - else - break ; - } - else if ( oSibling.nodeType != 1 || !(/^(?:P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|DT|DE)$/).test( oSibling.nodeName.toUpperCase() ) ) - { - // Continue if the sibling is not a block tag. - oNode = oSibling ; - } - else - break ; + this._Range.setStartBefore( oNode ) ; + oNode = oNode.previousSibling || oNode.parentNode ; } - - this._Range.setStartBefore( oNode ) ; } - if ( this.EndBlock ) + if ( this.EndBlock && FCKConfig.EnterMode != 'br' && unit == 'block_contents' && this.EndBlock.nodeName.toLowerCase() != 'li' ) this.SetEnd( this.EndBlock, 2 ) ; else { @@ -403,50 +717,202 @@ if ( oNode.nodeType == 1 ) oNode = oNode.childNodes[ this._Range.endOffset ] || oNode.lastChild ; - if ( !oNode ) - return ; - // We must look for the right boundary, relative to the range // end, which is limited by a block element. - while ( true ) + while ( oNode + && ( oNode.nodeType != 1 + || ( oNode != this.StartBlockLimit + && !boundarySet[ oNode.nodeName.toLowerCase() ] ) ) ) { - oSibling = oNode.nextSibling ; - - if ( !oSibling ) - { - // Continue if we are not yet in the block limit (inide a , for example). - if ( oNode.parentNode != this.EndBlockLimit ) - oNode = oNode.parentNode ; - else - break ; - } - else if ( oSibling.nodeType != 1 || !(/^(?:P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|DT|DE)$/).test( oSibling.nodeName.toUpperCase() ) ) - { - // Continue if the sibling is not a block tag. - oNode = oSibling ; - } - else - break ; + this._Range.setEndAfter( oNode ) ; + oNode = oNode.nextSibling || oNode.parentNode ; } - this._Range.setEndAfter( oNode ) ; + // In EnterMode='br', the end
boundary element must + // be included in the expanded range. + if ( oNode && oNode.nodeName.toLowerCase() == 'br' ) + this._Range.setEndAfter( oNode ) ; } this._UpdateElementInfo() ; } }, + /** + * Split the block element for the current range. It deletes the contents + * of the range and splits the block in the collapsed position, resulting + * in two sucessive blocks. The range is then positioned in the middle of + * them. + * + * It returns and object with the following properties: + * - PreviousBlock : a reference to the block element that preceeds + * the range after the split. + * - NextBlock : a reference to the block element that follows the + * range after the split. + * - WasStartOfBlock : a boolean indicating that the range was + * originaly at the start of the block. + * - WasEndOfBlock : a boolean indicating that the range was originaly + * at the end of the block. + * + * If the range was originaly at the start of the block, no split will happen + * and the PreviousBlock value will be null. The same is valid for the + * NextBlock value if the range was at the end of the block. + */ + SplitBlock : function( forceBlockTag ) + { + var blockTag = forceBlockTag || FCKConfig.EnterMode ; + + if ( !this._Range ) + this.MoveToSelection() ; + + // The range boundaries must be in the same "block limit" element. + if ( this.StartBlockLimit == this.EndBlockLimit ) + { + // Get the current blocks. + var eStartBlock = this.StartBlock ; + var eEndBlock = this.EndBlock ; + var oElementPath = null ; + + if ( blockTag != 'br' ) + { + if ( !eStartBlock ) + { + eStartBlock = this.FixBlock( true, blockTag ) ; + eEndBlock = this.EndBlock ; // FixBlock may have fixed the EndBlock too. + } + + if ( !eEndBlock ) + eEndBlock = this.FixBlock( false, blockTag ) ; + } + + // Get the range position. + var bIsStartOfBlock = ( eStartBlock != null && this.CheckStartOfBlock() ) ; + var bIsEndOfBlock = ( eEndBlock != null && this.CheckEndOfBlock() ) ; + + // Delete the current contents. + if ( !this.CheckIsEmpty() ) + this.DeleteContents() ; + + if ( eStartBlock && eEndBlock && eStartBlock == eEndBlock ) + { + if ( bIsEndOfBlock ) + { + oElementPath = new FCKElementPath( this.StartContainer ) ; + this.MoveToPosition( eEndBlock, 4 ) ; + eEndBlock = null ; + } + else if ( bIsStartOfBlock ) + { + oElementPath = new FCKElementPath( this.StartContainer ) ; + this.MoveToPosition( eStartBlock, 3 ) ; + eStartBlock = null ; + } + else + { + // Extract the contents of the block from the selection point to the end of its contents. + this.SetEnd( eStartBlock, 2 ) ; + var eDocFrag = this.ExtractContents() ; + + // Duplicate the block element after it. + eEndBlock = eStartBlock.cloneNode( false ) ; + eEndBlock.removeAttribute( 'id', false ) ; + + // Place the extracted contents in the duplicated block. + eDocFrag.AppendTo( eEndBlock ) ; + + FCKDomTools.InsertAfterNode( eStartBlock, eEndBlock ) ; + + this.MoveToPosition( eStartBlock, 4 ) ; + + // In Gecko, the last child node must be a bogus
. + // Note: bogus
added under
    or
      would cause lists to be incorrectly rendered. + if ( FCKBrowserInfo.IsGecko && + ! eStartBlock.nodeName.IEquals( ['ul', 'ol'] ) ) + FCKTools.AppendBogusBr( eStartBlock ) ; + } + } + + return { + PreviousBlock : eStartBlock, + NextBlock : eEndBlock, + WasStartOfBlock : bIsStartOfBlock, + WasEndOfBlock : bIsEndOfBlock, + ElementPath : oElementPath + } ; + } + + return null ; + }, + + // Transform a block without a block tag in a valid block (orphan text in the body or td, usually). + FixBlock : function( isStart, blockTag ) + { + // Bookmark the range so we can restore it later. + var oBookmark = this.CreateBookmark() ; + + // Collapse the range to the requested ending boundary. + this.Collapse( isStart ) ; + + // Expands it to the block contents. + this.Expand( 'block_contents' ) ; + + // Create the fixed block. + var oFixedBlock = this.Window.document.createElement( blockTag ) ; + + // Move the contents of the temporary range to the fixed block. + this.ExtractContents().AppendTo( oFixedBlock ) ; + FCKDomTools.TrimNode( oFixedBlock ) ; + + // Insert the fixed block into the DOM. + this.InsertNode( oFixedBlock ) ; + + // Move the range back to the bookmarked place. + this.MoveToBookmark( oBookmark ) ; + + return oFixedBlock ; + }, + Release : function( preserveWindow ) { if ( !preserveWindow ) this.Window = null ; + this.StartNode = null ; this.StartContainer = null ; this.StartBlock = null ; this.StartBlockLimit = null ; + this.EndNode = null ; this.EndContainer = null ; this.EndBlock = null ; this.EndBlockLimit = null ; this._Range = null ; + this._Cache = null ; + }, + + CheckHasRange : function() + { + return !!this._Range ; + }, + + GetTouchedStartNode : function() + { + var range = this._Range ; + var container = range.startContainer ; + + if ( range.collapsed || container.nodeType != 1 ) + return container ; + + return container.childNodes[ range.startOffset ] || container ; + }, + + GetTouchedEndNode : function() + { + var range = this._Range ; + var container = range.endContainer ; + + if ( range.collapsed || container.nodeType != 1 ) + return container ; + + return container.childNodes[ range.endOffset - 1 ] || container ; } -} ; \ No newline at end of file +} ; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrange_gecko.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrange_gecko.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrange_gecko.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -19,7 +19,7 @@ * == END LICENSE == * * Class for working with a selection range, much like the W3C DOM Range, but - * it is not intented to be an implementation of the W3C interface. + * it is not intended to be an implementation of the W3C interface. * (Gecko Implementation) */ @@ -29,11 +29,14 @@ var oSel = this.Window.getSelection() ; - if ( oSel.rangeCount == 1 ) + if ( oSel && oSel.rangeCount > 0 ) { this._Range = FCKW3CRange.CreateFromRange( this.Window.document, oSel.getRangeAt(0) ) ; this._UpdateElementInfo() ; } + else + if ( this.Window.document ) + this.MoveToElementStart( this.Window.document.body ) ; } FCKDomRange.prototype.Select = function() @@ -41,8 +44,15 @@ var oRange = this._Range ; if ( oRange ) { + var startContainer = oRange.startContainer ; + + // If we have a collapsed range, inside an empty element, we must add + // something to it, otherwise the caret will not be visible. + if ( oRange.collapsed && startContainer.nodeType == 1 && startContainer.childNodes.length == 0 ) + startContainer.appendChild( oRange._Document.createTextNode('') ) ; + var oDocRange = this.Window.document.createRange() ; - oDocRange.setStart( oRange.startContainer, oRange.startOffset ) ; + oDocRange.setStart( startContainer, oRange.startOffset ) ; try { @@ -51,7 +61,7 @@ catch ( e ) { // There is a bug in Firefox implementation (it would be too easy - // otherwhise). The new start can't be after the end (W3C says it can). + // otherwise). The new start can't be after the end (W3C says it can). // So, let's create a new range and collapse it to the desired point. if ( e.toString().Contains( 'NS_ERROR_ILLEGAL_VALUE' ) ) { @@ -69,3 +79,26 @@ oSel.addRange( oDocRange ) ; } } + +// Not compatible with bookmark created with CreateBookmark2. +// The bookmark nodes will be deleted from the document. +FCKDomRange.prototype.SelectBookmark = function( bookmark ) +{ + var domRange = this.Window.document.createRange() ; + + var startNode = this.GetBookmarkNode( bookmark, true ) ; + var endNode = this.GetBookmarkNode( bookmark, false ) ; + + domRange.setStart( startNode.parentNode, FCKDomTools.GetIndexOf( startNode ) ) ; + FCKDomTools.RemoveNode( startNode ) ; + + if ( endNode ) + { + domRange.setEnd( endNode.parentNode, FCKDomTools.GetIndexOf( endNode ) ) ; + FCKDomTools.RemoveNode( endNode ) ; + } + + var selection = this.Window.getSelection() ; + selection.removeAllRanges() ; + selection.addRange( domRange ) ; +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrange_ie.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrange_ie.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrange_ie.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -19,7 +19,7 @@ * == END LICENSE == * * Class for working with a selection range, much like the W3C DOM Range, but - * it is not intented to be an implementation of the W3C interface. + * it is not intended to be an implementation of the W3C interface. * (IE Implementation) */ @@ -33,15 +33,23 @@ if ( oSel.type != 'Control' ) { + var eMarkerStart = this._GetSelectionMarkerTag( true ) ; + var eMarkerEnd = this._GetSelectionMarkerTag( false ) ; + + if ( !eMarkerStart && !eMarkerEnd ) + { + this._Range.setStart( this.Window.document.body, 0 ) ; + this._UpdateElementInfo() ; + return ; + } + // Set the start boundary. - eMarker = this._GetSelectionMarkerTag( true ) ; - this._Range.setStart( eMarker.parentNode, FCKDomTools.GetIndexOf( eMarker ) ) ; - eMarker.parentNode.removeChild( eMarker ) ; + this._Range.setStart( eMarkerStart.parentNode, FCKDomTools.GetIndexOf( eMarkerStart ) ) ; + eMarkerStart.parentNode.removeChild( eMarkerStart ) ; // Set the end boundary. - var eMarker = this._GetSelectionMarkerTag( false ) ; - this._Range.setEnd( eMarker.parentNode, FCKDomTools.GetIndexOf( eMarker ) ) ; - eMarker.parentNode.removeChild( eMarker ) ; + this._Range.setEnd( eMarkerEnd.parentNode, FCKDomTools.GetIndexOf( eMarkerEnd ) ) ; + eMarkerEnd.parentNode.removeChild( eMarkerEnd ) ; this._UpdateElementInfo() ; } @@ -58,92 +66,134 @@ } } -FCKDomRange.prototype.Select = function() +FCKDomRange.prototype.Select = function( forceExpand ) { if ( this._Range ) - { - var bIsCollapsed = this.CheckIsCollapsed() ; + this.SelectBookmark( this.CreateBookmark( true ), forceExpand ) ; +} - // Create marker tags for the start and end boundaries. - var eStartMarker = this._GetRangeMarkerTag( true ) ; +// Not compatible with bookmark created with CreateBookmark2. +// The bookmark nodes will be deleted from the document. +FCKDomRange.prototype.SelectBookmark = function( bookmark, forceExpand ) +{ + var bIsCollapsed = this.CheckIsCollapsed() ; + var bIsStartMakerAlone ; + var dummySpan ; - if ( !bIsCollapsed ) - var eEndMarker = this._GetRangeMarkerTag( false ) ; + // Create marker tags for the start and end boundaries. + var eStartMarker = this.GetBookmarkNode( bookmark, true ) ; - // Create the main range which will be used for the selection. - var oIERange = this.Window.document.body.createTextRange() ; + if ( !eStartMarker ) + return ; - // Position the range at the start boundary. - oIERange.moveToElementText( eStartMarker ) ; - oIERange.moveStart( 'character', 1 ) ; + var eEndMarker ; + if ( !bIsCollapsed ) + eEndMarker = this.GetBookmarkNode( bookmark, false ) ; - if ( !bIsCollapsed ) - { - // Create a tool range for the end. - var oIERangeEnd = this.Window.document.body.createTextRange() ; + // Create the main range which will be used for the selection. + var oIERange = this.Window.document.body.createTextRange() ; - // Position the tool range at the end. - oIERangeEnd.moveToElementText( eEndMarker ) ; + // Position the range at the start boundary. + oIERange.moveToElementText( eStartMarker ) ; + oIERange.moveStart( 'character', 1 ) ; - // Move the end boundary of the main range to match the tool range. - oIERange.setEndPoint( 'EndToEnd', oIERangeEnd ) ; - oIERange.moveEnd( 'character', -1 ) ; + if ( eEndMarker ) + { + // Create a tool range for the end. + var oIERangeEnd = this.Window.document.body.createTextRange() ; + + // Position the tool range at the end. + oIERangeEnd.moveToElementText( eEndMarker ) ; + + // Move the end boundary of the main range to match the tool range. + oIERange.setEndPoint( 'EndToEnd', oIERangeEnd ) ; + oIERange.moveEnd( 'character', -1 ) ; + } + else + { + bIsStartMakerAlone = ( forceExpand || !eStartMarker.previousSibling || eStartMarker.previousSibling.nodeName.toLowerCase() == 'br' ) && !eStartMarker.nextSibing ; + + // Append a temporary  before the selection. + // This is needed to avoid IE destroying selections inside empty + // inline elements, like (#253). + // It is also needed when placing the selection right after an inline + // element to avoid the selection moving inside of it. + dummySpan = this.Window.document.createElement( 'span' ) ; + dummySpan.innerHTML = '' ; // Zero Width No-Break Space (U+FEFF). See #1359. + eStartMarker.parentNode.insertBefore( dummySpan, eStartMarker ) ; + + if ( bIsStartMakerAlone ) + { + // To expand empty blocks or line spaces after
      , we need + // instead to have any char, which will be later deleted using the + // selection. + // \ufeff = Zero Width No-Break Space (U+FEFF). See #1359. + eStartMarker.parentNode.insertBefore( this.Window.document.createTextNode( '\ufeff' ), eStartMarker ) ; } + } - // Remove the markers (reset the position, because of the changes in the DOM tree). - this._Range.setStartBefore( eStartMarker ) ; - eStartMarker.parentNode.removeChild( eStartMarker ) ; + if ( !this._Range ) + this._Range = this.CreateRange() ; - if ( bIsCollapsed ) + // Remove the markers (reset the position, because of the changes in the DOM tree). + this._Range.setStartBefore( eStartMarker ) ; + eStartMarker.parentNode.removeChild( eStartMarker ) ; + + if ( bIsCollapsed ) + { + if ( bIsStartMakerAlone ) { - // The following trick is needed so IE makes collapsed selections - // inside empty blocks visible (expands the block). - try - { - oIERange.pasteHTML(' ') ; - oIERange.moveStart( 'character', -1 ) ; - } - catch (e){} + // Move the selection start to include the temporary . + oIERange.moveStart( 'character', -1 ) ; + oIERange.select() ; - oIERange.pasteHTML('') ; + + // Remove our temporary stuff. + this.Window.document.selection.clear() ; } else - { - this._Range.setEndBefore( eEndMarker ) ; - eEndMarker.parentNode.removeChild( eEndMarker ) ; oIERange.select() ; - } + + FCKDomTools.RemoveNode( dummySpan ) ; } + else + { + this._Range.setEndBefore( eEndMarker ) ; + eEndMarker.parentNode.removeChild( eEndMarker ) ; + oIERange.select() ; + } } FCKDomRange.prototype._GetSelectionMarkerTag = function( toStart ) { + var doc = this.Window.document ; + var selection = doc.selection ; + // Get a range for the start boundary. - var oRange = this.Window.document.selection.createRange() ; + var oRange ; + + // IE may throw an "unspecified error" on some cases (it happened when + // loading _samples/default.html), so try/catch. + try + { + oRange = selection.createRange() ; + } + catch (e) + { + return null ; + } + + // IE might take the range object to the main window instead of inside the editor iframe window. + // This is known to happen when the editor window has not been selected before (See #933). + // We need to avoid that. + if ( oRange.parentElement().document != doc ) + return null ; + oRange.collapse( toStart === true ) ; // Paste a marker element at the collapsed range and get it from the DOM. var sMarkerId = 'fck_dom_range_temp_' + (new Date()).valueOf() + '_' + Math.floor(Math.random()*1000) ; oRange.pasteHTML( '' ) ; - return this.Window.document.getElementById( sMarkerId ) ; + + return doc.getElementById( sMarkerId ) ; } - -FCKDomRange.prototype._GetRangeMarkerTag = function( toStart ) -{ - // Get a range for the start boundary. - var oRange = this._Range ; - - // insertNode() will add the node at the beginning of the Range, updating - // the endOffset if necessary. So, we can work with the current range in this case. - if ( !toStart ) - { - oRange = oRange.cloneRange() ; - oRange.collapse( toStart === true ) ; - } - - var eSpan = this.Window.document.createElement( 'span' ) ; - eSpan.innerHTML = ' ' ; - oRange.insertNode( eSpan ) ; - - return eSpan ; -} \ No newline at end of file Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrangeiterator.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrangeiterator.js (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckdomrangeiterator.js 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,327 @@ +?/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * This class can be used to interate through nodes inside a range. + * + * During interation, the provided range can become invalid, due to document + * mutations, so CreateBookmark() used to restore it after processing, if + * needed. + */ + +var FCKDomRangeIterator = function( range ) +{ + /** + * The FCKDomRange object that marks the interation boundaries. + */ + this.Range = range ; + + /** + * Indicates that
      elements must be used as paragraph boundaries. + */ + this.ForceBrBreak = false ; + + /** + * Guarantees that the iterator will always return "real" block elements. + * If "false", elements like
    1. , and are returned. If "true", a + * dedicated block element block element will be created inside those + * elements to hold the selected content. + */ + this.EnforceRealBlocks = false ; +} + +FCKDomRangeIterator.CreateFromSelection = function( targetWindow ) +{ + var range = new FCKDomRange( targetWindow ) ; + range.MoveToSelection() ; + return new FCKDomRangeIterator( range ) ; +} + +FCKDomRangeIterator.prototype = +{ + /** + * Get the next paragraph element. It automatically breaks the document + * when necessary to generate block elements for the paragraphs. + */ + GetNextParagraph : function() + { + // The block element to be returned. + var block ; + + // The range object used to identify the paragraph contents. + var range ; + + // Indicated that the current element in the loop is the last one. + var isLast ; + + // Instructs to cleanup remaining BRs. + var removePreviousBr ; + var removeLastBr ; + + var boundarySet = this.ForceBrBreak ? FCKListsLib.ListBoundaries : FCKListsLib.BlockBoundaries ; + + // This is the first iteration. Let's initialize it. + if ( !this._LastNode ) + { + var range = this.Range.Clone() ; + range.Expand( this.ForceBrBreak ? 'list_contents' : 'block_contents' ) ; + + this._NextNode = range.GetTouchedStartNode() ; + this._LastNode = range.GetTouchedEndNode() ; + + // Let's reuse this variable. + range = null ; + } + + var currentNode = this._NextNode ; + var lastNode = this._LastNode ; + + this._NextNode = null ; + + while ( currentNode ) + { + // closeRange indicates that a paragraph boundary has been found, + // so the range can be closed. + var closeRange = false ; + + // includeNode indicates that the current node is good to be part + // of the range. By default, any non-element node is ok for it. + var includeNode = ( currentNode.nodeType != 1 ) ; + + var continueFromSibling = false ; + + // If it is an element node, let's check if it can be part of the + // range. + if ( !includeNode ) + { + var nodeName = currentNode.nodeName.toLowerCase() ; + + if ( boundarySet[ nodeName ] && ( !FCKBrowserInfo.IsIE || currentNode.scopeName == 'HTML' ) ) + { + //
      boundaries must be part of the range. It will + // happen only if ForceBrBreak. + if ( nodeName == 'br' ) + includeNode = true ; + else if ( !range && currentNode.childNodes.length == 0 && nodeName != 'hr' ) + { + // If we have found an empty block, and haven't started + // the range yet, it means we must return this block. + block = currentNode ; + isLast = currentNode == lastNode ; + break ; + } + + // The range must finish right before the boundary, + // including possibly skipped empty spaces. (#1603) + if ( range ) + { + range.SetEnd( currentNode, 3, true ) ; + + // The found boundary must be set as the next one at this + // point. (#1717) + if ( nodeName != 'br' ) + this._NextNode = currentNode ; + } + + closeRange = true ; + } + else + { + // If we have child nodes, let's check them. + if ( currentNode.firstChild ) + { + // If we don't have a range yet, let's start it. + if ( !range ) + { + range = new FCKDomRange( this.Range.Window ) ; + range.SetStart( currentNode, 3, true ) ; + } + + currentNode = currentNode.firstChild ; + continue ; + } + includeNode = true ; + } + } + else if ( currentNode.nodeType == 3 ) + { + // Ignore normal whitespaces (i.e. not including   or + // other unicode whitespaces) before/after a block node. + if ( /^[\r\n\t ]+$/.test( currentNode.nodeValue ) ) + includeNode = false ; + } + + // The current node is good to be part of the range and we are + // starting a new range, initialize it first. + if ( includeNode && !range ) + { + range = new FCKDomRange( this.Range.Window ) ; + range.SetStart( currentNode, 3, true ) ; + } + + // The last node has been found. + isLast = ( ( !closeRange || includeNode ) && currentNode == lastNode ) ; +// isLast = ( currentNode == lastNode && ( currentNode.nodeType != 1 || currentNode.childNodes.length == 0 ) ) ; + + // If we are in an element boundary, let's check if it is time + // to close the range, otherwise we include the parent within it. + if ( range && !closeRange ) + { + while ( !currentNode.nextSibling && !isLast ) + { + var parentNode = currentNode.parentNode ; + + if ( boundarySet[ parentNode.nodeName.toLowerCase() ] ) + { + closeRange = true ; + isLast = isLast || ( parentNode == lastNode ) ; + break ; + } + + currentNode = parentNode ; + includeNode = true ; + isLast = ( currentNode == lastNode ) ; + continueFromSibling = true ; + } + } + + // Now finally include the node. + if ( includeNode ) + range.SetEnd( currentNode, 4, true ) ; + + // We have found a block boundary. Let's close the range and move out of the + // loop. + if ( ( closeRange || isLast ) && range ) + { + range._UpdateElementInfo() ; + + if ( range.StartNode == range.EndNode + && range.StartNode.parentNode == range.StartBlockLimit + && range.StartNode.getAttribute && range.StartNode.getAttribute( '_fck_bookmark' ) ) + range = null ; + else + break ; + } + + if ( isLast ) + break ; + + currentNode = FCKDomTools.GetNextSourceNode( currentNode, continueFromSibling, null, lastNode ) ; + } + + // Now, based on the processed range, look for (or create) the block to be returned. + if ( !block ) + { + // If no range has been found, this is the end. + if ( !range ) + { + this._NextNode = null ; + return null ; + } + + block = range.StartBlock ; + + if ( !block + && !this.EnforceRealBlocks + && range.StartBlockLimit.nodeName.IEquals( 'DIV', 'TH', 'TD' ) + && range.CheckStartOfBlock() + && range.CheckEndOfBlock() ) + { + block = range.StartBlockLimit ; + } + else if ( !block || ( this.EnforceRealBlocks && block.nodeName.toLowerCase() == 'li' ) ) + { + // Create the fixed block. + block = this.Range.Window.document.createElement( FCKConfig.EnterMode == 'p' ? 'p' : 'div' ) ; + + // Move the contents of the temporary range to the fixed block. + range.ExtractContents().AppendTo( block ) ; + FCKDomTools.TrimNode( block ) ; + + // Insert the fixed block into the DOM. + range.InsertNode( block ) ; + + removePreviousBr = true ; + removeLastBr = true ; + } + else if ( block.nodeName.toLowerCase() != 'li' ) + { + // If the range doesn't includes the entire contents of the + // block, we must split it, isolating the range in a dedicated + // block. + if ( !range.CheckStartOfBlock() || !range.CheckEndOfBlock() ) + { + // The resulting block will be a clone of the current one. + block = block.cloneNode( false ) ; + + // Extract the range contents, moving it to the new block. + range.ExtractContents().AppendTo( block ) ; + FCKDomTools.TrimNode( block ) ; + + // Split the block. At this point, the range will be in the + // right position for our intents. + var splitInfo = range.SplitBlock() ; + + removePreviousBr = !splitInfo.WasStartOfBlock ; + removeLastBr = !splitInfo.WasEndOfBlock ; + + // Insert the new block into the DOM. + range.InsertNode( block ) ; + } + } + else if ( !isLast ) + { + // LIs are returned as is, with all their children (due to the + // nested lists). But, the next node is the node right after + // the current range, which could be an
    2. child (nested + // lists) or the next sibling
    3. . + + this._NextNode = block == lastNode ? null : FCKDomTools.GetNextSourceNode( range.EndNode, true, null, lastNode ) ; + return block ; + } + } + + if ( removePreviousBr ) + { + var previousSibling = block.previousSibling ; + if ( previousSibling && previousSibling.nodeType == 1 ) + { + if ( previousSibling.nodeName.toLowerCase() == 'br' ) + previousSibling.parentNode.removeChild( previousSibling ) ; + else if ( previousSibling.lastChild && previousSibling.lastChild.nodeName.IEquals( 'br' ) ) + previousSibling.removeChild( previousSibling.lastChild ) ; + } + } + + if ( removeLastBr ) + { + var lastChild = block.lastChild ; + if ( lastChild && lastChild.nodeType == 1 && lastChild.nodeName.toLowerCase() == 'br' ) + block.removeChild( lastChild ) ; + } + + // Get a reference for the next element. This is important because the + // above block can be removed or changed, so we can rely on it for the + // next interation. + if ( !this._NextNode ) + this._NextNode = ( isLast || block == lastNode ) ? null : FCKDomTools.GetNextSourceNode( block, true, null, lastNode ) ; + + return block ; + } +} ; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckeditingarea.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckeditingarea.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckeditingarea.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -44,49 +44,82 @@ var oTargetDocument = FCKTools.GetElementDocument( eTargetElement ) ; // Remove all child nodes from the target. - while( eTargetElement.childNodes.length > 0 ) - eTargetElement.removeChild( eTargetElement.childNodes[0] ) ; + while( eTargetElement.firstChild ) + eTargetElement.removeChild( eTargetElement.firstChild ) ; if ( this.Mode == FCK_EDITMODE_WYSIWYG ) { - // Create the editing area IFRAME. - var oIFrame = this.IFrame = oTargetDocument.createElement( 'iframe' ) ; - oIFrame.src = 'javascript:void(0)' ; - oIFrame.frameBorder = 0 ; - oIFrame.width = oIFrame.height = '100%' ; + // For FF, document.domain must be set only when different, otherwhise + // we'll strangely have "Permission denied" issues. + if ( FCK_IS_CUSTOM_DOMAIN ) + html = '' + html ; - // Append the new IFRAME to the target. - eTargetElement.appendChild( oIFrame ) ; - // IE has a bug with the tag... it must have a closer, - // otherwise the all sucessive tags will be set as children nodes of the . + // otherwise the all successive tags will be set as children nodes of the . if ( FCKBrowserInfo.IsIE ) html = html.replace( /(]*?)\s*\/?>(?!\s*<\/base>)/gi, '$1>' ) ; else if ( !secondCall ) { - // If nothing in the body, place a BOGUS tag so the cursor will appear. - if ( FCKBrowserInfo.IsGecko ) - html = html.replace( /(]*>)\s*(<\/body>)/i, '$1' + GECKO_BOGUS + '$2' ) ; - // Gecko moves some tags out of the body to the head, so we must use // innerHTML to set the body contents (SF BUG 1526154). // Extract the BODY contents from the html. - var oMatch = html.match( FCKRegexLib.BodyContents ) ; + var oMatchBefore = html.match( FCKRegexLib.BeforeBody ) ; + var oMatchAfter = html.match( FCKRegexLib.AfterBody ) ; - if ( oMatch ) + if ( oMatchBefore && oMatchAfter ) { + var sBody = html.substr( oMatchBefore[1].length, + html.length - oMatchBefore[1].length - oMatchAfter[1].length ) ; // This is the BODY tag contents. + html = - oMatch[1] + // This is the HTML until the tag, inclusive. + oMatchBefore[1] + // This is the HTML until the tag, inclusive. ' ' + - oMatch[3] ; // This is the HTML from the tag, inclusive. + oMatchAfter[1] ; // This is the HTML from the tag, inclusive. - this._BodyHTML = oMatch[2] ; // This is the BODY tag contents. + // If nothing in the body, place a BOGUS tag so the cursor will appear. + if ( FCKBrowserInfo.IsGecko && ( sBody.length == 0 || FCKRegexLib.EmptyParagraph.test( sBody ) ) ) + sBody = '
      ' ; + + this._BodyHTML = sBody ; + } else this._BodyHTML = html ; // Invalid HTML input. } + // Create the editing area IFRAME. + var oIFrame = this.IFrame = oTargetDocument.createElement( 'iframe' ) ; + + // IE: Avoid JavaScript errors thrown by the editing are source (like tags events). + // See #1055. + var sOverrideError = '' ; + + oIFrame.frameBorder = 0 ; + oIFrame.width = oIFrame.height = '100%' ; + + if ( FCK_IS_CUSTOM_DOMAIN && FCKBrowserInfo.IsIE ) + { + window._FCKHtmlToLoad = sOverrideError + html ; + oIFrame.src = 'javascript:void( (function(){' + + 'document.open() ;' + + 'document.domain="' + document.domain + '" ;' + + 'document.write( window.parent._FCKHtmlToLoad );' + + 'document.close() ;' + + 'window.parent._FCKHtmlToLoad = null ;' + + '})() )' ; + } + else if ( !FCKBrowserInfo.IsGecko ) + { + // Firefox will render the tables inside the body in Quirks mode if the + // source of the iframe is set to javascript. see #515 + oIFrame.src = 'javascript:void(0)' ; + } + + // Append the new IFRAME to the target. For IE, it must be done after + // setting the "src", to avoid the "secure/unsecure" message under HTTPS. + eTargetElement.appendChild( oIFrame ) ; + // Get the window and document objects used to interact with the newly created IFRAME. this.Window = oIFrame.contentWindow ; @@ -94,38 +127,69 @@ // TODO: This error handler is not being fired. // this.Window.onerror = function() { alert( 'Error!' ) ; return true ; } - var oDoc = this.Document = this.Window.document ; + if ( !FCK_IS_CUSTOM_DOMAIN || !FCKBrowserInfo.IsIE ) + { + var oDoc = this.Window.document ; - oDoc.open() ; - oDoc.write( html ) ; - oDoc.close() ; + oDoc.open() ; + oDoc.write( sOverrideError + html ) ; + oDoc.close() ; + } + if ( FCKBrowserInfo.IsAIR ) + FCKAdobeAIR.EditingArea_Start( oDoc, html ) ; + // Firefox 1.0.x is buggy... ohh yes... so let's do it two times and it - // will magicaly work. + // will magically work. if ( FCKBrowserInfo.IsGecko10 && !secondCall ) { this.Start( html, true ) ; return ; } - this.Window._FCKEditingArea = this ; + if ( oIFrame.readyState && oIFrame.readyState != 'completed' ) + { + var editArea = this ; + ( oIFrame.onreadystatechange = function() + { + if ( oIFrame.readyState == 'complete' ) + { + oIFrame.onreadystatechange = null ; + editArea.Window._FCKEditingArea = editArea ; + FCKEditingArea_CompleteStart.call( editArea.Window ) ; + } + // It happened that IE changed the state to "complete" after the + // "if" and before the "onreadystatechange" assignement, making we + // lost the event call, so we do a manual call just to be sure. + } )() ; + } + else + { + this.Window._FCKEditingArea = this ; - // FF 1.0.x is buggy... we must wait a lot to enable editing because - // sometimes the content simply disappears, for example when pasting - // "bla1!!bla2" in the source and then switching - // back to design. - if ( FCKBrowserInfo.IsGecko10 ) - this.Window.setTimeout( FCKEditingArea_CompleteStart, 500 ) ; - else - FCKEditingArea_CompleteStart.call( this.Window ) ; + // FF 1.0.x is buggy... we must wait a lot to enable editing because + // sometimes the content simply disappears, for example when pasting + // "bla1!!bla2" in the source and then switching + // back to design. + if ( FCKBrowserInfo.IsGecko10 ) + this.Window.setTimeout( FCKEditingArea_CompleteStart, 500 ) ; + else + FCKEditingArea_CompleteStart.call( this.Window ) ; + } } else { var eTextarea = this.Textarea = oTargetDocument.createElement( 'textarea' ) ; eTextarea.className = 'SourceField' ; eTextarea.dir = 'ltr' ; - eTextarea.style.width = eTextarea.style.height = '100%' ; - eTextarea.style.border = 'none' ; + FCKDomTools.SetElementStyles( eTextarea, + { + width : '100%', + height : '100%', + border : 'none', + resize : 'none', + outline : 'none' + } ) ; eTargetElement.appendChild( eTextarea ) ; eTextarea.value = html ; @@ -138,7 +202,7 @@ // "this" here is FCKEditingArea.Window function FCKEditingArea_CompleteStart() { - // Of Firefox, the DOM takes a little to become available. So we must wait for it in a loop. + // On Firefox, the DOM takes a little to become available. So we must wait for it in a loop. if ( !this.document.body ) { this.setTimeout( FCKEditingArea_CompleteStart, 50 ) ; @@ -146,6 +210,10 @@ } var oEditorArea = this._FCKEditingArea ; + + // Save this reference to be re-used later. + oEditorArea.Document = oEditorArea.Window.document ; + oEditorArea.MakeEditable() ; // Fire the "OnLoad" event. @@ -158,7 +226,10 @@ if ( FCKBrowserInfo.IsIE ) { + // Kludge for #141 and #523 + oDoc.body.disabled = true ; oDoc.body.contentEditable = true ; + oDoc.body.removeAttribute( "disabled" ) ; /* The following commands don't throw errors, but have no effect. oDoc.execCommand( 'AutoDetect', false, false ) ; @@ -180,51 +251,58 @@ oDoc.designMode = 'on' ; - // Tell Gecko to use or not the tag for the bold, italic and underline. - try - { - oDoc.execCommand( 'styleWithCSS', false, FCKConfig.GeckoUseSPAN ) ; - } - catch (e) - { - // As evidenced here, useCSS is deprecated in favor of styleWithCSS: - // http://www.mozilla.org/editor/midas-spec.html - oDoc.execCommand( 'useCSS', false, !FCKConfig.GeckoUseSPAN ) ; - } - - // Analysing Firefox 1.5 source code, it seams that there is support for a - // "insertBrOnReturn" command. Applying it gives no error, but it doesn't - // gives the same behavior that you have with IE. It works only if you are - // already inside a paragraph and it doesn't render correctly in the first enter. - // oDoc.execCommand( 'insertBrOnReturn', false, false ) ; - // Tell Gecko (Firefox 1.5+) to enable or not live resizing of objects (by Alfonso Martinez) oDoc.execCommand( 'enableObjectResizing', false, !FCKConfig.DisableObjectResizing ) ; // Disable the standard table editing features of Firefox. oDoc.execCommand( 'enableInlineTableEditing', false, !FCKConfig.DisableFFTableHandles ) ; } - catch (e) {} + catch (e) + { + // In Firefox if the iframe is initially hidden it can't be set to designMode and it raises an exception + // So we set up a DOM Mutation event Listener on the HTML, as it will raise several events when the document is visible again + FCKTools.AddEventListener( this.Window.frameElement, 'DOMAttrModified', FCKEditingArea_Document_AttributeNodeModified ) ; + } + } } +// This function processes the notifications of the DOM Mutation event on the document +// We use it to know that the document will be ready to be editable again (or we hope so) +function FCKEditingArea_Document_AttributeNodeModified( evt ) +{ + var editingArea = evt.currentTarget.contentWindow._FCKEditingArea ; + + // We want to run our function after the events no longer fire, so we can know that it's a stable situation + if ( editingArea._timer ) + window.clearTimeout( editingArea._timer ) ; + + editingArea._timer = FCKTools.SetTimeout( FCKEditingArea_MakeEditableByMutation, 1000, editingArea ) ; +} + +// This function ideally should be called after the document is visible, it does clean up of the +// mutation tracking and tries again to make the area editable. +function FCKEditingArea_MakeEditableByMutation() +{ + // Clean up + delete this._timer ; + // Now we don't want to keep on getting this event + FCKTools.RemoveEventListener( this.Window.frameElement, 'DOMAttrModified', FCKEditingArea_Document_AttributeNodeModified ) ; + // Let's try now to set the editing area editable + // If it fails it will set up the Mutation Listener again automatically + this.MakeEditable() ; +} + FCKEditingArea.prototype.Focus = function() { try { if ( this.Mode == FCK_EDITMODE_WYSIWYG ) { - // The following check is important to avoid IE entering in a focus loop. Ref: - // http://sourceforge.net/tracker/index.php?func=detail&aid=1567060&group_id=75348&atid=543653 - if ( FCKBrowserInfo.IsIE && this.Document.hasFocus() ) - return ; - - if ( FCKBrowserInfo.IsSafari ) - this.IFrame.focus() ; + if ( FCKBrowserInfo.IsIE ) + this._FocusIE() ; else - { this.Window.focus() ; - } } else { @@ -238,8 +316,39 @@ catch(e) {} } +FCKEditingArea.prototype._FocusIE = function() +{ + // In IE it can happen that the document is in theory focused but the + // active element is outside of it. + this.Document.body.setActive() ; + + this.Window.focus() ; + + // Kludge for #141... yet more code to workaround IE bugs + var range = this.Document.selection.createRange() ; + + var parentNode = range.parentElement() ; + var parentTag = parentNode.nodeName.toLowerCase() ; + + // Only apply the fix when in a block, and the block is empty. + if ( parentNode.childNodes.length > 0 || + !( FCKListsLib.BlockElements[parentTag] || + FCKListsLib.NonEmptyBlockElements[parentTag] ) ) + { + return ; + } + + // Force the selection to happen, in this way we guarantee the focus will + // be there. + range = new FCKDomRange( this.Window ) ; + range.MoveToElementEditStart( parentNode ) ; + range.Select() ; +} + function FCKEditingArea_Cleanup() { + if ( this.Document ) + this.Document.body.innerHTML = "" ; this.TargetElement = null ; this.IFrame = null ; this.Document = null ; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckelementpath.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckelementpath.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckelementpath.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -18,12 +18,10 @@ * * == END LICENSE == * - * Manages the DOM anscensors element list of a specific DOM node + * Manages the DOM ascensors element list of a specific DOM node * (limited to body, inclusive). */ -// TODO: Implement IE cleanup. - var FCKElementPath = function( lastNode ) { var eBlock = null ; @@ -40,6 +38,8 @@ this.LastElement = e ; var sElementName = e.nodeName.toLowerCase() ; + if ( FCKBrowserInfo.IsIE && e.scopeName != 'HTML' ) + sElementName = e.scopeName.toLowerCase() + ':' + sElementName ; if ( !eBlockLimit ) { @@ -47,7 +47,14 @@ eBlock = e ; if ( FCKListsLib.PathBlockLimitElements[ sElementName ] != null ) - eBlockLimit = e ; + { + // DIV is considered the Block, if no block is available (#525) + // and if it doesn't contain other blocks. + if ( !eBlock && sElementName == 'div' && !FCKElementPath._CheckHasBlock( e ) ) + eBlock = e ; + else + eBlockLimit = e ; + } } aElements.push( e ) ; @@ -63,4 +70,20 @@ this.Elements = aElements ; } +/** + * Check if an element contains any block element. + */ +FCKElementPath._CheckHasBlock = function( element ) +{ + var childNodes = element.childNodes ; + for ( var i = 0, count = childNodes.length ; i < count ; i++ ) + { + var child = childNodes[i] ; + + if ( child.nodeType == 1 && FCKListsLib.BlockElements[ child.nodeName.toLowerCase() ] ) + return true ; + } + + return false ; +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckenterkey.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckenterkey.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckenterkey.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -29,7 +29,7 @@ * @shiftEnterMode : the behavior for the + keystroke. * May be "p", "div", "br". Defaults to "br". */ -var FCKEnterKey = function( targetWindow, enterMode, shiftEnterMode ) +var FCKEnterKey = function( targetWindow, enterMode, shiftEnterMode, tabSpaces ) { this.Window = targetWindow ; this.EnterMode = enterMode || 'p' ; @@ -43,10 +43,19 @@ oKeystrokeHandler.SetKeystrokes( [ [ 13 , 'Enter' ], [ SHIFT + 13, 'ShiftEnter' ], + [ 9 , 'Tab' ], [ 8 , 'Backspace' ], + [ CTRL + 8 , 'CtrlBackspace' ], [ 46 , 'Delete' ] ] ) ; + if ( tabSpaces > 0 ) + { + this.TabText = '' ; + while ( tabSpaces-- > 0 ) + this.TabText += '\xa0' ; + } + oKeystrokeHandler.AttachToElement( targetWindow.document ) ; } @@ -62,17 +71,21 @@ case 'Enter' : return oEnterKey.DoEnter() ; break ; - case 'ShiftEnter' : return oEnterKey.DoShiftEnter() ; break ; - case 'Backspace' : return oEnterKey.DoBackspace() ; break ; - case 'Delete' : return oEnterKey.DoDelete() ; + break ; + case 'Tab' : + return oEnterKey.DoTab() ; + break ; + case 'CtrlBackspace' : + return oEnterKey.DoCtrlBackspace() ; + break ; } } catch (e) @@ -89,11 +102,16 @@ */ FCKEnterKey.prototype.DoEnter = function( mode, hasShift ) { + // Save an undo snapshot before doing anything + FCKUndo.SaveUndoStep() ; + this._HasShift = ( hasShift === true ) ; + var parentElement = FCKSelection.GetParentElement() ; + var parentPath = new FCKElementPath( parentElement ) ; var sMode = mode || this.EnterMode ; - if ( sMode == 'br' ) + if ( sMode == 'br' || parentPath.Block && parentPath.Block.tagName.toLowerCase() == 'pre' ) return this._ExecuteEnterBr() ; else return this._ExecuteEnterBlock( sMode ) ; @@ -118,8 +136,32 @@ var oRange = new FCKDomRange( this.Window ) ; oRange.MoveToSelection() ; - if ( !oRange.CheckIsCollapsed() ) + // Kludge for #247 + if ( FCKBrowserInfo.IsIE && this._CheckIsAllContentsIncluded( oRange, this.Window.document.body ) ) + { + this._FixIESelectAllBug( oRange ) ; + return true ; + } + + var isCollapsed = oRange.CheckIsCollapsed() ; + + if ( !isCollapsed ) + { + // Bug #327, Backspace with an img selection would activate the default action in IE. + // Let's override that with our logic here. + if ( FCKBrowserInfo.IsIE && this.Window.document.selection.type.toLowerCase() == "control" ) + { + var controls = this.Window.document.selection.createRange() ; + for ( var i = controls.length - 1 ; i >= 0 ; i-- ) + { + var el = controls.item( i ) ; + el.parentNode.removeChild( el ) ; + } + return true ; + } + return false ; + } var oStartBlock = oRange.StartBlock ; var oEndBlock = oRange.EndBlock ; @@ -127,7 +169,7 @@ // The selection boundaries must be in the same "block limit" element if ( oRange.StartBlockLimit == oRange.EndBlockLimit && oStartBlock && oEndBlock ) { - if ( !oRange.CheckIsCollapsed() ) + if ( !isCollapsed ) { var bEndOfBlock = oRange.CheckEndOfBlock() ; @@ -155,9 +197,10 @@ bCustom = this._ExecuteBackspace( oRange, ePrevious, oCurrentBlock ) ; } - else if ( FCKBrowserInfo.IsGecko ) + else if ( FCKBrowserInfo.IsGeckoLike ) { - // Firefox looses the selection when executing CheckStartOfBlock, so we must reselect. + // Firefox and Opera (#1095) loose the selection when executing + // CheckStartOfBlock, so we must reselect. oRange.Select() ; } } @@ -166,12 +209,25 @@ return bCustom ; } +FCKEnterKey.prototype.DoCtrlBackspace = function() +{ + FCKUndo.SaveUndoStep() ; + var oRange = new FCKDomRange( this.Window ) ; + oRange.MoveToSelection() ; + if ( FCKBrowserInfo.IsIE && this._CheckIsAllContentsIncluded( oRange, this.Window.document.body ) ) + { + this._FixIESelectAllBug( oRange ) ; + return true ; + } + return false ; +} + FCKEnterKey.prototype._ExecuteBackspace = function( range, previous, currentBlock ) { var bCustom = false ; // We could be in a nested LI. - if ( !previous && currentBlock.nodeName.IEquals( 'LI' ) && currentBlock.parentNode.parentNode.nodeName.IEquals( 'LI' ) ) + if ( !previous && currentBlock && currentBlock.nodeName.IEquals( 'LI' ) && currentBlock.parentNode.parentNode.nodeName.IEquals( 'LI' ) ) { this._OutdentWithSelection( currentBlock, range ) ; return true ; @@ -220,24 +276,26 @@ } // Cleanup the previous and the current elements. - FCKDomTools.TrimNode( currentBlock ) ; - FCKDomTools.TrimNode( previous ) ; + FCKDomTools.LTrimNode( currentBlock ) ; + FCKDomTools.RTrimNode( previous ) ; // Append a space to the previous. // Maybe it is not always desirable... // previous.appendChild( this.Window.document.createTextNode( ' ' ) ) ; // Set the range to the end of the previous element and bookmark it. - range.SetStart( previous, 2 ) ; + range.SetStart( previous, 2, true ) ; range.Collapse( true ) ; - var oBookmark = range.CreateBookmark() ; + var oBookmark = range.CreateBookmark( true ) ; // Move the contents of the block to the previous element and delete it. - FCKDomTools.MoveChildren( currentBlock, previous ) ; + // But for some block types (e.g. table), moving the children to the previous block makes no sense. + // So a check is needed. (See #1081) + if ( ! currentBlock.tagName.IEquals( [ 'TABLE' ] ) ) + FCKDomTools.MoveChildren( currentBlock, previous ) ; // Place the selection at the bookmark. - range.MoveToBookmark( oBookmark ) ; - range.Select() ; + range.SelectBookmark( oBookmark ) ; bCustom = true ; } @@ -251,6 +309,10 @@ */ FCKEnterKey.prototype.DoDelete = function() { + // Save an undo snapshot before doing anything + // This is to conform with the behavior seen in MS Word + FCKUndo.SaveUndoStep() ; + // The has the same effect as the , so we have the same // results if we just move to the next block and apply the same logic. @@ -260,13 +322,31 @@ var oRange = new FCKDomRange( this.Window ) ; oRange.MoveToSelection() ; + // Kludge for #247 + if ( FCKBrowserInfo.IsIE && this._CheckIsAllContentsIncluded( oRange, this.Window.document.body ) ) + { + this._FixIESelectAllBug( oRange ) ; + return true ; + } + // There is just one special case for collapsed selections at the end of a block. - if ( oRange.CheckIsCollapsed() && oRange.CheckEndOfBlock( FCKBrowserInfo.IsGecko ) ) + if ( oRange.CheckIsCollapsed() && oRange.CheckEndOfBlock( FCKBrowserInfo.IsGeckoLike ) ) { var oCurrentBlock = oRange.StartBlock ; + var eCurrentCell = FCKTools.GetElementAscensor( oCurrentBlock, 'td' ); - var eNext = FCKDomTools.GetNextSourceElement( oCurrentBlock, true, [ oRange.StartBlockLimit.nodeName ], ['UL','OL'] ) ; + var eNext = FCKDomTools.GetNextSourceElement( oCurrentBlock, true, [ oRange.StartBlockLimit.nodeName ], + ['UL','OL','TR'], true ) ; + // Bug #1323 : if we're in a table cell, and the next node belongs to a different cell, then don't + // delete anything. + if ( eCurrentCell ) + { + var eNextCell = FCKTools.GetElementAscensor( eNext, 'td' ); + if ( eNextCell != eCurrentCell ) + return true ; + } + bCustom = this._ExecuteBackspace( oRange, oCurrentBlock, eNext ) ; } @@ -274,145 +354,161 @@ return bCustom ; } +/* + * Executes the key behavior. + */ +FCKEnterKey.prototype.DoTab = function() +{ + var oRange = new FCKDomRange( this.Window ); + oRange.MoveToSelection() ; + + // If the user pressed inside a table, we should give him the default behavior ( moving between cells ) + // instead of giving him more non-breaking spaces. (Bug #973) + var node = oRange._Range.startContainer ; + while ( node ) + { + if ( node.nodeType == 1 ) + { + var tagName = node.tagName.toLowerCase() ; + if ( tagName == "tr" || tagName == "td" || tagName == "th" || tagName == "tbody" || tagName == "table" ) + return false ; + else + break ; + } + node = node.parentNode ; + } + + if ( this.TabText ) + { + oRange.DeleteContents() ; + oRange.InsertNode( this.Window.document.createTextNode( this.TabText ) ) ; + oRange.Collapse( false ) ; + oRange.Select() ; + } + return true ; +} + FCKEnterKey.prototype._ExecuteEnterBlock = function( blockTag, range ) { // Get the current selection. var oRange = range || new FCKDomRange( this.Window ) ; - // If we don't have a range, move it to the selection. - if ( !range ) - oRange.MoveToSelection() ; + var oSplitInfo = oRange.SplitBlock( blockTag ) ; - // The selection boundaries must be in the same "block limit" element. - if ( oRange.StartBlockLimit == oRange.EndBlockLimit ) + if ( oSplitInfo ) { - // If the StartBlock or EndBlock are not available (for text without a - // block tag), we must fix them, by moving the text to a block. - if ( !oRange.StartBlock ) - this._FixBlock( oRange, true, blockTag ) ; - - if ( !oRange.EndBlock ) - this._FixBlock( oRange, false, blockTag ) ; - // Get the current blocks. - var eStartBlock = oRange.StartBlock ; - var eEndBlock = oRange.EndBlock ; + var ePreviousBlock = oSplitInfo.PreviousBlock ; + var eNextBlock = oSplitInfo.NextBlock ; - // Delete the current selection. - if ( !oRange.CheckIsEmpty() ) - oRange.DeleteContents() ; + var bIsStartOfBlock = oSplitInfo.WasStartOfBlock ; + var bIsEndOfBlock = oSplitInfo.WasEndOfBlock ; - // If the selection boundaries are in the same block element - if ( eStartBlock == eEndBlock ) + // If there is one block under a list item, modify the split so that the list item gets split as well. (Bug #1647) + if ( eNextBlock ) { - var eNewBlock ; + if ( eNextBlock.parentNode.nodeName.IEquals( 'li' ) ) + { + FCKDomTools.BreakParent( eNextBlock, eNextBlock.parentNode ) ; + FCKDomTools.MoveNode( eNextBlock, eNextBlock.nextSibling, true ) ; + } + } + else if ( ePreviousBlock && ePreviousBlock.parentNode.nodeName.IEquals( 'li' ) ) + { + FCKDomTools.BreakParent( ePreviousBlock, ePreviousBlock.parentNode ) ; + oRange.MoveToElementEditStart( ePreviousBlock.nextSibling ); + FCKDomTools.MoveNode( ePreviousBlock, ePreviousBlock.previousSibling ) ; + } - var bIsStartOfBlock = oRange.CheckStartOfBlock() ; - var bIsEndOfBlock = oRange.CheckEndOfBlock() ; - - if ( bIsStartOfBlock && !bIsEndOfBlock ) + // If we have both the previous and next blocks, it means that the + // boundaries were on separated blocks, or none of them where on the + // block limits (start/end). + if ( !bIsStartOfBlock && !bIsEndOfBlock ) + { + // If the next block is an
    4. with another list tree as the first child + // We'll need to append a placeholder or the list item wouldn't be editable. (Bug #1420) + if ( eNextBlock.nodeName.IEquals( 'li' ) && eNextBlock.firstChild + && eNextBlock.firstChild.nodeName.IEquals( ['ul', 'ol'] ) ) + eNextBlock.insertBefore( FCKTools.GetElementDocument( eNextBlock ).createTextNode( '\xa0' ), eNextBlock.firstChild ) ; + // Move the selection to the end block. + if ( eNextBlock ) + oRange.MoveToElementEditStart( eNextBlock ) ; + } + else + { + if ( bIsStartOfBlock && bIsEndOfBlock && ePreviousBlock.tagName.toUpperCase() == 'LI' ) { - eNewBlock = eStartBlock.cloneNode(false) ; + oRange.MoveToElementStart( ePreviousBlock ) ; + this._OutdentWithSelection( ePreviousBlock, oRange ) ; + oRange.Release() ; + return true ; + } - if ( FCKBrowserInfo.IsGeckoLike ) - eNewBlock.innerHTML = GECKO_BOGUS ; + var eNewBlock ; - // Place the new block before the current block element. - eStartBlock.parentNode.insertBefore( eNewBlock, eStartBlock ) ; + if ( ePreviousBlock ) + { + var sPreviousBlockTag = ePreviousBlock.tagName.toUpperCase() ; - // This is tricky, but to make the new block visible correctly - // we must select it. - if ( FCKBrowserInfo.IsIE ) + // If is a header tag, or we are in a Shift+Enter (#77), + // create a new block element (later in the code). + if ( !this._HasShift && !(/^H[1-6]$/).test( sPreviousBlockTag ) ) { - // Move the selection to the new block. - oRange.MoveToNodeContents( eNewBlock ) ; - - oRange.Select() ; + // Otherwise, duplicate the previous block. + eNewBlock = FCKDomTools.CloneElement( ePreviousBlock ) ; } - - // Move the selection to the new block. - oRange.MoveToElementEditStart( eStartBlock ) ; } - else - { - // Check if the selection is at the end of the block. - if ( bIsEndOfBlock ) - { - var sStartBlockTag = eStartBlock.tagName.toUpperCase() ; + else if ( eNextBlock ) + eNewBlock = FCKDomTools.CloneElement( eNextBlock ) ; - // If the entire block is selected, and we are in a LI, let's decrease its indentation. - if ( bIsStartOfBlock && sStartBlockTag == 'LI' ) - { - this._OutdentWithSelection( eStartBlock, oRange ) ; - oRange.Release() ; - return true ; - } - else - { - // If is a header tag, or we are in a Shift+Enter (#77), - // create a new block element. - if ( (/^H[1-6]$/).test( sStartBlockTag ) || this._HasShift ) - eNewBlock = this.Window.document.createElement( blockTag ) ; - // Otherwise, duplicate the current block. - else - { - eNewBlock = eStartBlock.cloneNode(false) ; - this._RecreateEndingTree( eStartBlock, eNewBlock ) ; - } + if ( !eNewBlock ) + eNewBlock = this.Window.document.createElement( blockTag ) ; - if ( FCKBrowserInfo.IsGeckoLike ) - { - eNewBlock.innerHTML = GECKO_BOGUS ; - - // If the entire block is selected, let's add a bogus in the start block. - if ( bIsStartOfBlock ) - eStartBlock.innerHTML = GECKO_BOGUS ; - } - } - } - else + // Recreate the inline elements tree, which was available + // before the hitting enter, so the same styles will be + // available in the new block. + var elementPath = oSplitInfo.ElementPath ; + if ( elementPath ) + { + for ( var i = 0, len = elementPath.Elements.length ; i < len ; i++ ) { - // Extract the contents of the block from the selection point to the end of its contents. - oRange.SetEnd( eStartBlock, 2 ) ; - var eDocFrag = oRange.ExtractContents() ; + var element = elementPath.Elements[i] ; - // Duplicate the block element after it. - eNewBlock = eStartBlock.cloneNode(false) ; + if ( element == elementPath.Block || element == elementPath.BlockLimit ) + break ; - // It could be that we are in a LI with a child UL/OL. Insert a bogus to give us space to type. - FCKDomTools.TrimNode( eDocFrag.RootNode ) ; - if ( eDocFrag.RootNode.firstChild.nodeType == 1 && eDocFrag.RootNode.firstChild.tagName.toUpperCase().Equals( 'UL', 'OL' ) ) - eNewBlock.innerHTML = GECKO_BOGUS ; - - // Place the extracted contents in the duplicated block. - eDocFrag.AppendTo( eNewBlock ) ; - - if ( FCKBrowserInfo.IsGecko ) + if ( FCKListsLib.InlineChildReqElements[ element.nodeName.toLowerCase() ] ) { - // In Gecko, the last child node must be a bogus
      . - this._AppendBogusBr( eStartBlock ) ; - this._AppendBogusBr( eNewBlock ) ; + element = FCKDomTools.CloneElement( element ) ; + FCKDomTools.MoveChildren( eNewBlock, element ) ; + eNewBlock.appendChild( element ) ; } } + } - if ( eNewBlock ) - { - FCKDomTools.InsertAfterNode( eStartBlock, eNewBlock ) ; + if ( FCKBrowserInfo.IsGeckoLike ) + FCKTools.AppendBogusBr( eNewBlock ) ; - // Move the selection to the new block. - oRange.MoveToElementEditStart( eNewBlock ) ; + oRange.InsertNode( eNewBlock ) ; - if ( FCKBrowserInfo.IsGecko ) - eNewBlock.scrollIntoView( false ) ; - } + // This is tricky, but to make the new block visible correctly + // we must select it. + if ( FCKBrowserInfo.IsIE ) + { + // Move the selection to the new block. + oRange.MoveToElementEditStart( eNewBlock ) ; + oRange.Select() ; } + + // Move the selection to the new block. + oRange.MoveToElementEditStart( bIsStartOfBlock && !bIsEndOfBlock ? eNextBlock : eNewBlock ) ; } - else - { - // Move the selection to the end block. - oRange.MoveToElementEditStart( eEndBlock ) ; - } + if ( FCKBrowserInfo.IsSafari ) + FCKDomTools.ScrollIntoView( eNextBlock || eNewBlock, false ) ; + else if ( FCKBrowserInfo.IsGeckoLike ) + ( eNextBlock || eNewBlock ).scrollIntoView( false ) ; + oRange.Select() ; } @@ -442,6 +538,7 @@ var sStartBlockTag = oRange.StartBlock ? oRange.StartBlock.tagName.toUpperCase() : '' ; var bHasShift = this._HasShift ; + var bIsPre = false ; if ( !bHasShift && sStartBlockTag == 'LI' ) return this._ExecuteEnterBlock( null, oRange ) ; @@ -449,8 +546,6 @@ // If we are at the end of a header block. if ( !bHasShift && bIsEndOfBlock && (/^H[1-6]$/).test( sStartBlockTag ) ) { - FCKDebug.Output( 'BR - Header' ) ; - // Insert a BR after the current paragraph. FCKDomTools.InsertAfterNode( oRange.StartBlock, this.Window.document.createElement( 'br' ) ) ; @@ -463,31 +558,51 @@ } else { - FCKDebug.Output( 'BR - No Header' ) ; + var eLineBreak ; + bIsPre = sStartBlockTag.IEquals( 'pre' ) ; + if ( bIsPre ) + eLineBreak = this.Window.document.createTextNode( FCKBrowserInfo.IsIE ? '\r' : '\n' ) ; + else + eLineBreak = this.Window.document.createElement( 'br' ) ; - var eBr = this.Window.document.createElement( 'br' ) ; + oRange.InsertNode( eLineBreak ) ; - oRange.InsertNode( eBr ) ; - // The space is required by Gecko only to make the cursor blink. if ( FCKBrowserInfo.IsGecko ) - FCKDomTools.InsertAfterNode( eBr, this.Window.document.createTextNode( '' ) ) ; + FCKDomTools.InsertAfterNode( eLineBreak, this.Window.document.createTextNode( '' ) ) ; // If we are at the end of a block, we must be sure the bogus node is available in that block. - if ( bIsEndOfBlock && FCKBrowserInfo.IsGecko ) - this._AppendBogusBr( eBr.parentNode ) ; + if ( bIsEndOfBlock && FCKBrowserInfo.IsGeckoLike ) + FCKTools.AppendBogusBr( eLineBreak.parentNode ) ; if ( FCKBrowserInfo.IsIE ) - oRange.SetStart( eBr, 4 ) ; + oRange.SetStart( eLineBreak, 4 ) ; else - oRange.SetStart( eBr.nextSibling, 1 ) ; + oRange.SetStart( eLineBreak.nextSibling, 1 ) ; + if ( ! FCKBrowserInfo.IsIE ) + { + var dummy = null ; + if ( FCKBrowserInfo.IsOpera ) + dummy = this.Window.document.createElement( 'span' ) ; + else + dummy = this.Window.document.createElement( 'br' ) ; + + eLineBreak.parentNode.insertBefore( dummy, eLineBreak.nextSibling ) ; + + if ( FCKBrowserInfo.IsSafari ) + FCKDomTools.ScrollIntoView( dummy, false ) ; + else + dummy.scrollIntoView( false ) ; + + dummy.parentNode.removeChild( dummy ) ; + } } // This collapse guarantees the cursor will be blinking. oRange.Collapse( true ) ; - oRange.Select() ; + oRange.Select( bIsPre ) ; } // Release the resources used by the range. @@ -496,61 +611,57 @@ return true ; } -// Transform a block without a block tag in a valid block (orphan text in the body or td, usually). -FCKEnterKey.prototype._FixBlock = function( range, isStart, blockTag ) +// Outdents a LI, maintaining the selection defined on a range. +FCKEnterKey.prototype._OutdentWithSelection = function( li, range ) { - // Bookmark the range so we can restore it later. var oBookmark = range.CreateBookmark() ; - // Collapse the range to the requested ending boundary. - range.Collapse( isStart ) ; + FCKListHandler.OutdentListItem( li ) ; - // Expands it to the block contents. - range.Expand( 'block_contents' ) ; - - // Create the fixed block. - var oFixedBlock = this.Window.document.createElement( blockTag ) ; - - // Move the contents of the temporary range to the fixed block. - range.ExtractContents().AppendTo( oFixedBlock ) ; - FCKDomTools.TrimNode( oFixedBlock ) ; - - // Insert the fixed block into the DOM. - range.InsertNode( oFixedBlock ) ; - - // Move the range back to the bookmarked place. range.MoveToBookmark( oBookmark ) ; + range.Select() ; } -// Appends a bogus
      at the end of the element, if not yet available. -FCKEnterKey.prototype._AppendBogusBr = function( element ) +// Is all the contents under a node included by a range? +FCKEnterKey.prototype._CheckIsAllContentsIncluded = function( range, node ) { - var eLastChild = element.getElementsByTagName('br') ; + var startOk = false ; + var endOk = false ; - if ( eLastChild ) - eLastChild = eLastChild[ eLastChild.legth - 1 ] ; + /* + FCKDebug.Output( 'sc='+range.StartContainer.nodeName+ + ',so='+range._Range.startOffset+ + ',ec='+range.EndContainer.nodeName+ + ',eo='+range._Range.endOffset ) ; + */ + if ( range.StartContainer == node || range.StartContainer == node.firstChild ) + startOk = ( range._Range.startOffset == 0 ) ; - if ( !eLastChild || eLastChild.getAttribute( 'type', 2 ) != '_moz' ) - element.appendChild( FCKTools.CreateBogusBR( this.Window.document ) ) ; -} + if ( range.EndContainer == node || range.EndContainer == node.lastChild ) + { + var nodeLength = range.EndContainer.nodeType == 3 ? range.EndContainer.length : range.EndContainer.childNodes.length ; + endOk = ( range._Range.endOffset == nodeLength ) ; + } -// Recreate the elements tree at the end of the source block, at the beginning -// of the target block. Eg.: -// If source =

      Some sample text

      then target =

      -// If source =

      Some sample text

      then target =

      -FCKEnterKey.prototype._RecreateEndingTree = function( source, target ) -{ - while ( ( source = source.lastChild ) && source.nodeType == 1 && FCKListsLib.InlineChildReqElements[ source.nodeName.toLowerCase() ] != null ) - target = target.insertBefore( source.cloneNode( false ), target.firstChild ) ; + return startOk && endOk ; } -// Outdents a LI, maintaining the seletion defined on a range. -FCKEnterKey.prototype._OutdentWithSelection = function( li, range ) +// Kludge for #247 +FCKEnterKey.prototype._FixIESelectAllBug = function( range ) { - var oBookmark = range.CreateBookmark() ; + var doc = this.Window.document ; + doc.body.innerHTML = '' ; + var editBlock ; + if ( FCKConfig.EnterMode.IEquals( ['div', 'p'] ) ) + { + editBlock = doc.createElement( FCKConfig.EnterMode ) ; + doc.body.appendChild( editBlock ) ; + } + else + editBlock = doc.body ; - FCKListHandler.OutdentListItem( li ) ; - - range.MoveToBookmark( oBookmark ) ; + range.MoveToNodeContents( editBlock ) ; + range.Collapse( true ) ; range.Select() ; -} \ No newline at end of file + range.Release() ; +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckevents.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckevents.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckevents.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -34,7 +34,12 @@ if ( !( aTargets = this._RegisteredEvents[ eventName ] ) ) this._RegisteredEvents[ eventName ] = [ functionPointer ] ; else - aTargets.push( functionPointer ) ; + { + // Check that the event handler isn't already registered with the same listener + // It doesn't detect function pointers belonging to an object (at least in Gecko) + if ( aTargets.IndexOf( functionPointer ) == -1 ) + aTargets.push( functionPointer ) ; + } } FCKEvents.prototype.FireEvent = function( eventName, params ) @@ -46,7 +51,20 @@ if ( oCalls ) { for ( var i = 0 ; i < oCalls.length ; i++ ) - bReturnValue = ( oCalls[ i ]( this.Owner, params ) && bReturnValue ) ; + { + try + { + bReturnValue = ( oCalls[ i ]( this.Owner, params ) && bReturnValue ) ; + } + catch(e) + { + // Ignore the following error. It may happen if pointing to a + // script not anymore available (#934): + // -2146823277 = Can't execute code from a freed script + if ( e.number != -2146823277 ) + throw e ; + } + } } return bReturnValue ; Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckhtmliterator.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckhtmliterator.js (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckhtmliterator.js 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,142 @@ +?/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * This class can be used to interate through nodes inside a range. + * + * During interation, the provided range can become invalid, due to document + * mutations, so CreateBookmark() used to restore it after processing, if + * needed. + */ + +var FCKHtmlIterator = function( source ) +{ + this._sourceHtml = source ; +} +FCKHtmlIterator.prototype = +{ + Next : function() + { + var sourceHtml = this._sourceHtml ; + if ( sourceHtml == null ) + return null ; + + var match = FCKRegexLib.HtmlTag.exec( sourceHtml ) ; + var isTag = false ; + var value = "" ; + if ( match ) + { + if ( match.index > 0 ) + { + value = sourceHtml.substr( 0, match.index ) ; + this._sourceHtml = sourceHtml.substr( match.index ) ; + } + else + { + isTag = true ; + value = match[0] ; + this._sourceHtml = sourceHtml.substr( match[0].length ) ; + } + } + else + { + value = sourceHtml ; + this._sourceHtml = null ; + } + return { 'isTag' : isTag, 'value' : value } ; + }, + + Each : function( func ) + { + var chunk ; + while ( ( chunk = this.Next() ) ) + func( chunk.isTag, chunk.value ) ; + } +} ; +/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * This class can be used to interate through nodes inside a range. + * + * During interation, the provided range can become invalid, due to document + * mutations, so CreateBookmark() used to restore it after processing, if + * needed. + */ + +var FCKHtmlIterator = function( source ) +{ + this._sourceHtml = source ; +} +FCKHtmlIterator.prototype = +{ + Next : function() + { + var sourceHtml = this._sourceHtml ; + if ( sourceHtml == null ) + return null ; + + var match = FCKRegexLib.HtmlTag.exec( sourceHtml ) ; + var isTag = false ; + var value = "" ; + if ( match ) + { + if ( match.index > 0 ) + { + value = sourceHtml.substr( 0, match.index ) ; + this._sourceHtml = sourceHtml.substr( match.index ) ; + } + else + { + isTag = true ; + value = match[0] ; + this._sourceHtml = sourceHtml.substr( match[0].length ) ; + } + } + else + { + value = sourceHtml ; + this._sourceHtml = null ; + } + return { 'isTag' : isTag, 'value' : value } ; + }, + + Each : function( func ) + { + var chunk ; + while ( ( chunk = this.Next() ) ) + func( chunk.isTag, chunk.value ) ; + } +} ; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckicon.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckicon.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckicon.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -74,25 +74,30 @@ eIcon = document.createElement( 'IMG' ) ; eIcon.src = FCK_SPACER_PATH ; eIcon.style.backgroundPosition = '0px ' + sPos ; - eIcon.style.backgroundImage = 'url(' + this.Path + ')' ; + eIcon.style.backgroundImage = 'url("' + this.Path + '")' ; } } else // It is using a single icon image. { - // This is not working well with IE. See notes bellow. - // -// eIcon = document.createElement( 'IMG' ) ; -// eIcon.src = this.Path ? this.Path : FCK_SPACER_PATH ; + if ( FCKBrowserInfo.IsIE ) + { + // IE makes the button 1px higher if using the directly, so we + // are changing to the
      system to clip the image correctly. + eIcon = document.createElement( 'DIV' ) ; - // IE makes the button 1px higher if using the directly, so we - // are changing to the
      system to clip the image correctly. - eIcon = document.createElement( 'DIV' ) ; - - eIconImage = eIcon.appendChild( document.createElement( 'IMG' ) ) ; - eIconImage.src = this.Path ? this.Path : FCK_SPACER_PATH ; + eIconImage = eIcon.appendChild( document.createElement( 'IMG' ) ) ; + eIconImage.src = this.Path ? this.Path : FCK_SPACER_PATH ; + } + else + { + // This is not working well with IE. See notes above. + // + eIcon = document.createElement( 'IMG' ) ; + eIcon.src = this.Path ? this.Path : FCK_SPACER_PATH ; + } } eIcon.className = 'TB_Button_Image' ; return eIcon ; -} \ No newline at end of file +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckiecleanup.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckiecleanup.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckiecleanup.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -23,7 +23,7 @@ var FCKIECleanup = function( attachWindow ) { - // If the attachWindow already have a cleanup object, jusgt use that one. + // If the attachWindow already have a cleanup object, just use that one. if ( attachWindow._FCKCleanupObj ) this.Items = attachWindow._FCKCleanupObj.Items ; else @@ -43,7 +43,7 @@ function FCKIECleanup_Cleanup() { - if ( !this._FCKCleanupObj ) + if ( !this._FCKCleanupObj || !window.FCKUnloadFlag ) return ; var aItems = this._FCKCleanupObj.Items ; @@ -65,4 +65,4 @@ if ( CollectGarbage ) CollectGarbage() ; -} \ No newline at end of file +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckimagepreloader.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckimagepreloader.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckimagepreloader.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -44,8 +44,8 @@ for ( var i = 0 ; i < aImages.length ; i++ ) { var eImg = document.createElement( 'img' ) ; - eImg.onload = eImg.onerror = _FCKImagePreloader_OnImage ; - eImg._FCKImagePreloader = this ; + FCKTools.AddEventListenerEx( eImg, 'load', _FCKImagePreloader_OnImage, this ) ; + FCKTools.AddEventListenerEx( eImg, 'error', _FCKImagePreloader_OnImage, this ) ; eImg.src = aImages[i] ; _FCKImagePreloader_ImageCache.push( eImg ) ; @@ -57,12 +57,8 @@ // magic will not happen. var _FCKImagePreloader_ImageCache = new Array() ; -function _FCKImagePreloader_OnImage() +function _FCKImagePreloader_OnImage( ev, imagePreloader ) { - var oImagePreloader = this._FCKImagePreloader ; - - if ( (--oImagePreloader._PreloadCount) == 0 && oImagePreloader.OnComplete ) - oImagePreloader.OnComplete() ; - - this._FCKImagePreloader = null ; -} \ No newline at end of file + if ( (--imagePreloader._PreloadCount) == 0 && imagePreloader.OnComplete ) + imagePreloader.OnComplete() ; +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckkeystrokehandler.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckkeystrokehandler.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckkeystrokehandler.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -54,11 +54,16 @@ { var keyDef = arguments[i] ; + // If the configuration for the keystrokes is missing some element or has any extra comma + // this item won't be valid, so skip it and keep on processing. + if ( !keyDef ) + continue ; + if ( typeof( keyDef[0] ) == 'object' ) // It is an array with arrays defining the keystrokes. this.SetKeystrokes.apply( this, keyDef ) ; else { - if ( keyDef.length == 1 ) // If it has only one element, removed the keystroke. + if ( keyDef.length == 1 ) // If it has only one element, remove the keystroke. delete this.Keystrokes[ keyDef[0] ] ; else // Otherwise add it. this.Keystrokes[ keyDef[0] ] = keyDef[1] === true ? true : keyDef ; @@ -95,7 +100,7 @@ // If the keystroke is defined if ( keystrokeValue ) { - // If the keystroke has been explicetly set to "true" OR calling the + // If the keystroke has been explicitly set to "true" OR calling the // "OnKeystroke" event, it doesn't return "true", the default behavior // must be preserved. if ( keystrokeValue === true || !( keystrokeHandler.OnKeystroke && keystrokeHandler.OnKeystroke.apply( keystrokeHandler, keystrokeValue ) ) ) @@ -133,4 +138,4 @@ } return true ; -} \ No newline at end of file +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckmenublock.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckmenublock.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckmenublock.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -32,9 +32,9 @@ return this._Items.length ; } -FCKMenuBlock.prototype.AddItem = function( name, label, iconPathOrStripInfoArrayOrIndex, isDisabled ) +FCKMenuBlock.prototype.AddItem = function( name, label, iconPathOrStripInfoArrayOrIndex, isDisabled, customData ) { - var oItem = new FCKMenuItem( this, name, label, iconPathOrStripInfoArrayOrIndex, isDisabled ) ; + var oItem = new FCKMenuItem( this, name, label, iconPathOrStripInfoArrayOrIndex, isDisabled, customData ) ; oItem.OnClick = FCKTools.CreateEventListener( FCKMenuBlock_Item_OnClick, this ) ; oItem.OnActivate = FCKTools.CreateEventListener( FCKMenuBlock_Item_OnActivate, this ) ; @@ -94,6 +94,9 @@ function FCKMenuBlock_Item_OnClick( clickedItem, menuBlock ) { + if ( menuBlock.Hide ) + menuBlock.Hide() ; + FCKTools.RunFunction( menuBlock.OnClick, menuBlock, [ clickedItem ] ) ; } @@ -105,8 +108,15 @@ { // Set the focus to this menu block window (to fire OnBlur on opened panels). if ( !FCKBrowserInfo.IsIE && oActiveItem.HasSubMenu && !this.HasSubMenu ) + { menuBlock._Window.focus() ; + // Due to the event model provided by Opera, we need to set + // HasFocus here as the above focus() call will not fire the focus + // event in the panel immediately (#1200). + menuBlock.Panel.HasFocus = true ; + } + oActiveItem.Deactivate() ; } @@ -140,4 +150,4 @@ eCell = r.insertCell(-1) ; eCell.className = 'MN_Separator' ; eCell.appendChild( oDoc.createElement( 'DIV' ) ).className = 'MN_Separator_Line' ; -} \ No newline at end of file +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckmenublockpanel.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckmenublockpanel.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckmenublockpanel.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -35,7 +35,7 @@ FCKMenuBlockPanel.prototype.Create = function() { var oPanel = this.Panel = ( this.Parent && this.Parent.Panel ? this.Parent.Panel.CreateChildPanel() : new FCKPanel() ) ; - oPanel.AppendStyleSheet( FCKConfig.SkinPath + 'fck_editor.css' ) ; + oPanel.AppendStyleSheet( FCKConfig.SkinEditorCSS ) ; // Call the "base" implementation. FCKMenuBlock.prototype.Create.call( this, oPanel.MainNode ) ; @@ -51,4 +51,4 @@ { if ( this.Panel.CheckIsOpened() ) this.Panel.Hide() ; -} \ No newline at end of file +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckmenuitem.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckmenuitem.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckmenuitem.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -21,7 +21,7 @@ * Defines and renders a menu items in a menu block. */ -var FCKMenuItem = function( parentMenuBlock, name, label, iconPathOrStripInfoArray, isDisabled ) +var FCKMenuItem = function( parentMenuBlock, name, label, iconPathOrStripInfoArray, isDisabled, customData ) { this.Name = name ; this.Label = label || name ; @@ -32,16 +32,17 @@ this.SubMenu = new FCKMenuBlockPanel() ; this.SubMenu.Parent = parentMenuBlock ; this.SubMenu.OnClick = FCKTools.CreateEventListener( FCKMenuItem_SubMenu_OnClick, this ) ; + this.CustomData = customData ; if ( FCK.IECleanup ) FCK.IECleanup.AddItem( this, FCKMenuItem_Cleanup ) ; } -FCKMenuItem.prototype.AddItem = function( name, label, iconPathOrStripInfoArrayOrIndex, isDisabled ) +FCKMenuItem.prototype.AddItem = function( name, label, iconPathOrStripInfoArrayOrIndex, isDisabled, customData ) { this.HasSubMenu = true ; - return this.SubMenu.AddItem( name, label, iconPathOrStripInfoArrayOrIndex, isDisabled ) ; + return this.SubMenu.AddItem( name, label, iconPathOrStripInfoArrayOrIndex, isDisabled, customData ) ; } FCKMenuItem.prototype.AddSeparator = function() @@ -157,4 +158,4 @@ function FCKMenuItem_Cleanup() { this.MainElement = null ; -} \ No newline at end of file +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckpanel.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckpanel.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckpanel.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -35,9 +35,32 @@ if ( FCKBrowserInfo.IsIE ) { // Create the Popup that will hold the panel. + // The popup has to be created before playing with domain hacks, see #1666. this._Popup = this._Window.createPopup() ; + + // this._Window cannot be accessed while playing with domain hacks, but local variable is ok. + // See #1666. + var pDoc = this._Window.document ; + + // This is a trick to IE6 (not IE7). The original domain must be set + // before creating the popup, so we are able to take a refence to the + // document inside of it, and the set the proper domain for it. (#123) + if ( FCK_IS_CUSTOM_DOMAIN && !FCKBrowserInfo.IsIE7 ) + { + pDoc.domain = FCK_ORIGINAL_DOMAIN ; + document.domain = FCK_ORIGINAL_DOMAIN ; + } + oDocument = this.Document = this._Popup.document ; + // Set the proper domain inside the popup. + if ( FCK_IS_CUSTOM_DOMAIN ) + { + oDocument.domain = FCK_RUNTIME_DOMAIN ; + pDoc.domain = FCK_RUNTIME_DOMAIN ; + document.domain = FCK_RUNTIME_DOMAIN ; + } + FCK.IECleanup.AddItem( this, FCKPanel_Cleanup ) ; } else @@ -47,37 +70,45 @@ oIFrame.allowTransparency = true ; oIFrame.frameBorder = '0' ; oIFrame.scrolling = 'no' ; - oIFrame.style.position = 'absolute'; - oIFrame.style.zIndex = FCKConfig.FloatingPanelsZIndex ; oIFrame.width = oIFrame.height = 0 ; + FCKDomTools.SetElementStyles( oIFrame, + { + position : 'absolute', + zIndex : FCKConfig.FloatingPanelsZIndex + } ) ; - if ( this._Window == window.parent && window.frameElement ) - window.frameElement.parentNode.insertBefore( oIFrame, window.frameElement ) ; - else - this._Window.document.body.appendChild( oIFrame ) ; + this._Window.document.body.appendChild( oIFrame ) ; var oIFrameWindow = oIFrame.contentWindow ; oDocument = this.Document = oIFrameWindow.document ; + // Workaround for Safari 12256. Ticket #63 + var sBase = '' ; + if ( FCKBrowserInfo.IsSafari ) + sBase = '' ; + // Initialize the IFRAME document body. oDocument.open() ; - oDocument.write( '<\/body><\/html>' ) ; + oDocument.write( '' + sBase + '<\/head><\/body><\/html>' ) ; oDocument.close() ; + if( FCKBrowserInfo.IsAIR ) + FCKAdobeAIR.Panel_Contructor( oDocument, window.document.location ) ; + FCKTools.AddEventListenerEx( oIFrameWindow, 'focus', FCKPanel_Window_OnFocus, this ) ; FCKTools.AddEventListenerEx( oIFrameWindow, 'blur', FCKPanel_Window_OnBlur, this ) ; } oDocument.dir = FCKLang.Dir ; - oDocument.oncontextmenu = FCKTools.CancelEvent ; + FCKTools.AddEventListener( oDocument, 'contextmenu', FCKTools.CancelEvent ) ; // Create the main DIV that is used as the panel base. this.MainNode = oDocument.body.appendChild( oDocument.createElement('DIV') ) ; - // The "float" property must be set so Firefox calculates the size correcly. + // The "float" property must be set so Firefox calculates the size correctly. this.MainNode.style.cssFloat = this.IsRTL ? 'right' : 'left' ; } @@ -99,6 +130,7 @@ FCKPanel.prototype.Show = function( x, y, relElement, width, height ) { var iMainWidth ; + var eMainNode = this.MainNode ; if ( this._Popup ) { @@ -109,10 +141,13 @@ // The following lines must be place after the above "show", otherwise it // doesn't has the desired effect. - this.MainNode.style.width = width ? width + 'px' : '' ; - this.MainNode.style.height = height ? height + 'px' : '' ; + FCKDomTools.SetElementStyles( eMainNode, + { + width : width ? width + 'px' : '', + height : height ? height + 'px' : '' + } ) ; - iMainWidth = this.MainNode.offsetWidth ; + iMainWidth = eMainNode.offsetWidth ; if ( this.IsRTL ) { @@ -123,7 +158,7 @@ } // Second call: Show the Popup at the specified location, with the correct size. - this._Popup.show( x, y, iMainWidth, this.MainNode.offsetHeight, relElement ) ; + this._Popup.show( x, y, iMainWidth, eMainNode.offsetHeight, relElement ) ; if ( this.OnHide ) { @@ -136,17 +171,41 @@ else { // Do not fire OnBlur while the panel is opened. - if ( typeof( FCKFocusManager ) != 'undefined' ) - FCKFocusManager.Lock() ; + if ( typeof( FCK.ToolbarSet.CurrentInstance.FocusManager ) != 'undefined' ) + FCK.ToolbarSet.CurrentInstance.FocusManager.Lock() ; if ( this.ParentPanel ) + { this.ParentPanel.Lock() ; - this.MainNode.style.width = width ? width + 'px' : '' ; - this.MainNode.style.height = height ? height + 'px' : '' ; + // Due to a bug on FF3, we must ensure that the parent panel will + // blur (#1584). + FCKPanel_Window_OnBlur( null, this.ParentPanel ) ; + } - iMainWidth = this.MainNode.offsetWidth ; + // Toggle the iframe scrolling attribute to prevent the panel + // scrollbars from disappearing in FF Mac. (#191) + if ( FCKBrowserInfo.IsGecko && FCKBrowserInfo.IsMac ) + { + this._IFrame.scrolling = '' ; + FCKTools.RunFunction( function(){ this._IFrame.scrolling = 'no'; }, this ) ; + } + // Be sure we'll not have more than one Panel opened at the same time. + // Do not unlock focus manager here because we're displaying another floating panel + // instead of returning the editor to a "no panel" state (Bug #1514). + if ( FCK.ToolbarSet.CurrentInstance.GetInstanceObject( 'FCKPanel' )._OpenedPanel && + FCK.ToolbarSet.CurrentInstance.GetInstanceObject( 'FCKPanel' )._OpenedPanel != this ) + FCK.ToolbarSet.CurrentInstance.GetInstanceObject( 'FCKPanel' )._OpenedPanel.Hide( false, true ) ; + + FCKDomTools.SetElementStyles( eMainNode, + { + width : width ? width + 'px' : '', + height : height ? height + 'px' : '' + } ) ; + + iMainWidth = eMainNode.offsetWidth ; + if ( !width ) this._IFrame.width = 1 ; if ( !height ) this._IFrame.height = 1 ; @@ -154,19 +213,31 @@ // setting the _IFrame size (which returns "0"), and then after that, // to return the correct width. Remove the first step and it will not // work when the editor is in RTL. - iMainWidth = this.MainNode.offsetWidth ; + // + // The "|| eMainNode.firstChild.offsetWidth" part has been added + // for Opera compatibility (see #570). + iMainWidth = eMainNode.offsetWidth || eMainNode.firstChild.offsetWidth ; - var oPos = FCKTools.GetElementPosition( + // Base the popup coordinates upon the coordinates of relElement. + var oPos = FCKTools.GetDocumentPosition( this._Window, relElement.nodeType == 9 ? ( FCKTools.IsStrictMode( relElement ) ? relElement.documentElement : relElement.body ) : - relElement, - this._Window ) ; + relElement ) ; + // Minus the offsets provided by any positioned parent element of the panel iframe. + var positionedAncestor = FCKDomTools.GetPositionedAncestor( this._IFrame.parentNode ) ; + if ( positionedAncestor ) + { + var nPos = FCKTools.GetDocumentPosition( FCKTools.GetElementWindow( positionedAncestor ), positionedAncestor ) ; + oPos.x -= nPos.x ; + oPos.y -= nPos.y ; + } + if ( this.IsRTL && !this.IsContextMenu ) x = ( x * -1 ) ; - x += oPos.X ; - y += oPos.Y ; + x += oPos.x ; + y += oPos.y ; if ( this.IsRTL ) { @@ -186,43 +257,48 @@ if ( ( x + iMainWidth ) > iViewPaneWidth ) x -= x + iMainWidth - iViewPaneWidth ; - if ( ( y + this.MainNode.offsetHeight ) > iViewPaneHeight ) - y -= y + this.MainNode.offsetHeight - iViewPaneHeight ; + if ( ( y + eMainNode.offsetHeight ) > iViewPaneHeight ) + y -= y + eMainNode.offsetHeight - iViewPaneHeight ; } - if ( x < 0 ) - x = 0 ; - // Set the context menu DIV in the specified location. - this._IFrame.style.left = x + 'px' ; - this._IFrame.style.top = y + 'px' ; + FCKDomTools.SetElementStyles( this._IFrame, + { + left : x + 'px', + top : y + 'px' + } ) ; - var iWidth = iMainWidth ; - var iHeight = this.MainNode.offsetHeight ; + // Move the focus to the IFRAME so we catch the "onblur". + this._IFrame.contentWindow.focus() ; + this._IsOpened = true ; - this._IFrame.width = iWidth ; - this._IFrame.height = iHeight ; + var me = this ; + this._resizeTimer = setTimeout( function() + { + var iWidth = eMainNode.offsetWidth || eMainNode.firstChild.offsetWidth ; + var iHeight = eMainNode.offsetHeight ; + me._IFrame.width = iWidth ; + me._IFrame.height = iHeight ; - // Move the focus to the IFRAME so we catch the "onblur". - this._IFrame.contentWindow.focus() ; + }, 0 ) ; + + FCK.ToolbarSet.CurrentInstance.GetInstanceObject( 'FCKPanel' )._OpenedPanel = this ; } - this._IsOpened = true ; - FCKTools.RunFunction( this.OnShow, this ) ; } -FCKPanel.prototype.Hide = function( ignoreOnHide ) +FCKPanel.prototype.Hide = function( ignoreOnHide, ignoreFocusManagerUnlock ) { if ( this._Popup ) this._Popup.hide() ; else { - if ( !this._IsOpened ) + if ( !this._IsOpened || this._LockCounter > 0 ) return ; // Enable the editor to fire the "OnBlur". - if ( typeof( FCKFocusManager ) != 'undefined' ) + if ( typeof( FCKFocusManager ) != 'undefined' && !ignoreFocusManagerUnlock ) FCKFocusManager.Unlock() ; // It is better to set the sizes to 0, otherwise Firefox would have @@ -231,6 +307,12 @@ this._IsOpened = false ; + if ( this._resizeTimer ) + { + clearTimeout( this._resizeTimer ) ; + this._resizeTimer = null ; + } + if ( this.ParentPanel ) this.ParentPanel.Unlock() ; @@ -251,7 +333,7 @@ { var oWindow = this._Popup ? FCKTools.GetDocumentWindow( this.Document ) : this._Window ; - var oChildPanel = new FCKPanel( oWindow, true ) ; + var oChildPanel = new FCKPanel( oWindow ) ; oChildPanel.ParentPanel = this ; return oChildPanel ; @@ -300,4 +382,4 @@ this._Window = null ; this.Document = null ; this.MainNode = null ; -} \ No newline at end of file +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckplugin.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckplugin.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckplugin.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -53,4 +53,4 @@ // Add the main plugin script. LoadScript( this.Path + 'fckplugin.js' ) ; -} \ No newline at end of file +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckspecialcombo.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckspecialcombo.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckspecialcombo.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -36,8 +36,8 @@ this.Items = new Object() ; - this._Panel = new FCKPanel( parentWindow || window, true ) ; - this._Panel.AppendStyleSheet( FCKConfig.SkinPath + 'fck_editor.css' ) ; + this._Panel = new FCKPanel( parentWindow || window ) ; + this._Panel.AppendStyleSheet( FCKConfig.SkinEditorCSS ) ; this._PanelBox = this._Panel.MainNode.appendChild( this._Panel.Document.createElement( 'DIV' ) ) ; this._PanelBox.className = 'SC_Panel' ; this._PanelBox.style.width = this.PanelWidth + 'px' ; @@ -66,27 +66,35 @@ this.className = this.originalClass ; } -function FCKSpecialCombo_ItemOnClick() +function FCKSpecialCombo_ItemOnClick( ev, specialCombo, itemId ) { this.className = this.originalClass ; - this.FCKSpecialCombo._Panel.Hide() ; + specialCombo._Panel.Hide() ; - this.FCKSpecialCombo.SetLabel( this.FCKItemLabel ) ; + specialCombo.SetLabel( this.FCKItemLabel ) ; - if ( typeof( this.FCKSpecialCombo.OnSelect ) == 'function' ) - this.FCKSpecialCombo.OnSelect( this.FCKItemID, this ) ; + if ( typeof( specialCombo.OnSelect ) == 'function' ) + specialCombo.OnSelect( itemId, this ) ; } +FCKSpecialCombo.prototype.ClearItems = function () +{ + if ( this.Items ) + this.Items = {} ; + + var itemsholder = this._ItemsHolderEl ; + while ( itemsholder.firstChild ) + itemsholder.removeChild( itemsholder.firstChild ) ; +} + FCKSpecialCombo.prototype.AddItem = function( id, html, label, bgColor ) { //
      Bold 1
      var oDiv = this._ItemsHolderEl.appendChild( this._Panel.Document.createElement( 'DIV' ) ) ; oDiv.className = oDiv.originalClass = 'SC_Item' ; oDiv.innerHTML = html ; - oDiv.FCKItemID = id ; oDiv.FCKItemLabel = label || id ; - oDiv.FCKSpecialCombo = this ; oDiv.Selected = false ; // In IE, the width must be set so the borders are shown correctly when the content overflows. @@ -96,24 +104,24 @@ if ( bgColor ) oDiv.style.backgroundColor = bgColor ; - oDiv.onmouseover = FCKSpecialCombo_ItemOnMouseOver ; - oDiv.onmouseout = FCKSpecialCombo_ItemOnMouseOut ; - oDiv.onclick = FCKSpecialCombo_ItemOnClick ; + FCKTools.AddEventListenerEx( oDiv, 'mouseover', FCKSpecialCombo_ItemOnMouseOver ) ; + FCKTools.AddEventListenerEx( oDiv, 'mouseout', FCKSpecialCombo_ItemOnMouseOut ) ; + FCKTools.AddEventListenerEx( oDiv, 'click', FCKSpecialCombo_ItemOnClick, [ this, id ] ) ; this.Items[ id.toString().toLowerCase() ] = oDiv ; return oDiv ; } -FCKSpecialCombo.prototype.SelectItem = function( itemId ) +FCKSpecialCombo.prototype.SelectItem = function( item ) { - itemId = itemId ? itemId.toString().toLowerCase() : '' ; + if ( typeof item == 'string' ) + item = this.Items[ item.toString().toLowerCase() ] ; - var oDiv = this.Items[ itemId ] ; - if ( oDiv ) + if ( item ) { - oDiv.className = oDiv.originalClass = 'SC_ItemSelected' ; - oDiv.Selected = true ; + item.className = item.originalClass = 'SC_ItemSelected' ; + item.Selected = true ; } } @@ -138,6 +146,7 @@ { for ( var i in this.Items ) { + if ( !this.Items[i] ) continue; this.Items[i].className = this.Items[i].originalClass = 'SC_Item' ; this.Items[i].Selected = false ; } @@ -156,17 +165,23 @@ FCKSpecialCombo.prototype.SetLabel = function( text ) { - this.Label = text.length == 0 ? ' ' : text ; + text = ( !text || text.length == 0 ) ? ' ' : text ; - if ( this._LabelEl ) + if ( text == this.Label ) + return ; + + this.Label = text ; + + var labelEl = this._LabelEl ; + if ( labelEl ) { - this._LabelEl.innerHTML = this.Label ; + labelEl.innerHTML = text ; // It may happen that the label is some HTML, including tags. This // would be a problem because when the user click on those tags, the // combo will get the selection from the editing area. So we must // disable any kind of selection here. - FCKTools.DisableSelection( this._LabelEl ) ; + FCKTools.DisableSelection( labelEl ) ; } } @@ -174,7 +189,9 @@ { this.Enabled = isEnabled ; - this._OuterTable.className = isEnabled ? '' : 'SC_FieldDisabled' ; + // In IE it can happen when the page is reloaded that _OuterTable is null, so check its existence + if ( this._OuterTable ) + this._OuterTable.className = isEnabled ? '' : 'SC_FieldDisabled' ; } FCKSpecialCombo.prototype.Create = function( targetElement ) @@ -244,12 +261,10 @@ // Events Handlers - oField.SpecialCombo = this ; + FCKTools.AddEventListenerEx( oField, 'mouseover', FCKSpecialCombo_OnMouseOver, this ) ; + FCKTools.AddEventListenerEx( oField, 'mouseout', FCKSpecialCombo_OnMouseOut, this ) ; + FCKTools.AddEventListenerEx( oField, 'click', FCKSpecialCombo_OnClick, this ) ; - oField.onmouseover = FCKSpecialCombo_OnMouseOver ; - oField.onmouseout = FCKSpecialCombo_OnMouseOut ; - oField.onclick = FCKSpecialCombo_OnClick ; - FCKTools.DisableSelection( this._Panel.Document.body ) ; } @@ -267,28 +282,28 @@ } } -function FCKSpecialCombo_OnMouseOver() +function FCKSpecialCombo_OnMouseOver( ev, specialCombo ) { - if ( this.SpecialCombo.Enabled ) + if ( specialCombo.Enabled ) { - switch ( this.SpecialCombo.Style ) + switch ( specialCombo.Style ) { - case FCK_TOOLBARITEM_ONLYICON : - this.className = 'TB_Button_On_Over'; - break ; - case FCK_TOOLBARITEM_ONLYTEXT : - this.className = 'TB_Button_On_Over'; - break ; - case FCK_TOOLBARITEM_ICONTEXT : - this.className = 'SC_Field SC_FieldOver' ; - break ; + case FCK_TOOLBARITEM_ONLYICON : + this.className = 'TB_Button_On_Over'; + break ; + case FCK_TOOLBARITEM_ONLYTEXT : + this.className = 'TB_Button_On_Over'; + break ; + case FCK_TOOLBARITEM_ICONTEXT : + this.className = 'SC_Field SC_FieldOver' ; + break ; } } } -function FCKSpecialCombo_OnMouseOut() +function FCKSpecialCombo_OnMouseOut( ev, specialCombo ) { - switch ( this.SpecialCombo.Style ) + switch ( specialCombo.Style ) { case FCK_TOOLBARITEM_ONLYICON : this.className = 'TB_Button_Off'; @@ -302,7 +317,7 @@ } } -function FCKSpecialCombo_OnClick( e ) +function FCKSpecialCombo_OnClick( e, specialCombo ) { // For Mozilla we must stop the event propagation to avoid it hiding // the panel because of a click outside of it. @@ -312,17 +327,15 @@ // FCKPanelEventHandlers.OnDocumentClick( e ) ; // } - var oSpecialCombo = this.SpecialCombo ; - - if ( oSpecialCombo.Enabled ) + if ( specialCombo.Enabled ) { - var oPanel = oSpecialCombo._Panel ; - var oPanelBox = oSpecialCombo._PanelBox ; - var oItemsHolder = oSpecialCombo._ItemsHolderEl ; - var iMaxHeight = oSpecialCombo.PanelMaxHeight ; + var oPanel = specialCombo._Panel ; + var oPanelBox = specialCombo._PanelBox ; + var oItemsHolder = specialCombo._ItemsHolderEl ; + var iMaxHeight = specialCombo.PanelMaxHeight ; - if ( oSpecialCombo.OnBeforeClick ) - oSpecialCombo.OnBeforeClick( oSpecialCombo ) ; + if ( specialCombo.OnBeforeClick ) + specialCombo.OnBeforeClick( specialCombo ) ; // This is a tricky thing. We must call the "Load" function, otherwise // it will not be possible to retrieve "oItemsHolder.offsetHeight" (IE only). @@ -339,7 +352,7 @@ else oPanelBox.style.height = '' ; -// oPanel.PanelDiv.style.width = oSpecialCombo.PanelWidth + 'px' ; +// oPanel.PanelDiv.style.width = specialCombo.PanelWidth + 'px' ; oPanel.Show( 0, this.offsetHeight, this ) ; } @@ -360,4 +373,4 @@
      -*/ \ No newline at end of file +*/ Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckstyle.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckstyle.js (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/_source/classes/fckstyle.js 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,1443 @@ +?/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * FCKStyle Class: contains a style definition, and all methods to work with + * the style in a document. + */ + +/** + * @param {Object} styleDesc A "style descriptor" object, containing the raw + * style definition in the following format: + * ' + - - - - - - - - - - - - - - -
      - - - - - -
      - - - - - -
      -   -
      -   -
      + + Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_select/fck_select.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_select/fck_select.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_select/fck_select.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -61,10 +61,10 @@ var oTxtText = document.getElementById( "txtText" ) ; var oTxtValue = document.getElementById( "txtValue" ) ; - oListText.options[ iIndex ].innerHTML = oTxtText.value ; + oListText.options[ iIndex ].innerHTML = HTMLEncode( oTxtText.value ) ; oListText.options[ iIndex ].value = oTxtText.value ; - oListValue.options[ iIndex ].innerHTML = oTxtValue.value ; + oListValue.options[ iIndex ].innerHTML = HTMLEncode( oTxtValue.value ) ; oListValue.options[ iIndex ].value = oTxtValue.value ; oTxtText.value = '' ; @@ -115,7 +115,7 @@ return ; var oOption = combo.options[ iActualIndex ] ; - var sText = oOption.innerHTML ; + var sText = HTMLDecode( oOption.innerHTML ) ; var sValue = oOption.value ; combo.remove( iActualIndex ) ; @@ -162,8 +162,33 @@ else combo.options.add( oOption ) ; - oOption.innerHTML = optionText.length > 0 ? optionText : ' ' ; + oOption.innerHTML = optionText.length > 0 ? HTMLEncode( optionText ) : ' ' ; oOption.value = optionValue ; return oOption ; -} \ No newline at end of file +} + +function HTMLEncode( text ) +{ + if ( !text ) + return '' ; + + text = text.replace( /&/g, '&' ) ; + text = text.replace( //g, '>' ) ; + + return text ; +} + + +function HTMLDecode( text ) +{ + if ( !text ) + return '' ; + + text = text.replace( />/g, '>' ) ; + text = text.replace( /</g, '<' ) ; + text = text.replace( /&/g, '&' ) ; + + return text ; +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_select.html =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_select.html 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_select.html 2008-05-15 06:08:06 UTC (rev 930) @@ -1,7 +1,7 @@ - - + + + + + + + + - - - - - - - - - - - - function LastIndexOf(subs, str) - { - return Len(str) - Find(subs, Reverse(str)) + 1; - } - + + + - - - + - + - - - - - - + + + ]+>", " ", "all")> + + + - - - - - + - + + + + + + + - - - - - - - - - - - + + - - - - - + + + + - - - - - - - - + + + + + + + + + + + - + + - - - - - - + + - - - - - - - - + + + - - + - - + + - + + + @@ -172,3 +145,4 @@ + Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/server-scripts/spellchecker.php =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/server-scripts/spellchecker.php 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/server-scripts/spellchecker.php 2008-05-15 06:08:06 UTC (rev 930) @@ -7,7 +7,7 @@ //$aspell_prog = 'aspell'; // by FredCK (for Linux) $lang = 'en_US'; -$aspell_opts = "-a --lang=$lang --encoding=utf-8 -H"; // by FredCK +$aspell_opts = "-a --lang=$lang --encoding=utf-8 -H --rem-sgml-check=alt"; // by FredCK $tempfiledir = "./"; @@ -62,7 +62,7 @@ # handle a server-side error. function error_handler( $err ) { - echo "error = '" . escape_quote( $err ) . "';\n"; + echo "error = '" . preg_replace( "/['\\\\]/", "\\\\$0", $err ) . "';\n"; } ## get the list of misspelled words. Put the results in the javascript words array @@ -82,6 +82,10 @@ if( $fh = fopen( $tempfile, 'w' )) { for( $i = 0; $i < count( $textinputs ); $i++ ) { $text = urldecode( $textinputs[$i] ); + + // Strip all tags for the text. (by FredCK - #339 / #681) + $text = preg_replace( "/<[^>]+>/", " ", $text ) ; + $lines = explode( "\n", $text ); fwrite ( $fh, "%\n" ); # exit terse mode fwrite ( $fh, "^$input_separator\n" ); @@ -193,4 +197,3 @@ - Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/server-scripts/spellchecker.pl =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/server-scripts/spellchecker.pl 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/server-scripts/spellchecker.pl 2008-05-15 06:08:06 UTC (rev 930) @@ -12,7 +12,7 @@ my $aspell_cmd = '"C:\Program Files\Aspell\bin\aspell.exe"'; # by FredCK (for Windows) my $lang = 'en_US'; # my $aspell_opts = "-a --lang=$lang --encoding=utf-8"; # by FredCK -my $aspell_opts = "-a --lang=$lang --encoding=utf-8 -H"; # by FredCK +my $aspell_opts = "-a --lang=$lang --encoding=utf-8 -H --rem-sgml-check=alt"; # by FredCK my $input_separator = "A"; # set the 'wordtext' JavaScript variable to the submitted text. @@ -58,6 +58,8 @@ # open temp file, add the submitted text. for( my $i = 0; $i <= $#textinputs; $i++ ) { $text = url_decode( $textinputs[$i] ); + # Strip all tags for the text. (by FredCK - #339 / #681) + $text =~ s/<[^>]+>/ /g; @lines = split( /\n/, $text ); print $fh "\%\n"; # exit terse mode print $fh "^$input_separator\n"; @@ -177,4 +179,3 @@ EOF - Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/spellChecker.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/spellChecker.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/spellChecker.js 2008-05-15 06:08:06 UTC (rev 930) @@ -459,4 +459,3 @@ } return inputs; } - Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/spellerStyle.css =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/spellerStyle.css 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages/spellerpages/spellerStyle.css 2008-05-15 06:08:06 UTC (rev 930) @@ -46,4 +46,4 @@ width:200px; margin-top:2; font-size:8pt; -} \ No newline at end of file +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages.html =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages.html 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/dialog/fck_spellerpages.html 2008-05-15 06:08:06 UTC (rev 930) @@ -1,7 +1,7 @@ + - - - - - - - - - - - - - - -
      + +
      +
      - -
      - - - - - -
        - -   - -
      -
      +
      + +
      +
      + + + + + +
        + +   + +
      +
      + +
      +
      +
      +
      +
      +
      +
      +
      + + + - \ No newline at end of file + Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/fckeditor.html =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/fckeditor.html 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/fckeditor.html 2008-05-15 06:08:06 UTC (rev 930) @@ -1,7 +1,7 @@ - + FCKeditor - - - + + + Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/fckeditor.original.html =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/fckeditor.original.html 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/fckeditor.original.html 2008-05-15 06:08:06 UTC (rev 930) @@ -1,7 +1,7 @@ - +? - + FCKeditor - - + + Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/browser.css =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/browser.css 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/browser.css 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ /* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -46,6 +46,7 @@ { background-color: #ffffff; + margin: 10px; } body, td, input, select @@ -85,4 +86,4 @@ .FolderListFolder img { background-image: url(images/Folder.gif); -} \ No newline at end of file +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/browser.html =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/browser.html 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/browser/default/browser.html 2008-05-15 06:08:06 UTC (rev 930) @@ -1,7 +1,7 @@ + " + Response.End +End Sub + +%> Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/asp/upload.asp =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/asp/upload.asp (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/asp/upload.asp 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,65 @@ +?<%@ CodePage=65001 Language="VBScript"%> +<% +Option Explicit +Response.Buffer = True +%> +<% + ' FCKeditor - The text editor for Internet - http://www.fckeditor.net + ' Copyright (C) 2003-2008 Frederico Caldeira Knabben + ' + ' == BEGIN LICENSE == + ' + ' Licensed under the terms of any of the following licenses at your + ' choice: + ' + ' - GNU General Public License Version 2 or later (the "GPL") + ' http://www.gnu.org/licenses/gpl.html + ' + ' - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + ' http://www.gnu.org/licenses/lgpl.html + ' + ' - Mozilla Public License Version 1.1 or later (the "MPL") + ' http://www.mozilla.org/MPL/MPL-1.1.html + ' + ' == END LICENSE == + ' + ' This is the "File Uploader" for ASP. +%> + + + + + +<% + +Sub SendError( number, text ) + SendUploadResults number, "", "", text +End Sub + +' Check if this uploader has been enabled. +If ( ConfigIsEnabled = False ) Then + SendUploadResults "1", "", "", "This file uploader is disabled. Please check the ""editor/filemanager/connectors/asp/config.asp"" file" +End If + + Dim sCommand, sResourceType, sCurrentFolder + + sCommand = "QuickUpload" + + sResourceType = Request.QueryString("Type") + If ( sResourceType = "" ) Then sResourceType = "File" + + sCurrentFolder = GetCurrentFolder() + + ' Is Upload enabled? + if ( Not IsAllowedCommand( sCommand ) ) then + SendUploadResults "1", "", "", "The """ & sCommand & """ command isn't allowed" + end if + + ' Check if it is an allowed resource type. + if ( Not IsAllowedType( sResourceType ) ) Then + SendUploadResults "1", "", "", "The " & sResourceType & " resource type isn't allowed" + end if + + FileUpload sResourceType, sCurrentFolder, sCommand + +%> Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/asp/util.asp =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/asp/util.asp (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/asp/util.asp 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,55 @@ +?<% + ' FCKeditor - The text editor for Internet - http://www.fckeditor.net + ' Copyright (C) 2003-2008 Frederico Caldeira Knabben + ' + ' == BEGIN LICENSE == + ' + ' Licensed under the terms of any of the following licenses at your + ' choice: + ' + ' - GNU General Public License Version 2 or later (the "GPL") + ' http://www.gnu.org/licenses/gpl.html + ' + ' - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + ' http://www.gnu.org/licenses/lgpl.html + ' + ' - Mozilla Public License Version 1.1 or later (the "MPL") + ' http://www.mozilla.org/MPL/MPL-1.1.html + ' + ' == END LICENSE == + ' + ' This file include generic functions used by the ASP Connector. +%> +<% +Function RemoveFromStart( sourceString, charToRemove ) + Dim oRegex + Set oRegex = New RegExp + oRegex.Pattern = "^" & charToRemove & "+" + + RemoveFromStart = oRegex.Replace( sourceString, "" ) +End Function + +Function RemoveFromEnd( sourceString, charToRemove ) + Dim oRegex + Set oRegex = New RegExp + oRegex.Pattern = charToRemove & "+$" + + RemoveFromEnd = oRegex.Replace( sourceString, "" ) +End Function + +Function ConvertToXmlAttribute( value ) + ConvertToXmlAttribute = Replace( value, "&", "&" ) +End Function + +Function InArray( value, sourceArray ) + Dim i + For i = 0 to UBound( sourceArray ) + If sourceArray(i) = value Then + InArray = True + Exit Function + End If + Next + InArray = False +End Function + +%> Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/aspx/config.ascx =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/aspx/config.ascx (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/aspx/config.ascx 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,98 @@ +<%@ Control Language="C#" EnableViewState="false" AutoEventWireup="false" Inherits="FredCK.FCKeditorV2.FileBrowser.Config" %> +<%-- + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * Configuration file for the File Browser Connector for ASP.NET. +--%> + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/aspx/connector.aspx =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/aspx/connector.aspx (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/aspx/connector.aspx 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,32 @@ +<%@ Page Language="c#" Trace="false" Inherits="FredCK.FCKeditorV2.FileBrowser.Connector" AutoEventWireup="false" %> +<%@ Register Src="config.ascx" TagName="Config" TagPrefix="FCKeditor" %> +<%-- + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * This is the File Browser Connector for ASP.NET. + * + * The code of this page if included in the FCKeditor.Net package, + * in the FredCK.FCKeditorV2.dll assembly file. So to use it you must + * include that DLL in your "bin" directory. + * + * To download the FCKeditor.Net package, go to our official web site: + * http://www.fckeditor.net +--%> + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/aspx/upload.aspx =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/aspx/upload.aspx (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/aspx/upload.aspx 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,32 @@ +<%@ Page Language="c#" Trace="false" Inherits="FredCK.FCKeditorV2.FileBrowser.Uploader" AutoEventWireup="false" %> +<%@ Register Src="config.ascx" TagName="Config" TagPrefix="FCKeditor" %> +<%-- + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * This is the Uploader for ASP.NET. + * + * The code of this page if included in the FCKeditor.Net package, + * in the FredCK.FCKeditorV2.dll assemblyfile. So to use it you must + * include that DLL in your "bin" directory. + * + * To download the FCKeditor.Net package, go to our official web site: + * http://www.fckeditor.net +--%> + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/ImageObject.cfc =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/ImageObject.cfc (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/ImageObject.cfc 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,273 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf5_connector.cfm =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf5_connector.cfm (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf5_connector.cfm 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,315 @@ + + + + + + + + + + + + userFilesPath = config.userFilesPath; + + if ( userFilesPath eq "" ) + { + userFilesPath = "/userfiles/"; + } + + // make sure the user files path is correctly formatted + userFilesPath = replace(userFilesPath, "\", "/", "ALL"); + userFilesPath = replace(userFilesPath, '//', '/', 'ALL'); + if ( right(userFilesPath,1) NEQ "/" ) + { + userFilesPath = userFilesPath & "/"; + } + if ( left(userFilesPath,1) NEQ "/" ) + { + userFilesPath = "/" & userFilesPath; + } + + // make sure the current folder is correctly formatted + url.currentFolder = replace(url.currentFolder, "\", "/", "ALL"); + url.currentFolder = replace(url.currentFolder, '//', '/', 'ALL'); + if ( right(url.currentFolder,1) neq "/" ) + { + url.currentFolder = url.currentFolder & "/"; + } + if ( left(url.currentFolder,1) neq "/" ) + { + url.currentFolder = "/" & url.currentFolder; + } + + if ( find("/",getBaseTemplatePath()) neq 0 ) + { + fs = "/"; + } + else + { + fs = "\"; + } + + // Get the base physical path to the web root for this application. The code to determine the path automatically assumes that + // the "FCKeditor" directory in the http request path is directly off the web root for the application and that it's not a + // virtual directory or a symbolic link / junction. Use the serverPath config setting to force a physical path if necessary. + if ( len(config.serverPath) ) + { + serverPath = config.serverPath; + + if ( right(serverPath,1) neq fs ) + { + serverPath = serverPath & fs; + } + } + else + { + serverPath = replaceNoCase(getBaseTemplatePath(),replace(cgi.script_name,"/",fs,"all"),"") & replace(userFilesPath,"/",fs,"all"); + } + + rootPath = left( serverPath, Len(serverPath) - Len(userFilesPath) ) ; + xmlContent = ""; // append to this string to build content + + + + + + + + + + + + + + + + + + + + + + + + "> + + + + "> + + + + '> + + + + '> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + "> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + i=1; + folders = ""; + while( i lte qDir.recordCount ) { + if( not compareNoCase( qDir.type[i], "FILE" )) + break; + if( not listFind(".,..", qDir.name[i]) ) + folders = folders & ''; + i=i+1; + } + + xmlContent = xmlContent & '' & folders & ''; + + + + + + + + + + + + i=1; + folders = ""; + files = ""; + while( i lte qDir.recordCount ) { + if( not compareNoCase( qDir.type[i], "DIR" ) and not listFind(".,..", qDir.name[i]) ) { + folders = folders & ''; + } else if( not compareNoCase( qDir.type[i], "FILE" ) ) { + fileSizeKB = round(qDir.size[i] / 1024); + files = files & ''; + } + i=i+1; + } + + xmlContent = xmlContent & '' & folders & ''; + xmlContent = xmlContent & '' & files & ''; + + + + + + + + + + + newFolderName = url.newFolderName; + if( reFind("[^A-Za-z0-9_\-\.]", newFolderName) ) { + // Munge folder name same way as we do the filename + // This means folder names are always US-ASCII so we don't have to worry about CF5 and UTF-8 + newFolderName = reReplace(newFolderName, "[^A-Za-z0-9\-\.]", "_", "all"); + newFolderName = reReplace(newFolderName, "_{2,}", "_", "all"); + newFolderName = reReplace(newFolderName, "([^_]+)_+$", "\1", "all"); + newFolderName = reReplace(newFolderName, "$_([^_]+)$", "\1", "all"); + } + + + + + + + + + + + + + + + + + + + + + '> + + + + + + + + + + + + xmlHeader = ''; + xmlHeader = xmlHeader & ''; + xmlFooter = ''; + + + + + + +#xmlHeader##xmlContent##xmlFooter# Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf5_upload.cfm =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf5_upload.cfm (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf5_upload.cfm 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,328 @@ + + + + + + + + + + + + + function SendUploadResults(errorNumber, fileUrl, fileName, customMsg) + { + WriteOutput(''); + } + + + + + + + + + + + + + + + + + + + + + + + + userFilesPath = config.userFilesPath; + + if ( userFilesPath eq "" ) { + userFilesPath = "/userfiles/"; + } + + // make sure the user files path is correctly formatted + userFilesPath = replace(userFilesPath, "\", "/", "ALL"); + userFilesPath = replace(userFilesPath, '//', '/', 'ALL'); + if ( right(userFilesPath,1) NEQ "/" ) { + userFilesPath = userFilesPath & "/"; + } + if ( left(userFilesPath,1) NEQ "/" ) { + userFilesPath = "/" & userFilesPath; + } + + // make sure the current folder is correctly formatted + url.currentFolder = replace(url.currentFolder, "\", "/", "ALL"); + url.currentFolder = replace(url.currentFolder, '//', '/', 'ALL'); + if ( right(url.currentFolder,1) neq "/" ) { + url.currentFolder = url.currentFolder & "/"; + } + if ( left(url.currentFolder,1) neq "/" ) { + url.currentFolder = "/" & url.currentFolder; + } + + if (find("/",getBaseTemplatePath())) { + fs = "/"; + } else { + fs = "\"; + } + + // Get the base physical path to the web root for this application. The code to determine the path automatically assumes that + // the "FCKeditor" directory in the http request path is directly off the web root for the application and that it's not a + // virtual directory or a symbolic link / junction. Use the serverPath config setting to force a physical path if necessary. + if ( len(config.serverPath) ) { + serverPath = config.serverPath; + + if ( right(serverPath,1) neq fs ) { + serverPath = serverPath & fs; + } + } else { + serverPath = replaceNoCase(getBaseTemplatePath(),replace(cgi.script_name,"/",fs,"all"),"") & replace(userFilesPath,"/",fs,"all"); + } + + rootPath = left( serverPath, Len(serverPath) - Len(userFilesPath) ) ; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + errorNumber = 0; + fileName = cffile.ClientFileName ; + fileExt = cffile.ServerFileExt ; + fileExisted = false ; + + // munge filename for html download. Only a-z, 0-9, _, - and . are allowed + if( reFind("[^A-Za-z0-9_\-\.]", fileName) ) { + fileName = reReplace(fileName, "[^A-Za-z0-9\-\.]", "_", "ALL"); + fileName = reReplace(fileName, "_{2,}", "_", "ALL"); + fileName = reReplace(fileName, "([^_]+)_+$", "\1", "ALL"); + fileName = reReplace(fileName, "$_([^_]+)$", "\1", "ALL"); + } + + // remove additional dots from file name + if( isDefined("Config.ForceSingleExtension") and Config.ForceSingleExtension ) + fileName = replace( fileName, '.', "_", "all" ) ; + + // When the original filename already exists, add numbers (0), (1), (2), ... at the end of the filename. + if( compare( cffile.ServerFileName, fileName ) ) { + counter = 0; + tmpFileName = fileName; + while( fileExists("#currentFolderPath##fileName#.#fileExt#") ) { + fileExisted = true ; + counter = counter + 1 ; + fileName = tmpFileName & '(#counter#)' ; + } + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_basexml.cfm =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_basexml.cfm (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_basexml.cfm 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_commands.cfm =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_commands.cfm (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_commands.cfm 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,230 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + sFileExt = GetExtension( sFileName ) ; + sFilePart = RemoveExtension( sFileName ); + while( fileExists( sServerDir & sFileName ) ) + { + counter = counter + 1; + sFileName = sFilePart & '(#counter#).' & CFFILE.ClientFileExt; + errorNumber = 201; + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + while( i lte qDir.recordCount ) + { + if( compareNoCase( qDir.type[i], "FILE" ) and not listFind( ".,..", qDir.name[i] ) ) + { + folders = folders & '' ; + } + i = i + 1; + } + + #folders# + + + + + + + + + + + + + + + + while( i lte qDir.recordCount ) + { + if( not compareNoCase( qDir.type[i], "DIR" ) and not listFind( ".,..", qDir.name[i] ) ) + { + folders = folders & '' ; + } + else if( not compareNoCase( qDir.type[i], "FILE" ) ) + { + fileSizeKB = round(qDir.size[i] / 1024) ; + files = files & '' ; + } + i = i + 1 ; + } + + #folders# + #files# + + + + + + + + + + + + + + + + sNewFolderName = SanitizeFolderName( sNewFolderName ) ; + + + + + + + + + + + + + + + + + + + + + + + + + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_connector.cfm =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_connector.cfm (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_connector.cfm 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,89 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_io.cfm =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_io.cfm (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_io.cfm 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,319 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +|[[:cntrl:]]+', "_", "all" )> + + + + + + + + + + var chunk = ""; + var fileReaderClass = ""; + var fileReader = ""; + var file = ""; + var done = false; + var counter = 0; + var byteArray = ""; + + if( not fileExists( ARGUMENTS.fileName ) ) + { + return "" ; + } + + if (REQUEST.CFVersion gte 8) + { + file = FileOpen( ARGUMENTS.fileName, "readbinary" ) ; + byteArray = FileRead( file, 1024 ) ; + chunk = toString( toBinary( toBase64( byteArray ) ) ) ; + FileClose( file ) ; + } + else + { + fileReaderClass = createObject("java", "java.io.FileInputStream"); + fileReader = fileReaderClass.init(fileName); + + while(not done) + { + char = fileReader.read(); + counter = counter + 1; + if ( char eq -1 or counter eq ARGUMENTS.bytes) + { + done = true; + } + else + { + chunk = chunk & chr(char) ; + } + } + } + + + + + + + + + + + + + + + + + + + + + + + + + + + +|[[:cntrl:]]+', "_", "all" )> + + + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_upload.cfm =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_upload.cfm (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_upload.cfm 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_util.cfm =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_util.cfm (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/cf_util.cfm 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,131 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + > + + + + + + + + + + + + + + + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/config.cfm =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/config.cfm (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/config.cfm 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,189 @@ + + + + + Config = StructNew() ; + + // SECURITY: You must explicitly enable this "connector". (Set enabled to "true") + Config.Enabled = false ; + + + // Path to uploaded files relative to the document root. + Config.UserFilesPath = "/userfiles/" ; + + // Use this to force the server path if FCKeditor is not running directly off + // the root of the application or the FCKeditor directory in the URL is a virtual directory + // or a symbolic link / junction + // Example: C:\inetpub\wwwroot\myDocs\ + Config.ServerPath = "" ; + + // Due to security issues with Apache modules, it is recommended to leave the + // following setting enabled. + Config.ForceSingleExtension = true ; + + // Perform additional checks for image files - if set to true, validate image size + // (This feature works in MX 6.0 and above) + Config.SecureImageUploads = true; + + // What the user can do with this connector + Config.ConfigAllowedCommands = "QuickUpload,FileUpload,GetFolders,GetFoldersAndFiles,CreateFolder" ; + + //Allowed Resource Types + Config.ConfigAllowedTypes = "File,Image,Flash,Media" ; + + // For security, HTML is allowed in the first Kb of data for files having the + // following extensions only. + // (This feature works in MX 6.0 and above)) + Config.HtmlExtensions = "html,htm,xml,xsd,txt,js" ; + + //Due to known issues with GetTempDirectory function, it is + //recommended to set this vairiable to a valid directory + //instead of using the GetTempDirectory function + //(used by MX 6.0 and above) + Config.TempDirectory = GetTempDirectory(); + +// Configuration settings for each Resource Type +// +// - AllowedExtensions: the possible extensions that can be allowed. +// If it is empty then any file type can be uploaded. +// - DeniedExtensions: The extensions that won't be allowed. +// If it is empty then no restrictions are done here. +// +// For a file to be uploaded it has to fulfill both the AllowedExtensions +// and DeniedExtensions (that's it: not being denied) conditions. +// +// - FileTypesPath: the virtual folder relative to the document root where +// these resources will be located. +// Attention: It must start and end with a slash: '/' +// +// - FileTypesAbsolutePath: the physical path to the above folder. It must be +// an absolute path. +// If it's an empty string then it will be autocalculated. +// Usefull if you are using a virtual directory, symbolic link or alias. +// Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. +// Attention: The above 'FileTypesPath' must point to the same directory. +// Attention: It must end with a slash: '/' +// +// +// - QuickUploadPath: the virtual folder relative to the document root where +// these resources will be uploaded using the Upload tab in the resources +// dialogs. +// Attention: It must start and end with a slash: '/' +// +// - QuickUploadAbsolutePath: the physical path to the above folder. It must be +// an absolute path. +// If it's an empty string then it will be autocalculated. +// Usefull if you are using a virtual directory, symbolic link or alias. +// Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. +// Attention: The above 'QuickUploadPath' must point to the same directory. +// Attention: It must end with a slash: '/' + + Config.AllowedExtensions = StructNew() ; + Config.DeniedExtensions = StructNew() ; + Config.FileTypesPath = StructNew() ; + Config.FileTypesAbsolutePath = StructNew() ; + Config.QuickUploadPath = StructNew() ; + Config.QuickUploadAbsolutePath = StructNew() ; + + Config.AllowedExtensions["File"] = "7z,aiff,asf,avi,bmp,csv,doc,fla,flv,gif,gz,gzip,jpeg,jpg,mid,mov,mp3,mp4,mpc,mpeg,mpg,ods,odt,pdf,png,ppt,pxd,qt,ram,rar,rm,rmi,rmvb,rtf,sdc,sitd,swf,sxc,sxw,tar,tgz,tif,tiff,txt,vsd,wav,wma,wmv,xls,xml,zip" ; + Config.DeniedExtensions["File"] = "" ; + Config.FileTypesPath["File"] = Config.UserFilesPath & 'file/' ; + Config.FileTypesAbsolutePath["File"] = iif( Config.ServerPath eq "", de(""), de(Config.ServerPath & 'file/') ) ; + Config.QuickUploadPath["File"] = Config.FileTypesPath["File"] ; + Config.QuickUploadAbsolutePath["File"] = Config.FileTypesAbsolutePath["File"] ; + + Config.AllowedExtensions["Image"] = "bmp,gif,jpeg,jpg,png" ; + Config.DeniedExtensions["Image"] = "" ; + Config.FileTypesPath["Image"] = Config.UserFilesPath & 'image/' ; + Config.FileTypesAbsolutePath["Image"] = iif( Config.ServerPath eq "", de(""), de(Config.ServerPath & 'image/') ) ; + Config.QuickUploadPath["Image"] = Config.FileTypesPath["Image"] ; + Config.QuickUploadAbsolutePath["Image"] = Config.FileTypesAbsolutePath["Image"] ; + + Config.AllowedExtensions["Flash"] = "swf,flv" ; + Config.DeniedExtensions["Flash"] = "" ; + Config.FileTypesPath["Flash"] = Config.UserFilesPath & 'flash/' ; + Config.FileTypesAbsolutePath["Flash"] = iif( Config.ServerPath eq "", de(""), de(Config.ServerPath & 'flash/') ) ; + Config.QuickUploadPath["Flash"] = Config.FileTypesPath["Flash"] ; + Config.QuickUploadAbsolutePath["Flash"] = Config.FileTypesAbsolutePath["Flash"] ; + + Config.AllowedExtensions["Media"] = "aiff,asf,avi,bmp,fla,flv,gif,jpeg,jpg,mid,mov,mp3,mp4,mpc,mpeg,mpg,png,qt,ram,rm,rmi,rmvb,swf,tif,tiff,wav,wma,wmv" ; + Config.DeniedExtensions["Media"] = "" ; + Config.FileTypesPath["Media"] = Config.UserFilesPath & 'media/' ; + Config.FileTypesAbsolutePath["Media"] = iif( Config.ServerPath eq "", de(""), de(Config.ServerPath & 'media/') ) ; + Config.QuickUploadPath["Media"] = Config.FileTypesPath["Media"] ; + Config.QuickUploadAbsolutePath["Media"] = Config.FileTypesAbsolutePath["Media"] ; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + function structCopyKeys(stFrom, stTo) { + for ( key in stFrom ) { + if ( isStruct(stFrom[key]) ) { + structCopyKeys(stFrom[key],stTo[key]); + } else { + stTo[key] = stFrom[key]; + } + } + } + structCopyKeys(FCKeditor, config); + + + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/connector.cfm =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/connector.cfm (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/connector.cfm 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,32 @@ + + + + + + + + + + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/image.cfc =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/image.cfc (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/image.cfc 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,1324 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + paths = arrayNew(1); + paths[1] = expandPath("metadata-extractor-2.3.1.jar"); + loader = createObject("component", "javaloader.JavaLoader").init(paths); + + //at this stage we only have access to the class, but we don't have an instance + JpegMetadataReader = loader.create("com.drew.imaging.jpeg.JpegMetadataReader"); + + myMetaData = JpegMetadataReader.readMetadata(inFile); + directories = myMetaData.getDirectoryIterator(); + while (directories.hasNext()) { + currentDirectory = directories.next(); + tags = currentDirectory.getTagIterator(); + while (tags.hasNext()) { + currentTag = tags.next(); + if (currentTag.getTagName() DOES NOT CONTAIN "Unknown") { //leave out the junk data + queryAddRow(retQry); + querySetCell(retQry,"dirName",replace(currentTag.getDirectoryName(),' ','_','ALL')); + tagName = replace(currentTag.getTagName(),' ','','ALL'); + tagName = replace(tagName,'/','','ALL'); + querySetCell(retQry,"tagName",tagName); + querySetCell(retQry,"tagValue",currentTag.getDescription()); + } + } + } + return retQry; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + resizedImage = CreateObject("java", "java.awt.image.BufferedImage"); + at = CreateObject("java", "java.awt.geom.AffineTransform"); + op = CreateObject("java", "java.awt.image.AffineTransformOp"); + + w = img.getWidth(); + h = img.getHeight(); + + if (preserveAspect and cropToExact and newHeight gt 0 and newWidth gt 0) + { + if (w / h gt newWidth / newHeight){ + newWidth = 0; + } else if (w / h lt newWidth / newHeight){ + newHeight = 0; + } + } else if (preserveAspect and newHeight gt 0 and newWidth gt 0) { + if (w / h gt newWidth / newHeight){ + newHeight = 0; + } else if (w / h lt newWidth / newHeight){ + newWidth = 0; + } + } + if (newWidth gt 0 and newHeight eq 0) { + scale = newWidth / w; + w = newWidth; + h = round(h*scale); + } else if (newHeight gt 0 and newWidth eq 0) { + scale = newHeight / h; + h = newHeight; + w = round(w*scale); + } else if (newHeight gt 0 and newWidth gt 0) { + w = newWidth; + h = newHeight; + } else { + retVal = throw( retVal.errorMessage); + return retVal; + } + resizedImage.init(javacast("int",w),javacast("int",h),img.getType()); + + w = w / img.getWidth(); + h = h / img.getHeight(); + + + + op.init(at.getScaleInstance(javacast("double",w),javacast("double",h)), rh); + // resizedImage = op.createCompatibleDestImage(img, img.getColorModel()); + op.filter(img, resizedImage); + + imgInfo = getimageinfo(resizedImage, ""); + if (imgInfo.errorCode gt 0) + { + return imgInfo; + } + + cropOffsetX = max( Int( (imgInfo.width/2) - (newWidth/2) ), 0 ); + cropOffsetY = max( Int( (imgInfo.height/2) - (newHeight/2) ), 0 ); + // There is a chance that the image is exactly the correct + // width and height and don't need to be cropped + if + ( + preserveAspect and cropToExact + and + (imgInfo.width IS NOT specifiedWidth OR imgInfo.height IS NOT specifiedHeight) + ) + { + // Get the correct offset to get the center of the image + cropOffsetX = max( Int( (imgInfo.width/2) - (specifiedWidth/2) ), 0 ); + cropOffsetY = max( Int( (imgInfo.height/2) - (specifiedHeight/2) ), 0 ); + + cropImageResult = crop( resizedImage, "", "", cropOffsetX, cropOffsetY, specifiedWidth, specifiedHeight ); + if ( cropImageResult.errorCode GT 0) + { + return cropImageResult; + } else { + resizedImage = cropImageResult.img; + } + } + if (outputFile eq "") + { + retVal.img = resizedImage; + return retVal; + } else { + saveImage = writeImage(outputFile, resizedImage, jpegCompression); + if (saveImage.errorCode gt 0) + { + return saveImage; + } else { + return retVal; + } + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + if (fromX + newWidth gt img.getWidth() + OR + fromY + newHeight gt img.getHeight() + ) + { + retval = throw( "The cropped image dimensions go beyond the original image dimensions."); + return retVal; + } + croppedImage = img.getSubimage(javaCast("int", fromX), javaCast("int", fromY), javaCast("int", newWidth), javaCast("int", newHeight) ); + if (outputFile eq "") + { + retVal.img = croppedImage; + return retVal; + } else { + saveImage = writeImage(outputFile, croppedImage, jpegCompression); + if (saveImage.errorCode gt 0) + { + return saveImage; + } else { + return retVal; + } + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + rotatedImage = CreateObject("java", "java.awt.image.BufferedImage"); + at = CreateObject("java", "java.awt.geom.AffineTransform"); + op = CreateObject("java", "java.awt.image.AffineTransformOp"); + + iw = img.getWidth(); h = iw; + ih = img.getHeight(); w = ih; + + if(arguments.degrees eq 180) { w = iw; h = ih; } + + x = (w/2)-(iw/2); + y = (h/2)-(ih/2); + + rotatedImage.init(javacast("int",w),javacast("int",h),img.getType()); + + at.rotate(arguments.degrees * 0.0174532925,w/2,h/2); + at.translate(x,y); + op.init(at, rh); + + op.filter(img, rotatedImage); + + if (outputFile eq "") + { + retVal.img = rotatedImage; + return retVal; + } else { + saveImage = writeImage(outputFile, rotatedImage, jpegCompression); + if (saveImage.errorCode gt 0) + { + return saveImage; + } else { + return retVal; + } + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + if (outputFile eq "") + { + retVal = throw( "The convert method requires a valid output filename."); + return retVal; + } else { + saveImage = writeImage(outputFile, img, jpegCompression); + if (saveImage.errorCode gt 0) + { + return saveImage; + } else { + return retVal; + } + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /* + JPEG output method handles compression + */ + out = createObject("java", "java.io.BufferedOutputStream"); + fos = createObject("java", "java.io.FileOutputStream"); + fos.init(tempOutputFile); + out.init(fos); + JPEGCodec = createObject("java", "com.sun.image.codec.jpeg.JPEGCodec"); + encoder = JPEGCodec.createJPEGEncoder(out); + param = encoder.getDefaultJPEGEncodeParam(img); + param.setQuality(quality, false); + encoder.setJPEGEncodeParam(param); + encoder.encode(img); + out.close(); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + flippedImage = CreateObject("java", "java.awt.image.BufferedImage"); + at = CreateObject("java", "java.awt.geom.AffineTransform"); + op = CreateObject("java", "java.awt.image.AffineTransformOp"); + + flippedImage.init(img.getWidth(), img.getHeight(), img.getType()); + + if (direction eq "horizontal") { + at = at.getScaleInstance(-1, 1); + at.translate(-img.getWidth(), 0); + } else { + at = at.getScaleInstance(1,-1); + at.translate(0, -img.getHeight()); + } + op.init(at, rh); + op.filter(img, flippedImage); + + if (outputFile eq "") + { + retVal.img = flippedImage; + return retVal; + } else { + saveImage = writeImage(outputFile, flippedImage, jpegCompression); + if (saveImage.errorCode gt 0) + { + return saveImage; + } else { + return retVal; + } + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // initialize the blur filter + variables.blurFilter.init(arguments.blurAmount); + // move the source image into the destination image + // so we can repeatedly blur it. + destImage = srcImage; + + for (i=1; i lte iterations; i=i+1) + { + // do the blur i times + destImage = variables.blurFilter.filter(destImage); + } + + + if (outputFile eq "") + { + // return the image object + retVal.img = destImage; + return retVal; + } else { + // write the image object to the specified file. + saveImage = writeImage(outputFile, destImage, jpegCompression); + if (saveImage.errorCode gt 0) + { + return saveImage; + } else { + return retVal; + } + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // initialize the sharpen filter + variables.sharpenFilter.init(); + + destImage = variables.sharpenFilter.filter(srcImage); + + + if (outputFile eq "") + { + // return the image object + retVal.img = destImage; + return retVal; + } else { + // write the image object to the specified file. + saveImage = writeImage(outputFile, destImage, jpegCompression); + if (saveImage.errorCode gt 0) + { + return saveImage; + } else { + return retVal; + } + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // initialize the posterize filter + variables.posterizeFilter.init(arguments.amount); + + destImage = variables.posterizeFilter.filter(srcImage); + + + if (outputFile eq "") + { + // return the image object + retVal.img = destImage; + return retVal; + } else { + // write the image object to the specified file. + saveImage = writeImage(outputFile, destImage, jpegCompression); + if (saveImage.errorCode gt 0) + { + return saveImage; + } else { + return retVal; + } + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // load objects + bgImage = CreateObject("java", "java.awt.image.BufferedImage"); + fontImage = CreateObject("java", "java.awt.image.BufferedImage"); + overlayImage = CreateObject("java", "java.awt.image.BufferedImage"); + Color = CreateObject("java","java.awt.Color"); + font = createObject("java","java.awt.Font"); + font_stream = createObject("java","java.io.FileInputStream"); + ac = CreateObject("Java", "java.awt.AlphaComposite"); + + // set up basic needs + fontColor = Color.init(javacast("int", rgb.red), javacast("int", rgb.green), javacast("int", rgb.blue)); + + if (fontDetails.fontFile neq "") + { + font_stream.init(arguments.fontDetails.fontFile); + font = font.createFont(font.TRUETYPE_FONT, font_stream); + font = font.deriveFont(javacast("float",arguments.fontDetails.size)); + } else { + font.init(fontDetails.fontName, evaluate(fontDetails.style), fontDetails.size); + } + // get font metrics using a 1x1 bufferedImage + fontImage.init(1,1,img.getType()); + g2 = fontImage.createGraphics(); + g2.setRenderingHints(getRenderingHints()); + fc = g2.getFontRenderContext(); + bounds = font.getStringBounds(content,fc); + + g2 = img.createGraphics(); + g2.setRenderingHints(getRenderingHints()); + g2.setFont(font); + g2.setColor(fontColor); + // in case you want to change the alpha + // g2.setComposite(ac.getInstance(ac.SRC_OVER, 0.50)); + + // the location (arguments.fontDetails.size+y) doesn't really work + // the way I want it to. + g2.drawString(content,javacast("int",x),javacast("int",arguments.fontDetails.size+y)); + + if (outputFile eq "") + { + retVal.img = img; + return retVal; + } else { + saveImage = writeImage(outputFile, img, jpegCompression); + if (saveImage.errorCode gt 0) + { + return saveImage; + } else { + return retVal; + } + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + at = CreateObject("java", "java.awt.geom.AffineTransform"); + op = CreateObject("java", "java.awt.image.AffineTransformOp"); + ac = CreateObject("Java", "java.awt.AlphaComposite"); + gfx = originalImage.getGraphics(); + gfx.setComposite(ac.getInstance(ac.SRC_OVER, alpha)); + + at.init(); + // op.init(at,op.TYPE_BILINEAR); + op.init(at, rh); + + gfx.drawImage(wmImage, op, javaCast("int",arguments.placeAtX), javacast("int", arguments.placeAtY)); + + gfx.dispose(); + + if (outputFile eq "") + { + retVal.img = originalImage; + return retVal; + } else { + saveImage = writeImage(outputFile, originalImage, jpegCompression); + if (saveImage.errorCode gt 0) + { + return saveImage; + } else { + return retVal; + } + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + // convert the image to a specified BufferedImage type and return it + + var width = bImage.getWidth(); + var height = bImage.getHeight(); + var newImage = createObject("java","java.awt.image.BufferedImage").init(javacast("int",width), javacast("int",height), javacast("int",type)); + // int[] rgbArray = new int[width*height]; + var rgbArray = variables.arrObj.newInstance(variables.intClass, javacast("int",width*height)); + + bImage.getRGB( + javacast("int",0), + javacast("int",0), + javacast("int",width), + javacast("int",height), + rgbArray, + javacast("int",0), + javacast("int",width) + ); + newImage.setRGB( + javacast("int",0), + javacast("int",0), + javacast("int",width), + javacast("int",height), + rgbArray, + javacast("int",0), + javacast("int",width) + ); + return newImage; + + + + + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/upload.cfm =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/upload.cfm (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/cfm/upload.cfm 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,31 @@ + + + + + + + + + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/lasso/config.lasso =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/lasso/config.lasso (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/lasso/config.lasso 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,65 @@ +[//lasso +/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * Configuration file for the File Manager Connector for Lasso. + */ + + /*..................................................................... + The connector uses the file tags, which require authentication. Enter a + valid username and password from Lasso admin for a group with file tags + permissions for uploads and the path you define in UserFilesPath below. + */ + + var('connection') = array( + -username='xxxxxxxx', + -password='xxxxxxxx' + ); + + + /*..................................................................... + Set the base path for files that users can upload and browse (relative + to server root). + + Set which file extensions are allowed and/or denied for each file type. + */ + var('config') = map( + 'Enabled' = false, + 'UserFilesPath' = '/userfiles/', + 'Subdirectories' = map( + 'File' = 'File/', + 'Image' = 'Image/', + 'Flash' = 'Flash/', + 'Media' = 'Media/' + ), + 'AllowedExtensions' = map( + 'File' = array('7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip'), + 'Image' = array('bmp','gif','jpeg','jpg','png'), + 'Flash' = array('swf','flv'), + 'Media' = array('aiff','asf','avi','bmp','fla','flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv') + ), + 'DeniedExtensions' = map( + 'File' = array(), + 'Image' = array(), + 'Flash' = array(), + 'Media' = array() + ) + ); +] Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/lasso/connector.lasso =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/lasso/connector.lasso (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/lasso/connector.lasso 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,322 @@ +[//lasso +/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * This is the File Manager Connector for Lasso. + */ + + /*..................................................................... + Include global configuration. See config.lasso for details. + */ + include('config.lasso'); + + + /*..................................................................... + Translate current date/time to GMT for custom header. + */ + var('headerDate') = date_localtogmt(date)->format('%a, %d %b %Y %T GMT'); + + + /*..................................................................... + Convert query string parameters to variables and initialize output. + */ + var( + 'Command' = action_param('Command'), + 'Type' = action_param('Type'), + 'CurrentFolder' = action_param('CurrentFolder'), + 'ServerPath' = action_param('ServerPath'), + 'NewFolderName' = action_param('NewFolderName'), + 'NewFile' = null, + 'NewFileName' = string, + 'OrigFilePath' = string, + 'NewFilePath' = string, + 'commandData' = string, + 'folders' = '\t\n', + 'files' = '\t\n', + 'errorNumber' = integer, + 'responseType' = 'xml', + 'uploadResult' = '0' + ); + + /*..................................................................... + Custom tag sets the HTML response. + */ + + define_tag( + 'htmlreply', + -namespace='fck_', + -priority='replace', + -required='uploadResult', + -optional='NewFilePath', + -type='string', + -description='Sets the HTML response for the FCKEditor File Upload feature.' + ); + $__html_reply__ = '\ + + '; + else; + $__html_reply__ = $__html_reply__ + '\ + window.parent.OnUploadCompleted(' + $uploadResult + '); + + '; + /if; + /define_tag; + + + /*..................................................................... + Calculate the path to the current folder. + */ + $ServerPath == '' ? $ServerPath = $config->find('UserFilesPath'); + + var('currentFolderURL' = $ServerPath + + $config->find('Subdirectories')->find(action_param('Type')) + + $CurrentFolder + ); + + if($CurrentFolder->(Find: '..') || $CurrentFolder->(Find: '\\')); + if($Command == 'FileUpload'); + $responseType = 'html'; + $uploadResult = '102'; + fck_htmlreply( + -uploadResult=$uploadResult + ); + else; + $errorNumber = 102; + $commandData += '\n'; + /if; + else; + + /*..................................................................... + Build the appropriate response per the 'Command' parameter. Wrap the + entire process in an inline for file tag permissions. + */ + inline($connection); + select($Command); + /*............................................................. + List all subdirectories in the 'Current Folder' directory. + */ + case('GetFolders'); + $commandData += '\t\n'; + + iterate(file_listdirectory($currentFolderURL), local('this')); + #this->endswith('/') ? $commandData += '\t\t\n'; + /iterate; + + $commandData += '\t\n'; + + + /*............................................................. + List both files and folders in the 'Current Folder' directory. + Include the file sizes in kilobytes. + */ + case('GetFoldersAndFiles'); + iterate(file_listdirectory($currentFolderURL), local('this')); + if(#this->endswith('/')); + $folders += '\t\t\n'; + else; + local('size') = file_getsize($currentFolderURL + #this) / 1024; + $files += '\t\t\n'; + /if; + /iterate; + + $folders += '\t\n'; + $files += '\t\n'; + + $commandData += $folders + $files; + + + /*............................................................. + Create a directory 'NewFolderName' within the 'Current Folder.' + */ + case('CreateFolder'); + $NewFolderName = (String_ReplaceRegExp: $NewFolderName, -find='\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>', -replace='_'); + var('newFolder' = $currentFolderURL + $NewFolderName + '/'); + file_create($newFolder); + + + /*......................................................... + Map Lasso's file error codes to FCKEditor's error codes. + */ + select(file_currenterror( -errorcode)); + case(0); + $errorNumber = 0; + case( -9983); + $errorNumber = 101; + case( -9976); + $errorNumber = 102; + case( -9977); + $errorNumber = 102; + case( -9961); + $errorNumber = 103; + case; + $errorNumber = 110; + /select; + + $commandData += '\n'; + + + /*............................................................. + Process an uploaded file. + */ + case('FileUpload'); + /*......................................................... + This is the only command that returns an HTML response. + */ + $responseType = 'html'; + + + /*......................................................... + Was a file actually uploaded? + */ + if(file_uploads->size); + $NewFile = file_uploads->get(1); + else; + $uploadResult = '202'; + /if; + + if($uploadResult == '0'); + /*..................................................... + Split the file's extension from the filename in order + to follow the API's naming convention for duplicate + files. (Test.txt, Test(1).txt, Test(2).txt, etc.) + */ + $NewFileName = $NewFile->find('OrigName'); + $NewFileName = (String_ReplaceRegExp: $NewFileName, -find='\\\\|\\/|\\||\\:|\\?|\\*|"|<|>', -replace='_'); + $OrigFilePath = $currentFolderURL + $NewFileName; + $NewFilePath = $OrigFilePath; + local('fileExtension') = '.' + $NewFile->find('OrigExtension'); + #fileExtension = (String_ReplaceRegExp: #fileExtension, -find='\\\\|\\/|\\||\\:|\\?|\\*|"|<|>', -replace='_'); + local('shortFileName') = $NewFileName->removetrailing(#fileExtension)&; + + + /*..................................................... + Make sure the file extension is allowed. + */ + if($config->find('DeniedExtensions')->find($Type) >> $NewFile->find('OrigExtension')); + $uploadResult = '202'; + else; + /*................................................. + Rename the target path until it is unique. + */ + while(file_exists($NewFilePath)); + $NewFilePath = $currentFolderURL + #shortFileName + '(' + loop_count + ')' + #fileExtension; + /while; + + + /*................................................. + Copy the uploaded file to its final location. + */ + file_copy($NewFile->find('path'), $NewFilePath); + + + /*................................................. + Set the error code for the response. Note whether + the file had to be renamed. + */ + select(file_currenterror( -errorcode)); + case(0); + $OrigFilePath != $NewFilePath ? $uploadResult = 201; + case; + $uploadResult = file_currenterror( -errorcode); + /select; + /if; + /if; + fck_htmlreply( + -uploadResult=$uploadResult, + -NewFilePath=$NewFilePath + ); + /select; + /inline; + /if; + + /*..................................................................... + Send a custom header for xml responses. + */ + if($responseType == 'xml'); + header; +] +HTTP/1.0 200 OK +Date: [$headerDate] +Server: Lasso Professional [lasso_version( -lassoversion)] +Expires: Mon, 26 Jul 1997 05:00:00 GMT +Last-Modified: [$headerDate] +Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 +Pragma: no-cache +Keep-Alive: timeout=15, max=98 +Connection: Keep-Alive +Content-Type: text/xml; charset=utf-8 +[//lasso +/header; + + /* + Set the content type encoding for Lasso. + */ + content_type('text/xml; charset=utf-8'); + + /* + Wrap the response as XML and output. + */ + $__html_reply__ = '\ + +'; + + if($errorNumber != '102'); + $__html_reply__ += ''; + /if; + + $__html_reply__ += $commandData + ' +'; + /if; +] Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/lasso/upload.lasso =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/lasso/upload.lasso (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/lasso/upload.lasso 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,191 @@ +[//lasso +/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * This is the "File Uploader" for Lasso. + */ + + /*..................................................................... + Include global configuration. See config.lasso for details. + */ + include('config.lasso'); + + + /*..................................................................... + Convert query string parameters to variables and initialize output. + */ + var( + 'Type' = action_param('Type'), + 'CurrentFolder' = action_param('CurrentFolder'), + 'ServerPath' = action_param('ServerPath'), + 'NewFile' = null, + 'NewFileName' = string, + 'OrigFilePath' = string, + 'NewFilePath' = string, + 'errorNumber' = 0, + 'customMsg' = '' + ); + + $Type == '' ? $Type = 'File'; + + + /*..................................................................... + Calculate the path to the current folder. + */ + $ServerPath == '' ? $ServerPath = $config->find('UserFilesPath'); + + var('currentFolderURL' = $ServerPath + + $config->find('Subdirectories')->find(action_param('Type')) + + action_param('CurrentFolder') + ); + + /*..................................................................... + Custom tag sets the HTML response. + */ + + define_tag( + 'sendresults', + -namespace='fck_', + -priority='replace', + -required='errorNumber', + -type='integer', + -optional='fileUrl', + -type='string', + -optional='fileName', + -type='string', + -optional='customMsg', + -type='string', + -description='Sets the HTML response for the FCKEditor Quick Upload feature.' + ); + $__html_reply__ = '\ + + '; + /define_tag; + + if($CurrentFolder->(Find: '..') || $CurrentFolder->(Find: '\\')); + $errorNumber = 102; + /if; + + if($config->find('Enabled')); + /*................................................................. + Process an uploaded file. + */ + inline($connection); + /*............................................................. + Was a file actually uploaded? + */ + if($errorNumber != '102'); + file_uploads->size ? $NewFile = file_uploads->get(1) | $errorNumber = 202; + /if; + + if($errorNumber == 0); + /*......................................................... + Split the file's extension from the filename in order + to follow the API's naming convention for duplicate + files. (Test.txt, Test(1).txt, Test(2).txt, etc.) + */ + $NewFileName = $NewFile->find('OrigName'); + $OrigFilePath = $currentFolderURL + $NewFileName; + $NewFilePath = $OrigFilePath; + local('fileExtension') = '.' + $NewFile->find('OrigExtension'); + local('shortFileName') = $NewFileName->removetrailing(#fileExtension)&; + + + /*......................................................... + Make sure the file extension is allowed. + */ + + if($config->find('DeniedExtensions')->find($Type) >> $NewFile->find('OrigExtension')); + $errorNumber = 202; + else; + /*..................................................... + Rename the target path until it is unique. + */ + while(file_exists($NewFilePath)); + $NewFileName = #shortFileName + '(' + loop_count + ')' + #fileExtension; + $NewFilePath = $currentFolderURL + $NewFileName; + /while; + + + /*..................................................... + Copy the uploaded file to its final location. + */ + file_copy($NewFile->find('path'), $NewFilePath); + + + /*..................................................... + Set the error code for the response. + */ + select(file_currenterror( -errorcode)); + case(0); + $OrigFilePath != $NewFilePath ? $errorNumber = 201; + case; + $errorNumber = 202; + /select; + /if; + /if; + /inline; + else; + $errorNumber = 1; + $customMsg = 'This file uploader is disabled. Please check the "editor/filemanager/upload/lasso/config.lasso" file.'; + /if; + + fck_sendresults( + -errorNumber=$errorNumber, + -fileUrl=$NewFilePath, + -fileName=$NewFileName, + -customMsg=$customMsg + ); +] Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/basexml.pl =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/basexml.pl (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/basexml.pl 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,63 @@ +##### +# FCKeditor - The text editor for Internet - http://www.fckeditor.net +# Copyright (C) 2003-2008 Frederico Caldeira Knabben +# +# == BEGIN LICENSE == +# +# Licensed under the terms of any of the following licenses at your +# choice: +# +# - GNU General Public License Version 2 or later (the "GPL") +# http://www.gnu.org/licenses/gpl.html +# +# - GNU Lesser General Public License Version 2.1 or later (the "LGPL") +# http://www.gnu.org/licenses/lgpl.html +# +# - Mozilla Public License Version 1.1 or later (the "MPL") +# http://www.mozilla.org/MPL/MPL-1.1.html +# +# == END LICENSE == +# +# This is the File Manager Connector for Perl. +##### + +sub CreateXmlHeader +{ + local($command,$resourceType,$currentFolder) = @_; + + # Create the XML document header. + print ''; + + # Create the main "Connector" node. + print ''; + + # Add the current folder node. + print ''; +} + +sub CreateXmlFooter +{ + print ''; +} + +sub SendError +{ + local( $number, $text ) = @_; + + print << "_HTML_HEAD_"; +Content-Type:text/xml; charset=utf-8 +Pragma: no-cache +Cache-Control: no-cache +Expires: Thu, 01 Dec 1994 16:00:00 GMT + +_HTML_HEAD_ + + # Create the XML document header + print '' ; + + print '' ; + + exit ; +} + +1; Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/commands.pl =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/commands.pl (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/commands.pl 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,214 @@ +##### +# FCKeditor - The text editor for Internet - http://www.fckeditor.net +# Copyright (C) 2003-2008 Frederico Caldeira Knabben +# +# == BEGIN LICENSE == +# +# Licensed under the terms of any of the following licenses at your +# choice: +# +# - GNU General Public License Version 2 or later (the "GPL") +# http://www.gnu.org/licenses/gpl.html +# +# - GNU Lesser General Public License Version 2.1 or later (the "LGPL") +# http://www.gnu.org/licenses/lgpl.html +# +# - Mozilla Public License Version 1.1 or later (the "MPL") +# http://www.mozilla.org/MPL/MPL-1.1.html +# +# == END LICENSE == +# +# This is the File Manager Connector for Perl. +##### + +sub GetFolders +{ + + local($resourceType, $currentFolder) = @_; + + # Map the virtual path to the local server path. + $sServerDir = &ServerMapFolder($resourceType, $currentFolder); + print ""; # Open the "Folders" node. + + opendir(DIR,"$sServerDir"); + @files = grep(!/^\.\.?$/,readdir(DIR)); + closedir(DIR); + + foreach $sFile (@files) { + if($sFile != '.' && $sFile != '..' && (-d "$sServerDir$sFile")) { + $cnv_filename = &ConvertToXmlAttribute($sFile); + print ''; + } + } + print ""; # Close the "Folders" node. +} + +sub GetFoldersAndFiles +{ + + local($resourceType, $currentFolder) = @_; + # Map the virtual path to the local server path. + $sServerDir = &ServerMapFolder($resourceType,$currentFolder); + + # Initialize the output buffers for "Folders" and "Files". + $sFolders = ''; + $sFiles = ''; + + opendir(DIR,"$sServerDir"); + @files = grep(!/^\.\.?$/,readdir(DIR)); + closedir(DIR); + + foreach $sFile (@files) { + if($sFile ne '.' && $sFile ne '..') { + if(-d "$sServerDir$sFile") { + $cnv_filename = &ConvertToXmlAttribute($sFile); + $sFolders .= '' ; + } else { + ($iFileSize,$refdate,$filedate,$fileperm) = (stat("$sServerDir$sFile"))[7,8,9,2]; + if($iFileSize > 0) { + $iFileSize = int($iFileSize / 1024); + if($iFileSize < 1) { + $iFileSize = 1; + } + } + $cnv_filename = &ConvertToXmlAttribute($sFile); + $sFiles .= '' ; + } + } + } + print $sFolders ; + print ''; # Close the "Folders" node. + print $sFiles ; + print ''; # Close the "Files" node. +} + +sub CreateFolder +{ + + local($resourceType, $currentFolder) = @_; + $sErrorNumber = '0' ; + $sErrorMsg = '' ; + + if($FORM{'NewFolderName'} ne "") { + $sNewFolderName = $FORM{'NewFolderName'}; + $sNewFolderName =~ s/\.|\\|\/|\||\:|\?|\*|\"|<|>|[[:cntrl:]]/_/g; + # Map the virtual path to the local server path of the current folder. + $sServerDir = &ServerMapFolder($resourceType, $currentFolder); + if(-w $sServerDir) { + $sServerDir .= $sNewFolderName; + $sErrorMsg = &CreateServerFolder($sServerDir); + if($sErrorMsg == 0) { + $sErrorNumber = '0'; + } elsif($sErrorMsg eq 'Invalid argument' || $sErrorMsg eq 'No such file or directory') { + $sErrorNumber = '102'; #// Path too long. + } else { + $sErrorNumber = '110'; + } + } else { + $sErrorNumber = '103'; + } + } else { + $sErrorNumber = '102' ; + } + # Create the "Error" node. + $cnv_errmsg = &ConvertToXmlAttribute($sErrorMsg); + print ''; +} + +sub FileUpload +{ +eval("use File::Copy;"); + + local($resourceType, $currentFolder) = @_; + + $sErrorNumber = '0' ; + $sFileName = '' ; + if($new_fname) { + # Map the virtual path to the local server path. + $sServerDir = &ServerMapFolder($resourceType,$currentFolder); + + # Get the uploaded file name. + $sFileName = $new_fname; + $sFileName =~ s/\\|\/|\||\:|\?|\*|\"|<|>|[[:cntrl:]]/_/g; + $sOriginalFileName = $sFileName; + + $iCounter = 0; + while(1) { + $sFilePath = $sServerDir . $sFileName; + if(-e $sFilePath) { + $iCounter++ ; + ($path,$BaseName,$ext) = &RemoveExtension($sOriginalFileName); + $sFileName = $BaseName . '(' . $iCounter . ').' . $ext; + $sErrorNumber = '201'; + } else { + copy("$img_dir/$new_fname","$sFilePath"); + if (defined $CHMOD_ON_UPLOAD) { + if ($CHMOD_ON_UPLOAD) { + umask(000); + chmod($CHMOD_ON_UPLOAD,$sFilePath); + } + } + else { + umask(000); + chmod(0777,$sFilePath); + } + unlink("$img_dir/$new_fname"); + last; + } + } + } else { + $sErrorNumber = '202' ; + } + $sFileName =~ s/"/\\"/g; + + SendUploadResults($sErrorNumber, $resourceType.$currentFolder.$sFileName, $sFileName, ''); +} + +sub SendUploadResults +{ + + local($sErrorNumber, $sFileUrl, $sFileName, $customMsg) = @_; + + print < +// Automatically detect the correct document.domain (#1919). +(function() +{ + var d = document.domain ; + + while ( true ) + { + // Test if we can access a parent property. + try + { + var test = window.top.opener.document.domain ; + break ; + } + catch( e ) {} + + // Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ... + d = d.replace( /.*?(?:\\.|\$)/, '' ) ; + + if ( d.length == 0 ) + break ; // It was not able to detect the domain. + + try + { + document.domain = d ; + } + catch (e) + { + break ; + } + } +})() ; + +EOF + print 'window.parent.OnUploadCompleted(' . $sErrorNumber . ',"' . JS_cnv($sFileUrl) . '","' . JS_cnv($sFileName) . '","' . JS_cnv($customMsg) . '") ;'; + print ''; + exit ; +} + +1; Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/connector.cgi =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/connector.cgi (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/connector.cgi 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,136 @@ +#!/usr/bin/env perl + +##### +# FCKeditor - The text editor for Internet - http://www.fckeditor.net +# Copyright (C) 2003-2008 Frederico Caldeira Knabben +# +# == BEGIN LICENSE == +# +# Licensed under the terms of any of the following licenses at your +# choice: +# +# - GNU General Public License Version 2 or later (the "GPL") +# http://www.gnu.org/licenses/gpl.html +# +# - GNU Lesser General Public License Version 2.1 or later (the "LGPL") +# http://www.gnu.org/licenses/lgpl.html +# +# - Mozilla Public License Version 1.1 or later (the "MPL") +# http://www.mozilla.org/MPL/MPL-1.1.html +# +# == END LICENSE == +# +# This is the File Manager Connector for Perl. +##### + +## +# ATTENTION: To enable this connector, look for the "SECURITY" comment in this file. +## + +## START: Hack for Windows (Not important to understand the editor code... Perl specific). +if(Windows_check()) { + chdir(GetScriptPath($0)); +} + +sub Windows_check +{ + # IIS,PWS(NT/95) + $www_server_os = $^O; + # Win98 & NT(SP4) + if($www_server_os eq "") { $www_server_os= $ENV{'OS'}; } + # AnHTTPd/Omni/IIS + if($ENV{'SERVER_SOFTWARE'} =~ /AnWeb|Omni|IIS\//i) { $www_server_os= 'win'; } + # Win Apache + if($ENV{'WINDIR'} ne "") { $www_server_os= 'win'; } + if($www_server_os=~ /win/i) { return(1); } + return(0); +} + +sub GetScriptPath { + local($path) = @_; + if($path =~ /[\:\/\\]/) { $path =~ s/(.*?)[\/\\][^\/\\]+$/$1/; } else { $path = '.'; } + $path; +} +## END: Hack for IIS + +require 'util.pl'; +require 'io.pl'; +require 'basexml.pl'; +require 'commands.pl'; +require 'upload_fck.pl'; + +## +# SECURITY: REMOVE/COMMENT THE FOLLOWING LINE TO ENABLE THIS CONNECTOR. +## + &SendError( 1, 'This connector is disabled. Please check the "editor/filemanager/connectors/perl/connector.cgi" file' ) ; + + &read_input(); + + if($FORM{'ServerPath'} ne "") { + $GLOBALS{'UserFilesPath'} = $FORM{'ServerPath'}; + if(!($GLOBALS{'UserFilesPath'} =~ /\/$/)) { + $GLOBALS{'UserFilesPath'} .= '/' ; + } + } else { + $GLOBALS{'UserFilesPath'} = '/userfiles/'; + } + + # Map the "UserFiles" path to a local directory. + $rootpath = &GetRootPath(); + $GLOBALS{'UserFilesDirectory'} = $rootpath . $GLOBALS{'UserFilesPath'}; + + &DoResponse(); + +sub DoResponse +{ + + if($FORM{'Command'} eq "" || $FORM{'Type'} eq "" || $FORM{'CurrentFolder'} eq "") { + return ; + } + # Get the main request informaiton. + $sCommand = $FORM{'Command'}; + $sResourceType = $FORM{'Type'}; + $sCurrentFolder = $FORM{'CurrentFolder'}; + + # Check the current folder syntax (must begin and start with a slash). + if(!($sCurrentFolder =~ /\/$/)) { + $sCurrentFolder .= '/'; + } + if(!($sCurrentFolder =~ /^\//)) { + $sCurrentFolder = '/' . $sCurrentFolder; + } + + # Check for invalid folder paths (..) + if ( $sCurrentFolder =~ /(?:\.\.|\\)/ ) { + SendError( 102, "" ) ; + } + + # File Upload doesn't have to Return XML, so it must be intercepted before anything. + if($sCommand eq 'FileUpload') { + FileUpload($sResourceType,$sCurrentFolder); + return ; + } + + print << "_HTML_HEAD_"; +Content-Type:text/xml; charset=utf-8 +Pragma: no-cache +Cache-Control: no-cache +Expires: Thu, 01 Dec 1994 16:00:00 GMT + +_HTML_HEAD_ + + &CreateXmlHeader($sCommand,$sResourceType,$sCurrentFolder); + + # Execute the required command. + if($sCommand eq 'GetFolders') { + &GetFolders($sResourceType,$sCurrentFolder); + } elsif($sCommand eq 'GetFoldersAndFiles') { + &GetFoldersAndFiles($sResourceType,$sCurrentFolder); + } elsif($sCommand eq 'CreateFolder') { + &CreateFolder($sResourceType,$sCurrentFolder); + } + + &CreateXmlFooter(); + + exit ; +} Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/io.pl =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/io.pl (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/io.pl 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,141 @@ +##### +# FCKeditor - The text editor for Internet - http://www.fckeditor.net +# Copyright (C) 2003-2008 Frederico Caldeira Knabben +# +# == BEGIN LICENSE == +# +# Licensed under the terms of any of the following licenses at your +# choice: +# +# - GNU General Public License Version 2 or later (the "GPL") +# http://www.gnu.org/licenses/gpl.html +# +# - GNU Lesser General Public License Version 2.1 or later (the "LGPL") +# http://www.gnu.org/licenses/lgpl.html +# +# - Mozilla Public License Version 1.1 or later (the "MPL") +# http://www.mozilla.org/MPL/MPL-1.1.html +# +# == END LICENSE == +# +# This is the File Manager Connector for Perl. +##### + +sub GetUrlFromPath +{ + local($resourceType, $folderPath) = @_; + + if($resourceType eq '') { + $rmpath = &RemoveFromEnd($GLOBALS{'UserFilesPath'},'/'); + return("$rmpath$folderPath"); + } else { + return("$GLOBALS{'UserFilesPath'}$resourceType$folderPath"); + } +} + +sub RemoveExtension +{ + local($fileName) = @_; + local($path, $base, $ext); + if($fileName !~ /\./) { + $fileName .= '.'; + } + if($fileName =~ /([^\\\/]*)\.(.*)$/) { + $base = $1; + $ext = $2; + if($fileName =~ /(.*)$base\.$ext$/) { + $path = $1; + } + } + return($path,$base,$ext); + +} + +sub ServerMapFolder +{ + local($resourceType,$folderPath) = @_; + + # Get the resource type directory. + $sResourceTypePath = $GLOBALS{'UserFilesDirectory'} . $resourceType . '/'; + + # Ensure that the directory exists. + &CreateServerFolder($sResourceTypePath); + + # Return the resource type directory combined with the required path. + $rmpath = &RemoveFromStart($folderPath,'/'); + return("$sResourceTypePath$rmpath"); +} + +sub GetParentFolder +{ + local($folderPath) = @_; + + $folderPath =~ s/[\/][^\/]+[\/]?$//g; + return $folderPath; +} + +sub CreateServerFolder +{ + local($folderPath) = @_; + + $sParent = &GetParentFolder($folderPath); + # Check if the parent exists, or create it. + if(!(-e $sParent)) { + $sErrorMsg = &CreateServerFolder($sParent); + if($sErrorMsg == 1) { + return(1); + } + } + if(!(-e $folderPath)) { + if (defined $CHMOD_ON_FOLDER_CREATE && !$CHMOD_ON_FOLDER_CREATE) { + mkdir("$folderPath"); + } + else { + umask(000); + if (defined $CHMOD_ON_FOLDER_CREATE) { + mkdir("$folderPath",$CHMOD_ON_FOLDER_CREATE); + } + else { + mkdir("$folderPath",0777); + } + } + + return(0); + } else { + return(1); + } +} + +sub GetRootPath +{ +#use Cwd; + +# my $dir = getcwd; +# print $dir; +# $dir =~ s/$ENV{'DOCUMENT_ROOT'}//g; +# print $dir; +# return($dir); + +# $wk = $0; +# $wk =~ s/\/connector\.cgi//g; +# if($wk) { +# $current_dir = $wk; +# } else { +# $current_dir = `pwd`; +# } +# return($current_dir); +use Cwd; + + if($ENV{'DOCUMENT_ROOT'}) { + $dir = $ENV{'DOCUMENT_ROOT'}; + } else { + my $dir = getcwd; + $workdir =~ s/\/connector\.cgi//g; + $dir =~ s/$workdir//g; + } + return($dir); + + + +} +1; Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/upload.cgi =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/upload.cgi (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/upload.cgi 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,117 @@ +#!/usr/bin/env perl + +##### +# FCKeditor - The text editor for Internet - http://www.fckeditor.net +# Copyright (C) 2003-2008 Frederico Caldeira Knabben +# +# == BEGIN LICENSE == +# +# Licensed under the terms of any of the following licenses at your +# choice: +# +# - GNU General Public License Version 2 or later (the "GPL") +# http://www.gnu.org/licenses/gpl.html +# +# - GNU Lesser General Public License Version 2.1 or later (the "LGPL") +# http://www.gnu.org/licenses/lgpl.html +# +# - Mozilla Public License Version 1.1 or later (the "MPL") +# http://www.mozilla.org/MPL/MPL-1.1.html +# +# == END LICENSE == +# +# This is the File Manager Connector for Perl. +##### + +## +# ATTENTION: To enable this connector, look for the "SECURITY" comment in this file. +## + +## START: Hack for Windows (Not important to understand the editor code... Perl specific). +if(Windows_check()) { + chdir(GetScriptPath($0)); +} + +sub Windows_check +{ + # IIS,PWS(NT/95) + $www_server_os = $^O; + # Win98 & NT(SP4) + if($www_server_os eq "") { $www_server_os= $ENV{'OS'}; } + # AnHTTPd/Omni/IIS + if($ENV{'SERVER_SOFTWARE'} =~ /AnWeb|Omni|IIS\//i) { $www_server_os= 'win'; } + # Win Apache + if($ENV{'WINDIR'} ne "") { $www_server_os= 'win'; } + if($www_server_os=~ /win/i) { return(1); } + return(0); +} + +sub GetScriptPath { + local($path) = @_; + if($path =~ /[\:\/\\]/) { $path =~ s/(.*?)[\/\\][^\/\\]+$/$1/; } else { $path = '.'; } + $path; +} +## END: Hack for IIS + +require 'util.pl'; +require 'io.pl'; +require 'basexml.pl'; +require 'commands.pl'; +require 'upload_fck.pl'; + +## +# SECURITY: REMOVE/COMMENT THE FOLLOWING LINE TO ENABLE THIS CONNECTOR. +## + &SendUploadResults(1, '', '', 'This connector is disabled. Please check the "editor/filemanager/connectors/perl/upload.cgi" file' ) ; + + &read_input(); + + if($FORM{'ServerPath'} ne "") { + $GLOBALS{'UserFilesPath'} = $FORM{'ServerPath'}; + if(!($GLOBALS{'UserFilesPath'} =~ /\/$/)) { + $GLOBALS{'UserFilesPath'} .= '/' ; + } + } else { + $GLOBALS{'UserFilesPath'} = '/userfiles/'; + } + + # Map the "UserFiles" path to a local directory. + $rootpath = &GetRootPath(); + $GLOBALS{'UserFilesDirectory'} = $rootpath . $GLOBALS{'UserFilesPath'}; + + &DoResponse(); + +sub DoResponse +{ + # Get the main request information. + $sCommand = 'FileUpload'; #$FORM{'Command'}; + $sResourceType = $FORM{'Type'}; + $sCurrentFolder = $FORM{'CurrentFolder'}; + + if ($sResourceType eq '') { + $sResourceType = 'File' ; + } + if ($sCurrentFolder eq '') { + $sCurrentFolder = '/' ; + } + + # Check the current folder syntax (must begin and start with a slash). + if(!($sCurrentFolder =~ /\/$/)) { + $sCurrentFolder .= '/'; + } + if(!($sCurrentFolder =~ /^\//)) { + $sCurrentFolder = '/' . $sCurrentFolder; + } + + # Check for invalid folder paths (..) + if ( $sCurrentFolder =~ /(?:\.\.|\\)/ ) { + SendError( 102, "" ) ; + } + + # File Upload doesn't have to Return XML, so it must be intercepted before anything. + if($sCommand eq 'FileUpload') { + FileUpload($sResourceType,$sCurrentFolder); + return ; + } + +} Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/upload_fck.pl =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/upload_fck.pl (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/upload_fck.pl 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,686 @@ +##### +# FCKeditor - The text editor for Internet - http://www.fckeditor.net +# Copyright (C) 2003-2008 Frederico Caldeira Knabben +# +# == BEGIN LICENSE == +# +# Licensed under the terms of any of the following licenses at your +# choice: +# +# - GNU General Public License Version 2 or later (the "GPL") +# http://www.gnu.org/licenses/gpl.html +# +# - GNU Lesser General Public License Version 2.1 or later (the "LGPL") +# http://www.gnu.org/licenses/lgpl.html +# +# - Mozilla Public License Version 1.1 or later (the "MPL") +# http://www.mozilla.org/MPL/MPL-1.1.html +# +# == END LICENSE == +# +# This is the File Manager Connector for Perl. +##### + +# image data save dir +$img_dir = './temp/'; + + +# File size max(unit KB) +$MAX_CONTENT_SIZE = 30000; + +# After file is uploaded, sometimes it is required to change its permissions +# so that it was possible to access it at the later time. +# If possible, it is recommended to set more restrictive permissions, like 0755. +# Set to 0 to disable this feature. +$CHMOD_ON_UPLOAD = 0777; + +# See comments above. +# Used when creating folders that does not exist. +$CHMOD_ON_FOLDER_CREATE = 0755; + +# Filelock (1=use,0=not use) +$PM{'flock'} = '1'; + + +# upload Content-Type list +my %UPLOAD_CONTENT_TYPE_LIST = ( + 'image/(x-)?png' => 'png', # PNG image + 'image/p?jpe?g' => 'jpg', # JPEG image + 'image/gif' => 'gif', # GIF image + 'image/x-xbitmap' => 'xbm', # XBM image + + 'image/(x-(MS-)?)?bmp' => 'bmp', # Windows BMP image + 'image/pict' => 'pict', # Macintosh PICT image + 'image/tiff' => 'tif', # TIFF image + 'application/pdf' => 'pdf', # PDF image + 'application/x-shockwave-flash' => 'swf', # Shockwave Flash + + 'video/(x-)?msvideo' => 'avi', # Microsoft Video + 'video/quicktime' => 'mov', # QuickTime Video + 'video/mpeg' => 'mpeg', # MPEG Video + 'video/x-mpeg2' => 'mpv2', # MPEG2 Video + + 'audio/(x-)?midi?' => 'mid', # MIDI Audio + 'audio/(x-)?wav' => 'wav', # WAV Audio + 'audio/basic' => 'au', # ULAW Audio + 'audio/mpeg' => 'mpga', # MPEG Audio + + 'application/(x-)?zip(-compressed)?' => 'zip', # ZIP Compress + + 'text/html' => 'html', # HTML + 'text/plain' => 'txt', # TEXT + '(?:application|text)/(?:rtf|richtext)' => 'rtf', # RichText + + 'application/msword' => 'doc', # Microsoft Word + 'application/vnd.ms-excel' => 'xls', # Microsoft Excel + + '' +); + +# Upload is permitted. +# A regular expression is possible. +my %UPLOAD_EXT_LIST = ( + 'png' => 'PNG image', + 'p?jpe?g|jpe|jfif|pjp' => 'JPEG image', + 'gif' => 'GIF image', + 'xbm' => 'XBM image', + + 'bmp|dib|rle' => 'Windows BMP image', + 'pi?ct' => 'Macintosh PICT image', + 'tiff?' => 'TIFF image', + 'pdf' => 'PDF image', + 'swf' => 'Shockwave Flash', + + 'avi' => 'Microsoft Video', + 'moo?v|qt' => 'QuickTime Video', + 'm(p(e?gv?|e|v)|1v)' => 'MPEG Video', + 'mp(v2|2v)' => 'MPEG2 Video', + + 'midi?|kar|smf|rmi|mff' => 'MIDI Audio', + 'wav' => 'WAVE Audio', + 'au|snd' => 'ULAW Audio', + 'mp(e?ga|2|a|3)|abs' => 'MPEG Audio', + + 'zip' => 'ZIP Compress', + 'lzh' => 'LZH Compress', + 'cab' => 'CAB Compress', + + 'd?html?' => 'HTML', + 'rtf|rtx' => 'RichText', + 'txt|text' => 'Text', + + '' +); + + +# sjis or euc +my $CHARCODE = 'sjis'; + +$TRANS_2BYTE_CODE = 0; + +############################################################################## +# Summary +# +# Form Read input +# +# Parameters +# Returns +# Memo +############################################################################## +sub read_input +{ +eval("use File::Copy;"); +eval("use File::Path;"); + + my ($FORM) = @_; + + if (defined $CHMOD_ON_FOLDER_CREATE && !$CHMOD_ON_FOLDER_CREATE) { + mkdir("$img_dir"); + } + else { + umask(000); + if (defined $CHMOD_ON_FOLDER_CREATE) { + mkdir("$img_dir",$CHMOD_ON_FOLDER_CREATE); + } + else { + mkdir("$img_dir",0777); + } + } + + undef $img_data_exists; + undef @NEWFNAMES; + undef @NEWFNAME_DATA; + + if($ENV{'CONTENT_LENGTH'} > 10000000 || $ENV{'CONTENT_LENGTH'} > $MAX_CONTENT_SIZE * 1024) { + &upload_error( + 'Size Error', + sprintf( + "Transmitting size is too large.MAX %d KB Now Size %d KB(%d bytes Over)", + $MAX_CONTENT_SIZE, + int($ENV{'CONTENT_LENGTH'} / 1024), + $ENV{'CONTENT_LENGTH'} - $MAX_CONTENT_SIZE * 1024 + ) + ); + } + + my $Buffer; + if($ENV{'CONTENT_TYPE'} =~ /multipart\/form-data/) { + # METHOD POST only + return unless($ENV{'CONTENT_LENGTH'}); + + binmode(STDIN); + # STDIN A pause character is detected.'(MacIE3.0 boundary of $ENV{'CONTENT_TYPE'} cannot be trusted.) + my $Boundary = ; + $Boundary =~ s/\x0D\x0A//; + $Boundary = quotemeta($Boundary); + while() { + if(/^\s*Content-Disposition:/i) { + my($name,$ContentType,$FileName); + # form data get + if(/\bname="([^"]+)"/i || /\bname=([^\s:;]+)/i) { + $name = $1; + $name =~ tr/+/ /; + $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; + &Encode(\$name); + } + if(/\bfilename="([^"]*)"/i || /\bfilename=([^\s:;]*)/i) { + $FileName = $1 || 'unknown'; + } + # head read + while() { + last if(! /\w/); + if(/^\s*Content-Type:\s*"([^"]+)"/i || /^\s*Content-Type:\s*([^\s:;]+)/i) { + $ContentType = $1; + } + } + # body read + $value = ""; + while() { + last if(/^$Boundary/o); + $value .= $_; + }; + $lastline = $_; + $value =~s /\x0D\x0A$//; + if($value ne '') { + if($FileName || $ContentType) { + $img_data_exists = 1; + ( + $FileName, # + $Ext, # + $Length, # + $ImageWidth, # + $ImageHeight, # + $ContentName # + ) = &CheckContentType(\$value,$FileName,$ContentType); + + $FORM{$name} = $FileName; + $new_fname = $FileName; + push(@NEWFNAME_DATA,"$FileName\t$Ext\t$Length\t$ImageWidth\t$ImageHeight\t$ContentName"); + + # Multi-upload correspondence + push(@NEWFNAMES,$new_fname); + open(OUT,">$img_dir/$new_fname"); + binmode(OUT); + eval "flock(OUT,2);" if($PM{'flock'} == 1); + print OUT $value; + eval "flock(OUT,8);" if($PM{'flock'} == 1); + close(OUT); + + } elsif($name) { + $value =~ tr/+/ /; + $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; + &Encode(\$value,'trans'); + $FORM{$name} .= "\0" if(defined($FORM{$name})); + $FORM{$name} .= $value; + } + } + }; + last if($lastline =~ /^$Boundary\-\-/o); + } + } elsif($ENV{'CONTENT_LENGTH'}) { + read(STDIN,$Buffer,$ENV{'CONTENT_LENGTH'}); + } + foreach(split(/&/,$Buffer),split(/&/,$ENV{'QUERY_STRING'})) { + my($name, $value) = split(/=/); + $name =~ tr/+/ /; + $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; + $value =~ tr/+/ /; + $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; + + &Encode(\$name); + &Encode(\$value,'trans'); + $FORM{$name} .= "\0" if(defined($FORM{$name})); + $FORM{$name} .= $value; + + } + +} + +############################################################################## +# Summary +# +# CheckContentType +# +# Parameters +# Returns +# Memo +############################################################################## +sub CheckContentType +{ + + my($DATA,$FileName,$ContentType) = @_; + my($Ext,$ImageWidth,$ImageHeight,$ContentName,$Infomation); + my $DataLength = length($$DATA); + + # An unknown file type + + $_ = $ContentType; + my $UnknownType = ( + !$_ + || /^application\/(x-)?macbinary$/i + || /^application\/applefile$/i + || /^application\/octet-stream$/i + || /^text\/plane$/i + || /^x-unknown-content-type/i + ); + + # MacBinary(Mac Unnecessary data are deleted.) + if($UnknownType || $ENV{'HTTP_USER_AGENT'} =~ /Macintosh|Mac_/) { + if($DataLength > 128 && !unpack("C",substr($$DATA,0,1)) && !unpack("C",substr($$DATA,74,1)) && !unpack("C",substr($$DATA,82,1)) ) { + my $MacBinary_ForkLength = unpack("N", substr($$DATA, 83, 4)); # ForkLength Get + my $MacBinary_FileName = quotemeta(substr($$DATA, 2, unpack("C",substr($$DATA, 1, 1)))); + if($MacBinary_FileName && $MacBinary_ForkLength && $DataLength >= $MacBinary_ForkLength + 128 + && ($FileName =~ /$MacBinary_FileName/i || substr($$DATA,102,4) eq 'mBIN')) { # DATA TOP 128byte MacBinary!! + $$DATA = substr($$DATA,128,$MacBinary_ForkLength); + my $ResourceLength = $DataLength - $MacBinary_ForkLength - 128; + $DataLength = $MacBinary_ForkLength; + } + } + } + + # A file name is changed into EUC. +# &jcode::convert(\$FileName,'euc',$FormCodeDefault); +# &jcode::h2z_euc(\$FileName); + $FileName =~ s/^.*\\//; # Windows, Mac + $FileName =~ s/^.*\///; # UNIX + $FileName =~ s/&/&/g; + $FileName =~ s/"/"/g; + $FileName =~ s//>/g; +# +# if($CHARCODE ne 'euc') { +# &jcode::convert(\$FileName,$CHARCODE,'euc'); +# } + + # An extension is extracted and it changes into a small letter. + my $FileExt; + if($FileName =~ /\.(\w+)$/) { + $FileExt = $1; + $FileExt =~ tr/A-Z/a-z/; + } + + # Executable file detection (ban on upload) + if($$DATA =~ /^MZ/) { + $Ext = 'exe'; + } + # text + if(!$Ext && ($UnknownType || $ContentType =~ /^text\//i || $ContentType =~ /^application\/(?:rtf|richtext)$/i || $ContentType =~ /^image\/x-xbitmap$/i) + && ! $$DATA =~ /[\000-\006\177\377]/) { +# $$DATA =~ s/\x0D\x0A/\n/g; +# $$DATA =~ tr/\x0D\x0A/\n\n/; +# +# if( +# $$DATA =~ /<\s*SCRIPT(?:.|\n)*?>/i +# || $$DATA =~ /<\s*(?:.|\n)*?\bONLOAD\s*=(?:.|\n)*?>/i +# || $$DATA =~ /<\s*(?:.|\n)*?\bONCLICK\s*=(?:.|\n)*?>/i +# ) { +# $Infomation = '(JavaScript contains)'; +# } +# if($$DATA =~ /<\s*TABLE(?:.|\n)*?>/i +# || $$DATA =~ /<\s*BLINK(?:.|\n)*?>/i +# || $$DATA =~ /<\s*MARQUEE(?:.|\n)*?>/i +# || $$DATA =~ /<\s*OBJECT(?:.|\n)*?>/i +# || $$DATA =~ /<\s*EMBED(?:.|\n)*?>/i +# || $$DATA =~ /<\s*FRAME(?:.|\n)*?>/i +# || $$DATA =~ /<\s*APPLET(?:.|\n)*?>/i +# || $$DATA =~ /<\s*FORM(?:.|\n)*?>/i +# || $$DATA =~ /<\s*(?:.|\n)*?\bSRC\s*=(?:.|\n)*?>/i +# || $$DATA =~ /<\s*(?:.|\n)*?\bDYNSRC\s*=(?:.|\n)*?>/i +# ) { +# $Infomation = '(the HTML tag which is not safe is included)'; +# } + + if($FileExt =~ /^txt$/i || $FileExt =~ /^cgi$/i || $FileExt =~ /^pl$/i) { # Text File + $Ext = 'txt'; + } elsif($ContentType =~ /^text\/html$/i || $FileExt =~ /html?/i || $$DATA =~ /<\s*HTML(?:.|\n)*?>/i) { # HTML File + $Ext = 'html'; + } elsif($ContentType =~ /^image\/x-xbitmap$/i || $FileExt =~ /^xbm$/i) { # XBM(x-BitMap) Image + my $XbmName = $1; + my ($XbmWidth, $XbmHeight); + if($$DATA =~ /\#define\s*$XbmName\_width\s*(\d+)/i) { + $XbmWidth = $1; + } + if($$DATA =~ /\#define\s*$XbmName\_height\s*(\d+)/i) { + $XbmHeight = $1; + } + if($XbmWidth && $XbmHeight) { + $Ext = 'xbm'; + $ImageWidth = $XbmWidth; + $ImageHeight = $XbmHeight; + } + } else { # + $Ext = 'txt'; + } + } + + # image + if(!$Ext && ($UnknownType || $ContentType =~ /^image\//i)) { + # PNG + if($$DATA =~ /^\x89PNG\x0D\x0A\x1A\x0A/) { + if(substr($$DATA, 12, 4) eq 'IHDR') { + $Ext = 'png'; + ($ImageWidth, $ImageHeight) = unpack("N2", substr($$DATA, 16, 8)); + } + } elsif($$DATA =~ /^GIF8(?:9|7)a/) { # GIF89a(modified), GIF89a, GIF87a + $Ext = 'gif'; + ($ImageWidth, $ImageHeight) = unpack("v2", substr($$DATA, 6, 4)); + } elsif($$DATA =~ /^II\x2a\x00\x08\x00\x00\x00/ || $$DATA =~ /^MM\x00\x2a\x00\x00\x00\x08/) { # TIFF + $Ext = 'tif'; + } elsif($$DATA =~ /^BM/) { # BMP + $Ext = 'bmp'; + } elsif($$DATA =~ /^\xFF\xD8\xFF/ || $$DATA =~ /JFIF/) { # JPEG + my $HeaderPoint = index($$DATA, "\xFF\xD8\xFF", 0); + my $Point = $HeaderPoint + 2; + while($Point < $DataLength) { + my($Maker, $MakerType, $MakerLength) = unpack("C2n",substr($$DATA,$Point,4)); + if($Maker != 0xFF || $MakerType == 0xd9 || $MakerType == 0xda) { + last; + } elsif($MakerType >= 0xC0 && $MakerType <= 0xC3) { + $Ext = 'jpg'; + ($ImageHeight, $ImageWidth) = unpack("n2", substr($$DATA, $Point + 5, 4)); + if($HeaderPoint > 0) { + $$DATA = substr($$DATA, $HeaderPoint); + $DataLength = length($$DATA); + } + last; + } else { + $Point += $MakerLength + 2; + } + } + } + } + + # audio + if(!$Ext && ($UnknownType || $ContentType =~ /^audio\//i)) { + # MIDI Audio + if($$DATA =~ /^MThd/) { + $Ext = 'mid'; + } elsif($$DATA =~ /^\x2esnd/) { # ULAW Audio + $Ext = 'au'; + } elsif($$DATA =~ /^RIFF/ || $$DATA =~ /^ID3/ && $$DATA =~ /RIFF/) { + my $HeaderPoint = index($$DATA, "RIFF", 0); + $_ = substr($$DATA, $HeaderPoint + 8, 8); + if(/^WAVEfmt $/) { + # WAVE + if(unpack("V",substr($$DATA, $HeaderPoint + 16, 4)) == 16) { + $Ext = 'wav'; + } else { # RIFF WAVE MP3 + $Ext = 'mp3'; + } + } elsif(/^RMIDdata$/) { # RIFF MIDI + $Ext = 'rmi'; + } elsif(/^RMP3data$/) { # RIFF MP3 + $Ext = 'rmp'; + } + if($ContentType =~ /^audio\//i) { + $Infomation .= '(RIFF '. substr($$DATA, $HeaderPoint + 8, 4). ')'; + } + } + } + + # a binary file + unless ($Ext) { + # PDF image + if($$DATA =~ /^\%PDF/) { + # Picture size is not measured. + $Ext = 'pdf'; + } elsif($$DATA =~ /^FWS/) { # Shockwave Flash + $Ext = 'swf'; + } elsif($$DATA =~ /^RIFF/ || $$DATA =~ /^ID3/ && $$DATA =~ /RIFF/) { + my $HeaderPoint = index($$DATA, "RIFF", 0); + $_ = substr($$DATA,$HeaderPoint + 8, 8); + # AVI + if(/^AVI LIST$/) { + $Ext = 'avi'; + } + if($ContentType =~ /^video\//i) { + $Infomation .= '(RIFF '. substr($$DATA, $HeaderPoint + 8, 4). ')'; + } + } elsif($$DATA =~ /^PK/) { # ZIP Compress File + $Ext = 'zip'; + } elsif($$DATA =~ /^MSCF/) { # CAB Compress File + $Ext = 'cab'; + } elsif($$DATA =~ /^Rar\!/) { # RAR Compress File + $Ext = 'rar'; + } elsif(substr($$DATA, 2, 5) =~ /^\-lh(\d+|d)\-$/) { # LHA Compress File + $Infomation .= "(lh$1)"; + $Ext = 'lzh'; + } elsif(substr($$DATA, 325, 25) eq "Apple Video Media Handler" || substr($$DATA, 325, 30) eq "Apple \x83\x72\x83\x66\x83\x49\x81\x45\x83\x81\x83\x66\x83\x42\x83\x41\x83\x6E\x83\x93\x83\x68\x83\x89") { + # QuickTime + $Ext = 'mov'; + } + } + + # Header analysis failure + unless ($Ext) { + # It will be followed if it applies for the MIME type from the browser. + foreach (keys %UPLOAD_CONTENT_TYPE_LIST) { + next unless ($_); + if($ContentType =~ /^$_$/i) { + $Ext = $UPLOAD_CONTENT_TYPE_LIST{$_}; + $ContentName = &CheckContentExt($Ext); + if( + grep {$_ eq $Ext;} ( + 'png', + 'gif', + 'jpg', + 'xbm', + 'tif', + 'bmp', + 'pdf', + 'swf', + 'mov', + 'zip', + 'cab', + 'lzh', + 'rar', + 'mid', + 'rmi', + 'au', + 'wav', + 'avi', + 'exe' + ) + ) { + $Infomation .= ' / Header analysis failure'; + } + if($Ext ne $FileExt && &CheckContentExt($FileExt) eq $ContentName) { + $Ext = $FileExt; + } + last; + } + } + # a MIME type is unknown--It judges from an extension. + unless ($Ext) { + $ContentName = &CheckContentExt($FileExt); + if($ContentName) { + $Ext = $FileExt; + $Infomation .= ' / MIME type is unknown('. $ContentType. ')'; + last; + } + } + } + +# $ContentName = &CheckContentExt($Ext) unless($ContentName); +# if($Ext && $ContentName) { +# $ContentName .= $Infomation; +# } else { +# &upload_error( +# 'Extension Error', +# "$FileName A not corresponding extension ($Ext)
      The extension which can be responded ". join(',', sort values(%UPLOAD_EXT_LIST)) +# ); +# } + +# # SSI Tag Deletion +# if($Ext =~ /.?html?/ && $$DATA =~ /<\!/) { +# foreach ( +# 'config', +# 'echo', +# 'exec', +# 'flastmod', +# 'fsize', +# 'include' +# ) { +# $$DATA =~ s/\#\s*$_/\&\#35\;$_/ig +# } +# } + + return ( + $FileName, + $Ext, + int($DataLength / 1024 + 1), + $ImageWidth, + $ImageHeight, + $ContentName + ); +} + +############################################################################## +# Summary +# +# Extension discernment +# +# Parameters +# Returns +# Memo +############################################################################## + +sub CheckContentExt +{ + + my($Ext) = @_; + my $ContentName; + foreach (keys %UPLOAD_EXT_LIST) { + next unless ($_); + if($_ && $Ext =~ /^$_$/) { + $ContentName = $UPLOAD_EXT_LIST{$_}; + last; + } + } + return $ContentName; + +} + +############################################################################## +# Summary +# +# Form decode +# +# Parameters +# Returns +# Memo +############################################################################## +sub Encode +{ + + my($value,$Trans) = @_; + +# my $FormCode = &jcode::getcode($value) || $FormCodeDefault; +# $FormCodeDefault ||= $FormCode; +# +# if($Trans && $TRANS_2BYTE_CODE) { +# if($FormCode ne 'euc') { +# &jcode::convert($value, 'euc', $FormCode); +# } +# &jcode::tr( +# $value, +# "\xA3\xB0-\xA3\xB9\xA3\xC1-\xA3\xDA\xA3\xE1-\xA3\xFA", +# '0-9A-Za-z' +# ); +# if($CHARCODE ne 'euc') { +# &jcode::convert($value,$CHARCODE,'euc'); +# } +# } else { +# if($CHARCODE ne $FormCode) { +# &jcode::convert($value,$CHARCODE,$FormCode); +# } +# } +# if($CHARCODE eq 'euc') { +# &jcode::h2z_euc($value); +# } elsif($CHARCODE eq 'sjis') { +# &jcode::h2z_sjis($value); +# } + +} + +############################################################################## +# Summary +# +# Error Msg +# +# Parameters +# Returns +# Memo +############################################################################## + +sub upload_error +{ + + local($error_message) = $_[0]; + local($error_message2) = $_[1]; + + print "Content-type: text/html\n\n"; + print< + +Error Message + + + + + +
      Error Message
      +
        +

        $error_message

        +$error_message2
        +
      + + +EOF + &rm_tmp_uploaded_files; # Image Temporary deletion + exit; +} + +############################################################################## +# Summary +# +# Image Temporary deletion +# +# Parameters +# Returns +# Memo +############################################################################## + +sub rm_tmp_uploaded_files +{ + if($img_data_exists == 1){ + sleep 1; + foreach $fname_list(@NEWFNAMES) { + if(-e "$img_dir/$fname_list") { + unlink("$img_dir/$fname_list"); + } + } + } + +} +1; Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/util.pl =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/util.pl (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/perl/util.pl 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,68 @@ +##### +# FCKeditor - The text editor for Internet - http://www.fckeditor.net +# Copyright (C) 2003-2008 Frederico Caldeira Knabben +# +# == BEGIN LICENSE == +# +# Licensed under the terms of any of the following licenses at your +# choice: +# +# - GNU General Public License Version 2 or later (the "GPL") +# http://www.gnu.org/licenses/gpl.html +# +# - GNU Lesser General Public License Version 2.1 or later (the "LGPL") +# http://www.gnu.org/licenses/lgpl.html +# +# - Mozilla Public License Version 1.1 or later (the "MPL") +# http://www.mozilla.org/MPL/MPL-1.1.html +# +# == END LICENSE == +# +# This is the File Manager Connector for Perl. +##### + +sub RemoveFromStart +{ + local($sourceString, $charToRemove) = @_; + $sPattern = '^' . $charToRemove . '+' ; + $sourceString =~ s/^$charToRemove+//g; + return $sourceString; +} + +sub RemoveFromEnd +{ + local($sourceString, $charToRemove) = @_; + $sPattern = $charToRemove . '+$' ; + $sourceString =~ s/$charToRemove+$//g; + return $sourceString; +} + +sub ConvertToXmlAttribute +{ + local($value) = @_; + return $value; +# return utf8_encode(htmlspecialchars($value)); + +} + +sub specialchar_cnv +{ + local($ch) = @_; + + $ch =~ s/&/&/g; # & + $ch =~ s/\"/"/g; #" + $ch =~ s/\'/'/g; # ' + $ch =~ s//>/g; # > + return($ch); +} + +sub JS_cnv +{ + local($ch) = @_; + + $ch =~ s/\"/\\\"/g; #" + return($ch); +} + +1; Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/basexml.php =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/basexml.php (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/basexml.php 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,93 @@ +' ; + + // Create the main "Connector" node. + echo '' ; + + // Add the current folder node. + echo '' ; + + $GLOBALS['HeaderSent'] = true ; +} + +function CreateXmlFooter() +{ + echo '' ; +} + +function SendError( $number, $text ) +{ + if ( isset( $GLOBALS['HeaderSent'] ) && $GLOBALS['HeaderSent'] ) + { + SendErrorNode( $number, $text ) ; + CreateXmlFooter() ; + } + else + { + SetXmlHeaders() ; + + // Create the XML document header + echo '' ; + + echo '' ; + + SendErrorNode( $number, $text ) ; + + echo '' ; + } + exit ; +} + +function SendErrorNode( $number, $text ) +{ + echo '' ; +} +?> Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/commands.php =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/commands.php (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/commands.php 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,273 @@ +' ; + } + + closedir( $oCurrentFolder ) ; + + // Open the "Folders" node. + echo "" ; + + natcasesort( $aFolders ) ; + foreach ( $aFolders as $sFolder ) + echo $sFolder ; + + // Close the "Folders" node. + echo "" ; +} + +function GetFoldersAndFiles( $resourceType, $currentFolder ) +{ + // Map the virtual path to the local server path. + $sServerDir = ServerMapFolder( $resourceType, $currentFolder, 'GetFoldersAndFiles' ) ; + + // Arrays that will hold the folders and files names. + $aFolders = array() ; + $aFiles = array() ; + + $oCurrentFolder = opendir( $sServerDir ) ; + + while ( $sFile = readdir( $oCurrentFolder ) ) + { + if ( $sFile != '.' && $sFile != '..' ) + { + if ( is_dir( $sServerDir . $sFile ) ) + $aFolders[] = '' ; + else + { + $iFileSize = @filesize( $sServerDir . $sFile ) ; + if ( !$iFileSize ) { + $iFileSize = 0 ; + } + if ( $iFileSize > 0 ) + { + $iFileSize = round( $iFileSize / 1024 ) ; + if ( $iFileSize < 1 ) $iFileSize = 1 ; + } + + $aFiles[] = '' ; + } + } + } + + // Send the folders + natcasesort( $aFolders ) ; + echo '' ; + + foreach ( $aFolders as $sFolder ) + echo $sFolder ; + + echo '' ; + + // Send the files + natcasesort( $aFiles ) ; + echo '' ; + + foreach ( $aFiles as $sFiles ) + echo $sFiles ; + + echo '' ; +} + +function CreateFolder( $resourceType, $currentFolder ) +{ + if (!isset($_GET)) { + global $_GET; + } + $sErrorNumber = '0' ; + $sErrorMsg = '' ; + + if ( isset( $_GET['NewFolderName'] ) ) + { + $sNewFolderName = $_GET['NewFolderName'] ; + $sNewFolderName = SanitizeFolderName( $sNewFolderName ) ; + + if ( strpos( $sNewFolderName, '..' ) !== FALSE ) + $sErrorNumber = '102' ; // Invalid folder name. + else + { + // Map the virtual path to the local server path of the current folder. + $sServerDir = ServerMapFolder( $resourceType, $currentFolder, 'CreateFolder' ) ; + + if ( is_writable( $sServerDir ) ) + { + $sServerDir .= $sNewFolderName ; + + $sErrorMsg = CreateServerFolder( $sServerDir ) ; + + switch ( $sErrorMsg ) + { + case '' : + $sErrorNumber = '0' ; + break ; + case 'Invalid argument' : + case 'No such file or directory' : + $sErrorNumber = '102' ; // Path too long. + break ; + default : + $sErrorNumber = '110' ; + break ; + } + } + else + $sErrorNumber = '103' ; + } + } + else + $sErrorNumber = '102' ; + + // Create the "Error" node. + echo '' ; +} + +function FileUpload( $resourceType, $currentFolder, $sCommand ) +{ + if (!isset($_FILES)) { + global $_FILES; + } + $sErrorNumber = '0' ; + $sFileName = '' ; + + if ( isset( $_FILES['NewFile'] ) && !is_null( $_FILES['NewFile']['tmp_name'] ) ) + { + global $Config ; + + $oFile = $_FILES['NewFile'] ; + + // Map the virtual path to the local server path. + $sServerDir = ServerMapFolder( $resourceType, $currentFolder, $sCommand ) ; + + // Get the uploaded file name. + $sFileName = $oFile['name'] ; + $sFileName = SanitizeFileName( $sFileName ) ; + + $sOriginalFileName = $sFileName ; + + // Get the extension. + $sExtension = substr( $sFileName, ( strrpos($sFileName, '.') + 1 ) ) ; + $sExtension = strtolower( $sExtension ) ; + + if ( isset( $Config['SecureImageUploads'] ) ) + { + if ( ( $isImageValid = IsImageValid( $oFile['tmp_name'], $sExtension ) ) === false ) + { + $sErrorNumber = '202' ; + } + } + + if ( isset( $Config['HtmlExtensions'] ) ) + { + if ( !IsHtmlExtension( $sExtension, $Config['HtmlExtensions'] ) && + ( $detectHtml = DetectHtml( $oFile['tmp_name'] ) ) === true ) + { + $sErrorNumber = '202' ; + } + } + + // Check if it is an allowed extension. + if ( !$sErrorNumber && IsAllowedExt( $sExtension, $resourceType ) ) + { + $iCounter = 0 ; + + while ( true ) + { + $sFilePath = $sServerDir . $sFileName ; + + if ( is_file( $sFilePath ) ) + { + $iCounter++ ; + $sFileName = RemoveExtension( $sOriginalFileName ) . '(' . $iCounter . ').' . $sExtension ; + $sErrorNumber = '201' ; + } + else + { + move_uploaded_file( $oFile['tmp_name'], $sFilePath ) ; + + if ( is_file( $sFilePath ) ) + { + if ( isset( $Config['ChmodOnUpload'] ) && !$Config['ChmodOnUpload'] ) + { + break ; + } + + $permissions = 0777; + + if ( isset( $Config['ChmodOnUpload'] ) && $Config['ChmodOnUpload'] ) + { + $permissions = $Config['ChmodOnUpload'] ; + } + + $oldumask = umask(0) ; + chmod( $sFilePath, $permissions ) ; + umask( $oldumask ) ; + } + + break ; + } + } + + if ( file_exists( $sFilePath ) ) + { + //previous checks failed, try once again + if ( isset( $isImageValid ) && $isImageValid === -1 && IsImageValid( $sFilePath, $sExtension ) === false ) + { + @unlink( $sFilePath ) ; + $sErrorNumber = '202' ; + } + else if ( isset( $detectHtml ) && $detectHtml === -1 && DetectHtml( $sFilePath ) === true ) + { + @unlink( $sFilePath ) ; + $sErrorNumber = '202' ; + } + } + } + else + $sErrorNumber = '202' ; + } + else + $sErrorNumber = '202' ; + + + $sFileUrl = CombinePaths( GetResourceTypePath( $resourceType, $sCommand ) , $currentFolder ) ; + $sFileUrl = CombinePaths( $sFileUrl, $sFileName ) ; + + SendUploadResults( $sErrorNumber, $sFileUrl, $sFileName ) ; + + exit ; +} +?> Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/config.php =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/config.php (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/config.php 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,152 @@ + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/connector.php =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/connector.php (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/connector.php 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,87 @@ + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/io.php =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/io.php (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/io.php 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,320 @@ + 0 ) + return $Config['QuickUploadAbsolutePath'][$resourceType] ; + + // Map the "UserFiles" path to a local directory. + return Server_MapPath( $Config['QuickUploadPath'][$resourceType] ) ; + } + else + { + if ( strlen( $Config['FileTypesAbsolutePath'][$resourceType] ) > 0 ) + return $Config['FileTypesAbsolutePath'][$resourceType] ; + + // Map the "UserFiles" path to a local directory. + return Server_MapPath( $Config['FileTypesPath'][$resourceType] ) ; + } +} + +function GetUrlFromPath( $resourceType, $folderPath, $sCommand ) +{ + return CombinePaths( GetResourceTypePath( $resourceType, $sCommand ), $folderPath ) ; +} + +function RemoveExtension( $fileName ) +{ + return substr( $fileName, 0, strrpos( $fileName, '.' ) ) ; +} + +function ServerMapFolder( $resourceType, $folderPath, $sCommand ) +{ + // Get the resource type directory. + $sResourceTypePath = GetResourceTypeDirectory( $resourceType, $sCommand ) ; + + // Ensure that the directory exists. + $sErrorMsg = CreateServerFolder( $sResourceTypePath ) ; + if ( $sErrorMsg != '' ) + SendError( 1, "Error creating folder \"{$sResourceTypePath}\" ({$sErrorMsg})" ) ; + + // Return the resource type directory combined with the required path. + return CombinePaths( $sResourceTypePath , $folderPath ) ; +} + +function GetParentFolder( $folderPath ) +{ + $sPattern = "-[/\\\\][^/\\\\]+[/\\\\]?$-" ; + return preg_replace( $sPattern, '', $folderPath ) ; +} + +function CreateServerFolder( $folderPath, $lastFolder = null ) +{ + global $Config ; + $sParent = GetParentFolder( $folderPath ) ; + + // Ensure the folder path has no double-slashes, or mkdir may fail on certain platforms + while ( strpos($folderPath, '//') !== false ) + { + $folderPath = str_replace( '//', '/', $folderPath ) ; + } + + // Check if the parent exists, or create it. + if ( !file_exists( $sParent ) ) + { + //prevents agains infinite loop when we can't create root folder + if ( !is_null( $lastFolder ) && $lastFolder === $sParent) { + return "Can't create $folderPath directory" ; + } + + $sErrorMsg = CreateServerFolder( $sParent, $folderPath ) ; + if ( $sErrorMsg != '' ) + return $sErrorMsg ; + } + + if ( !file_exists( $folderPath ) ) + { + // Turn off all error reporting. + error_reporting( 0 ) ; + + $php_errormsg = '' ; + // Enable error tracking to catch the error. + ini_set( 'track_errors', '1' ) ; + + if ( isset( $Config['ChmodOnFolderCreate'] ) && !$Config['ChmodOnFolderCreate'] ) + { + mkdir( $folderPath ) ; + } + else + { + $permissions = 0777 ; + if ( isset( $Config['ChmodOnFolderCreate'] ) ) + { + $permissions = $Config['ChmodOnFolderCreate'] ; + } + // To create the folder with 0777 permissions, we need to set umask to zero. + $oldumask = umask(0) ; + mkdir( $folderPath, $permissions ) ; + umask( $oldumask ) ; + } + + $sErrorMsg = $php_errormsg ; + + // Restore the configurations. + ini_restore( 'track_errors' ) ; + ini_restore( 'error_reporting' ) ; + + return $sErrorMsg ; + } + else + return '' ; +} + +function GetRootPath() +{ + if (!isset($_SERVER)) { + global $_SERVER; + } + $sRealPath = realpath( './' ) ; + + $sSelfPath = $_SERVER['PHP_SELF'] ; + $sSelfPath = substr( $sSelfPath, 0, strrpos( $sSelfPath, '/' ) ) ; + + $sSelfPath = str_replace( '/', DIRECTORY_SEPARATOR, $sSelfPath ) ; + + $position = strpos( $sRealPath, $sSelfPath ) ; + + // This can check only that this script isn't run from a virtual dir + // But it avoids the problems that arise if it isn't checked + if ( $position === false || $position <> strlen( $sRealPath ) - strlen( $sSelfPath ) ) + SendError( 1, 'Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/php/config.php".' ) ; + + return substr( $sRealPath, 0, $position ) ; +} + +// Emulate the asp Server.mapPath function. +// given an url path return the physical directory that it corresponds to +function Server_MapPath( $path ) +{ + // This function is available only for Apache + if ( function_exists( 'apache_lookup_uri' ) ) + { + $info = apache_lookup_uri( $path ) ; + return $info->filename . $info->path_info ; + } + + // This isn't correct but for the moment there's no other solution + // If this script is under a virtual directory or symlink it will detect the problem and stop + return GetRootPath() . $path ; +} + +function IsAllowedExt( $sExtension, $resourceType ) +{ + global $Config ; + // Get the allowed and denied extensions arrays. + $arAllowed = $Config['AllowedExtensions'][$resourceType] ; + $arDenied = $Config['DeniedExtensions'][$resourceType] ; + + if ( count($arAllowed) > 0 && !in_array( $sExtension, $arAllowed ) ) + return false ; + + if ( count($arDenied) > 0 && in_array( $sExtension, $arDenied ) ) + return false ; + + return true ; +} + +function IsAllowedType( $resourceType ) +{ + global $Config ; + if ( !in_array( $resourceType, $Config['ConfigAllowedTypes'] ) ) + return false ; + + return true ; +} + +function IsAllowedCommand( $sCommand ) +{ + global $Config ; + + if ( !in_array( $sCommand, $Config['ConfigAllowedCommands'] ) ) + return false ; + + return true ; +} + +function GetCurrentFolder() +{ + if (!isset($_GET)) { + global $_GET; + } + $sCurrentFolder = isset( $_GET['CurrentFolder'] ) ? $_GET['CurrentFolder'] : '/' ; + + // Check the current folder syntax (must begin and start with a slash). + if ( !preg_match( '|/$|', $sCurrentFolder ) ) + $sCurrentFolder .= '/' ; + if ( strpos( $sCurrentFolder, '/' ) !== 0 ) + $sCurrentFolder = '/' . $sCurrentFolder ; + + // Ensure the folder path has no double-slashes + while ( strpos ($sCurrentFolder, '//') !== false ) { + $sCurrentFolder = str_replace ('//', '/', $sCurrentFolder) ; + } + + // Check for invalid folder paths (..) + if ( strpos( $sCurrentFolder, '..' ) || strpos( $sCurrentFolder, "\\" )) + SendError( 102, '' ) ; + + return $sCurrentFolder ; +} + +// Do a cleanup of the folder name to avoid possible problems +function SanitizeFolderName( $sNewFolderName ) +{ + $sNewFolderName = stripslashes( $sNewFolderName ) ; + + // Remove . \ / | : ? * " < > + $sNewFolderName = preg_replace( '/\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/', '_', $sNewFolderName ) ; + + return $sNewFolderName ; +} + +// Do a cleanup of the file name to avoid possible problems +function SanitizeFileName( $sNewFileName ) +{ + global $Config ; + + $sNewFileName = stripslashes( $sNewFileName ) ; + + // Replace dots in the name with underscores (only one dot can be there... security issue). + if ( $Config['ForceSingleExtension'] ) + $sNewFileName = preg_replace( '/\\.(?![^.]*$)/', '_', $sNewFileName ) ; + + // Remove \ / | : ? * " < > + $sNewFileName = preg_replace( '/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[[:cntrl:]]/', '_', $sNewFileName ) ; + + return $sNewFileName ; +} + +// This is the function that sends the results of the uploading process. +function SendUploadResults( $errorNumber, $fileUrl = '', $fileName = '', $customMsg = '' ) +{ + echo << +(function() +{ + var d = document.domain ; + + while ( true ) + { + // Test if we can access a parent property. + try + { + var test = window.top.opener.document.domain ; + break ; + } + catch( e ) {} + + // Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ... + d = d.replace( /.*?(?:\.|$)/, '' ) ; + + if ( d.length == 0 ) + break ; // It was not able to detect the domain. + + try + { + document.domain = d ; + } + catch (e) + { + break ; + } + } +})() ; + +EOF; + $rpl = array( '\\' => '\\\\', '"' => '\\"' ) ; + echo 'window.parent.OnUploadCompleted(' . $errorNumber . ',"' . strtr( $fileUrl, $rpl ) . '","' . strtr( $fileName, $rpl ) . '", "' . strtr( $customMsg, $rpl ) . '") ;' ; + echo '' ; + exit ; +} + +?> Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/phpcompat.php =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/phpcompat.php (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/phpcompat.php 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,17 @@ + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/util.php =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/util.php (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/php/util.php 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,220 @@ + $val ) + { + $lcaseHtmlExtensions[$key] = strtolower( $val ) ; + } + return in_array( $ext, $lcaseHtmlExtensions ) ; +} + +/** + * Detect HTML in the first KB to prevent against potential security issue with + * IE/Safari/Opera file type auto detection bug. + * Returns true if file contain insecure HTML code at the beginning. + * + * @param string $filePath absolute path to file + * @return boolean + */ +function DetectHtml( $filePath ) +{ + $fp = @fopen( $filePath, 'rb' ) ; + + //open_basedir restriction, see #1906 + if ( $fp === false || !flock( $fp, LOCK_SH ) ) + { + return -1 ; + } + + $chunk = fread( $fp, 1024 ) ; + flock( $fp, LOCK_UN ) ; + fclose( $fp ) ; + + $chunk = strtolower( $chunk ) ; + + if (!$chunk) + { + return false ; + } + + $chunk = trim( $chunk ) ; + + if ( preg_match( "/= 4.0.7 + if ( function_exists( 'version_compare' ) ) { + $sCurrentVersion = phpversion(); + if ( version_compare( $sCurrentVersion, "4.2.0" ) >= 0 ) { + $imageCheckExtensions[] = "tiff"; + $imageCheckExtensions[] = "tif"; + } + if ( version_compare( $sCurrentVersion, "4.3.0" ) >= 0 ) { + $imageCheckExtensions[] = "swc"; + } + if ( version_compare( $sCurrentVersion, "4.3.2" ) >= 0 ) { + $imageCheckExtensions[] = "jpc"; + $imageCheckExtensions[] = "jp2"; + $imageCheckExtensions[] = "jpx"; + $imageCheckExtensions[] = "jb2"; + $imageCheckExtensions[] = "xbm"; + $imageCheckExtensions[] = "wbmp"; + } + } + + if ( !in_array( $extension, $imageCheckExtensions ) ) { + return true; + } + + if ( @getimagesize( $filePath ) === false ) { + return false ; + } + + return true; +} + +?> Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/config.py =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/config.py (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/config.py 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,146 @@ +#!/usr/bin/env python +""" + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * Configuration file for the File Manager Connector for Python +""" + +# INSTALLATION NOTE: You must set up your server environment accordingly to run +# python scripts. This connector requires Python 2.4 or greater. +# +# Supported operation modes: +# * WSGI (recommended): You'll need apache + mod_python + modpython_gateway +# or any web server capable of the WSGI python standard +# * Plain Old CGI: Any server capable of running standard python scripts +# (although mod_python is recommended for performance) +# This was the previous connector version operation mode +# +# If you're using Apache web server, replace the htaccess.txt to to .htaccess, +# and set the proper options and paths. +# For WSGI and mod_python, you may need to download modpython_gateway from: +# http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this +# directory. + + +# SECURITY: You must explicitly enable this "connector". (Set it to "True"). +# WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only +# authenticated users can access this file or use some kind of session checking. +Enabled = False + +# Path to user files relative to the document root. +UserFilesPath = '/userfiles/' + +# Fill the following value it you prefer to specify the absolute path for the +# user files directory. Useful if you are using a virtual directory, symbolic +# link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. +# Attention: The above 'UserFilesPath' must point to the same directory. +# WARNING: GetRootPath may not work in virtual or mod_python configurations, and +# may not be thread safe. Use this configuration parameter instead. +UserFilesAbsolutePath = '' + +# Due to security issues with Apache modules, it is recommended to leave the +# following setting enabled. +ForceSingleExtension = True + +# What the user can do with this connector +ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ] + +# Allowed Resource Types +ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media'] + +# After file is uploaded, sometimes it is required to change its permissions +# so that it was possible to access it at the later time. +# If possible, it is recommended to set more restrictive permissions, like 0755. +# Set to 0 to disable this feature. +# Note: not needed on Windows-based servers. +ChmodOnUpload = 0755 + +# See comments above. +# Used when creating folders that does not exist. +ChmodOnFolderCreate = 0755 + +# Do not touch this 3 lines, see "Configuration settings for each Resource Type" +AllowedExtensions = {}; DeniedExtensions = {}; +FileTypesPath = {}; FileTypesAbsolutePath = {}; +QuickUploadPath = {}; QuickUploadAbsolutePath = {}; + +# Configuration settings for each Resource Type +# +# - AllowedExtensions: the possible extensions that can be allowed. +# If it is empty then any file type can be uploaded. +# - DeniedExtensions: The extensions that won't be allowed. +# If it is empty then no restrictions are done here. +# +# For a file to be uploaded it has to fulfill both the AllowedExtensions +# and DeniedExtensions (that's it: not being denied) conditions. +# +# - FileTypesPath: the virtual folder relative to the document root where +# these resources will be located. +# Attention: It must start and end with a slash: '/' +# +# - FileTypesAbsolutePath: the physical path to the above folder. It must be +# an absolute path. +# If it's an empty string then it will be autocalculated. +# Useful if you are using a virtual directory, symbolic link or alias. +# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. +# Attention: The above 'FileTypesPath' must point to the same directory. +# Attention: It must end with a slash: '/' +# +# +# - QuickUploadPath: the virtual folder relative to the document root where +# these resources will be uploaded using the Upload tab in the resources +# dialogs. +# Attention: It must start and end with a slash: '/' +# +# - QuickUploadAbsolutePath: the physical path to the above folder. It must be +# an absolute path. +# If it's an empty string then it will be autocalculated. +# Useful if you are using a virtual directory, symbolic link or alias. +# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. +# Attention: The above 'QuickUploadPath' must point to the same directory. +# Attention: It must end with a slash: '/' + +AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip'] +DeniedExtensions['File'] = [] +FileTypesPath['File'] = UserFilesPath + 'file/' +FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or '' +QuickUploadPath['File'] = FileTypesPath['File'] +QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File'] + +AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png'] +DeniedExtensions['Image'] = [] +FileTypesPath['Image'] = UserFilesPath + 'image/' +FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or '' +QuickUploadPath['Image'] = FileTypesPath['Image'] +QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image'] + +AllowedExtensions['Flash'] = ['swf','flv'] +DeniedExtensions['Flash'] = [] +FileTypesPath['Flash'] = UserFilesPath + 'flash/' +FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or '' +QuickUploadPath['Flash'] = FileTypesPath['Flash'] +QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash'] + +AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv'] +DeniedExtensions['Media'] = [] +FileTypesPath['Media'] = UserFilesPath + 'media/' +FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or '' +QuickUploadPath['Media'] = FileTypesPath['Media'] +QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media'] Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/connector.py =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/connector.py (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/connector.py 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,118 @@ +#!/usr/bin/env python + +""" +FCKeditor - The text editor for Internet - http://www.fckeditor.net +Copyright (C) 2003-2008 Frederico Caldeira Knabben + +== BEGIN LICENSE == + +Licensed under the terms of any of the following licenses at your +choice: + + - GNU General Public License Version 2 or later (the "GPL") + http://www.gnu.org/licenses/gpl.html + + - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + http://www.gnu.org/licenses/lgpl.html + + - Mozilla Public License Version 1.1 or later (the "MPL") + http://www.mozilla.org/MPL/MPL-1.1.html + +== END LICENSE == + +Connector for Python (CGI and WSGI). + +See config.py for configuration settings + +""" +import os + +from fckutil import * +from fckcommands import * # default command's implementation +from fckoutput import * # base http, xml and html output mixins +from fckconnector import FCKeditorConnectorBase # import base connector +import config as Config + +class FCKeditorConnector( FCKeditorConnectorBase, + GetFoldersCommandMixin, + GetFoldersAndFilesCommandMixin, + CreateFolderCommandMixin, + UploadFileCommandMixin, + BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ): + "The Standard connector class." + def doResponse(self): + "Main function. Process the request, set headers and return a string as response." + s = "" + # Check if this connector is disabled + if not(Config.Enabled): + return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.") + # Make sure we have valid inputs + for key in ("Command","Type","CurrentFolder"): + if not self.request.has_key (key): + return + # Get command, resource type and current folder + command = self.request.get("Command") + resourceType = self.request.get("Type") + currentFolder = getCurrentFolder(self.request.get("CurrentFolder")) + # Check for invalid paths + if currentFolder is None: + return self.sendError(102, "") + + # Check if it is an allowed command + if ( not command in Config.ConfigAllowedCommands ): + return self.sendError( 1, 'The %s command isn\'t allowed' % command ) + + if ( not resourceType in Config.ConfigAllowedTypes ): + return self.sendError( 1, 'Invalid type specified' ) + + # Setup paths + if command == "QuickUpload": + self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] + self.webUserFilesFolder = Config.QuickUploadPath[resourceType] + else: + self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType] + self.webUserFilesFolder = Config.FileTypesPath[resourceType] + + if not self.userFilesFolder: # no absolute path given (dangerous...) + self.userFilesFolder = mapServerPath(self.environ, + self.webUserFilesFolder) + # Ensure that the directory exists. + if not os.path.exists(self.userFilesFolder): + try: + self.createServerFoldercreateServerFolder( self.userFilesFolder ) + except: + return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") + + # File upload doesn't have to return XML, so intercept here + if (command == "FileUpload"): + return self.uploadFile(resourceType, currentFolder) + + # Create Url + url = combinePaths( self.webUserFilesFolder, currentFolder ) + + # Begin XML + s += self.createXmlHeader(command, resourceType, currentFolder, url) + # Execute the command + selector = {"GetFolders": self.getFolders, + "GetFoldersAndFiles": self.getFoldersAndFiles, + "CreateFolder": self.createFolder, + } + s += selector[command](resourceType, currentFolder) + s += self.createXmlFooter() + return s + +# Running from command line (plain old CGI) +if __name__ == '__main__': + try: + # Create a Connector Instance + conn = FCKeditorConnector() + data = conn.doResponse() + for header in conn.headers: + print '%s: %s' % header + print + print data + except: + print "Content-Type: text/plain" + print + import cgi + cgi.print_exception() Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckcommands.py =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckcommands.py (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckcommands.py 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,198 @@ +#!/usr/bin/env python + +""" +FCKeditor - The text editor for Internet - http://www.fckeditor.net +Copyright (C) 2003-2008 Frederico Caldeira Knabben + +== BEGIN LICENSE == + +Licensed under the terms of any of the following licenses at your +choice: + +- GNU General Public License Version 2 or later (the "GPL") +http://www.gnu.org/licenses/gpl.html + +- GNU Lesser General Public License Version 2.1 or later (the "LGPL") +http://www.gnu.org/licenses/lgpl.html + +- Mozilla Public License Version 1.1 or later (the "MPL") +http://www.mozilla.org/MPL/MPL-1.1.html + +== END LICENSE == + +Connector for Python (CGI and WSGI). + +""" + +import os +try: # Windows needs stdio set for binary mode for file upload to work. + import msvcrt + msvcrt.setmode (0, os.O_BINARY) # stdin = 0 + msvcrt.setmode (1, os.O_BINARY) # stdout = 1 +except ImportError: + pass + +from fckutil import * +from fckoutput import * +import config as Config + +class GetFoldersCommandMixin (object): + def getFolders(self, resourceType, currentFolder): + """ + Purpose: command to recieve a list of folders + """ + # Map the virtual path to our local server + serverPath = mapServerFolder(self.userFilesFolder,currentFolder) + s = """""" # Open the folders node + for someObject in os.listdir(serverPath): + someObjectPath = mapServerFolder(serverPath, someObject) + if os.path.isdir(someObjectPath): + s += """""" % ( + convertToXmlAttribute(someObject) + ) + s += """""" # Close the folders node + return s + +class GetFoldersAndFilesCommandMixin (object): + def getFoldersAndFiles(self, resourceType, currentFolder): + """ + Purpose: command to recieve a list of folders and files + """ + # Map the virtual path to our local server + serverPath = mapServerFolder(self.userFilesFolder,currentFolder) + # Open the folders / files node + folders = """""" + files = """""" + for someObject in os.listdir(serverPath): + someObjectPath = mapServerFolder(serverPath, someObject) + if os.path.isdir(someObjectPath): + folders += """""" % ( + convertToXmlAttribute(someObject) + ) + elif os.path.isfile(someObjectPath): + size = os.path.getsize(someObjectPath) + files += """""" % ( + convertToXmlAttribute(someObject), + os.path.getsize(someObjectPath) + ) + # Close the folders / files node + folders += """""" + files += """""" + return folders + files + +class CreateFolderCommandMixin (object): + def createFolder(self, resourceType, currentFolder): + """ + Purpose: command to create a new folder + """ + errorNo = 0; errorMsg =''; + if self.request.has_key("NewFolderName"): + newFolder = self.request.get("NewFolderName", None) + newFolder = sanitizeFolderName (newFolder) + try: + newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder)) + self.createServerFolder(newFolderPath) + except Exception, e: + errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!! + if hasattr(e,'errno'): + if e.errno==17: #file already exists + errorNo=0 + elif e.errno==13: # permission denied + errorNo = 103 + elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name + errorNo = 102 + else: + errorNo = 110 + else: + errorNo = 102 + return self.sendErrorNode ( errorNo, errorMsg ) + + def createServerFolder(self, folderPath): + "Purpose: physically creates a folder on the server" + # No need to check if the parent exists, just create all hierachy + + try: + permissions = Config.ChmodOnFolderCreate + if not permissions: + os.makedirs(folderPath) + except AttributeError: #ChmodOnFolderCreate undefined + permissions = 0755 + + if permissions: + oldumask = os.umask(0) + os.makedirs(folderPath,mode=0755) + os.umask( oldumask ) + +class UploadFileCommandMixin (object): + def uploadFile(self, resourceType, currentFolder): + """ + Purpose: command to upload files to server (same as FileUpload) + """ + errorNo = 0 + if self.request.has_key("NewFile"): + # newFile has all the contents we need + newFile = self.request.get("NewFile", "") + # Get the file name + newFileName = newFile.filename + newFileName = sanitizeFileName( newFileName ) + newFileNameOnly = removeExtension(newFileName) + newFileExtension = getExtension(newFileName).lower() + allowedExtensions = Config.AllowedExtensions[resourceType] + deniedExtensions = Config.DeniedExtensions[resourceType] + + if (allowedExtensions): + # Check for allowed + isAllowed = False + if (newFileExtension in allowedExtensions): + isAllowed = True + elif (deniedExtensions): + # Check for denied + isAllowed = True + if (newFileExtension in deniedExtensions): + isAllowed = False + else: + # No extension limitations + isAllowed = True + + if (isAllowed): + # Upload to operating system + # Map the virtual path to the local server path + currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder) + i = 0 + while (True): + newFilePath = os.path.join (currentFolderPath,newFileName) + if os.path.exists(newFilePath): + i += 1 + newFileName = "%s(%04d).%s" % ( + newFileNameOnly, i, newFileExtension + ) + errorNo= 201 # file renamed + else: + # Read file contents and write to the desired path (similar to php's move_uploaded_file) + fout = file(newFilePath, 'wb') + while (True): + chunk = newFile.file.read(100000) + if not chunk: break + fout.write (chunk) + fout.close() + + if os.path.exists ( newFilePath ): + doChmod = False + try: + doChmod = Config.ChmodOnUpload + permissions = Config.ChmodOnUpload + except AttributeError: #ChmodOnUpload undefined + doChmod = True + permissions = 0755 + if ( doChmod ): + oldumask = os.umask(0) + os.chmod( newFilePath, permissions ) + os.umask( oldumask ) + + newFileUrl = self.webUserFilesFolder + currentFolder + newFileName + + return self.sendUploadResults( errorNo , newFileUrl, newFileName ) + else: + return self.sendUploadResults( errorNo = 203, customMsg = "Extension not allowed" ) + else: + return self.sendUploadResults( errorNo = 202, customMsg = "No File" ) Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckconnector.py =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckconnector.py (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckconnector.py 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,90 @@ +#!/usr/bin/env python + +""" +FCKeditor - The text editor for Internet - http://www.fckeditor.net +Copyright (C) 2003-2008 Frederico Caldeira Knabben + +== BEGIN LICENSE == + +Licensed under the terms of any of the following licenses at your +choice: + +- GNU General Public License Version 2 or later (the "GPL") +http://www.gnu.org/licenses/gpl.html + +- GNU Lesser General Public License Version 2.1 or later (the "LGPL") +http://www.gnu.org/licenses/lgpl.html + +- Mozilla Public License Version 1.1 or later (the "MPL") +http://www.mozilla.org/MPL/MPL-1.1.html + +== END LICENSE == + +Base Connector for Python (CGI and WSGI). + +See config.py for configuration settings + +""" +import cgi, os + +from fckutil import * +from fckcommands import * # default command's implementation +from fckoutput import * # base http, xml and html output mixins +import config as Config + +class FCKeditorConnectorBase( object ): + "The base connector class. Subclass it to extend functionality (see Zope example)" + + def __init__(self, environ=None): + "Constructor: Here you should parse request fields, initialize variables, etc." + self.request = FCKeditorRequest(environ) # Parse request + self.headers = [] # Clean Headers + if environ: + self.environ = environ + else: + self.environ = os.environ + + # local functions + + def setHeader(self, key, value): + self.headers.append ((key, value)) + return + +class FCKeditorRequest(object): + "A wrapper around the request object" + def __init__(self, environ): + if environ: # WSGI + self.request = cgi.FieldStorage(fp=environ['wsgi.input'], + environ=environ, + keep_blank_values=1) + self.environ = environ + else: # plain old cgi + self.environ = os.environ + self.request = cgi.FieldStorage() + if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ: + if self.environ['REQUEST_METHOD'].upper()=='POST': + # we are in a POST, but GET query_string exists + # cgi parses by default POST data, so parse GET QUERY_STRING too + self.get_request = cgi.FieldStorage(fp=None, + environ={ + 'REQUEST_METHOD':'GET', + 'QUERY_STRING':self.environ['QUERY_STRING'], + }, + ) + else: + self.get_request={} + + def has_key(self, key): + return self.request.has_key(key) or self.get_request.has_key(key) + + def get(self, key, default=None): + if key in self.request.keys(): + field = self.request[key] + elif key in self.get_request.keys(): + field = self.get_request[key] + else: + return default + if hasattr(field,"filename") and field.filename: #file upload, do not convert return value + return field + else: + return field.value Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckoutput.py =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckoutput.py (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckoutput.py 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,142 @@ +#!/usr/bin/env python + +""" +FCKeditor - The text editor for Internet - http://www.fckeditor.net +Copyright (C) 2003-2008 Frederico Caldeira Knabben + +== BEGIN LICENSE == + +Licensed under the terms of any of the following licenses at your +choice: + +- GNU General Public License Version 2 or later (the "GPL") +http://www.gnu.org/licenses/gpl.html + +- GNU Lesser General Public License Version 2.1 or later (the "LGPL") +http://www.gnu.org/licenses/lgpl.html + +- Mozilla Public License Version 1.1 or later (the "MPL") +http://www.mozilla.org/MPL/MPL-1.1.html + +== END LICENSE == + +Connector for Python (CGI and WSGI). + +""" + +from time import gmtime, strftime +import string + +def escape(text, replace=string.replace): + """ + Converts the special characters '<', '>', and '&'. + + RFC 1866 specifies that these characters be represented + in HTML as < > and & respectively. In Python + 1.5 we use the new string.replace() function for speed. + """ + text = replace(text, '&', '&') # must be done 1st + text = replace(text, '<', '<') + text = replace(text, '>', '>') + text = replace(text, '"', '"') + return text + +def convertToXmlAttribute(value): + if (value is None): + value = "" + return escape(value) + +class BaseHttpMixin(object): + def setHttpHeaders(self, content_type='text/xml'): + "Purpose: to prepare the headers for the xml to return" + # Prevent the browser from caching the result. + # Date in the past + self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT') + # always modified + self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())) + # HTTP/1.1 + self.setHeader('Cache-Control','no-store, no-cache, must-revalidate') + self.setHeader('Cache-Control','post-check=0, pre-check=0') + # HTTP/1.0 + self.setHeader('Pragma','no-cache') + + # Set the response format. + self.setHeader( 'Content-Type', content_type + '; charset=utf-8' ) + return + +class BaseXmlMixin(object): + def createXmlHeader(self, command, resourceType, currentFolder, url): + "Purpose: returns the xml header" + self.setHttpHeaders() + # Create the XML document header + s = """""" + # Create the main connector node + s += """""" % ( + command, + resourceType + ) + # Add the current folder node + s += """""" % ( + convertToXmlAttribute(currentFolder), + convertToXmlAttribute(url), + ) + return s + + def createXmlFooter(self): + "Purpose: returns the xml footer" + return """""" + + def sendError(self, number, text): + "Purpose: in the event of an error, return an xml based error" + self.setHttpHeaders() + return ("""""" + + """""" + + self.sendErrorNode (number, text) + + """""" ) + + def sendErrorNode(self, number, text): + return """""" % (number, convertToXmlAttribute(text)) + +class BaseHtmlMixin(object): + def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ): + self.setHttpHeaders("text/html") + "This is the function that sends the results of the uploading process" + return """""" % { + 'errorNumber': errorNo, + 'fileUrl': fileUrl.replace ('"', '\\"'), + 'fileName': fileName.replace ( '"', '\\"' ) , + 'customMsg': customMsg.replace ( '"', '\\"' ), + } Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckutil.py =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckutil.py (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/fckutil.py 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,126 @@ +#!/usr/bin/env python + +""" +FCKeditor - The text editor for Internet - http://www.fckeditor.net +Copyright (C) 2003-2008 Frederico Caldeira Knabben + +== BEGIN LICENSE == + +Licensed under the terms of any of the following licenses at your +choice: + +- GNU General Public License Version 2 or later (the "GPL") +http://www.gnu.org/licenses/gpl.html + +- GNU Lesser General Public License Version 2.1 or later (the "LGPL") +http://www.gnu.org/licenses/lgpl.html + +- Mozilla Public License Version 1.1 or later (the "MPL") +http://www.mozilla.org/MPL/MPL-1.1.html + +== END LICENSE == + +Utility functions for the File Manager Connector for Python + +""" + +import string, re +import os +import config as Config + +# Generic manipulation functions + +def removeExtension(fileName): + index = fileName.rindex(".") + newFileName = fileName[0:index] + return newFileName + +def getExtension(fileName): + index = fileName.rindex(".") + 1 + fileExtension = fileName[index:] + return fileExtension + +def removeFromStart(string, char): + return string.lstrip(char) + +def removeFromEnd(string, char): + return string.rstrip(char) + +# Path functions + +def combinePaths( basePath, folder ): + return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' ) + +def getFileName(filename): + " Purpose: helper function to extrapolate the filename " + for splitChar in ["/", "\\"]: + array = filename.split(splitChar) + if (len(array) > 1): + filename = array[-1] + return filename + +def sanitizeFolderName( newFolderName ): + "Do a cleanup of the folder name to avoid possible problems" + # Remove . \ / | : ? * " < > and control characters + return re.sub( '(?u)\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]', '_', newFolderName ) + +def sanitizeFileName( newFileName ): + "Do a cleanup of the file name to avoid possible problems" + # Replace dots in the name with underscores (only one dot can be there... security issue). + if ( Config.ForceSingleExtension ): # remove dots + newFileName = re.sub ( '/\\.(?![^.]*$)/', '_', newFileName ) ; + newFileName = newFileName.replace('\\','/') # convert windows to unix path + newFileName = os.path.basename (newFileName) # strip directories + # Remove \ / | : ? * + return re.sub ( '(?u)/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]/', '_', newFileName ) + +def getCurrentFolder(currentFolder): + if not currentFolder: + currentFolder = '/' + + # Check the current folder syntax (must begin and end with a slash). + if (currentFolder[-1] <> "/"): + currentFolder += "/" + if (currentFolder[0] <> "/"): + currentFolder = "/" + currentFolder + + # Ensure the folder path has no double-slashes + while '//' in currentFolder: + currentFolder = currentFolder.replace('//','/') + + # Check for invalid folder paths (..) + if '..' in currentFolder or '\\' in currentFolder: + return None + + return currentFolder + +def mapServerPath( environ, url): + " Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to " + # This isn't correct but for the moment there's no other solution + # If this script is under a virtual directory or symlink it will detect the problem and stop + return combinePaths( getRootPath(environ), url ) + +def mapServerFolder(resourceTypePath, folderPath): + return combinePaths ( resourceTypePath , folderPath ) + +def getRootPath(environ): + "Purpose: returns the root path on the server" + # WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python + # Use Config.UserFilesAbsolutePath instead + + if environ.has_key('DOCUMENT_ROOT'): + return environ['DOCUMENT_ROOT'] + else: + realPath = os.path.realpath( './' ) + selfPath = environ['SCRIPT_FILENAME'] + selfPath = selfPath [ : selfPath.rfind( '/' ) ] + selfPath = selfPath.replace( '/', os.path.sep) + + position = realPath.find(selfPath) + + # This can check only that this script isn't run from a virtual dir + # But it avoids the problems that arise if it isn't checked + raise realPath + if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''): + raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".') + return realPath[ : position ] Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/htaccess.txt =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/htaccess.txt (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/htaccess.txt 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,23 @@ +# replace the name of this file to .htaccess (if using apache), +# and set the proper options and paths according your enviroment + +Allow from all + +# If using mod_python uncomment this: +PythonPath "[r'C:\Archivos de programa\Apache Software Foundation\Apache2.2\htdocs\fckeditor\editor\filemanager\connectors\py'] + sys.path" + + +# Recomended: WSGI application running with mod_python and modpython_gateway +SetHandler python-program +PythonHandler modpython_gateway::handler +PythonOption wsgi.application wsgi::App + + +# Emulated CGI with mod_python and cgihandler +#AddHandler mod_python .py +#PythonHandler mod_python.cgihandler + + +# Plain old CGI +#Options +ExecCGI +#AddHandler cgi-script py Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/upload.py =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/upload.py (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/upload.py 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,88 @@ +#!/usr/bin/env python + +""" +FCKeditor - The text editor for Internet - http://www.fckeditor.net +Copyright (C) 2003-2008 Frederico Caldeira Knabben + +== BEGIN LICENSE == + +Licensed under the terms of any of the following licenses at your +choice: + +- GNU General Public License Version 2 or later (the "GPL") +http://www.gnu.org/licenses/gpl.html + +- GNU Lesser General Public License Version 2.1 or later (the "LGPL") +http://www.gnu.org/licenses/lgpl.html + +- Mozilla Public License Version 1.1 or later (the "MPL") +http://www.mozilla.org/MPL/MPL-1.1.html + +== END LICENSE == + +This is the "File Uploader" for Python + +""" +import os + +from fckutil import * +from fckcommands import * # default command's implementation +from fckconnector import FCKeditorConnectorBase # import base connector +import config as Config + +class FCKeditorQuickUpload( FCKeditorConnectorBase, + UploadFileCommandMixin, + BaseHttpMixin, BaseHtmlMixin): + def doResponse(self): + "Main function. Process the request, set headers and return a string as response." + # Check if this connector is disabled + if not(Config.Enabled): + return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"") + command = 'QuickUpload' + # The file type (from the QueryString, by default 'File'). + resourceType = self.request.get('Type','File') + currentFolder = getCurrentFolder(self.request.get("CurrentFolder","")) + # Check for invalid paths + if currentFolder is None: + return self.sendUploadResults(102, '', '', "") + + # Check if it is an allowed command + if ( not command in Config.ConfigAllowedCommands ): + return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command ) + + if ( not resourceType in Config.ConfigAllowedTypes ): + return self.sendUploadResults( 1, '', '', 'Invalid type specified' ) + + # Setup paths + self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] + self.webUserFilesFolder = Config.QuickUploadPath[resourceType] + if not self.userFilesFolder: # no absolute path given (dangerous...) + self.userFilesFolder = mapServerPath(self.environ, + self.webUserFilesFolder) + + # Ensure that the directory exists. + if not os.path.exists(self.userFilesFolder): + try: + self.createServerFoldercreateServerFolder( self.userFilesFolder ) + except: + return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") + + # File upload doesn't have to return XML, so intercept here + return self.uploadFile(resourceType, currentFolder) + +# Running from command line (plain old CGI) +if __name__ == '__main__': + try: + # Create a Connector Instance + conn = FCKeditorQuickUpload() + data = conn.doResponse() + for header in conn.headers: + if not header is None: + print '%s: %s' % header + print + print data + except: + print "Content-Type: text/plain" + print + import cgi + cgi.print_exception() Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/wsgi.py =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/wsgi.py (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/wsgi.py 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,58 @@ +#!/usr/bin/env python + +""" +FCKeditor - The text editor for Internet - http://www.fckeditor.net +Copyright (C) 2003-2008 Frederico Caldeira Knabben + +== BEGIN LICENSE == + +Licensed under the terms of any of the following licenses at your +choice: + + - GNU General Public License Version 2 or later (the "GPL") + http://www.gnu.org/licenses/gpl.html + + - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + http://www.gnu.org/licenses/lgpl.html + + - Mozilla Public License Version 1.1 or later (the "MPL") + http://www.mozilla.org/MPL/MPL-1.1.html + +== END LICENSE == + +Connector/QuickUpload for Python (WSGI wrapper). + +See config.py for configuration settings + +""" + +from connector import FCKeditorConnector +from upload import FCKeditorQuickUpload + +import cgitb +from cStringIO import StringIO + +# Running from WSGI capable server (recomended) +def App(environ, start_response): + "WSGI entry point. Run the connector" + if environ['SCRIPT_NAME'].endswith("connector.py"): + conn = FCKeditorConnector(environ) + elif environ['SCRIPT_NAME'].endswith("upload.py"): + conn = FCKeditorQuickUpload(environ) + else: + start_response ("200 Ok", [('Content-Type','text/html')]) + yield "Unknown page requested: " + yield environ['SCRIPT_NAME'] + return + try: + # run the connector + data = conn.doResponse() + # Start WSGI response: + start_response ("200 Ok", conn.headers) + # Send response text + yield data + except: + start_response("500 Internal Server Error",[("Content-type","text/html")]) + file = StringIO() + cgitb.Hook(file = file).handle() + yield file.getvalue() Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/zope.py =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/zope.py (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/py/zope.py 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,188 @@ +#!/usr/bin/env python + +""" +FCKeditor - The text editor for Internet - http://www.fckeditor.net +Copyright (C) 2003-2008 Frederico Caldeira Knabben + +== BEGIN LICENSE == + +Licensed under the terms of any of the following licenses at your +choice: + +- GNU General Public License Version 2 or later (the "GPL") +http://www.gnu.org/licenses/gpl.html + +- GNU Lesser General Public License Version 2.1 or later (the "LGPL") +http://www.gnu.org/licenses/lgpl.html + +- Mozilla Public License Version 1.1 or later (the "MPL") +http://www.mozilla.org/MPL/MPL-1.1.html + +== END LICENSE == + +Connector for Python and Zope. + +This code was not tested at all. +It just was ported from pre 2.5 release, so for further reference see +\editor\filemanager\browser\default\connectors\py\connector.py in previous +releases. + +""" + +from fckutil import * +from connector import * +import config as Config + +class FCKeditorConnectorZope(FCKeditorConnector): + """ + Zope versiof FCKeditorConnector + """ + # Allow access (Zope) + __allow_access_to_unprotected_subobjects__ = 1 + + def __init__(self, context=None): + """ + Constructor + """ + FCKeditorConnector.__init__(self, environ=None) # call superclass constructor + # Instance Attributes + self.context = context + self.request = FCKeditorRequest(context) + + def getZopeRootContext(self): + if self.zopeRootContext is None: + self.zopeRootContext = self.context.getPhysicalRoot() + return self.zopeRootContext + + def getZopeUploadContext(self): + if self.zopeUploadContext is None: + folderNames = self.userFilesFolder.split("/") + c = self.getZopeRootContext() + for folderName in folderNames: + if (folderName <> ""): + c = c[folderName] + self.zopeUploadContext = c + return self.zopeUploadContext + + def setHeader(self, key, value): + self.context.REQUEST.RESPONSE.setHeader(key, value) + + def getFolders(self, resourceType, currentFolder): + # Open the folders node + s = "" + s += """""" + zopeFolder = self.findZopeFolder(resourceType, currentFolder) + for (name, o) in zopeFolder.objectItems(["Folder"]): + s += """""" % ( + convertToXmlAttribute(name) + ) + # Close the folders node + s += """""" + return s + + def getZopeFoldersAndFiles(self, resourceType, currentFolder): + folders = self.getZopeFolders(resourceType, currentFolder) + files = self.getZopeFiles(resourceType, currentFolder) + s = folders + files + return s + + def getZopeFiles(self, resourceType, currentFolder): + # Open the files node + s = "" + s += """""" + zopeFolder = self.findZopeFolder(resourceType, currentFolder) + for (name, o) in zopeFolder.objectItems(["File","Image"]): + s += """""" % ( + convertToXmlAttribute(name), + ((o.get_size() / 1024) + 1) + ) + # Close the files node + s += """""" + return s + + def findZopeFolder(self, resourceType, folderName): + # returns the context of the resource / folder + zopeFolder = self.getZopeUploadContext() + folderName = self.removeFromStart(folderName, "/") + folderName = self.removeFromEnd(folderName, "/") + if (resourceType <> ""): + try: + zopeFolder = zopeFolder[resourceType] + except: + zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType) + zopeFolder = zopeFolder[resourceType] + if (folderName <> ""): + folderNames = folderName.split("/") + for folderName in folderNames: + zopeFolder = zopeFolder[folderName] + return zopeFolder + + def createFolder(self, resourceType, currentFolder): + # Find out where we are + zopeFolder = self.findZopeFolder(resourceType, currentFolder) + errorNo = 0 + errorMsg = "" + if self.request.has_key("NewFolderName"): + newFolder = self.request.get("NewFolderName", None) + zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder) + else: + errorNo = 102 + return self.sendErrorNode ( errorNo, errorMsg ) + + def uploadFile(self, resourceType, currentFolder, count=None): + zopeFolder = self.findZopeFolder(resourceType, currentFolder) + file = self.request.get("NewFile", None) + fileName = self.getFileName(file.filename) + fileNameOnly = self.removeExtension(fileName) + fileExtension = self.getExtension(fileName).lower() + if (count): + nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension) + else: + nid = fileName + title = nid + try: + zopeFolder.manage_addProduct['OFSP'].manage_addFile( + id=nid, + title=title, + file=file.read() + ) + except: + if (count): + count += 1 + else: + count = 1 + return self.zopeFileUpload(resourceType, currentFolder, count) + return self.sendUploadResults( 0 ) + +class FCKeditorRequest(object): + "A wrapper around the request object" + def __init__(self, context=None): + r = context.REQUEST + self.request = r + + def has_key(self, key): + return self.request.has_key(key) + + def get(self, key, default=None): + return self.request.get(key, default) + +""" +Running from zope, you will need to modify this connector. +If you have uploaded the FCKeditor into Zope (like me), you need to +move this connector out of Zope, and replace the "connector" with an +alias as below. The key to it is to pass the Zope context in, as +we then have a like to the Zope context. + +## Script (Python) "connector.py" +##bind container=container +##bind context=context +##bind namespace= +##bind script=script +##bind subpath=traverse_subpath +##parameters=*args, **kws +##title=ALIAS +## + +import Products.zope as connector +return connector.FCKeditorConnectorZope(context=context).doResponse() +""" Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/test.html =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/test.html (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/test.html 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,210 @@ + + + + + FCKeditor - Connectors Tests + + + + + + + + + + + +
      + + + + + + + + +
      + Connector:
      + +
      +     + Current Folder
      +
      +     + Resource Type
      + +
      +
      + + + + + + + + + + +
      + Get Folders +     + Get Folders and Files +     + Create Folder +     +
      + File Upload
      + + +
      +
      +
      + URL: +
      + +
      + + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/uploadtest.html =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/uploadtest.html (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/filemanager/connectors/uploadtest.html 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,192 @@ + + + + FCKeditor - Uploaders Tests + + + + + + + + + + + +
      + + + + + + + + +
      + Select the "File Uploader" to use:
      + +
      + Resource Type
      + +
      + Current Folder:
      + +
             + Custom Uploader URL:
      + +
      +
      + + + + + + +
      +
      + Upload a new file:
      +
      + + +
      +
             + Uploaded File URL:
      + +
      +
      + Post URL:   +
      + +
      + + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/js/fckadobeair.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/js/fckadobeair.js (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/js/fckadobeair.js 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,176 @@ +?/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * Compatibility code for Adobe AIR. + */ + +if ( FCKBrowserInfo.IsAIR ) +{ + var FCKAdobeAIR = (function() + { + /* + * ### Private functions. + */ + + var getDocumentHead = function( doc ) + { + var head ; + var heads = doc.getElementsByTagName( 'head' ) ; + + if( heads && heads[0] ) + head = heads[0] ; + else + { + head = doc.createElement( 'head' ) ; + doc.documentElement.insertBefore( head, doc.documentElement.firstChild ) ; + } + + return head ; + } ; + + /* + * ### Public interface. + */ + return { + FCKeditorAPI_Evaluate : function( parentWindow, script ) + { + // TODO : This one doesn't work always. The parent window will + // point to an anonymous function in this window. If this + // window is destroyied the parent window will be pointing to + // an invalid reference. + + // Evaluate the script in this window. + eval( script ) ; + + // Point the FCKeditorAPI property of the parent window to the + // local reference. + parentWindow.FCKeditorAPI = window.FCKeditorAPI ; + }, + + EditingArea_Start : function( doc, html ) + { + // Get the HTML for the . + var headInnerHtml = html.match( /([\s\S]*)<\/head>/i )[1] ; + + if ( headInnerHtml && headInnerHtml.length > 0 ) + { + // Inject the HTML inside a
      . + // Do that before getDocumentHead because WebKit moves + // elements to the at this point. + var div = doc.createElement( 'div' ) ; + div.innerHTML = headInnerHtml ; + + // Move the
      nodes to . + FCKDomTools.MoveChildren( div, getDocumentHead( doc ) ) ; + } + + doc.body.innerHTML = html.match( /([\s\S]*)<\/body>/i )[1] ; + + //prevent clicking on hyperlinks and navigating away + doc.addEventListener('click', function( ev ) + { + ev.preventDefault() ; + ev.stopPropagation() ; + }, true ) ; + }, + + Panel_Contructor : function( doc, baseLocation ) + { + var head = getDocumentHead( doc ) ; + + // Set the href. + head.appendChild( doc.createElement('base') ).href = baseLocation ; + + doc.body.style.margin = '0px' ; + doc.body.style.padding = '0px' ; + }, + + ToolbarSet_GetOutElement : function( win, outMatch ) + { + var toolbarTarget = win.parent ; + + var targetWindowParts = outMatch[1].split( '.' ) ; + while ( targetWindowParts.length > 0 ) + { + var part = targetWindowParts.shift() ; + if ( part.length > 0 ) + toolbarTarget = toolbarTarget[ part ] ; + } + + toolbarTarget = toolbarTarget.document.getElementById( outMatch[2] ) ; + }, + + ToolbarSet_InitOutFrame : function( doc ) + { + var head = getDocumentHead( doc ) ; + + head.appendChild( doc.createElement('base') ).href = window.document.location ; + + var targetWindow = doc.defaultView; + + targetWindow.adjust = function() + { + targetWindow.frameElement.height = doc.body.scrollHeight; + } ; + + targetWindow.onresize = targetWindow.adjust ; + targetWindow.setTimeout( targetWindow.adjust, 0 ) ; + + doc.body.style.overflow = 'hidden'; + doc.body.innerHTML = document.getElementById( 'xToolbarSpace' ).innerHTML ; + } + } ; + })(); + + /* + * ### Overrides + */ + ( function() + { + // Save references for override reuse. + var _Original_FCKPanel_Window_OnFocus = FCKPanel_Window_OnFocus ; + var _Original_FCKPanel_Window_OnBlur = FCKPanel_Window_OnBlur ; + var _Original_FCK_StartEditor = FCK.StartEditor ; + + FCKPanel_Window_OnFocus = function( e, panel ) + { + // Call the original implementation. + _Original_FCKPanel_Window_OnFocus.call( this, e, panel ) ; + + if ( panel._focusTimer ) + clearTimeout( panel._focusTimer ) ; + } + + FCKPanel_Window_OnBlur = function( e, panel ) + { + // Delay the execution of the original function. + panel._focusTimer = FCKTools.SetTimeout( _Original_FCKPanel_Window_OnBlur, 100, this, [ e, panel ] ) ; + } + + FCK.StartEditor = function() + { + // Force pointing to the CSS files instead of using the inline CSS cached styles. + window.FCK_InternalCSS = FCKConfig.FullBasePath + 'css/fck_internal.css' ; + window.FCK_ShowTableBordersCSS = FCKConfig.FullBasePath + 'css/fck_showtableborders_gecko.css' ; + + _Original_FCK_StartEditor.apply( this, arguments ) ; + } + })(); +} Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/js/fckeditorcode_gecko.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/js/fckeditorcode_gecko.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/js/fckeditorcode_gecko.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,98 +1,108 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben - * + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * * == BEGIN LICENSE == - * + * * Licensed under the terms of any of the following licenses at your * choice: - * + * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html - * + * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html - * + * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html - * + * * == END LICENSE == - * + * * This file has been compressed for better performance. The original source * can be found at "editor/_source". */ -var FCK_STATUS_NOTLOADED=window.parent.FCK_STATUS_NOTLOADED=0;var FCK_STATUS_ACTIVE=window.parent.FCK_STATUS_ACTIVE=1;var FCK_STATUS_COMPLETE=window.parent.FCK_STATUS_COMPLETE=2;var FCK_TRISTATE_OFF=window.parent.FCK_TRISTATE_OFF=0;var FCK_TRISTATE_ON=window.parent.FCK_TRISTATE_ON=1;var FCK_TRISTATE_DISABLED=window.parent.FCK_TRISTATE_DISABLED=-1;var FCK_UNKNOWN=window.parent.FCK_UNKNOWN=-9;var FCK_TOOLBARITEM_ONLYICON=window.parent.FCK_TOOLBARITEM_ONLYICON=0;var FCK_TOOLBARITEM_ONLYTEXT=window.parent.FCK_TOOLBARITEM_ONLYTEXT=1;var FCK_TOOLBARITEM_ICONTEXT=window.parent.FCK_TOOLBARITEM_ICONTEXT=2;var FCK_EDITMODE_WYSIWYG=window.parent.FCK_EDITMODE_WYSIWYG=0;var FCK_EDITMODE_SOURCE=window.parent.FCK_EDITMODE_SOURCE=1;var FCK_IMAGES_PATH='images/';var FCK_SPACER_PATH='images/spacer.gif';var CTRL=1000;var SHIFT=2000;var ALT=4000; -String.prototype.Contains=function(A){return (this.indexOf(A)>-1);};String.prototype.Equals=function(){var A=arguments;if (A.length==1&&A[0].pop) A=A[0];for (var i=0;iC) return false;if (B){var E=new RegExp(A+'$','i');return E.test(this);}else return (D==0||this.substr(C-D,D)==A);};String.prototype.Remove=function(A,B){var s='';if (A>0) s=this.substring(0,A);if (A+B0?'':'';var A=FCK.KeystrokeHandler=new FCKKeystrokeHandler();A.OnKeystroke=_FCK_KeystrokeHandler_OnKeystroke;A.SetKeystrokes(FCKConfig.Keystrokes);if (FCKBrowserInfo.IsIE7){if ((CTRL+86/*V*/) in A.Keystrokes) A.SetKeystrokes([CTRL+86,true]);if ((SHIFT+45/*INS*/) in A.Keystrokes) A.SetKeystrokes([SHIFT+45,true]);};this.EditingArea=new FCKEditingArea(document.getElementById('xEditingArea'));this.EditingArea.FFSpellChecker=false;FCKListsLib.Setup();this.SetHTML(this.GetLinkedFieldValue(),true);},Focus:function(){FCK.EditingArea.Focus();},SetStatus:function(A){this.Status=A;if (A==1){FCKFocusManager.AddWindow(window,true);if (FCKBrowserInfo.IsIE) FCKFocusManager.AddWindow(window.frameElement,true);if (FCKConfig.StartupFocus) FCK.Focus();};this.Events.FireEvent('OnStatusChange',A);},FixBody:function(){var A=FCKConfig.EnterMode;if (A!='p'&&A!='div') return;var B=this.EditorDocument;if (!B) return;var C=B.body;if (!C) return;FCKDomTools.TrimNode(C);var D=C.firstChild;var E;while (D){var F=false;switch (D.nodeType){case 1:if (!FCKListsLib.BlockElements[D.nodeName.toLowerCase()]) F=true;break;case 3:if (E||D.nodeValue.Trim().length>0) F=true;};if (F){var G=D.parentNode;if (!E) E=G.insertBefore(B.createElement(A),D);E.appendChild(G.removeChild(D));D=E.nextSibling;}else{if (E){FCKDomTools.TrimNode(E);E=null;};D=D.nextSibling;}};if (E) FCKDomTools.TrimNode(E);},GetXHTML:function(A){if (FCK.EditMode==1) return FCK.EditingArea.Textarea.value;this.FixBody();var B;var C=FCK.EditorDocument;if (!C) return null;if (FCKConfig.FullPage){B=FCKXHtml.GetXHTML(C.getElementsByTagName('html')[0],true,A);if (FCK.DocTypeDeclaration&&FCK.DocTypeDeclaration.length>0) B=FCK.DocTypeDeclaration+'\n'+B;if (FCK.XmlDeclaration&&FCK.XmlDeclaration.length>0) B=FCK.XmlDeclaration+'\n'+B;}else{B=FCKXHtml.GetXHTML(C.body,false,A);if (FCKConfig.IgnoreEmptyParagraphValue&&FCKRegexLib.EmptyOutParagraph.test(B)) B='';};B=FCK.ProtectEventsRestore(B);if (FCKBrowserInfo.IsIE) B=B.replace(FCKRegexLib.ToReplace,'$1');return FCKConfig.ProtectedSource.Revert(B);},UpdateLinkedField:function(){FCK.LinkedField.value=FCK.GetXHTML(FCKConfig.FormatOutput);FCK.Events.FireEvent('OnAfterLinkedFieldUpdate');},RegisteredDoubleClickHandlers:{},OnDoubleClick:function(A){var B=FCK.RegisteredDoubleClickHandlers[A.tagName];if (B) B(A);},RegisterDoubleClickHandler:function(A,B){FCK.RegisteredDoubleClickHandlers[B.toUpperCase()]=A;},OnAfterSetHTML:function(){FCKDocumentProcessor.Process(FCK.EditorDocument);FCKUndo.SaveUndoStep();FCK.Events.FireEvent('OnSelectionChange');FCK.Events.FireEvent('OnAfterSetHTML');},ProtectUrls:function(A){A=A.replace(FCKRegexLib.ProtectUrlsA,'$& _fcksavedurl=$1');A=A.replace(FCKRegexLib.ProtectUrlsImg,'$& _fcksavedurl=$1');return A;},ProtectEvents:function(A){return A.replace(FCKRegexLib.TagsWithEvent,_FCK_ProtectEvents_ReplaceTags);},ProtectEventsRestore:function(A){return A.replace(FCKRegexLib.ProtectedEvents,_FCK_ProtectEvents_RestoreEvents);},ProtectTags:function(A){var B=FCKConfig.ProtectedTags;if (FCKBrowserInfo.IsIE) B+=B.length>0?'|ABBR':'ABBR';var C;if (B.length>0){C=new RegExp('<('+B+')(?!\w|:)','gi');A=A.replace(C,'','gi');A=A.replace(C,'<\/FCK:$1>');};B='META';if (FCKBrowserInfo.IsIE) B+='|HR';C=new RegExp('<(('+B+')(?=\s|>)[\s\S]*?)/?>','gi');A=A.replace(C,'');return A;},SetHTML:function(A,B){this.EditingArea.Mode=FCK.EditMode;if (FCK.EditMode==0){A=FCKConfig.ProtectedSource.Protect(A);A=A.replace(FCKRegexLib.InvalidSelfCloseTags,'$1>');A=FCK.ProtectEvents(A);A=FCK.ProtectUrls(A);A=FCK.ProtectTags(A);if (FCKBrowserInfo.IsGecko){A=A.replace(FCKRegexLib.StrongOpener,'');A=A.replace(FCKRegexLib.EmOpener,'');};this._ForceResetIsDirty=(B===true);var C='';if (FCKConfig.FullPage){if (!FCKRegexLib.HeadOpener.test(A)){if (!FCKRegexLib.HtmlOpener.test(A)) A=''+A+'';A=A.replace(FCKRegexLib.HtmlOpener,'$&');};FCK.DocTypeDeclaration=A.match(FCKRegexLib.DocTypeTag);if (FCKBrowserInfo.IsIE) C=FCK._GetBehaviorsStyle();else if (FCKConfig.ShowBorders) C='';C+='';C=A.replace(FCKRegexLib.HeadCloser,C+'$&');if (FCK.TempBaseTag.length>0&&!FCKRegexLib.HasBaseTag.test(A)) C=C.replace(FCKRegexLib.HeadOpener,'$&'+FCK.TempBaseTag);}else{C=FCKConfig.DocType+'';if (FCKBrowserInfo.IsIE) C+=FCK._GetBehaviorsStyle();else if (FCKConfig.ShowBorders) C+='';C+=FCK.TempBaseTag;var D='0) D+=' id="'+FCKConfig.BodyId+'"';if (FCKConfig.BodyClass&&FCKConfig.BodyClass.length>0) D+=' class="'+FCKConfig.BodyClass+'"';C+=''+D+'>';if (FCKBrowserInfo.IsGecko&&(A.length==0||FCKRegexLib.EmptyParagraph.test(A))) C+=GECKO_BOGUS;else C+=A;C+='';};this.EditingArea.OnLoad=_FCK_EditingArea_OnLoad;this.EditingArea.Start(C);}else{FCK.EditorWindow=null;FCK.EditorDocument=null;this.EditingArea.OnLoad=null;this.EditingArea.Start(A);this.EditingArea.Textarea._FCKShowContextMenu=true;FCK.EnterKeyHandler=null;if (B) this.ResetIsDirty();FCK.KeystrokeHandler.AttachToElement(this.EditingArea.Textarea);this.EditingArea.Textarea.focus();FCK.Events.FireEvent('OnAfterSetHTML');};if (FCKBrowserInfo.IsGecko) window.onresize();},HasFocus:false,RedirectNamedCommands:{},ExecuteNamedCommand:function(A,B,C){FCKUndo.SaveUndoStep();if (!C&&FCK.RedirectNamedCommands[A]!=null) FCK.ExecuteRedirectedNamedCommand(A,B);else{FCK.Focus();FCK.EditorDocument.execCommand(A,false,B);FCK.Events.FireEvent('OnSelectionChange');};FCKUndo.SaveUndoStep();},GetNamedCommandState:function(A){try{if (!FCK.EditorDocument.queryCommandEnabled(A)) return -1;else return FCK.EditorDocument.queryCommandState(A)?1:0;}catch (e){return 0;}},GetNamedCommandValue:function(A){var B='';var C=FCK.GetNamedCommandState(A);if (C==-1) return null;try{B=this.EditorDocument.queryCommandValue(A);}catch(e) {};return B?B:'';},PasteFromWord:function(){FCKDialog.OpenDialog('FCKDialog_Paste',FCKLang.PasteFromWord,'dialog/fck_paste.html',400,330,'Word');},Preview:function(){var A=FCKConfig.ScreenWidth*0.8;var B=FCKConfig.ScreenHeight*0.7;var C=(FCKConfig.ScreenWidth-A)/2;var D=window.open('',null,'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+A+',height='+B+',left='+C);var E;if (FCKConfig.FullPage){if (FCK.TempBaseTag.length>0) E=FCK.TempBaseTag+FCK.GetXHTML();else E=FCK.GetXHTML();}else{E=FCKConfig.DocType+''+FCK.TempBaseTag+''+FCKLang.Preview+''+_FCK_GetEditorAreaStyleTags()+''+FCK.GetXHTML()+'';};D.document.write(E);D.document.close();},SwitchEditMode:function(A){var B=(FCK.EditMode==0);var C=FCK.IsDirty();var D;if (B){if (!A&&FCKBrowserInfo.IsIE) FCKUndo.SaveUndoStep();D=FCK.GetXHTML(FCKConfig.FormatSource);if (D==null) return false;}else D=this.EditingArea.Textarea.value;FCK.EditMode=B?1:0;FCK.SetHTML(D,!C);FCK.Focus();FCKTools.RunFunction(FCK.ToolbarSet.RefreshModeState,FCK.ToolbarSet);return true;},CreateElement:function(A){var e=FCK.EditorDocument.createElement(A);return FCK.InsertElementAndGetIt(e);},InsertElementAndGetIt:function(e){e.setAttribute('FCKTempLabel','true');this.InsertElement(e);var A=FCK.EditorDocument.getElementsByTagName(e.tagName);for (var i=0;i/g,/\r/g,/\n/g],[''',''','"','=','<','>',' ',' '])+'"';};function _FCK_ProtectEvents_RestoreEvents(A,B){return B.ReplaceAll([/'/g,/"/g,/=/g,/</g,/>/g,/ /g,/ /g,/'/g],["'",'"','=','<','>','\r','\n','&']);};function _FCK_EditingArea_OnLoad(){FCK.EditorWindow=FCK.EditingArea.Window;FCK.EditorDocument=FCK.EditingArea.Document;FCK.InitializeBehaviors();if (!FCKConfig.DisableEnterKeyHandler) FCK.EnterKeyHandler=new FCKEnterKey(FCK.EditorWindow,FCKConfig.EnterMode,FCKConfig.ShiftEnterMode);FCK.KeystrokeHandler.AttachToElement(FCK.EditorDocument);if (FCK._ForceResetIsDirty) FCK.ResetIsDirty();if (FCKBrowserInfo.IsIE&&FCK.HasFocus) FCK.EditorDocument.body.setActive();FCK.OnAfterSetHTML();if (FCK.Status!=0) return;FCK.SetStatus(1);};function _FCK_GetEditorAreaStyleTags(){var A='';var B=FCKConfig.EditorAreaCSS;for (var i=0;i';return A;};function _FCK_KeystrokeHandler_OnKeystroke(A,B){if (FCK.Status!=2) return false;if (FCK.EditMode==0){if (B=='Paste') return!FCK.Events.FireEvent('OnPaste');}else{if (B.Equals('Paste','Undo','Redo','SelectAll')) return false;};var C=FCK.Commands.GetCommand(B);return (C.Execute.apply(C,FCKTools.ArgumentsToArray(arguments,2))!==false);};(function(){var A=window.parent.document;var B=A.getElementById(FCK.Name);var i=0;while (B||i==0){if (B&&B.tagName.toLowerCase().Equals('input','textarea')){FCK.LinkedField=B;break;};B=A.getElementsByName(FCK.Name)[i++];}})();var FCKTempBin={Elements:[],AddElement:function(A){var B=this.Elements.length;this.Elements[B]=A;return B;},RemoveElement:function(A){var e=this.Elements[A];this.Elements[A]=null;return e;},Reset:function(){var i=0;while (i');A=A.replace(FCKRegexLib.EmOpener,'');var B=FCKSelection.Delete();var C=B.getRangeAt(0);var D=C.createContextualFragment(A);var E=D.lastChild;C.insertNode(D);FCKSelection.SelectNode(E);FCKSelection.Collapse(false);this.Focus();};FCK.InsertElement=function(A){var B=FCKSelection.Delete();var C=B.getRangeAt(0);C.insertNode(A);FCKSelection.SelectNode(A);FCKSelection.Collapse(false);this.Focus();};FCK.PasteAsPlainText=function(){FCKTools.RunFunction(FCKDialog.OpenDialog,FCKDialog,['FCKDialog_Paste',FCKLang.PasteAsText,'dialog/fck_paste.html',400,330,'PlainText']);};FCK.GetClipboardHTML=function(){return '';};FCK.CreateLink=function(A){FCK.ExecuteNamedCommand('Unlink');if (A.length>0){var B='javascript:void(0);/*'+(new Date().getTime())+'*/';FCK.ExecuteNamedCommand('CreateLink',B);var C=this.EditorDocument.evaluate("//a[@href='"+B+"']",this.EditorDocument.body,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;if (C){C.href=A;return C;}};return null;}; -var FCKConfig=FCK.Config={};if (document.location.protocol=='file:'){FCKConfig.BasePath=decodeURIComponent(document.location.pathname.substr(1));FCKConfig.BasePath=FCKConfig.BasePath.replace(/\\/gi, '/');FCKConfig.BasePath='file://'+FCKConfig.BasePath.substring(0,FCKConfig.BasePath.lastIndexOf('/')+1);FCKConfig.FullBasePath=FCKConfig.BasePath;}else{FCKConfig.BasePath=document.location.pathname.substring(0,document.location.pathname.lastIndexOf('/')+1);FCKConfig.FullBasePath=document.location.protocol+'//'+document.location.host+FCKConfig.BasePath;};FCKConfig.EditorPath=FCKConfig.BasePath.replace(/editor\/$/,'');try{FCKConfig.ScreenWidth=screen.width;FCKConfig.ScreenHeight=screen.height;}catch (e){FCKConfig.ScreenWidth=800;FCKConfig.ScreenHeight=600;};FCKConfig.ProcessHiddenField=function(){this.PageConfig={};var A=window.parent.document.getElementById(FCK.Name+'___Config');if (!A) return;var B=A.value.split('&');for (var i=0;i0&&!isNaN(E)) this.PageConfig[D]=parseInt(E,10);else this.PageConfig[D]=E;}};function FCKConfig_LoadPageConfig(){var A=FCKConfig.PageConfig;for (var B in A) FCKConfig[B]=A[B];};function FCKConfig_PreProcess(){var A=FCKConfig;if (A.AllowQueryStringDebug){try{if ((/fckdebug=true/i).test(window.top.location.search)) A.Debug=true;}catch (e) {/*Ignore it. Much probably we are inside a FRAME where the "top" is in another domain (security error).*/}};if (!A.PluginsPath.EndsWith('/')) A.PluginsPath+='/';if (typeof(A.EditorAreaCSS)=='string') A.EditorAreaCSS=[A.EditorAreaCSS];var B=A.ToolbarComboPreviewCSS;if (!B||B.length==0) A.ToolbarComboPreviewCSS=A.EditorAreaCSS;else if (typeof(B)=='string') A.ToolbarComboPreviewCSS=[B];};FCKConfig.ToolbarSets={};FCKConfig.Plugins={};FCKConfig.Plugins.Items=[];FCKConfig.Plugins.Add=function(A,B,C){FCKConfig.Plugins.Items.AddItem([A,B,C]);};FCKConfig.ProtectedSource={};FCKConfig.ProtectedSource.RegexEntries=[//g,//gi,//gi];FCKConfig.ProtectedSource.Add=function(A){this.RegexEntries.AddItem(A);};FCKConfig.ProtectedSource.Protect=function(A){function _Replace(protectedSource){var B=FCKTempBin.AddElement(protectedSource);return '';};for (var i=0;i|>)/g,_Replace);} -var FCKDebug={};FCKDebug._GetWindow=function(){if (!this.DebugWindow||this.DebugWindow.closed) this.DebugWindow=window.open(FCKConfig.BasePath+'fckdebug.html','FCKeditorDebug','menubar=no,scrollbars=yes,resizable=yes,location=no,toolbar=no,width=600,height=500',true);return this.DebugWindow;};FCKDebug.Output=function(A,B,C){if (!FCKConfig.Debug) return;try{this._GetWindow().Output(A,B);}catch (e) {}};FCKDebug.OutputObject=function(A,B){if (!FCKConfig.Debug) return;try{this._GetWindow().OutputObject(A,B);}catch (e) {}} -var FCKDomTools={MoveChildren:function(A,B){if (A==B) return;var C;while ((C=A.firstChild)) B.appendChild(A.removeChild(C));},TrimNode:function(A,B){this.LTrimNode(A);this.RTrimNode(A,B);},LTrimNode:function(A){var B;while ((B=A.firstChild)){if (B.nodeType==3){var C=B.nodeValue.LTrim();var D=B.nodeValue.length;if (C.length==0){A.removeChild(B);continue;}else if (C.length0) break;if (A.lastChild) A=A.lastChild;else return this.GetPreviousSourceElement(A,B,C,D);};return null;},GetNextSourceElement:function(A,B,C,D){if (!A) return null;if (A.nextSibling) A=A.nextSibling;else return this.GetNextSourceElement(A.parentNode,B,C,D);while (A){if (A.nodeType==1){if (C&&A.nodeName.IEquals(C)) break;if (!D||!A.nodeName.IEquals(D)) return A;}else if (B&&A.nodeType==3&&A.nodeValue.RTrim().length>0) break;if (A.firstChild) A=A.firstChild;else return this.GetNextSourceElement(A,B,C,D);};return null;},InsertAfterNode:function(A,B){return A.parentNode.insertBefore(B,A.nextSibling);},GetParents:function(A){var B=[];while (A){B.splice(0,0,A);A=A.parentNode;};return B;},GetIndexOf:function(A){var B=A.parentNode?A.parentNode.firstChild:null;var C=-1;while (B){C++;if (B==A) return C;B=B.nextSibling;};return-1;}}; -var GECKO_BOGUS='
      ';var FCKTools={};FCKTools.CreateBogusBR=function(A){var B=A.createElement('br');B.setAttribute('type','_moz');return B;};FCKTools.AppendStyleSheet=function(A,B){if (typeof(B)=='string') return this._AppendStyleSheet(A,B);else{var C=[];for (var i=0;i/g,'>');return A;};FCKTools.HTMLDecode=function(A){if (!A) return '';A=A.replace(/>/g,'>');A=A.replace(/</g,'<');A=A.replace(/&/g,'&');return A;};FCKTools.AddSelectOption=function(A,B,C){var D=FCKTools.GetElementDocument(A).createElement("OPTION");D.text=B;D.value=C;A.options.add(D);return D;};FCKTools.RunFunction=function(A,B,C,D){if (A) this.SetTimeout(A,0,B,C,D);};FCKTools.SetTimeout=function(A,B,C,D,E){return (E||window).setTimeout(function(){if (D) A.apply(C,[].concat(D));else A.apply(C);},B);};FCKTools.SetInterval=function(A,B,C,D,E){return (E||window).setInterval(function(){A.apply(C,D||[]);},B);};FCKTools.ConvertStyleSizeToHtml=function(A){return A.EndsWith('%')?A:parseInt(A,10);};FCKTools.ConvertHtmlSizeToStyle=function(A){return A.EndsWith('%')?A:(A+'px');};FCKTools.GetElementAscensor=function(A,B){var e=A;var C=","+B.toUpperCase()+",";while (e){if (C.indexOf(","+e.nodeName.toUpperCase()+",")!=-1) return e;e=e.parentNode;};return null;};FCKTools.CreateEventListener=function(A,B){var f=function(){var C=[];for (var i=0;i0) B[B.length]=D;C(parent.childNodes[i]);}};C(A);return B;};FCKTools.RemoveOuterTags=function(e){var A=e.ownerDocument.createDocumentFragment();for (var i=0;i0){B.Class=A.className;A.className='';};var C=A.getAttribute('style');if (C&&C.length>0){B.Inline=C;A.setAttribute('style','',0);};return B;};FCKTools.RestoreStyles=function(A,B){A.className=B.Class||'';if (B.Inline) A.setAttribute('style',B.Inline,0);else A.removeAttribute('style',0);};FCKTools.RegisterDollarFunction=function(A){A.$=function(id){return this.document.getElementById(id);};};FCKTools.AppendElement=function(A,B){return A.appendChild(A.ownerDocument.createElement(B));};FCKTools.GetElementPosition=function(A,B){var c={ X:0,Y:0 };var C=B||window;var D=FCKTools.GetElementWindow(A);while (A){var E=D.getComputedStyle(A,'').position;if (E&&E!='static'&&A.style.zIndex!=FCKConfig.FloatingPanelsZIndex) break;c.X+=A.offsetLeft-A.scrollLeft;c.Y+=A.offsetTop-A.scrollTop;if (A.offsetParent) A=A.offsetParent;else{if (D!=C){A=D.frameElement;if (A) D=FCKTools.GetElementWindow(A);}else{c.X+=A.scrollLeft;c.Y+=A.scrollTop;break;}}};return c;} -var FCKeditorAPI;function InitializeAPI(){var A=window.parent;if (!(FCKeditorAPI=A.FCKeditorAPI)){var B='var FCKeditorAPI = {Version : "2.4.2",VersionBuild : "14978",__Instances : new Object(),GetInstance : function( name ){return this.__Instances[ name ];},_FormSubmit : function(){for ( var name in FCKeditorAPI.__Instances ){var oEditor = FCKeditorAPI.__Instances[ name ] ;if ( oEditor.GetParentForm && oEditor.GetParentForm() == this )oEditor.UpdateLinkedField() ;}this._FCKOriginalSubmit() ;},_FunctionQueue : {Functions : new Array(),IsRunning : false,Add : function( f ){this.Functions.push( f );if ( !this.IsRunning )this.StartNext();},StartNext : function(){var aQueue = this.Functions ;if ( aQueue.length > 0 ){this.IsRunning = true;aQueue[0].call();}else this.IsRunning = false;},Remove : function( f ){var aQueue = this.Functions;var i = 0, fFunc;while( (fFunc = aQueue[ i ]) ){if ( fFunc == f )aQueue.splice( i,1 );i++ ;}this.StartNext();}}}';if (A.execScript) A.execScript(B,'JavaScript');else{if (FCKBrowserInfo.IsGecko10){eval.call(A,B);}else if (FCKBrowserInfo.IsSafari){var C=A.document;var D=C.createElement('script');D.appendChild(C.createTextNode(B));C.documentElement.appendChild(D);}else A.eval(B);};FCKeditorAPI=A.FCKeditorAPI;};FCKeditorAPI.__Instances[FCK.Name]=FCK;};function _AttachFormSubmitToAPI(){var A=FCK.GetParentForm();if (A){FCKTools.AddEventListener(A,'submit',FCK.UpdateLinkedField);if (!A._FCKOriginalSubmit&&(typeof(A.submit)=='function'||(!A.submit.tagName&&!A.submit.length))){A._FCKOriginalSubmit=A.submit;A.submit=FCKeditorAPI._FormSubmit;}}};function FCKeditorAPI_Cleanup(){delete FCKeditorAPI.__Instances[FCK.Name];};FCKTools.AddEventListener(window,'unload',FCKeditorAPI_Cleanup); -var FCKImagePreloader=function(){this._Images=[];};FCKImagePreloader.prototype={AddImages:function(A){if (typeof(A)=='string') A=A.split(';');this._Images=this._Images.concat(A);},Start:function(){var A=this._Images;this._PreloadCount=A.length;for (var i=0;i]*\>)([\s\S]*)(\<\/body\>[\s\S]*)/i,ToReplace:/___fcktoreplace:([\w]+)/ig,MetaHttpEquiv:/http-equiv\s*=\s*["']?([^"' ]+)/i,HasBaseTag:/]*>/i,HeadOpener:/]*>/i,HeadCloser:/<\/head\s*>/i,FCK_Class:/(\s*FCK__[A-Za-z]*\s*)/,ElementName:/(^[a-z_:][\w.\-:]*\w$)|(^[a-z_]$)/,ForceSimpleAmpersand:/___FCKAmp___/g,SpaceNoClose:/\/>/g,EmptyParagraph:/^<([^ >]+)[^>]*>\s*(<\/\1>)?$/,EmptyOutParagraph:/^<([^ >]+)[^>]*>(?:\s*| )(<\/\1>)?$/,TagBody:/>])/gi,StrongCloser:/<\/STRONG>/gi,EmOpener:/])/gi,EmCloser:/<\/EM>/gi,GeckoEntitiesMarker:/#\?-\:/g,ProtectUrlsImg:/]+))/gi,ProtectUrlsA:/]+))/gi,Html4DocType:/HTML 4\.0 Transitional/i,DocTypeTag:/]*>/i,TagsWithEvent:/<[^\>]+ on\w+[\s\r\n]*=[\s\r\n]*?('|")[\s\S]+?\>/g,EventAttributes:/\s(on\w+)[\s\r\n]*=[\s\r\n]*?('|")([\s\S]*?)\2/g,ProtectedEvents:/\s\w+_fckprotectedatt="([^"]+)"/g,StyleProperties:/\S+\s*:/g,InvalidSelfCloseTags:/(<(?!base|meta|link|hr|br|param|img|area|input)([a-zA-Z0-9:]+)[^>]*)\/>/gi}; -var FCKListsLib={BlockElements:{ address:1,blockquote:1,center:1,div:1,dl:1,fieldset:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,noscript:1,ol:1,p:1,pre:1,script:1,table:1,ul:1 },NonEmptyBlockElements:{ p:1,div:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,address:1,pre:1,ol:1,ul:1,li:1,td:1,th:1 },InlineChildReqElements:{ abbr:1,acronym:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,samp:1,small:1,span:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1 },EmptyElements:{ base:1,meta:1,link:1,hr:1,br:1,param:1,img:1,area:1,input:1 },PathBlockElements:{ address:1,blockquote:1,dl:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,p:1,pre:1,ol:1,ul:1,li:1,dt:1,de:1 },PathBlockLimitElements:{ body:1,td:1,th:1,caption:1,form:1 },Setup:function(){if (FCKConfig.EnterMode=='div') this.PathBlockElements.div=1;else this.PathBlockLimitElements.div=1;}}; -var FCKLanguageManager=FCK.Language={AvailableLanguages:{af:'Afrikaans',ar:'Arabic',bg:'Bulgarian',bn:'Bengali/Bangla',bs:'Bosnian',ca:'Catalan',cs:'Czech',da:'Danish',de:'German',el:'Greek',en:'English','en-au':'English (Australia)','en-ca':'English (Canadian)','en-uk':'English (United Kingdom)',eo:'Esperanto',es:'Spanish',et:'Estonian',eu:'Basque',fa:'Persian',fi:'Finnish',fo:'Faroese',fr:'French',gl:'Galician',he:'Hebrew',hi:'Hindi',hr:'Croatian',hu:'Hungarian',it:'Italian',ja:'Japanese',km:'Khmer',ko:'Korean',lt:'Lithuanian',lv:'Latvian',mn:'Mongolian',ms:'Malay',nb:'Norwegian Bokmal',nl:'Dutch',no:'Norwegian',pl:'Polish',pt:'Portuguese (Portugal)','pt-br':'Portuguese (Brazil)',ro:'Romanian',ru:'Russian',sk:'Slovak',sl:'Slovenian',sr:'Serbian (Cyrillic)','sr-latn':'Serbian (Latin)',sv:'Swedish',th:'Thai',tr:'Turkish',uk:'Ukrainian',vi:'Vietnamese',zh:'Chinese Traditional','zh-cn':'Chinese Simplified'},GetActiveLanguage:function(){if (FCKConfig.AutoDetectLanguage){var A;if (navigator.userLanguage) A=navigator.userLanguage.toLowerCase();else if (navigator.language) A=navigator.language.toLowerCase();else{return FCKConfig.DefaultLanguage;};if (A.length>=5){A=A.substr(0,5);if (this.AvailableLanguages[A]) return A;};if (A.length>=2){A=A.substr(0,2);if (this.AvailableLanguages[A]) return A;}};return this.DefaultLanguage;},TranslateElements:function(A,B,C,D){var e=A.getElementsByTagName(B);var E,s;for (var i=0;i0) C+='|'+FCKConfig.AdditionalNumericEntities;FCKXHtmlEntities.EntitiesRegex=new RegExp(C,'g');} -var FCKXHtml={};FCKXHtml.CurrentJobNum=0;FCKXHtml.GetXHTML=function(A,B,C){FCKXHtmlEntities.Initialize();this._NbspEntity=(FCKConfig.ProcessHTMLEntities?'nbsp':'#160');var D=FCK.IsDirty();this._CreateNode=FCKConfig.ForceStrongEm?FCKXHtml_CreateNode_StrongEm:FCKXHtml_CreateNode_Normal;FCKXHtml.SpecialBlocks=[];this.XML=FCKTools.CreateXmlObject('DOMDocument');this.MainNode=this.XML.appendChild(this.XML.createElement('xhtml'));FCKXHtml.CurrentJobNum++;if (B) this._AppendNode(this.MainNode,A);else this._AppendChildNodes(this.MainNode,A,false);var E=this._GetMainXmlString();this.XML=null;E=E.substr(7,E.length-15).Trim();if (FCKBrowserInfo.IsGecko) E=E.replace(/$/,'');E=E.replace(FCKRegexLib.SpaceNoClose,' />');if (FCKConfig.ForceSimpleAmpersand) E=E.replace(FCKRegexLib.ForceSimpleAmpersand,'&');if (C) E=FCKCodeFormatter.Format(E);for (var i=0;i0;if (C) A.appendChild(this.XML.createTextNode(B.replace(FCKXHtmlEntities.EntitiesRegex,FCKXHtml_GetEntity)));return C;};function FCKXHtml_GetEntity(A){var B=FCKXHtmlEntities.Entities[A]||('#'+A.charCodeAt(0));return '#?-:'+B+';';};FCKXHtml._RemoveAttribute=function(A,B,C){var D=A.attributes.getNamedItem(C);if (D&&B.test(D.nodeValue)){var E=D.nodeValue.replace(B,'');if (E.length==0) A.attributes.removeNamedItem(C);else D.nodeValue=E;}};FCKXHtml.TagProcessors={img:function(A,B){if (!A.attributes.getNamedItem('alt')) FCKXHtml._AppendAttribute(A,'alt','');var C=B.getAttribute('_fcksavedurl');if (C!=null) FCKXHtml._AppendAttribute(A,'src',C);return A;},a:function(A,B){if (B.innerHTML.Trim().length==0&&!B.name) return false;var C=B.getAttribute('_fcksavedurl');if (C!=null) FCKXHtml._AppendAttribute(A,'href',C);if (FCKBrowserInfo.IsIE){FCKXHtml._RemoveAttribute(A,FCKRegexLib.FCK_Class,'class');if (B.name) FCKXHtml._AppendAttribute(A,'name',B.name);};A=FCKXHtml._AppendChildNodes(A,B,false);return A;},script:function(A,B){if (!A.attributes.getNamedItem('type')) FCKXHtml._AppendAttribute(A,'type','text/javascript');A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem(B.text)));return A;},style:function(A,B){if (!A.attributes.getNamedItem('type')) FCKXHtml._AppendAttribute(A,'type','text/css');A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem(B.innerHTML)));return A;},title:function(A,B){A.appendChild(FCKXHtml.XML.createTextNode(FCK.EditorDocument.title));return A;},table:function(A,B){if (FCKBrowserInfo.IsIE) FCKXHtml._RemoveAttribute(A,FCKRegexLib.FCK_Class,'class');A=FCKXHtml._AppendChildNodes(A,B,false);return A;},ol:function(A,B,C){if (B.innerHTML.Trim().length==0) return false;var D=C.lastChild;if (D&&D.nodeType==3) D=D.previousSibling;if (D&&D.nodeName.toUpperCase()=='LI'){B._fckxhtmljob=null;FCKXHtml._AppendNode(D,B);return false;};A=FCKXHtml._AppendChildNodes(A,B);return A;},span:function(A,B){if (B.innerHTML.length==0) return false;A=FCKXHtml._AppendChildNodes(A,B,false);return A;},iframe:function(A,B){var C=B.innerHTML;if (FCKBrowserInfo.IsGecko) C=FCKTools.HTMLDecode(C);C=C.replace(/\s_fcksavedurl="[^"]*"/g,'');A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem(C)));return A;}};FCKXHtml.TagProcessors.ul=FCKXHtml.TagProcessors.ol; -FCKXHtml._GetMainXmlString=function(){var A=new XMLSerializer();return A.serializeToString(this.MainNode);};FCKXHtml._AppendAttributes=function(A,B,C){var D=B.attributes;for (var n=0;n]*\>/gi;A.BlocksCloser=/\<\/(P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|TITLE|META|LINK|BASE|SCRIPT|LINK|TD|TH|AREA|OPTION)[^\>]*\>/gi;A.NewLineTags=/\<(BR|HR)[^\>]*\>/gi;A.MainTags=/\<\/?(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR)[^\>]*\>/gi;A.LineSplitter=/\s*\n+\s*/g;A.IncreaseIndent=/^\<(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL)[ \/\>]/i;A.DecreaseIndent=/^\<\/(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL)[ \>]/i;A.FormatIndentatorRemove=new RegExp('^'+FCKConfig.FormatIndentator);A.ProtectedTags=/(]*>)([\s\S]*?)(<\/PRE>)/gi;};FCKCodeFormatter._ProtectData=function(A,B,C,D){return B+'___FCKpd___'+FCKCodeFormatter.ProtectedData.AddItem(C)+D;};FCKCodeFormatter.Format=function(A){if (!this.Regex) this.Init();FCKCodeFormatter.ProtectedData=[];var B=A.replace(this.Regex.ProtectedTags,FCKCodeFormatter._ProtectData);B=B.replace(this.Regex.BlocksOpener,'\n$&');B=B.replace(this.Regex.BlocksCloser,'$&\n');B=B.replace(this.Regex.NewLineTags,'$&\n');B=B.replace(this.Regex.MainTags,'\n$&\n');var C='';var D=B.split(this.Regex.LineSplitter);B='';for (var i=0;i0) C.removeChild(C.childNodes[0]);if (this.Mode==0){var E=this.IFrame=D.createElement('iframe');E.src='javascript:void(0)';E.frameBorder=0;E.width=E.height='100%';C.appendChild(E);if (FCKBrowserInfo.IsIE) A=A.replace(/(]*?)\s*\/?>(?!\s*<\/base>)/gi,'$1>');else if (!B){if (FCKBrowserInfo.IsGecko) A=A.replace(/(]*>)\s*(<\/body>)/i,'$1'+GECKO_BOGUS+'$2');var F=A.match(FCKRegexLib.BodyContents);if (F){A=F[1]+' '+F[3];this._BodyHTML=F[2];}else this._BodyHTML=A;};this.Window=E.contentWindow;var G=this.Document=this.Window.document;G.open();G.write(A);G.close();if (FCKBrowserInfo.IsGecko10&&!B){this.Start(A,true);return;};this.Window._FCKEditingArea=this;if (FCKBrowserInfo.IsGecko10) this.Window.setTimeout(FCKEditingArea_CompleteStart,500);else FCKEditingArea_CompleteStart.call(this.Window);}else{var H=this.Textarea=D.createElement('textarea');H.className='SourceField';H.dir='ltr';H.style.width=H.style.height='100%';H.style.border='none';C.appendChild(H);H.value=A;FCKTools.RunFunction(this.OnLoad);}};function FCKEditingArea_CompleteStart(){if (!this.document.body){this.setTimeout(FCKEditingArea_CompleteStart,50);return;};var A=this._FCKEditingArea;A.MakeEditable();FCKTools.RunFunction(A.OnLoad);};FCKEditingArea.prototype.MakeEditable=function(){var A=this.Document;if (FCKBrowserInfo.IsIE){A.body.contentEditable=true;}else{try{A.body.spellcheck=(this.FFSpellChecker!==false);if (this._BodyHTML){A.body.innerHTML=this._BodyHTML;this._BodyHTML=null;};A.designMode='on';try{A.execCommand('styleWithCSS',false,FCKConfig.GeckoUseSPAN);}catch (e){A.execCommand('useCSS',false,!FCKConfig.GeckoUseSPAN);};A.execCommand('enableObjectResizing',false,!FCKConfig.DisableObjectResizing);A.execCommand('enableInlineTableEditing',false,!FCKConfig.DisableFFTableHandles);}catch (e) {}}};FCKEditingArea.prototype.Focus=function(){try{if (this.Mode==0){if (FCKBrowserInfo.IsIE&&this.Document.hasFocus()) return;if (FCKBrowserInfo.IsSafari) this.IFrame.focus();else{this.Window.focus();}}else{var A=FCKTools.GetElementDocument(this.Textarea);if ((!A.hasFocus||A.hasFocus())&&A.activeElement==this.Textarea) return;this.Textarea.focus();}}catch(e) {}};function FCKEditingArea_Cleanup(){this.TargetElement=null;this.IFrame=null;this.Document=null;this.Textarea=null;if (this.Window){this.Window._FCKEditingArea=null;this.Window=null;}}; -var FCKKeystrokeHandler=function(A){this.Keystrokes={};this.CancelCtrlDefaults=(A!==false);};FCKKeystrokeHandler.prototype.AttachToElement=function(A){FCKTools.AddEventListenerEx(A,'keydown',_FCKKeystrokeHandler_OnKeyDown,this);if (FCKBrowserInfo.IsGecko10||FCKBrowserInfo.IsOpera||(FCKBrowserInfo.IsGecko&&FCKBrowserInfo.IsMac)) FCKTools.AddEventListenerEx(A,'keypress',_FCKKeystrokeHandler_OnKeyPress,this);};FCKKeystrokeHandler.prototype.SetKeystrokes=function(){for (var i=0;i40))){B._CancelIt=true;if (A.preventDefault) return A.preventDefault();A.returnValue=false;A.cancelBubble=true;return false;};return true;};function _FCKKeystrokeHandler_OnKeyPress(A,B){if (B._CancelIt){if (A.preventDefault) return A.preventDefault();return false;};return true;} -var FCKListHandler={OutdentListItem:function(A){var B=A.parentNode;if (B.tagName.toUpperCase().Equals('UL','OL')){var C=FCKTools.GetElementDocument(A);var D=new FCKDocumentFragment(C);var E=D.RootNode;var F=false;var G=FCKDomTools.GetFirstChild(A,['UL','OL']);if (G){F=true;var H;while ((H=G.firstChild)) E.appendChild(G.removeChild(H));FCKDomTools.RemoveNode(G);};var I;var J=false;while ((I=A.nextSibling)){if (!F&&I.nodeType==1&&I.nodeName.toUpperCase()=='LI') J=F=true;E.appendChild(I.parentNode.removeChild(I));if (!J&&I.nodeType==1&&I.nodeName.toUpperCase().Equals('UL','OL')) FCKDomTools.RemoveNode(I,true);};var K=B.parentNode.tagName.toUpperCase();var L=(K=='LI');if (L||K.Equals('UL','OL')){if (F){var G=B.cloneNode(false);D.AppendTo(G);A.appendChild(G);}else if (L) D.InsertAfterNode(B.parentNode);else D.InsertAfterNode(B);if (L) FCKDomTools.InsertAfterNode(B.parentNode,B.removeChild(A));else FCKDomTools.InsertAfterNode(B,B.removeChild(A));}else{if (F){var N=B.cloneNode(false);D.AppendTo(N);FCKDomTools.InsertAfterNode(B,N);};var O=C.createElement(FCKConfig.EnterMode=='p'?'p':'div');FCKDomTools.MoveChildren(B.removeChild(A),O);FCKDomTools.InsertAfterNode(B,O);if (FCKConfig.EnterMode=='br'){if (FCKBrowserInfo.IsGecko) O.parentNode.insertBefore(FCKTools.CreateBogusBR(C),O);else FCKDomTools.InsertAfterNode(O,FCKTools.CreateBogusBR(C));FCKDomTools.RemoveNode(O,true);}};if (this.CheckEmptyList(B)) FCKDomTools.RemoveNode(B,true);}},CheckEmptyList:function(A){return (FCKDomTools.GetFirstChild(A,'LI')==null);},CheckListHasContents:function(A){var B=A.firstChild;while (B){switch (B.nodeType){case 1:if (!B.nodeName.IEquals('UL','LI')) return true;break;case 3:if (B.nodeValue.Trim().length>0) return true;};B=B.nextSibling;};return false;}}; -var FCKElementPath=function(A){var B=null;var C=null;var D=[];var e=A;while (e){if (e.nodeType==1){if (!this.LastElement) this.LastElement=e;var E=e.nodeName.toLowerCase();if (!C){if (!B&&FCKListsLib.PathBlockElements[E]!=null) B=e;if (FCKListsLib.PathBlockLimitElements[E]!=null) C=e;};D.push(e);if (E=='body') break;};e=e.parentNode;};this.Block=B;this.BlockLimit=C;this.Elements=D;}; -var FCKDomRange=function(A){this.Window=A;};FCKDomRange.prototype={_UpdateElementInfo:function(){if (!this._Range) this.Release(true);else{var A=this._Range.startContainer;var B=this._Range.endContainer;var C=new FCKElementPath(A);this.StartContainer=C.LastElement;this.StartBlock=C.Block;this.StartBlockLimit=C.BlockLimit;if (A!=B) C=new FCKElementPath(B);this.EndContainer=C.LastElement;this.EndBlock=C.Block;this.EndBlockLimit=C.BlockLimit;}},CreateRange:function(){return new FCKW3CRange(this.Window.document);},DeleteContents:function(){if (this._Range){this._Range.deleteContents();this._UpdateElementInfo();}},ExtractContents:function(){if (this._Range){var A=this._Range.extractContents();this._UpdateElementInfo();return A;}},CheckIsCollapsed:function(){if (this._Range) return this._Range.collapsed;},Collapse:function(A){if (this._Range) this._Range.collapse(A);this._UpdateElementInfo();},Clone:function(){var A=FCKTools.CloneObject(this);if (this._Range) A._Range=this._Range.cloneRange();return A;},MoveToNodeContents:function(A){if (!this._Range) this._Range=this.CreateRange();this._Range.selectNodeContents(A);this._UpdateElementInfo();},MoveToElementStart:function(A){this.SetStart(A,1);this.SetEnd(A,1);},MoveToElementEditStart:function(A){var B;while ((B=A.firstChild)&&B.nodeType==1&&FCKListsLib.EmptyElements[B.nodeName.toLowerCase()]==null) A=B;this.MoveToElementStart(A);},InsertNode:function(A){if (this._Range) this._Range.insertNode(A);},CheckIsEmpty:function(A){if (this.CheckIsCollapsed()) return true;var B=this.Window.document.createElement('div');this._Range.cloneContents().AppendTo(B);FCKDomTools.TrimNode(B,A);return (B.innerHTML.length==0);},CheckStartOfBlock:function(){var A=this.Clone();A.Collapse(true);A.SetStart(A.StartBlock||A.StartBlockLimit,1);var B=A.CheckIsEmpty();A.Release();return B;},CheckEndOfBlock:function(A){var B=this.Clone();B.Collapse(false);B.SetEnd(B.EndBlock||B.EndBlockLimit,2);var C=B.CheckIsCollapsed();if (!C){var D=this.Window.document.createElement('div');B._Range.cloneContents().AppendTo(D);FCKDomTools.TrimNode(D,true);C=true;var E=D;while ((E=E.lastChild)){if (E.previousSibling||E.nodeType!=1||FCKListsLib.InlineChildReqElements[E.nodeName.toLowerCase()]==null){C=false;break;}}};B.Release();if (A) this.Select();return C;},CreateBookmark:function(){var A={StartId:'fck_dom_range_start_'+(new Date()).valueOf()+'_'+Math.floor(Math.random()*1000),EndId:'fck_dom_range_end_'+(new Date()).valueOf()+'_'+Math.floor(Math.random()*1000)};var B=this.Window.document;var C;var D;if (!this.CheckIsCollapsed()){C=B.createElement('span');C.id=A.EndId;C.innerHTML=' ';D=this.Clone();D.Collapse(false);D.InsertNode(C);};C=B.createElement('span');C.id=A.StartId;C.innerHTML=' ';D=this.Clone();D.Collapse(true);D.InsertNode(C);return A;},MoveToBookmark:function(A,B){var C=this.Window.document;var D=C.getElementById(A.StartId);var E=C.getElementById(A.EndId);this.SetStart(D,3);if (!B) FCKDomTools.RemoveNode(D);if (E){this.SetEnd(E,3);if (!B) FCKDomTools.RemoveNode(E);}else this.Collapse(true);},SetStart:function(A,B){var C=this._Range;if (!C) C=this._Range=this.CreateRange();switch(B){case 1:C.setStart(A,0);break;case 2:C.setStart(A,A.childNodes.length);break;case 3:C.setStartBefore(A);break;case 4:C.setStartAfter(A);};this._UpdateElementInfo();},SetEnd:function(A,B){var C=this._Range;if (!C) C=this._Range=this.CreateRange();switch(B){case 1:C.setEnd(A,0);break;case 2:C.setEnd(A,A.childNodes.length);break;case 3:C.setEndBefore(A);break;case 4:C.setEndAfter(A);};this._UpdateElementInfo();},Expand:function(A){var B,oSibling;switch (A){case 'block_contents':if (this.StartBlock) this.SetStart(this.StartBlock,1);else{B=this._Range.startContainer;if (B.nodeType==1){if (!(B=B.childNodes[this._Range.startOffset])) B=B.firstChild;};if (!B) return;while (true){oSibling=B.previousSibling;if (!oSibling){if (B.parentNode!=this.StartBlockLimit) B=B.parentNode;else break;}else if (oSibling.nodeType!=1||!(/^(?:P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|DT|DE)$/).test(oSibling.nodeName.toUpperCase())){B=oSibling;}else break;};this._Range.setStartBefore(B);};if (this.EndBlock) this.SetEnd(this.EndBlock,2);else{B=this._Range.endContainer;if (B.nodeType==1) B=B.childNodes[this._Range.endOffset]||B.lastChild;if (!B) return;while (true){oSibling=B.nextSibling;if (!oSibling){if (B.parentNode!=this.EndBlockLimit) B=B.parentNode;else break;}else if (oSibling.nodeType!=1||!(/^(?:P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|DT|DE)$/).test(oSibling.nodeName.toUpperCase())){B=oSibling;}else break;};this._Range.setEndAfter(B);};this._UpdateElementInfo();}},Release:function(A){if (!A) this.Window=null;this.StartContainer=null;this.StartBlock=null;this.StartBlockLimit=null;this.EndContainer=null;this.EndBlock=null;this.EndBlockLimit=null;this._Range=null;}}; -FCKDomRange.prototype.MoveToSelection=function(){this.Release(true);var A=this.Window.getSelection();if (A.rangeCount==1){this._Range=FCKW3CRange.CreateFromRange(this.Window.document,A.getRangeAt(0));this._UpdateElementInfo();}};FCKDomRange.prototype.Select=function(){var A=this._Range;if (A){var B=this.Window.document.createRange();B.setStart(A.startContainer,A.startOffset);try{B.setEnd(A.endContainer,A.endOffset);}catch (e){if (e.toString().Contains('NS_ERROR_ILLEGAL_VALUE')){A.collapse(true);B.setEnd(A.endContainer,A.endOffset);}else throw(e);};var C=this.Window.getSelection();C.removeAllRanges();C.addRange(B);}}; -var FCKDocumentFragment=function(A,B){this.RootNode=B||A.createDocumentFragment();};FCKDocumentFragment.prototype={AppendTo:function(A){A.appendChild(this.RootNode);},InsertAfterNode:function(A){FCKDomTools.InsertAfterNode(A,this.RootNode);}} -var FCKW3CRange=function(A){this._Document=A;this.startContainer=null;this.startOffset=null;this.endContainer=null;this.endOffset=null;this.collapsed=true;};FCKW3CRange.CreateRange=function(A){return new FCKW3CRange(A);};FCKW3CRange.CreateFromRange=function(A,B){var C=FCKW3CRange.CreateRange(A);C.setStart(B.startContainer,B.startOffset);C.setEnd(B.endContainer,B.endOffset);return C;};FCKW3CRange.prototype={_UpdateCollapsed:function(){this.collapsed=(this.startContainer==this.endContainer&&this.startOffset==this.endOffset);},setStart:function(A,B){this.startContainer=A;this.startOffset=B;if (!this.endContainer){this.endContainer=A;this.endOffset=B;};this._UpdateCollapsed();},setEnd:function(A,B){this.endContainer=A;this.endOffset=B;if (!this.startContainer){this.startContainer=A;this.startOffset=B;};this._UpdateCollapsed();},setStartAfter:function(A){this.setStart(A.parentNode,FCKDomTools.GetIndexOf(A)+1);},setStartBefore:function(A){this.setStart(A.parentNode,FCKDomTools.GetIndexOf(A));},setEndAfter:function(A){this.setEnd(A.parentNode,FCKDomTools.GetIndexOf(A)+1);},setEndBefore:function(A){this.setEnd(A.parentNode,FCKDomTools.GetIndexOf(A));},collapse:function(A){if (A){this.endContainer=this.startContainer;this.endOffset=this.startOffset;}else{this.startContainer=this.endContainer;this.startOffset=this.endOffset;};this.collapsed=true;},selectNodeContents:function(A){this.setStart(A,0);this.setEnd(A,A.nodeType==3?A.data.length:A.childNodes.length);},insertNode:function(A){var B=this.startContainer;var C=this.startOffset;if (B.nodeType==3){B.splitText(C);if (B==this.endContainer) this.setEnd(B.nextSibling,this.endOffset-this.startOffset);FCKDomTools.InsertAfterNode(B,A);return;}else{B.insertBefore(A,B.childNodes[C]||null);if (B==this.endContainer){this.endOffset++;this.collapsed=false;}}},deleteContents:function(){if (this.collapsed) return;this._ExecContentsAction(0);},extractContents:function(){var A=new FCKDocumentFragment(this._Document);if (!this.collapsed) this._ExecContentsAction(1,A);return A;},cloneContents:function(){var A=new FCKDocumentFragment(this._Document);if (!this.collapsed) this._ExecContentsAction(2,A);return A;},_ExecContentsAction:function(A,B){var C=this.startContainer;var D=this.endContainer;var E=this.startOffset;var F=this.endOffset;var G=false;var H=false;if (D.nodeType==3) D=D.splitText(F);else{if (D.childNodes.length>0){if (F>D.childNodes.length-1){D=FCKDomTools.InsertAfterNode(D.lastChild,this._Document.createTextNode(''));H=true;}else D=D.childNodes[F];}};if (C.nodeType==3){C.splitText(E);if (C==D) D=C.nextSibling;}else{if (C.childNodes.length>0&&E<=C.childNodes.length-1){if (E==0){C=C.insertBefore(this._Document.createTextNode(''),C.firstChild);G=true;}else C=C.childNodes[E].previousSibling;}};var I=FCKDomTools.GetParents(C);var J=FCKDomTools.GetParents(D);var i,topStart,topEnd;for (i=0;i0&&levelStartNode!=D) levelClone=K.appendChild(levelStartNode.cloneNode(levelStartNode==D));if (!I[k]||levelStartNode.parentNode!=I[k].parentNode){currentNode=levelStartNode.previousSibling;while(currentNode){if (currentNode==I[k]||currentNode==C) break;currentSibling=currentNode.previousSibling;if (A==2) K.insertBefore(currentNode.cloneNode(true),K.firstChild);else{currentNode.parentNode.removeChild(currentNode);if (A==1) K.insertBefore(currentNode,K.firstChild);};currentNode=currentSibling;}};if (K) K=levelClone;};if (A==2){var L=this.startContainer;if (L.nodeType==3){L.data+=L.nextSibling.data;L.parentNode.removeChild(L.nextSibling);};var M=this.endContainer;if (M.nodeType==3&&M.nextSibling){M.data+=M.nextSibling.data;M.parentNode.removeChild(M.nextSibling);}}else{if (topStart&&topEnd&&(C.parentNode!=topStart.parentNode||D.parentNode!=topEnd.parentNode)) this.setStart(topEnd.parentNode,FCKDomTools.GetIndexOf(topEnd));this.collapse(true);};if(G) C.parentNode.removeChild(C);if(H&&D.parentNode) D.parentNode.removeChild(D);},cloneRange:function(){return FCKW3CRange.CreateFromRange(this._Document,this);},toString:function(){var A=this.cloneContents();var B=this._Document.createElement('div');A.AppendTo(B);return B.textContent||B.innerText;}}; -var FCKEnterKey=function(A,B,C){this.Window=A;this.EnterMode=B||'p';this.ShiftEnterMode=C||'br';var D=new FCKKeystrokeHandler(false);D._EnterKey=this;D.OnKeystroke=FCKEnterKey_OnKeystroke;D.SetKeystrokes([[13,'Enter'],[SHIFT+13,'ShiftEnter'],[8,'Backspace'],[46,'Delete']]);D.AttachToElement(A.document);};function FCKEnterKey_OnKeystroke(A,B){var C=this._EnterKey;try{switch (B){case 'Enter':return C.DoEnter();break;case 'ShiftEnter':return C.DoShiftEnter();break;case 'Backspace':return C.DoBackspace();break;case 'Delete':return C.DoDelete();}}catch (e){};return false;};FCKEnterKey.prototype.DoEnter=function(A,B){this._HasShift=(B===true);var C=A||this.EnterMode;if (C=='br') return this._ExecuteEnterBr();else return this._ExecuteEnterBlock(C);};FCKEnterKey.prototype.DoShiftEnter=function(){return this.DoEnter(this.ShiftEnterMode,true);};FCKEnterKey.prototype.DoBackspace=function(){var A=false;var B=new FCKDomRange(this.Window);B.MoveToSelection();if (!B.CheckIsCollapsed()) return false;var C=B.StartBlock;var D=B.EndBlock;if (B.StartBlockLimit==B.EndBlockLimit&&C&&D){if (!B.CheckIsCollapsed()){var E=B.CheckEndOfBlock();B.DeleteContents();if (C!=D){B.SetStart(D,1);B.SetEnd(D,1);};B.Select();A=(C==D);};if (B.CheckStartOfBlock()){var F=B.StartBlock;var G=FCKDomTools.GetPreviousSourceElement(F,true,['BODY',B.StartBlockLimit.nodeName],['UL','OL']);A=this._ExecuteBackspace(B,G,F);}else if (FCKBrowserInfo.IsGecko){B.Select();}};B.Release();return A;};FCKEnterKey.prototype._ExecuteBackspace=function(A,B,C){var D=false;if (!B&&C.nodeName.IEquals('LI')&&C.parentNode.parentNode.nodeName.IEquals('LI')){this._OutdentWithSelection(C,A);return true;};if (B&&B.nodeName.IEquals('LI')){var E=FCKDomTools.GetLastChild(B,['UL','OL']);while (E){B=FCKDomTools.GetLastChild(E,'LI');E=FCKDomTools.GetLastChild(B,['UL','OL']);}};if (B&&C){if (C.nodeName.IEquals('LI')&&!B.nodeName.IEquals('LI')){this._OutdentWithSelection(C,A);return true;};var F=C.parentNode;var G=B.nodeName.toLowerCase();if (FCKListsLib.EmptyElements[G]!=null||G=='table'){FCKDomTools.RemoveNode(B);D=true;}else{FCKDomTools.RemoveNode(C);while (F.innerHTML.Trim().length==0){var H=F.parentNode;H.removeChild(F);F=H;};FCKDomTools.TrimNode(C);FCKDomTools.TrimNode(B);A.SetStart(B,2);A.Collapse(true);var I=A.CreateBookmark();FCKDomTools.MoveChildren(C,B);A.MoveToBookmark(I);A.Select();D=true;}};return D;};FCKEnterKey.prototype.DoDelete=function(){var A=false;var B=new FCKDomRange(this.Window);B.MoveToSelection();if (B.CheckIsCollapsed()&&B.CheckEndOfBlock(FCKBrowserInfo.IsGecko)){var C=B.StartBlock;var D=FCKDomTools.GetNextSourceElement(C,true,[B.StartBlockLimit.nodeName],['UL','OL']);A=this._ExecuteBackspace(B,C,D);};B.Release();return A;};FCKEnterKey.prototype._ExecuteEnterBlock=function(A,B){var C=B||new FCKDomRange(this.Window);if (!B) C.MoveToSelection();if (C.StartBlockLimit==C.EndBlockLimit){if (!C.StartBlock) this._FixBlock(C,true,A);if (!C.EndBlock) this._FixBlock(C,false,A);var D=C.StartBlock;var E=C.EndBlock;if (!C.CheckIsEmpty()) C.DeleteContents();if (D==E){var F;var G=C.CheckStartOfBlock();var H=C.CheckEndOfBlock();if (G&&!H){F=D.cloneNode(false);if (FCKBrowserInfo.IsGeckoLike) F.innerHTML=GECKO_BOGUS;D.parentNode.insertBefore(F,D);if (FCKBrowserInfo.IsIE){C.MoveToNodeContents(F);C.Select();};C.MoveToElementEditStart(D);}else{if (H){var I=D.tagName.toUpperCase();if (G&&I=='LI'){this._OutdentWithSelection(D,C);C.Release();return true;}else{if ((/^H[1-6]$/).test(I)||this._HasShift) F=this.Window.document.createElement(A);else{F=D.cloneNode(false);this._RecreateEndingTree(D,F);};if (FCKBrowserInfo.IsGeckoLike){F.innerHTML=GECKO_BOGUS;if (G) D.innerHTML=GECKO_BOGUS;}}}else{C.SetEnd(D,2);var J=C.ExtractContents();F=D.cloneNode(false);FCKDomTools.TrimNode(J.RootNode);if (J.RootNode.firstChild.nodeType==1&&J.RootNode.firstChild.tagName.toUpperCase().Equals('UL','OL')) F.innerHTML=GECKO_BOGUS;J.AppendTo(F);if (FCKBrowserInfo.IsGecko){this._AppendBogusBr(D);this._AppendBogusBr(F);}};if (F){FCKDomTools.InsertAfterNode(D,F);C.MoveToElementEditStart(F);if (FCKBrowserInfo.IsGecko) F.scrollIntoView(false);}}}else{C.MoveToElementEditStart(E);};C.Select();};C.Release();return true;};FCKEnterKey.prototype._ExecuteEnterBr=function(A){var B=new FCKDomRange(this.Window);B.MoveToSelection();if (B.StartBlockLimit==B.EndBlockLimit){B.DeleteContents();B.MoveToSelection();var C=B.CheckStartOfBlock();var D=B.CheckEndOfBlock();var E=B.StartBlock?B.StartBlock.tagName.toUpperCase():'';var F=this._HasShift;if (!F&&E=='LI') return this._ExecuteEnterBlock(null,B);if (!F&&D&&(/^H[1-6]$/).test(E)){FCKDebug.Output('BR - Header');FCKDomTools.InsertAfterNode(B.StartBlock,this.Window.document.createElement('br'));if (FCKBrowserInfo.IsGecko) FCKDomTools.InsertAfterNode(B.StartBlock,this.Window.document.createTextNode(''));B.SetStart(B.StartBlock.nextSibling,FCKBrowserInfo.IsIE?3:1);}else{FCKDebug.Output('BR - No Header');var G=this.Window.document.createElement('br');B.InsertNode(G);if (FCKBrowserInfo.IsGecko) FCKDomTools.InsertAfterNode(G,this.Window.document.createTextNode(''));if (D&&FCKBrowserInfo.IsGecko) this._AppendBogusBr(G.parentNode);if (FCKBrowserInfo.IsIE) B.SetStart(G,4);else B.SetStart(G.nextSibling,1);};B.Collapse(true);B.Select();};B.Release();return true;};FCKEnterKey.prototype._FixBlock=function(A,B,C){var D=A.CreateBookmark();A.Collapse(B);A.Expand('block_contents');var E=this.Window.document.createElement(C);A.ExtractContents().AppendTo(E);FCKDomTools.TrimNode(E);A.InsertNode(E);A.MoveToBookmark(D);};FCKEnterKey.prototype._AppendBogusBr=function(A){var B=A.getElementsByTagName('br');if (B) B=B[B.legth-1];if (!B||B.getAttribute('type',2)!='_moz') A.appendChild(FCKTools.CreateBogusBR(this.Window.document));};FCKEnterKey.prototype._RecreateEndingTree=function(A,B){while ((A=A.lastChild)&&A.nodeType==1&&FCKListsLib.InlineChildReqElements[A.nodeName.toLowerCase()]!=null) B=B.insertBefore(A.cloneNode(false),B.firstChild);};FCKEnterKey.prototype._OutdentWithSelection=function(A,B){var C=B.CreateBookmark();FCKListHandler.OutdentListItem(A);B.MoveToBookmark(C);B.Select();} -var FCKDocumentProcessor={};FCKDocumentProcessor._Items=[];FCKDocumentProcessor.AppendNew=function(){var A={};this._Items.AddItem(A);return A;};FCKDocumentProcessor.Process=function(A){var B,i=0;while((B=this._Items[i++])) B.ProcessDocument(A);};var FCKDocumentProcessor_CreateFakeImage=function(A,B){var C=FCK.EditorDocument.createElement('IMG');C.className=A;C.src=FCKConfig.FullBasePath+'images/spacer.gif';C.setAttribute('_fckfakelement','true',0);C.setAttribute('_fckrealelement',FCKTempBin.AddElement(B),0);return C;};if (FCKBrowserInfo.IsIE||FCKBrowserInfo.IsOpera){var FCKAnchorsProcessor=FCKDocumentProcessor.AppendNew();FCKAnchorsProcessor.ProcessDocument=function(A){var B=A.getElementsByTagName('A');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){if (C.name.length>0){if (C.innerHTML!=''){if (FCKBrowserInfo.IsIE) C.className+=' FCK__AnchorC';}else{var D=FCKDocumentProcessor_CreateFakeImage('FCK__Anchor',C.cloneNode(true));D.setAttribute('_fckanchor','true',0);C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}}}};var FCKPageBreaksProcessor=FCKDocumentProcessor.AppendNew();FCKPageBreaksProcessor.ProcessDocument=function(A){var B=A.getElementsByTagName('DIV');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){if (C.style.pageBreakAfter=='always'&&C.childNodes.length==1&&C.childNodes[0].style&&C.childNodes[0].style.display=='none'){var D=FCKDocumentProcessor_CreateFakeImage('FCK__PageBreak',C.cloneNode(true));C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}};var FCKFlashProcessor=FCKDocumentProcessor.AppendNew();FCKFlashProcessor.ProcessDocument=function(A){var B=A.getElementsByTagName('EMBED');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){var D=C.attributes['type'];if ((C.src&&C.src.EndsWith('.swf',true))||(D&&D.nodeValue=='application/x-shockwave-flash')){var E=C.cloneNode(true);if (FCKBrowserInfo.IsIE){var F=['scale','play','loop','menu','wmode','quality'];for (var G=0;G0) A.style.width=FCKTools.ConvertHtmlSizeToStyle(B.width);if (B.height>0) A.style.height=FCKTools.ConvertHtmlSizeToStyle(B.height);};FCK.GetRealElement=function(A){var e=FCKTempBin.Elements[A.getAttribute('_fckrealelement')];if (A.getAttribute('_fckflash')){if (A.style.width.length>0) e.width=FCKTools.ConvertStyleSizeToHtml(A.style.width);if (A.style.height.length>0) e.height=FCKTools.ConvertStyleSizeToHtml(A.style.height);};return e;};if (FCKBrowserInfo.IsIE){FCKDocumentProcessor.AppendNew().ProcessDocument=function(A){var B=A.getElementsByTagName('HR');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){var D=A.createElement('hr');D.mergeAttributes(C,true);FCKDomTools.InsertAfterNode(C,D);C.parentNode.removeChild(C);}}};FCKDocumentProcessor.AppendNew().ProcessDocument=function(A){var B=A.getElementsByTagName('INPUT');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){if (C.type=='hidden'){var D=FCKDocumentProcessor_CreateFakeImage('FCK__InputHidden',C.cloneNode(true));D.setAttribute('_fckinputhidden','true',0);C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}} -var FCKSelection=FCK.Selection={}; -FCKSelection.GetType=function(){this._Type='Text';var A;try { A=FCK.EditorWindow.getSelection();}catch (e) {};if (A&&A.rangeCount==1){var B=A.getRangeAt(0);if (B.startContainer==B.endContainer&&(B.endOffset-B.startOffset)==1&&B.startContainer.nodeType!=Node.TEXT_NODE) this._Type='Control';};return this._Type;};FCKSelection.GetSelectedElement=function(){if (this.GetType()=='Control'){var A=FCK.EditorWindow.getSelection();return A.anchorNode.childNodes[A.anchorOffset];};return null;};FCKSelection.GetParentElement=function(){if (this.GetType()=='Control') return FCKSelection.GetSelectedElement().parentNode;else{var A=FCK.EditorWindow.getSelection();if (A){var B=A.anchorNode;while (B&&B.nodeType!=1) B=B.parentNode;return B;}};return null;};FCKSelection.SelectNode=function(A){var B=FCK.EditorDocument.createRange();B.selectNode(A);var C=FCK.EditorWindow.getSelection();C.removeAllRanges();C.addRange(B);};FCKSelection.Collapse=function(A){var B=FCK.EditorWindow.getSelection();if (A==null||A===true) B.collapseToStart();else B.collapseToEnd();};FCKSelection.HasAncestorNode=function(A){var B=this.GetSelectedElement();if (!B&&FCK.EditorWindow){try { B=FCK.EditorWindow.getSelection().getRangeAt(0).startContainer;}catch(e){}};while (B){if (B.nodeType==1&&B.tagName==A) return true;B=B.parentNode;};return false;};FCKSelection.MoveToAncestorNode=function(A){var B;var C=this.GetSelectedElement();if (!C) C=FCK.EditorWindow.getSelection().getRangeAt(0).startContainer;while (C){if (C.nodeName==A) return C;C=C.parentNode;};return null;};FCKSelection.Delete=function(){var A=FCK.EditorWindow.getSelection();for (var i=0;i=0;i--){var D=B.rows[i];if (C==0&&D.cells.length==1){FCKTableHandler.DeleteRows(D);continue;};if (D.cells[C]) D.removeChild(D.cells[C]);}};FCKTableHandler.InsertCell=function(A){var B=A?A:FCKSelection.MoveToAncestorNode('TD');if (!B) return null;var C=FCK.EditorDocument.createElement('TD');if (FCKBrowserInfo.IsGecko) C.innerHTML=GECKO_BOGUS;if (B.cellIndex==B.parentNode.cells.length-1){B.parentNode.appendChild(C);}else{B.parentNode.insertBefore(C,B.nextSibling);};return C;};FCKTableHandler.DeleteCell=function(A){if (A.parentNode.cells.length==1){FCKTableHandler.DeleteRows(FCKTools.GetElementAscensor(A,'TR'));return;};A.parentNode.removeChild(A);};FCKTableHandler.DeleteCells=function(){var A=FCKTableHandler.GetSelectedCells();for (var i=A.length-1;i>=0;i--){FCKTableHandler.DeleteCell(A[i]);}};FCKTableHandler.MergeCells=function(){var A=FCKTableHandler.GetSelectedCells();if (A.length<2) return;if (A[0].parentNode!=A[A.length-1].parentNode) return;var B=isNaN(A[0].colSpan)?1:A[0].colSpan;var C='';var D=FCK.EditorDocument.createDocumentFragment();for (var i=A.length-1;i>=0;i--){var E=A[i];for (var c=E.childNodes.length-1;c>=0;c--){var F=E.removeChild(E.childNodes[c]);if ((F.hasAttribute&&F.hasAttribute('_moz_editor_bogus_node'))||(F.getAttribute&&F.getAttribute('type',2)=='_moz')) continue;D.insertBefore(F,D.firstChild);};if (i>0){B+=isNaN(E.colSpan)?1:E.colSpan;FCKTableHandler.DeleteCell(E);}};A[0].colSpan=B;if (FCKBrowserInfo.IsGecko&&D.childNodes.length==0) A[0].innerHTML=GECKO_BOGUS;else A[0].appendChild(D);};FCKTableHandler.SplitCell=function(){var A=FCKTableHandler.GetSelectedCells();if (A.length!=1) return;var B=this._CreateTableMap(A[0].parentNode.parentNode);var C=FCKTableHandler._GetCellIndexSpan(B,A[0].parentNode.rowIndex,A[0]);var D=this._GetCollumnCells(B,C);for (var i=0;i1) E.rowSpan=A[0].rowSpan;}else{if (isNaN(D[i].colSpan)) D[i].colSpan=2;else D[i].colSpan+=1;}}};FCKTableHandler._GetCellIndexSpan=function(A,B,C){if (A.length';};FCKStyleDef.prototype.GetCloserTag=function(){return '';};FCKStyleDef.prototype.RemoveFromSelection=function(){if (FCKSelection.GetType()=='Control') this._RemoveMe(FCK.ToolbarSet.CurrentInstance.Selection.GetSelectedElement());else this._RemoveMe(FCK.ToolbarSet.CurrentInstance.Selection.GetParentElement());} -FCKStyleDef.prototype.ApplyToSelection=function(){if (FCKSelection.GetType()=='Text'&&!this.IsObjectElement){var A=FCK.ToolbarSet.CurrentInstance.EditorWindow.getSelection();var e=FCK.ToolbarSet.CurrentInstance.EditorDocument.createElement(this.Element);for (var i=0;i');else if (A=='div'&&FCKBrowserInfo.IsGecko) FCK.ExecuteNamedCommand('FormatBlock','div');else FCK.ExecuteNamedCommand('FormatBlock','<'+A+'>');};FCKFormatBlockCommand.prototype.GetState=function(){return FCK.GetNamedCommandValue('FormatBlock');};var FCKPreviewCommand=function(){this.Name='Preview';};FCKPreviewCommand.prototype.Execute=function(){FCK.Preview();};FCKPreviewCommand.prototype.GetState=function(){return 0;};var FCKSaveCommand=function(){this.Name='Save';};FCKSaveCommand.prototype.Execute=function(){var A=FCK.GetParentForm();if (typeof(A.onsubmit)=='function'){var B=A.onsubmit();if (B!=null&&B===false) return;};A.submit();};FCKSaveCommand.prototype.GetState=function(){return 0;};var FCKNewPageCommand=function(){this.Name='NewPage';};FCKNewPageCommand.prototype.Execute=function(){FCKUndo.SaveUndoStep();FCK.SetHTML('');FCKUndo.Typing=true;};FCKNewPageCommand.prototype.GetState=function(){return 0;};var FCKSourceCommand=function(){this.Name='Source';};FCKSourceCommand.prototype.Execute=function(){if (FCKConfig.SourcePopup){var A=FCKConfig.ScreenWidth*0.65;var B=FCKConfig.ScreenHeight*0.65;FCKDialog.OpenDialog('FCKDialog_Source',FCKLang.Source,'dialog/fck_source.html',A,B,null,null,true);}else FCK.SwitchEditMode();};FCKSourceCommand.prototype.GetState=function(){return (FCK.EditMode==0?0:1);};var FCKUndoCommand=function(){this.Name='Undo';};FCKUndoCommand.prototype.Execute=function(){if (FCKBrowserInfo.IsIE) FCKUndo.Undo();else FCK.ExecuteNamedCommand('Undo');};FCKUndoCommand.prototype.GetState=function(){if (FCKBrowserInfo.IsIE) return (FCKUndo.CheckUndoState()?0:-1);else return FCK.GetNamedCommandState('Undo');};var FCKRedoCommand=function(){this.Name='Redo';};FCKRedoCommand.prototype.Execute=function(){if (FCKBrowserInfo.IsIE) FCKUndo.Redo();else FCK.ExecuteNamedCommand('Redo');};FCKRedoCommand.prototype.GetState=function(){if (FCKBrowserInfo.IsIE) return (FCKUndo.CheckRedoState()?0:-1);else return FCK.GetNamedCommandState('Redo');};var FCKPageBreakCommand=function(){this.Name='PageBreak';};FCKPageBreakCommand.prototype.Execute=function(){var e=FCK.EditorDocument.createElement('DIV');e.style.pageBreakAfter='always';e.innerHTML=' ';var A=FCKDocumentProcessor_CreateFakeImage('FCK__PageBreak',e);A=FCK.InsertElement(A);};FCKPageBreakCommand.prototype.GetState=function(){return 0;};var FCKUnlinkCommand=function(){this.Name='Unlink';};FCKUnlinkCommand.prototype.Execute=function(){if (FCKBrowserInfo.IsGecko){var A=FCK.Selection.MoveToAncestorNode('A');if (A) FCK.Selection.SelectNode(A);};FCK.ExecuteNamedCommand(this.Name);if (FCKBrowserInfo.IsGecko) FCK.Selection.Collapse(true);};FCKUnlinkCommand.prototype.GetState=function(){var A=FCK.GetNamedCommandState(this.Name);if (A==0&&FCK.EditMode==0){var B=FCKSelection.MoveToAncestorNode('A');var C=(B&&B.name.length>0&&B.href.length==0);if (C) A=-1;};return A;};var FCKSelectAllCommand=function(){this.Name='SelectAll';};FCKSelectAllCommand.prototype.Execute=function(){if (FCK.EditMode==0){FCK.ExecuteNamedCommand('SelectAll');}else{var A=FCK.EditingArea.Textarea;if (FCKBrowserInfo.IsIE){A.createTextRange().execCommand('SelectAll');}else{A.selectionStart=0;A.selectionEnd=A.value.length;};A.focus();}};FCKSelectAllCommand.prototype.GetState=function(){return 0;};var FCKPasteCommand=function(){this.Name='Paste';};FCKPasteCommand.prototype={Execute:function(){if (FCKBrowserInfo.IsIE) FCK.Paste();else FCK.ExecuteNamedCommand('Paste');},GetState:function(){return FCK.GetNamedCommandState('Paste');}}; -var FCKSpellCheckCommand=function(){this.Name='SpellCheck';this.IsEnabled=(FCKConfig.SpellChecker=='SpellerPages');};FCKSpellCheckCommand.prototype.Execute=function(){FCKDialog.OpenDialog('FCKDialog_SpellCheck','Spell Check','dialog/fck_spellerpages.html',440,480);};FCKSpellCheckCommand.prototype.GetState=function(){return this.IsEnabled?0:-1;} -var FCKTextColorCommand=function(A){this.Name=A=='ForeColor'?'TextColor':'BGColor';this.Type=A;var B;if (FCKBrowserInfo.IsIE) B=window;else if (FCK.ToolbarSet._IFrame) B=FCKTools.GetElementWindow(FCK.ToolbarSet._IFrame);else B=window.parent;this._Panel=new FCKPanel(B,true);this._Panel.AppendStyleSheet(FCKConfig.SkinPath+'fck_editor.css');this._Panel.MainNode.className='FCK_Panel';this._CreatePanelBody(this._Panel.Document,this._Panel.MainNode);FCKTools.DisableSelection(this._Panel.Document.body);};FCKTextColorCommand.prototype.Execute=function(A,B,C){FCK._ActiveColorPanelType=this.Type;this._Panel.Show(A,B,C);};FCKTextColorCommand.prototype.SetColor=function(A){if (FCK._ActiveColorPanelType=='ForeColor') FCK.ExecuteNamedCommand('ForeColor',A);else if (FCKBrowserInfo.IsGeckoLike){if (FCKBrowserInfo.IsGecko&&!FCKConfig.GeckoUseSPAN) FCK.EditorDocument.execCommand('useCSS',false,false);FCK.ExecuteNamedCommand('hilitecolor',A);if (FCKBrowserInfo.IsGecko&&!FCKConfig.GeckoUseSPAN) FCK.EditorDocument.execCommand('useCSS',false,true);}else FCK.ExecuteNamedCommand('BackColor',A);delete FCK._ActiveColorPanelType;};FCKTextColorCommand.prototype.GetState=function(){return 0;};function FCKTextColorCommand_OnMouseOver() { this.className='ColorSelected';};function FCKTextColorCommand_OnMouseOut() { this.className='ColorDeselected';};function FCKTextColorCommand_OnClick(){this.className='ColorDeselected';this.Command.SetColor('#'+this.Color);this.Command._Panel.Hide();};function FCKTextColorCommand_AutoOnClick(){this.className='ColorDeselected';this.Command.SetColor('');this.Command._Panel.Hide();};function FCKTextColorCommand_MoreOnClick(){this.className='ColorDeselected';this.Command._Panel.Hide();FCKDialog.OpenDialog('FCKDialog_Color',FCKLang.DlgColorTitle,'dialog/fck_colorselector.html',400,330,this.Command.SetColor);};FCKTextColorCommand.prototype._CreatePanelBody=function(A,B){function CreateSelectionDiv(){var C=A.createElement("DIV");C.className='ColorDeselected';C.onmouseover=FCKTextColorCommand_OnMouseOver;C.onmouseout=FCKTextColorCommand_OnMouseOut;return C;};var D=B.appendChild(A.createElement("TABLE"));D.className='ForceBaseFont';D.style.tableLayout='fixed';D.cellPadding=0;D.cellSpacing=0;D.border=0;D.width=150;var E=D.insertRow(-1).insertCell(-1);E.colSpan=8;var C=E.appendChild(CreateSelectionDiv());C.innerHTML='\n \n \n \n \n
      '+FCKLang.ColorAutomatic+'
      ';C.Command=this;C.onclick=FCKTextColorCommand_AutoOnClick;var G=FCKConfig.FontColors.toString().split(',');var H=0;while (H
      ';C.Command=this;C.onclick=FCKTextColorCommand_OnClick;}};E=D.insertRow(-1).insertCell(-1);E.colSpan=8;C=E.appendChild(CreateSelectionDiv());C.innerHTML='
      '+FCKLang.ColorMoreColors+'
      ';C.Command=this;C.onclick=FCKTextColorCommand_MoreOnClick;} -var FCKPastePlainTextCommand=function(){this.Name='PasteText';};FCKPastePlainTextCommand.prototype.Execute=function(){FCK.PasteAsPlainText();};FCKPastePlainTextCommand.prototype.GetState=function(){return FCK.GetNamedCommandState('Paste');}; -var FCKPasteWordCommand=function(){this.Name='PasteWord';};FCKPasteWordCommand.prototype.Execute=function(){FCK.PasteFromWord();};FCKPasteWordCommand.prototype.GetState=function(){if (FCKConfig.ForcePasteAsPlainText) return -1;else return FCK.GetNamedCommandState('Paste');}; -var FCKTableCommand=function(A){this.Name=A;};FCKTableCommand.prototype.Execute=function(){FCKUndo.SaveUndoStep();switch (this.Name){case 'TableInsertRow':FCKTableHandler.InsertRow();break;case 'TableDeleteRows':FCKTableHandler.DeleteRows();break;case 'TableInsertColumn':FCKTableHandler.InsertColumn();break;case 'TableDeleteColumns':FCKTableHandler.DeleteColumns();break;case 'TableInsertCell':FCKTableHandler.InsertCell();break;case 'TableDeleteCells':FCKTableHandler.DeleteCells();break;case 'TableMergeCells':FCKTableHandler.MergeCells();break;case 'TableSplitCell':FCKTableHandler.SplitCell();break;case 'TableDelete':FCKTableHandler.DeleteTable();break;default:alert(FCKLang.UnknownCommand.replace(/%1/g,this.Name));}};FCKTableCommand.prototype.GetState=function(){return 0;} -var FCKStyleCommand=function(){this.Name='Style';this.StylesLoader=new FCKStylesLoader();this.StylesLoader.Load(FCKConfig.StylesXmlPath);this.Styles=this.StylesLoader.Styles;};FCKStyleCommand.prototype.Execute=function(A,B){FCKUndo.SaveUndoStep();if (B.Selected) B.Style.RemoveFromSelection();else B.Style.ApplyToSelection();FCKUndo.SaveUndoStep();FCK.Focus();FCK.Events.FireEvent("OnSelectionChange");};FCKStyleCommand.prototype.GetState=function(){if (!FCK.EditorDocument) return -1;var A=FCK.EditorDocument.selection;if (FCKSelection.GetType()=='Control'){var e=FCKSelection.GetSelectedElement();if (e) return this.StylesLoader.StyleGroups[e.tagName]?0:-1;};return 0;};FCKStyleCommand.prototype.GetActiveStyles=function(){var A=[];if (FCKSelection.GetType()=='Control') this._CheckStyle(FCKSelection.GetSelectedElement(),A,false);else this._CheckStyle(FCKSelection.GetParentElement(),A,true);return A;};FCKStyleCommand.prototype._CheckStyle=function(A,B,C){if (!A) return;if (A.nodeType==1){var D=this.StylesLoader.StyleGroups[A.tagName];if (D){for (var i=0;i<\/body><\/html>');B.close();FCKTools.AddEventListenerEx(D,'focus',FCKPanel_Window_OnFocus,this);FCKTools.AddEventListenerEx(D,'blur',FCKPanel_Window_OnBlur,this);};B.dir=FCKLang.Dir;B.oncontextmenu=FCKTools.CancelEvent;this.MainNode=B.body.appendChild(B.createElement('DIV'));this.MainNode.style.cssFloat=this.IsRTL?'right':'left';};FCKPanel.prototype.AppendStyleSheet=function(A){FCKTools.AppendStyleSheet(this.Document,A);};FCKPanel.prototype.Preload=function(x,y,A){if (this._Popup) this._Popup.show(x,y,0,0,A);};FCKPanel.prototype.Show=function(x,y,A,B,C){var D;if (this._Popup){this._Popup.show(x,y,0,0,A);this.MainNode.style.width=B?B+'px':'';this.MainNode.style.height=C?C+'px':'';D=this.MainNode.offsetWidth;if (this.IsRTL){if (this.IsContextMenu) x=x-D+1;else if (A) x=(x*-1)+A.offsetWidth-D;};this._Popup.show(x,y,D,this.MainNode.offsetHeight,A);if (this.OnHide){if (this._Timer) CheckPopupOnHide.call(this,true);this._Timer=FCKTools.SetInterval(CheckPopupOnHide,100,this);}}else{if (typeof(FCKFocusManager)!='undefined') FCKFocusManager.Lock();if (this.ParentPanel) this.ParentPanel.Lock();this.MainNode.style.width=B?B+'px':'';this.MainNode.style.height=C?C+'px':'';D=this.MainNode.offsetWidth;if (!B) this._IFrame.width=1;if (!C) this._IFrame.height=1;D=this.MainNode.offsetWidth;var E=FCKTools.GetElementPosition(A.nodeType==9?(FCKTools.IsStrictMode(A)?A.documentElement:A.body):A,this._Window);if (this.IsRTL&&!this.IsContextMenu) x=(x*-1);x+=E.X;y+=E.Y;if (this.IsRTL){if (this.IsContextMenu) x=x-D+1;else if (A) x=x+A.offsetWidth-D;}else{var F=FCKTools.GetViewPaneSize(this._Window);var G=FCKTools.GetScrollPosition(this._Window);var H=F.Height+G.Y;var I=F.Width+G.X;if ((x+D)>I) x-=x+D-I;if ((y+this.MainNode.offsetHeight)>H) y-=y+this.MainNode.offsetHeight-H;};if (x<0) x=0;this._IFrame.style.left=x+'px';this._IFrame.style.top=y+'px';var J=D;var K=this.MainNode.offsetHeight;this._IFrame.width=J;this._IFrame.height=K;this._IFrame.contentWindow.focus();};this._IsOpened=true;FCKTools.RunFunction(this.OnShow,this);};FCKPanel.prototype.Hide=function(A){if (this._Popup) this._Popup.hide();else{if (!this._IsOpened) return;if (typeof(FCKFocusManager)!='undefined') FCKFocusManager.Unlock();this._IFrame.width=this._IFrame.height=0;this._IsOpened=false;if (this.ParentPanel) this.ParentPanel.Unlock();if (!A) FCKTools.RunFunction(this.OnHide,this);}};FCKPanel.prototype.CheckIsOpened=function(){if (this._Popup) return this._Popup.isOpen;else return this._IsOpened;};FCKPanel.prototype.CreateChildPanel=function(){var A=this._Popup?FCKTools.GetDocumentWindow(this.Document):this._Window;var B=new FCKPanel(A,true);B.ParentPanel=this;return B;};FCKPanel.prototype.Lock=function(){this._LockCounter++;};FCKPanel.prototype.Unlock=function(){if (--this._LockCounter==0&&!this.HasFocus) this.Hide();};function FCKPanel_Window_OnFocus(e,A){A.HasFocus=true;};function FCKPanel_Window_OnBlur(e,A){A.HasFocus=false;if (A._LockCounter==0) FCKTools.RunFunction(A.Hide,A);};function CheckPopupOnHide(A){if (A||!this._Popup.isOpen){window.clearInterval(this._Timer);this._Timer=null;FCKTools.RunFunction(this.OnHide,this);}};function FCKPanel_Cleanup(){this._Popup=null;this._Window=null;this.Document=null;this.MainNode=null;} -var FCKIcon=function(A){var B=A?typeof(A):'undefined';switch (B){case 'number':this.Path=FCKConfig.SkinPath+'fck_strip.gif';this.Size=16;this.Position=A;break;case 'undefined':this.Path=FCK_SPACER_PATH;break;case 'string':this.Path=A;break;default:this.Path=A[0];this.Size=A[1];this.Position=A[2];}};FCKIcon.prototype.CreateIconElement=function(A){var B,eIconImage;if (this.Position){var C='-'+((this.Position-1)*this.Size)+'px';if (FCKBrowserInfo.IsIE){B=A.createElement('DIV');eIconImage=B.appendChild(A.createElement('IMG'));eIconImage.src=this.Path;eIconImage.style.top=C;}else{B=A.createElement('IMG');B.src=FCK_SPACER_PATH;B.style.backgroundPosition='0px '+C;B.style.backgroundImage='url('+this.Path+')';}}else{B=A.createElement('DIV');eIconImage=B.appendChild(A.createElement('IMG'));eIconImage.src=this.Path?this.Path:FCK_SPACER_PATH;};B.className='TB_Button_Image';return B;} -var FCKToolbarButtonUI=function(A,B,C,D,E,F){this.Name=A;this.Label=B||A;this.Tooltip=C||this.Label;this.Style=E||0;this.State=F||0;this.Icon=new FCKIcon(D);if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKToolbarButtonUI_Cleanup);};FCKToolbarButtonUI.prototype._CreatePaddingElement=function(A){var B=A.createElement('IMG');B.className='TB_Button_Padding';B.src=FCK_SPACER_PATH;return B;};FCKToolbarButtonUI.prototype.Create=function(A){var B=this.MainElement;if (B){FCKToolbarButtonUI_Cleanup.call(this);if (B.parentNode) B.parentNode.removeChild(B);B=this.MainElement=null;};var C=FCKTools.GetElementDocument(A);B=this.MainElement=C.createElement('DIV');B._FCKButton=this;B.title=this.Tooltip;if (FCKBrowserInfo.IsGecko) B.onmousedown=FCKTools.CancelEvent;this.ChangeState(this.State,true);if (this.Style==0&&!this.ShowArrow){B.appendChild(this.Icon.CreateIconElement(C));}else{var D=B.appendChild(C.createElement('TABLE'));D.cellPadding=0;D.cellSpacing=0;var E=D.insertRow(-1);var F=E.insertCell(-1);if (this.Style==0||this.Style==2) F.appendChild(this.Icon.CreateIconElement(C));else F.appendChild(this._CreatePaddingElement(C));if (this.Style==1||this.Style==2){F=E.insertCell(-1);F.className='TB_Button_Text';F.noWrap=true;F.appendChild(C.createTextNode(this.Label));};if (this.ShowArrow){if (this.Style!=0){E.insertCell(-1).appendChild(this._CreatePaddingElement(C));};F=E.insertCell(-1);var G=F.appendChild(C.createElement('IMG'));G.src=FCKConfig.SkinPath+'images/toolbar.buttonarrow.gif';G.width=5;G.height=3;};F=E.insertCell(-1);F.appendChild(this._CreatePaddingElement(C));};A.appendChild(B);};FCKToolbarButtonUI.prototype.ChangeState=function(A,B){if (!B&&this.State==A) return;var e=this.MainElement;switch (parseInt(A,10)){case 0:e.className='TB_Button_Off';e.onmouseover=FCKToolbarButton_OnMouseOverOff;e.onmouseout=FCKToolbarButton_OnMouseOutOff;e.onclick=FCKToolbarButton_OnClick;break;case 1:e.className='TB_Button_On';e.onmouseover=FCKToolbarButton_OnMouseOverOn;e.onmouseout=FCKToolbarButton_OnMouseOutOn;e.onclick=FCKToolbarButton_OnClick;break;case -1:e.className='TB_Button_Disabled';e.onmouseover=null;e.onmouseout=null;e.onclick=null;break;};this.State=A;};function FCKToolbarButtonUI_Cleanup(){if (this.MainElement){this.MainElement._FCKButton=null;this.MainElement=null;}};function FCKToolbarButton_OnMouseOverOn(){this.className='TB_Button_On_Over';};function FCKToolbarButton_OnMouseOutOn(){this.className='TB_Button_On';};function FCKToolbarButton_OnMouseOverOff(){this.className='TB_Button_Off_Over';};function FCKToolbarButton_OnMouseOutOff(){this.className='TB_Button_Off';};function FCKToolbarButton_OnClick(e){if (this._FCKButton.OnClick) this._FCKButton.OnClick(this._FCKButton);}; -var FCKToolbarButton=function(A,B,C,D,E,F,G){this.CommandName=A;this.Label=B;this.Tooltip=C;this.Style=D;this.SourceView=E?true:false;this.ContextSensitive=F?true:false;if (G==null) this.IconPath=FCKConfig.SkinPath+'toolbar/'+A.toLowerCase()+'.gif';else if (typeof(G)=='number') this.IconPath=[FCKConfig.SkinPath+'fck_strip.gif',16,G];};FCKToolbarButton.prototype.Create=function(A){this._UIButton=new FCKToolbarButtonUI(this.CommandName,this.Label,this.Tooltip,this.IconPath,this.Style);this._UIButton.OnClick=this.Click;this._UIButton._ToolbarButton=this;this._UIButton.Create(A);};FCKToolbarButton.prototype.RefreshState=function(){var A=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetState();if (A==this._UIButton.State) return;this._UIButton.ChangeState(A);};FCKToolbarButton.prototype.Click=function(){var A=this._ToolbarButton||this;FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(A.CommandName).Execute();};FCKToolbarButton.prototype.Enable=function(){this.RefreshState();};FCKToolbarButton.prototype.Disable=function(){this._UIButton.ChangeState(-1);} -var FCKSpecialCombo=function(A,B,C,D,E){this.FieldWidth=B||100;this.PanelWidth=C||150;this.PanelMaxHeight=D||150;this.Label=' ';this.Caption=A;this.Tooltip=A;this.Style=2;this.Enabled=true;this.Items={};this._Panel=new FCKPanel(E||window,true);this._Panel.AppendStyleSheet(FCKConfig.SkinPath+'fck_editor.css');this._PanelBox=this._Panel.MainNode.appendChild(this._Panel.Document.createElement('DIV'));this._PanelBox.className='SC_Panel';this._PanelBox.style.width=this.PanelWidth+'px';this._PanelBox.innerHTML='
      ';this._ItemsHolderEl=this._PanelBox.getElementsByTagName('TD')[0];if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKSpecialCombo_Cleanup);};function FCKSpecialCombo_ItemOnMouseOver(){this.className+=' SC_ItemOver';};function FCKSpecialCombo_ItemOnMouseOut(){this.className=this.originalClass;};function FCKSpecialCombo_ItemOnClick(){this.className=this.originalClass;this.FCKSpecialCombo._Panel.Hide();this.FCKSpecialCombo.SetLabel(this.FCKItemLabel);if (typeof(this.FCKSpecialCombo.OnSelect)=='function') this.FCKSpecialCombo.OnSelect(this.FCKItemID,this);};FCKSpecialCombo.prototype.AddItem=function(A,B,C,D){var E=this._ItemsHolderEl.appendChild(this._Panel.Document.createElement('DIV'));E.className=E.originalClass='SC_Item';E.innerHTML=B;E.FCKItemID=A;E.FCKItemLabel=C||A;E.FCKSpecialCombo=this;E.Selected=false;if (FCKBrowserInfo.IsIE) E.style.width='100%';if (D) E.style.backgroundColor=D;E.onmouseover=FCKSpecialCombo_ItemOnMouseOver;E.onmouseout=FCKSpecialCombo_ItemOnMouseOut;E.onclick=FCKSpecialCombo_ItemOnClick;this.Items[A.toString().toLowerCase()]=E;return E;};FCKSpecialCombo.prototype.SelectItem=function(A){A=A?A.toString().toLowerCase():'';var B=this.Items[A];if (B){B.className=B.originalClass='SC_ItemSelected';B.Selected=true;}};FCKSpecialCombo.prototype.SelectItemByLabel=function(A,B){for (var C in this.Items){var D=this.Items[C];if (D.FCKItemLabel==A){D.className=D.originalClass='SC_ItemSelected';D.Selected=true;if (B) this.SetLabel(A);}}};FCKSpecialCombo.prototype.DeselectAll=function(A){for (var i in this.Items){this.Items[i].className=this.Items[i].originalClass='SC_Item';this.Items[i].Selected=false;};if (A) this.SetLabel('');};FCKSpecialCombo.prototype.SetLabelById=function(A){A=A?A.toString().toLowerCase():'';var B=this.Items[A];this.SetLabel(B?B.FCKItemLabel:'');};FCKSpecialCombo.prototype.SetLabel=function(A){this.Label=A.length==0?' ':A;if (this._LabelEl){this._LabelEl.innerHTML=this.Label;FCKTools.DisableSelection(this._LabelEl);}};FCKSpecialCombo.prototype.SetEnabled=function(A){this.Enabled=A;this._OuterTable.className=A?'':'SC_FieldDisabled';};FCKSpecialCombo.prototype.Create=function(A){var B=FCKTools.GetElementDocument(A);var C=this._OuterTable=A.appendChild(B.createElement('TABLE'));C.cellPadding=0;C.cellSpacing=0;C.insertRow(-1);var D;var E;switch (this.Style){case 0:D='TB_ButtonType_Icon';E=false;break;case 1:D='TB_ButtonType_Text';E=false;break;case 2:E=true;break;};if (this.Caption&&this.Caption.length>0&&E){var F=C.rows[0].insertCell(-1);F.innerHTML=this.Caption;F.className='SC_FieldCaption';};var G=FCKTools.AppendElement(C.rows[0].insertCell(-1),'div');if (E){G.className='SC_Field';G.style.width=this.FieldWidth+'px';G.innerHTML='
       
      ';this._LabelEl=G.getElementsByTagName('label')[0];this._LabelEl.innerHTML=this.Label;}else{G.className='TB_Button_Off';G.innerHTML='
      '+this.Caption+'
      ';};G.SpecialCombo=this;G.onmouseover=FCKSpecialCombo_OnMouseOver;G.onmouseout=FCKSpecialCombo_OnMouseOut;G.onclick=FCKSpecialCombo_OnClick;FCKTools.DisableSelection(this._Panel.Document.body);};function FCKSpecialCombo_Cleanup(){this._LabelEl=null;this._OuterTable=null;this._ItemsHolderEl=null;this._PanelBox=null;if (this.Items){for (var A in this.Items) this.Items[A]=null;}};function FCKSpecialCombo_OnMouseOver(){if (this.SpecialCombo.Enabled){switch (this.SpecialCombo.Style){case 0:this.className='TB_Button_On_Over';break;case 1:this.className='TB_Button_On_Over';break;case 2:this.className='SC_Field SC_FieldOver';break;}}};function FCKSpecialCombo_OnMouseOut(){switch (this.SpecialCombo.Style){case 0:this.className='TB_Button_Off';break;case 1:this.className='TB_Button_Off';break;case 2:this.className='SC_Field';break;}};function FCKSpecialCombo_OnClick(e){var A=this.SpecialCombo;if (A.Enabled){var B=A._Panel;var C=A._PanelBox;var D=A._ItemsHolderEl;var E=A.PanelMaxHeight;if (A.OnBeforeClick) A.OnBeforeClick(A);if (FCKBrowserInfo.IsIE) B.Preload(0,this.offsetHeight,this);if (D.offsetHeight>E) C.style.height=E+'px';else C.style.height='';B.Show(0,this.offsetHeight,this);}}; -var FCKToolbarSpecialCombo=function(){this.SourceView=false;this.ContextSensitive=true;this._LastValue=null;};function FCKToolbarSpecialCombo_OnSelect(A,B){FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).Execute(A,B);};FCKToolbarSpecialCombo.prototype.Create=function(A){this._Combo=new FCKSpecialCombo(this.GetLabel(),this.FieldWidth,this.PanelWidth,this.PanelMaxHeight,FCKBrowserInfo.IsIE?window:FCKTools.GetElementWindow(A).parent);this._Combo.Tooltip=this.Tooltip;this._Combo.Style=this.Style;this.CreateItems(this._Combo);this._Combo.Create(A);this._Combo.CommandName=this.CommandName;this._Combo.OnSelect=FCKToolbarSpecialCombo_OnSelect;};function FCKToolbarSpecialCombo_RefreshActiveItems(A,B){A.DeselectAll();A.SelectItem(B);A.SetLabelById(B);};FCKToolbarSpecialCombo.prototype.RefreshState=function(){var A;var B=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetState();if (B!=-1){A=1;if (this.RefreshActiveItems) this.RefreshActiveItems(this._Combo,B);else{if (this._LastValue!=B){this._LastValue=B;FCKToolbarSpecialCombo_RefreshActiveItems(this._Combo,B);}}}else A=-1;if (A==this.State) return;if (A==-1){this._Combo.DeselectAll();this._Combo.SetLabel('');};this.State=A;this._Combo.SetEnabled(A!=-1);};FCKToolbarSpecialCombo.prototype.Enable=function(){this.RefreshState();};FCKToolbarSpecialCombo.prototype.Disable=function(){this.State=-1;this._Combo.DeselectAll();this._Combo.SetLabel('');this._Combo.SetEnabled(false);}; -var FCKToolbarFontsCombo=function(A,B){this.CommandName='FontName';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;};FCKToolbarFontsCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarFontsCombo.prototype.GetLabel=function(){return FCKLang.Font;};FCKToolbarFontsCombo.prototype.CreateItems=function(A){var B=FCKConfig.FontNames.split(';');for (var i=0;i'+B[i]+'');} -var FCKToolbarFontSizeCombo=function(A,B){this.CommandName='FontSize';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;};FCKToolbarFontSizeCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarFontSizeCombo.prototype.GetLabel=function(){return FCKLang.FontSize;};FCKToolbarFontSizeCombo.prototype.CreateItems=function(A){A.FieldWidth=70;var B=FCKConfig.FontSizes.split(';');for (var i=0;i'+C[1]+'',C[1]);}} -var FCKToolbarFontFormatCombo=function(A,B){this.CommandName='FontFormat';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;this.NormalLabel='Normal';this.PanelWidth=190;};FCKToolbarFontFormatCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarFontFormatCombo.prototype.GetLabel=function(){return FCKLang.FontFormat;};FCKToolbarFontFormatCombo.prototype.CreateItems=function(A){var B=A._Panel.Document;FCKTools.AppendStyleSheet(B,FCKConfig.ToolbarComboPreviewCSS);if (FCKConfig.BodyId&&FCKConfig.BodyId.length>0) B.body.id=FCKConfig.BodyId;if (FCKConfig.BodyClass&&FCKConfig.BodyClass.length>0) B.body.className+=' '+FCKConfig.BodyClass;var C=FCKLang['FontFormats'].split(';');var D={p:C[0],pre:C[1],address:C[2],h1:C[3],h2:C[4],h3:C[5],h4:C[6],h5:C[7],h6:C[8],div:C[9]};var E=FCKConfig.FontFormats.split(';');for (var i=0;i<'+F+'>'+G+'
      ',G);}};if (FCKBrowserInfo.IsIE){FCKToolbarFontFormatCombo.prototype.RefreshActiveItems=function(A,B){if (B==this.NormalLabel){if (A.Label!=' ') A.DeselectAll(true);}else{if (this._LastValue==B) return;A.SelectItemByLabel(B,true);};this._LastValue=B;}} -var FCKToolbarStyleCombo=function(A,B){this.CommandName='Style';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;};FCKToolbarStyleCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarStyleCombo.prototype.GetLabel=function(){return FCKLang.Style;};FCKToolbarStyleCombo.prototype.CreateItems=function(A){var B=A._Panel.Document;FCKTools.AppendStyleSheet(B,FCKConfig.ToolbarComboPreviewCSS);B.body.className+=' ForceBaseFont';if (FCKConfig.BodyId&&FCKConfig.BodyId.length>0) B.body.id=FCKConfig.BodyId;if (FCKConfig.BodyClass&&FCKConfig.BodyClass.length>0) B.body.className+=' '+FCKConfig.BodyClass;if (!(FCKBrowserInfo.IsGecko&&FCKBrowserInfo.IsGecko10)) A.OnBeforeClick=this.RefreshVisibleItems;var C=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).Styles;for (var s in C){var D=C[s];var E;if (D.IsObjectElement) E=A.AddItem(s,s);else E=A.AddItem(s,D.GetOpenerTag()+s+D.GetCloserTag());E.Style=D;}};FCKToolbarStyleCombo.prototype.RefreshActiveItems=function(A){A.DeselectAll();var B=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetActiveStyles();if (B.length>0){for (var i=0;i'+document.getElementById('xToolbarSpace').innerHTML+'');G.close();G.oncontextmenu=FCKTools.CancelEvent;FCKTools.AppendStyleSheet(G,FCKConfig.SkinPath+'fck_editor.css');B=D.__FCKToolbarSet=new FCKToolbarSet(G);B._IFrame=F;if (FCK.IECleanup) FCK.IECleanup.AddItem(D,FCKToolbarSet_Target_Cleanup);};B.CurrentInstance=FCK;FCK.AttachToOnSelectionChange(B.RefreshItemsState);return B;};function FCK_OnBlur(A){var B=A.ToolbarSet;if (B.CurrentInstance==A) B.Disable();};function FCK_OnFocus(A){var B=A.ToolbarSet;var C=A||FCK;B.CurrentInstance.FocusManager.RemoveWindow(B._IFrame.contentWindow);B.CurrentInstance=C;C.FocusManager.AddWindow(B._IFrame.contentWindow,true);B.Enable();};function FCKToolbarSet_Cleanup(){this._TargetElement=null;this._IFrame=null;};function FCKToolbarSet_Target_Cleanup(){this.__FCKToolbarSet=null;};var FCKToolbarSet=function(A){this._Document=A;this._TargetElement=A.getElementById('xToolbar');var B=A.getElementById('xExpandHandle');var C=A.getElementById('xCollapseHandle');B.title=FCKLang.ToolbarExpand;B.onclick=FCKToolbarSet_Expand_OnClick;C.title=FCKLang.ToolbarCollapse;C.onclick=FCKToolbarSet_Collapse_OnClick;if (!FCKConfig.ToolbarCanCollapse||FCKConfig.ToolbarStartExpanded) this.Expand();else this.Collapse();C.style.display=FCKConfig.ToolbarCanCollapse?'':'none';if (FCKConfig.ToolbarCanCollapse) C.style.display='';else A.getElementById('xTBLeftBorder').style.display='';this.Toolbars=[];this.IsLoaded=false;if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKToolbarSet_Cleanup);};function FCKToolbarSet_Expand_OnClick(){FCK.ToolbarSet.Expand();};function FCKToolbarSet_Collapse_OnClick(){FCK.ToolbarSet.Collapse();};FCKToolbarSet.prototype.Expand=function(){this._ChangeVisibility(false);};FCKToolbarSet.prototype.Collapse=function(){this._ChangeVisibility(true);};FCKToolbarSet.prototype._ChangeVisibility=function(A){this._Document.getElementById('xCollapsed').style.display=A?'':'none';this._Document.getElementById('xExpanded').style.display=A?'none':'';if (FCKBrowserInfo.IsGecko){FCKTools.RunFunction(window.onresize);}};FCKToolbarSet.prototype.Load=function(A){this.Name=A;this.Items=[];this.ItemsWysiwygOnly=[];this.ItemsContextSensitive=[];this._TargetElement.innerHTML='';var B=FCKConfig.ToolbarSets[A];if (!B){alert(FCKLang.UnknownToolbarSet.replace(/%1/g,A));return;};this.Toolbars=[];for (var x=0;x0) A.deleteRow(0);}};FCKMenuBlock.prototype.Create=function(A){if (!this._ItemsTable){if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKMenuBlock_Cleanup);this._Window=FCKTools.GetElementWindow(A);var B=FCKTools.GetElementDocument(A);var C=A.appendChild(B.createElement('table'));C.cellPadding=0;C.cellSpacing=0;FCKTools.DisableSelection(C);var D=C.insertRow(-1).insertCell(-1);D.className='MN_Menu';var E=this._ItemsTable=D.appendChild(B.createElement('table'));E.cellPadding=0;E.cellSpacing=0;};for (var i=0;i0&&F.href.length==0);if (G) return;menu.AddSeparator();if (E) menu.AddItem('Link',FCKLang.EditLink,34);menu.AddItem('Unlink',FCKLang.RemoveLink,35);}}};case 'Image':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&!tag.getAttribute('_fckfakelement')){menu.AddSeparator();menu.AddItem('Image',FCKLang.ImageProperties,37);}}};case 'Anchor':return {AddItems:function(menu,tag,tagName){var F=FCKSelection.MoveToAncestorNode('A');var G=(F&&F.name.length>0);if (G||(tagName=='IMG'&&tag.getAttribute('_fckanchor'))){menu.AddSeparator();menu.AddItem('Anchor',FCKLang.AnchorProp,36);}}};case 'Flash':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&tag.getAttribute('_fckflash')){menu.AddSeparator();menu.AddItem('Flash',FCKLang.FlashProperties,38);}}};case 'Form':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('FORM')){menu.AddSeparator();menu.AddItem('Form',FCKLang.FormProp,48);}}};case 'Checkbox':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='checkbox'){menu.AddSeparator();menu.AddItem('Checkbox',FCKLang.CheckboxProp,49);}}};case 'Radio':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='radio'){menu.AddSeparator();menu.AddItem('Radio',FCKLang.RadioButtonProp,50);}}};case 'TextField':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&(tag.type=='text'||tag.type=='password')){menu.AddSeparator();menu.AddItem('TextField',FCKLang.TextFieldProp,51);}}};case 'HiddenField':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&tag.getAttribute('_fckinputhidden')){menu.AddSeparator();menu.AddItem('HiddenField',FCKLang.HiddenFieldProp,56);}}};case 'ImageButton':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='image'){menu.AddSeparator();menu.AddItem('ImageButton',FCKLang.ImageButtonProp,55);}}};case 'Button':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&(tag.type=='button'||tag.type=='submit'||tag.type=='reset')){menu.AddSeparator();menu.AddItem('Button',FCKLang.ButtonProp,54);}}};case 'Select':return {AddItems:function(menu,tag,tagName){if (tagName=='SELECT'){menu.AddSeparator();menu.AddItem('Select',FCKLang.SelectionFieldProp,53);}}};case 'Textarea':return {AddItems:function(menu,tag,tagName){if (tagName=='TEXTAREA'){menu.AddSeparator();menu.AddItem('Textarea',FCKLang.TextareaProp,52);}}};case 'BulletedList':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('UL')){menu.AddSeparator();menu.AddItem('BulletedList',FCKLang.BulletedListProp,27);}}};case 'NumberedList':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('OL')){menu.AddSeparator();menu.AddItem('NumberedList',FCKLang.NumberedListProp,26);}}};};return null;};function FCK_ContextMenu_OnBeforeOpen(){FCK.Events.FireEvent('OnSelectionChange');var A,sTagName;if ((A=FCKSelection.GetSelectedElement())) sTagName=A.tagName;var B=FCK.ContextMenu._InnerContextMenu;B.RemoveAllItems();var C=FCK.ContextMenu.Listeners;for (var i=0;i0){var A;if (this.AvailableLangs.IndexOf(FCKLanguageManager.ActiveLanguage.Code)>=0) A=FCKLanguageManager.ActiveLanguage.Code;else A=this.AvailableLangs[0];LoadScript(this.Path+'lang/'+A+'.js');};LoadScript(this.Path+'fckplugin.js');} -var FCKPlugins=FCK.Plugins={};FCKPlugins.ItemsCount=0;FCKPlugins.Items={};FCKPlugins.Load=function(){var A=FCKPlugins.Items;for (var i=0;i-1);};String.prototype.Equals=function(){var A=arguments;if (A.length==1&&A[0].pop) A=A[0];for (var i=0;iC) return false;if (B){var E=new RegExp(A+'$','i');return E.test(this);}else return (D==0||this.substr(C-D,D)==A);};String.prototype.Remove=function(A,B){var s='';if (A>0) s=this.substring(0,A);if (A+B=7),IsIE6:/*@cc_on!@*/false && ( parseInt( s.match( /msie (\d+)/)[1],10)>=6),IsGecko:s.Contains('gecko/'),IsSafari:s.Contains(' applewebkit/'),IsOpera:!!window.opera,IsAIR:s.Contains(' adobeair/'),IsMac:s.Contains('macintosh')};(function(A){A.IsGeckoLike=(A.IsGecko||A.IsSafari||A.IsOpera);if (A.IsGecko){var B=s.match(/gecko\/(\d+)/)[1];A.IsGecko10=((B<20051111)||(/rv:1\.7/.test(s)));A.IsGecko19=/rv:1\.9/.test(s);}else A.IsGecko10=false;})(FCKBrowserInfo); +var FCKURLParams={};(function(){var A=document.location.search.substr(1).split('&');for (var i=0;i';if (!FCKRegexLib.HtmlOpener.test(A)) A=''+A+'';if (!FCKRegexLib.HeadOpener.test(A)) A=A.replace(FCKRegexLib.HtmlOpener,'$&');return A;}else{var B=FCKConfig.DocType+'0&&!FCKRegexLib.Html4DocType.test(FCKConfig.DocType)) B+=' style="overflow-y: scroll"';B+='>'+A+'';return B;}},ConvertToDataFormat:function(A,B,C,D){var E=FCKXHtml.GetXHTML(A,!B,D);if (C&&FCKRegexLib.EmptyOutParagraph.test(E)) return '';return E;},FixHtml:function(A){return A;}}; +var FCK={Name:FCKURLParams['InstanceName'],Status:0,EditMode:0,Toolbar:null,HasFocus:false,DataProcessor:new FCKDataProcessor(),GetInstanceObject:(function(){var w=window;return function(name){return w[name];}})(),AttachToOnSelectionChange:function(A){this.Events.AttachEvent('OnSelectionChange',A);},GetLinkedFieldValue:function(){return this.LinkedField.value;},GetParentForm:function(){return this.LinkedField.form;},StartupValue:'',IsDirty:function(){if (this.EditMode==1) return (this.StartupValue!=this.EditingArea.Textarea.value);else{if (!this.EditorDocument) return false;return (this.StartupValue!=this.EditorDocument.body.innerHTML);}},ResetIsDirty:function(){if (this.EditMode==1) this.StartupValue=this.EditingArea.Textarea.value;else if (this.EditorDocument.body) this.StartupValue=this.EditorDocument.body.innerHTML;},StartEditor:function(){this.TempBaseTag=FCKConfig.BaseHref.length>0?'':'';var A=FCK.KeystrokeHandler=new FCKKeystrokeHandler();A.OnKeystroke=_FCK_KeystrokeHandler_OnKeystroke;A.SetKeystrokes(FCKConfig.Keystrokes);if (FCKBrowserInfo.IsIE7){if ((CTRL+86/*V*/) in A.Keystrokes) A.SetKeystrokes([CTRL+86,true]);if ((SHIFT+45/*INS*/) in A.Keystrokes) A.SetKeystrokes([SHIFT+45,true]);};A.SetKeystrokes([CTRL+8,true]);this.EditingArea=new FCKEditingArea(document.getElementById('xEditingArea'));this.EditingArea.FFSpellChecker=FCKConfig.FirefoxSpellChecker;this.SetData(this.GetLinkedFieldValue(),true);FCKTools.AddEventListener(document,"keydown",this._TabKeyHandler);this.AttachToOnSelectionChange(_FCK_PaddingNodeListener);if (FCKBrowserInfo.IsGecko) this.AttachToOnSelectionChange(this._ExecCheckEmptyBlock);},Focus:function(){FCK.EditingArea.Focus();},SetStatus:function(A){this.Status=A;if (A==1){FCKFocusManager.AddWindow(window,true);if (FCKBrowserInfo.IsIE) FCKFocusManager.AddWindow(window.frameElement,true);if (FCKConfig.StartupFocus) FCK.Focus();};this.Events.FireEvent('OnStatusChange',A);},FixBody:function(){var A=FCKConfig.EnterMode;if (A!='p'&&A!='div') return;var B=this.EditorDocument;if (!B) return;var C=B.body;if (!C) return;FCKDomTools.TrimNode(C);var D=C.firstChild;var E;while (D){var F=false;switch (D.nodeType){case 1:var G=D.nodeName.toLowerCase();if (!FCKListsLib.BlockElements[G]&&G!='li'&&!D.getAttribute('_fckfakelement')&&D.getAttribute('_moz_dirty')==null) F=true;break;case 3:if (E||D.nodeValue.Trim().length>0) F=true;};if (F){var H=D.parentNode;if (!E) E=H.insertBefore(B.createElement(A),D);E.appendChild(H.removeChild(D));D=E.nextSibling;}else{if (E){FCKDomTools.TrimNode(E);E=null;};D=D.nextSibling;}};if (E) FCKDomTools.TrimNode(E);},GetData:function(A){if (FCK.EditMode==1) return FCK.EditingArea.Textarea.value;this.FixBody();var B=FCK.EditorDocument;if (!B) return null;var C=FCKConfig.FullPage;var D=FCK.DataProcessor.ConvertToDataFormat(C?B.documentElement:B.body,!C,FCKConfig.IgnoreEmptyParagraphValue,A);D=FCK.ProtectEventsRestore(D);if (FCKBrowserInfo.IsIE) D=D.replace(FCKRegexLib.ToReplace,'$1');if (C){if (FCK.DocTypeDeclaration&&FCK.DocTypeDeclaration.length>0) D=FCK.DocTypeDeclaration+'\n'+D;if (FCK.XmlDeclaration&&FCK.XmlDeclaration.length>0) D=FCK.XmlDeclaration+'\n'+D;};return FCKConfig.ProtectedSource.Revert(D);},UpdateLinkedField:function(){var A=FCK.GetXHTML(FCKConfig.FormatOutput);if (FCKConfig.HtmlEncodeOutput) A=FCKTools.HTMLEncode(A);FCK.LinkedField.value=A;FCK.Events.FireEvent('OnAfterLinkedFieldUpdate');},RegisteredDoubleClickHandlers:{},OnDoubleClick:function(A){var B=FCK.RegisteredDoubleClickHandlers[A.tagName.toUpperCase()];if (B){for (var i=0;i0?'|ABBR|XML|EMBED|OBJECT':'ABBR|XML|EMBED|OBJECT';var C;if (B.length>0){C=new RegExp('<('+B+')(?!\w|:)','gi');A=A.replace(C,'','gi');A=A.replace(C,'<\/FCK:$1>');};B='META';if (FCKBrowserInfo.IsIE) B+='|HR';C=new RegExp('<(('+B+')(?=\\s|>|/)[\\s\\S]*?)/?>','gi');A=A.replace(C,'');return A;},SetData:function(A,B){this.EditingArea.Mode=FCK.EditMode;if (FCKBrowserInfo.IsIE&&FCK.EditorDocument){FCK.EditorDocument.detachEvent("onselectionchange",Doc_OnSelectionChange);};if (FCK.EditMode==0){this._ForceResetIsDirty=(B===true);A=FCKConfig.ProtectedSource.Protect(A);A=FCK.DataProcessor.ConvertToHtml(A);A=A.replace(FCKRegexLib.InvalidSelfCloseTags,'$1>');A=FCK.ProtectEvents(A);A=FCK.ProtectUrls(A);A=FCK.ProtectTags(A);if (FCK.TempBaseTag.length>0&&!FCKRegexLib.HasBaseTag.test(A)) A=A.replace(FCKRegexLib.HeadOpener,'$&'+FCK.TempBaseTag);var C='';if (!FCKConfig.FullPage) C+=_FCK_GetEditorAreaStyleTags();if (FCKBrowserInfo.IsIE) C+=FCK._GetBehaviorsStyle();else if (FCKConfig.ShowBorders) C+=FCKTools.GetStyleHtml(FCK_ShowTableBordersCSS,true);C+=FCKTools.GetStyleHtml(FCK_InternalCSS,true);A=A.replace(FCKRegexLib.HeadCloser,C+'$&');this.EditingArea.OnLoad=_FCK_EditingArea_OnLoad;this.EditingArea.Start(A);}else{FCK.EditorWindow=null;FCK.EditorDocument=null;FCKDomTools.PaddingNode=null;this.EditingArea.OnLoad=null;this.EditingArea.Start(A);this.EditingArea.Textarea._FCKShowContextMenu=true;FCK.EnterKeyHandler=null;if (B) this.ResetIsDirty();FCK.KeystrokeHandler.AttachToElement(this.EditingArea.Textarea);this.EditingArea.Textarea.focus();FCK.Events.FireEvent('OnAfterSetHTML');};if (FCKBrowserInfo.IsGecko) window.onresize();},RedirectNamedCommands:{},ExecuteNamedCommand:function(A,B,C,D){if (!D) FCKUndo.SaveUndoStep();if (!C&&FCK.RedirectNamedCommands[A]!=null) FCK.ExecuteRedirectedNamedCommand(A,B);else{FCK.Focus();FCK.EditorDocument.execCommand(A,false,B);FCK.Events.FireEvent('OnSelectionChange');};if (!D) FCKUndo.SaveUndoStep();},GetNamedCommandState:function(A){try{if (FCKBrowserInfo.IsSafari&&FCK.EditorWindow&&A.IEquals('Paste')) return 0;if (!FCK.EditorDocument.queryCommandEnabled(A)) return -1;else{return FCK.EditorDocument.queryCommandState(A)?1:0;}}catch (e){return 0;}},GetNamedCommandValue:function(A){var B='';var C=FCK.GetNamedCommandState(A);if (C==-1) return null;try{B=this.EditorDocument.queryCommandValue(A);}catch(e) {};return B?B:'';},Paste:function(A){if (FCK.Status!=2||!FCK.Events.FireEvent('OnPaste')) return false;return A||FCK._ExecPaste();},PasteFromWord:function(){FCKDialog.OpenDialog('FCKDialog_Paste',FCKLang.PasteFromWord,'dialog/fck_paste.html',400,330,'Word');},Preview:function(){var A;if (FCKConfig.FullPage){if (FCK.TempBaseTag.length>0) A=FCK.TempBaseTag+FCK.GetXHTML();else A=FCK.GetXHTML();}else{A=FCKConfig.DocType+''+FCK.TempBaseTag+''+FCKLang.Preview+''+_FCK_GetEditorAreaStyleTags()+''+FCK.GetXHTML()+'';};var B=FCKConfig.ScreenWidth*0.8;var C=FCKConfig.ScreenHeight*0.7;var D=(FCKConfig.ScreenWidth-B)/2;var E='';if (FCK_IS_CUSTOM_DOMAIN&&FCKBrowserInfo.IsIE){window._FCKHtmlToLoad=A;E='javascript:void( (function(){document.open() ;document.domain="'+document.domain+'" ;document.write( window.opener._FCKHtmlToLoad );document.close() ;window.opener._FCKHtmlToLoad = null ;})() )';};var F=window.open(E,null,'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+B+',height='+C+',left='+D);if (!FCK_IS_CUSTOM_DOMAIN||!FCKBrowserInfo.IsIE){F.document.write(A);F.document.close();}},SwitchEditMode:function(A){var B=(FCK.EditMode==0);var C=FCK.IsDirty();var D;if (B){FCKCommands.GetCommand('ShowBlocks').SaveState();if (!A&&FCKBrowserInfo.IsIE) FCKUndo.SaveUndoStep();D=FCK.GetXHTML(FCKConfig.FormatSource);if (D==null) return false;}else D=this.EditingArea.Textarea.value;FCK.EditMode=B?1:0;FCK.SetData(D,!C);FCK.Focus();FCKTools.RunFunction(FCK.ToolbarSet.RefreshModeState,FCK.ToolbarSet);return true;},InsertElement:function(A){if (typeof A=='string') A=this.EditorDocument.createElement(A);var B=A.nodeName.toLowerCase();FCKSelection.Restore();var C=new FCKDomRange(this.EditorWindow);if (FCKListsLib.BlockElements[B]!=null){C.SplitBlock();C.InsertNode(A);var D=FCKDomTools.GetNextSourceElement(A,false,null,['hr','br','param','img','area','input'],true);if (!D&&FCKConfig.EnterMode!='br'){D=this.EditorDocument.body.appendChild(this.EditorDocument.createElement(FCKConfig.EnterMode));if (FCKBrowserInfo.IsGeckoLike) FCKTools.AppendBogusBr(D);};if (FCKListsLib.EmptyElements[B]==null) C.MoveToElementEditStart(A);else if (D) C.MoveToElementEditStart(D);else C.MoveToPosition(A,4);if (FCKBrowserInfo.IsGecko){if (D) D.scrollIntoView(false);A.scrollIntoView(false);}}else{C.MoveToSelection();C.DeleteContents();C.InsertNode(A);C.SetStart(A,4);C.SetEnd(A,4);};C.Select();C.Release();this.Focus();return A;},_InsertBlockElement:function(A){},_IsFunctionKey:function(A){if (A>=16&&A<=20) return true;if (A==27||(A>=33&&A<=40)) return true;if (A==45) return true;return false;},_KeyDownListener:function(A){if (!A) A=FCK.EditorWindow.event;if (FCK.EditorWindow){if (!FCK._IsFunctionKey(A.keyCode)&&!(A.ctrlKey||A.metaKey)&&!(A.keyCode==46)) FCK._KeyDownUndo();};return true;},_KeyDownUndo:function(){if (!FCKUndo.Typing){FCKUndo.SaveUndoStep();FCKUndo.Typing=true;FCK.Events.FireEvent("OnSelectionChange");};FCKUndo.TypesCount++;FCKUndo.Changed=1;if (FCKUndo.TypesCount>FCKUndo.MaxTypes){FCKUndo.TypesCount=0;FCKUndo.SaveUndoStep();}},_TabKeyHandler:function(A){if (!A) A=window.event;var B=A.keyCode;if (B==9&&FCK.EditMode!=0){if (FCKBrowserInfo.IsIE){var C=document.selection.createRange();if (C.parentElement()!=FCK.EditingArea.Textarea) return true;C.text='\t';C.select();}else{var a=[];var D=FCK.EditingArea.Textarea;var E=D.selectionStart;var F=D.selectionEnd;a.push(D.value.substr(0,E));a.push('\t');a.push(D.value.substr(F));D.value=a.join('');D.setSelectionRange(E+1,E+1);};if (A.preventDefault) return A.preventDefault();return A.returnValue=false;};return true;}};FCK.Events=new FCKEvents(FCK);FCK.GetHTML=FCK.GetXHTML=FCK.GetData;FCK.SetHTML=FCK.SetData;FCK.InsertElementAndGetIt=FCK.CreateElement=FCK.InsertElement;function _FCK_ProtectEvents_ReplaceTags(A){return A.replace(FCKRegexLib.EventAttributes,_FCK_ProtectEvents_ReplaceEvents);};function _FCK_ProtectEvents_ReplaceEvents(A,B){return ' '+B+'_fckprotectedatt="'+encodeURIComponent(A)+'"';};function _FCK_ProtectEvents_RestoreEvents(A,B){return decodeURIComponent(B);};function _FCK_MouseEventsListener(A){if (!A) A=window.event;if (A.type=='mousedown') FCK.MouseDownFlag=true;else if (A.type=='mouseup') FCK.MouseDownFlag=false;else if (A.type=='mousemove') FCK.Events.FireEvent('OnMouseMove',A);};function _FCK_PaddingNodeListener(){if (FCKConfig.EnterMode.IEquals('br')) return;FCKDomTools.EnforcePaddingNode(FCK.EditorDocument,FCKConfig.EnterMode);if (!FCKBrowserInfo.IsIE&&FCKDomTools.PaddingNode){var A=FCKSelection.GetSelection();if (A&&A.rangeCount==1){var B=A.getRangeAt(0);if (B.collapsed&&B.startContainer==FCK.EditorDocument.body&&B.startOffset==0){B.selectNodeContents(FCKDomTools.PaddingNode);B.collapse(true);A.removeAllRanges();A.addRange(B);}}}else if (FCKDomTools.PaddingNode){var C=FCKSelection.GetParentElement();var D=FCKDomTools.PaddingNode;if (C&&C.nodeName.IEquals('body')){if (FCK.EditorDocument.body.childNodes.length==1&&FCK.EditorDocument.body.firstChild==D){var B=FCK.EditorDocument.body.createTextRange();var F=false;if (!D.childNodes.firstChild){D.appendChild(FCKTools.GetElementDocument(D).createTextNode('\ufeff'));F=true;};B.moveToElementText(D);B.select();if (F) B.pasteHTML('');}}}};function _FCK_EditingArea_OnLoad(){FCK.EditorWindow=FCK.EditingArea.Window;FCK.EditorDocument=FCK.EditingArea.Document;FCK.InitializeBehaviors();FCK.MouseDownFlag=false;FCKTools.AddEventListener(FCK.EditorDocument,'mousemove',_FCK_MouseEventsListener);FCKTools.AddEventListener(FCK.EditorDocument,'mousedown',_FCK_MouseEventsListener);FCKTools.AddEventListener(FCK.EditorDocument,'mouseup',_FCK_MouseEventsListener);if (FCKBrowserInfo.IsSafari){var A=function(evt){if (!(evt.ctrlKey||evt.metaKey)) return;if (FCK.EditMode!=0) return;switch (evt.keyCode){case 89:FCKUndo.Redo();break;case 90:FCKUndo.Undo();break;}};FCKTools.AddEventListener(FCK.EditorDocument,'keyup',A);};FCK.EnterKeyHandler=new FCKEnterKey(FCK.EditorWindow,FCKConfig.EnterMode,FCKConfig.ShiftEnterMode,FCKConfig.TabSpaces);FCK.KeystrokeHandler.AttachToElement(FCK.EditorDocument);if (FCK._ForceResetIsDirty) FCK.ResetIsDirty();if (FCKBrowserInfo.IsIE&&FCK.HasFocus) FCK.EditorDocument.body.setActive();FCK.OnAfterSetHTML();FCKCommands.GetCommand('ShowBlocks').RestoreState();if (FCK.Status!=0) return;FCK.SetStatus(1);};function _FCK_GetEditorAreaStyleTags(){return FCKTools.GetStyleHtml(FCKConfig.EditorAreaCSS)+FCKTools.GetStyleHtml(FCKConfig.EditorAreaStyles);};function _FCK_KeystrokeHandler_OnKeystroke(A,B){if (FCK.Status!=2) return false;if (FCK.EditMode==0){switch (B){case 'Paste':return!FCK.Paste();case 'Cut':FCKUndo.SaveUndoStep();return false;}}else{if (B.Equals('Paste','Undo','Redo','SelectAll','Cut')) return false;};var C=FCK.Commands.GetCommand(B);if (C.GetState()==-1) return false;return (C.Execute.apply(C,FCKTools.ArgumentsToArray(arguments,2))!==false);};(function(){var A=window.parent.document;var B=A.getElementById(FCK.Name);var i=0;while (B||i==0){if (B&&B.tagName.toLowerCase().Equals('input','textarea')){FCK.LinkedField=B;break;};B=A.getElementsByName(FCK.Name)[i++];}})();var FCKTempBin={Elements:[],AddElement:function(A){var B=this.Elements.length;this.Elements[B]=A;return B;},RemoveElement:function(A){var e=this.Elements[A];this.Elements[A]=null;return e;},Reset:function(){var i=0;while (i40) return;};var C=function(H){if (H.nodeType!=1) return false;var D=H.tagName.toLowerCase();return (FCKListsLib.BlockElements[D]||FCKListsLib.EmptyElements[D]);};var E=function(){var F=FCKSelection.GetSelection();var G=F.getRangeAt(0);if (!G||!G.collapsed) return;var H=G.endContainer;if (H.nodeType!=3) return;if (H.nodeValue.length!=G.endOffset) return;var I=H.parentNode.tagName.toLowerCase();if (!(I=='a'||String(H.parentNode.contentEditable)=='false'||(!(FCKListsLib.BlockElements[I]||FCKListsLib.NonEmptyBlockElements[I])&&B==35))) return;var J=FCKTools.GetNextTextNode(H,H.parentNode,C);if (J) return;G=FCK.EditorDocument.createRange();J=FCKTools.GetNextTextNode(H,H.parentNode.parentNode,C);if (J){if (FCKBrowserInfo.IsOpera&&B==37) return;G.setStart(J,0);G.setEnd(J,0);}else{while (H.parentNode&&H.parentNode!=FCK.EditorDocument.body&&H.parentNode!=FCK.EditorDocument.documentElement&&H==H.parentNode.lastChild&&(!FCKListsLib.BlockElements[H.parentNode.tagName.toLowerCase()]&&!FCKListsLib.NonEmptyBlockElements[H.parentNode.tagName.toLowerCase()])) H=H.parentNode;if (FCKListsLib.BlockElements[I]||FCKListsLib.EmptyElements[I]||H==FCK.EditorDocument.body){G.setStart(H,H.childNodes.length);G.setEnd(H,H.childNodes.length);}else{var K=H.nextSibling;while (K){if (K.nodeType!=1){K=K.nextSibling;continue;};var L=K.tagName.toLowerCase();if (FCKListsLib.BlockElements[L]||FCKListsLib.EmptyElements[L]||FCKListsLib.NonEmptyBlockElements[L]) break;K=K.nextSibling;};var M=FCK.EditorDocument.createTextNode('');if (K) H.parentNode.insertBefore(M,K);else H.parentNode.appendChild(M);G.setStart(M,0);G.setEnd(M,0);}};F.removeAllRanges();F.addRange(G);FCK.Events.FireEvent("OnSelectionChange");};setTimeout(E,1);};this.ExecOnSelectionChangeTimer=function(){if (FCK.LastOnChangeTimer) window.clearTimeout(FCK.LastOnChangeTimer);FCK.LastOnChangeTimer=window.setTimeout(FCK.ExecOnSelectionChange,100);};this.EditorDocument.addEventListener('mouseup',this.ExecOnSelectionChange,false);this.EditorDocument.addEventListener('keyup',this.ExecOnSelectionChangeTimer,false);this._DblClickListener=function(e){FCK.OnDoubleClick(e.target);e.stopPropagation();};this.EditorDocument.addEventListener('dblclick',this._DblClickListener,true);this.EditorDocument.addEventListener('keydown',this._KeyDownListener,false);if (FCKBrowserInfo.IsGecko){this.EditorWindow.addEventListener('dragdrop',this._ExecDrop,true);}else if (FCKBrowserInfo.IsSafari){var N=function(evt){ if (!FCK.MouseDownFlag) evt.returnValue=false;};this.EditorDocument.addEventListener('dragenter',N,true);this.EditorDocument.addEventListener('dragover',N,true);this.EditorDocument.addEventListener('drop',this._ExecDrop,true);this.EditorDocument.addEventListener('mousedown',function(ev){var O=ev.srcElement;if (O.nodeName.IEquals('IMG','HR','INPUT','TEXTAREA','SELECT')){FCKSelection.SelectNode(O);}},true);this.EditorDocument.addEventListener('mouseup',function(ev){if (ev.srcElement.nodeName.IEquals('INPUT','TEXTAREA','SELECT')) ev.preventDefault()},true);this.EditorDocument.addEventListener('click',function(ev){if (ev.srcElement.nodeName.IEquals('INPUT','TEXTAREA','SELECT')) ev.preventDefault()},true);};if (FCKBrowserInfo.IsGecko||FCKBrowserInfo.IsOpera){this.EditorDocument.addEventListener('keypress',this._ExecCheckCaret,false);this.EditorDocument.addEventListener('click',this._ExecCheckCaret,false);};FCK.ContextMenu._InnerContextMenu.SetMouseClickWindow(FCK.EditorWindow);FCK.ContextMenu._InnerContextMenu.AttachToElement(FCK.EditorDocument);};FCK.MakeEditable=function(){this.EditingArea.MakeEditable();};function Document_OnContextMenu(e){if (!e.target._FCKShowContextMenu) e.preventDefault();};document.oncontextmenu=Document_OnContextMenu;FCK._BaseGetNamedCommandState=FCK.GetNamedCommandState;FCK.GetNamedCommandState=function(A){switch (A){case 'Unlink':return FCKSelection.HasAncestorNode('A')?0:-1;default:return FCK._BaseGetNamedCommandState(A);}};FCK.RedirectNamedCommands={Print:true,Paste:true};FCK.ExecuteRedirectedNamedCommand=function(A,B){switch (A){case 'Print':FCK.EditorWindow.print();break;case 'Paste':try{if (FCKBrowserInfo.IsSafari) throw '';if (FCK.Paste()) FCK.ExecuteNamedCommand('Paste',null,true);}catch (e) { FCKDialog.OpenDialog('FCKDialog_Paste',FCKLang.Paste,'dialog/fck_paste.html',400,330,'Security');};break;default:FCK.ExecuteNamedCommand(A,B);}};FCK._ExecPaste=function(){FCKUndo.SaveUndoStep();if (FCKConfig.ForcePasteAsPlainText){FCK.PasteAsPlainText();return false;};return true;};FCK.InsertHtml=function(A){A=FCKConfig.ProtectedSource.Protect(A);A=FCK.ProtectEvents(A);A=FCK.ProtectUrls(A);A=FCK.ProtectTags(A);FCKUndo.SaveUndoStep();this.EditorDocument.execCommand('inserthtml',false,A);this.Focus();FCKDocumentProcessor.Process(FCK.EditorDocument);this.Events.FireEvent("OnSelectionChange");};FCK.PasteAsPlainText=function(){FCKTools.RunFunction(FCKDialog.OpenDialog,FCKDialog,['FCKDialog_Paste',FCKLang.PasteAsText,'dialog/fck_paste.html',400,330,'PlainText']);};FCK.GetClipboardHTML=function(){return '';};FCK.CreateLink=function(A,B){var C=[];FCK.ExecuteNamedCommand('Unlink',null,false,!!B);if (A.length>0){var D='javascript:void(0);/*'+(new Date().getTime())+'*/';FCK.ExecuteNamedCommand('CreateLink',D,false,!!B);var E=this.EditorDocument.evaluate("//a[@href='"+D+"']",this.EditorDocument.body,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);for (var i=0;i0&&!isNaN(E)) this.PageConfig[D]=parseInt(E,10);else this.PageConfig[D]=E;}};function FCKConfig_LoadPageConfig(){var A=FCKConfig.PageConfig;for (var B in A) FCKConfig[B]=A[B];};function FCKConfig_PreProcess(){var A=FCKConfig;if (A.AllowQueryStringDebug){try{if ((/fckdebug=true/i).test(window.top.location.search)) A.Debug=true;}catch (e) {/*Ignore it. Much probably we are inside a FRAME where the "top" is in another domain (security error).*/}};if (!A.PluginsPath.EndsWith('/')) A.PluginsPath+='/';var B=A.ToolbarComboPreviewCSS;if (!B||B.length==0) A.ToolbarComboPreviewCSS=A.EditorAreaCSS;A.RemoveAttributesArray=(A.RemoveAttributes||'').split(',');if (!FCKConfig.SkinEditorCSS||FCKConfig.SkinEditorCSS.length==0) FCKConfig.SkinEditorCSS=FCKConfig.SkinPath+'fck_editor.css';if (!FCKConfig.SkinDialogCSS||FCKConfig.SkinDialogCSS.length==0) FCKConfig.SkinDialogCSS=FCKConfig.SkinPath+'fck_dialog.css';};FCKConfig.ToolbarSets={};FCKConfig.Plugins={};FCKConfig.Plugins.Items=[];FCKConfig.Plugins.Add=function(A,B,C){FCKConfig.Plugins.Items.AddItem([A,B,C]);};FCKConfig.ProtectedSource={};FCKConfig.ProtectedSource._CodeTag=(new Date()).valueOf();FCKConfig.ProtectedSource.RegexEntries=[//g,//gi,//gi];FCKConfig.ProtectedSource.Add=function(A){this.RegexEntries.AddItem(A);};FCKConfig.ProtectedSource.Protect=function(A){var B=this._CodeTag;function _Replace(protectedSource){var C=FCKTempBin.AddElement(protectedSource);return '';};for (var i=0;i|>)","g");return A.replace(D,_Replace);};FCKConfig.GetBodyAttributes=function(){var A='';if (this.BodyId&&this.BodyId.length>0) A+=' id="'+this.BodyId+'"';if (this.BodyClass&&this.BodyClass.length>0) A+=' class="'+this.BodyClass+'"';return A;};FCKConfig.ApplyBodyAttributes=function(A){if (this.BodyId&&this.BodyId.length>0) A.id=FCKConfig.BodyId;if (this.BodyClass&&this.BodyClass.length>0) A.className+=' '+FCKConfig.BodyClass;}; +var FCKDebug={};FCKDebug._GetWindow=function(){if (!this.DebugWindow||this.DebugWindow.closed) this.DebugWindow=window.open(FCKConfig.BasePath+'fckdebug.html','FCKeditorDebug','menubar=no,scrollbars=yes,resizable=yes,location=no,toolbar=no,width=600,height=500',true);return this.DebugWindow;};FCKDebug.Output=function(A,B,C){if (!FCKConfig.Debug) return;try{this._GetWindow().Output(A,B);}catch (e) {}};FCKDebug.OutputObject=function(A,B){if (!FCKConfig.Debug) return;try{this._GetWindow().OutputObject(A,B);}catch (e) {}}; +var FCKDomTools={MoveChildren:function(A,B,C){if (A==B) return;var D;if (C){while ((D=A.lastChild)) B.insertBefore(A.removeChild(D),B.firstChild);}else{while ((D=A.firstChild)) B.appendChild(A.removeChild(D));}},MoveNode:function(A,B,C){if (C) B.insertBefore(FCKDomTools.RemoveNode(A),B.firstChild);else B.appendChild(FCKDomTools.RemoveNode(A));},TrimNode:function(A){this.LTrimNode(A);this.RTrimNode(A);},LTrimNode:function(A){var B;while ((B=A.firstChild)){if (B.nodeType==3){var C=B.nodeValue.LTrim();var D=B.nodeValue.length;if (C.length==0){A.removeChild(B);continue;}else if (C.length0) break;if (A.lastChild) A=A.lastChild;else return this.GetPreviousSourceElement(A,B,C,D);};return null;},GetNextSourceElement:function(A,B,C,D,E){while((A=this.GetNextSourceNode(A,E))){if (A.nodeType==1){if (C&&A.nodeName.IEquals(C)) break;if (D&&A.nodeName.IEquals(D)) return this.GetNextSourceElement(A,B,C,D);return A;}else if (B&&A.nodeType==3&&A.nodeValue.RTrim().length>0) break;};return null;},GetNextSourceNode:function(A,B,C,D){if (!A) return null;var E;if (!B&&A.firstChild) E=A.firstChild;else{if (D&&A==D) return null;E=A.nextSibling;if (!E&&(!D||D!=A.parentNode)) return this.GetNextSourceNode(A.parentNode,true,C,D);};if (C&&E&&E.nodeType!=C) return this.GetNextSourceNode(E,false,C,D);return E;},GetPreviousSourceNode:function(A,B,C,D){if (!A) return null;var E;if (!B&&A.lastChild) E=A.lastChild;else{if (D&&A==D) return null;E=A.previousSibling;if (!E&&(!D||D!=A.parentNode)) return this.GetPreviousSourceNode(A.parentNode,true,C,D);};if (C&&E&&E.nodeType!=C) return this.GetPreviousSourceNode(E,false,C,D);return E;},InsertAfterNode:function(A,B){return A.parentNode.insertBefore(B,A.nextSibling);},GetParents:function(A){var B=[];while (A){B.unshift(A);A=A.parentNode;};return B;},GetCommonParents:function(A,B){var C=this.GetParents(A);var D=this.GetParents(B);var E=[];for (var i=0;i0) D[C.pop().toLowerCase()]=1;var E=this.GetCommonParents(A,B);var F=null;while ((F=E.pop())){if (D[F.nodeName.toLowerCase()]) return F;};return null;},GetIndexOf:function(A){var B=A.parentNode?A.parentNode.firstChild:null;var C=-1;while (B){C++;if (B==A) return C;B=B.nextSibling;};return-1;},PaddingNode:null,EnforcePaddingNode:function(A,B){try{if (!A||!A.body) return;}catch (e){return;};this.CheckAndRemovePaddingNode(A,B,true);try{if (A.body.lastChild&&(A.body.lastChild.nodeType!=1||A.body.lastChild.tagName.toLowerCase()==B.toLowerCase())) return;}catch (e){return;};var C=A.createElement(B);if (FCKBrowserInfo.IsGecko&&FCKListsLib.NonEmptyBlockElements[B]) FCKTools.AppendBogusBr(C);this.PaddingNode=C;if (A.body.childNodes.length==1&&A.body.firstChild.nodeType==1&&A.body.firstChild.tagName.toLowerCase()=='br'&&(A.body.firstChild.getAttribute('_moz_dirty')!=null||A.body.firstChild.getAttribute('type')=='_moz')) A.body.replaceChild(C,A.body.firstChild);else A.body.appendChild(C);},CheckAndRemovePaddingNode:function(A,B,C){var D=this.PaddingNode;if (!D) return;try{if (D.parentNode!=A.body||D.tagName.toLowerCase()!=B||(D.childNodes.length>1)||(D.firstChild&&D.firstChild.nodeValue!='\xa0'&&String(D.firstChild.tagName).toLowerCase()!='br')){this.PaddingNode=null;return;}}catch (e){this.PaddingNode=null;return;};if (!C){if (D.parentNode.childNodes.length>1) D.parentNode.removeChild(D);this.PaddingNode=null;}},HasAttribute:function(A,B){if (A.hasAttribute) return A.hasAttribute(B);else{var C=A.attributes[B];return (C!=undefined&&C.specified);}},HasAttributes:function(A){var B=A.attributes;for (var i=0;i0) return true;}else if (B[i].specified) return true;};return false;},RemoveAttribute:function(A,B){if (FCKBrowserInfo.IsIE&&B.toLowerCase()=='class') B='className';return A.removeAttribute(B,0);},RemoveAttributes:function (A,B){for (var i=0;i0) return false;C=C.nextSibling;};return D?this.CheckIsEmptyElement(D,B):true;},SetElementStyles:function(A,B){var C=A.style;for (var D in B) C[D]=B[D];},SetOpacity:function(A,B){if (FCKBrowserInfo.IsIE){B=Math.round(B*100);A.style.filter=(B>100?'':'progid:DXImageTransform.Microsoft.Alpha(opacity='+B+')');}else A.style.opacity=B;},GetCurrentElementStyle:function(A,B){if (FCKBrowserInfo.IsIE) return A.currentStyle[B];else return A.ownerDocument.defaultView.getComputedStyle(A,'').getPropertyValue(B);},GetPositionedAncestor:function(A){var B=A;while (B!=FCKTools.GetElementDocument(B).documentElement){if (this.GetCurrentElementStyle(B,'position')!='static') return B;if (B==FCKTools.GetElementDocument(B).documentElement&¤tWindow!=w) B=currentWindow.frameElement;else B=B.parentNode;};return null;},ScrollIntoView:function(A,B){var C=FCKTools.GetElementWindow(A);var D=FCKTools.GetViewPaneSize(C).Height;var E=D*-1;if (B===false){E+=A.offsetHeight;E+=parseInt(this.GetCurrentElementStyle(A,'marginBottom')||0,10);};E+=A.offsetTop;while ((A=A.offsetParent)) E+=A.offsetTop||0;var F=FCKTools.GetScrollPosition(C).Y;if (E>0&&E>F) C.scrollTo(0,E);},CheckIsEditable:function(A){var B=A.nodeName.toLowerCase();var C=FCK.DTD[B]||FCK.DTD.span;return (C['#']&&!FCKListsLib.NonEditableElements[B]);}}; +var FCKTools={};FCKTools.CreateBogusBR=function(A){var B=A.createElement('br');B.setAttribute('type','_moz');return B;};FCKTools.FixCssUrls=function(A,B){if (!A||A.length==0) return B;return B.replace(/url\s*\(([\s'"]*)(.*?)([\s"']*)\)/g,function(match,opener,path,closer){if (/^\/|^\w?:/.test(path)) return match;else return 'url('+opener+A+path+closer+')';});};FCKTools._GetUrlFixedCss=function(A,B){var C=A.match(/^([^|]+)\|([\s\S]*)/);if (C) return FCKTools.FixCssUrls(C[1],C[2]);else return A;};FCKTools.AppendStyleSheet=function(A,B){if (!B) return [];if (typeof(B)=='string'){if (/[\\\/\.]\w*$/.test(B)){return this.AppendStyleSheet(A,B.split(','));}else return [this.AppendStyleString(A,FCKTools._GetUrlFixedCss(B))];}else{var C=[];for (var i=0;i'+styleDef+'';};var C=function(cssFileUrl,markTemp){if (cssFileUrl.length==0) return '';var B=markTemp?' _fcktemp="true"':'';return '';};return function(cssFileOrArrayOrDef,markTemp){if (!cssFileOrArrayOrDef) return '';if (typeof(cssFileOrArrayOrDef)=='string'){if (/[\\\/\.]\w*$/.test(cssFileOrArrayOrDef)){return this.GetStyleHtml(cssFileOrArrayOrDef.split(','),markTemp);}else return A(this._GetUrlFixedCss(cssFileOrArrayOrDef),markTemp);}else{var E='';for (var i=0;i/g,'>');return A;};FCKTools.HTMLDecode=function(A){if (!A) return '';A=A.replace(/>/g,'>');A=A.replace(/</g,'<');A=A.replace(/&/g,'&');return A;};FCKTools._ProcessLineBreaksForPMode=function(A,B,C,D,E){var F=0;var G="

      ";var H="

      ";var I="
      ";if (C){G="
    5. ";H="
    6. ";F=1;};while (D&&D!=A.FCK.EditorDocument.body){if (D.tagName.toLowerCase()=='p'){F=1;break;};D=D.parentNode;};for (var i=0;i0) return A[A.length-1];return null;};FCKTools.GetDocumentPosition=function(w,A){var x=0;var y=0;var B=A;var C=null;var D=FCKTools.GetElementWindow(B);while (B&&!(D==w&&(B==w.document.body||B==w.document.documentElement))){x+=B.offsetLeft-B.scrollLeft;y+=B.offsetTop-B.scrollTop;if (!FCKBrowserInfo.IsOpera){var E=C;while (E&&E!=B){x-=E.scrollLeft;y-=E.scrollTop;E=E.parentNode;}};C=B;if (B.offsetParent) B=B.offsetParent;else{if (D!=w){B=D.frameElement;C=null;if (B) D=B.contentWindow.parent;}else B=null;}};if (FCKDomTools.GetCurrentElementStyle(w.document.body,'position')!='static'||(FCKBrowserInfo.IsIE&&FCKDomTools.GetPositionedAncestor(A)==null)){x+=w.document.body.offsetLeft;y+=w.document.body.offsetTop;};return { "x":x,"y":y };};FCKTools.GetWindowPosition=function(w,A){var B=this.GetDocumentPosition(w,A);var C=FCKTools.GetScrollPosition(w);B.x-=C.X;B.y-=C.Y;return B;};FCKTools.ProtectFormStyles=function(A){if (!A||A.nodeType!=1||A.tagName.toLowerCase()!='form') return [];var B=[];var C=['style','className'];for (var i=0;i0){for (var i=B.length-1;i>=0;i--){var C=B[i][0];var D=B[i][1];if (D) A.insertBefore(C,D);else A.appendChild(C);}}};FCKTools.GetNextNode=function(A,B){if (A.firstChild) return A.firstChild;else if (A.nextSibling) return A.nextSibling;else{var C=A.parentNode;while (C){if (C==B) return null;if (C.nextSibling) return C.nextSibling;else C=C.parentNode;}};return null;};FCKTools.GetNextTextNode=function(A,B,C){node=this.GetNextNode(A,B);if (C&&node&&C(node)) return null;while (node&&node.nodeType!=3){node=this.GetNextNode(node,B);if (C&&node&&C(node)) return null;};return node;};FCKTools.Merge=function(){var A=arguments;var o=A[0];for (var i=1;i');document.domain = '"+FCK_RUNTIME_DOMAIN+"';document.close();}() ) ;";if (FCKBrowserInfo.IsIE){if (FCKBrowserInfo.IsIE7||!FCKBrowserInfo.IsIE6) return "";else return "javascript: '';";};return "javascript: void(0);";}; +FCKTools.CancelEvent=function(e){if (e) e.preventDefault();};FCKTools.DisableSelection=function(A){if (FCKBrowserInfo.IsGecko) A.style.MozUserSelect='none';else if (FCKBrowserInfo.IsSafari) A.style.KhtmlUserSelect='none';else A.style.userSelect='none';};FCKTools._AppendStyleSheet=function(A,B){var e=A.createElement('LINK');e.rel='stylesheet';e.type='text/css';e.href=B;A.getElementsByTagName("HEAD")[0].appendChild(e);return e;};FCKTools.AppendStyleString=function(A,B){if (!B) return null;var e=A.createElement("STYLE");e.appendChild(A.createTextNode(B));A.getElementsByTagName("HEAD")[0].appendChild(e);return e;};FCKTools.ClearElementAttributes=function(A){for (var i=0;i0) B[B.length]=D;C(parent.childNodes[i]);}};C(A);return B;};FCKTools.RemoveOuterTags=function(e){var A=e.ownerDocument.createDocumentFragment();for (var i=0;i','text/xml');FCKDomTools.RemoveNode(B.firstChild);return B;};return null;};FCKTools.GetScrollPosition=function(A){return { X:A.pageXOffset,Y:A.pageYOffset };};FCKTools.AddEventListener=function(A,B,C){A.addEventListener(B,C,false);};FCKTools.RemoveEventListener=function(A,B,C){A.removeEventListener(B,C,false);};FCKTools.AddEventListenerEx=function(A,B,C,D){A.addEventListener(B,function(e){C.apply(A,[e].concat(D||[]));},false);};FCKTools.GetViewPaneSize=function(A){return { Width:A.innerWidth,Height:A.innerHeight };};FCKTools.SaveStyles=function(A){var B=FCKTools.ProtectFormStyles(A);var C={};if (A.className.length>0){C.Class=A.className;A.className='';};var D=A.getAttribute('style');if (D&&D.length>0){C.Inline=D;A.setAttribute('style','',0);};FCKTools.RestoreFormStyles(A,B);return C;};FCKTools.RestoreStyles=function(A,B){var C=FCKTools.ProtectFormStyles(A);A.className=B.Class||'';if (B.Inline) A.setAttribute('style',B.Inline,0);else A.removeAttribute('style',0);FCKTools.RestoreFormStyles(A,C);};FCKTools.RegisterDollarFunction=function(A){A.$=function(id){return A.document.getElementById(id);};};FCKTools.AppendElement=function(A,B){return A.appendChild(A.ownerDocument.createElement(B));};FCKTools.GetElementPosition=function(A,B){var c={ X:0,Y:0 };var C=B||window;var D=FCKTools.GetElementWindow(A);var E=null;while (A){var F=D.getComputedStyle(A,'').position;if (F&&F!='static'&&A.style.zIndex!=FCKConfig.FloatingPanelsZIndex) break;c.X+=A.offsetLeft-A.scrollLeft;c.Y+=A.offsetTop-A.scrollTop;if (!FCKBrowserInfo.IsOpera){var G=E;while (G&&G!=A){c.X-=G.scrollLeft;c.Y-=G.scrollTop;G=G.parentNode;}};E=A;if (A.offsetParent) A=A.offsetParent;else{if (D!=C){A=D.frameElement;E=null;if (A) D=FCKTools.GetElementWindow(A);}else{c.X+=A.scrollLeft;c.Y+=A.scrollTop;break;}}};return c;}; +var FCKeditorAPI;function InitializeAPI(){var A=window.parent;if (!(FCKeditorAPI=A.FCKeditorAPI)){var B='window.FCKeditorAPI = {Version : "2.6",VersionBuild : "18638",Instances : new Object(),GetInstance : function( name ){return this.Instances[ name ];},_FormSubmit : function(){for ( var name in FCKeditorAPI.Instances ){var oEditor = FCKeditorAPI.Instances[ name ] ;if ( oEditor.GetParentForm && oEditor.GetParentForm() == this )oEditor.UpdateLinkedField() ;}this._FCKOriginalSubmit() ;},_FunctionQueue : {Functions : new Array(),IsRunning : false,Add : function( f ){this.Functions.push( f );if ( !this.IsRunning )this.StartNext();},StartNext : function(){var aQueue = this.Functions ;if ( aQueue.length > 0 ){this.IsRunning = true;aQueue[0].call();}else this.IsRunning = false;},Remove : function( f ){var aQueue = this.Functions;var i = 0, fFunc;while( (fFunc = aQueue[ i ]) ){if ( fFunc == f )aQueue.splice( i,1 );i++ ;}this.StartNext();}}}';if (A.execScript) A.execScript(B,'JavaScript');else{if (FCKBrowserInfo.IsGecko10){eval.call(A,B);}else if(FCKBrowserInfo.IsAIR){FCKAdobeAIR.FCKeditorAPI_Evaluate(A,B);}else if (FCKBrowserInfo.IsSafari||FCKBrowserInfo.IsGecko19){var C=A.document;var D=C.createElement('script');D.appendChild(C.createTextNode(B));C.documentElement.appendChild(D);}else A.eval(B);};FCKeditorAPI=A.FCKeditorAPI;FCKeditorAPI.__Instances=FCKeditorAPI.Instances;};FCKeditorAPI.Instances[FCK.Name]=FCK;};function _AttachFormSubmitToAPI(){var A=FCK.GetParentForm();if (A){FCKTools.AddEventListener(A,'submit',FCK.UpdateLinkedField);if (!A._FCKOriginalSubmit&&(typeof(A.submit)=='function'||(!A.submit.tagName&&!A.submit.length))){A._FCKOriginalSubmit=A.submit;A.submit=FCKeditorAPI._FormSubmit;}}};function FCKeditorAPI_Cleanup(){if (!window.FCKUnloadFlag) return;delete FCKeditorAPI.Instances[FCK.Name];};function FCKeditorAPI_ConfirmCleanup(){window.FCKUnloadFlag=true;};FCKTools.AddEventListener(window,'unload',FCKeditorAPI_Cleanup);FCKTools.AddEventListener(window,'beforeunload',FCKeditorAPI_ConfirmCleanup); +var FCKImagePreloader=function(){this._Images=[];};FCKImagePreloader.prototype={AddImages:function(A){if (typeof(A)=='string') A=A.split(';');this._Images=this._Images.concat(A);},Start:function(){var A=this._Images;this._PreloadCount=A.length;for (var i=0;i]*\>)/i,AfterBody:/(\<\/body\>[\s\S]*$)/i,ToReplace:/___fcktoreplace:([\w]+)/ig,MetaHttpEquiv:/http-equiv\s*=\s*["']?([^"' ]+)/i,HasBaseTag:/]/i,HtmlOpener:/]*>/i,HeadOpener:/]*>/i,HeadCloser:/<\/head\s*>/i,FCK_Class:/\s*FCK__[^ ]*(?=\s+|$)/,ElementName:/(^[a-z_:][\w.\-:]*\w$)|(^[a-z_]$)/,ForceSimpleAmpersand:/___FCKAmp___/g,SpaceNoClose:/\/>/g,EmptyParagraph:/^<(p|div|address|h\d|center)(?=[ >])[^>]*>\s*(<\/\1>)?$/,EmptyOutParagraph:/^<(p|div|address|h\d|center)(?=[ >])[^>]*>(?:\s*| )(<\/\1>)?$/,TagBody:/>]+))/gi,ProtectUrlsA:/]+))/gi,ProtectUrlsArea:/]+))/gi,Html4DocType:/HTML 4\.0 Transitional/i,DocTypeTag:/]*>/i,TagsWithEvent:/<[^\>]+ on\w+[\s\r\n]*=[\s\r\n]*?('|")[\s\S]+?\>/g,EventAttributes:/\s(on\w+)[\s\r\n]*=[\s\r\n]*?('|")([\s\S]*?)\2/g,ProtectedEvents:/\s\w+_fckprotectedatt="([^"]+)"/g,StyleProperties:/\S+\s*:/g,InvalidSelfCloseTags:/(<(?!base|meta|link|hr|br|param|img|area|input)([a-zA-Z0-9:]+)[^>]*)\/>/gi,StyleVariableAttName:/#\(\s*("|')(.+?)\1[^\)]*\s*\)/g,RegExp:/^\/(.*)\/([gim]*)$/,HtmlTag:/<[^\s<>](?:"[^"]*"|'[^']*'|[^<])*>/}; +var FCKListsLib={BlockElements:{ address:1,blockquote:1,center:1,div:1,dl:1,fieldset:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,marquee:1,noscript:1,ol:1,p:1,pre:1,script:1,table:1,ul:1 },NonEmptyBlockElements:{ p:1,div:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,address:1,pre:1,ol:1,ul:1,li:1,td:1,th:1 },InlineChildReqElements:{ abbr:1,acronym:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1 },InlineNonEmptyElements:{ a:1,abbr:1,acronym:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1 },EmptyElements:{ base:1,col:1,meta:1,link:1,hr:1,br:1,param:1,img:1,area:1,input:1 },PathBlockElements:{ address:1,blockquote:1,dl:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,p:1,pre:1,li:1,dt:1,de:1 },PathBlockLimitElements:{ body:1,div:1,td:1,th:1,caption:1,form:1 },StyleBlockElements:{ address:1,div:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,p:1,pre:1 },StyleObjectElements:{ img:1,hr:1,li:1,table:1,tr:1,td:1,embed:1,object:1,ol:1,ul:1 },NonEditableElements:{ button:1,option:1,script:1,iframe:1,textarea:1,object:1,embed:1,map:1,applet:1 },BlockBoundaries:{ p:1,div:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,address:1,pre:1,ol:1,ul:1,li:1,dt:1,de:1,table:1,thead:1,tbody:1,tfoot:1,tr:1,th:1,td:1,caption:1,col:1,colgroup:1,blockquote:1,body:1 },ListBoundaries:{ p:1,div:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,address:1,pre:1,ol:1,ul:1,li:1,dt:1,de:1,table:1,thead:1,tbody:1,tfoot:1,tr:1,th:1,td:1,caption:1,col:1,colgroup:1,blockquote:1,body:1,br:1 }}; +var FCKLanguageManager=FCK.Language={AvailableLanguages:{af:'Afrikaans',ar:'Arabic',bg:'Bulgarian',bn:'Bengali/Bangla',bs:'Bosnian',ca:'Catalan',cs:'Czech',da:'Danish',de:'German',el:'Greek',en:'English','en-au':'English (Australia)','en-ca':'English (Canadian)','en-uk':'English (United Kingdom)',eo:'Esperanto',es:'Spanish',et:'Estonian',eu:'Basque',fa:'Persian',fi:'Finnish',fo:'Faroese',fr:'French','fr-ca':'French (Canada)',gl:'Galician',he:'Hebrew',hi:'Hindi',hr:'Croatian',hu:'Hungarian',it:'Italian',ja:'Japanese',km:'Khmer',ko:'Korean',lt:'Lithuanian',lv:'Latvian',mn:'Mongolian',ms:'Malay',nb:'Norwegian Bokmal',nl:'Dutch',no:'Norwegian',pl:'Polish',pt:'Portuguese (Portugal)','pt-br':'Portuguese (Brazil)',ro:'Romanian',ru:'Russian',sk:'Slovak',sl:'Slovenian',sr:'Serbian (Cyrillic)','sr-latn':'Serbian (Latin)',sv:'Swedish',th:'Thai',tr:'Turkish',uk:'Ukrainian',vi:'Vietnamese',zh:'Chinese Traditional','zh-cn':'Chinese Simplified'},GetActiveLanguage:function(){if (FCKConfig.AutoDetectLanguage){var A;if (navigator.userLanguage) A=navigator.userLanguage.toLowerCase();else if (navigator.language) A=navigator.language.toLowerCase();else{return FCKConfig.DefaultLanguage;};if (A.length>=5){A=A.substr(0,5);if (this.AvailableLanguages[A]) return A;};if (A.length>=2){A=A.substr(0,2);if (this.AvailableLanguages[A]) return A;}};return this.DefaultLanguage;},TranslateElements:function(A,B,C,D){var e=A.getElementsByTagName(B);var E,s;for (var i=0;i0) C+='|'+FCKConfig.AdditionalNumericEntities;FCKXHtmlEntities.EntitiesRegex=new RegExp(C,'g');}; +var FCKXHtml={};FCKXHtml.CurrentJobNum=0;FCKXHtml.GetXHTML=function(A,B,C){FCKDomTools.CheckAndRemovePaddingNode(FCKTools.GetElementDocument(A),FCKConfig.EnterMode);FCKXHtmlEntities.Initialize();this._NbspEntity=(FCKConfig.ProcessHTMLEntities?'nbsp':'#160');var D=FCK.IsDirty();FCKXHtml.SpecialBlocks=[];this.XML=FCKTools.CreateXmlObject('DOMDocument');this.MainNode=this.XML.appendChild(this.XML.createElement('xhtml'));FCKXHtml.CurrentJobNum++;if (B) this._AppendNode(this.MainNode,A);else this._AppendChildNodes(this.MainNode,A,false);var E=this._GetMainXmlString();this.XML=null;if (FCKBrowserInfo.IsSafari) E=E.replace(/^/,'');E=E.substr(7,E.length-15).Trim();E=E.replace(FCKRegexLib.SpaceNoClose,' />');if (FCKConfig.ForceSimpleAmpersand) E=E.replace(FCKRegexLib.ForceSimpleAmpersand,'&');if (C) E=FCKCodeFormatter.Format(E);for (var i=0;i0;if (C) A.appendChild(this.XML.createTextNode(B.replace(FCKXHtmlEntities.EntitiesRegex,FCKXHtml_GetEntity)));return C;};function FCKXHtml_GetEntity(A){var B=FCKXHtmlEntities.Entities[A]||('#'+A.charCodeAt(0));return '#?-:'+B+';';};FCKXHtml.TagProcessors={a:function(A,B){if (B.innerHTML.Trim().length==0&&!B.name) return false;var C=B.getAttribute('_fcksavedurl');if (C!=null) FCKXHtml._AppendAttribute(A,'href',C);if (FCKBrowserInfo.IsIE){if (B.name) FCKXHtml._AppendAttribute(A,'name',B.name);};A=FCKXHtml._AppendChildNodes(A,B,false);return A;},area:function(A,B){var C=B.getAttribute('_fcksavedurl');if (C!=null) FCKXHtml._AppendAttribute(A,'href',C);if (FCKBrowserInfo.IsIE){if (!A.attributes.getNamedItem('coords')){var D=B.getAttribute('coords',2);if (D&&D!='0,0,0') FCKXHtml._AppendAttribute(A,'coords',D);};if (!A.attributes.getNamedItem('shape')){var E=B.getAttribute('shape',2);if (E&&E.length>0) FCKXHtml._AppendAttribute(A,'shape',E.toLowerCase());}};return A;},body:function(A,B){A=FCKXHtml._AppendChildNodes(A,B,false);A.removeAttribute('spellcheck');return A;},iframe:function(A,B){var C=B.innerHTML;if (FCKBrowserInfo.IsGecko) C=FCKTools.HTMLDecode(C);C=C.replace(/\s_fcksavedurl="[^"]*"/g,'');A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem(C)));return A;},img:function(A,B){if (!A.attributes.getNamedItem('alt')) FCKXHtml._AppendAttribute(A,'alt','');var C=B.getAttribute('_fcksavedurl');if (C!=null) FCKXHtml._AppendAttribute(A,'src',C);return A;},li:function(A,B,C){if (C.nodeName.IEquals(['ul','ol'])) return FCKXHtml._AppendChildNodes(A,B,true);var D=FCKXHtml.XML.createElement('ul');B._fckxhtmljob=null;do{FCKXHtml._AppendNode(D,B);do{B=FCKDomTools.GetNextSibling(B);} while (B&&B.nodeType==3&&B.nodeValue.Trim().length==0)} while (B&&B.nodeName.toLowerCase()=='li') return D;},ol:function(A,B,C){if (B.innerHTML.Trim().length==0) return false;var D=C.lastChild;if (D&&D.nodeType==3) D=D.previousSibling;if (D&&D.nodeName.toUpperCase()=='LI'){B._fckxhtmljob=null;FCKXHtml._AppendNode(D,B);return false;};A=FCKXHtml._AppendChildNodes(A,B);return A;},pre:function (A,B){var C=B.firstChild;if (C&&C.nodeType==3) A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem('\r\n')));FCKXHtml._AppendChildNodes(A,B,true);return A;},script:function(A,B){if (!A.attributes.getNamedItem('type')) FCKXHtml._AppendAttribute(A,'type','text/javascript');A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem(B.text)));return A;},span:function(A,B){if (B.innerHTML.length==0) return false;A=FCKXHtml._AppendChildNodes(A,B,false);return A;},style:function(A,B){if (!A.attributes.getNamedItem('type')) FCKXHtml._AppendAttribute(A,'type','text/css');var C=B.innerHTML;if (FCKBrowserInfo.IsIE) C=C.replace(/^(\r\n|\n|\r)/,'');A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem(C)));return A;},title:function(A,B){A.appendChild(FCKXHtml.XML.createTextNode(FCK.EditorDocument.title));return A;}};FCKXHtml.TagProcessors.ul=FCKXHtml.TagProcessors.ol; +FCKXHtml._GetMainXmlString=function(){return (new XMLSerializer()).serializeToString(this.MainNode);};FCKXHtml._AppendAttributes=function(A,B,C){var D=B.attributes;for (var n=0;n]*\>/gi;A.BlocksCloser=/\<\/(P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|TITLE|META|LINK|BASE|SCRIPT|LINK|TD|TH|AREA|OPTION)[^\>]*\>/gi;A.NewLineTags=/\<(BR|HR)[^\>]*\>/gi;A.MainTags=/\<\/?(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR)[^\>]*\>/gi;A.LineSplitter=/\s*\n+\s*/g;A.IncreaseIndent=/^\<(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL)[ \/\>]/i;A.DecreaseIndent=/^\<\/(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL)[ \>]/i;A.FormatIndentatorRemove=new RegExp('^'+FCKConfig.FormatIndentator);A.ProtectedTags=/(]*>)([\s\S]*?)(<\/PRE>)/gi;};FCKCodeFormatter._ProtectData=function(A,B,C,D){return B+'___FCKpd___'+FCKCodeFormatter.ProtectedData.AddItem(C)+D;};FCKCodeFormatter.Format=function(A){if (!this.Regex) this.Init();FCKCodeFormatter.ProtectedData=[];var B=A.replace(this.Regex.ProtectedTags,FCKCodeFormatter._ProtectData);B=B.replace(this.Regex.BlocksOpener,'\n$&');B=B.replace(this.Regex.BlocksCloser,'$&\n');B=B.replace(this.Regex.NewLineTags,'$&\n');B=B.replace(this.Regex.MainTags,'\n$&\n');var C='';var D=B.split(this.Regex.LineSplitter);B='';for (var i=0;iB[i]) return 1;};if (A.lengthB.length) return 1;return 0;};FCKUndo._CheckIsBookmarksEqual=function(A,B){if (!(A&&B)) return false;if (FCKBrowserInfo.IsIE){var C=A[1].search(A[0].StartId);var D=B[1].search(B[0].StartId);var E=A[1].search(A[0].EndId);var F=B[1].search(B[0].EndId);return C==D&&E==F;}else{return this._CompareCursors(A.Start,B.Start)==0&&this._CompareCursors(A.End,B.End)==0;}};FCKUndo.SaveUndoStep=function(){if (FCK.EditMode!=0||this.SaveLocked) return;if (this.SavedData.length) this.Changed=true;var A=FCK.EditorDocument.body.innerHTML;var B=this._GetBookmark();this.SavedData=this.SavedData.slice(0,this.CurrentIndex+1);if (this.CurrentIndex>0&&A==this.SavedData[this.CurrentIndex][0]&&this._CheckIsBookmarksEqual(B,this.SavedData[this.CurrentIndex][1])) return;else if (this.CurrentIndex==0&&this.SavedData.length&&A==this.SavedData[0][0]){this.SavedData[0][1]=B;return;};if (this.CurrentIndex+1>=FCKConfig.MaxUndoLevels) this.SavedData.shift();else this.CurrentIndex++;this.SavedData[this.CurrentIndex]=[A,B];FCK.Events.FireEvent("OnSelectionChange");};FCKUndo.CheckUndoState=function(){return (this.Changed||this.CurrentIndex>0);};FCKUndo.CheckRedoState=function(){return (this.CurrentIndex<(this.SavedData.length-1));};FCKUndo.Undo=function(){if (this.CheckUndoState()){if (this.CurrentIndex==(this.SavedData.length-1)){this.SaveUndoStep();};this._ApplyUndoLevel(--this.CurrentIndex);FCK.Events.FireEvent("OnSelectionChange");}};FCKUndo.Redo=function(){if (this.CheckRedoState()){this._ApplyUndoLevel(++this.CurrentIndex);FCK.Events.FireEvent("OnSelectionChange");}};FCKUndo._ApplyUndoLevel=function(A){var B=this.SavedData[A];if (!B) return;if (FCKBrowserInfo.IsIE){if (B[1]&&B[1][1]) FCK.SetInnerHtml(B[1][1]);else FCK.SetInnerHtml(B[0]);}else FCK.EditorDocument.body.innerHTML=B[0];this._SelectBookmark(B[1]);this.TypesCount=0;this.Changed=false;this.Typing=false;}; +var FCKEditingArea=function(A){this.TargetElement=A;this.Mode=0;if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKEditingArea_Cleanup);};FCKEditingArea.prototype.Start=function(A,B){var C=this.TargetElement;var D=FCKTools.GetElementDocument(C);while(C.firstChild) C.removeChild(C.firstChild);if (this.Mode==0){if (FCK_IS_CUSTOM_DOMAIN) A=''+A;if (FCKBrowserInfo.IsIE) A=A.replace(/(]*?)\s*\/?>(?!\s*<\/base>)/gi,'$1>');else if (!B){var E=A.match(FCKRegexLib.BeforeBody);var F=A.match(FCKRegexLib.AfterBody);if (E&&F){var G=A.substr(E[1].length,A.length-E[1].length-F[1].length);A=E[1]+' '+F[1];if (FCKBrowserInfo.IsGecko&&(G.length==0||FCKRegexLib.EmptyParagraph.test(G))) G='
      ';this._BodyHTML=G;}else this._BodyHTML=A;};var H=this.IFrame=D.createElement('iframe');var I='';H.frameBorder=0;H.width=H.height='100%';if (FCK_IS_CUSTOM_DOMAIN&&FCKBrowserInfo.IsIE){window._FCKHtmlToLoad=I+A;H.src='javascript:void( (function(){document.open() ;document.domain="'+document.domain+'" ;document.write( window.parent._FCKHtmlToLoad );document.close() ;window.parent._FCKHtmlToLoad = null ;})() )';}else if (!FCKBrowserInfo.IsGecko){H.src='javascript:void(0)';};C.appendChild(H);this.Window=H.contentWindow;if (!FCK_IS_CUSTOM_DOMAIN||!FCKBrowserInfo.IsIE){var J=this.Window.document;J.open();J.write(I+A);J.close();};if (FCKBrowserInfo.IsAIR) FCKAdobeAIR.EditingArea_Start(J,A);if (FCKBrowserInfo.IsGecko10&&!B){this.Start(A,true);return;};if (H.readyState&&H.readyState!='completed'){var K=this;(H.onreadystatechange=function(){if (H.readyState=='complete'){H.onreadystatechange=null;K.Window._FCKEditingArea=K;FCKEditingArea_CompleteStart.call(K.Window);}})();}else{this.Window._FCKEditingArea=this;if (FCKBrowserInfo.IsGecko10) this.Window.setTimeout(FCKEditingArea_CompleteStart,500);else FCKEditingArea_CompleteStart.call(this.Window);}}else{var L=this.Textarea=D.createElement('textarea');L.className='SourceField';L.dir='ltr';FCKDomTools.SetElementStyles(L,{width:'100%',height:'100%',border:'none',resize:'none',outline:'none'});C.appendChild(L);L.value=A;FCKTools.RunFunction(this.OnLoad);}};function FCKEditingArea_CompleteStart(){if (!this.document.body){this.setTimeout(FCKEditingArea_CompleteStart,50);return;};var A=this._FCKEditingArea;A.Document=A.Window.document;A.MakeEditable();FCKTools.RunFunction(A.OnLoad);};FCKEditingArea.prototype.MakeEditable=function(){var A=this.Document;if (FCKBrowserInfo.IsIE){A.body.disabled=true;A.body.contentEditable=true;A.body.removeAttribute("disabled");}else{try{A.body.spellcheck=(this.FFSpellChecker!==false);if (this._BodyHTML){A.body.innerHTML=this._BodyHTML;this._BodyHTML=null;};A.designMode='on';A.execCommand('enableObjectResizing',false,!FCKConfig.DisableObjectResizing);A.execCommand('enableInlineTableEditing',false,!FCKConfig.DisableFFTableHandles);}catch (e){FCKTools.AddEventListener(this.Window.frameElement,'DOMAttrModified',FCKEditingArea_Document_AttributeNodeModified);}}};function FCKEditingArea_Document_AttributeNodeModified(A){var B=A.currentTarget.contentWindow._FCKEditingArea;if (B._timer) window.clearTimeout(B._timer);B._timer=FCKTools.SetTimeout(FCKEditingArea_MakeEditableByMutation,1000,B);};function FCKEditingArea_MakeEditableByMutation(){delete this._timer;FCKTools.RemoveEventListener(this.Window.frameElement,'DOMAttrModified',FCKEditingArea_Document_AttributeNodeModified);this.MakeEditable();};FCKEditingArea.prototype.Focus=function(){try{if (this.Mode==0){if (FCKBrowserInfo.IsIE) this._FocusIE();else this.Window.focus();}else{var A=FCKTools.GetElementDocument(this.Textarea);if ((!A.hasFocus||A.hasFocus())&&A.activeElement==this.Textarea) return;this.Textarea.focus();}}catch(e) {}};FCKEditingArea.prototype._FocusIE=function(){this.Document.body.setActive();this.Window.focus();var A=this.Document.selection.createRange();var B=A.parentElement();var C=B.nodeName.toLowerCase();if (B.childNodes.length>0||!(FCKListsLib.BlockElements[C]||FCKListsLib.NonEmptyBlockElements[C])){return;};A=new FCKDomRange(this.Window);A.MoveToElementEditStart(B);A.Select();};function FCKEditingArea_Cleanup(){if (this.Document) this.Document.body.innerHTML="";this.TargetElement=null;this.IFrame=null;this.Document=null;this.Textarea=null;if (this.Window){this.Window._FCKEditingArea=null;this.Window=null;}}; +var FCKKeystrokeHandler=function(A){this.Keystrokes={};this.CancelCtrlDefaults=(A!==false);};FCKKeystrokeHandler.prototype.AttachToElement=function(A){FCKTools.AddEventListenerEx(A,'keydown',_FCKKeystrokeHandler_OnKeyDown,this);if (FCKBrowserInfo.IsGecko10||FCKBrowserInfo.IsOpera||(FCKBrowserInfo.IsGecko&&FCKBrowserInfo.IsMac)) FCKTools.AddEventListenerEx(A,'keypress',_FCKKeystrokeHandler_OnKeyPress,this);};FCKKeystrokeHandler.prototype.SetKeystrokes=function(){for (var i=0;i40))){B._CancelIt=true;if (A.preventDefault) return A.preventDefault();A.returnValue=false;A.cancelBubble=true;return false;};return true;};function _FCKKeystrokeHandler_OnKeyPress(A,B){if (B._CancelIt){if (A.preventDefault) return A.preventDefault();return false;};return true;}; +FCK.DTD=(function(){var X=FCKTools.Merge;var A,L,J,M,N,O,D,H,P,K,Q,F,G,C,B,E,I;A={isindex:1,fieldset:1};B={input:1,button:1,select:1,textarea:1,label:1};C=X({a:1},B);D=X({iframe:1},C);E={hr:1,ul:1,menu:1,div:1,blockquote:1,noscript:1,table:1,center:1,address:1,dir:1,pre:1,h5:1,dl:1,h4:1,noframes:1,h6:1,ol:1,h1:1,h3:1,h2:1};F={ins:1,del:1,script:1};G=X({b:1,acronym:1,bdo:1,'var':1,'#':1,abbr:1,code:1,br:1,i:1,cite:1,kbd:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,dfn:1,span:1},F);H=X({sub:1,img:1,object:1,sup:1,basefont:1,map:1,applet:1,font:1,big:1,small:1},G);I=X({p:1},H);J=X({iframe:1},H,B);K={img:1,noscript:1,br:1,kbd:1,center:1,button:1,basefont:1,h5:1,h4:1,samp:1,h6:1,ol:1,h1:1,h3:1,h2:1,form:1,font:1,'#':1,select:1,menu:1,ins:1,abbr:1,label:1,code:1,table:1,script:1,cite:1,input:1,iframe:1,strong:1,textarea:1,noframes:1,big:1,small:1,span:1,hr:1,sub:1,bdo:1,'var':1,div:1,object:1,sup:1,strike:1,dir:1,map:1,dl:1,applet:1,del:1,isindex:1,fieldset:1,ul:1,b:1,acronym:1,a:1,blockquote:1,i:1,u:1,s:1,tt:1,address:1,q:1,pre:1,p:1,em:1,dfn:1};L=X({a:1},J);M={tr:1};N={'#':1};O=X({param:1},K);P=X({form:1},A,D,E,I);Q={li:1};return {col:{},tr:{td:1,th:1},img:{},colgroup:{col:1},noscript:P,td:P,br:{},th:P,center:P,kbd:L,button:X(I,E),basefont:{},h5:L,h4:L,samp:L,h6:L,ol:Q,h1:L,h3:L,option:N,h2:L,form:X(A,D,E,I),select:{optgroup:1,option:1},font:J,ins:P,menu:Q,abbr:L,label:L,table:{thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1},code:L,script:N,tfoot:M,cite:L,li:P,input:{},iframe:P,strong:J,textarea:N,noframes:P,big:J,small:J,span:J,hr:{},dt:L,sub:J,optgroup:{option:1},param:{},bdo:L,'var':J,div:P,object:O,sup:J,dd:P,strike:J,area:{},dir:Q,map:X({area:1,form:1,p:1},A,F,E),applet:O,dl:{dt:1,dd:1},del:P,isindex:{},fieldset:X({legend:1},K),thead:M,ul:Q,acronym:L,b:J,a:J,blockquote:P,caption:L,i:J,u:J,tbody:M,s:L,address:X(D,I),tt:J,legend:L,q:L,pre:X(G,C),p:L,em:J,dfn:L};})(); +var FCKStyle=function(A){this.Element=(A.Element||'span').toLowerCase();this._StyleDesc=A;};FCKStyle.prototype={GetType:function(){var A=this.GetType_$;if (A!=undefined) return A;var B=this.Element;if (B=='#'||FCKListsLib.StyleBlockElements[B]) A=0;else if (FCKListsLib.StyleObjectElements[B]) A=2;else A=1;return (this.GetType_$=A);},ApplyToSelection:function(A){var B=new FCKDomRange(A);B.MoveToSelection();this.ApplyToRange(B,true);},ApplyToRange:function(A,B,C){switch (this.GetType()){case 0:this.ApplyToRange=this._ApplyBlockStyle;break;case 1:this.ApplyToRange=this._ApplyInlineStyle;break;default:return;};this.ApplyToRange(A,B,C);},ApplyToObject:function(A){if (!A) return;this.BuildElement(null,A);},RemoveFromSelection:function(A){var B=new FCKDomRange(A);B.MoveToSelection();this.RemoveFromRange(B,true);},RemoveFromRange:function(A,B,C){var D;var E=this._GetAttribsForComparison();var F=this._GetOverridesForComparison();if (A.CheckIsCollapsed()){var D=A.CreateBookmark(true);var H=A.GetBookmarkNode(D,true);var I=new FCKElementPath(H.parentNode);var J=[];var K=!FCKDomTools.GetNextSibling(H);var L=K||!FCKDomTools.GetPreviousSibling(H);var M;var N=-1;for (var i=0;i=0;i--){var E=D[i];for (var F in B){if (FCKDomTools.HasAttribute(E,F)){switch (F){case 'style':this._RemoveStylesFromElement(E);break;case 'class':if (FCKDomTools.GetAttributeValue(E,F)!=this.GetFinalAttributeValue(F)) continue;default:FCKDomTools.RemoveAttribute(E,F);}}};this._RemoveOverrides(E,C[this.Element]);this._RemoveNoAttribElement(E);};for (var G in C){if (G!=this.Element){D=A.getElementsByTagName(G);for (var i=D.length-1;i>=0;i--){var E=D[i];this._RemoveOverrides(E,C[G]);this._RemoveNoAttribElement(E);}}}},_RemoveStylesFromElement:function(A){var B=A.style.cssText;var C=this.GetFinalStyleValue();if (B.length>0&&C.length==0) return;C='(^|;)\\s*('+C.replace(/\s*([^ ]+):.*?(;|$)/g,'$1|').replace(/\|$/,'')+'):[^;]+';var D=new RegExp(C,'gi');B=B.replace(D,'').Trim();if (B.length==0||B==';') FCKDomTools.RemoveAttribute(A,'style');else A.style.cssText=B.replace(D,'');},_RemoveOverrides:function(A,B){var C=B&&B.Attributes;if (C){for (var i=0;i0) C.style.cssText=this.GetFinalStyleValue();return C;},_CompareAttributeValues:function(A,B,C){if (A=='style'&&B&&C){B=B.replace(/;$/,'').toLowerCase();C=C.replace(/;$/,'').toLowerCase();};return (B==C||((B===null||B==='')&&(C===null||C==='')))},GetFinalAttributeValue:function(A){var B=this._StyleDesc.Attributes;var B=B?B[A]:null;if (!B&&A=='style') return this.GetFinalStyleValue();if (B&&this._Variables) B=B.Replace(FCKRegexLib.StyleVariableAttName,this._GetVariableReplace,this);return B;},GetFinalStyleValue:function(){var A=this._GetStyleText();if (A.length>0&&this._Variables){A=A.Replace(FCKRegexLib.StyleVariableAttName,this._GetVariableReplace,this);A=FCKTools.NormalizeCssText(A);};return A;},_GetVariableReplace:function(){return this._Variables[arguments[2]]||arguments[0];},SetVariable:function(A,B){var C=this._Variables;if (!C) C=this._Variables={};this._Variables[A]=B;},_FromPre:function(A,B,C){var D=B.innerHTML;D=D.replace(/(\r\n|\r)/g,'\n');D=D.replace(/^[ \t]*\n/,'');D=D.replace(/\n$/,'');D=D.replace(/^[ \t]+|[ \t]+$/g,function(match,offset,s){if (match.length==1) return ' ';else if (offset==0) return new Array(match.length).join(' ')+' ';else return ' '+new Array(match.length).join(' ');});var E=new FCKHtmlIterator(D);var F=[];E.Each(function(isTag,value){if (!isTag){value=value.replace(/\n/g,'
      ');value=value.replace(/[ \t]{2,}/g,function (match){return new Array(match.length).join(' ')+' ';});};F.push(value);});C.innerHTML=F.join('');return C;},_ToPre:function(A,B,C){var D=B.innerHTML.Trim();D=D.replace(/[ \t\r\n]*(]*>)[ \t\r\n]*/gi,'
      ');var E=new FCKHtmlIterator(D);var F=[];E.Each(function(isTag,value){if (!isTag) value=value.replace(/([ \t\n\r]+| )/g,' ');else if (isTag&&value=='
      ') value='\n';F.push(value);});if (FCKBrowserInfo.IsIE){var G=A.createElement('div');G.appendChild(C);C.outerHTML='
      \n'+F.join('')+'
      ';C=G.removeChild(G.firstChild);}else C.innerHTML=F.join('');return C;},_ApplyBlockStyle:function(A,B,C){var D;if (B) D=A.CreateBookmark();var E=new FCKDomRangeIterator(A);E.EnforceRealBlocks=true;var F;var G=A.Window.document;var H=[];var I=[];while((F=E.GetNextParagraph())){var J=this.BuildElement(G);var K=J.nodeName.IEquals('pre');var L=F.nodeName.IEquals('pre');if (K&&!L){J=this._ToPre(G,F,J);H.push(J);}else if (!K&&L){J=this._FromPre(G,F,J);I.push(J);}else FCKDomTools.MoveChildren(F,J);F.parentNode.insertBefore(J,F);FCKDomTools.RemoveNode(F);};for (var i=0;i0){A.InsertNode(I);this.RemoveFromElement(I);this._MergeSiblings(I,this._GetAttribsForComparison());if (!FCKBrowserInfo.IsIE) I.normalize();};A.Release(true);}};this._FixBookmarkStart(K);if (B) A.SelectBookmark(J);if (C) A.MoveToBookmark(J);},_FixBookmarkStart:function(A){var B;while ((B=A.nextSibling)){if (B.nodeType==1&&FCKListsLib.InlineNonEmptyElements[B.nodeName.toLowerCase()]){if (!B.firstChild) FCKDomTools.RemoveNode(B);else FCKDomTools.MoveNode(A,B,true);continue;};if (B.nodeType==3&&B.length==0){FCKDomTools.RemoveNode(B);continue;};break;}},_MergeSiblings:function(A,B){if (!A||A.nodeType!=1||!FCKListsLib.InlineNonEmptyElements[A.nodeName.toLowerCase()]) return;this._MergeNextSibling(A,B);this._MergePreviousSibling(A,B);},_MergeNextSibling:function(A,B){var C=A.nextSibling;var D=(C&&C.nodeType==1&&C.getAttribute('_fck_bookmark'));if (D) C=C.nextSibling;if (C&&C.nodeType==1&&C.nodeName==A.nodeName){if (!B) B=this._CreateElementAttribsForComparison(A);if (this._CheckAttributesMatch(C,B)){var E=A.lastChild;if (D) FCKDomTools.MoveNode(A.nextSibling,A);FCKDomTools.MoveChildren(C,A);FCKDomTools.RemoveNode(C);if (E) this._MergeNextSibling(E);}}},_MergePreviousSibling:function(A,B){var C=A.previousSibling;var D=(C&&C.nodeType==1&&C.getAttribute('_fck_bookmark'));if (D) C=C.previousSibling;if (C&&C.nodeType==1&&C.nodeName==A.nodeName){if (!B) B=this._CreateElementAttribsForComparison(A);if (this._CheckAttributesMatch(C,B)){var E=A.firstChild;if (D) FCKDomTools.MoveNode(A.previousSibling,A,true);FCKDomTools.MoveChildren(C,A,true);FCKDomTools.RemoveNode(C);if (E) this._MergePreviousSibling(E);}}},_GetStyleText:function(){var A=this._StyleDesc.Styles;var B=(this._StyleDesc.Attributes?this._StyleDesc.Attributes['style']||'':'');if (B.length>0) B+=';';for (var C in A) B+=C+':'+A[C]+';';if (B.length>0&&!(/#\(/.test(B))){B=FCKTools.NormalizeCssText(B);};return (this._GetStyleText=function() { return B;})();},_GetAttribsForComparison:function(){var A=this._GetAttribsForComparison_$;if (A) return A;A={};var B=this._StyleDesc.Attributes;if (B){for (var C in B){A[C.toLowerCase()]=B[C].toLowerCase();}};if (this._GetStyleText().length>0){A['style']=this._GetStyleText().toLowerCase();};FCKTools.AppendLengthProperty(A,'_length');return (this._GetAttribsForComparison_$=A);},_GetOverridesForComparison:function(){var A=this._GetOverridesForComparison_$;if (A) return A;A={};var B=this._StyleDesc.Overrides;if (B){if (!FCKTools.IsArray(B)) B=[B];for (var i=0;i0) return true;};B=B.nextSibling;};return false;}}; +var FCKElementPath=function(A){var B=null;var C=null;var D=[];var e=A;while (e){if (e.nodeType==1){if (!this.LastElement) this.LastElement=e;var E=e.nodeName.toLowerCase();if (FCKBrowserInfo.IsIE&&e.scopeName!='HTML') E=e.scopeName.toLowerCase()+':'+E;if (!C){if (!B&&FCKListsLib.PathBlockElements[E]!=null) B=e;if (FCKListsLib.PathBlockLimitElements[E]!=null){if (!B&&E=='div'&&!FCKElementPath._CheckHasBlock(e)) B=e;else C=e;}};D.push(e);if (E=='body') break;};e=e.parentNode;};this.Block=B;this.BlockLimit=C;this.Elements=D;};FCKElementPath._CheckHasBlock=function(A){var B=A.childNodes;for (var i=0,count=B.length;i0){if (D.nodeType==3){var G=D.nodeValue.substr(0,E).Trim();if (G.length!=0) return A.IsStartOfBlock=false;}else F=D.childNodes[E-1];};if (!F) F=FCKDomTools.GetPreviousSourceNode(D,true,null,C);while (F){switch (F.nodeType){case 1:if (!FCKListsLib.InlineChildReqElements[F.nodeName.toLowerCase()]) return A.IsStartOfBlock=false;break;case 3:if (F.nodeValue.Trim().length>0) return A.IsStartOfBlock=false;};F=FCKDomTools.GetPreviousSourceNode(F,false,null,C);};return A.IsStartOfBlock=true;},CheckEndOfBlock:function(A){var B=this._Cache.IsEndOfBlock;if (B!=undefined) return B;var C=this.EndBlock||this.EndBlockLimit;var D=this._Range.endContainer;var E=this._Range.endOffset;var F;if (D.nodeType==3){var G=D.nodeValue;if (E0) return this._Cache.IsEndOfBlock=false;};F=FCKDomTools.GetNextSourceNode(F,false,null,C);};if (A) this.Select();return this._Cache.IsEndOfBlock=true;},CreateBookmark:function(A){var B={StartId:(new Date()).valueOf()+Math.floor(Math.random()*1000)+'S',EndId:(new Date()).valueOf()+Math.floor(Math.random()*1000)+'E'};var C=this.Window.document;var D;var E;var F;if (!this.CheckIsCollapsed()){E=C.createElement('span');E.style.display='none';E.id=B.EndId;E.setAttribute('_fck_bookmark',true);E.innerHTML=' ';F=this.Clone();F.Collapse(false);F.InsertNode(E);};D=C.createElement('span');D.style.display='none';D.id=B.StartId;D.setAttribute('_fck_bookmark',true);D.innerHTML=' ';F=this.Clone();F.Collapse(true);F.InsertNode(D);if (A){B.StartNode=D;B.EndNode=E;};if (E){this.SetStart(D,4);this.SetEnd(E,3);}else this.MoveToPosition(D,4);return B;},GetBookmarkNode:function(A,B){var C=this.Window.document;if (B) return A.StartNode||C.getElementById(A.StartId);else return A.EndNode||C.getElementById(A.EndId);},MoveToBookmark:function(A,B){var C=this.GetBookmarkNode(A,true);var D=this.GetBookmarkNode(A,false);this.SetStart(C,3);if (!B) FCKDomTools.RemoveNode(C);if (D){this.SetEnd(D,3);if (!B) FCKDomTools.RemoveNode(D);}else this.Collapse(true);this._UpdateElementInfo();},CreateBookmark2:function(){if (!this._Range) return { "Start":0,"End":0 };var A={"Start":[this._Range.startOffset],"End":[this._Range.endOffset]};var B=this._Range.startContainer.previousSibling;var C=this._Range.endContainer.previousSibling;var D=this._Range.startContainer;var E=this._Range.endContainer;while (B&&B.nodeType==3){A.Start[0]+=B.length;D=B;B=B.previousSibling;};while (C&&C.nodeType==3){A.End[0]+=C.length;E=C;C=C.previousSibling;};if (D.nodeType==1&&D.childNodes[A.Start[0]]&&D.childNodes[A.Start[0]].nodeType==3){var F=D.childNodes[A.Start[0]];var G=0;while (F.previousSibling&&F.previousSibling.nodeType==3){F=F.previousSibling;G+=F.length;};D=F;A.Start[0]=G;};if (E.nodeType==1&&E.childNodes[A.End[0]]&&E.childNodes[A.End[0]].nodeType==3){var F=E.childNodes[A.End[0]];var G=0;while (F.previousSibling&&F.previousSibling.nodeType==3){F=F.previousSibling;G+=F.length;};E=F;A.End[0]=G;};A.Start=FCKDomTools.GetNodeAddress(D,true).concat(A.Start);A.End=FCKDomTools.GetNodeAddress(E,true).concat(A.End);return A;},MoveToBookmark2:function(A){var B=FCKDomTools.GetNodeFromAddress(this.Window.document,A.Start.slice(0,-1),true);var C=FCKDomTools.GetNodeFromAddress(this.Window.document,A.End.slice(0,-1),true);this.Release(true);this._Range=new FCKW3CRange(this.Window.document);var D=A.Start[A.Start.length-1];var E=A.End[A.End.length-1];while (B.nodeType==3&&D>B.length){if (!B.nextSibling||B.nextSibling.nodeType!=3) break;D-=B.length;B=B.nextSibling;};while (C.nodeType==3&&E>C.length){if (!C.nextSibling||C.nextSibling.nodeType!=3) break;E-=C.length;C=C.nextSibling;};this._Range.setStart(B,D);this._Range.setEnd(C,E);this._UpdateElementInfo();},MoveToPosition:function(A,B){this.SetStart(A,B);this.Collapse(true);},SetStart:function(A,B,C){var D=this._Range;if (!D) D=this._Range=this.CreateRange();switch(B){case 1:D.setStart(A,0);break;case 2:D.setStart(A,A.childNodes.length);break;case 3:D.setStartBefore(A);break;case 4:D.setStartAfter(A);};if (!C) this._UpdateElementInfo();},SetEnd:function(A,B,C){var D=this._Range;if (!D) D=this._Range=this.CreateRange();switch(B){case 1:D.setEnd(A,0);break;case 2:D.setEnd(A,A.childNodes.length);break;case 3:D.setEndBefore(A);break;case 4:D.setEndAfter(A);};if (!C) this._UpdateElementInfo();},Expand:function(A){var B,oSibling;switch (A){case 'inline_elements':if (this._Range.startOffset==0){B=this._Range.startContainer;if (B.nodeType!=1) B=B.previousSibling?null:B.parentNode;if (B){while (FCKListsLib.InlineNonEmptyElements[B.nodeName.toLowerCase()]){this._Range.setStartBefore(B);if (B!=B.parentNode.firstChild) break;B=B.parentNode;}}};B=this._Range.endContainer;var C=this._Range.endOffset;if ((B.nodeType==3&&C>=B.nodeValue.length)||(B.nodeType==1&&C>=B.childNodes.length)||(B.nodeType!=1&&B.nodeType!=3)){if (B.nodeType!=1) B=B.nextSibling?null:B.parentNode;if (B){while (FCKListsLib.InlineNonEmptyElements[B.nodeName.toLowerCase()]){this._Range.setEndAfter(B);if (B!=B.parentNode.lastChild) break;B=B.parentNode;}}};break;case 'block_contents':case 'list_contents':var D=FCKListsLib.BlockBoundaries;if (A=='list_contents'||FCKConfig.EnterMode=='br') D=FCKListsLib.ListBoundaries;if (this.StartBlock&&FCKConfig.EnterMode!='br'&&A=='block_contents') this.SetStart(this.StartBlock,1);else{B=this._Range.startContainer;if (B.nodeType==1){var E=B.childNodes[this._Range.startOffset];if (E) B=FCKDomTools.GetPreviousSourceNode(E,true);else B=B.lastChild||B;};while (B&&(B.nodeType!=1||(B!=this.StartBlockLimit&&!D[B.nodeName.toLowerCase()]))){this._Range.setStartBefore(B);B=B.previousSibling||B.parentNode;}};if (this.EndBlock&&FCKConfig.EnterMode!='br'&&A=='block_contents'&&this.EndBlock.nodeName.toLowerCase()!='li') this.SetEnd(this.EndBlock,2);else{B=this._Range.endContainer;if (B.nodeType==1) B=B.childNodes[this._Range.endOffset]||B.lastChild;while (B&&(B.nodeType!=1||(B!=this.StartBlockLimit&&!D[B.nodeName.toLowerCase()]))){this._Range.setEndAfter(B);B=B.nextSibling||B.parentNode;};if (B&&B.nodeName.toLowerCase()=='br') this._Range.setEndAfter(B);};this._UpdateElementInfo();}},SplitBlock:function(A){var B=A||FCKConfig.EnterMode;if (!this._Range) this.MoveToSelection();if (this.StartBlockLimit==this.EndBlockLimit){var C=this.StartBlock;var D=this.EndBlock;var E=null;if (B!='br'){if (!C){C=this.FixBlock(true,B);D=this.EndBlock;};if (!D) D=this.FixBlock(false,B);};var F=(C!=null&&this.CheckStartOfBlock());var G=(D!=null&&this.CheckEndOfBlock());if (!this.CheckIsEmpty()) this.DeleteContents();if (C&&D&&C==D){if (G){E=new FCKElementPath(this.StartContainer);this.MoveToPosition(D,4);D=null;}else if (F){E=new FCKElementPath(this.StartContainer);this.MoveToPosition(C,3);C=null;}else{this.SetEnd(C,2);var H=this.ExtractContents();D=C.cloneNode(false);D.removeAttribute('id',false);H.AppendTo(D);FCKDomTools.InsertAfterNode(C,D);this.MoveToPosition(C,4);if (FCKBrowserInfo.IsGecko&&!C.nodeName.IEquals(['ul','ol'])) FCKTools.AppendBogusBr(C);}};return {PreviousBlock:C,NextBlock:D,WasStartOfBlock:F,WasEndOfBlock:G,ElementPath:E};};return null;},FixBlock:function(A,B){var C=this.CreateBookmark();this.Collapse(A);this.Expand('block_contents');var D=this.Window.document.createElement(B);this.ExtractContents().AppendTo(D);FCKDomTools.TrimNode(D);this.InsertNode(D);this.MoveToBookmark(C);return D;},Release:function(A){if (!A) this.Window=null;this.StartNode=null;this.StartContainer=null;this.StartBlock=null;this.StartBlockLimit=null;this.EndNode=null;this.EndContainer=null;this.EndBlock=null;this.EndBlockLimit=null;this._Range=null;this._Cache=null;},CheckHasRange:function(){return!!this._Range;},GetTouchedStartNode:function(){var A=this._Range;var B=A.startContainer;if (A.collapsed||B.nodeType!=1) return B;return B.childNodes[A.startOffset]||B;},GetTouchedEndNode:function(){var A=this._Range;var B=A.endContainer;if (A.collapsed||B.nodeType!=1) return B;return B.childNodes[A.endOffset-1]||B;}}; +FCKDomRange.prototype.MoveToSelection=function(){this.Release(true);var A=this.Window.getSelection();if (A&&A.rangeCount>0){this._Range=FCKW3CRange.CreateFromRange(this.Window.document,A.getRangeAt(0));this._UpdateElementInfo();}else if (this.Window.document) this.MoveToElementStart(this.Window.document.body);};FCKDomRange.prototype.Select=function(){var A=this._Range;if (A){var B=A.startContainer;if (A.collapsed&&B.nodeType==1&&B.childNodes.length==0) B.appendChild(A._Document.createTextNode(''));var C=this.Window.document.createRange();C.setStart(B,A.startOffset);try{C.setEnd(A.endContainer,A.endOffset);}catch (e){if (e.toString().Contains('NS_ERROR_ILLEGAL_VALUE')){A.collapse(true);C.setEnd(A.endContainer,A.endOffset);}else throw(e);};var D=this.Window.getSelection();D.removeAllRanges();D.addRange(C);}};FCKDomRange.prototype.SelectBookmark=function(A){var B=this.Window.document.createRange();var C=this.GetBookmarkNode(A,true);var D=this.GetBookmarkNode(A,false);B.setStart(C.parentNode,FCKDomTools.GetIndexOf(C));FCKDomTools.RemoveNode(C);if (D){B.setEnd(D.parentNode,FCKDomTools.GetIndexOf(D));FCKDomTools.RemoveNode(D);};var E=this.Window.getSelection();E.removeAllRanges();E.addRange(B);}; +var FCKDomRangeIterator=function(A){this.Range=A;this.ForceBrBreak=false;this.EnforceRealBlocks=false;};FCKDomRangeIterator.CreateFromSelection=function(A){var B=new FCKDomRange(A);B.MoveToSelection();return new FCKDomRangeIterator(B);};FCKDomRangeIterator.prototype={GetNextParagraph:function(){var A;var B;var C;var D;var E;var F=this.ForceBrBreak?FCKListsLib.ListBoundaries:FCKListsLib.BlockBoundaries;if (!this._LastNode){var B=this.Range.Clone();B.Expand(this.ForceBrBreak?'list_contents':'block_contents');this._NextNode=B.GetTouchedStartNode();this._LastNode=B.GetTouchedEndNode();B=null;};var H=this._NextNode;var I=this._LastNode;this._NextNode=null;while (H){var J=false;var K=(H.nodeType!=1);var L=false;if (!K){var M=H.nodeName.toLowerCase();if (F[M]&&(!FCKBrowserInfo.IsIE||H.scopeName=='HTML')){if (M=='br') K=true;else if (!B&&H.childNodes.length==0&&M!='hr'){A=H;C=H==I;break;};if (B){B.SetEnd(H,3,true);if (M!='br') this._NextNode=H;};J=true;}else{if (H.firstChild){if (!B){B=new FCKDomRange(this.Range.Window);B.SetStart(H,3,true);};H=H.firstChild;continue;};K=true;}}else if (H.nodeType==3){if (/^[\r\n\t ]+$/.test(H.nodeValue)) K=false;};if (K&&!B){B=new FCKDomRange(this.Range.Window);B.SetStart(H,3,true);};C=((!J||K)&&H==I);if (B&&!J){while (!H.nextSibling&&!C){var N=H.parentNode;if (F[N.nodeName.toLowerCase()]){J=true;C=C||(N==I);break;};H=N;K=true;C=(H==I);L=true;}};if (K) B.SetEnd(H,4,true);if ((J||C)&&B){B._UpdateElementInfo();if (B.StartNode==B.EndNode&&B.StartNode.parentNode==B.StartBlockLimit&&B.StartNode.getAttribute&&B.StartNode.getAttribute('_fck_bookmark')) B=null;else break;};if (C) break;H=FCKDomTools.GetNextSourceNode(H,L,null,I);};if (!A){if (!B){this._NextNode=null;return null;};A=B.StartBlock;if (!A&&!this.EnforceRealBlocks&&B.StartBlockLimit.nodeName.IEquals('DIV','TH','TD')&&B.CheckStartOfBlock()&&B.CheckEndOfBlock()){A=B.StartBlockLimit;}else if (!A||(this.EnforceRealBlocks&&A.nodeName.toLowerCase()=='li')){A=this.Range.Window.document.createElement(FCKConfig.EnterMode=='p'?'p':'div');B.ExtractContents().AppendTo(A);FCKDomTools.TrimNode(A);B.InsertNode(A);D=true;E=true;}else if (A.nodeName.toLowerCase()!='li'){if (!B.CheckStartOfBlock()||!B.CheckEndOfBlock()){A=A.cloneNode(false);B.ExtractContents().AppendTo(A);FCKDomTools.TrimNode(A);var O=B.SplitBlock();D=!O.WasStartOfBlock;E=!O.WasEndOfBlock;B.InsertNode(A);}}else if (!C){this._NextNode=A==I?null:FCKDomTools.GetNextSourceNode(B.EndNode,true,null,I);return A;}};if (D){var P=A.previousSibling;if (P&&P.nodeType==1){if (P.nodeName.toLowerCase()=='br') P.parentNode.removeChild(P);else if (P.lastChild&&P.lastChild.nodeName.IEquals('br')) P.removeChild(P.lastChild);}};if (E){var Q=A.lastChild;if (Q&&Q.nodeType==1&&Q.nodeName.toLowerCase()=='br') A.removeChild(Q);};if (!this._NextNode) this._NextNode=(C||A==I)?null:FCKDomTools.GetNextSourceNode(A,true,null,I);return A;}}; +var FCKDocumentFragment=function(A,B){this.RootNode=B||A.createDocumentFragment();};FCKDocumentFragment.prototype={AppendTo:function(A){A.appendChild(this.RootNode);},InsertAfterNode:function(A){FCKDomTools.InsertAfterNode(A,this.RootNode);}}; +var FCKW3CRange=function(A){this._Document=A;this.startContainer=null;this.startOffset=null;this.endContainer=null;this.endOffset=null;this.collapsed=true;};FCKW3CRange.CreateRange=function(A){return new FCKW3CRange(A);};FCKW3CRange.CreateFromRange=function(A,B){var C=FCKW3CRange.CreateRange(A);C.setStart(B.startContainer,B.startOffset);C.setEnd(B.endContainer,B.endOffset);return C;};FCKW3CRange.prototype={_UpdateCollapsed:function(){this.collapsed=(this.startContainer==this.endContainer&&this.startOffset==this.endOffset);},setStart:function(A,B){this.startContainer=A;this.startOffset=B;if (!this.endContainer){this.endContainer=A;this.endOffset=B;};this._UpdateCollapsed();},setEnd:function(A,B){this.endContainer=A;this.endOffset=B;if (!this.startContainer){this.startContainer=A;this.startOffset=B;};this._UpdateCollapsed();},setStartAfter:function(A){this.setStart(A.parentNode,FCKDomTools.GetIndexOf(A)+1);},setStartBefore:function(A){this.setStart(A.parentNode,FCKDomTools.GetIndexOf(A));},setEndAfter:function(A){this.setEnd(A.parentNode,FCKDomTools.GetIndexOf(A)+1);},setEndBefore:function(A){this.setEnd(A.parentNode,FCKDomTools.GetIndexOf(A));},collapse:function(A){if (A){this.endContainer=this.startContainer;this.endOffset=this.startOffset;}else{this.startContainer=this.endContainer;this.startOffset=this.endOffset;};this.collapsed=true;},selectNodeContents:function(A){this.setStart(A,0);this.setEnd(A,A.nodeType==3?A.data.length:A.childNodes.length);},insertNode:function(A){var B=this.startContainer;var C=this.startOffset;if (B.nodeType==3){B.splitText(C);if (B==this.endContainer) this.setEnd(B.nextSibling,this.endOffset-this.startOffset);FCKDomTools.InsertAfterNode(B,A);return;}else{B.insertBefore(A,B.childNodes[C]||null);if (B==this.endContainer){this.endOffset++;this.collapsed=false;}}},deleteContents:function(){if (this.collapsed) return;this._ExecContentsAction(0);},extractContents:function(){var A=new FCKDocumentFragment(this._Document);if (!this.collapsed) this._ExecContentsAction(1,A);return A;},cloneContents:function(){var A=new FCKDocumentFragment(this._Document);if (!this.collapsed) this._ExecContentsAction(2,A);return A;},_ExecContentsAction:function(A,B){var C=this.startContainer;var D=this.endContainer;var E=this.startOffset;var F=this.endOffset;var G=false;var H=false;if (D.nodeType==3) D=D.splitText(F);else{if (D.childNodes.length>0){if (F>D.childNodes.length-1){D=FCKDomTools.InsertAfterNode(D.lastChild,this._Document.createTextNode(''));H=true;}else D=D.childNodes[F];}};if (C.nodeType==3){C.splitText(E);if (C==D) D=C.nextSibling;}else{if (E==0){C=C.insertBefore(this._Document.createTextNode(''),C.firstChild);G=true;}else if (E>C.childNodes.length-1){C=C.appendChild(this._Document.createTextNode(''));G=true;}else C=C.childNodes[E].previousSibling;};var I=FCKDomTools.GetParents(C);var J=FCKDomTools.GetParents(D);var i,topStart,topEnd;for (i=0;i0&&levelStartNode!=D) levelClone=K.appendChild(levelStartNode.cloneNode(levelStartNode==D));if (!I[k]||levelStartNode.parentNode!=I[k].parentNode){currentNode=levelStartNode.previousSibling;while(currentNode){if (currentNode==I[k]||currentNode==C) break;currentSibling=currentNode.previousSibling;if (A==2) K.insertBefore(currentNode.cloneNode(true),K.firstChild);else{currentNode.parentNode.removeChild(currentNode);if (A==1) K.insertBefore(currentNode,K.firstChild);};currentNode=currentSibling;}};if (K) K=levelClone;};if (A==2){var L=this.startContainer;if (L.nodeType==3){L.data+=L.nextSibling.data;L.parentNode.removeChild(L.nextSibling);};var M=this.endContainer;if (M.nodeType==3&&M.nextSibling){M.data+=M.nextSibling.data;M.parentNode.removeChild(M.nextSibling);}}else{if (topStart&&topEnd&&(C.parentNode!=topStart.parentNode||D.parentNode!=topEnd.parentNode)){var N=FCKDomTools.GetIndexOf(topEnd);if (G&&topEnd.parentNode==C.parentNode) N--;this.setStart(topEnd.parentNode,N);};this.collapse(true);};if(G) C.parentNode.removeChild(C);if(H&&D.parentNode) D.parentNode.removeChild(D);},cloneRange:function(){return FCKW3CRange.CreateFromRange(this._Document,this);}}; +var FCKEnterKey=function(A,B,C,D){this.Window=A;this.EnterMode=B||'p';this.ShiftEnterMode=C||'br';var E=new FCKKeystrokeHandler(false);E._EnterKey=this;E.OnKeystroke=FCKEnterKey_OnKeystroke;E.SetKeystrokes([[13,'Enter'],[SHIFT+13,'ShiftEnter'],[9,'Tab'],[8,'Backspace'],[CTRL+8,'CtrlBackspace'],[46,'Delete']]);if (D>0){this.TabText='';while (D-->0) this.TabText+='\xa0';};E.AttachToElement(A.document);};function FCKEnterKey_OnKeystroke(A,B){var C=this._EnterKey;try{switch (B){case 'Enter':return C.DoEnter();break;case 'ShiftEnter':return C.DoShiftEnter();break;case 'Backspace':return C.DoBackspace();break;case 'Delete':return C.DoDelete();break;case 'Tab':return C.DoTab();break;case 'CtrlBackspace':return C.DoCtrlBackspace();break;}}catch (e){};return false;};FCKEnterKey.prototype.DoEnter=function(A,B){FCKUndo.SaveUndoStep();this._HasShift=(B===true);var C=FCKSelection.GetParentElement();var D=new FCKElementPath(C);var E=A||this.EnterMode;if (E=='br'||D.Block&&D.Block.tagName.toLowerCase()=='pre') return this._ExecuteEnterBr();else return this._ExecuteEnterBlock(E);};FCKEnterKey.prototype.DoShiftEnter=function(){return this.DoEnter(this.ShiftEnterMode,true);};FCKEnterKey.prototype.DoBackspace=function(){var A=false;var B=new FCKDomRange(this.Window);B.MoveToSelection();if (FCKBrowserInfo.IsIE&&this._CheckIsAllContentsIncluded(B,this.Window.document.body)){this._FixIESelectAllBug(B);return true;};var C=B.CheckIsCollapsed();if (!C){if (FCKBrowserInfo.IsIE&&this.Window.document.selection.type.toLowerCase()=="control"){var D=this.Window.document.selection.createRange();for (var i=D.length-1;i>=0;i--){var E=D.item(i);E.parentNode.removeChild(E);};return true;};return false;};var F=B.StartBlock;var G=B.EndBlock;if (B.StartBlockLimit==B.EndBlockLimit&&F&&G){if (!C){var H=B.CheckEndOfBlock();B.DeleteContents();if (F!=G){B.SetStart(G,1);B.SetEnd(G,1);};B.Select();A=(F==G);};if (B.CheckStartOfBlock()){var I=B.StartBlock;var J=FCKDomTools.GetPreviousSourceElement(I,true,['BODY',B.StartBlockLimit.nodeName],['UL','OL']);A=this._ExecuteBackspace(B,J,I);}else if (FCKBrowserInfo.IsGeckoLike){B.Select();}};B.Release();return A;};FCKEnterKey.prototype.DoCtrlBackspace=function(){FCKUndo.SaveUndoStep();var A=new FCKDomRange(this.Window);A.MoveToSelection();if (FCKBrowserInfo.IsIE&&this._CheckIsAllContentsIncluded(A,this.Window.document.body)){this._FixIESelectAllBug(A);return true;};return false;};FCKEnterKey.prototype._ExecuteBackspace=function(A,B,C){var D=false;if (!B&&C&&C.nodeName.IEquals('LI')&&C.parentNode.parentNode.nodeName.IEquals('LI')){this._OutdentWithSelection(C,A);return true;};if (B&&B.nodeName.IEquals('LI')){var E=FCKDomTools.GetLastChild(B,['UL','OL']);while (E){B=FCKDomTools.GetLastChild(E,'LI');E=FCKDomTools.GetLastChild(B,['UL','OL']);}};if (B&&C){if (C.nodeName.IEquals('LI')&&!B.nodeName.IEquals('LI')){this._OutdentWithSelection(C,A);return true;};var F=C.parentNode;var G=B.nodeName.toLowerCase();if (FCKListsLib.EmptyElements[G]!=null||G=='table'){FCKDomTools.RemoveNode(B);D=true;}else{FCKDomTools.RemoveNode(C);while (F.innerHTML.Trim().length==0){var H=F.parentNode;H.removeChild(F);F=H;};FCKDomTools.LTrimNode(C);FCKDomTools.RTrimNode(B);A.SetStart(B,2,true);A.Collapse(true);var I=A.CreateBookmark(true);if (!C.tagName.IEquals(['TABLE'])) FCKDomTools.MoveChildren(C,B);A.SelectBookmark(I);D=true;}};return D;};FCKEnterKey.prototype.DoDelete=function(){FCKUndo.SaveUndoStep();var A=false;var B=new FCKDomRange(this.Window);B.MoveToSelection();if (FCKBrowserInfo.IsIE&&this._CheckIsAllContentsIncluded(B,this.Window.document.body)){this._FixIESelectAllBug(B);return true;};if (B.CheckIsCollapsed()&&B.CheckEndOfBlock(FCKBrowserInfo.IsGeckoLike)){var C=B.StartBlock;var D=FCKTools.GetElementAscensor(C,'td');var E=FCKDomTools.GetNextSourceElement(C,true,[B.StartBlockLimit.nodeName],['UL','OL','TR'],true);if (D){var F=FCKTools.GetElementAscensor(E,'td');if (F!=D) return true;};A=this._ExecuteBackspace(B,C,E);};B.Release();return A;};FCKEnterKey.prototype.DoTab=function(){var A=new FCKDomRange(this.Window);A.MoveToSelection();var B=A._Range.startContainer;while (B){if (B.nodeType==1){var C=B.tagName.toLowerCase();if (C=="tr"||C=="td"||C=="th"||C=="tbody"||C=="table") return false;else break;};B=B.parentNode;};if (this.TabText){A.DeleteContents();A.InsertNode(this.Window.document.createTextNode(this.TabText));A.Collapse(false);A.Select();};return true;};FCKEnterKey.prototype._ExecuteEnterBlock=function(A,B){var C=B||new FCKDomRange(this.Window);var D=C.SplitBlock(A);if (D){var E=D.PreviousBlock;var F=D.NextBlock;var G=D.WasStartOfBlock;var H=D.WasEndOfBlock;if (F){if (F.parentNode.nodeName.IEquals('li')){FCKDomTools.BreakParent(F,F.parentNode);FCKDomTools.MoveNode(F,F.nextSibling,true);}}else if (E&&E.parentNode.nodeName.IEquals('li')){FCKDomTools.BreakParent(E,E.parentNode);C.MoveToElementEditStart(E.nextSibling);FCKDomTools.MoveNode(E,E.previousSibling);};if (!G&&!H){if (F.nodeName.IEquals('li')&&F.firstChild&&F.firstChild.nodeName.IEquals(['ul','ol'])) F.insertBefore(FCKTools.GetElementDocument(F).createTextNode('\xa0'),F.firstChild);if (F) C.MoveToElementEditStart(F);}else{if (G&&H&&E.tagName.toUpperCase()=='LI'){C.MoveToElementStart(E);this._OutdentWithSelection(E,C);C.Release();return true;};var I;if (E){var J=E.tagName.toUpperCase();if (!this._HasShift&&!(/^H[1-6]$/).test(J)){I=FCKDomTools.CloneElement(E);}}else if (F) I=FCKDomTools.CloneElement(F);if (!I) I=this.Window.document.createElement(A);var K=D.ElementPath;if (K){for (var i=0,len=K.Elements.length;i=0&&(C=B[i--])){if (C.name.length>0){if (C.innerHTML!==''){if (FCKBrowserInfo.IsIE) C.className+=' FCK__AnchorC';}else{var D=FCKDocumentProcessor_CreateFakeImage('FCK__Anchor',C.cloneNode(true));D.setAttribute('_fckanchor','true',0);C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}}}};var FCKPageBreaksProcessor=FCKDocumentProcessor.AppendNew();FCKPageBreaksProcessor.ProcessDocument=function(A){var B=A.getElementsByTagName('DIV');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){if (C.style.pageBreakAfter=='always'&&C.childNodes.length==1&&C.childNodes[0].style&&C.childNodes[0].style.display=='none'){var D=FCKDocumentProcessor_CreateFakeImage('FCK__PageBreak',C.cloneNode(true));C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}};FCKEmbedAndObjectProcessor=(function(){var A=[];var B=function(el){var C=el.cloneNode(true);var D;var E=D=FCKDocumentProcessor_CreateFakeImage('FCK__UnknownObject',C);FCKEmbedAndObjectProcessor.RefreshView(E,el);for (var i=0;i=0;i--) B(F[i]);var G=doc.getElementsByTagName('embed');for (var i=G.length-1;i>=0;i--) B(G[i]);});},RefreshView:function(placeHolder,original){if (original.getAttribute('width')>0) placeHolder.style.width=FCKTools.ConvertHtmlSizeToStyle(original.getAttribute('width'));if (original.getAttribute('height')>0) placeHolder.style.height=FCKTools.ConvertHtmlSizeToStyle(original.getAttribute('height'));},AddCustomHandler:function(func){A.push(func);}});})();FCK.GetRealElement=function(A){var e=FCKTempBin.Elements[A.getAttribute('_fckrealelement')];if (A.getAttribute('_fckflash')){if (A.style.width.length>0) e.width=FCKTools.ConvertStyleSizeToHtml(A.style.width);if (A.style.height.length>0) e.height=FCKTools.ConvertStyleSizeToHtml(A.style.height);};return e;};if (FCKBrowserInfo.IsIE){FCKDocumentProcessor.AppendNew().ProcessDocument=function(A){var B=A.getElementsByTagName('HR');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){var D=A.createElement('hr');D.mergeAttributes(C,true);FCKDomTools.InsertAfterNode(C,D);C.parentNode.removeChild(C);}}};FCKDocumentProcessor.AppendNew().ProcessDocument=function(A){var B=A.getElementsByTagName('INPUT');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){if (C.type=='hidden'){var D=FCKDocumentProcessor_CreateFakeImage('FCK__InputHidden',C.cloneNode(true));D.setAttribute('_fckinputhidden','true',0);C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}};FCKEmbedAndObjectProcessor.AddCustomHandler(function(A,B){if (!(A.nodeName.IEquals('embed')&&(A.type=='application/x-shockwave-flash'||/\.swf($|#|\?)/i.test(A.src)))) return;B.className='FCK__Flash';B.setAttribute('_fckflash','true',0);}); +var FCKSelection=FCK.Selection={GetParentBlock:function(){var A=this.GetParentElement();while (A){if (FCKListsLib.BlockBoundaries[A.nodeName.toLowerCase()]) break;A=A.parentNode;};return A;},ApplyStyle:function(A){FCKStyles.ApplyStyle(new FCKStyle(A));}}; +FCKSelection.GetType=function(){var A='Text';var B;try { B=this.GetSelection();} catch (e) {};if (B&&B.rangeCount==1){var C=B.getRangeAt(0);if (C.startContainer==C.endContainer&&(C.endOffset-C.startOffset)==1&&C.startContainer.nodeType==1&&FCKListsLib.StyleObjectElements[C.startContainer.childNodes[C.startOffset].nodeName.toLowerCase()]){A='Control';}};return A;};FCKSelection.GetSelectedElement=function(){var A=!!FCK.EditorWindow&&this.GetSelection();if (!A||A.rangeCount<1) return null;var B=A.getRangeAt(0);if (B.startContainer!=B.endContainer||B.startContainer.nodeType!=1||B.startOffset!=B.endOffset-1) return null;var C=B.startContainer.childNodes[B.startOffset];if (C.nodeType!=1) return null;return C;};FCKSelection.GetParentElement=function(){if (this.GetType()=='Control') return FCKSelection.GetSelectedElement().parentNode;else{var A=this.GetSelection();if (A){if (A.anchorNode&&A.anchorNode==A.focusNode) return A.anchorNode.parentNode;var B=new FCKElementPath(A.anchorNode);var C=new FCKElementPath(A.focusNode);var D=null;var E=null;if (B.Elements.length>C.Elements.length){D=B.Elements;E=C.Elements;}else{D=C.Elements;E=B.Elements;};var F=D.length-E.length;for(var i=0;i0){var C=B.getRangeAt(A?0:(B.rangeCount-1));var D=A?C.startContainer:C.endContainer;return (D.nodeType==1?D:D.parentNode);}};return null;};FCKSelection.SelectNode=function(A){var B=FCK.EditorDocument.createRange();B.selectNode(A);var C=this.GetSelection();C.removeAllRanges();C.addRange(B);};FCKSelection.Collapse=function(A){var B=this.GetSelection();if (A==null||A===true) B.collapseToStart();else B.collapseToEnd();};FCKSelection.HasAncestorNode=function(A){var B=this.GetSelectedElement();if (!B&&FCK.EditorWindow){try { B=this.GetSelection().getRangeAt(0).startContainer;}catch(e){}};while (B){if (B.nodeType==1&&B.tagName==A) return true;B=B.parentNode;};return false;};FCKSelection.MoveToAncestorNode=function(A){var B;var C=this.GetSelectedElement();if (!C) C=this.GetSelection().getRangeAt(0).startContainer;while (C){if (C.nodeName==A) return C;C=C.parentNode;};return null;};FCKSelection.Delete=function(){var A=this.GetSelection();for (var i=0;i=0;i--){if (C[i]) FCKTableHandler.DeleteRows(C[i]);};return;};var E=FCKTools.GetElementAscensor(A,'TABLE');if (E.rows.length==1){FCKTableHandler.DeleteTable(E);return;};A.parentNode.removeChild(A);};FCKTableHandler.DeleteTable=function(A){if (!A){A=FCKSelection.GetSelectedElement();if (!A||A.tagName!='TABLE') A=FCKSelection.MoveToAncestorNode('TABLE');};if (!A) return;FCKSelection.SelectNode(A);FCKSelection.Collapse();if (A.parentNode.childNodes.length==1) A.parentNode.parentNode.removeChild(A.parentNode);else A.parentNode.removeChild(A);};FCKTableHandler.InsertColumn=function(A){var B=null;var C=this.GetSelectedCells();if (C&&C.length) B=C[A?0:(C.length-1)];if (!B) return;var D=FCKTools.GetElementAscensor(B,'TABLE');var E=B.cellIndex;for (var i=0;i=0;i--){if (B[i]) FCKTableHandler.DeleteColumns(B[i]);};return;};if (!A) return;var C=FCKTools.GetElementAscensor(A,'TABLE');var D=A.cellIndex;for (var i=C.rows.length-1;i>=0;i--){var E=C.rows[i];if (D==0&&E.cells.length==1){FCKTableHandler.DeleteRows(E);continue;};if (E.cells[D]) E.removeChild(E.cells[D]);}};FCKTableHandler.InsertCell=function(A,B){var C=null;var D=this.GetSelectedCells();if (D&&D.length) C=D[B?0:(D.length-1)];if (!C) return null;var E=FCK.EditorDocument.createElement('TD');if (FCKBrowserInfo.IsGeckoLike) FCKTools.AppendBogusBr(E);if (!B&&C.cellIndex==C.parentNode.cells.length-1) C.parentNode.appendChild(E);else C.parentNode.insertBefore(E,B?C:C.nextSibling);return E;};FCKTableHandler.DeleteCell=function(A){if (A.parentNode.cells.length==1){FCKTableHandler.DeleteRows(FCKTools.GetElementAscensor(A,'TR'));return;};A.parentNode.removeChild(A);};FCKTableHandler.DeleteCells=function(){var A=FCKTableHandler.GetSelectedCells();for (var i=A.length-1;i>=0;i--){FCKTableHandler.DeleteCell(A[i]);}};FCKTableHandler._MarkCells=function(A,B){for (var i=0;i=E.height){for (D=F;D0){var L=K.removeChild(K.firstChild);if (L.nodeType!=1||(L.getAttribute('type',2)!='_moz'&&L.getAttribute('_moz_dirty')!=null)){I.appendChild(L);J++;}}};if (J>0) I.appendChild(FCKTools.GetElementDocument(B).createElement('br'));};this._ReplaceCellsByMarker(C,'_SelectedCells',B);this._UnmarkCells(A,'_SelectedCells');this._InstallTableMap(C,B.parentNode.parentNode);B.appendChild(I);if (FCKBrowserInfo.IsGeckoLike&&(!B.firstChild)) FCKTools.AppendBogusBr(B);this._MoveCaretToCell(B,false);};FCKTableHandler.MergeRight=function(){var A=this.GetMergeRightTarget();if (A==null) return;var B=A.refCell;var C=A.tableMap;var D=A.nextCell;var E=FCK.EditorDocument.createDocumentFragment();while (D&&D.childNodes&&D.childNodes.length>0) E.appendChild(D.removeChild(D.firstChild));D.parentNode.removeChild(D);B.appendChild(E);this._MarkCells([D],'_Replace');this._ReplaceCellsByMarker(C,'_Replace',B);this._InstallTableMap(C,B.parentNode.parentNode);this._MoveCaretToCell(B,false);};FCKTableHandler.MergeDown=function(){var A=this.GetMergeDownTarget();if (A==null) return;var B=A.refCell;var C=A.tableMap;var D=A.nextCell;var E=FCKTools.GetElementDocument(B).createDocumentFragment();while (D&&D.childNodes&&D.childNodes.length>0) E.appendChild(D.removeChild(D.firstChild));if (E.firstChild) E.insertBefore(FCKTools.GetElementDocument(D).createElement('br'),E.firstChild);B.appendChild(E);this._MarkCells([D],'_Replace');this._ReplaceCellsByMarker(C,'_Replace',B);this._InstallTableMap(C,B.parentNode.parentNode);this._MoveCaretToCell(B,false);};FCKTableHandler.HorizontalSplitCell=function(){var A=FCKTableHandler.GetSelectedCells();if (A.length!=1) return;var B=A[0];var C=this._CreateTableMap(B.parentNode.parentNode);var D=B.parentNode.rowIndex;var E=FCKTableHandler._GetCellIndexSpan(C,D,B);var F=isNaN(B.colSpan)?1:B.colSpan;if (F>1){var G=Math.ceil(F/2);var H=FCKTools.GetElementDocument(B).createElement('td');if (FCKBrowserInfo.IsGeckoLike) FCKTools.AppendBogusBr(H);var I=E+G;var J=E+F;var K=isNaN(B.rowSpan)?1:B.rowSpan;for (var r=D;r1){B.rowSpan=Math.ceil(E/2);var G=F+Math.ceil(E/2);var H=null;for (var i=D+1;i0){var C=B.rows[0];C.parentNode.removeChild(C);};for (var i=0;iE) E=j;if (D._colScanned===true) continue;if (A[i][j-1]==D) D.colSpan++;if (A[i][j+1]!=D) D._colScanned=true;}};for (var i=0;i<=E;i++){for (var j=0;j ';var A=FCKDocumentProcessor_CreateFakeImage('FCK__PageBreak',e);var B=new FCKDomRange(FCK.EditorWindow);B.MoveToSelection();var C=B.SplitBlock();B.InsertNode(A);FCK.Events.FireEvent('OnSelectionChange');};FCKPageBreakCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;return 0;};var FCKUnlinkCommand=function(){this.Name='Unlink';};FCKUnlinkCommand.prototype.Execute=function(){FCKUndo.SaveUndoStep();if (FCKBrowserInfo.IsGeckoLike){var A=FCK.Selection.MoveToAncestorNode('A');if (A) FCKTools.RemoveOuterTags(A);return;};FCK.ExecuteNamedCommand(this.Name);};FCKUnlinkCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;var A=FCK.GetNamedCommandState(this.Name);if (A==0&&FCK.EditMode==0){var B=FCKSelection.MoveToAncestorNode('A');var C=(B&&B.name.length>0&&B.href.length==0);if (C) A=-1;};return A;};var FCKSelectAllCommand=function(){this.Name='SelectAll';};FCKSelectAllCommand.prototype.Execute=function(){if (FCK.EditMode==0){FCK.ExecuteNamedCommand('SelectAll');}else{var A=FCK.EditingArea.Textarea;if (FCKBrowserInfo.IsIE){A.createTextRange().execCommand('SelectAll');}else{A.selectionStart=0;A.selectionEnd=A.value.length;};A.focus();}};FCKSelectAllCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;return 0;};var FCKPasteCommand=function(){this.Name='Paste';};FCKPasteCommand.prototype={Execute:function(){if (FCKBrowserInfo.IsIE) FCK.Paste();else FCK.ExecuteNamedCommand('Paste');},GetState:function(){if (FCK.EditMode!=0) return -1;return FCK.GetNamedCommandState('Paste');}};var FCKRuleCommand=function(){this.Name='Rule';};FCKRuleCommand.prototype={Execute:function(){FCKUndo.SaveUndoStep();FCK.InsertElement('hr');},GetState:function(){if (FCK.EditMode!=0) return -1;return FCK.GetNamedCommandState('InsertHorizontalRule');}};var FCKCutCopyCommand=function(A){this.Name=A?'Cut':'Copy';};FCKCutCopyCommand.prototype={Execute:function(){var A=false;if (FCKBrowserInfo.IsIE){var B=function(){A=true;};var C='on'+this.Name.toLowerCase();FCK.EditorDocument.body.attachEvent(C,B);FCK.ExecuteNamedCommand(this.Name);FCK.EditorDocument.body.detachEvent(C,B);}else{try{FCK.ExecuteNamedCommand(this.Name);A=true;}catch(e){}};if (!A) alert(FCKLang['PasteError'+this.Name]);},GetState:function(){return FCK.EditMode!=0?-1:FCK.GetNamedCommandState('Cut');}};var FCKAnchorDeleteCommand=function(){this.Name='AnchorDelete';};FCKAnchorDeleteCommand.prototype={Execute:function(){if (FCK.Selection.GetType()=='Control'){FCK.Selection.Delete();}else{var A=FCK.Selection.GetSelectedElement();if (A){if (A.tagName=='IMG'&&A.getAttribute('_fckanchor')) oAnchor=FCK.GetRealElement(A);else A=null;};if (!A){oAnchor=FCK.Selection.MoveToAncestorNode('A');if (oAnchor) FCK.Selection.SelectNode(oAnchor);};if (oAnchor.href.length!=0){oAnchor.removeAttribute('name');if (FCKBrowserInfo.IsIE) oAnchor.className=oAnchor.className.replace(FCKRegexLib.FCK_Class,'');return;};if (A){A.parentNode.removeChild(A);return;};if (oAnchor.innerHTML.length==0){oAnchor.parentNode.removeChild(oAnchor);return;};FCKTools.RemoveOuterTags(oAnchor);};if (FCKBrowserInfo.IsGecko) FCK.Selection.Collapse(true);},GetState:function(){if (FCK.EditMode!=0) return -1;return FCK.GetNamedCommandState('Unlink');}}; +var FCKShowBlockCommand=function(A,B){this.Name=A;if (B!=undefined) this._SavedState=B;else this._SavedState=null;};FCKShowBlockCommand.prototype.Execute=function(){var A=this.GetState();if (A==-1) return;var B=FCK.EditorDocument.body;if (A==1) B.className=B.className.replace(/(^| )FCK__ShowBlocks/g,'');else B.className+=' FCK__ShowBlocks';FCK.Events.FireEvent('OnSelectionChange');};FCKShowBlockCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;if (!FCK.EditorDocument) return 0;if (/FCK__ShowBlocks(?:\s|$)/.test(FCK.EditorDocument.body.className)) return 1;return 0;};FCKShowBlockCommand.prototype.SaveState=function(){this._SavedState=this.GetState();};FCKShowBlockCommand.prototype.RestoreState=function(){if (this._SavedState!=null&&this.GetState()!=this._SavedState) this.Execute();}; +var FCKSpellCheckCommand=function(){this.Name='SpellCheck';this.IsEnabled=(FCKConfig.SpellChecker=='SpellerPages');};FCKSpellCheckCommand.prototype.Execute=function(){FCKDialog.OpenDialog('FCKDialog_SpellCheck','Spell Check','dialog/fck_spellerpages.html',440,480);};FCKSpellCheckCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;return this.IsEnabled?0:-1;}; +var FCKTextColorCommand=function(A){this.Name=A=='ForeColor'?'TextColor':'BGColor';this.Type=A;var B;if (FCKBrowserInfo.IsIE) B=window;else if (FCK.ToolbarSet._IFrame) B=FCKTools.GetElementWindow(FCK.ToolbarSet._IFrame);else B=window.parent;this._Panel=new FCKPanel(B);this._Panel.AppendStyleSheet(FCKConfig.SkinEditorCSS);this._Panel.MainNode.className='FCK_Panel';this._CreatePanelBody(this._Panel.Document,this._Panel.MainNode);FCK.ToolbarSet.ToolbarItems.GetItem(this.Name).RegisterPanel(this._Panel);FCKTools.DisableSelection(this._Panel.Document.body);};FCKTextColorCommand.prototype.Execute=function(A,B,C){this._Panel.Show(A,B,C);};FCKTextColorCommand.prototype.SetColor=function(A){FCKUndo.SaveUndoStep();var B=FCKStyles.GetStyle('_FCK_'+(this.Type=='ForeColor'?'Color':'BackColor'));if (!A||A.length==0) FCK.Styles.RemoveStyle(B);else{B.SetVariable('Color',A);FCKStyles.ApplyStyle(B);};FCKUndo.SaveUndoStep();FCK.Focus();FCK.Events.FireEvent('OnSelectionChange');};FCKTextColorCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;return 0;};function FCKTextColorCommand_OnMouseOver(){this.className='ColorSelected';};function FCKTextColorCommand_OnMouseOut(){this.className='ColorDeselected';};function FCKTextColorCommand_OnClick(A,B,C){this.className='ColorDeselected';B.SetColor(C);B._Panel.Hide();};function FCKTextColorCommand_AutoOnClick(A,B){this.className='ColorDeselected';B.SetColor('');B._Panel.Hide();};function FCKTextColorCommand_MoreOnClick(A,B){this.className='ColorDeselected';B._Panel.Hide();FCKDialog.OpenDialog('FCKDialog_Color',FCKLang.DlgColorTitle,'dialog/fck_colorselector.html',410,320,FCKTools.Bind(B,B.SetColor));};FCKTextColorCommand.prototype._CreatePanelBody=function(A,B){function CreateSelectionDiv(){var C=A.createElement("DIV");C.className='ColorDeselected';FCKTools.AddEventListenerEx(C,'mouseover',FCKTextColorCommand_OnMouseOver);FCKTools.AddEventListenerEx(C,'mouseout',FCKTextColorCommand_OnMouseOut);return C;};var D=B.appendChild(A.createElement("TABLE"));D.className='ForceBaseFont';D.style.tableLayout='fixed';D.cellPadding=0;D.cellSpacing=0;D.border=0;D.width=150;var E=D.insertRow(-1).insertCell(-1);E.colSpan=8;var C=E.appendChild(CreateSelectionDiv());C.innerHTML='\n \n \n \n \n
      '+FCKLang.ColorAutomatic+'
      ';FCKTools.AddEventListenerEx(C,'click',FCKTextColorCommand_AutoOnClick,this);if (!FCKBrowserInfo.IsIE) C.style.width='96%';var G=FCKConfig.FontColors.toString().split(',');var H=0;while (H
      ';if (H>=G.length) C.style.visibility='hidden';else FCKTools.AddEventListenerEx(C,'click',FCKTextColorCommand_OnClick,[this,L]);}};if (FCKConfig.EnableMoreFontColors){E=D.insertRow(-1).insertCell(-1);E.colSpan=8;C=E.appendChild(CreateSelectionDiv());C.innerHTML='
      '+FCKLang.ColorMoreColors+'
      ';FCKTools.AddEventListenerEx(C,'click',FCKTextColorCommand_MoreOnClick,this);};if (!FCKBrowserInfo.IsIE) C.style.width='96%';}; +var FCKPastePlainTextCommand=function(){this.Name='PasteText';};FCKPastePlainTextCommand.prototype.Execute=function(){FCK.PasteAsPlainText();};FCKPastePlainTextCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;return FCK.GetNamedCommandState('Paste');}; +var FCKPasteWordCommand=function(){this.Name='PasteWord';};FCKPasteWordCommand.prototype.Execute=function(){FCK.PasteFromWord();};FCKPasteWordCommand.prototype.GetState=function(){if (FCK.EditMode!=0||FCKConfig.ForcePasteAsPlainText) return -1;else return FCK.GetNamedCommandState('Paste');}; +var FCKTableCommand=function(A){this.Name=A;};FCKTableCommand.prototype.Execute=function(){FCKUndo.SaveUndoStep();if (!FCKBrowserInfo.IsGecko){switch (this.Name){case 'TableMergeRight':return FCKTableHandler.MergeRight();case 'TableMergeDown':return FCKTableHandler.MergeDown();}};switch (this.Name){case 'TableInsertRowAfter':return FCKTableHandler.InsertRow(false);case 'TableInsertRowBefore':return FCKTableHandler.InsertRow(true);case 'TableDeleteRows':return FCKTableHandler.DeleteRows();case 'TableInsertColumnAfter':return FCKTableHandler.InsertColumn(false);case 'TableInsertColumnBefore':return FCKTableHandler.InsertColumn(true);case 'TableDeleteColumns':return FCKTableHandler.DeleteColumns();case 'TableInsertCellAfter':return FCKTableHandler.InsertCell(null,false);case 'TableInsertCellBefore':return FCKTableHandler.InsertCell(null,true);case 'TableDeleteCells':return FCKTableHandler.DeleteCells();case 'TableMergeCells':return FCKTableHandler.MergeCells();case 'TableHorizontalSplitCell':return FCKTableHandler.HorizontalSplitCell();case 'TableVerticalSplitCell':return FCKTableHandler.VerticalSplitCell();case 'TableDelete':return FCKTableHandler.DeleteTable();default:return alert(FCKLang.UnknownCommand.replace(/%1/g,this.Name));}};FCKTableCommand.prototype.GetState=function(){if (FCK.EditorDocument!=null&&FCKSelection.HasAncestorNode('TABLE')){switch (this.Name){case 'TableHorizontalSplitCell':case 'TableVerticalSplitCell':if (FCKTableHandler.GetSelectedCells().length==1) return 0;else return -1;case 'TableMergeCells':if (FCKTableHandler.CheckIsSelectionRectangular()&&FCKTableHandler.GetSelectedCells().length>1) return 0;else return -1;case 'TableMergeRight':return FCKTableHandler.GetMergeRightTarget()?0:-1;case 'TableMergeDown':return FCKTableHandler.GetMergeDownTarget()?0:-1;default:return 0;}}else return -1;}; +var FCKFitWindow=function(){this.Name='FitWindow';};FCKFitWindow.prototype.Execute=function(){var A=window.frameElement;var B=A.style;var C=parent;var D=C.document.documentElement;var E=C.document.body;var F=E.style;var G;if (!this.IsMaximized){if(FCKBrowserInfo.IsIE) C.attachEvent('onresize',FCKFitWindow_Resize);else C.addEventListener('resize',FCKFitWindow_Resize,true);this._ScrollPos=FCKTools.GetScrollPosition(C);G=A;while((G=G.parentNode)){if (G.nodeType==1){G._fckSavedStyles=FCKTools.SaveStyles(G);G.style.zIndex=FCKConfig.FloatingPanelsZIndex-1;}};if (FCKBrowserInfo.IsIE){this.documentElementOverflow=D.style.overflow;D.style.overflow='hidden';F.overflow='hidden';}else{F.overflow='hidden';F.width='0px';F.height='0px';};this._EditorFrameStyles=FCKTools.SaveStyles(A);var H=FCKTools.GetViewPaneSize(C);B.position="absolute";B.zIndex=FCKConfig.FloatingPanelsZIndex-1;B.left="0px";B.top="0px";B.width=H.Width+"px";B.height=H.Height+"px";if (!FCKBrowserInfo.IsIE){B.borderRight=B.borderBottom="9999px solid white";B.backgroundColor="white";};C.scrollTo(0,0);var I=FCKTools.GetWindowPosition(C,A);if (I.x!=0) B.left=(-1*I.x)+"px";if (I.y!=0) B.top=(-1*I.y)+"px";this.IsMaximized=true;}else{if(FCKBrowserInfo.IsIE) C.detachEvent("onresize",FCKFitWindow_Resize);else C.removeEventListener("resize",FCKFitWindow_Resize,true);G=A;while((G=G.parentNode)){if (G._fckSavedStyles){FCKTools.RestoreStyles(G,G._fckSavedStyles);G._fckSavedStyles=null;}};if (FCKBrowserInfo.IsIE) D.style.overflow=this.documentElementOverflow;FCKTools.RestoreStyles(A,this._EditorFrameStyles);C.scrollTo(this._ScrollPos.X,this._ScrollPos.Y);this.IsMaximized=false;};FCKToolbarItems.GetItem('FitWindow').RefreshState();if (FCK.EditMode==0) FCK.EditingArea.MakeEditable();FCK.Focus();};FCKFitWindow.prototype.GetState=function(){if (FCKConfig.ToolbarLocation!='In') return -1;else return (this.IsMaximized?1:0);};function FCKFitWindow_Resize(){var A=FCKTools.GetViewPaneSize(parent);var B=window.frameElement.style;B.width=A.Width+'px';B.height=A.Height+'px';}; +var FCKListCommand=function(A,B){this.Name=A;this.TagName=B;};FCKListCommand.prototype={GetState:function(){if (FCK.EditMode!=0||!FCK.EditorWindow) return -1;var A=FCKSelection.GetBoundaryParentElement(true);var B=A;while (B){if (B.nodeName.IEquals(['ul','ol'])) break;B=B.parentNode;};if (B&&B.nodeName.IEquals(this.TagName)) return 1;else return 0;},Execute:function(){FCKUndo.SaveUndoStep();var A=FCK.EditorDocument;var B=new FCKDomRange(FCK.EditorWindow);B.MoveToSelection();var C=this.GetState();if (C==0){FCKDomTools.TrimNode(A.body);if (!A.body.firstChild){var D=A.createElement('p');A.body.appendChild(D);B.MoveToNodeContents(D);}};var E=B.CreateBookmark();var F=[];var G={};var H=new FCKDomRangeIterator(B);var I;H.ForceBrBreak=(C==0);var J=true;var K=null;while (J){while ((I=H.GetNextParagraph())){var L=new FCKElementPath(I);var M=null;var N=false;var O=L.BlockLimit;for (var i=L.Elements.length-1;i>=0;i--){var P=L.Elements[i];if (P.nodeName.IEquals(['ol','ul'])){if (O._FCK_ListGroupObject) O._FCK_ListGroupObject=null;var Q=P._FCK_ListGroupObject;if (Q) Q.contents.push(I);else{Q={ 'root':P,'contents':[I] };F.push(Q);FCKDomTools.SetElementMarker(G,P,'_FCK_ListGroupObject',Q);};N=true;break;}};if (N) continue;var R=O;if (R._FCK_ListGroupObject) R._FCK_ListGroupObject.contents.push(I);else{var Q={ 'root':R,'contents':[I] };FCKDomTools.SetElementMarker(G,R,'_FCK_ListGroupObject',Q);F.push(Q);}};if (FCKBrowserInfo.IsIE) J=false;else{if (K==null){K=[];var T=FCKSelection.GetSelection();if (T&&F.length==0) K.push(T.getRangeAt(0));for (var i=1;T&&i0){var Q=F.shift();if (C==0){if (Q.root.nodeName.IEquals(['ul','ol'])) this._ChangeListType(Q,G,W);else this._CreateList(Q,W);}else if (C==1&&Q.root.nodeName.IEquals(['ul','ol'])) this._RemoveList(Q,G);};for (var i=0;iC[i-1].indent+1){var H=C[i-1].indent+1-C[i].indent;var I=C[i].indent;while (C[i]&&C[i].indent>=I){C[i].indent+=H;i++;};i--;}};var J=FCKDomTools.ArrayToList(C,B);if (A.root.nextSibling==null||A.root.nextSibling.nodeName.IEquals('br')){if (J.listNode.lastChild.nodeName.IEquals('br')) J.listNode.removeChild(J.listNode.lastChild);};A.root.parentNode.replaceChild(J.listNode,A.root);}}; +var FCKJustifyCommand=function(A){this.AlignValue=A;var B=FCKConfig.ContentLangDirection.toLowerCase();this.IsDefaultAlign=(A=='left'&&B=='ltr')||(A=='right'&&B=='rtl');var C=this._CssClassName=(function(){var D=FCKConfig.JustifyClasses;if (D){switch (A){case 'left':return D[0]||null;case 'center':return D[1]||null;case 'right':return D[2]||null;case 'justify':return D[3]||null;}};return null;})();if (C&&C.length>0) this._CssClassRegex=new RegExp('(?:^|\\s+)'+C+'(?=$|\\s)');};FCKJustifyCommand._GetClassNameRegex=function(){var A=FCKJustifyCommand._ClassRegex;if (A!=undefined) return A;var B=[];var C=FCKConfig.JustifyClasses;if (C){for (var i=0;i<4;i++){var D=C[i];if (D&&D.length>0) B.push(D);}};if (B.length>0) A=new RegExp('(?:^|\\s+)(?:'+B.join('|')+')(?=$|\\s)');else A=null;return FCKJustifyCommand._ClassRegex=A;};FCKJustifyCommand.prototype={Execute:function(){FCKUndo.SaveUndoStep();var A=new FCKDomRange(FCK.EditorWindow);A.MoveToSelection();var B=this.GetState();if (B==-1) return;var C=A.CreateBookmark();var D=this._CssClassName;var E=new FCKDomRangeIterator(A);var F;while ((F=E.GetNextParagraph())){F.removeAttribute('align');if (D){var G=F.className.replace(FCKJustifyCommand._GetClassNameRegex(),'');if (B==0){if (G.length>0) G+=' ';F.className=G+D;}else if (G.length==0) FCKDomTools.RemoveAttribute(F,'class');}else{var H=F.style;if (B==0) H.textAlign=this.AlignValue;else{H.textAlign='';if (H.cssText.length==0) F.removeAttribute('style');}}};A.MoveToBookmark(C);A.Select();FCK.Focus();FCK.Events.FireEvent('OnSelectionChange');},GetState:function(){if (FCK.EditMode!=0||!FCK.EditorWindow) return -1;var A=new FCKElementPath(FCKSelection.GetBoundaryParentElement(true));var B=A.Block||A.BlockLimit;if (!B||B.nodeName.toLowerCase()=='body') return 0;var C;if (FCKBrowserInfo.IsIE) C=B.currentStyle.textAlign;else C=FCK.EditorWindow.getComputedStyle(B,'').getPropertyValue('text-align');C=C.replace(/(-moz-|-webkit-|start|auto)/i,'');if ((!C&&this.IsDefaultAlign)||C==this.AlignValue) return 1;return 0;}}; +var FCKIndentCommand=function(A,B){this.Name=A;this.Offset=B;this.IndentCSSProperty=FCKConfig.ContentLangDirection.IEquals('ltr')?'marginLeft':'marginRight';};FCKIndentCommand._InitIndentModeParameters=function(){if (FCKConfig.IndentClasses&&FCKConfig.IndentClasses.length>0){this._UseIndentClasses=true;this._IndentClassMap={};for (var i=0;i0?H+' ':'')+FCKConfig.IndentClasses[G-1];}else{var I=parseInt(E.style[this.IndentCSSProperty],10);if (isNaN(I)) I=0;I+=this.Offset;I=Math.max(I,0);I=Math.ceil(I/this.Offset)*this.Offset;E.style[this.IndentCSSProperty]=I?I+FCKConfig.IndentUnit:'';if (E.getAttribute('style')=='') E.removeAttribute('style');}}},_IndentList:function(A,B){var C=A.StartContainer;var D=A.EndContainer;while (C&&C.parentNode!=B) C=C.parentNode;while (D&&D.parentNode!=B) D=D.parentNode;if (!C||!D) return;var E=C;var F=[];var G=false;while (G==false){if (E==D) G=true;F.push(E);E=E.nextSibling;};if (F.length<1) return;var H=FCKDomTools.GetParents(B);for (var i=0;iN;i++) M[i].indent+=I;var O=FCKDomTools.ArrayToList(M);if (O) B.parentNode.replaceChild(O.listNode,B);FCKDomTools.ClearAllMarkers(L);}}; +var FCKBlockQuoteCommand=function(){};FCKBlockQuoteCommand.prototype={Execute:function(){FCKUndo.SaveUndoStep();var A=this.GetState();var B=new FCKDomRange(FCK.EditorWindow);B.MoveToSelection();var C=B.CreateBookmark();if (FCKBrowserInfo.IsIE){var D=B.GetBookmarkNode(C,true);var E=B.GetBookmarkNode(C,false);var F;if (D&&D.parentNode.nodeName.IEquals('blockquote')&&!D.previousSibling){F=D;while ((F=F.nextSibling)){if (FCKListsLib.BlockElements[F.nodeName.toLowerCase()]) FCKDomTools.MoveNode(D,F,true);}};if (E&&E.parentNode.nodeName.IEquals('blockquote')&&!E.previousSibling){F=E;while ((F=F.nextSibling)){if (FCKListsLib.BlockElements[F.nodeName.toLowerCase()]){if (F.firstChild==D) FCKDomTools.InsertAfterNode(D,E);else FCKDomTools.MoveNode(E,F,true);}}}};var G=new FCKDomRangeIterator(B);var H;if (A==0){G.EnforceRealBlocks=true;var I=[];while ((H=G.GetNextParagraph())) I.push(H);if (I.length<1){para=B.Window.document.createElement(FCKConfig.EnterMode.IEquals('p')?'p':'div');B.InsertNode(para);para.appendChild(B.Window.document.createTextNode('\ufeff'));B.MoveToBookmark(C);B.MoveToNodeContents(para);B.Collapse(true);C=B.CreateBookmark();I.push(para);};var J=I[0].parentNode;var K=[];for (var i=0;i0){H=I.shift();while (H.parentNode!=J) H=H.parentNode;if (H!=L) K.push(H);L=H;};while (K.length>0){H=K.shift();if (H.nodeName.IEquals('blockquote')){var M=FCKTools.GetElementDocument(H).createDocumentFragment();while (H.firstChild){M.appendChild(H.removeChild(H.firstChild));I.push(M.lastChild);};H.parentNode.replaceChild(M,H);}else I.push(H);};var N=B.Window.document.createElement('blockquote');J.insertBefore(N,I[0]);while (I.length>0){H=I.shift();N.appendChild(H);}}else if (A==1){var O=[];while ((H=G.GetNextParagraph())){var P=null;var Q=null;while (H.parentNode){if (H.parentNode.nodeName.IEquals('blockquote')){P=H.parentNode;Q=H;break;};H=H.parentNode;};if (P&&Q) O.push(Q);};var R=[];while (O.length>0){var S=O.shift();var N=S.parentNode;if (S==S.parentNode.firstChild){N.parentNode.insertBefore(N.removeChild(S),N);if (!N.firstChild) N.parentNode.removeChild(N);}else if (S==S.parentNode.lastChild){N.parentNode.insertBefore(N.removeChild(S),N.nextSibling);if (!N.firstChild) N.parentNode.removeChild(N);}else FCKDomTools.BreakParent(S,S.parentNode,B);R.push(S);};if (FCKConfig.EnterMode.IEquals('br')){while (R.length){var S=R.shift();var W=true;if (S.nodeName.IEquals('div')){var M=FCKTools.GetElementDocument(S).createDocumentFragment();var Y=W&&S.previousSibling&&!FCKListsLib.BlockBoundaries[S.previousSibling.nodeName.toLowerCase()];if (W&&Y) M.appendChild(FCKTools.GetElementDocument(S).createElement('br'));var Z=S.nextSibling&&!FCKListsLib.BlockBoundaries[S.nextSibling.nodeName.toLowerCase()];while (S.firstChild) M.appendChild(S.removeChild(S.firstChild));if (Z) M.appendChild(FCKTools.GetElementDocument(S).createElement('br'));S.parentNode.replaceChild(M,S);W=false;}}}};B.MoveToBookmark(C);B.Select();FCK.Focus();FCK.Events.FireEvent('OnSelectionChange');},GetState:function(){if (FCK.EditMode!=0||!FCK.EditorWindow) return -1;var A=new FCKElementPath(FCKSelection.GetBoundaryParentElement(true));var B=A.Block||A.BlockLimit;if (!B||B.nodeName.toLowerCase()=='body') return 0;for (var i=0;i';B.open();B.write(''+F+'<\/head><\/body><\/html>');B.close();if(FCKBrowserInfo.IsAIR) FCKAdobeAIR.Panel_Contructor(B,window.document.location);FCKTools.AddEventListenerEx(E,'focus',FCKPanel_Window_OnFocus,this);FCKTools.AddEventListenerEx(E,'blur',FCKPanel_Window_OnBlur,this);};B.dir=FCKLang.Dir;FCKTools.AddEventListener(B,'contextmenu',FCKTools.CancelEvent);this.MainNode=B.body.appendChild(B.createElement('DIV'));this.MainNode.style.cssFloat=this.IsRTL?'right':'left';};FCKPanel.prototype.AppendStyleSheet=function(A){FCKTools.AppendStyleSheet(this.Document,A);};FCKPanel.prototype.Preload=function(x,y,A){if (this._Popup) this._Popup.show(x,y,0,0,A);};FCKPanel.prototype.Show=function(x,y,A,B,C){var D;var E=this.MainNode;if (this._Popup){this._Popup.show(x,y,0,0,A);FCKDomTools.SetElementStyles(E,{B:B?B+'px':'',C:C?C+'px':''});D=E.offsetWidth;if (this.IsRTL){if (this.IsContextMenu) x=x-D+1;else if (A) x=(x*-1)+A.offsetWidth-D;};this._Popup.show(x,y,D,E.offsetHeight,A);if (this.OnHide){if (this._Timer) CheckPopupOnHide.call(this,true);this._Timer=FCKTools.SetInterval(CheckPopupOnHide,100,this);}}else{if (typeof(FCK.ToolbarSet.CurrentInstance.FocusManager)!='undefined') FCK.ToolbarSet.CurrentInstance.FocusManager.Lock();if (this.ParentPanel){this.ParentPanel.Lock();FCKPanel_Window_OnBlur(null,this.ParentPanel);};if (FCKBrowserInfo.IsGecko&&FCKBrowserInfo.IsMac){this._IFrame.scrolling='';FCKTools.RunFunction(function(){ this._IFrame.scrolling='no';},this);};if (FCK.ToolbarSet.CurrentInstance.GetInstanceObject('FCKPanel')._OpenedPanel&&FCK.ToolbarSet.CurrentInstance.GetInstanceObject('FCKPanel')._OpenedPanel!=this) FCK.ToolbarSet.CurrentInstance.GetInstanceObject('FCKPanel')._OpenedPanel.Hide(false,true);FCKDomTools.SetElementStyles(E,{B:B?B+'px':'',C:C?C+'px':''});D=E.offsetWidth;if (!B) this._IFrame.width=1;if (!C) this._IFrame.height=1;D=E.offsetWidth||E.firstChild.offsetWidth;var F=FCKTools.GetDocumentPosition(this._Window,A.nodeType==9?(FCKTools.IsStrictMode(A)?A.documentElement:A.body):A);var G=FCKDomTools.GetPositionedAncestor(this._IFrame.parentNode);if (G){var H=FCKTools.GetDocumentPosition(FCKTools.GetElementWindow(G),G);F.x-=H.x;F.y-=H.y;};if (this.IsRTL&&!this.IsContextMenu) x=(x*-1);x+=F.x;y+=F.y;if (this.IsRTL){if (this.IsContextMenu) x=x-D+1;else if (A) x=x+A.offsetWidth-D;}else{var I=FCKTools.GetViewPaneSize(this._Window);var J=FCKTools.GetScrollPosition(this._Window);var K=I.Height+J.Y;var L=I.Width+J.X;if ((x+D)>L) x-=x+D-L;if ((y+E.offsetHeight)>K) y-=y+E.offsetHeight-K;};FCKDomTools.SetElementStyles(this._IFrame,{left:x+'px',top:y+'px'});this._IFrame.contentWindow.focus();this._IsOpened=true;var M=this;this._resizeTimer=setTimeout(function(){var N=E.offsetWidth||E.firstChild.offsetWidth;var O=E.offsetHeight;M._IFrame.width=N;M._IFrame.height=O;},0);FCK.ToolbarSet.CurrentInstance.GetInstanceObject('FCKPanel')._OpenedPanel=this;};FCKTools.RunFunction(this.OnShow,this);};FCKPanel.prototype.Hide=function(A,B){if (this._Popup) this._Popup.hide();else{if (!this._IsOpened||this._LockCounter>0) return;if (typeof(FCKFocusManager)!='undefined'&&!B) FCKFocusManager.Unlock();this._IFrame.width=this._IFrame.height=0;this._IsOpened=false;if (this._resizeTimer){clearTimeout(this._resizeTimer);this._resizeTimer=null;};if (this.ParentPanel) this.ParentPanel.Unlock();if (!A) FCKTools.RunFunction(this.OnHide,this);}};FCKPanel.prototype.CheckIsOpened=function(){if (this._Popup) return this._Popup.isOpen;else return this._IsOpened;};FCKPanel.prototype.CreateChildPanel=function(){var A=this._Popup?FCKTools.GetDocumentWindow(this.Document):this._Window;var B=new FCKPanel(A);B.ParentPanel=this;return B;};FCKPanel.prototype.Lock=function(){this._LockCounter++;};FCKPanel.prototype.Unlock=function(){if (--this._LockCounter==0&&!this.HasFocus) this.Hide();};function FCKPanel_Window_OnFocus(e,A){A.HasFocus=true;};function FCKPanel_Window_OnBlur(e,A){A.HasFocus=false;if (A._LockCounter==0) FCKTools.RunFunction(A.Hide,A);};function CheckPopupOnHide(A){if (A||!this._Popup.isOpen){window.clearInterval(this._Timer);this._Timer=null;FCKTools.RunFunction(this.OnHide,this);}};function FCKPanel_Cleanup(){this._Popup=null;this._Window=null;this.Document=null;this.MainNode=null;}; +var FCKIcon=function(A){var B=A?typeof(A):'undefined';switch (B){case 'number':this.Path=FCKConfig.SkinPath+'fck_strip.gif';this.Size=16;this.Position=A;break;case 'undefined':this.Path=FCK_SPACER_PATH;break;case 'string':this.Path=A;break;default:this.Path=A[0];this.Size=A[1];this.Position=A[2];}};FCKIcon.prototype.CreateIconElement=function(A){var B,eIconImage;if (this.Position){var C='-'+((this.Position-1)*this.Size)+'px';if (FCKBrowserInfo.IsIE){B=A.createElement('DIV');eIconImage=B.appendChild(A.createElement('IMG'));eIconImage.src=this.Path;eIconImage.style.top=C;}else{B=A.createElement('IMG');B.src=FCK_SPACER_PATH;B.style.backgroundPosition='0px '+C;B.style.backgroundImage='url("'+this.Path+'")';}}else{if (FCKBrowserInfo.IsIE){B=A.createElement('DIV');eIconImage=B.appendChild(A.createElement('IMG'));eIconImage.src=this.Path?this.Path:FCK_SPACER_PATH;}else{B=A.createElement('IMG');B.src=this.Path?this.Path:FCK_SPACER_PATH;}};B.className='TB_Button_Image';return B;}; +var FCKToolbarButtonUI=function(A,B,C,D,E,F){this.Name=A;this.Label=B||A;this.Tooltip=C||this.Label;this.Style=E||0;this.State=F||0;this.Icon=new FCKIcon(D);if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKToolbarButtonUI_Cleanup);};FCKToolbarButtonUI.prototype._CreatePaddingElement=function(A){var B=A.createElement('IMG');B.className='TB_Button_Padding';B.src=FCK_SPACER_PATH;return B;};FCKToolbarButtonUI.prototype.Create=function(A){var B=FCKTools.GetElementDocument(A);var C=this.MainElement=B.createElement('DIV');C.title=this.Tooltip;if (FCKBrowserInfo.IsGecko) C.onmousedown=FCKTools.CancelEvent;FCKTools.AddEventListenerEx(C,'mouseover',FCKToolbarButtonUI_OnMouseOver,this);FCKTools.AddEventListenerEx(C,'mouseout',FCKToolbarButtonUI_OnMouseOut,this);FCKTools.AddEventListenerEx(C,'click',FCKToolbarButtonUI_OnClick,this);this.ChangeState(this.State,true);if (this.Style==0&&!this.ShowArrow){C.appendChild(this.Icon.CreateIconElement(B));}else{var D=C.appendChild(B.createElement('TABLE'));D.cellPadding=0;D.cellSpacing=0;var E=D.insertRow(-1);var F=E.insertCell(-1);if (this.Style==0||this.Style==2) F.appendChild(this.Icon.CreateIconElement(B));else F.appendChild(this._CreatePaddingElement(B));if (this.Style==1||this.Style==2){F=E.insertCell(-1);F.className='TB_Button_Text';F.noWrap=true;F.appendChild(B.createTextNode(this.Label));};if (this.ShowArrow){if (this.Style!=0){E.insertCell(-1).appendChild(this._CreatePaddingElement(B));};F=E.insertCell(-1);var G=F.appendChild(B.createElement('IMG'));G.src=FCKConfig.SkinPath+'images/toolbar.buttonarrow.gif';G.width=5;G.height=3;};F=E.insertCell(-1);F.appendChild(this._CreatePaddingElement(B));};A.appendChild(C);};FCKToolbarButtonUI.prototype.ChangeState=function(A,B){if (!B&&this.State==A) return;var e=this.MainElement;if (!e) return;switch (parseInt(A,10)){case 0:e.className='TB_Button_Off';break;case 1:e.className='TB_Button_On';break;case -1:e.className='TB_Button_Disabled';break;};this.State=A;};function FCKToolbarButtonUI_OnMouseOver(A,B){if (B.State==0) this.className='TB_Button_Off_Over';else if (B.State==1) this.className='TB_Button_On_Over';};function FCKToolbarButtonUI_OnMouseOut(A,B){if (B.State==0) this.className='TB_Button_Off';else if (B.State==1) this.className='TB_Button_On';};function FCKToolbarButtonUI_OnClick(A,B){if (B.OnClick&&B.State!=-1) B.OnClick(B);};function FCKToolbarButtonUI_Cleanup(){this.MainElement=null;}; +var FCKToolbarButton=function(A,B,C,D,E,F,G){this.CommandName=A;this.Label=B;this.Tooltip=C;this.Style=D;this.SourceView=E?true:false;this.ContextSensitive=F?true:false;if (G==null) this.IconPath=FCKConfig.SkinPath+'toolbar/'+A.toLowerCase()+'.gif';else if (typeof(G)=='number') this.IconPath=[FCKConfig.SkinPath+'fck_strip.gif',16,G];else this.IconPath=G;};FCKToolbarButton.prototype.Create=function(A){this._UIButton=new FCKToolbarButtonUI(this.CommandName,this.Label,this.Tooltip,this.IconPath,this.Style);this._UIButton.OnClick=this.Click;this._UIButton._ToolbarButton=this;this._UIButton.Create(A);};FCKToolbarButton.prototype.RefreshState=function(){var A=this._UIButton;if (!A) return;var B=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetState();if (B==A.State) return;A.ChangeState(B);};FCKToolbarButton.prototype.Click=function(){var A=this._ToolbarButton||this;FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(A.CommandName).Execute();};FCKToolbarButton.prototype.Enable=function(){this.RefreshState();};FCKToolbarButton.prototype.Disable=function(){this._UIButton.ChangeState(-1);}; +var FCKSpecialCombo=function(A,B,C,D,E){this.FieldWidth=B||100;this.PanelWidth=C||150;this.PanelMaxHeight=D||150;this.Label=' ';this.Caption=A;this.Tooltip=A;this.Style=2;this.Enabled=true;this.Items={};this._Panel=new FCKPanel(E||window);this._Panel.AppendStyleSheet(FCKConfig.SkinEditorCSS);this._PanelBox=this._Panel.MainNode.appendChild(this._Panel.Document.createElement('DIV'));this._PanelBox.className='SC_Panel';this._PanelBox.style.width=this.PanelWidth+'px';this._PanelBox.innerHTML='
      ';this._ItemsHolderEl=this._PanelBox.getElementsByTagName('TD')[0];if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKSpecialCombo_Cleanup);};function FCKSpecialCombo_ItemOnMouseOver(){this.className+=' SC_ItemOver';};function FCKSpecialCombo_ItemOnMouseOut(){this.className=this.originalClass;};function FCKSpecialCombo_ItemOnClick(A,B,C){this.className=this.originalClass;B._Panel.Hide();B.SetLabel(this.FCKItemLabel);if (typeof(B.OnSelect)=='function') B.OnSelect(C,this);};FCKSpecialCombo.prototype.ClearItems=function (){if (this.Items) this.Items={};var A=this._ItemsHolderEl;while (A.firstChild) A.removeChild(A.firstChild);};FCKSpecialCombo.prototype.AddItem=function(A,B,C,D){var E=this._ItemsHolderEl.appendChild(this._Panel.Document.createElement('DIV'));E.className=E.originalClass='SC_Item';E.innerHTML=B;E.FCKItemLabel=C||A;E.Selected=false;if (FCKBrowserInfo.IsIE) E.style.width='100%';if (D) E.style.backgroundColor=D;FCKTools.AddEventListenerEx(E,'mouseover',FCKSpecialCombo_ItemOnMouseOver);FCKTools.AddEventListenerEx(E,'mouseout',FCKSpecialCombo_ItemOnMouseOut);FCKTools.AddEventListenerEx(E,'click',FCKSpecialCombo_ItemOnClick,[this,A]);this.Items[A.toString().toLowerCase()]=E;return E;};FCKSpecialCombo.prototype.SelectItem=function(A){if (typeof A=='string') A=this.Items[A.toString().toLowerCase()];if (A){A.className=A.originalClass='SC_ItemSelected';A.Selected=true;}};FCKSpecialCombo.prototype.SelectItemByLabel=function(A,B){for (var C in this.Items){var D=this.Items[C];if (D.FCKItemLabel==A){D.className=D.originalClass='SC_ItemSelected';D.Selected=true;if (B) this.SetLabel(A);}}};FCKSpecialCombo.prototype.DeselectAll=function(A){for (var i in this.Items){if (!this.Items[i]) continue;this.Items[i].className=this.Items[i].originalClass='SC_Item';this.Items[i].Selected=false;};if (A) this.SetLabel('');};FCKSpecialCombo.prototype.SetLabelById=function(A){A=A?A.toString().toLowerCase():'';var B=this.Items[A];this.SetLabel(B?B.FCKItemLabel:'');};FCKSpecialCombo.prototype.SetLabel=function(A){A=(!A||A.length==0)?' ':A;if (A==this.Label) return;this.Label=A;var B=this._LabelEl;if (B){B.innerHTML=A;FCKTools.DisableSelection(B);}};FCKSpecialCombo.prototype.SetEnabled=function(A){this.Enabled=A;if (this._OuterTable) this._OuterTable.className=A?'':'SC_FieldDisabled';};FCKSpecialCombo.prototype.Create=function(A){var B=FCKTools.GetElementDocument(A);var C=this._OuterTable=A.appendChild(B.createElement('TABLE'));C.cellPadding=0;C.cellSpacing=0;C.insertRow(-1);var D;var E;switch (this.Style){case 0:D='TB_ButtonType_Icon';E=false;break;case 1:D='TB_ButtonType_Text';E=false;break;case 2:E=true;break;};if (this.Caption&&this.Caption.length>0&&E){var F=C.rows[0].insertCell(-1);F.innerHTML=this.Caption;F.className='SC_FieldCaption';};var G=FCKTools.AppendElement(C.rows[0].insertCell(-1),'div');if (E){G.className='SC_Field';G.style.width=this.FieldWidth+'px';G.innerHTML='
       
      ';this._LabelEl=G.getElementsByTagName('label')[0];this._LabelEl.innerHTML=this.Label;}else{G.className='TB_Button_Off';G.innerHTML='
      '+this.Caption+'
      ';};FCKTools.AddEventListenerEx(G,'mouseover',FCKSpecialCombo_OnMouseOver,this);FCKTools.AddEventListenerEx(G,'mouseout',FCKSpecialCombo_OnMouseOut,this);FCKTools.AddEventListenerEx(G,'click',FCKSpecialCombo_OnClick,this);FCKTools.DisableSelection(this._Panel.Document.body);};function FCKSpecialCombo_Cleanup(){this._LabelEl=null;this._OuterTable=null;this._ItemsHolderEl=null;this._PanelBox=null;if (this.Items){for (var A in this.Items) this.Items[A]=null;}};function FCKSpecialCombo_OnMouseOver(A,B){if (B.Enabled){switch (B.Style){case 0:this.className='TB_Button_On_Over';break;case 1:this.className='TB_Button_On_Over';break;case 2:this.className='SC_Field SC_FieldOver';break;}}};function FCKSpecialCombo_OnMouseOut(A,B){switch (B.Style){case 0:this.className='TB_Button_Off';break;case 1:this.className='TB_Button_Off';break;case 2:this.className='SC_Field';break;}};function FCKSpecialCombo_OnClick(e,A){if (A.Enabled){var B=A._Panel;var C=A._PanelBox;var D=A._ItemsHolderEl;var E=A.PanelMaxHeight;if (A.OnBeforeClick) A.OnBeforeClick(A);if (FCKBrowserInfo.IsIE) B.Preload(0,this.offsetHeight,this);if (D.offsetHeight>E) C.style.height=E+'px';else C.style.height='';B.Show(0,this.offsetHeight,this);}}; +var FCKToolbarSpecialCombo=function(){this.SourceView=false;this.ContextSensitive=true;this.FieldWidth=null;this.PanelWidth=null;this.PanelMaxHeight=null;};FCKToolbarSpecialCombo.prototype.DefaultLabel='';function FCKToolbarSpecialCombo_OnSelect(A,B){FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).Execute(A,B);};FCKToolbarSpecialCombo.prototype.Create=function(A){this._Combo=new FCKSpecialCombo(this.GetLabel(),this.FieldWidth,this.PanelWidth,this.PanelMaxHeight,FCKBrowserInfo.IsIE?window:FCKTools.GetElementWindow(A).parent);this._Combo.Tooltip=this.Tooltip;this._Combo.Style=this.Style;this.CreateItems(this._Combo);this._Combo.Create(A);this._Combo.CommandName=this.CommandName;this._Combo.OnSelect=FCKToolbarSpecialCombo_OnSelect;};function FCKToolbarSpecialCombo_RefreshActiveItems(A,B){A.DeselectAll();A.SelectItem(B);A.SetLabelById(B);};FCKToolbarSpecialCombo.prototype.RefreshState=function(){var A;var B=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetState();if (B!=-1){A=1;if (this.RefreshActiveItems) this.RefreshActiveItems(this._Combo,B);else{if (this._LastValue!==B){this._LastValue=B;if (!B||B.length==0){this._Combo.DeselectAll();this._Combo.SetLabel(this.DefaultLabel);}else FCKToolbarSpecialCombo_RefreshActiveItems(this._Combo,B);}}}else A=-1;if (A==this.State) return;if (A==-1){this._Combo.DeselectAll();this._Combo.SetLabel('');};this.State=A;this._Combo.SetEnabled(A!=-1);};FCKToolbarSpecialCombo.prototype.Enable=function(){this.RefreshState();};FCKToolbarSpecialCombo.prototype.Disable=function(){this.State=-1;this._Combo.DeselectAll();this._Combo.SetLabel('');this._Combo.SetEnabled(false);}; +var FCKToolbarStyleCombo=function(A,B){if (A===false) return;this.CommandName='Style';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;this.DefaultLabel=FCKConfig.DefaultStyleLabel||'';};FCKToolbarStyleCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarStyleCombo.prototype.GetLabel=function(){return FCKLang.Style;};FCKToolbarStyleCombo.prototype.GetStyles=function(){var A={};var B=FCK.ToolbarSet.CurrentInstance.Styles.GetStyles();for (var C in B){var D=B[C];if (!D.IsCore) A[C]=D;};return A;};FCKToolbarStyleCombo.prototype.CreateItems=function(A){var B=A._Panel.Document;FCKTools.AppendStyleSheet(B,FCKConfig.ToolbarComboPreviewCSS);FCKTools.AppendStyleString(B,FCKConfig.EditorAreaStyles);B.body.className+=' ForceBaseFont';FCKConfig.ApplyBodyAttributes(B.body);var C=this.GetStyles();for (var D in C){var E=C[D];var F=E.GetType()==2?D:FCKToolbarStyleCombo_BuildPreview(E,E.Label||D);var G=A.AddItem(D,F);G.Style=E;};A.OnBeforeClick=this.StyleCombo_OnBeforeClick;};FCKToolbarStyleCombo.prototype.RefreshActiveItems=function(A){var B=FCK.ToolbarSet.CurrentInstance.Selection.GetBoundaryParentElement(true);if (B){var C=new FCKElementPath(B);var D=C.Elements;for (var e=0;e');var E=A.Element;if (E=='bdo') E='span';D=['<',E];var F=A._StyleDesc.Attributes;if (F){for (var G in F){D.push(' ',G,'="',A.GetFinalAttributeValue(G),'"');}};if (A._GetStyleText().length>0) D.push(' style="',A.GetFinalStyleValue(),'"');D.push('>',B,'');if (C==0) D.push('');return D.join('');}; +var FCKToolbarFontFormatCombo=function(A,B){if (A===false) return;this.CommandName='FontFormat';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;this.NormalLabel='Normal';this.PanelWidth=190;this.DefaultLabel=FCKConfig.DefaultFontFormatLabel||'';};FCKToolbarFontFormatCombo.prototype=new FCKToolbarStyleCombo(false);FCKToolbarFontFormatCombo.prototype.GetLabel=function(){return FCKLang.FontFormat;};FCKToolbarFontFormatCombo.prototype.GetStyles=function(){var A={};var B=FCKLang['FontFormats'].split(';');var C={p:B[0],pre:B[1],address:B[2],h1:B[3],h2:B[4],h3:B[5],h4:B[6],h5:B[7],h6:B[8],div:B[9]||(B[0]+' (DIV)')};var D=FCKConfig.FontFormats.split(';');for (var i=0;i';G.open();G.write(''+H+''+document.getElementById('xToolbarSpace').innerHTML+'');G.close();if(FCKBrowserInfo.IsAIR) FCKAdobeAIR.ToolbarSet_InitOutFrame(G);FCKTools.AddEventListener(G,'contextmenu',FCKTools.CancelEvent);FCKTools.AppendStyleSheet(G,FCKConfig.SkinEditorCSS);B=D.__FCKToolbarSet=new FCKToolbarSet(G);B._IFrame=F;if (FCK.IECleanup) FCK.IECleanup.AddItem(D,FCKToolbarSet_Target_Cleanup);};B.CurrentInstance=FCK;if (!B.ToolbarItems) B.ToolbarItems=FCKToolbarItems;FCK.AttachToOnSelectionChange(B.RefreshItemsState);return B;};function FCK_OnBlur(A){var B=A.ToolbarSet;if (B.CurrentInstance==A) B.Disable();};function FCK_OnFocus(A){var B=A.ToolbarSet;var C=A||FCK;B.CurrentInstance.FocusManager.RemoveWindow(B._IFrame.contentWindow);B.CurrentInstance=C;C.FocusManager.AddWindow(B._IFrame.contentWindow,true);B.Enable();};function FCKToolbarSet_Cleanup(){this._TargetElement=null;this._IFrame=null;};function FCKToolbarSet_Target_Cleanup(){this.__FCKToolbarSet=null;};var FCKToolbarSet=function(A){this._Document=A;this._TargetElement=A.getElementById('xToolbar');var B=A.getElementById('xExpandHandle');var C=A.getElementById('xCollapseHandle');B.title=FCKLang.ToolbarExpand;FCKTools.AddEventListener(B,'click',FCKToolbarSet_Expand_OnClick);C.title=FCKLang.ToolbarCollapse;FCKTools.AddEventListener(C,'click',FCKToolbarSet_Collapse_OnClick);if (!FCKConfig.ToolbarCanCollapse||FCKConfig.ToolbarStartExpanded) this.Expand();else this.Collapse();C.style.display=FCKConfig.ToolbarCanCollapse?'':'none';if (FCKConfig.ToolbarCanCollapse) C.style.display='';else A.getElementById('xTBLeftBorder').style.display='';this.Toolbars=[];this.IsLoaded=false;if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKToolbarSet_Cleanup);};function FCKToolbarSet_Expand_OnClick(){FCK.ToolbarSet.Expand();};function FCKToolbarSet_Collapse_OnClick(){FCK.ToolbarSet.Collapse();};FCKToolbarSet.prototype.Expand=function(){this._ChangeVisibility(false);};FCKToolbarSet.prototype.Collapse=function(){this._ChangeVisibility(true);};FCKToolbarSet.prototype._ChangeVisibility=function(A){this._Document.getElementById('xCollapsed').style.display=A?'':'none';this._Document.getElementById('xExpanded').style.display=A?'none':'';if (FCKBrowserInfo.IsGecko){FCKTools.RunFunction(window.onresize);}};FCKToolbarSet.prototype.Load=function(A){this.Name=A;this.Items=[];this.ItemsWysiwygOnly=[];this.ItemsContextSensitive=[];this._TargetElement.innerHTML='';var B=FCKConfig.ToolbarSets[A];if (!B){alert(FCKLang.UnknownToolbarSet.replace(/%1/g,A));return;};this.Toolbars=[];for (var x=0;x0) break;}catch (e){break;};D=D.parent;};var E=D.document;var F=function(){if (!B) B=FCKConfig.FloatingPanelsZIndex+999;return++B;};var G=function(){if (!C) return;var H=FCKTools.IsStrictMode(E)?E.documentElement:E.body;FCKDomTools.SetElementStyles(C,{'width':Math.max(H.scrollWidth,H.clientWidth,E.scrollWidth||0)-1+'px','height':Math.max(H.scrollHeight,H.clientHeight,E.scrollHeight||0)-1+'px'});};var I=function(element){element.style.cssText='margin:0;padding:0;border:0;background-color:transparent;background-image:none;';};return {OpenDialog:function(dialogName,dialogTitle,dialogPage,width,height,customValue,parentWindow,resizable){if (!A) this.DisplayMainCover();var J={Title:dialogTitle,Page:dialogPage,Editor:window,CustomValue:customValue,TopWindow:D};FCK.ToolbarSet.CurrentInstance.Selection.Save();var K=FCKTools.GetViewPaneSize(D);var L=FCKTools.GetScrollPosition(D);var M=Math.max(L.Y+(K.Height-height-20)/2,0);var N=Math.max(L.X+(K.Width-width-20)/2,0);var O=E.createElement('iframe');I(O);O.src=FCKConfig.BasePath+'fckdialog.html';O.frameBorder=0;O.allowTransparency=true;FCKDomTools.SetElementStyles(O,{'position':'absolute','top':M+'px','left':N+'px','width':width+'px','height':height+'px','zIndex':F()});O._DialogArguments=J;E.body.appendChild(O);O._ParentDialog=A;A=O;},OnDialogClose:function(dialogWindow){var O=dialogWindow.frameElement;FCKDomTools.RemoveNode(O);if (O._ParentDialog){A=O._ParentDialog;O._ParentDialog.contentWindow.SetEnabled(true);}else{if (!FCKBrowserInfo.IsIE) FCK.Focus();this.HideMainCover();setTimeout(function(){ A=null;},0);FCK.ToolbarSet.CurrentInstance.Selection.Release();}},DisplayMainCover:function(){C=E.createElement('div');I(C);FCKDomTools.SetElementStyles(C,{'position':'absolute','zIndex':F(),'top':'0px','left':'0px','backgroundColor':FCKConfig.BackgroundBlockerColor});FCKDomTools.SetOpacity(C,FCKConfig.BackgroundBlockerOpacity);if (FCKBrowserInfo.IsIE&&!FCKBrowserInfo.IsIE7){var Q=E.createElement('iframe');I(Q);Q.hideFocus=true;Q.frameBorder=0;Q.src=FCKTools.GetVoidUrl();FCKDomTools.SetElementStyles(Q,{'width':'100%','height':'100%','position':'absolute','left':'0px','top':'0px','filter':'progid:DXImageTransform.Microsoft.Alpha(opacity=0)'});C.appendChild(Q);};FCKTools.AddEventListener(D,'resize',G);G();E.body.appendChild(C);FCKFocusManager.Lock();},HideMainCover:function(){FCKDomTools.RemoveNode(C);FCKFocusManager.Unlock();},GetCover:function(){return C;}};})(); +var FCKMenuItem=function(A,B,C,D,E,F){this.Name=B;this.Label=C||B;this.IsDisabled=E;this.Icon=new FCKIcon(D);this.SubMenu=new FCKMenuBlockPanel();this.SubMenu.Parent=A;this.SubMenu.OnClick=FCKTools.CreateEventListener(FCKMenuItem_SubMenu_OnClick,this);this.CustomData=F;if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKMenuItem_Cleanup);};FCKMenuItem.prototype.AddItem=function(A,B,C,D,E){this.HasSubMenu=true;return this.SubMenu.AddItem(A,B,C,D,E);};FCKMenuItem.prototype.AddSeparator=function(){this.SubMenu.AddSeparator();};FCKMenuItem.prototype.Create=function(A){var B=this.HasSubMenu;var C=FCKTools.GetElementDocument(A);var r=this.MainElement=A.insertRow(-1);r.className=this.IsDisabled?'MN_Item_Disabled':'MN_Item';if (!this.IsDisabled){FCKTools.AddEventListenerEx(r,'mouseover',FCKMenuItem_OnMouseOver,[this]);FCKTools.AddEventListenerEx(r,'click',FCKMenuItem_OnClick,[this]);if (!B) FCKTools.AddEventListenerEx(r,'mouseout',FCKMenuItem_OnMouseOut,[this]);};var D=r.insertCell(-1);D.className='MN_Icon';D.appendChild(this.Icon.CreateIconElement(C));D=r.insertCell(-1);D.className='MN_Label';D.noWrap=true;D.appendChild(C.createTextNode(this.Label));D=r.insertCell(-1);if (B){D.className='MN_Arrow';var E=D.appendChild(C.createElement('IMG'));E.src=FCK_IMAGES_PATH+'arrow_'+FCKLang.Dir+'.gif';E.width=4;E.height=7;this.SubMenu.Create();this.SubMenu.Panel.OnHide=FCKTools.CreateEventListener(FCKMenuItem_SubMenu_OnHide,this);}};FCKMenuItem.prototype.Activate=function(){this.MainElement.className='MN_Item_Over';if (this.HasSubMenu){this.SubMenu.Show(this.MainElement.offsetWidth+2,-2,this.MainElement);};FCKTools.RunFunction(this.OnActivate,this);};FCKMenuItem.prototype.Deactivate=function(){this.MainElement.className='MN_Item';if (this.HasSubMenu) this.SubMenu.Hide();};function FCKMenuItem_SubMenu_OnClick(A,B){FCKTools.RunFunction(B.OnClick,B,[A]);};function FCKMenuItem_SubMenu_OnHide(A){A.Deactivate();};function FCKMenuItem_OnClick(A,B){if (B.HasSubMenu) B.Activate();else{B.Deactivate();FCKTools.RunFunction(B.OnClick,B,[B]);}};function FCKMenuItem_OnMouseOver(A,B){B.Activate();};function FCKMenuItem_OnMouseOut(A,B){B.Deactivate();};function FCKMenuItem_Cleanup(){this.MainElement=null;}; +var FCKMenuBlock=function(){this._Items=[];};FCKMenuBlock.prototype.Count=function(){return this._Items.length;};FCKMenuBlock.prototype.AddItem=function(A,B,C,D,E){var F=new FCKMenuItem(this,A,B,C,D,E);F.OnClick=FCKTools.CreateEventListener(FCKMenuBlock_Item_OnClick,this);F.OnActivate=FCKTools.CreateEventListener(FCKMenuBlock_Item_OnActivate,this);this._Items.push(F);return F;};FCKMenuBlock.prototype.AddSeparator=function(){this._Items.push(new FCKMenuSeparator());};FCKMenuBlock.prototype.RemoveAllItems=function(){this._Items=[];var A=this._ItemsTable;if (A){while (A.rows.length>0) A.deleteRow(0);}};FCKMenuBlock.prototype.Create=function(A){if (!this._ItemsTable){if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKMenuBlock_Cleanup);this._Window=FCKTools.GetElementWindow(A);var B=FCKTools.GetElementDocument(A);var C=A.appendChild(B.createElement('table'));C.cellPadding=0;C.cellSpacing=0;FCKTools.DisableSelection(C);var D=C.insertRow(-1).insertCell(-1);D.className='MN_Menu';var E=this._ItemsTable=D.appendChild(B.createElement('table'));E.cellPadding=0;E.cellSpacing=0;};for (var i=0;i0&&F.href.length==0);if (G) return;menu.AddSeparator();if (E) menu.AddItem('Link',FCKLang.EditLink,34);menu.AddItem('Unlink',FCKLang.RemoveLink,35);}}};case 'Image':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&!tag.getAttribute('_fckfakelement')){menu.AddSeparator();menu.AddItem('Image',FCKLang.ImageProperties,37);}}};case 'Anchor':return {AddItems:function(menu,tag,tagName){var F=FCKSelection.MoveToAncestorNode('A');var G=(F&&F.name.length>0);if (G||(tagName=='IMG'&&tag.getAttribute('_fckanchor'))){menu.AddSeparator();menu.AddItem('Anchor',FCKLang.AnchorProp,36);menu.AddItem('AnchorDelete',FCKLang.AnchorDelete);}}};case 'Flash':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&tag.getAttribute('_fckflash')){menu.AddSeparator();menu.AddItem('Flash',FCKLang.FlashProperties,38);}}};case 'Form':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('FORM')){menu.AddSeparator();menu.AddItem('Form',FCKLang.FormProp,48);}}};case 'Checkbox':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='checkbox'){menu.AddSeparator();menu.AddItem('Checkbox',FCKLang.CheckboxProp,49);}}};case 'Radio':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='radio'){menu.AddSeparator();menu.AddItem('Radio',FCKLang.RadioButtonProp,50);}}};case 'TextField':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&(tag.type=='text'||tag.type=='password')){menu.AddSeparator();menu.AddItem('TextField',FCKLang.TextFieldProp,51);}}};case 'HiddenField':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&tag.getAttribute('_fckinputhidden')){menu.AddSeparator();menu.AddItem('HiddenField',FCKLang.HiddenFieldProp,56);}}};case 'ImageButton':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='image'){menu.AddSeparator();menu.AddItem('ImageButton',FCKLang.ImageButtonProp,55);}}};case 'Button':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&(tag.type=='button'||tag.type=='submit'||tag.type=='reset')){menu.AddSeparator();menu.AddItem('Button',FCKLang.ButtonProp,54);}}};case 'Select':return {AddItems:function(menu,tag,tagName){if (tagName=='SELECT'){menu.AddSeparator();menu.AddItem('Select',FCKLang.SelectionFieldProp,53);}}};case 'Textarea':return {AddItems:function(menu,tag,tagName){if (tagName=='TEXTAREA'){menu.AddSeparator();menu.AddItem('Textarea',FCKLang.TextareaProp,52);}}};case 'BulletedList':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('UL')){menu.AddSeparator();menu.AddItem('BulletedList',FCKLang.BulletedListProp,27);}}};case 'NumberedList':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('OL')){menu.AddSeparator();menu.AddItem('NumberedList',FCKLang.NumberedListProp,26);}}};};return null;};function FCK_ContextMenu_OnBeforeOpen(){FCK.Events.FireEvent('OnSelectionChange');var A,sTagName;if ((A=FCKSelection.GetSelectedElement())) sTagName=A.tagName;var B=FCK.ContextMenu._InnerContextMenu;B.RemoveAllItems();var C=FCK.ContextMenu.Listeners;for (var i=0;i0){D=A.substr(0,B.index);this._sourceHtml=A.substr(B.index);}else{C=true;D=B[0];this._sourceHtml=A.substr(B[0].length);}}else{D=A;this._sourceHtml=null;};return { 'isTag':C,'value':D };},Each:function(A){var B;while ((B=this.Next())) A(B.isTag,B.value);}};var FCKHtmlIterator=function(A){this._sourceHtml=A;};FCKHtmlIterator.prototype={Next:function(){var A=this._sourceHtml;if (A==null) return null;var B=FCKRegexLib.HtmlTag.exec(A);var C=false;var D="";if (B){if (B.index>0){D=A.substr(0,B.index);this._sourceHtml=A.substr(B.index);}else{C=true;D=B[0];this._sourceHtml=A.substr(B[0].length);}}else{D=A;this._sourceHtml=null;};return { 'isTag':C,'value':D };},Each:function(A){var B;while ((B=this.Next())) A(B.isTag,B.value);}}; +var FCKPlugin=function(A,B,C){this.Name=A;this.BasePath=C?C:FCKConfig.PluginsPath;this.Path=this.BasePath+A+'/';if (!B||B.length==0) this.AvailableLangs=[];else this.AvailableLangs=B.split(',');};FCKPlugin.prototype.Load=function(){if (this.AvailableLangs.length>0){var A;if (this.AvailableLangs.IndexOf(FCKLanguageManager.ActiveLanguage.Code)>=0) A=FCKLanguageManager.ActiveLanguage.Code;else A=this.AvailableLangs[0];LoadScript(this.Path+'lang/'+A+'.js');};LoadScript(this.Path+'fckplugin.js');}; +var FCKPlugins=FCK.Plugins={};FCKPlugins.ItemsCount=0;FCKPlugins.Items={};FCKPlugins.Load=function(){var A=FCKPlugins.Items;for (var i=0;i-1);};String.prototype.Equals=function(){var A=arguments;if (A.length==1&&A[0].pop) A=A[0];for (var i=0;iC) return false;if (B){var E=new RegExp(A+'$','i');return E.test(this);}else return (D==0||this.substr(C-D,D)==A);};String.prototype.Remove=function(A,B){var s='';if (A>0) s=this.substring(0,A);if (A+B0){var B=A.pop();if (B) B[1].call(B[0]);};this._FCKCleanupObj=null;if (CollectGarbage) CollectGarbage();} -var s=navigator.userAgent.toLowerCase();var FCKBrowserInfo={IsIE:s.Contains('msie'),IsIE7:s.Contains('msie 7'),IsGecko:s.Contains('gecko/'),IsSafari:s.Contains('safari'),IsOpera:s.Contains('opera'),IsMac:s.Contains('macintosh')};(function(A){A.IsGeckoLike=(A.IsGecko||A.IsSafari||A.IsOpera);if (A.IsGecko){var B=s.match(/gecko\/(\d+)/)[1];A.IsGecko10=B<20051111;}else A.IsGecko10=false;})(FCKBrowserInfo); -var FCKURLParams={};(function(){var A=document.location.search.substr(1).split('&');for (var i=0;i0?'':'';var A=FCK.KeystrokeHandler=new FCKKeystrokeHandler();A.OnKeystroke=_FCK_KeystrokeHandler_OnKeystroke;A.SetKeystrokes(FCKConfig.Keystrokes);if (FCKBrowserInfo.IsIE7){if ((CTRL+86/*V*/) in A.Keystrokes) A.SetKeystrokes([CTRL+86,true]);if ((SHIFT+45/*INS*/) in A.Keystrokes) A.SetKeystrokes([SHIFT+45,true]);};this.EditingArea=new FCKEditingArea(document.getElementById('xEditingArea'));this.EditingArea.FFSpellChecker=false;FCKListsLib.Setup();this.SetHTML(this.GetLinkedFieldValue(),true);},Focus:function(){FCK.EditingArea.Focus();},SetStatus:function(A){this.Status=A;if (A==1){FCKFocusManager.AddWindow(window,true);if (FCKBrowserInfo.IsIE) FCKFocusManager.AddWindow(window.frameElement,true);if (FCKConfig.StartupFocus) FCK.Focus();};this.Events.FireEvent('OnStatusChange',A);},FixBody:function(){var A=FCKConfig.EnterMode;if (A!='p'&&A!='div') return;var B=this.EditorDocument;if (!B) return;var C=B.body;if (!C) return;FCKDomTools.TrimNode(C);var D=C.firstChild;var E;while (D){var F=false;switch (D.nodeType){case 1:if (!FCKListsLib.BlockElements[D.nodeName.toLowerCase()]) F=true;break;case 3:if (E||D.nodeValue.Trim().length>0) F=true;};if (F){var G=D.parentNode;if (!E) E=G.insertBefore(B.createElement(A),D);E.appendChild(G.removeChild(D));D=E.nextSibling;}else{if (E){FCKDomTools.TrimNode(E);E=null;};D=D.nextSibling;}};if (E) FCKDomTools.TrimNode(E);},GetXHTML:function(A){if (FCK.EditMode==1) return FCK.EditingArea.Textarea.value;this.FixBody();var B;var C=FCK.EditorDocument;if (!C) return null;if (FCKConfig.FullPage){B=FCKXHtml.GetXHTML(C.getElementsByTagName('html')[0],true,A);if (FCK.DocTypeDeclaration&&FCK.DocTypeDeclaration.length>0) B=FCK.DocTypeDeclaration+'\n'+B;if (FCK.XmlDeclaration&&FCK.XmlDeclaration.length>0) B=FCK.XmlDeclaration+'\n'+B;}else{B=FCKXHtml.GetXHTML(C.body,false,A);if (FCKConfig.IgnoreEmptyParagraphValue&&FCKRegexLib.EmptyOutParagraph.test(B)) B='';};B=FCK.ProtectEventsRestore(B);if (FCKBrowserInfo.IsIE) B=B.replace(FCKRegexLib.ToReplace,'$1');return FCKConfig.ProtectedSource.Revert(B);},UpdateLinkedField:function(){FCK.LinkedField.value=FCK.GetXHTML(FCKConfig.FormatOutput);FCK.Events.FireEvent('OnAfterLinkedFieldUpdate');},RegisteredDoubleClickHandlers:{},OnDoubleClick:function(A){var B=FCK.RegisteredDoubleClickHandlers[A.tagName];if (B) B(A);},RegisterDoubleClickHandler:function(A,B){FCK.RegisteredDoubleClickHandlers[B.toUpperCase()]=A;},OnAfterSetHTML:function(){FCKDocumentProcessor.Process(FCK.EditorDocument);FCKUndo.SaveUndoStep();FCK.Events.FireEvent('OnSelectionChange');FCK.Events.FireEvent('OnAfterSetHTML');},ProtectUrls:function(A){A=A.replace(FCKRegexLib.ProtectUrlsA,'$& _fcksavedurl=$1');A=A.replace(FCKRegexLib.ProtectUrlsImg,'$& _fcksavedurl=$1');return A;},ProtectEvents:function(A){return A.replace(FCKRegexLib.TagsWithEvent,_FCK_ProtectEvents_ReplaceTags);},ProtectEventsRestore:function(A){return A.replace(FCKRegexLib.ProtectedEvents,_FCK_ProtectEvents_RestoreEvents);},ProtectTags:function(A){var B=FCKConfig.ProtectedTags;if (FCKBrowserInfo.IsIE) B+=B.length>0?'|ABBR':'ABBR';var C;if (B.length>0){C=new RegExp('<('+B+')(?!\w|:)','gi');A=A.replace(C,'','gi');A=A.replace(C,'<\/FCK:$1>');};B='META';if (FCKBrowserInfo.IsIE) B+='|HR';C=new RegExp('<(('+B+')(?=\s|>)[\s\S]*?)/?>','gi');A=A.replace(C,'');return A;},SetHTML:function(A,B){this.EditingArea.Mode=FCK.EditMode;if (FCK.EditMode==0){A=FCKConfig.ProtectedSource.Protect(A);A=A.replace(FCKRegexLib.InvalidSelfCloseTags,'$1>');A=FCK.ProtectEvents(A);A=FCK.ProtectUrls(A);A=FCK.ProtectTags(A);if (FCKBrowserInfo.IsGecko){A=A.replace(FCKRegexLib.StrongOpener,'');A=A.replace(FCKRegexLib.EmOpener,'');};this._ForceResetIsDirty=(B===true);var C='';if (FCKConfig.FullPage){if (!FCKRegexLib.HeadOpener.test(A)){if (!FCKRegexLib.HtmlOpener.test(A)) A=''+A+'';A=A.replace(FCKRegexLib.HtmlOpener,'$&');};FCK.DocTypeDeclaration=A.match(FCKRegexLib.DocTypeTag);if (FCKBrowserInfo.IsIE) C=FCK._GetBehaviorsStyle();else if (FCKConfig.ShowBorders) C='';C+='';C=A.replace(FCKRegexLib.HeadCloser,C+'$&');if (FCK.TempBaseTag.length>0&&!FCKRegexLib.HasBaseTag.test(A)) C=C.replace(FCKRegexLib.HeadOpener,'$&'+FCK.TempBaseTag);}else{C=FCKConfig.DocType+'';if (FCKBrowserInfo.IsIE) C+=FCK._GetBehaviorsStyle();else if (FCKConfig.ShowBorders) C+='';C+=FCK.TempBaseTag;var D='0) D+=' id="'+FCKConfig.BodyId+'"';if (FCKConfig.BodyClass&&FCKConfig.BodyClass.length>0) D+=' class="'+FCKConfig.BodyClass+'"';C+=''+D+'>';if (FCKBrowserInfo.IsGecko&&(A.length==0||FCKRegexLib.EmptyParagraph.test(A))) C+=GECKO_BOGUS;else C+=A;C+='';};this.EditingArea.OnLoad=_FCK_EditingArea_OnLoad;this.EditingArea.Start(C);}else{FCK.EditorWindow=null;FCK.EditorDocument=null;this.EditingArea.OnLoad=null;this.EditingArea.Start(A);this.EditingArea.Textarea._FCKShowContextMenu=true;FCK.EnterKeyHandler=null;if (B) this.ResetIsDirty();FCK.KeystrokeHandler.AttachToElement(this.EditingArea.Textarea);this.EditingArea.Textarea.focus();FCK.Events.FireEvent('OnAfterSetHTML');};if (FCKBrowserInfo.IsGecko) window.onresize();},HasFocus:false,RedirectNamedCommands:{},ExecuteNamedCommand:function(A,B,C){FCKUndo.SaveUndoStep();if (!C&&FCK.RedirectNamedCommands[A]!=null) FCK.ExecuteRedirectedNamedCommand(A,B);else{FCK.Focus();FCK.EditorDocument.execCommand(A,false,B);FCK.Events.FireEvent('OnSelectionChange');};FCKUndo.SaveUndoStep();},GetNamedCommandState:function(A){try{if (!FCK.EditorDocument.queryCommandEnabled(A)) return -1;else return FCK.EditorDocument.queryCommandState(A)?1:0;}catch (e){return 0;}},GetNamedCommandValue:function(A){var B='';var C=FCK.GetNamedCommandState(A);if (C==-1) return null;try{B=this.EditorDocument.queryCommandValue(A);}catch(e) {};return B?B:'';},PasteFromWord:function(){FCKDialog.OpenDialog('FCKDialog_Paste',FCKLang.PasteFromWord,'dialog/fck_paste.html',400,330,'Word');},Preview:function(){var A=FCKConfig.ScreenWidth*0.8;var B=FCKConfig.ScreenHeight*0.7;var C=(FCKConfig.ScreenWidth-A)/2;var D=window.open('',null,'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+A+',height='+B+',left='+C);var E;if (FCKConfig.FullPage){if (FCK.TempBaseTag.length>0) E=FCK.TempBaseTag+FCK.GetXHTML();else E=FCK.GetXHTML();}else{E=FCKConfig.DocType+''+FCK.TempBaseTag+''+FCKLang.Preview+''+_FCK_GetEditorAreaStyleTags()+''+FCK.GetXHTML()+'';};D.document.write(E);D.document.close();},SwitchEditMode:function(A){var B=(FCK.EditMode==0);var C=FCK.IsDirty();var D;if (B){if (!A&&FCKBrowserInfo.IsIE) FCKUndo.SaveUndoStep();D=FCK.GetXHTML(FCKConfig.FormatSource);if (D==null) return false;}else D=this.EditingArea.Textarea.value;FCK.EditMode=B?1:0;FCK.SetHTML(D,!C);FCK.Focus();FCKTools.RunFunction(FCK.ToolbarSet.RefreshModeState,FCK.ToolbarSet);return true;},CreateElement:function(A){var e=FCK.EditorDocument.createElement(A);return FCK.InsertElementAndGetIt(e);},InsertElementAndGetIt:function(e){e.setAttribute('FCKTempLabel','true');this.InsertElement(e);var A=FCK.EditorDocument.getElementsByTagName(e.tagName);for (var i=0;i/g,/\r/g,/\n/g],[''',''','"','=','<','>',' ',' '])+'"';};function _FCK_ProtectEvents_RestoreEvents(A,B){return B.ReplaceAll([/'/g,/"/g,/=/g,/</g,/>/g,/ /g,/ /g,/'/g],["'",'"','=','<','>','\r','\n','&']);};function _FCK_EditingArea_OnLoad(){FCK.EditorWindow=FCK.EditingArea.Window;FCK.EditorDocument=FCK.EditingArea.Document;FCK.InitializeBehaviors();if (!FCKConfig.DisableEnterKeyHandler) FCK.EnterKeyHandler=new FCKEnterKey(FCK.EditorWindow,FCKConfig.EnterMode,FCKConfig.ShiftEnterMode);FCK.KeystrokeHandler.AttachToElement(FCK.EditorDocument);if (FCK._ForceResetIsDirty) FCK.ResetIsDirty();if (FCKBrowserInfo.IsIE&&FCK.HasFocus) FCK.EditorDocument.body.setActive();FCK.OnAfterSetHTML();if (FCK.Status!=0) return;FCK.SetStatus(1);};function _FCK_GetEditorAreaStyleTags(){var A='';var B=FCKConfig.EditorAreaCSS;for (var i=0;i';return A;};function _FCK_KeystrokeHandler_OnKeystroke(A,B){if (FCK.Status!=2) return false;if (FCK.EditMode==0){if (B=='Paste') return!FCK.Events.FireEvent('OnPaste');}else{if (B.Equals('Paste','Undo','Redo','SelectAll')) return false;};var C=FCK.Commands.GetCommand(B);return (C.Execute.apply(C,FCKTools.ArgumentsToArray(arguments,2))!==false);};(function(){var A=window.parent.document;var B=A.getElementById(FCK.Name);var i=0;while (B||i==0){if (B&&B.tagName.toLowerCase().Equals('input','textarea')){FCK.LinkedField=B;break;};B=A.getElementsByName(FCK.Name)[i++];}})();var FCKTempBin={Elements:[],AddElement:function(A){var B=this.Elements.length;this.Elements[B]=A;return B;},RemoveElement:function(A){var e=this.Elements[A];this.Elements[A]=null;return e;},Reset:function(){var i=0;while (i0) C+='TABLE { behavior: '+B+' ; }';C+='';FCK._BehaviorsStyle=C;};return FCK._BehaviorsStyle;};function Doc_OnMouseUp(){if (FCK.EditorWindow.event.srcElement.tagName=='HTML'){FCK.Focus();FCK.EditorWindow.event.cancelBubble=true;FCK.EditorWindow.event.returnValue=false;}};function Doc_OnPaste(){return (FCK.Status==2&&FCK.Events.FireEvent("OnPaste"));};function Doc_OnKeyDown(){if (FCK.EditorWindow){var e=FCK.EditorWindow.event;if (!(e.keyCode>=16&&e.keyCode<=18)) Doc_OnKeyDownUndo();};return true;};function Doc_OnKeyDownUndo(){if (!FCKUndo.Typing){FCKUndo.SaveUndoStep();FCKUndo.Typing=true;FCK.Events.FireEvent("OnSelectionChange");};FCKUndo.TypesCount++;if (FCKUndo.TypesCount>FCKUndo.MaxTypes){FCKUndo.TypesCount=0;FCKUndo.SaveUndoStep();}};function Doc_OnDblClick(){FCK.OnDoubleClick(FCK.EditorWindow.event.srcElement);FCK.EditorWindow.event.cancelBubble=true;};function Doc_OnSelectionChange(){FCK.Events.FireEvent("OnSelectionChange");};FCK.InitializeBehaviors=function(A){this.EditorDocument.attachEvent('onmouseup',Doc_OnMouseUp);this.EditorDocument.body.attachEvent('onpaste',Doc_OnPaste);FCK.ContextMenu._InnerContextMenu.AttachToElement(FCK.EditorDocument.body);if (FCKConfig.TabSpaces>0){window.FCKTabHTML='';for (i=0;i '+A;B.getElementById('__fakeFCKRemove__').removeNode(true);};function FCK_PreloadImages(){var A=new FCKImagePreloader();A.AddImages(FCKConfig.PreloadImages);A.AddImages(FCKConfig.SkinPath+'fck_strip.gif');A.OnComplete=LoadToolbarSetup;A.Start();};function Document_OnContextMenu(){return (event.srcElement._FCKShowContextMenu==true);};document.oncontextmenu=Document_OnContextMenu;function FCK_Cleanup(){this.EditorWindow=null;this.EditorDocument=null;};FCK.Paste=function(){if (FCK._PasteIsRunning) return true;if (FCKConfig.ForcePasteAsPlainText){FCK.PasteAsPlainText();return false;};var A=FCK._CheckIsPastingEnabled(true);if (A===false) FCKTools.RunFunction(FCKDialog.OpenDialog,FCKDialog,['FCKDialog_Paste',FCKLang.Paste,'dialog/fck_paste.html',400,330,'Security']);else{if (FCKConfig.AutoDetectPasteFromWord&&A.length>0){var B=/<\w[^>]*(( class="?MsoNormal"?)|(="mso-))/gi;if (B.test(A)){if (confirm(FCKLang.PasteWordConfirm)){FCK.PasteFromWord();return false;}}};FCK._PasteIsRunning=true;FCK.ExecuteNamedCommand('Paste');delete FCK._PasteIsRunning;};return false;};FCK.PasteAsPlainText=function(){if (!FCK._CheckIsPastingEnabled()){FCKDialog.OpenDialog('FCKDialog_Paste',FCKLang.PasteAsText,'dialog/fck_paste.html',400,330,'PlainText');return;};var A=clipboardData.getData("Text");if (A&&A.length>0){A=FCKTools.HTMLEncode(A).replace(/\n/g,'
      ');this.InsertHtml(A);}};FCK._CheckIsPastingEnabled=function(A){FCK._PasteIsEnabled=false;document.body.attachEvent('onpaste',FCK_CheckPasting_Listener);var B=FCK.GetClipboardHTML();document.body.detachEvent('onpaste',FCK_CheckPasting_Listener);if (FCK._PasteIsEnabled){if (!A) B=true;}else B=false;delete FCK._PasteIsEnabled;return B;};function FCK_CheckPasting_Listener(){FCK._PasteIsEnabled=true;};FCK.InsertElement=function(A){FCK.InsertHtml(A.outerHTML);};FCK.GetClipboardHTML=function(){var A=document.getElementById('___FCKHiddenDiv');if (!A){A=document.createElement('DIV');A.id='___FCKHiddenDiv';var B=A.style;B.position='absolute';B.visibility=B.overflow='hidden';B.width=B.height=1;document.body.appendChild(A);};A.innerHTML='';var C=document.body.createTextRange();C.moveToElementText(A);C.execCommand('Paste');var D=A.innerHTML;A.innerHTML='';return D;};FCK.AttachToOnSelectionChange=function(A){this.Events.AttachEvent('OnSelectionChange',A);};FCK.CreateLink=function(A){FCK.ExecuteNamedCommand('Unlink');if (A.length>0){var B='javascript:void(0);/*'+(new Date().getTime())+'*/';FCK.ExecuteNamedCommand('CreateLink',B);var C=this.EditorDocument.links;for (i=0;i0&&!isNaN(E)) this.PageConfig[D]=parseInt(E,10);else this.PageConfig[D]=E;}};function FCKConfig_LoadPageConfig(){var A=FCKConfig.PageConfig;for (var B in A) FCKConfig[B]=A[B];};function FCKConfig_PreProcess(){var A=FCKConfig;if (A.AllowQueryStringDebug){try{if ((/fckdebug=true/i).test(window.top.location.search)) A.Debug=true;}catch (e) {/*Ignore it. Much probably we are inside a FRAME where the "top" is in another domain (security error).*/}};if (!A.PluginsPath.EndsWith('/')) A.PluginsPath+='/';if (typeof(A.EditorAreaCSS)=='string') A.EditorAreaCSS=[A.EditorAreaCSS];var B=A.ToolbarComboPreviewCSS;if (!B||B.length==0) A.ToolbarComboPreviewCSS=A.EditorAreaCSS;else if (typeof(B)=='string') A.ToolbarComboPreviewCSS=[B];};FCKConfig.ToolbarSets={};FCKConfig.Plugins={};FCKConfig.Plugins.Items=[];FCKConfig.Plugins.Add=function(A,B,C){FCKConfig.Plugins.Items.AddItem([A,B,C]);};FCKConfig.ProtectedSource={};FCKConfig.ProtectedSource.RegexEntries=[//g,//gi,//gi];FCKConfig.ProtectedSource.Add=function(A){this.RegexEntries.AddItem(A);};FCKConfig.ProtectedSource.Protect=function(A){function _Replace(protectedSource){var B=FCKTempBin.AddElement(protectedSource);return '';};for (var i=0;i|>)/g,_Replace);} -var FCKDebug={};FCKDebug._GetWindow=function(){if (!this.DebugWindow||this.DebugWindow.closed) this.DebugWindow=window.open(FCKConfig.BasePath+'fckdebug.html','FCKeditorDebug','menubar=no,scrollbars=yes,resizable=yes,location=no,toolbar=no,width=600,height=500',true);return this.DebugWindow;};FCKDebug.Output=function(A,B,C){if (!FCKConfig.Debug) return;try{this._GetWindow().Output(A,B);}catch (e) {}};FCKDebug.OutputObject=function(A,B){if (!FCKConfig.Debug) return;try{this._GetWindow().OutputObject(A,B);}catch (e) {}} -var FCKDomTools={MoveChildren:function(A,B){if (A==B) return;var C;while ((C=A.firstChild)) B.appendChild(A.removeChild(C));},TrimNode:function(A,B){this.LTrimNode(A);this.RTrimNode(A,B);},LTrimNode:function(A){var B;while ((B=A.firstChild)){if (B.nodeType==3){var C=B.nodeValue.LTrim();var D=B.nodeValue.length;if (C.length==0){A.removeChild(B);continue;}else if (C.length0) break;if (A.lastChild) A=A.lastChild;else return this.GetPreviousSourceElement(A,B,C,D);};return null;},GetNextSourceElement:function(A,B,C,D){if (!A) return null;if (A.nextSibling) A=A.nextSibling;else return this.GetNextSourceElement(A.parentNode,B,C,D);while (A){if (A.nodeType==1){if (C&&A.nodeName.IEquals(C)) break;if (!D||!A.nodeName.IEquals(D)) return A;}else if (B&&A.nodeType==3&&A.nodeValue.RTrim().length>0) break;if (A.firstChild) A=A.firstChild;else return this.GetNextSourceElement(A,B,C,D);};return null;},InsertAfterNode:function(A,B){return A.parentNode.insertBefore(B,A.nextSibling);},GetParents:function(A){var B=[];while (A){B.splice(0,0,A);A=A.parentNode;};return B;},GetIndexOf:function(A){var B=A.parentNode?A.parentNode.firstChild:null;var C=-1;while (B){C++;if (B==A) return C;B=B.nextSibling;};return-1;}}; -var GECKO_BOGUS='
      ';var FCKTools={};FCKTools.CreateBogusBR=function(A){var B=A.createElement('br');B.setAttribute('type','_moz');return B;};FCKTools.AppendStyleSheet=function(A,B){if (typeof(B)=='string') return this._AppendStyleSheet(A,B);else{var C=[];for (var i=0;i/g,'>');return A;};FCKTools.HTMLDecode=function(A){if (!A) return '';A=A.replace(/>/g,'>');A=A.replace(/</g,'<');A=A.replace(/&/g,'&');return A;};FCKTools.AddSelectOption=function(A,B,C){var D=FCKTools.GetElementDocument(A).createElement("OPTION");D.text=B;D.value=C;A.options.add(D);return D;};FCKTools.RunFunction=function(A,B,C,D){if (A) this.SetTimeout(A,0,B,C,D);};FCKTools.SetTimeout=function(A,B,C,D,E){return (E||window).setTimeout(function(){if (D) A.apply(C,[].concat(D));else A.apply(C);},B);};FCKTools.SetInterval=function(A,B,C,D,E){return (E||window).setInterval(function(){A.apply(C,D||[]);},B);};FCKTools.ConvertStyleSizeToHtml=function(A){return A.EndsWith('%')?A:parseInt(A,10);};FCKTools.ConvertHtmlSizeToStyle=function(A){return A.EndsWith('%')?A:(A+'px');};FCKTools.GetElementAscensor=function(A,B){var e=A;var C=","+B.toUpperCase()+",";while (e){if (C.indexOf(","+e.nodeName.toUpperCase()+",")!=-1) return e;e=e.parentNode;};return null;};FCKTools.CreateEventListener=function(A,B){var f=function(){var C=[];for (var i=0;i0) B[B.length]=C;};return B;};FCKTools.RemoveOuterTags=function(e){e.insertAdjacentHTML('beforeBegin',e.innerHTML);e.parentNode.removeChild(e);};FCKTools.CreateXmlObject=function(A){var B;switch (A){case 'XmlHttp':B=['MSXML2.XmlHttp','Microsoft.XmlHttp'];break;case 'DOMDocument':B=['MSXML2.DOMDocument','Microsoft.XmlDom'];break;};for (var i=0;i<2;i++){try { return new ActiveXObject(B[i]);}catch (e){}};if (FCKLang.NoActiveX){alert(FCKLang.NoActiveX);FCKLang.NoActiveX=null;};return null;};FCKTools.DisableSelection=function(A){A.unselectable='on';var e,i=0;while ((e=A.all[i++])){switch (e.tagName){case 'IFRAME':case 'TEXTAREA':case 'INPUT':case 'SELECT':break;default:e.unselectable='on';}}};FCKTools.GetScrollPosition=function(A){var B=A.document;var C={ X:B.documentElement.scrollLeft,Y:B.documentElement.scrollTop };if (C.X>0||C.Y>0) return C;return { X:B.body.scrollLeft,Y:B.body.scrollTop };};FCKTools.AddEventListener=function(A,B,C){A.attachEvent('on'+B,C);};FCKTools.RemoveEventListener=function(A,B,C){A.detachEvent('on'+B,C);};FCKTools.AddEventListenerEx=function(A,B,C,D){var o={};o.Source=A;o.Params=D||[];o.Listener=function(ev){return C.apply(o.Source,[ev].concat(o.Params));};if (FCK.IECleanup) FCK.IECleanup.AddItem(null,function() { o.Source=null;o.Params=null;});A.attachEvent('on'+B,o.Listener);A=null;D=null;};FCKTools.GetViewPaneSize=function(A){var B;var C=A.document.documentElement;if (C&&C.clientWidth) B=C;else B=top.document.body;if (B) return { Width:B.clientWidth,Height:B.clientHeight };else return { Width:0,Height:0 };};FCKTools.SaveStyles=function(A){var B={};if (A.className.length>0){B.Class=A.className;A.className='';};var C=A.style.cssText;if (C.length>0){B.Inline=C;A.style.cssText='';};return B;};FCKTools.RestoreStyles=function(A,B){A.className=B.Class||'';A.style.cssText=B.Inline||'';};FCKTools.RegisterDollarFunction=function(A){A.$=A.document.getElementById;};FCKTools.AppendElement=function(A,B){return A.appendChild(this.GetElementDocument(A).createElement(B));};FCKTools.ToLowerCase=function(A){return A.toLowerCase();} -var FCKeditorAPI;function InitializeAPI(){var A=window.parent;if (!(FCKeditorAPI=A.FCKeditorAPI)){var B='var FCKeditorAPI = {Version : "2.4.2",VersionBuild : "14978",__Instances : new Object(),GetInstance : function( name ){return this.__Instances[ name ];},_FormSubmit : function(){for ( var name in FCKeditorAPI.__Instances ){var oEditor = FCKeditorAPI.__Instances[ name ] ;if ( oEditor.GetParentForm && oEditor.GetParentForm() == this )oEditor.UpdateLinkedField() ;}this._FCKOriginalSubmit() ;},_FunctionQueue : {Functions : new Array(),IsRunning : false,Add : function( f ){this.Functions.push( f );if ( !this.IsRunning )this.StartNext();},StartNext : function(){var aQueue = this.Functions ;if ( aQueue.length > 0 ){this.IsRunning = true;aQueue[0].call();}else this.IsRunning = false;},Remove : function( f ){var aQueue = this.Functions;var i = 0, fFunc;while( (fFunc = aQueue[ i ]) ){if ( fFunc == f )aQueue.splice( i,1 );i++ ;}this.StartNext();}}}';if (A.execScript) A.execScript(B,'JavaScript');else{if (FCKBrowserInfo.IsGecko10){eval.call(A,B);}else if (FCKBrowserInfo.IsSafari){var C=A.document;var D=C.createElement('script');D.appendChild(C.createTextNode(B));C.documentElement.appendChild(D);}else A.eval(B);};FCKeditorAPI=A.FCKeditorAPI;};FCKeditorAPI.__Instances[FCK.Name]=FCK;};function _AttachFormSubmitToAPI(){var A=FCK.GetParentForm();if (A){FCKTools.AddEventListener(A,'submit',FCK.UpdateLinkedField);if (!A._FCKOriginalSubmit&&(typeof(A.submit)=='function'||(!A.submit.tagName&&!A.submit.length))){A._FCKOriginalSubmit=A.submit;A.submit=FCKeditorAPI._FormSubmit;}}};function FCKeditorAPI_Cleanup(){delete FCKeditorAPI.__Instances[FCK.Name];};FCKTools.AddEventListener(window,'unload',FCKeditorAPI_Cleanup); -var FCKImagePreloader=function(){this._Images=[];};FCKImagePreloader.prototype={AddImages:function(A){if (typeof(A)=='string') A=A.split(';');this._Images=this._Images.concat(A);},Start:function(){var A=this._Images;this._PreloadCount=A.length;for (var i=0;i]*\>)([\s\S]*)(\<\/body\>[\s\S]*)/i,ToReplace:/___fcktoreplace:([\w]+)/ig,MetaHttpEquiv:/http-equiv\s*=\s*["']?([^"' ]+)/i,HasBaseTag:/]*>/i,HeadOpener:/]*>/i,HeadCloser:/<\/head\s*>/i,FCK_Class:/(\s*FCK__[A-Za-z]*\s*)/,ElementName:/(^[a-z_:][\w.\-:]*\w$)|(^[a-z_]$)/,ForceSimpleAmpersand:/___FCKAmp___/g,SpaceNoClose:/\/>/g,EmptyParagraph:/^<([^ >]+)[^>]*>\s*(<\/\1>)?$/,EmptyOutParagraph:/^<([^ >]+)[^>]*>(?:\s*| )(<\/\1>)?$/,TagBody:/>])/gi,StrongCloser:/<\/STRONG>/gi,EmOpener:/])/gi,EmCloser:/<\/EM>/gi,GeckoEntitiesMarker:/#\?-\:/g,ProtectUrlsImg:/]+))/gi,ProtectUrlsA:/]+))/gi,Html4DocType:/HTML 4\.0 Transitional/i,DocTypeTag:/]*>/i,TagsWithEvent:/<[^\>]+ on\w+[\s\r\n]*=[\s\r\n]*?('|")[\s\S]+?\>/g,EventAttributes:/\s(on\w+)[\s\r\n]*=[\s\r\n]*?('|")([\s\S]*?)\2/g,ProtectedEvents:/\s\w+_fckprotectedatt="([^"]+)"/g,StyleProperties:/\S+\s*:/g,InvalidSelfCloseTags:/(<(?!base|meta|link|hr|br|param|img|area|input)([a-zA-Z0-9:]+)[^>]*)\/>/gi}; -var FCKListsLib={BlockElements:{ address:1,blockquote:1,center:1,div:1,dl:1,fieldset:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,noscript:1,ol:1,p:1,pre:1,script:1,table:1,ul:1 },NonEmptyBlockElements:{ p:1,div:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,address:1,pre:1,ol:1,ul:1,li:1,td:1,th:1 },InlineChildReqElements:{ abbr:1,acronym:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,samp:1,small:1,span:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1 },EmptyElements:{ base:1,meta:1,link:1,hr:1,br:1,param:1,img:1,area:1,input:1 },PathBlockElements:{ address:1,blockquote:1,dl:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,p:1,pre:1,ol:1,ul:1,li:1,dt:1,de:1 },PathBlockLimitElements:{ body:1,td:1,th:1,caption:1,form:1 },Setup:function(){if (FCKConfig.EnterMode=='div') this.PathBlockElements.div=1;else this.PathBlockLimitElements.div=1;}}; -var FCKLanguageManager=FCK.Language={AvailableLanguages:{af:'Afrikaans',ar:'Arabic',bg:'Bulgarian',bn:'Bengali/Bangla',bs:'Bosnian',ca:'Catalan',cs:'Czech',da:'Danish',de:'German',el:'Greek',en:'English','en-au':'English (Australia)','en-ca':'English (Canadian)','en-uk':'English (United Kingdom)',eo:'Esperanto',es:'Spanish',et:'Estonian',eu:'Basque',fa:'Persian',fi:'Finnish',fo:'Faroese',fr:'French',gl:'Galician',he:'Hebrew',hi:'Hindi',hr:'Croatian',hu:'Hungarian',it:'Italian',ja:'Japanese',km:'Khmer',ko:'Korean',lt:'Lithuanian',lv:'Latvian',mn:'Mongolian',ms:'Malay',nb:'Norwegian Bokmal',nl:'Dutch',no:'Norwegian',pl:'Polish',pt:'Portuguese (Portugal)','pt-br':'Portuguese (Brazil)',ro:'Romanian',ru:'Russian',sk:'Slovak',sl:'Slovenian',sr:'Serbian (Cyrillic)','sr-latn':'Serbian (Latin)',sv:'Swedish',th:'Thai',tr:'Turkish',uk:'Ukrainian',vi:'Vietnamese',zh:'Chinese Traditional','zh-cn':'Chinese Simplified'},GetActiveLanguage:function(){if (FCKConfig.AutoDetectLanguage){var A;if (navigator.userLanguage) A=navigator.userLanguage.toLowerCase();else if (navigator.language) A=navigator.language.toLowerCase();else{return FCKConfig.DefaultLanguage;};if (A.length>=5){A=A.substr(0,5);if (this.AvailableLanguages[A]) return A;};if (A.length>=2){A=A.substr(0,2);if (this.AvailableLanguages[A]) return A;}};return this.DefaultLanguage;},TranslateElements:function(A,B,C,D){var e=A.getElementsByTagName(B);var E,s;for (var i=0;i0) C+='|'+FCKConfig.AdditionalNumericEntities;FCKXHtmlEntities.EntitiesRegex=new RegExp(C,'g');} -var FCKXHtml={};FCKXHtml.CurrentJobNum=0;FCKXHtml.GetXHTML=function(A,B,C){FCKXHtmlEntities.Initialize();this._NbspEntity=(FCKConfig.ProcessHTMLEntities?'nbsp':'#160');var D=FCK.IsDirty();this._CreateNode=FCKConfig.ForceStrongEm?FCKXHtml_CreateNode_StrongEm:FCKXHtml_CreateNode_Normal;FCKXHtml.SpecialBlocks=[];this.XML=FCKTools.CreateXmlObject('DOMDocument');this.MainNode=this.XML.appendChild(this.XML.createElement('xhtml'));FCKXHtml.CurrentJobNum++;if (B) this._AppendNode(this.MainNode,A);else this._AppendChildNodes(this.MainNode,A,false);var E=this._GetMainXmlString();this.XML=null;E=E.substr(7,E.length-15).Trim();if (FCKBrowserInfo.IsGecko) E=E.replace(/$/,'');E=E.replace(FCKRegexLib.SpaceNoClose,' />');if (FCKConfig.ForceSimpleAmpersand) E=E.replace(FCKRegexLib.ForceSimpleAmpersand,'&');if (C) E=FCKCodeFormatter.Format(E);for (var i=0;i0;if (C) A.appendChild(this.XML.createTextNode(B.replace(FCKXHtmlEntities.EntitiesRegex,FCKXHtml_GetEntity)));return C;};function FCKXHtml_GetEntity(A){var B=FCKXHtmlEntities.Entities[A]||('#'+A.charCodeAt(0));return '#?-:'+B+';';};FCKXHtml._RemoveAttribute=function(A,B,C){var D=A.attributes.getNamedItem(C);if (D&&B.test(D.nodeValue)){var E=D.nodeValue.replace(B,'');if (E.length==0) A.attributes.removeNamedItem(C);else D.nodeValue=E;}};FCKXHtml.TagProcessors={img:function(A,B){if (!A.attributes.getNamedItem('alt')) FCKXHtml._AppendAttribute(A,'alt','');var C=B.getAttribute('_fcksavedurl');if (C!=null) FCKXHtml._AppendAttribute(A,'src',C);return A;},a:function(A,B){if (B.innerHTML.Trim().length==0&&!B.name) return false;var C=B.getAttribute('_fcksavedurl');if (C!=null) FCKXHtml._AppendAttribute(A,'href',C);if (FCKBrowserInfo.IsIE){FCKXHtml._RemoveAttribute(A,FCKRegexLib.FCK_Class,'class');if (B.name) FCKXHtml._AppendAttribute(A,'name',B.name);};A=FCKXHtml._AppendChildNodes(A,B,false);return A;},script:function(A,B){if (!A.attributes.getNamedItem('type')) FCKXHtml._AppendAttribute(A,'type','text/javascript');A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem(B.text)));return A;},style:function(A,B){if (!A.attributes.getNamedItem('type')) FCKXHtml._AppendAttribute(A,'type','text/css');A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem(B.innerHTML)));return A;},title:function(A,B){A.appendChild(FCKXHtml.XML.createTextNode(FCK.EditorDocument.title));return A;},table:function(A,B){if (FCKBrowserInfo.IsIE) FCKXHtml._RemoveAttribute(A,FCKRegexLib.FCK_Class,'class');A=FCKXHtml._AppendChildNodes(A,B,false);return A;},ol:function(A,B,C){if (B.innerHTML.Trim().length==0) return false;var D=C.lastChild;if (D&&D.nodeType==3) D=D.previousSibling;if (D&&D.nodeName.toUpperCase()=='LI'){B._fckxhtmljob=null;FCKXHtml._AppendNode(D,B);return false;};A=FCKXHtml._AppendChildNodes(A,B);return A;},span:function(A,B){if (B.innerHTML.length==0) return false;A=FCKXHtml._AppendChildNodes(A,B,false);return A;},iframe:function(A,B){var C=B.innerHTML;if (FCKBrowserInfo.IsGecko) C=FCKTools.HTMLDecode(C);C=C.replace(/\s_fcksavedurl="[^"]*"/g,'');A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem(C)));return A;}};FCKXHtml.TagProcessors.ul=FCKXHtml.TagProcessors.ol; -FCKXHtml._GetMainXmlString=function(){return this.MainNode.xml;};FCKXHtml._AppendAttributes=function(A,B,C,D){var E=B.attributes;for (var n=0;n0) FCKXHtml._AppendAttribute(A,'shape',D);};return A;};FCKXHtml.TagProcessors['label']=function(A,B){if (B.htmlFor.length>0) FCKXHtml._AppendAttribute(A,'for',B.htmlFor);A=FCKXHtml._AppendChildNodes(A,B);return A;};FCKXHtml.TagProcessors['form']=function(A,B){if (B.acceptCharset&&B.acceptCharset.length>0&&B.acceptCharset!='UNKNOWN') FCKXHtml._AppendAttribute(A,'accept-charset',B.acceptCharset);if (B.name) FCKXHtml._AppendAttribute(A,'name',B.name);A=FCKXHtml._AppendChildNodes(A,B);return A;};FCKXHtml.TagProcessors['textarea']=FCKXHtml.TagProcessors['select']=function(A,B){if (B.name) FCKXHtml._AppendAttribute(A,'name',B.name);A=FCKXHtml._AppendChildNodes(A,B);return A;};FCKXHtml.TagProcessors['div']=function(A,B){if (B.align.length>0) FCKXHtml._AppendAttribute(A,'align',B.align);A=FCKXHtml._AppendChildNodes(A,B,true);return A;} -var FCKCodeFormatter={};FCKCodeFormatter.Init=function(){var A=this.Regex={};A.BlocksOpener=/\<(P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|TITLE|META|LINK|BASE|SCRIPT|LINK|TD|TH|AREA|OPTION)[^\>]*\>/gi;A.BlocksCloser=/\<\/(P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|TITLE|META|LINK|BASE|SCRIPT|LINK|TD|TH|AREA|OPTION)[^\>]*\>/gi;A.NewLineTags=/\<(BR|HR)[^\>]*\>/gi;A.MainTags=/\<\/?(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR)[^\>]*\>/gi;A.LineSplitter=/\s*\n+\s*/g;A.IncreaseIndent=/^\<(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL)[ \/\>]/i;A.DecreaseIndent=/^\<\/(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL)[ \>]/i;A.FormatIndentatorRemove=new RegExp('^'+FCKConfig.FormatIndentator);A.ProtectedTags=/(]*>)([\s\S]*?)(<\/PRE>)/gi;};FCKCodeFormatter._ProtectData=function(A,B,C,D){return B+'___FCKpd___'+FCKCodeFormatter.ProtectedData.AddItem(C)+D;};FCKCodeFormatter.Format=function(A){if (!this.Regex) this.Init();FCKCodeFormatter.ProtectedData=[];var B=A.replace(this.Regex.ProtectedTags,FCKCodeFormatter._ProtectData);B=B.replace(this.Regex.BlocksOpener,'\n$&');B=B.replace(this.Regex.BlocksCloser,'$&\n');B=B.replace(this.Regex.NewLineTags,'$&\n');B=B.replace(this.Regex.MainTags,'\n$&\n');var C='';var D=B.split(this.Regex.LineSplitter);B='';for (var i=0;i=0&&A==FCKUndo.SavedData[FCKUndo.CurrentIndex][0]) return;if (FCKUndo.CurrentIndex+1>=FCKConfig.MaxUndoLevels) FCKUndo.SavedData.shift();else FCKUndo.CurrentIndex++;var B;if (FCK.EditorDocument.selection.type=='Text') B=FCK.EditorDocument.selection.createRange().getBookmark();FCKUndo.SavedData[FCKUndo.CurrentIndex]=[A,B];FCK.Events.FireEvent("OnSelectionChange");};FCKUndo.CheckUndoState=function(){return (FCKUndo.Typing||FCKUndo.CurrentIndex>0);};FCKUndo.CheckRedoState=function(){return (!FCKUndo.Typing&&FCKUndo.CurrentIndex<(FCKUndo.SavedData.length-1));};FCKUndo.Undo=function(){if (FCKUndo.CheckUndoState()){if (FCKUndo.CurrentIndex==(FCKUndo.SavedData.length-1)){FCKUndo.SaveUndoStep();};FCKUndo._ApplyUndoLevel(--FCKUndo.CurrentIndex);FCK.Events.FireEvent("OnSelectionChange");}};FCKUndo.Redo=function(){if (FCKUndo.CheckRedoState()){FCKUndo._ApplyUndoLevel(++FCKUndo.CurrentIndex);FCK.Events.FireEvent("OnSelectionChange");}};FCKUndo._ApplyUndoLevel=function(A){var B=FCKUndo.SavedData[A];if (!B) return;FCK.SetInnerHtml(B[0]);if (B[1]){var C=FCK.EditorDocument.selection.createRange();C.moveToBookmark(B[1]);C.select();};FCKUndo.TypesCount=0;FCKUndo.Typing=false;} -var FCKEditingArea=function(A){this.TargetElement=A;this.Mode=0;if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKEditingArea_Cleanup);};FCKEditingArea.prototype.Start=function(A,B){var C=this.TargetElement;var D=FCKTools.GetElementDocument(C);while(C.childNodes.length>0) C.removeChild(C.childNodes[0]);if (this.Mode==0){var E=this.IFrame=D.createElement('iframe');E.src='javascript:void(0)';E.frameBorder=0;E.width=E.height='100%';C.appendChild(E);if (FCKBrowserInfo.IsIE) A=A.replace(/(]*?)\s*\/?>(?!\s*<\/base>)/gi,'$1>');else if (!B){if (FCKBrowserInfo.IsGecko) A=A.replace(/(]*>)\s*(<\/body>)/i,'$1'+GECKO_BOGUS+'$2');var F=A.match(FCKRegexLib.BodyContents);if (F){A=F[1]+' '+F[3];this._BodyHTML=F[2];}else this._BodyHTML=A;};this.Window=E.contentWindow;var G=this.Document=this.Window.document;G.open();G.write(A);G.close();if (FCKBrowserInfo.IsGecko10&&!B){this.Start(A,true);return;};this.Window._FCKEditingArea=this;if (FCKBrowserInfo.IsGecko10) this.Window.setTimeout(FCKEditingArea_CompleteStart,500);else FCKEditingArea_CompleteStart.call(this.Window);}else{var H=this.Textarea=D.createElement('textarea');H.className='SourceField';H.dir='ltr';H.style.width=H.style.height='100%';H.style.border='none';C.appendChild(H);H.value=A;FCKTools.RunFunction(this.OnLoad);}};function FCKEditingArea_CompleteStart(){if (!this.document.body){this.setTimeout(FCKEditingArea_CompleteStart,50);return;};var A=this._FCKEditingArea;A.MakeEditable();FCKTools.RunFunction(A.OnLoad);};FCKEditingArea.prototype.MakeEditable=function(){var A=this.Document;if (FCKBrowserInfo.IsIE){A.body.contentEditable=true;}else{try{A.body.spellcheck=(this.FFSpellChecker!==false);if (this._BodyHTML){A.body.innerHTML=this._BodyHTML;this._BodyHTML=null;};A.designMode='on';try{A.execCommand('styleWithCSS',false,FCKConfig.GeckoUseSPAN);}catch (e){A.execCommand('useCSS',false,!FCKConfig.GeckoUseSPAN);};A.execCommand('enableObjectResizing',false,!FCKConfig.DisableObjectResizing);A.execCommand('enableInlineTableEditing',false,!FCKConfig.DisableFFTableHandles);}catch (e) {}}};FCKEditingArea.prototype.Focus=function(){try{if (this.Mode==0){if (FCKBrowserInfo.IsIE&&this.Document.hasFocus()) return;if (FCKBrowserInfo.IsSafari) this.IFrame.focus();else{this.Window.focus();}}else{var A=FCKTools.GetElementDocument(this.Textarea);if ((!A.hasFocus||A.hasFocus())&&A.activeElement==this.Textarea) return;this.Textarea.focus();}}catch(e) {}};function FCKEditingArea_Cleanup(){this.TargetElement=null;this.IFrame=null;this.Document=null;this.Textarea=null;if (this.Window){this.Window._FCKEditingArea=null;this.Window=null;}}; -var FCKKeystrokeHandler=function(A){this.Keystrokes={};this.CancelCtrlDefaults=(A!==false);};FCKKeystrokeHandler.prototype.AttachToElement=function(A){FCKTools.AddEventListenerEx(A,'keydown',_FCKKeystrokeHandler_OnKeyDown,this);if (FCKBrowserInfo.IsGecko10||FCKBrowserInfo.IsOpera||(FCKBrowserInfo.IsGecko&&FCKBrowserInfo.IsMac)) FCKTools.AddEventListenerEx(A,'keypress',_FCKKeystrokeHandler_OnKeyPress,this);};FCKKeystrokeHandler.prototype.SetKeystrokes=function(){for (var i=0;i40))){B._CancelIt=true;if (A.preventDefault) return A.preventDefault();A.returnValue=false;A.cancelBubble=true;return false;};return true;};function _FCKKeystrokeHandler_OnKeyPress(A,B){if (B._CancelIt){if (A.preventDefault) return A.preventDefault();return false;};return true;} -var FCKListHandler={OutdentListItem:function(A){var B=A.parentNode;if (B.tagName.toUpperCase().Equals('UL','OL')){var C=FCKTools.GetElementDocument(A);var D=new FCKDocumentFragment(C);var E=D.RootNode;var F=false;var G=FCKDomTools.GetFirstChild(A,['UL','OL']);if (G){F=true;var H;while ((H=G.firstChild)) E.appendChild(G.removeChild(H));FCKDomTools.RemoveNode(G);};var I;var J=false;while ((I=A.nextSibling)){if (!F&&I.nodeType==1&&I.nodeName.toUpperCase()=='LI') J=F=true;E.appendChild(I.parentNode.removeChild(I));if (!J&&I.nodeType==1&&I.nodeName.toUpperCase().Equals('UL','OL')) FCKDomTools.RemoveNode(I,true);};var K=B.parentNode.tagName.toUpperCase();var L=(K=='LI');if (L||K.Equals('UL','OL')){if (F){var G=B.cloneNode(false);D.AppendTo(G);A.appendChild(G);}else if (L) D.InsertAfterNode(B.parentNode);else D.InsertAfterNode(B);if (L) FCKDomTools.InsertAfterNode(B.parentNode,B.removeChild(A));else FCKDomTools.InsertAfterNode(B,B.removeChild(A));}else{if (F){var N=B.cloneNode(false);D.AppendTo(N);FCKDomTools.InsertAfterNode(B,N);};var O=C.createElement(FCKConfig.EnterMode=='p'?'p':'div');FCKDomTools.MoveChildren(B.removeChild(A),O);FCKDomTools.InsertAfterNode(B,O);if (FCKConfig.EnterMode=='br'){if (FCKBrowserInfo.IsGecko) O.parentNode.insertBefore(FCKTools.CreateBogusBR(C),O);else FCKDomTools.InsertAfterNode(O,FCKTools.CreateBogusBR(C));FCKDomTools.RemoveNode(O,true);}};if (this.CheckEmptyList(B)) FCKDomTools.RemoveNode(B,true);}},CheckEmptyList:function(A){return (FCKDomTools.GetFirstChild(A,'LI')==null);},CheckListHasContents:function(A){var B=A.firstChild;while (B){switch (B.nodeType){case 1:if (!B.nodeName.IEquals('UL','LI')) return true;break;case 3:if (B.nodeValue.Trim().length>0) return true;};B=B.nextSibling;};return false;}}; -var FCKElementPath=function(A){var B=null;var C=null;var D=[];var e=A;while (e){if (e.nodeType==1){if (!this.LastElement) this.LastElement=e;var E=e.nodeName.toLowerCase();if (!C){if (!B&&FCKListsLib.PathBlockElements[E]!=null) B=e;if (FCKListsLib.PathBlockLimitElements[E]!=null) C=e;};D.push(e);if (E=='body') break;};e=e.parentNode;};this.Block=B;this.BlockLimit=C;this.Elements=D;}; -var FCKDomRange=function(A){this.Window=A;};FCKDomRange.prototype={_UpdateElementInfo:function(){if (!this._Range) this.Release(true);else{var A=this._Range.startContainer;var B=this._Range.endContainer;var C=new FCKElementPath(A);this.StartContainer=C.LastElement;this.StartBlock=C.Block;this.StartBlockLimit=C.BlockLimit;if (A!=B) C=new FCKElementPath(B);this.EndContainer=C.LastElement;this.EndBlock=C.Block;this.EndBlockLimit=C.BlockLimit;}},CreateRange:function(){return new FCKW3CRange(this.Window.document);},DeleteContents:function(){if (this._Range){this._Range.deleteContents();this._UpdateElementInfo();}},ExtractContents:function(){if (this._Range){var A=this._Range.extractContents();this._UpdateElementInfo();return A;}},CheckIsCollapsed:function(){if (this._Range) return this._Range.collapsed;},Collapse:function(A){if (this._Range) this._Range.collapse(A);this._UpdateElementInfo();},Clone:function(){var A=FCKTools.CloneObject(this);if (this._Range) A._Range=this._Range.cloneRange();return A;},MoveToNodeContents:function(A){if (!this._Range) this._Range=this.CreateRange();this._Range.selectNodeContents(A);this._UpdateElementInfo();},MoveToElementStart:function(A){this.SetStart(A,1);this.SetEnd(A,1);},MoveToElementEditStart:function(A){var B;while ((B=A.firstChild)&&B.nodeType==1&&FCKListsLib.EmptyElements[B.nodeName.toLowerCase()]==null) A=B;this.MoveToElementStart(A);},InsertNode:function(A){if (this._Range) this._Range.insertNode(A);},CheckIsEmpty:function(A){if (this.CheckIsCollapsed()) return true;var B=this.Window.document.createElement('div');this._Range.cloneContents().AppendTo(B);FCKDomTools.TrimNode(B,A);return (B.innerHTML.length==0);},CheckStartOfBlock:function(){var A=this.Clone();A.Collapse(true);A.SetStart(A.StartBlock||A.StartBlockLimit,1);var B=A.CheckIsEmpty();A.Release();return B;},CheckEndOfBlock:function(A){var B=this.Clone();B.Collapse(false);B.SetEnd(B.EndBlock||B.EndBlockLimit,2);var C=B.CheckIsCollapsed();if (!C){var D=this.Window.document.createElement('div');B._Range.cloneContents().AppendTo(D);FCKDomTools.TrimNode(D,true);C=true;var E=D;while ((E=E.lastChild)){if (E.previousSibling||E.nodeType!=1||FCKListsLib.InlineChildReqElements[E.nodeName.toLowerCase()]==null){C=false;break;}}};B.Release();if (A) this.Select();return C;},CreateBookmark:function(){var A={StartId:'fck_dom_range_start_'+(new Date()).valueOf()+'_'+Math.floor(Math.random()*1000),EndId:'fck_dom_range_end_'+(new Date()).valueOf()+'_'+Math.floor(Math.random()*1000)};var B=this.Window.document;var C;var D;if (!this.CheckIsCollapsed()){C=B.createElement('span');C.id=A.EndId;C.innerHTML=' ';D=this.Clone();D.Collapse(false);D.InsertNode(C);};C=B.createElement('span');C.id=A.StartId;C.innerHTML=' ';D=this.Clone();D.Collapse(true);D.InsertNode(C);return A;},MoveToBookmark:function(A,B){var C=this.Window.document;var D=C.getElementById(A.StartId);var E=C.getElementById(A.EndId);this.SetStart(D,3);if (!B) FCKDomTools.RemoveNode(D);if (E){this.SetEnd(E,3);if (!B) FCKDomTools.RemoveNode(E);}else this.Collapse(true);},SetStart:function(A,B){var C=this._Range;if (!C) C=this._Range=this.CreateRange();switch(B){case 1:C.setStart(A,0);break;case 2:C.setStart(A,A.childNodes.length);break;case 3:C.setStartBefore(A);break;case 4:C.setStartAfter(A);};this._UpdateElementInfo();},SetEnd:function(A,B){var C=this._Range;if (!C) C=this._Range=this.CreateRange();switch(B){case 1:C.setEnd(A,0);break;case 2:C.setEnd(A,A.childNodes.length);break;case 3:C.setEndBefore(A);break;case 4:C.setEndAfter(A);};this._UpdateElementInfo();},Expand:function(A){var B,oSibling;switch (A){case 'block_contents':if (this.StartBlock) this.SetStart(this.StartBlock,1);else{B=this._Range.startContainer;if (B.nodeType==1){if (!(B=B.childNodes[this._Range.startOffset])) B=B.firstChild;};if (!B) return;while (true){oSibling=B.previousSibling;if (!oSibling){if (B.parentNode!=this.StartBlockLimit) B=B.parentNode;else break;}else if (oSibling.nodeType!=1||!(/^(?:P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|DT|DE)$/).test(oSibling.nodeName.toUpperCase())){B=oSibling;}else break;};this._Range.setStartBefore(B);};if (this.EndBlock) this.SetEnd(this.EndBlock,2);else{B=this._Range.endContainer;if (B.nodeType==1) B=B.childNodes[this._Range.endOffset]||B.lastChild;if (!B) return;while (true){oSibling=B.nextSibling;if (!oSibling){if (B.parentNode!=this.EndBlockLimit) B=B.parentNode;else break;}else if (oSibling.nodeType!=1||!(/^(?:P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|DT|DE)$/).test(oSibling.nodeName.toUpperCase())){B=oSibling;}else break;};this._Range.setEndAfter(B);};this._UpdateElementInfo();}},Release:function(A){if (!A) this.Window=null;this.StartContainer=null;this.StartBlock=null;this.StartBlockLimit=null;this.EndContainer=null;this.EndBlock=null;this.EndBlockLimit=null;this._Range=null;}}; -FCKDomRange.prototype.MoveToSelection=function(){this.Release(true);this._Range=new FCKW3CRange(this.Window.document);var A=this.Window.document.selection;if (A.type!='Control'){B=this._GetSelectionMarkerTag(true);this._Range.setStart(B.parentNode,FCKDomTools.GetIndexOf(B));B.parentNode.removeChild(B);var B=this._GetSelectionMarkerTag(false);this._Range.setEnd(B.parentNode,FCKDomTools.GetIndexOf(B));B.parentNode.removeChild(B);this._UpdateElementInfo();}else{var C=A.createRange().item(0);if (C){this._Range.setStartBefore(C);this._Range.setEndAfter(C);this._UpdateElementInfo();}}};FCKDomRange.prototype.Select=function(){if (this._Range){var A=this.CheckIsCollapsed();var B=this._GetRangeMarkerTag(true);if (!A) var C=this._GetRangeMarkerTag(false);var D=this.Window.document.body.createTextRange();D.moveToElementText(B);D.moveStart('character',1);if (!A){var E=this.Window.document.body.createTextRange();E.moveToElementText(C);D.setEndPoint('EndToEnd',E);D.moveEnd('character',-1);};this._Range.setStartBefore(B);B.parentNode.removeChild(B);if (A){try{D.pasteHTML(' ');D.moveStart('character',-1);}catch (e){};D.select();D.pasteHTML('');}else{this._Range.setEndBefore(C);C.parentNode.removeChild(C);D.select();}}};FCKDomRange.prototype._GetSelectionMarkerTag=function(A){var B=this.Window.document.selection.createRange();B.collapse(A===true);var C='fck_dom_range_temp_'+(new Date()).valueOf()+'_'+Math.floor(Math.random()*1000);B.pasteHTML('');return this.Window.document.getElementById(C);};FCKDomRange.prototype._GetRangeMarkerTag=function(A){var B=this._Range;if (!A){B=B.cloneRange();B.collapse(A===true);};var C=this.Window.document.createElement('span');C.innerHTML=' ';B.insertNode(C);return C;} -var FCKDocumentFragment=function(A){this._Document=A;this.RootNode=A.createElement('div');};FCKDocumentFragment.prototype={AppendTo:function(A){FCKDomTools.MoveChildren(this.RootNode,A);},AppendHtml:function(A){var B=this._Document.createElement('div');B.innerHTML=A;FCKDomTools.MoveChildren(B,this.RootNode);},InsertAfterNode:function(A){var B=this.RootNode;var C;while((C=B.lastChild)) FCKDomTools.InsertAfterNode(A,B.removeChild(C));}}; -var FCKW3CRange=function(A){this._Document=A;this.startContainer=null;this.startOffset=null;this.endContainer=null;this.endOffset=null;this.collapsed=true;};FCKW3CRange.CreateRange=function(A){return new FCKW3CRange(A);};FCKW3CRange.CreateFromRange=function(A,B){var C=FCKW3CRange.CreateRange(A);C.setStart(B.startContainer,B.startOffset);C.setEnd(B.endContainer,B.endOffset);return C;};FCKW3CRange.prototype={_UpdateCollapsed:function(){this.collapsed=(this.startContainer==this.endContainer&&this.startOffset==this.endOffset);},setStart:function(A,B){this.startContainer=A;this.startOffset=B;if (!this.endContainer){this.endContainer=A;this.endOffset=B;};this._UpdateCollapsed();},setEnd:function(A,B){this.endContainer=A;this.endOffset=B;if (!this.startContainer){this.startContainer=A;this.startOffset=B;};this._UpdateCollapsed();},setStartAfter:function(A){this.setStart(A.parentNode,FCKDomTools.GetIndexOf(A)+1);},setStartBefore:function(A){this.setStart(A.parentNode,FCKDomTools.GetIndexOf(A));},setEndAfter:function(A){this.setEnd(A.parentNode,FCKDomTools.GetIndexOf(A)+1);},setEndBefore:function(A){this.setEnd(A.parentNode,FCKDomTools.GetIndexOf(A));},collapse:function(A){if (A){this.endContainer=this.startContainer;this.endOffset=this.startOffset;}else{this.startContainer=this.endContainer;this.startOffset=this.endOffset;};this.collapsed=true;},selectNodeContents:function(A){this.setStart(A,0);this.setEnd(A,A.nodeType==3?A.data.length:A.childNodes.length);},insertNode:function(A){var B=this.startContainer;var C=this.startOffset;if (B.nodeType==3){B.splitText(C);if (B==this.endContainer) this.setEnd(B.nextSibling,this.endOffset-this.startOffset);FCKDomTools.InsertAfterNode(B,A);return;}else{B.insertBefore(A,B.childNodes[C]||null);if (B==this.endContainer){this.endOffset++;this.collapsed=false;}}},deleteContents:function(){if (this.collapsed) return;this._ExecContentsAction(0);},extractContents:function(){var A=new FCKDocumentFragment(this._Document);if (!this.collapsed) this._ExecContentsAction(1,A);return A;},cloneContents:function(){var A=new FCKDocumentFragment(this._Document);if (!this.collapsed) this._ExecContentsAction(2,A);return A;},_ExecContentsAction:function(A,B){var C=this.startContainer;var D=this.endContainer;var E=this.startOffset;var F=this.endOffset;var G=false;var H=false;if (D.nodeType==3) D=D.splitText(F);else{if (D.childNodes.length>0){if (F>D.childNodes.length-1){D=FCKDomTools.InsertAfterNode(D.lastChild,this._Document.createTextNode(''));H=true;}else D=D.childNodes[F];}};if (C.nodeType==3){C.splitText(E);if (C==D) D=C.nextSibling;}else{if (C.childNodes.length>0&&E<=C.childNodes.length-1){if (E==0){C=C.insertBefore(this._Document.createTextNode(''),C.firstChild);G=true;}else C=C.childNodes[E].previousSibling;}};var I=FCKDomTools.GetParents(C);var J=FCKDomTools.GetParents(D);var i,topStart,topEnd;for (i=0;i0&&levelStartNode!=D) levelClone=K.appendChild(levelStartNode.cloneNode(levelStartNode==D));if (!I[k]||levelStartNode.parentNode!=I[k].parentNode){currentNode=levelStartNode.previousSibling;while(currentNode){if (currentNode==I[k]||currentNode==C) break;currentSibling=currentNode.previousSibling;if (A==2) K.insertBefore(currentNode.cloneNode(true),K.firstChild);else{currentNode.parentNode.removeChild(currentNode);if (A==1) K.insertBefore(currentNode,K.firstChild);};currentNode=currentSibling;}};if (K) K=levelClone;};if (A==2){var L=this.startContainer;if (L.nodeType==3){L.data+=L.nextSibling.data;L.parentNode.removeChild(L.nextSibling);};var M=this.endContainer;if (M.nodeType==3&&M.nextSibling){M.data+=M.nextSibling.data;M.parentNode.removeChild(M.nextSibling);}}else{if (topStart&&topEnd&&(C.parentNode!=topStart.parentNode||D.parentNode!=topEnd.parentNode)) this.setStart(topEnd.parentNode,FCKDomTools.GetIndexOf(topEnd));this.collapse(true);};if(G) C.parentNode.removeChild(C);if(H&&D.parentNode) D.parentNode.removeChild(D);},cloneRange:function(){return FCKW3CRange.CreateFromRange(this._Document,this);},toString:function(){var A=this.cloneContents();var B=this._Document.createElement('div');A.AppendTo(B);return B.textContent||B.innerText;}}; -var FCKEnterKey=function(A,B,C){this.Window=A;this.EnterMode=B||'p';this.ShiftEnterMode=C||'br';var D=new FCKKeystrokeHandler(false);D._EnterKey=this;D.OnKeystroke=FCKEnterKey_OnKeystroke;D.SetKeystrokes([[13,'Enter'],[SHIFT+13,'ShiftEnter'],[8,'Backspace'],[46,'Delete']]);D.AttachToElement(A.document);};function FCKEnterKey_OnKeystroke(A,B){var C=this._EnterKey;try{switch (B){case 'Enter':return C.DoEnter();break;case 'ShiftEnter':return C.DoShiftEnter();break;case 'Backspace':return C.DoBackspace();break;case 'Delete':return C.DoDelete();}}catch (e){};return false;};FCKEnterKey.prototype.DoEnter=function(A,B){this._HasShift=(B===true);var C=A||this.EnterMode;if (C=='br') return this._ExecuteEnterBr();else return this._ExecuteEnterBlock(C);};FCKEnterKey.prototype.DoShiftEnter=function(){return this.DoEnter(this.ShiftEnterMode,true);};FCKEnterKey.prototype.DoBackspace=function(){var A=false;var B=new FCKDomRange(this.Window);B.MoveToSelection();if (!B.CheckIsCollapsed()) return false;var C=B.StartBlock;var D=B.EndBlock;if (B.StartBlockLimit==B.EndBlockLimit&&C&&D){if (!B.CheckIsCollapsed()){var E=B.CheckEndOfBlock();B.DeleteContents();if (C!=D){B.SetStart(D,1);B.SetEnd(D,1);};B.Select();A=(C==D);};if (B.CheckStartOfBlock()){var F=B.StartBlock;var G=FCKDomTools.GetPreviousSourceElement(F,true,['BODY',B.StartBlockLimit.nodeName],['UL','OL']);A=this._ExecuteBackspace(B,G,F);}else if (FCKBrowserInfo.IsGecko){B.Select();}};B.Release();return A;};FCKEnterKey.prototype._ExecuteBackspace=function(A,B,C){var D=false;if (!B&&C.nodeName.IEquals('LI')&&C.parentNode.parentNode.nodeName.IEquals('LI')){this._OutdentWithSelection(C,A);return true;};if (B&&B.nodeName.IEquals('LI')){var E=FCKDomTools.GetLastChild(B,['UL','OL']);while (E){B=FCKDomTools.GetLastChild(E,'LI');E=FCKDomTools.GetLastChild(B,['UL','OL']);}};if (B&&C){if (C.nodeName.IEquals('LI')&&!B.nodeName.IEquals('LI')){this._OutdentWithSelection(C,A);return true;};var F=C.parentNode;var G=B.nodeName.toLowerCase();if (FCKListsLib.EmptyElements[G]!=null||G=='table'){FCKDomTools.RemoveNode(B);D=true;}else{FCKDomTools.RemoveNode(C);while (F.innerHTML.Trim().length==0){var H=F.parentNode;H.removeChild(F);F=H;};FCKDomTools.TrimNode(C);FCKDomTools.TrimNode(B);A.SetStart(B,2);A.Collapse(true);var I=A.CreateBookmark();FCKDomTools.MoveChildren(C,B);A.MoveToBookmark(I);A.Select();D=true;}};return D;};FCKEnterKey.prototype.DoDelete=function(){var A=false;var B=new FCKDomRange(this.Window);B.MoveToSelection();if (B.CheckIsCollapsed()&&B.CheckEndOfBlock(FCKBrowserInfo.IsGecko)){var C=B.StartBlock;var D=FCKDomTools.GetNextSourceElement(C,true,[B.StartBlockLimit.nodeName],['UL','OL']);A=this._ExecuteBackspace(B,C,D);};B.Release();return A;};FCKEnterKey.prototype._ExecuteEnterBlock=function(A,B){var C=B||new FCKDomRange(this.Window);if (!B) C.MoveToSelection();if (C.StartBlockLimit==C.EndBlockLimit){if (!C.StartBlock) this._FixBlock(C,true,A);if (!C.EndBlock) this._FixBlock(C,false,A);var D=C.StartBlock;var E=C.EndBlock;if (!C.CheckIsEmpty()) C.DeleteContents();if (D==E){var F;var G=C.CheckStartOfBlock();var H=C.CheckEndOfBlock();if (G&&!H){F=D.cloneNode(false);if (FCKBrowserInfo.IsGeckoLike) F.innerHTML=GECKO_BOGUS;D.parentNode.insertBefore(F,D);if (FCKBrowserInfo.IsIE){C.MoveToNodeContents(F);C.Select();};C.MoveToElementEditStart(D);}else{if (H){var I=D.tagName.toUpperCase();if (G&&I=='LI'){this._OutdentWithSelection(D,C);C.Release();return true;}else{if ((/^H[1-6]$/).test(I)||this._HasShift) F=this.Window.document.createElement(A);else{F=D.cloneNode(false);this._RecreateEndingTree(D,F);};if (FCKBrowserInfo.IsGeckoLike){F.innerHTML=GECKO_BOGUS;if (G) D.innerHTML=GECKO_BOGUS;}}}else{C.SetEnd(D,2);var J=C.ExtractContents();F=D.cloneNode(false);FCKDomTools.TrimNode(J.RootNode);if (J.RootNode.firstChild.nodeType==1&&J.RootNode.firstChild.tagName.toUpperCase().Equals('UL','OL')) F.innerHTML=GECKO_BOGUS;J.AppendTo(F);if (FCKBrowserInfo.IsGecko){this._AppendBogusBr(D);this._AppendBogusBr(F);}};if (F){FCKDomTools.InsertAfterNode(D,F);C.MoveToElementEditStart(F);if (FCKBrowserInfo.IsGecko) F.scrollIntoView(false);}}}else{C.MoveToElementEditStart(E);};C.Select();};C.Release();return true;};FCKEnterKey.prototype._ExecuteEnterBr=function(A){var B=new FCKDomRange(this.Window);B.MoveToSelection();if (B.StartBlockLimit==B.EndBlockLimit){B.DeleteContents();B.MoveToSelection();var C=B.CheckStartOfBlock();var D=B.CheckEndOfBlock();var E=B.StartBlock?B.StartBlock.tagName.toUpperCase():'';var F=this._HasShift;if (!F&&E=='LI') return this._ExecuteEnterBlock(null,B);if (!F&&D&&(/^H[1-6]$/).test(E)){FCKDebug.Output('BR - Header');FCKDomTools.InsertAfterNode(B.StartBlock,this.Window.document.createElement('br'));if (FCKBrowserInfo.IsGecko) FCKDomTools.InsertAfterNode(B.StartBlock,this.Window.document.createTextNode(''));B.SetStart(B.StartBlock.nextSibling,FCKBrowserInfo.IsIE?3:1);}else{FCKDebug.Output('BR - No Header');var G=this.Window.document.createElement('br');B.InsertNode(G);if (FCKBrowserInfo.IsGecko) FCKDomTools.InsertAfterNode(G,this.Window.document.createTextNode(''));if (D&&FCKBrowserInfo.IsGecko) this._AppendBogusBr(G.parentNode);if (FCKBrowserInfo.IsIE) B.SetStart(G,4);else B.SetStart(G.nextSibling,1);};B.Collapse(true);B.Select();};B.Release();return true;};FCKEnterKey.prototype._FixBlock=function(A,B,C){var D=A.CreateBookmark();A.Collapse(B);A.Expand('block_contents');var E=this.Window.document.createElement(C);A.ExtractContents().AppendTo(E);FCKDomTools.TrimNode(E);A.InsertNode(E);A.MoveToBookmark(D);};FCKEnterKey.prototype._AppendBogusBr=function(A){var B=A.getElementsByTagName('br');if (B) B=B[B.legth-1];if (!B||B.getAttribute('type',2)!='_moz') A.appendChild(FCKTools.CreateBogusBR(this.Window.document));};FCKEnterKey.prototype._RecreateEndingTree=function(A,B){while ((A=A.lastChild)&&A.nodeType==1&&FCKListsLib.InlineChildReqElements[A.nodeName.toLowerCase()]!=null) B=B.insertBefore(A.cloneNode(false),B.firstChild);};FCKEnterKey.prototype._OutdentWithSelection=function(A,B){var C=B.CreateBookmark();FCKListHandler.OutdentListItem(A);B.MoveToBookmark(C);B.Select();} -var FCKDocumentProcessor={};FCKDocumentProcessor._Items=[];FCKDocumentProcessor.AppendNew=function(){var A={};this._Items.AddItem(A);return A;};FCKDocumentProcessor.Process=function(A){var B,i=0;while((B=this._Items[i++])) B.ProcessDocument(A);};var FCKDocumentProcessor_CreateFakeImage=function(A,B){var C=FCK.EditorDocument.createElement('IMG');C.className=A;C.src=FCKConfig.FullBasePath+'images/spacer.gif';C.setAttribute('_fckfakelement','true',0);C.setAttribute('_fckrealelement',FCKTempBin.AddElement(B),0);return C;};if (FCKBrowserInfo.IsIE||FCKBrowserInfo.IsOpera){var FCKAnchorsProcessor=FCKDocumentProcessor.AppendNew();FCKAnchorsProcessor.ProcessDocument=function(A){var B=A.getElementsByTagName('A');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){if (C.name.length>0){if (C.innerHTML!=''){if (FCKBrowserInfo.IsIE) C.className+=' FCK__AnchorC';}else{var D=FCKDocumentProcessor_CreateFakeImage('FCK__Anchor',C.cloneNode(true));D.setAttribute('_fckanchor','true',0);C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}}}};var FCKPageBreaksProcessor=FCKDocumentProcessor.AppendNew();FCKPageBreaksProcessor.ProcessDocument=function(A){var B=A.getElementsByTagName('DIV');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){if (C.style.pageBreakAfter=='always'&&C.childNodes.length==1&&C.childNodes[0].style&&C.childNodes[0].style.display=='none'){var D=FCKDocumentProcessor_CreateFakeImage('FCK__PageBreak',C.cloneNode(true));C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}};var FCKFlashProcessor=FCKDocumentProcessor.AppendNew();FCKFlashProcessor.ProcessDocument=function(A){var B=A.getElementsByTagName('EMBED');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){var D=C.attributes['type'];if ((C.src&&C.src.EndsWith('.swf',true))||(D&&D.nodeValue=='application/x-shockwave-flash')){var E=C.cloneNode(true);if (FCKBrowserInfo.IsIE){var F=['scale','play','loop','menu','wmode','quality'];for (var G=0;G0) A.style.width=FCKTools.ConvertHtmlSizeToStyle(B.width);if (B.height>0) A.style.height=FCKTools.ConvertHtmlSizeToStyle(B.height);};FCK.GetRealElement=function(A){var e=FCKTempBin.Elements[A.getAttribute('_fckrealelement')];if (A.getAttribute('_fckflash')){if (A.style.width.length>0) e.width=FCKTools.ConvertStyleSizeToHtml(A.style.width);if (A.style.height.length>0) e.height=FCKTools.ConvertStyleSizeToHtml(A.style.height);};return e;};if (FCKBrowserInfo.IsIE){FCKDocumentProcessor.AppendNew().ProcessDocument=function(A){var B=A.getElementsByTagName('HR');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){var D=A.createElement('hr');D.mergeAttributes(C,true);FCKDomTools.InsertAfterNode(C,D);C.parentNode.removeChild(C);}}};FCKDocumentProcessor.AppendNew().ProcessDocument=function(A){var B=A.getElementsByTagName('INPUT');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){if (C.type=='hidden'){var D=FCKDocumentProcessor_CreateFakeImage('FCK__InputHidden',C.cloneNode(true));D.setAttribute('_fckinputhidden','true',0);C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}} -var FCKSelection=FCK.Selection={}; -FCKSelection.GetType=function(){return FCK.EditorDocument.selection.type;};FCKSelection.GetSelectedElement=function(){if (this.GetType()=='Control'){var A=FCK.EditorDocument.selection.createRange();if (A&&A.item) return FCK.EditorDocument.selection.createRange().item(0);}};FCKSelection.GetParentElement=function(){switch (this.GetType()){case 'Control':return FCKSelection.GetSelectedElement().parentElement;case 'None':return null;default:return FCK.EditorDocument.selection.createRange().parentElement();}};FCKSelection.SelectNode=function(A){FCK.Focus();FCK.EditorDocument.selection.empty();var B;try{B=FCK.EditorDocument.body.createControlRange();B.addElement(A);}catch(e){B=FCK.EditorDocument.body.createTextRange();B.moveToElementText(A);};B.select();};FCKSelection.Collapse=function(A){FCK.Focus();if (this.GetType()=='Text'){var B=FCK.EditorDocument.selection.createRange();B.collapse(A==null||A===true);B.select();}};FCKSelection.HasAncestorNode=function(A){var B;if (FCK.EditorDocument.selection.type=="Control"){B=this.GetSelectedElement();}else{var C=FCK.EditorDocument.selection.createRange();B=C.parentElement();};while (B){if (B.tagName==A) return true;B=B.parentNode;};return false;};FCKSelection.MoveToAncestorNode=function(A){var B,oRange;if (!FCK.EditorDocument) return null;if (FCK.EditorDocument.selection.type=="Control"){oRange=FCK.EditorDocument.selection.createRange();for (i=0;i=0;i--){var D=B.rows[i];if (C==0&&D.cells.length==1){FCKTableHandler.DeleteRows(D);continue;};if (D.cells[C]) D.removeChild(D.cells[C]);}};FCKTableHandler.InsertCell=function(A){var B=A?A:FCKSelection.MoveToAncestorNode('TD');if (!B) return null;var C=FCK.EditorDocument.createElement('TD');if (FCKBrowserInfo.IsGecko) C.innerHTML=GECKO_BOGUS;if (B.cellIndex==B.parentNode.cells.length-1){B.parentNode.appendChild(C);}else{B.parentNode.insertBefore(C,B.nextSibling);};return C;};FCKTableHandler.DeleteCell=function(A){if (A.parentNode.cells.length==1){FCKTableHandler.DeleteRows(FCKTools.GetElementAscensor(A,'TR'));return;};A.parentNode.removeChild(A);};FCKTableHandler.DeleteCells=function(){var A=FCKTableHandler.GetSelectedCells();for (var i=A.length-1;i>=0;i--){FCKTableHandler.DeleteCell(A[i]);}};FCKTableHandler.MergeCells=function(){var A=FCKTableHandler.GetSelectedCells();if (A.length<2) return;if (A[0].parentNode!=A[A.length-1].parentNode) return;var B=isNaN(A[0].colSpan)?1:A[0].colSpan;var C='';var D=FCK.EditorDocument.createDocumentFragment();for (var i=A.length-1;i>=0;i--){var E=A[i];for (var c=E.childNodes.length-1;c>=0;c--){var F=E.removeChild(E.childNodes[c]);if ((F.hasAttribute&&F.hasAttribute('_moz_editor_bogus_node'))||(F.getAttribute&&F.getAttribute('type',2)=='_moz')) continue;D.insertBefore(F,D.firstChild);};if (i>0){B+=isNaN(E.colSpan)?1:E.colSpan;FCKTableHandler.DeleteCell(E);}};A[0].colSpan=B;if (FCKBrowserInfo.IsGecko&&D.childNodes.length==0) A[0].innerHTML=GECKO_BOGUS;else A[0].appendChild(D);};FCKTableHandler.SplitCell=function(){var A=FCKTableHandler.GetSelectedCells();if (A.length!=1) return;var B=this._CreateTableMap(A[0].parentNode.parentNode);var C=FCKTableHandler._GetCellIndexSpan(B,A[0].parentNode.rowIndex,A[0]);var D=this._GetCollumnCells(B,C);for (var i=0;i1) E.rowSpan=A[0].rowSpan;}else{if (isNaN(D[i].colSpan)) D[i].colSpan=2;else D[i].colSpan+=1;}}};FCKTableHandler._GetCellIndexSpan=function(A,B,C){if (A.length=0&&B.compareEndPoints('StartToEnd',D)<=0)||(B.compareEndPoints('EndToStart',D)>=0&&B.compareEndPoints('EndToEnd',D)<=0)){A[A.length]=C.cells[i];}}}};return A;}; -var FCKXml=function(){this.Error=false;};FCKXml.prototype.LoadUrl=function(A){this.Error=false;var B=FCKTools.CreateXmlObject('XmlHttp');if (!B){this.Error=true;return;};B.open("GET",A,false);B.send(null);if (B.status==200||B.status==304) this.DOMDocument=B.responseXML;else if (B.status==0&&B.readyState==4){this.DOMDocument=FCKTools.CreateXmlObject('DOMDocument');this.DOMDocument.async=false;this.DOMDocument.resolveExternals=false;this.DOMDocument.loadXML(B.responseText);}else{this.DOMDocument=null;};if (this.DOMDocument==null||this.DOMDocument.firstChild==null){this.Error=true;if (window.confirm('Error loading "'+A+'"\r\nDo you want to see more info?')) alert('URL requested: "'+A+'"\r\nServer response:\r\nStatus: '+B.status+'\r\nResponse text:\r\n'+B.responseText);}};FCKXml.prototype.SelectNodes=function(A,B){if (this.Error) return [];if (B) return B.selectNodes(A);else return this.DOMDocument.selectNodes(A);};FCKXml.prototype.SelectSingleNode=function(A,B){if (this.Error) return null;if (B) return B.selectSingleNode(A);else return this.DOMDocument.selectSingleNode(A);} -var FCKStyleDef=function(A,B){this.Name=A;this.Element=B.toUpperCase();this.IsObjectElement=FCKRegexLib.ObjectElements.test(this.Element);this.Attributes={};};FCKStyleDef.prototype.AddAttribute=function(A,B){this.Attributes[A]=B;};FCKStyleDef.prototype.GetOpenerTag=function(){var s='<'+this.Element;for (var a in this.Attributes) s+=' '+a+'="'+this.Attributes[a]+'"';return s+'>';};FCKStyleDef.prototype.GetCloserTag=function(){return '';};FCKStyleDef.prototype.RemoveFromSelection=function(){if (FCKSelection.GetType()=='Control') this._RemoveMe(FCK.ToolbarSet.CurrentInstance.Selection.GetSelectedElement());else this._RemoveMe(FCK.ToolbarSet.CurrentInstance.Selection.GetParentElement());} -FCKStyleDef.prototype.ApplyToSelection=function(){var A=FCK.ToolbarSet.CurrentInstance.EditorDocument.selection;if (A.type=='Text'){var B=A.createRange();var e=document.createElement(this.Element);e.innerHTML=B.htmlText;this._AddAttributes(e);this._RemoveDuplicates(e);B.pasteHTML(e.outerHTML);}else if (A.type=='Control'){var C=FCK.ToolbarSet.CurrentInstance.Selection.GetSelectedElement();if (C.tagName==this.Element) this._AddAttributes(C);}};FCKStyleDef.prototype._AddAttributes=function(A){for (var a in this.Attributes){switch (a.toLowerCase()){case 'style':A.style.cssText=this.Attributes[a];break;case 'class':A.setAttribute('className',this.Attributes[a],0);break;case 'src':A.setAttribute('_fcksavedurl',this.Attributes[a],0);default:A.setAttribute(a,this.Attributes[a],0);}}};FCKStyleDef.prototype._RemoveDuplicates=function(A){for (var i=0;i');else if (A=='div'&&FCKBrowserInfo.IsGecko) FCK.ExecuteNamedCommand('FormatBlock','div');else FCK.ExecuteNamedCommand('FormatBlock','<'+A+'>');};FCKFormatBlockCommand.prototype.GetState=function(){return FCK.GetNamedCommandValue('FormatBlock');};var FCKPreviewCommand=function(){this.Name='Preview';};FCKPreviewCommand.prototype.Execute=function(){FCK.Preview();};FCKPreviewCommand.prototype.GetState=function(){return 0;};var FCKSaveCommand=function(){this.Name='Save';};FCKSaveCommand.prototype.Execute=function(){var A=FCK.GetParentForm();if (typeof(A.onsubmit)=='function'){var B=A.onsubmit();if (B!=null&&B===false) return;};A.submit();};FCKSaveCommand.prototype.GetState=function(){return 0;};var FCKNewPageCommand=function(){this.Name='NewPage';};FCKNewPageCommand.prototype.Execute=function(){FCKUndo.SaveUndoStep();FCK.SetHTML('');FCKUndo.Typing=true;};FCKNewPageCommand.prototype.GetState=function(){return 0;};var FCKSourceCommand=function(){this.Name='Source';};FCKSourceCommand.prototype.Execute=function(){if (FCKConfig.SourcePopup){var A=FCKConfig.ScreenWidth*0.65;var B=FCKConfig.ScreenHeight*0.65;FCKDialog.OpenDialog('FCKDialog_Source',FCKLang.Source,'dialog/fck_source.html',A,B,null,null,true);}else FCK.SwitchEditMode();};FCKSourceCommand.prototype.GetState=function(){return (FCK.EditMode==0?0:1);};var FCKUndoCommand=function(){this.Name='Undo';};FCKUndoCommand.prototype.Execute=function(){if (FCKBrowserInfo.IsIE) FCKUndo.Undo();else FCK.ExecuteNamedCommand('Undo');};FCKUndoCommand.prototype.GetState=function(){if (FCKBrowserInfo.IsIE) return (FCKUndo.CheckUndoState()?0:-1);else return FCK.GetNamedCommandState('Undo');};var FCKRedoCommand=function(){this.Name='Redo';};FCKRedoCommand.prototype.Execute=function(){if (FCKBrowserInfo.IsIE) FCKUndo.Redo();else FCK.ExecuteNamedCommand('Redo');};FCKRedoCommand.prototype.GetState=function(){if (FCKBrowserInfo.IsIE) return (FCKUndo.CheckRedoState()?0:-1);else return FCK.GetNamedCommandState('Redo');};var FCKPageBreakCommand=function(){this.Name='PageBreak';};FCKPageBreakCommand.prototype.Execute=function(){var e=FCK.EditorDocument.createElement('DIV');e.style.pageBreakAfter='always';e.innerHTML=' ';var A=FCKDocumentProcessor_CreateFakeImage('FCK__PageBreak',e);A=FCK.InsertElement(A);};FCKPageBreakCommand.prototype.GetState=function(){return 0;};var FCKUnlinkCommand=function(){this.Name='Unlink';};FCKUnlinkCommand.prototype.Execute=function(){if (FCKBrowserInfo.IsGecko){var A=FCK.Selection.MoveToAncestorNode('A');if (A) FCK.Selection.SelectNode(A);};FCK.ExecuteNamedCommand(this.Name);if (FCKBrowserInfo.IsGecko) FCK.Selection.Collapse(true);};FCKUnlinkCommand.prototype.GetState=function(){var A=FCK.GetNamedCommandState(this.Name);if (A==0&&FCK.EditMode==0){var B=FCKSelection.MoveToAncestorNode('A');var C=(B&&B.name.length>0&&B.href.length==0);if (C) A=-1;};return A;};var FCKSelectAllCommand=function(){this.Name='SelectAll';};FCKSelectAllCommand.prototype.Execute=function(){if (FCK.EditMode==0){FCK.ExecuteNamedCommand('SelectAll');}else{var A=FCK.EditingArea.Textarea;if (FCKBrowserInfo.IsIE){A.createTextRange().execCommand('SelectAll');}else{A.selectionStart=0;A.selectionEnd=A.value.length;};A.focus();}};FCKSelectAllCommand.prototype.GetState=function(){return 0;};var FCKPasteCommand=function(){this.Name='Paste';};FCKPasteCommand.prototype={Execute:function(){if (FCKBrowserInfo.IsIE) FCK.Paste();else FCK.ExecuteNamedCommand('Paste');},GetState:function(){return FCK.GetNamedCommandState('Paste');}}; -var FCKSpellCheckCommand=function(){this.Name='SpellCheck';this.IsEnabled=(FCKConfig.SpellChecker=='ieSpell'||FCKConfig.SpellChecker=='SpellerPages');};FCKSpellCheckCommand.prototype.Execute=function(){switch (FCKConfig.SpellChecker){case 'ieSpell':this._RunIeSpell();break;case 'SpellerPages':FCKDialog.OpenDialog('FCKDialog_SpellCheck','Spell Check','dialog/fck_spellerpages.html',440,480);break;}};FCKSpellCheckCommand.prototype._RunIeSpell=function(){try{var A=new ActiveXObject("ieSpell.ieSpellExtension");A.CheckAllLinkedDocuments(FCK.EditorDocument);}catch(e){if(e.number==-2146827859){if (confirm(FCKLang.IeSpellDownload)) window.open(FCKConfig.IeSpellDownloadUrl,'IeSpellDownload');}else alert('Error Loading ieSpell: '+e.message+' ('+e.number+')');}};FCKSpellCheckCommand.prototype.GetState=function(){return this.IsEnabled?0:-1;} -var FCKTextColorCommand=function(A){this.Name=A=='ForeColor'?'TextColor':'BGColor';this.Type=A;var B;if (FCKBrowserInfo.IsIE) B=window;else if (FCK.ToolbarSet._IFrame) B=FCKTools.GetElementWindow(FCK.ToolbarSet._IFrame);else B=window.parent;this._Panel=new FCKPanel(B,true);this._Panel.AppendStyleSheet(FCKConfig.SkinPath+'fck_editor.css');this._Panel.MainNode.className='FCK_Panel';this._CreatePanelBody(this._Panel.Document,this._Panel.MainNode);FCKTools.DisableSelection(this._Panel.Document.body);};FCKTextColorCommand.prototype.Execute=function(A,B,C){FCK._ActiveColorPanelType=this.Type;this._Panel.Show(A,B,C);};FCKTextColorCommand.prototype.SetColor=function(A){if (FCK._ActiveColorPanelType=='ForeColor') FCK.ExecuteNamedCommand('ForeColor',A);else if (FCKBrowserInfo.IsGeckoLike){if (FCKBrowserInfo.IsGecko&&!FCKConfig.GeckoUseSPAN) FCK.EditorDocument.execCommand('useCSS',false,false);FCK.ExecuteNamedCommand('hilitecolor',A);if (FCKBrowserInfo.IsGecko&&!FCKConfig.GeckoUseSPAN) FCK.EditorDocument.execCommand('useCSS',false,true);}else FCK.ExecuteNamedCommand('BackColor',A);delete FCK._ActiveColorPanelType;};FCKTextColorCommand.prototype.GetState=function(){return 0;};function FCKTextColorCommand_OnMouseOver() { this.className='ColorSelected';};function FCKTextColorCommand_OnMouseOut() { this.className='ColorDeselected';};function FCKTextColorCommand_OnClick(){this.className='ColorDeselected';this.Command.SetColor('#'+this.Color);this.Command._Panel.Hide();};function FCKTextColorCommand_AutoOnClick(){this.className='ColorDeselected';this.Command.SetColor('');this.Command._Panel.Hide();};function FCKTextColorCommand_MoreOnClick(){this.className='ColorDeselected';this.Command._Panel.Hide();FCKDialog.OpenDialog('FCKDialog_Color',FCKLang.DlgColorTitle,'dialog/fck_colorselector.html',400,330,this.Command.SetColor);};FCKTextColorCommand.prototype._CreatePanelBody=function(A,B){function CreateSelectionDiv(){var C=A.createElement("DIV");C.className='ColorDeselected';C.onmouseover=FCKTextColorCommand_OnMouseOver;C.onmouseout=FCKTextColorCommand_OnMouseOut;return C;};var D=B.appendChild(A.createElement("TABLE"));D.className='ForceBaseFont';D.style.tableLayout='fixed';D.cellPadding=0;D.cellSpacing=0;D.border=0;D.width=150;var E=D.insertRow(-1).insertCell(-1);E.colSpan=8;var C=E.appendChild(CreateSelectionDiv());C.innerHTML='\n \n \n \n \n
      '+FCKLang.ColorAutomatic+'
      ';C.Command=this;C.onclick=FCKTextColorCommand_AutoOnClick;var G=FCKConfig.FontColors.toString().split(',');var H=0;while (H
      ';C.Command=this;C.onclick=FCKTextColorCommand_OnClick;}};E=D.insertRow(-1).insertCell(-1);E.colSpan=8;C=E.appendChild(CreateSelectionDiv());C.innerHTML='
      '+FCKLang.ColorMoreColors+'
      ';C.Command=this;C.onclick=FCKTextColorCommand_MoreOnClick;} -var FCKPastePlainTextCommand=function(){this.Name='PasteText';};FCKPastePlainTextCommand.prototype.Execute=function(){FCK.PasteAsPlainText();};FCKPastePlainTextCommand.prototype.GetState=function(){return FCK.GetNamedCommandState('Paste');}; -var FCKPasteWordCommand=function(){this.Name='PasteWord';};FCKPasteWordCommand.prototype.Execute=function(){FCK.PasteFromWord();};FCKPasteWordCommand.prototype.GetState=function(){if (FCKConfig.ForcePasteAsPlainText) return -1;else return FCK.GetNamedCommandState('Paste');}; -var FCKTableCommand=function(A){this.Name=A;};FCKTableCommand.prototype.Execute=function(){FCKUndo.SaveUndoStep();switch (this.Name){case 'TableInsertRow':FCKTableHandler.InsertRow();break;case 'TableDeleteRows':FCKTableHandler.DeleteRows();break;case 'TableInsertColumn':FCKTableHandler.InsertColumn();break;case 'TableDeleteColumns':FCKTableHandler.DeleteColumns();break;case 'TableInsertCell':FCKTableHandler.InsertCell();break;case 'TableDeleteCells':FCKTableHandler.DeleteCells();break;case 'TableMergeCells':FCKTableHandler.MergeCells();break;case 'TableSplitCell':FCKTableHandler.SplitCell();break;case 'TableDelete':FCKTableHandler.DeleteTable();break;default:alert(FCKLang.UnknownCommand.replace(/%1/g,this.Name));}};FCKTableCommand.prototype.GetState=function(){return 0;} -var FCKStyleCommand=function(){this.Name='Style';this.StylesLoader=new FCKStylesLoader();this.StylesLoader.Load(FCKConfig.StylesXmlPath);this.Styles=this.StylesLoader.Styles;};FCKStyleCommand.prototype.Execute=function(A,B){FCKUndo.SaveUndoStep();if (B.Selected) B.Style.RemoveFromSelection();else B.Style.ApplyToSelection();FCKUndo.SaveUndoStep();FCK.Focus();FCK.Events.FireEvent("OnSelectionChange");};FCKStyleCommand.prototype.GetState=function(){if (!FCK.EditorDocument) return -1;var A=FCK.EditorDocument.selection;if (FCKSelection.GetType()=='Control'){var e=FCKSelection.GetSelectedElement();if (e) return this.StylesLoader.StyleGroups[e.tagName]?0:-1;};return 0;};FCKStyleCommand.prototype.GetActiveStyles=function(){var A=[];if (FCKSelection.GetType()=='Control') this._CheckStyle(FCKSelection.GetSelectedElement(),A,false);else this._CheckStyle(FCKSelection.GetParentElement(),A,true);return A;};FCKStyleCommand.prototype._CheckStyle=function(A,B,C){if (!A) return;if (A.nodeType==1){var D=this.StylesLoader.StyleGroups[A.tagName];if (D){for (var i=0;i<\/body><\/html>');B.close();FCKTools.AddEventListenerEx(D,'focus',FCKPanel_Window_OnFocus,this);FCKTools.AddEventListenerEx(D,'blur',FCKPanel_Window_OnBlur,this);};B.dir=FCKLang.Dir;B.oncontextmenu=FCKTools.CancelEvent;this.MainNode=B.body.appendChild(B.createElement('DIV'));this.MainNode.style.cssFloat=this.IsRTL?'right':'left';};FCKPanel.prototype.AppendStyleSheet=function(A){FCKTools.AppendStyleSheet(this.Document,A);};FCKPanel.prototype.Preload=function(x,y,A){if (this._Popup) this._Popup.show(x,y,0,0,A);};FCKPanel.prototype.Show=function(x,y,A,B,C){var D;if (this._Popup){this._Popup.show(x,y,0,0,A);this.MainNode.style.width=B?B+'px':'';this.MainNode.style.height=C?C+'px':'';D=this.MainNode.offsetWidth;if (this.IsRTL){if (this.IsContextMenu) x=x-D+1;else if (A) x=(x*-1)+A.offsetWidth-D;};this._Popup.show(x,y,D,this.MainNode.offsetHeight,A);if (this.OnHide){if (this._Timer) CheckPopupOnHide.call(this,true);this._Timer=FCKTools.SetInterval(CheckPopupOnHide,100,this);}}else{if (typeof(FCKFocusManager)!='undefined') FCKFocusManager.Lock();if (this.ParentPanel) this.ParentPanel.Lock();this.MainNode.style.width=B?B+'px':'';this.MainNode.style.height=C?C+'px':'';D=this.MainNode.offsetWidth;if (!B) this._IFrame.width=1;if (!C) this._IFrame.height=1;D=this.MainNode.offsetWidth;var E=FCKTools.GetElementPosition(A.nodeType==9?(FCKTools.IsStrictMode(A)?A.documentElement:A.body):A,this._Window);if (this.IsRTL&&!this.IsContextMenu) x=(x*-1);x+=E.X;y+=E.Y;if (this.IsRTL){if (this.IsContextMenu) x=x-D+1;else if (A) x=x+A.offsetWidth-D;}else{var F=FCKTools.GetViewPaneSize(this._Window);var G=FCKTools.GetScrollPosition(this._Window);var H=F.Height+G.Y;var I=F.Width+G.X;if ((x+D)>I) x-=x+D-I;if ((y+this.MainNode.offsetHeight)>H) y-=y+this.MainNode.offsetHeight-H;};if (x<0) x=0;this._IFrame.style.left=x+'px';this._IFrame.style.top=y+'px';var J=D;var K=this.MainNode.offsetHeight;this._IFrame.width=J;this._IFrame.height=K;this._IFrame.contentWindow.focus();};this._IsOpened=true;FCKTools.RunFunction(this.OnShow,this);};FCKPanel.prototype.Hide=function(A){if (this._Popup) this._Popup.hide();else{if (!this._IsOpened) return;if (typeof(FCKFocusManager)!='undefined') FCKFocusManager.Unlock();this._IFrame.width=this._IFrame.height=0;this._IsOpened=false;if (this.ParentPanel) this.ParentPanel.Unlock();if (!A) FCKTools.RunFunction(this.OnHide,this);}};FCKPanel.prototype.CheckIsOpened=function(){if (this._Popup) return this._Popup.isOpen;else return this._IsOpened;};FCKPanel.prototype.CreateChildPanel=function(){var A=this._Popup?FCKTools.GetDocumentWindow(this.Document):this._Window;var B=new FCKPanel(A,true);B.ParentPanel=this;return B;};FCKPanel.prototype.Lock=function(){this._LockCounter++;};FCKPanel.prototype.Unlock=function(){if (--this._LockCounter==0&&!this.HasFocus) this.Hide();};function FCKPanel_Window_OnFocus(e,A){A.HasFocus=true;};function FCKPanel_Window_OnBlur(e,A){A.HasFocus=false;if (A._LockCounter==0) FCKTools.RunFunction(A.Hide,A);};function CheckPopupOnHide(A){if (A||!this._Popup.isOpen){window.clearInterval(this._Timer);this._Timer=null;FCKTools.RunFunction(this.OnHide,this);}};function FCKPanel_Cleanup(){this._Popup=null;this._Window=null;this.Document=null;this.MainNode=null;} -var FCKIcon=function(A){var B=A?typeof(A):'undefined';switch (B){case 'number':this.Path=FCKConfig.SkinPath+'fck_strip.gif';this.Size=16;this.Position=A;break;case 'undefined':this.Path=FCK_SPACER_PATH;break;case 'string':this.Path=A;break;default:this.Path=A[0];this.Size=A[1];this.Position=A[2];}};FCKIcon.prototype.CreateIconElement=function(A){var B,eIconImage;if (this.Position){var C='-'+((this.Position-1)*this.Size)+'px';if (FCKBrowserInfo.IsIE){B=A.createElement('DIV');eIconImage=B.appendChild(A.createElement('IMG'));eIconImage.src=this.Path;eIconImage.style.top=C;}else{B=A.createElement('IMG');B.src=FCK_SPACER_PATH;B.style.backgroundPosition='0px '+C;B.style.backgroundImage='url('+this.Path+')';}}else{B=A.createElement('DIV');eIconImage=B.appendChild(A.createElement('IMG'));eIconImage.src=this.Path?this.Path:FCK_SPACER_PATH;};B.className='TB_Button_Image';return B;} -var FCKToolbarButtonUI=function(A,B,C,D,E,F){this.Name=A;this.Label=B||A;this.Tooltip=C||this.Label;this.Style=E||0;this.State=F||0;this.Icon=new FCKIcon(D);if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKToolbarButtonUI_Cleanup);};FCKToolbarButtonUI.prototype._CreatePaddingElement=function(A){var B=A.createElement('IMG');B.className='TB_Button_Padding';B.src=FCK_SPACER_PATH;return B;};FCKToolbarButtonUI.prototype.Create=function(A){var B=this.MainElement;if (B){FCKToolbarButtonUI_Cleanup.call(this);if (B.parentNode) B.parentNode.removeChild(B);B=this.MainElement=null;};var C=FCKTools.GetElementDocument(A);B=this.MainElement=C.createElement('DIV');B._FCKButton=this;B.title=this.Tooltip;if (FCKBrowserInfo.IsGecko) B.onmousedown=FCKTools.CancelEvent;this.ChangeState(this.State,true);if (this.Style==0&&!this.ShowArrow){B.appendChild(this.Icon.CreateIconElement(C));}else{var D=B.appendChild(C.createElement('TABLE'));D.cellPadding=0;D.cellSpacing=0;var E=D.insertRow(-1);var F=E.insertCell(-1);if (this.Style==0||this.Style==2) F.appendChild(this.Icon.CreateIconElement(C));else F.appendChild(this._CreatePaddingElement(C));if (this.Style==1||this.Style==2){F=E.insertCell(-1);F.className='TB_Button_Text';F.noWrap=true;F.appendChild(C.createTextNode(this.Label));};if (this.ShowArrow){if (this.Style!=0){E.insertCell(-1).appendChild(this._CreatePaddingElement(C));};F=E.insertCell(-1);var G=F.appendChild(C.createElement('IMG'));G.src=FCKConfig.SkinPath+'images/toolbar.buttonarrow.gif';G.width=5;G.height=3;};F=E.insertCell(-1);F.appendChild(this._CreatePaddingElement(C));};A.appendChild(B);};FCKToolbarButtonUI.prototype.ChangeState=function(A,B){if (!B&&this.State==A) return;var e=this.MainElement;switch (parseInt(A,10)){case 0:e.className='TB_Button_Off';e.onmouseover=FCKToolbarButton_OnMouseOverOff;e.onmouseout=FCKToolbarButton_OnMouseOutOff;e.onclick=FCKToolbarButton_OnClick;break;case 1:e.className='TB_Button_On';e.onmouseover=FCKToolbarButton_OnMouseOverOn;e.onmouseout=FCKToolbarButton_OnMouseOutOn;e.onclick=FCKToolbarButton_OnClick;break;case -1:e.className='TB_Button_Disabled';e.onmouseover=null;e.onmouseout=null;e.onclick=null;break;};this.State=A;};function FCKToolbarButtonUI_Cleanup(){if (this.MainElement){this.MainElement._FCKButton=null;this.MainElement=null;}};function FCKToolbarButton_OnMouseOverOn(){this.className='TB_Button_On_Over';};function FCKToolbarButton_OnMouseOutOn(){this.className='TB_Button_On';};function FCKToolbarButton_OnMouseOverOff(){this.className='TB_Button_Off_Over';};function FCKToolbarButton_OnMouseOutOff(){this.className='TB_Button_Off';};function FCKToolbarButton_OnClick(e){if (this._FCKButton.OnClick) this._FCKButton.OnClick(this._FCKButton);}; -var FCKToolbarButton=function(A,B,C,D,E,F,G){this.CommandName=A;this.Label=B;this.Tooltip=C;this.Style=D;this.SourceView=E?true:false;this.ContextSensitive=F?true:false;if (G==null) this.IconPath=FCKConfig.SkinPath+'toolbar/'+A.toLowerCase()+'.gif';else if (typeof(G)=='number') this.IconPath=[FCKConfig.SkinPath+'fck_strip.gif',16,G];};FCKToolbarButton.prototype.Create=function(A){this._UIButton=new FCKToolbarButtonUI(this.CommandName,this.Label,this.Tooltip,this.IconPath,this.Style);this._UIButton.OnClick=this.Click;this._UIButton._ToolbarButton=this;this._UIButton.Create(A);};FCKToolbarButton.prototype.RefreshState=function(){var A=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetState();if (A==this._UIButton.State) return;this._UIButton.ChangeState(A);};FCKToolbarButton.prototype.Click=function(){var A=this._ToolbarButton||this;FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(A.CommandName).Execute();};FCKToolbarButton.prototype.Enable=function(){this.RefreshState();};FCKToolbarButton.prototype.Disable=function(){this._UIButton.ChangeState(-1);} -var FCKSpecialCombo=function(A,B,C,D,E){this.FieldWidth=B||100;this.PanelWidth=C||150;this.PanelMaxHeight=D||150;this.Label=' ';this.Caption=A;this.Tooltip=A;this.Style=2;this.Enabled=true;this.Items={};this._Panel=new FCKPanel(E||window,true);this._Panel.AppendStyleSheet(FCKConfig.SkinPath+'fck_editor.css');this._PanelBox=this._Panel.MainNode.appendChild(this._Panel.Document.createElement('DIV'));this._PanelBox.className='SC_Panel';this._PanelBox.style.width=this.PanelWidth+'px';this._PanelBox.innerHTML='
      ';this._ItemsHolderEl=this._PanelBox.getElementsByTagName('TD')[0];if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKSpecialCombo_Cleanup);};function FCKSpecialCombo_ItemOnMouseOver(){this.className+=' SC_ItemOver';};function FCKSpecialCombo_ItemOnMouseOut(){this.className=this.originalClass;};function FCKSpecialCombo_ItemOnClick(){this.className=this.originalClass;this.FCKSpecialCombo._Panel.Hide();this.FCKSpecialCombo.SetLabel(this.FCKItemLabel);if (typeof(this.FCKSpecialCombo.OnSelect)=='function') this.FCKSpecialCombo.OnSelect(this.FCKItemID,this);};FCKSpecialCombo.prototype.AddItem=function(A,B,C,D){var E=this._ItemsHolderEl.appendChild(this._Panel.Document.createElement('DIV'));E.className=E.originalClass='SC_Item';E.innerHTML=B;E.FCKItemID=A;E.FCKItemLabel=C||A;E.FCKSpecialCombo=this;E.Selected=false;if (FCKBrowserInfo.IsIE) E.style.width='100%';if (D) E.style.backgroundColor=D;E.onmouseover=FCKSpecialCombo_ItemOnMouseOver;E.onmouseout=FCKSpecialCombo_ItemOnMouseOut;E.onclick=FCKSpecialCombo_ItemOnClick;this.Items[A.toString().toLowerCase()]=E;return E;};FCKSpecialCombo.prototype.SelectItem=function(A){A=A?A.toString().toLowerCase():'';var B=this.Items[A];if (B){B.className=B.originalClass='SC_ItemSelected';B.Selected=true;}};FCKSpecialCombo.prototype.SelectItemByLabel=function(A,B){for (var C in this.Items){var D=this.Items[C];if (D.FCKItemLabel==A){D.className=D.originalClass='SC_ItemSelected';D.Selected=true;if (B) this.SetLabel(A);}}};FCKSpecialCombo.prototype.DeselectAll=function(A){for (var i in this.Items){this.Items[i].className=this.Items[i].originalClass='SC_Item';this.Items[i].Selected=false;};if (A) this.SetLabel('');};FCKSpecialCombo.prototype.SetLabelById=function(A){A=A?A.toString().toLowerCase():'';var B=this.Items[A];this.SetLabel(B?B.FCKItemLabel:'');};FCKSpecialCombo.prototype.SetLabel=function(A){this.Label=A.length==0?' ':A;if (this._LabelEl){this._LabelEl.innerHTML=this.Label;FCKTools.DisableSelection(this._LabelEl);}};FCKSpecialCombo.prototype.SetEnabled=function(A){this.Enabled=A;this._OuterTable.className=A?'':'SC_FieldDisabled';};FCKSpecialCombo.prototype.Create=function(A){var B=FCKTools.GetElementDocument(A);var C=this._OuterTable=A.appendChild(B.createElement('TABLE'));C.cellPadding=0;C.cellSpacing=0;C.insertRow(-1);var D;var E;switch (this.Style){case 0:D='TB_ButtonType_Icon';E=false;break;case 1:D='TB_ButtonType_Text';E=false;break;case 2:E=true;break;};if (this.Caption&&this.Caption.length>0&&E){var F=C.rows[0].insertCell(-1);F.innerHTML=this.Caption;F.className='SC_FieldCaption';};var G=FCKTools.AppendElement(C.rows[0].insertCell(-1),'div');if (E){G.className='SC_Field';G.style.width=this.FieldWidth+'px';G.innerHTML='
       
      ';this._LabelEl=G.getElementsByTagName('label')[0];this._LabelEl.innerHTML=this.Label;}else{G.className='TB_Button_Off';G.innerHTML='
      '+this.Caption+'
      ';};G.SpecialCombo=this;G.onmouseover=FCKSpecialCombo_OnMouseOver;G.onmouseout=FCKSpecialCombo_OnMouseOut;G.onclick=FCKSpecialCombo_OnClick;FCKTools.DisableSelection(this._Panel.Document.body);};function FCKSpecialCombo_Cleanup(){this._LabelEl=null;this._OuterTable=null;this._ItemsHolderEl=null;this._PanelBox=null;if (this.Items){for (var A in this.Items) this.Items[A]=null;}};function FCKSpecialCombo_OnMouseOver(){if (this.SpecialCombo.Enabled){switch (this.SpecialCombo.Style){case 0:this.className='TB_Button_On_Over';break;case 1:this.className='TB_Button_On_Over';break;case 2:this.className='SC_Field SC_FieldOver';break;}}};function FCKSpecialCombo_OnMouseOut(){switch (this.SpecialCombo.Style){case 0:this.className='TB_Button_Off';break;case 1:this.className='TB_Button_Off';break;case 2:this.className='SC_Field';break;}};function FCKSpecialCombo_OnClick(e){var A=this.SpecialCombo;if (A.Enabled){var B=A._Panel;var C=A._PanelBox;var D=A._ItemsHolderEl;var E=A.PanelMaxHeight;if (A.OnBeforeClick) A.OnBeforeClick(A);if (FCKBrowserInfo.IsIE) B.Preload(0,this.offsetHeight,this);if (D.offsetHeight>E) C.style.height=E+'px';else C.style.height='';B.Show(0,this.offsetHeight,this);}}; -var FCKToolbarSpecialCombo=function(){this.SourceView=false;this.ContextSensitive=true;this._LastValue=null;};function FCKToolbarSpecialCombo_OnSelect(A,B){FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).Execute(A,B);};FCKToolbarSpecialCombo.prototype.Create=function(A){this._Combo=new FCKSpecialCombo(this.GetLabel(),this.FieldWidth,this.PanelWidth,this.PanelMaxHeight,FCKBrowserInfo.IsIE?window:FCKTools.GetElementWindow(A).parent);this._Combo.Tooltip=this.Tooltip;this._Combo.Style=this.Style;this.CreateItems(this._Combo);this._Combo.Create(A);this._Combo.CommandName=this.CommandName;this._Combo.OnSelect=FCKToolbarSpecialCombo_OnSelect;};function FCKToolbarSpecialCombo_RefreshActiveItems(A,B){A.DeselectAll();A.SelectItem(B);A.SetLabelById(B);};FCKToolbarSpecialCombo.prototype.RefreshState=function(){var A;var B=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetState();if (B!=-1){A=1;if (this.RefreshActiveItems) this.RefreshActiveItems(this._Combo,B);else{if (this._LastValue!=B){this._LastValue=B;FCKToolbarSpecialCombo_RefreshActiveItems(this._Combo,B);}}}else A=-1;if (A==this.State) return;if (A==-1){this._Combo.DeselectAll();this._Combo.SetLabel('');};this.State=A;this._Combo.SetEnabled(A!=-1);};FCKToolbarSpecialCombo.prototype.Enable=function(){this.RefreshState();};FCKToolbarSpecialCombo.prototype.Disable=function(){this.State=-1;this._Combo.DeselectAll();this._Combo.SetLabel('');this._Combo.SetEnabled(false);}; -var FCKToolbarFontsCombo=function(A,B){this.CommandName='FontName';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;};FCKToolbarFontsCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarFontsCombo.prototype.GetLabel=function(){return FCKLang.Font;};FCKToolbarFontsCombo.prototype.CreateItems=function(A){var B=FCKConfig.FontNames.split(';');for (var i=0;i'+B[i]+'');} -var FCKToolbarFontSizeCombo=function(A,B){this.CommandName='FontSize';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;};FCKToolbarFontSizeCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarFontSizeCombo.prototype.GetLabel=function(){return FCKLang.FontSize;};FCKToolbarFontSizeCombo.prototype.CreateItems=function(A){A.FieldWidth=70;var B=FCKConfig.FontSizes.split(';');for (var i=0;i'+C[1]+'',C[1]);}} -var FCKToolbarFontFormatCombo=function(A,B){this.CommandName='FontFormat';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;this.NormalLabel='Normal';this.PanelWidth=190;};FCKToolbarFontFormatCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarFontFormatCombo.prototype.GetLabel=function(){return FCKLang.FontFormat;};FCKToolbarFontFormatCombo.prototype.CreateItems=function(A){var B=A._Panel.Document;FCKTools.AppendStyleSheet(B,FCKConfig.ToolbarComboPreviewCSS);if (FCKConfig.BodyId&&FCKConfig.BodyId.length>0) B.body.id=FCKConfig.BodyId;if (FCKConfig.BodyClass&&FCKConfig.BodyClass.length>0) B.body.className+=' '+FCKConfig.BodyClass;var C=FCKLang['FontFormats'].split(';');var D={p:C[0],pre:C[1],address:C[2],h1:C[3],h2:C[4],h3:C[5],h4:C[6],h5:C[7],h6:C[8],div:C[9]};var E=FCKConfig.FontFormats.split(';');for (var i=0;i<'+F+'>'+G+'',G);}};if (FCKBrowserInfo.IsIE){FCKToolbarFontFormatCombo.prototype.RefreshActiveItems=function(A,B){if (B==this.NormalLabel){if (A.Label!=' ') A.DeselectAll(true);}else{if (this._LastValue==B) return;A.SelectItemByLabel(B,true);};this._LastValue=B;}} -var FCKToolbarStyleCombo=function(A,B){this.CommandName='Style';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;};FCKToolbarStyleCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarStyleCombo.prototype.GetLabel=function(){return FCKLang.Style;};FCKToolbarStyleCombo.prototype.CreateItems=function(A){var B=A._Panel.Document;FCKTools.AppendStyleSheet(B,FCKConfig.ToolbarComboPreviewCSS);B.body.className+=' ForceBaseFont';if (FCKConfig.BodyId&&FCKConfig.BodyId.length>0) B.body.id=FCKConfig.BodyId;if (FCKConfig.BodyClass&&FCKConfig.BodyClass.length>0) B.body.className+=' '+FCKConfig.BodyClass;if (!(FCKBrowserInfo.IsGecko&&FCKBrowserInfo.IsGecko10)) A.OnBeforeClick=this.RefreshVisibleItems;var C=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).Styles;for (var s in C){var D=C[s];var E;if (D.IsObjectElement) E=A.AddItem(s,s);else E=A.AddItem(s,D.GetOpenerTag()+s+D.GetCloserTag());E.Style=D;}};FCKToolbarStyleCombo.prototype.RefreshActiveItems=function(A){A.DeselectAll();var B=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetActiveStyles();if (B.length>0){for (var i=0;i'+document.getElementById('xToolbarSpace').innerHTML+'');G.close();G.oncontextmenu=FCKTools.CancelEvent;FCKTools.AppendStyleSheet(G,FCKConfig.SkinPath+'fck_editor.css');B=D.__FCKToolbarSet=new FCKToolbarSet(G);B._IFrame=F;if (FCK.IECleanup) FCK.IECleanup.AddItem(D,FCKToolbarSet_Target_Cleanup);};B.CurrentInstance=FCK;FCK.AttachToOnSelectionChange(B.RefreshItemsState);return B;};function FCK_OnBlur(A){var B=A.ToolbarSet;if (B.CurrentInstance==A) B.Disable();};function FCK_OnFocus(A){var B=A.ToolbarSet;var C=A||FCK;B.CurrentInstance.FocusManager.RemoveWindow(B._IFrame.contentWindow);B.CurrentInstance=C;C.FocusManager.AddWindow(B._IFrame.contentWindow,true);B.Enable();};function FCKToolbarSet_Cleanup(){this._TargetElement=null;this._IFrame=null;};function FCKToolbarSet_Target_Cleanup(){this.__FCKToolbarSet=null;};var FCKToolbarSet=function(A){this._Document=A;this._TargetElement=A.getElementById('xToolbar');var B=A.getElementById('xExpandHandle');var C=A.getElementById('xCollapseHandle');B.title=FCKLang.ToolbarExpand;B.onclick=FCKToolbarSet_Expand_OnClick;C.title=FCKLang.ToolbarCollapse;C.onclick=FCKToolbarSet_Collapse_OnClick;if (!FCKConfig.ToolbarCanCollapse||FCKConfig.ToolbarStartExpanded) this.Expand();else this.Collapse();C.style.display=FCKConfig.ToolbarCanCollapse?'':'none';if (FCKConfig.ToolbarCanCollapse) C.style.display='';else A.getElementById('xTBLeftBorder').style.display='';this.Toolbars=[];this.IsLoaded=false;if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKToolbarSet_Cleanup);};function FCKToolbarSet_Expand_OnClick(){FCK.ToolbarSet.Expand();};function FCKToolbarSet_Collapse_OnClick(){FCK.ToolbarSet.Collapse();};FCKToolbarSet.prototype.Expand=function(){this._ChangeVisibility(false);};FCKToolbarSet.prototype.Collapse=function(){this._ChangeVisibility(true);};FCKToolbarSet.prototype._ChangeVisibility=function(A){this._Document.getElementById('xCollapsed').style.display=A?'':'none';this._Document.getElementById('xExpanded').style.display=A?'none':'';if (FCKBrowserInfo.IsGecko){FCKTools.RunFunction(window.onresize);}};FCKToolbarSet.prototype.Load=function(A){this.Name=A;this.Items=[];this.ItemsWysiwygOnly=[];this.ItemsContextSensitive=[];this._TargetElement.innerHTML='';var B=FCKConfig.ToolbarSets[A];if (!B){alert(FCKLang.UnknownToolbarSet.replace(/%1/g,A));return;};this.Toolbars=[];for (var x=0;x0) A.deleteRow(0);}};FCKMenuBlock.prototype.Create=function(A){if (!this._ItemsTable){if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKMenuBlock_Cleanup);this._Window=FCKTools.GetElementWindow(A);var B=FCKTools.GetElementDocument(A);var C=A.appendChild(B.createElement('table'));C.cellPadding=0;C.cellSpacing=0;FCKTools.DisableSelection(C);var D=C.insertRow(-1).insertCell(-1);D.className='MN_Menu';var E=this._ItemsTable=D.appendChild(B.createElement('table'));E.cellPadding=0;E.cellSpacing=0;};for (var i=0;i0&&F.href.length==0);if (G) return;menu.AddSeparator();if (E) menu.AddItem('Link',FCKLang.EditLink,34);menu.AddItem('Unlink',FCKLang.RemoveLink,35);}}};case 'Image':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&!tag.getAttribute('_fckfakelement')){menu.AddSeparator();menu.AddItem('Image',FCKLang.ImageProperties,37);}}};case 'Anchor':return {AddItems:function(menu,tag,tagName){var F=FCKSelection.MoveToAncestorNode('A');var G=(F&&F.name.length>0);if (G||(tagName=='IMG'&&tag.getAttribute('_fckanchor'))){menu.AddSeparator();menu.AddItem('Anchor',FCKLang.AnchorProp,36);}}};case 'Flash':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&tag.getAttribute('_fckflash')){menu.AddSeparator();menu.AddItem('Flash',FCKLang.FlashProperties,38);}}};case 'Form':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('FORM')){menu.AddSeparator();menu.AddItem('Form',FCKLang.FormProp,48);}}};case 'Checkbox':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='checkbox'){menu.AddSeparator();menu.AddItem('Checkbox',FCKLang.CheckboxProp,49);}}};case 'Radio':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='radio'){menu.AddSeparator();menu.AddItem('Radio',FCKLang.RadioButtonProp,50);}}};case 'TextField':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&(tag.type=='text'||tag.type=='password')){menu.AddSeparator();menu.AddItem('TextField',FCKLang.TextFieldProp,51);}}};case 'HiddenField':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&tag.getAttribute('_fckinputhidden')){menu.AddSeparator();menu.AddItem('HiddenField',FCKLang.HiddenFieldProp,56);}}};case 'ImageButton':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='image'){menu.AddSeparator();menu.AddItem('ImageButton',FCKLang.ImageButtonProp,55);}}};case 'Button':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&(tag.type=='button'||tag.type=='submit'||tag.type=='reset')){menu.AddSeparator();menu.AddItem('Button',FCKLang.ButtonProp,54);}}};case 'Select':return {AddItems:function(menu,tag,tagName){if (tagName=='SELECT'){menu.AddSeparator();menu.AddItem('Select',FCKLang.SelectionFieldProp,53);}}};case 'Textarea':return {AddItems:function(menu,tag,tagName){if (tagName=='TEXTAREA'){menu.AddSeparator();menu.AddItem('Textarea',FCKLang.TextareaProp,52);}}};case 'BulletedList':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('UL')){menu.AddSeparator();menu.AddItem('BulletedList',FCKLang.BulletedListProp,27);}}};case 'NumberedList':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('OL')){menu.AddSeparator();menu.AddItem('NumberedList',FCKLang.NumberedListProp,26);}}};};return null;};function FCK_ContextMenu_OnBeforeOpen(){FCK.Events.FireEvent('OnSelectionChange');var A,sTagName;if ((A=FCKSelection.GetSelectedElement())) sTagName=A.tagName;var B=FCK.ContextMenu._InnerContextMenu;B.RemoveAllItems();var C=FCK.ContextMenu.Listeners;for (var i=0;i0){var A;if (this.AvailableLangs.IndexOf(FCKLanguageManager.ActiveLanguage.Code)>=0) A=FCKLanguageManager.ActiveLanguage.Code;else A=this.AvailableLangs[0];LoadScript(this.Path+'lang/'+A+'.js');};LoadScript(this.Path+'fckplugin.js');} -var FCKPlugins=FCK.Plugins={};FCKPlugins.ItemsCount=0;FCKPlugins.Items={};FCKPlugins.Load=function(){var A=FCKPlugins.Items;for (var i=0;i-1);};String.prototype.Equals=function(){var A=arguments;if (A.length==1&&A[0].pop) A=A[0];for (var i=0;iC) return false;if (B){var E=new RegExp(A+'$','i');return E.test(this);}else return (D==0||this.substr(C-D,D)==A);};String.prototype.Remove=function(A,B){var s='';if (A>0) s=this.substring(0,A);if (A+B0){var B=A.pop();if (B) B[1].call(B[0]);};this._FCKCleanupObj=null;if (CollectGarbage) CollectGarbage();}; +var s=navigator.userAgent.toLowerCase();var FCKBrowserInfo={IsIE:/*@cc_on!@*/false,IsIE7:/*@cc_on!@*/false && ( parseInt( s.match( /msie (\d+)/)[1],10)>=7),IsIE6:/*@cc_on!@*/false && ( parseInt( s.match( /msie (\d+)/)[1],10)>=6),IsGecko:s.Contains('gecko/'),IsSafari:s.Contains(' applewebkit/'),IsOpera:!!window.opera,IsAIR:s.Contains(' adobeair/'),IsMac:s.Contains('macintosh')};(function(A){A.IsGeckoLike=(A.IsGecko||A.IsSafari||A.IsOpera);if (A.IsGecko){var B=s.match(/gecko\/(\d+)/)[1];A.IsGecko10=((B<20051111)||(/rv:1\.7/.test(s)));A.IsGecko19=/rv:1\.9/.test(s);}else A.IsGecko10=false;})(FCKBrowserInfo); +var FCKURLParams={};(function(){var A=document.location.search.substr(1).split('&');for (var i=0;i';if (!FCKRegexLib.HtmlOpener.test(A)) A=''+A+'';if (!FCKRegexLib.HeadOpener.test(A)) A=A.replace(FCKRegexLib.HtmlOpener,'$&');return A;}else{var B=FCKConfig.DocType+'0&&!FCKRegexLib.Html4DocType.test(FCKConfig.DocType)) B+=' style="overflow-y: scroll"';B+='>'+A+'';return B;}},ConvertToDataFormat:function(A,B,C,D){var E=FCKXHtml.GetXHTML(A,!B,D);if (C&&FCKRegexLib.EmptyOutParagraph.test(E)) return '';return E;},FixHtml:function(A){return A;}}; +var FCK={Name:FCKURLParams['InstanceName'],Status:0,EditMode:0,Toolbar:null,HasFocus:false,DataProcessor:new FCKDataProcessor(),GetInstanceObject:(function(){var w=window;return function(name){return w[name];}})(),AttachToOnSelectionChange:function(A){this.Events.AttachEvent('OnSelectionChange',A);},GetLinkedFieldValue:function(){return this.LinkedField.value;},GetParentForm:function(){return this.LinkedField.form;},StartupValue:'',IsDirty:function(){if (this.EditMode==1) return (this.StartupValue!=this.EditingArea.Textarea.value);else{if (!this.EditorDocument) return false;return (this.StartupValue!=this.EditorDocument.body.innerHTML);}},ResetIsDirty:function(){if (this.EditMode==1) this.StartupValue=this.EditingArea.Textarea.value;else if (this.EditorDocument.body) this.StartupValue=this.EditorDocument.body.innerHTML;},StartEditor:function(){this.TempBaseTag=FCKConfig.BaseHref.length>0?'':'';var A=FCK.KeystrokeHandler=new FCKKeystrokeHandler();A.OnKeystroke=_FCK_KeystrokeHandler_OnKeystroke;A.SetKeystrokes(FCKConfig.Keystrokes);if (FCKBrowserInfo.IsIE7){if ((CTRL+86/*V*/) in A.Keystrokes) A.SetKeystrokes([CTRL+86,true]);if ((SHIFT+45/*INS*/) in A.Keystrokes) A.SetKeystrokes([SHIFT+45,true]);};A.SetKeystrokes([CTRL+8,true]);this.EditingArea=new FCKEditingArea(document.getElementById('xEditingArea'));this.EditingArea.FFSpellChecker=FCKConfig.FirefoxSpellChecker;this.SetData(this.GetLinkedFieldValue(),true);FCKTools.AddEventListener(document,"keydown",this._TabKeyHandler);this.AttachToOnSelectionChange(_FCK_PaddingNodeListener);if (FCKBrowserInfo.IsGecko) this.AttachToOnSelectionChange(this._ExecCheckEmptyBlock);},Focus:function(){FCK.EditingArea.Focus();},SetStatus:function(A){this.Status=A;if (A==1){FCKFocusManager.AddWindow(window,true);if (FCKBrowserInfo.IsIE) FCKFocusManager.AddWindow(window.frameElement,true);if (FCKConfig.StartupFocus) FCK.Focus();};this.Events.FireEvent('OnStatusChange',A);},FixBody:function(){var A=FCKConfig.EnterMode;if (A!='p'&&A!='div') return;var B=this.EditorDocument;if (!B) return;var C=B.body;if (!C) return;FCKDomTools.TrimNode(C);var D=C.firstChild;var E;while (D){var F=false;switch (D.nodeType){case 1:var G=D.nodeName.toLowerCase();if (!FCKListsLib.BlockElements[G]&&G!='li'&&!D.getAttribute('_fckfakelement')&&D.getAttribute('_moz_dirty')==null) F=true;break;case 3:if (E||D.nodeValue.Trim().length>0) F=true;};if (F){var H=D.parentNode;if (!E) E=H.insertBefore(B.createElement(A),D);E.appendChild(H.removeChild(D));D=E.nextSibling;}else{if (E){FCKDomTools.TrimNode(E);E=null;};D=D.nextSibling;}};if (E) FCKDomTools.TrimNode(E);},GetData:function(A){if (FCK.EditMode==1) return FCK.EditingArea.Textarea.value;this.FixBody();var B=FCK.EditorDocument;if (!B) return null;var C=FCKConfig.FullPage;var D=FCK.DataProcessor.ConvertToDataFormat(C?B.documentElement:B.body,!C,FCKConfig.IgnoreEmptyParagraphValue,A);D=FCK.ProtectEventsRestore(D);if (FCKBrowserInfo.IsIE) D=D.replace(FCKRegexLib.ToReplace,'$1');if (C){if (FCK.DocTypeDeclaration&&FCK.DocTypeDeclaration.length>0) D=FCK.DocTypeDeclaration+'\n'+D;if (FCK.XmlDeclaration&&FCK.XmlDeclaration.length>0) D=FCK.XmlDeclaration+'\n'+D;};return FCKConfig.ProtectedSource.Revert(D);},UpdateLinkedField:function(){var A=FCK.GetXHTML(FCKConfig.FormatOutput);if (FCKConfig.HtmlEncodeOutput) A=FCKTools.HTMLEncode(A);FCK.LinkedField.value=A;FCK.Events.FireEvent('OnAfterLinkedFieldUpdate');},RegisteredDoubleClickHandlers:{},OnDoubleClick:function(A){var B=FCK.RegisteredDoubleClickHandlers[A.tagName.toUpperCase()];if (B){for (var i=0;i0?'|ABBR|XML|EMBED|OBJECT':'ABBR|XML|EMBED|OBJECT';var C;if (B.length>0){C=new RegExp('<('+B+')(?!\w|:)','gi');A=A.replace(C,'','gi');A=A.replace(C,'<\/FCK:$1>');};B='META';if (FCKBrowserInfo.IsIE) B+='|HR';C=new RegExp('<(('+B+')(?=\\s|>|/)[\\s\\S]*?)/?>','gi');A=A.replace(C,'');return A;},SetData:function(A,B){this.EditingArea.Mode=FCK.EditMode;if (FCKBrowserInfo.IsIE&&FCK.EditorDocument){FCK.EditorDocument.detachEvent("onselectionchange",Doc_OnSelectionChange);};if (FCK.EditMode==0){this._ForceResetIsDirty=(B===true);A=FCKConfig.ProtectedSource.Protect(A);A=FCK.DataProcessor.ConvertToHtml(A);A=A.replace(FCKRegexLib.InvalidSelfCloseTags,'$1>');A=FCK.ProtectEvents(A);A=FCK.ProtectUrls(A);A=FCK.ProtectTags(A);if (FCK.TempBaseTag.length>0&&!FCKRegexLib.HasBaseTag.test(A)) A=A.replace(FCKRegexLib.HeadOpener,'$&'+FCK.TempBaseTag);var C='';if (!FCKConfig.FullPage) C+=_FCK_GetEditorAreaStyleTags();if (FCKBrowserInfo.IsIE) C+=FCK._GetBehaviorsStyle();else if (FCKConfig.ShowBorders) C+=FCKTools.GetStyleHtml(FCK_ShowTableBordersCSS,true);C+=FCKTools.GetStyleHtml(FCK_InternalCSS,true);A=A.replace(FCKRegexLib.HeadCloser,C+'$&');this.EditingArea.OnLoad=_FCK_EditingArea_OnLoad;this.EditingArea.Start(A);}else{FCK.EditorWindow=null;FCK.EditorDocument=null;FCKDomTools.PaddingNode=null;this.EditingArea.OnLoad=null;this.EditingArea.Start(A);this.EditingArea.Textarea._FCKShowContextMenu=true;FCK.EnterKeyHandler=null;if (B) this.ResetIsDirty();FCK.KeystrokeHandler.AttachToElement(this.EditingArea.Textarea);this.EditingArea.Textarea.focus();FCK.Events.FireEvent('OnAfterSetHTML');};if (FCKBrowserInfo.IsGecko) window.onresize();},RedirectNamedCommands:{},ExecuteNamedCommand:function(A,B,C,D){if (!D) FCKUndo.SaveUndoStep();if (!C&&FCK.RedirectNamedCommands[A]!=null) FCK.ExecuteRedirectedNamedCommand(A,B);else{FCK.Focus();FCK.EditorDocument.execCommand(A,false,B);FCK.Events.FireEvent('OnSelectionChange');};if (!D) FCKUndo.SaveUndoStep();},GetNamedCommandState:function(A){try{if (FCKBrowserInfo.IsSafari&&FCK.EditorWindow&&A.IEquals('Paste')) return 0;if (!FCK.EditorDocument.queryCommandEnabled(A)) return -1;else{return FCK.EditorDocument.queryCommandState(A)?1:0;}}catch (e){return 0;}},GetNamedCommandValue:function(A){var B='';var C=FCK.GetNamedCommandState(A);if (C==-1) return null;try{B=this.EditorDocument.queryCommandValue(A);}catch(e) {};return B?B:'';},Paste:function(A){if (FCK.Status!=2||!FCK.Events.FireEvent('OnPaste')) return false;return A||FCK._ExecPaste();},PasteFromWord:function(){FCKDialog.OpenDialog('FCKDialog_Paste',FCKLang.PasteFromWord,'dialog/fck_paste.html',400,330,'Word');},Preview:function(){var A;if (FCKConfig.FullPage){if (FCK.TempBaseTag.length>0) A=FCK.TempBaseTag+FCK.GetXHTML();else A=FCK.GetXHTML();}else{A=FCKConfig.DocType+''+FCK.TempBaseTag+''+FCKLang.Preview+''+_FCK_GetEditorAreaStyleTags()+''+FCK.GetXHTML()+'';};var B=FCKConfig.ScreenWidth*0.8;var C=FCKConfig.ScreenHeight*0.7;var D=(FCKConfig.ScreenWidth-B)/2;var E='';if (FCK_IS_CUSTOM_DOMAIN&&FCKBrowserInfo.IsIE){window._FCKHtmlToLoad=A;E='javascript:void( (function(){document.open() ;document.domain="'+document.domain+'" ;document.write( window.opener._FCKHtmlToLoad );document.close() ;window.opener._FCKHtmlToLoad = null ;})() )';};var F=window.open(E,null,'toolbar=yes,location=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+B+',height='+C+',left='+D);if (!FCK_IS_CUSTOM_DOMAIN||!FCKBrowserInfo.IsIE){F.document.write(A);F.document.close();}},SwitchEditMode:function(A){var B=(FCK.EditMode==0);var C=FCK.IsDirty();var D;if (B){FCKCommands.GetCommand('ShowBlocks').SaveState();if (!A&&FCKBrowserInfo.IsIE) FCKUndo.SaveUndoStep();D=FCK.GetXHTML(FCKConfig.FormatSource);if (D==null) return false;}else D=this.EditingArea.Textarea.value;FCK.EditMode=B?1:0;FCK.SetData(D,!C);FCK.Focus();FCKTools.RunFunction(FCK.ToolbarSet.RefreshModeState,FCK.ToolbarSet);return true;},InsertElement:function(A){if (typeof A=='string') A=this.EditorDocument.createElement(A);var B=A.nodeName.toLowerCase();FCKSelection.Restore();var C=new FCKDomRange(this.EditorWindow);if (FCKListsLib.BlockElements[B]!=null){C.SplitBlock();C.InsertNode(A);var D=FCKDomTools.GetNextSourceElement(A,false,null,['hr','br','param','img','area','input'],true);if (!D&&FCKConfig.EnterMode!='br'){D=this.EditorDocument.body.appendChild(this.EditorDocument.createElement(FCKConfig.EnterMode));if (FCKBrowserInfo.IsGeckoLike) FCKTools.AppendBogusBr(D);};if (FCKListsLib.EmptyElements[B]==null) C.MoveToElementEditStart(A);else if (D) C.MoveToElementEditStart(D);else C.MoveToPosition(A,4);if (FCKBrowserInfo.IsGecko){if (D) D.scrollIntoView(false);A.scrollIntoView(false);}}else{C.MoveToSelection();C.DeleteContents();C.InsertNode(A);C.SetStart(A,4);C.SetEnd(A,4);};C.Select();C.Release();this.Focus();return A;},_InsertBlockElement:function(A){},_IsFunctionKey:function(A){if (A>=16&&A<=20) return true;if (A==27||(A>=33&&A<=40)) return true;if (A==45) return true;return false;},_KeyDownListener:function(A){if (!A) A=FCK.EditorWindow.event;if (FCK.EditorWindow){if (!FCK._IsFunctionKey(A.keyCode)&&!(A.ctrlKey||A.metaKey)&&!(A.keyCode==46)) FCK._KeyDownUndo();};return true;},_KeyDownUndo:function(){if (!FCKUndo.Typing){FCKUndo.SaveUndoStep();FCKUndo.Typing=true;FCK.Events.FireEvent("OnSelectionChange");};FCKUndo.TypesCount++;FCKUndo.Changed=1;if (FCKUndo.TypesCount>FCKUndo.MaxTypes){FCKUndo.TypesCount=0;FCKUndo.SaveUndoStep();}},_TabKeyHandler:function(A){if (!A) A=window.event;var B=A.keyCode;if (B==9&&FCK.EditMode!=0){if (FCKBrowserInfo.IsIE){var C=document.selection.createRange();if (C.parentElement()!=FCK.EditingArea.Textarea) return true;C.text='\t';C.select();}else{var a=[];var D=FCK.EditingArea.Textarea;var E=D.selectionStart;var F=D.selectionEnd;a.push(D.value.substr(0,E));a.push('\t');a.push(D.value.substr(F));D.value=a.join('');D.setSelectionRange(E+1,E+1);};if (A.preventDefault) return A.preventDefault();return A.returnValue=false;};return true;}};FCK.Events=new FCKEvents(FCK);FCK.GetHTML=FCK.GetXHTML=FCK.GetData;FCK.SetHTML=FCK.SetData;FCK.InsertElementAndGetIt=FCK.CreateElement=FCK.InsertElement;function _FCK_ProtectEvents_ReplaceTags(A){return A.replace(FCKRegexLib.EventAttributes,_FCK_ProtectEvents_ReplaceEvents);};function _FCK_ProtectEvents_ReplaceEvents(A,B){return ' '+B+'_fckprotectedatt="'+encodeURIComponent(A)+'"';};function _FCK_ProtectEvents_RestoreEvents(A,B){return decodeURIComponent(B);};function _FCK_MouseEventsListener(A){if (!A) A=window.event;if (A.type=='mousedown') FCK.MouseDownFlag=true;else if (A.type=='mouseup') FCK.MouseDownFlag=false;else if (A.type=='mousemove') FCK.Events.FireEvent('OnMouseMove',A);};function _FCK_PaddingNodeListener(){if (FCKConfig.EnterMode.IEquals('br')) return;FCKDomTools.EnforcePaddingNode(FCK.EditorDocument,FCKConfig.EnterMode);if (!FCKBrowserInfo.IsIE&&FCKDomTools.PaddingNode){var A=FCKSelection.GetSelection();if (A&&A.rangeCount==1){var B=A.getRangeAt(0);if (B.collapsed&&B.startContainer==FCK.EditorDocument.body&&B.startOffset==0){B.selectNodeContents(FCKDomTools.PaddingNode);B.collapse(true);A.removeAllRanges();A.addRange(B);}}}else if (FCKDomTools.PaddingNode){var C=FCKSelection.GetParentElement();var D=FCKDomTools.PaddingNode;if (C&&C.nodeName.IEquals('body')){if (FCK.EditorDocument.body.childNodes.length==1&&FCK.EditorDocument.body.firstChild==D){var B=FCK.EditorDocument.body.createTextRange();var F=false;if (!D.childNodes.firstChild){D.appendChild(FCKTools.GetElementDocument(D).createTextNode('\ufeff'));F=true;};B.moveToElementText(D);B.select();if (F) B.pasteHTML('');}}}};function _FCK_EditingArea_OnLoad(){FCK.EditorWindow=FCK.EditingArea.Window;FCK.EditorDocument=FCK.EditingArea.Document;FCK.InitializeBehaviors();FCK.MouseDownFlag=false;FCKTools.AddEventListener(FCK.EditorDocument,'mousemove',_FCK_MouseEventsListener);FCKTools.AddEventListener(FCK.EditorDocument,'mousedown',_FCK_MouseEventsListener);FCKTools.AddEventListener(FCK.EditorDocument,'mouseup',_FCK_MouseEventsListener);if (FCKBrowserInfo.IsSafari){var A=function(evt){if (!(evt.ctrlKey||evt.metaKey)) return;if (FCK.EditMode!=0) return;switch (evt.keyCode){case 89:FCKUndo.Redo();break;case 90:FCKUndo.Undo();break;}};FCKTools.AddEventListener(FCK.EditorDocument,'keyup',A);};FCK.EnterKeyHandler=new FCKEnterKey(FCK.EditorWindow,FCKConfig.EnterMode,FCKConfig.ShiftEnterMode,FCKConfig.TabSpaces);FCK.KeystrokeHandler.AttachToElement(FCK.EditorDocument);if (FCK._ForceResetIsDirty) FCK.ResetIsDirty();if (FCKBrowserInfo.IsIE&&FCK.HasFocus) FCK.EditorDocument.body.setActive();FCK.OnAfterSetHTML();FCKCommands.GetCommand('ShowBlocks').RestoreState();if (FCK.Status!=0) return;FCK.SetStatus(1);};function _FCK_GetEditorAreaStyleTags(){return FCKTools.GetStyleHtml(FCKConfig.EditorAreaCSS)+FCKTools.GetStyleHtml(FCKConfig.EditorAreaStyles);};function _FCK_KeystrokeHandler_OnKeystroke(A,B){if (FCK.Status!=2) return false;if (FCK.EditMode==0){switch (B){case 'Paste':return!FCK.Paste();case 'Cut':FCKUndo.SaveUndoStep();return false;}}else{if (B.Equals('Paste','Undo','Redo','SelectAll','Cut')) return false;};var C=FCK.Commands.GetCommand(B);if (C.GetState()==-1) return false;return (C.Execute.apply(C,FCKTools.ArgumentsToArray(arguments,2))!==false);};(function(){var A=window.parent.document;var B=A.getElementById(FCK.Name);var i=0;while (B||i==0){if (B&&B.tagName.toLowerCase().Equals('input','textarea')){FCK.LinkedField=B;break;};B=A.getElementsByName(FCK.Name)[i++];}})();var FCKTempBin={Elements:[],AddElement:function(A){var B=this.Elements.length;this.Elements[B]=A;return B;},RemoveElement:function(A){var e=this.Elements[A];this.Elements[A]=null;return e;},Reset:function(){var i=0;while (i0) C+='TABLE { behavior: '+B+' ; }';C+='';FCK._BehaviorsStyle=C;};return FCK._BehaviorsStyle;};function Doc_OnMouseUp(){if (FCK.EditorWindow.event.srcElement.tagName=='HTML'){FCK.Focus();FCK.EditorWindow.event.cancelBubble=true;FCK.EditorWindow.event.returnValue=false;}};function Doc_OnPaste(){var A=FCK.EditorDocument.body;A.detachEvent('onpaste',Doc_OnPaste);var B=FCK.Paste(!FCKConfig.ForcePasteAsPlainText&&!FCKConfig.AutoDetectPasteFromWord);A.attachEvent('onpaste',Doc_OnPaste);return B;};function Doc_OnDblClick(){FCK.OnDoubleClick(FCK.EditorWindow.event.srcElement);FCK.EditorWindow.event.cancelBubble=true;};function Doc_OnSelectionChange(){if (!FCK.IsSelectionChangeLocked&&FCK.EditorDocument) FCK.Events.FireEvent("OnSelectionChange");};function Doc_OnDrop(){if (FCK.MouseDownFlag){FCK.MouseDownFlag=false;return;};if (FCKConfig.ForcePasteAsPlainText){var A=FCK.EditorWindow.event;if (FCK._CheckIsPastingEnabled()||FCKConfig.ShowDropDialog) FCK.PasteAsPlainText(A.dataTransfer.getData('Text'));A.returnValue=false;A.cancelBubble=true;}};FCK.InitializeBehaviors=function(A){this.EditorDocument.attachEvent('onmouseup',Doc_OnMouseUp);this.EditorDocument.body.attachEvent('onpaste',Doc_OnPaste);this.EditorDocument.body.attachEvent('ondrop',Doc_OnDrop);FCK.ContextMenu._InnerContextMenu.AttachToElement(FCK.EditorDocument.body);this.EditorDocument.attachEvent("onkeydown",FCK._KeyDownListener);this.EditorDocument.attachEvent("ondblclick",Doc_OnDblClick);this.EditorDocument.attachEvent("onselectionchange",Doc_OnSelectionChange);FCKTools.AddEventListener(FCK.EditorDocument,'mousedown',Doc_OnMouseDown);};FCK.InsertHtml=function(A){A=FCKConfig.ProtectedSource.Protect(A);A=FCK.ProtectEvents(A);A=FCK.ProtectUrls(A);A=FCK.ProtectTags(A);FCK.EditorWindow.focus();FCKUndo.SaveUndoStep();var B=FCKSelection.GetSelection();if (B.type.toLowerCase()=='control') B.clear();A=''+A;B.createRange().pasteHTML(A);FCK.EditorDocument.getElementById('__fakeFCKRemove__').removeNode(true);FCKDocumentProcessor.Process(FCK.EditorDocument);this.Events.FireEvent("OnSelectionChange");};FCK.SetInnerHtml=function(A){var B=FCK.EditorDocument;B.body.innerHTML='
       
      '+A;B.getElementById('__fakeFCKRemove__').removeNode(true);};function FCK_PreloadImages(){var A=new FCKImagePreloader();A.AddImages(FCKConfig.PreloadImages);A.AddImages(FCKConfig.SkinPath+'fck_strip.gif');A.OnComplete=LoadToolbarSetup;A.Start();};function Document_OnContextMenu(){return (event.srcElement._FCKShowContextMenu==true);};document.oncontextmenu=Document_OnContextMenu;function FCK_Cleanup(){this.LinkedField=null;this.EditorWindow=null;this.EditorDocument=null;};FCK._ExecPaste=function(){if (FCK._PasteIsRunning) return true;if (FCKConfig.ForcePasteAsPlainText){FCK.PasteAsPlainText();return false;};var A=FCK._CheckIsPastingEnabled(true);if (A===false) FCKTools.RunFunction(FCKDialog.OpenDialog,FCKDialog,['FCKDialog_Paste',FCKLang.Paste,'dialog/fck_paste.html',400,330,'Security']);else{if (FCKConfig.AutoDetectPasteFromWord&&A.length>0){var B=/<\w[^>]*(( class="?MsoNormal"?)|(="mso-))/gi;if (B.test(A)){if (confirm(FCKLang.PasteWordConfirm)){FCK.PasteFromWord();return false;}}};FCK._PasteIsRunning=true;FCK.ExecuteNamedCommand('Paste');delete FCK._PasteIsRunning;};return false;};FCK.PasteAsPlainText=function(A){if (!FCK._CheckIsPastingEnabled()){FCKDialog.OpenDialog('FCKDialog_Paste',FCKLang.PasteAsText,'dialog/fck_paste.html',400,330,'PlainText');return;};var B=null;if (!A) B=clipboardData.getData("Text");else B=A;if (B&&B.length>0){B=FCKTools.HTMLEncode(B);B=FCKTools.ProcessLineBreaks(window,FCKConfig,B);var C=B.search('

      ');var D=B.search('

      ');if ((C!=-1&&D!=-1&&C0){if (FCKSelection.GetType()=='Control'){var D=this.EditorDocument.createElement('A');D.href=A;var E=FCKSelection.GetSelectedElement();E.parentNode.insertBefore(D,E);E.parentNode.removeChild(E);D.appendChild(E);return [D];};var F='javascript:void(0);/*'+(new Date().getTime())+'*/';FCK.ExecuteNamedCommand('CreateLink',F,false,!!B);var G=this.EditorDocument.links;for (i=0;i0&&!isNaN(E)) this.PageConfig[D]=parseInt(E,10);else this.PageConfig[D]=E;}};function FCKConfig_LoadPageConfig(){var A=FCKConfig.PageConfig;for (var B in A) FCKConfig[B]=A[B];};function FCKConfig_PreProcess(){var A=FCKConfig;if (A.AllowQueryStringDebug){try{if ((/fckdebug=true/i).test(window.top.location.search)) A.Debug=true;}catch (e) {/*Ignore it. Much probably we are inside a FRAME where the "top" is in another domain (security error).*/}};if (!A.PluginsPath.EndsWith('/')) A.PluginsPath+='/';var B=A.ToolbarComboPreviewCSS;if (!B||B.length==0) A.ToolbarComboPreviewCSS=A.EditorAreaCSS;A.RemoveAttributesArray=(A.RemoveAttributes||'').split(',');if (!FCKConfig.SkinEditorCSS||FCKConfig.SkinEditorCSS.length==0) FCKConfig.SkinEditorCSS=FCKConfig.SkinPath+'fck_editor.css';if (!FCKConfig.SkinDialogCSS||FCKConfig.SkinDialogCSS.length==0) FCKConfig.SkinDialogCSS=FCKConfig.SkinPath+'fck_dialog.css';};FCKConfig.ToolbarSets={};FCKConfig.Plugins={};FCKConfig.Plugins.Items=[];FCKConfig.Plugins.Add=function(A,B,C){FCKConfig.Plugins.Items.AddItem([A,B,C]);};FCKConfig.ProtectedSource={};FCKConfig.ProtectedSource._CodeTag=(new Date()).valueOf();FCKConfig.ProtectedSource.RegexEntries=[//g,//gi,//gi];FCKConfig.ProtectedSource.Add=function(A){this.RegexEntries.AddItem(A);};FCKConfig.ProtectedSource.Protect=function(A){var B=this._CodeTag;function _Replace(protectedSource){var C=FCKTempBin.AddElement(protectedSource);return '';};for (var i=0;i|>)","g");return A.replace(D,_Replace);};FCKConfig.GetBodyAttributes=function(){var A='';if (this.BodyId&&this.BodyId.length>0) A+=' id="'+this.BodyId+'"';if (this.BodyClass&&this.BodyClass.length>0) A+=' class="'+this.BodyClass+'"';return A;};FCKConfig.ApplyBodyAttributes=function(A){if (this.BodyId&&this.BodyId.length>0) A.id=FCKConfig.BodyId;if (this.BodyClass&&this.BodyClass.length>0) A.className+=' '+FCKConfig.BodyClass;}; +var FCKDebug={};FCKDebug._GetWindow=function(){if (!this.DebugWindow||this.DebugWindow.closed) this.DebugWindow=window.open(FCKConfig.BasePath+'fckdebug.html','FCKeditorDebug','menubar=no,scrollbars=yes,resizable=yes,location=no,toolbar=no,width=600,height=500',true);return this.DebugWindow;};FCKDebug.Output=function(A,B,C){if (!FCKConfig.Debug) return;try{this._GetWindow().Output(A,B);}catch (e) {}};FCKDebug.OutputObject=function(A,B){if (!FCKConfig.Debug) return;try{this._GetWindow().OutputObject(A,B);}catch (e) {}}; +var FCKDomTools={MoveChildren:function(A,B,C){if (A==B) return;var D;if (C){while ((D=A.lastChild)) B.insertBefore(A.removeChild(D),B.firstChild);}else{while ((D=A.firstChild)) B.appendChild(A.removeChild(D));}},MoveNode:function(A,B,C){if (C) B.insertBefore(FCKDomTools.RemoveNode(A),B.firstChild);else B.appendChild(FCKDomTools.RemoveNode(A));},TrimNode:function(A){this.LTrimNode(A);this.RTrimNode(A);},LTrimNode:function(A){var B;while ((B=A.firstChild)){if (B.nodeType==3){var C=B.nodeValue.LTrim();var D=B.nodeValue.length;if (C.length==0){A.removeChild(B);continue;}else if (C.length0) break;if (A.lastChild) A=A.lastChild;else return this.GetPreviousSourceElement(A,B,C,D);};return null;},GetNextSourceElement:function(A,B,C,D,E){while((A=this.GetNextSourceNode(A,E))){if (A.nodeType==1){if (C&&A.nodeName.IEquals(C)) break;if (D&&A.nodeName.IEquals(D)) return this.GetNextSourceElement(A,B,C,D);return A;}else if (B&&A.nodeType==3&&A.nodeValue.RTrim().length>0) break;};return null;},GetNextSourceNode:function(A,B,C,D){if (!A) return null;var E;if (!B&&A.firstChild) E=A.firstChild;else{if (D&&A==D) return null;E=A.nextSibling;if (!E&&(!D||D!=A.parentNode)) return this.GetNextSourceNode(A.parentNode,true,C,D);};if (C&&E&&E.nodeType!=C) return this.GetNextSourceNode(E,false,C,D);return E;},GetPreviousSourceNode:function(A,B,C,D){if (!A) return null;var E;if (!B&&A.lastChild) E=A.lastChild;else{if (D&&A==D) return null;E=A.previousSibling;if (!E&&(!D||D!=A.parentNode)) return this.GetPreviousSourceNode(A.parentNode,true,C,D);};if (C&&E&&E.nodeType!=C) return this.GetPreviousSourceNode(E,false,C,D);return E;},InsertAfterNode:function(A,B){return A.parentNode.insertBefore(B,A.nextSibling);},GetParents:function(A){var B=[];while (A){B.unshift(A);A=A.parentNode;};return B;},GetCommonParents:function(A,B){var C=this.GetParents(A);var D=this.GetParents(B);var E=[];for (var i=0;i0) D[C.pop().toLowerCase()]=1;var E=this.GetCommonParents(A,B);var F=null;while ((F=E.pop())){if (D[F.nodeName.toLowerCase()]) return F;};return null;},GetIndexOf:function(A){var B=A.parentNode?A.parentNode.firstChild:null;var C=-1;while (B){C++;if (B==A) return C;B=B.nextSibling;};return-1;},PaddingNode:null,EnforcePaddingNode:function(A,B){try{if (!A||!A.body) return;}catch (e){return;};this.CheckAndRemovePaddingNode(A,B,true);try{if (A.body.lastChild&&(A.body.lastChild.nodeType!=1||A.body.lastChild.tagName.toLowerCase()==B.toLowerCase())) return;}catch (e){return;};var C=A.createElement(B);if (FCKBrowserInfo.IsGecko&&FCKListsLib.NonEmptyBlockElements[B]) FCKTools.AppendBogusBr(C);this.PaddingNode=C;if (A.body.childNodes.length==1&&A.body.firstChild.nodeType==1&&A.body.firstChild.tagName.toLowerCase()=='br'&&(A.body.firstChild.getAttribute('_moz_dirty')!=null||A.body.firstChild.getAttribute('type')=='_moz')) A.body.replaceChild(C,A.body.firstChild);else A.body.appendChild(C);},CheckAndRemovePaddingNode:function(A,B,C){var D=this.PaddingNode;if (!D) return;try{if (D.parentNode!=A.body||D.tagName.toLowerCase()!=B||(D.childNodes.length>1)||(D.firstChild&&D.firstChild.nodeValue!='\xa0'&&String(D.firstChild.tagName).toLowerCase()!='br')){this.PaddingNode=null;return;}}catch (e){this.PaddingNode=null;return;};if (!C){if (D.parentNode.childNodes.length>1) D.parentNode.removeChild(D);this.PaddingNode=null;}},HasAttribute:function(A,B){if (A.hasAttribute) return A.hasAttribute(B);else{var C=A.attributes[B];return (C!=undefined&&C.specified);}},HasAttributes:function(A){var B=A.attributes;for (var i=0;i0) return true;}else if (B[i].specified) return true;};return false;},RemoveAttribute:function(A,B){if (FCKBrowserInfo.IsIE&&B.toLowerCase()=='class') B='className';return A.removeAttribute(B,0);},RemoveAttributes:function (A,B){for (var i=0;i0) return false;C=C.nextSibling;};return D?this.CheckIsEmptyElement(D,B):true;},SetElementStyles:function(A,B){var C=A.style;for (var D in B) C[D]=B[D];},SetOpacity:function(A,B){if (FCKBrowserInfo.IsIE){B=Math.round(B*100);A.style.filter=(B>100?'':'progid:DXImageTransform.Microsoft.Alpha(opacity='+B+')');}else A.style.opacity=B;},GetCurrentElementStyle:function(A,B){if (FCKBrowserInfo.IsIE) return A.currentStyle[B];else return A.ownerDocument.defaultView.getComputedStyle(A,'').getPropertyValue(B);},GetPositionedAncestor:function(A){var B=A;while (B!=FCKTools.GetElementDocument(B).documentElement){if (this.GetCurrentElementStyle(B,'position')!='static') return B;if (B==FCKTools.GetElementDocument(B).documentElement&¤tWindow!=w) B=currentWindow.frameElement;else B=B.parentNode;};return null;},ScrollIntoView:function(A,B){var C=FCKTools.GetElementWindow(A);var D=FCKTools.GetViewPaneSize(C).Height;var E=D*-1;if (B===false){E+=A.offsetHeight;E+=parseInt(this.GetCurrentElementStyle(A,'marginBottom')||0,10);};E+=A.offsetTop;while ((A=A.offsetParent)) E+=A.offsetTop||0;var F=FCKTools.GetScrollPosition(C).Y;if (E>0&&E>F) C.scrollTo(0,E);},CheckIsEditable:function(A){var B=A.nodeName.toLowerCase();var C=FCK.DTD[B]||FCK.DTD.span;return (C['#']&&!FCKListsLib.NonEditableElements[B]);}}; +var FCKTools={};FCKTools.CreateBogusBR=function(A){var B=A.createElement('br');B.setAttribute('type','_moz');return B;};FCKTools.FixCssUrls=function(A,B){if (!A||A.length==0) return B;return B.replace(/url\s*\(([\s'"]*)(.*?)([\s"']*)\)/g,function(match,opener,path,closer){if (/^\/|^\w?:/.test(path)) return match;else return 'url('+opener+A+path+closer+')';});};FCKTools._GetUrlFixedCss=function(A,B){var C=A.match(/^([^|]+)\|([\s\S]*)/);if (C) return FCKTools.FixCssUrls(C[1],C[2]);else return A;};FCKTools.AppendStyleSheet=function(A,B){if (!B) return [];if (typeof(B)=='string'){if (/[\\\/\.]\w*$/.test(B)){return this.AppendStyleSheet(A,B.split(','));}else return [this.AppendStyleString(A,FCKTools._GetUrlFixedCss(B))];}else{var C=[];for (var i=0;i'+styleDef+'';};var C=function(cssFileUrl,markTemp){if (cssFileUrl.length==0) return '';var B=markTemp?' _fcktemp="true"':'';return '';};return function(cssFileOrArrayOrDef,markTemp){if (!cssFileOrArrayOrDef) return '';if (typeof(cssFileOrArrayOrDef)=='string'){if (/[\\\/\.]\w*$/.test(cssFileOrArrayOrDef)){return this.GetStyleHtml(cssFileOrArrayOrDef.split(','),markTemp);}else return A(this._GetUrlFixedCss(cssFileOrArrayOrDef),markTemp);}else{var E='';for (var i=0;i/g,'>');return A;};FCKTools.HTMLDecode=function(A){if (!A) return '';A=A.replace(/>/g,'>');A=A.replace(/</g,'<');A=A.replace(/&/g,'&');return A;};FCKTools._ProcessLineBreaksForPMode=function(A,B,C,D,E){var F=0;var G="

      ";var H="

      ";var I="
      ";if (C){G="
    7. ";H="
    8. ";F=1;};while (D&&D!=A.FCK.EditorDocument.body){if (D.tagName.toLowerCase()=='p'){F=1;break;};D=D.parentNode;};for (var i=0;i0) return A[A.length-1];return null;};FCKTools.GetDocumentPosition=function(w,A){var x=0;var y=0;var B=A;var C=null;var D=FCKTools.GetElementWindow(B);while (B&&!(D==w&&(B==w.document.body||B==w.document.documentElement))){x+=B.offsetLeft-B.scrollLeft;y+=B.offsetTop-B.scrollTop;if (!FCKBrowserInfo.IsOpera){var E=C;while (E&&E!=B){x-=E.scrollLeft;y-=E.scrollTop;E=E.parentNode;}};C=B;if (B.offsetParent) B=B.offsetParent;else{if (D!=w){B=D.frameElement;C=null;if (B) D=B.contentWindow.parent;}else B=null;}};if (FCKDomTools.GetCurrentElementStyle(w.document.body,'position')!='static'||(FCKBrowserInfo.IsIE&&FCKDomTools.GetPositionedAncestor(A)==null)){x+=w.document.body.offsetLeft;y+=w.document.body.offsetTop;};return { "x":x,"y":y };};FCKTools.GetWindowPosition=function(w,A){var B=this.GetDocumentPosition(w,A);var C=FCKTools.GetScrollPosition(w);B.x-=C.X;B.y-=C.Y;return B;};FCKTools.ProtectFormStyles=function(A){if (!A||A.nodeType!=1||A.tagName.toLowerCase()!='form') return [];var B=[];var C=['style','className'];for (var i=0;i0){for (var i=B.length-1;i>=0;i--){var C=B[i][0];var D=B[i][1];if (D) A.insertBefore(C,D);else A.appendChild(C);}}};FCKTools.GetNextNode=function(A,B){if (A.firstChild) return A.firstChild;else if (A.nextSibling) return A.nextSibling;else{var C=A.parentNode;while (C){if (C==B) return null;if (C.nextSibling) return C.nextSibling;else C=C.parentNode;}};return null;};FCKTools.GetNextTextNode=function(A,B,C){node=this.GetNextNode(A,B);if (C&&node&&C(node)) return null;while (node&&node.nodeType!=3){node=this.GetNextNode(node,B);if (C&&node&&C(node)) return null;};return node;};FCKTools.Merge=function(){var A=arguments;var o=A[0];for (var i=1;i');document.domain = '"+FCK_RUNTIME_DOMAIN+"';document.close();}() ) ;";if (FCKBrowserInfo.IsIE){if (FCKBrowserInfo.IsIE7||!FCKBrowserInfo.IsIE6) return "";else return "javascript: '';";};return "javascript: void(0);";}; +FCKTools.CancelEvent=function(e){return false;};FCKTools._AppendStyleSheet=function(A,B){return A.createStyleSheet(B).owningElement;};FCKTools.AppendStyleString=function(A,B){if (!B) return null;var s=A.createStyleSheet("");s.cssText=B;return s;};FCKTools.ClearElementAttributes=function(A){A.clearAttributes();};FCKTools.GetAllChildrenIds=function(A){var B=[];for (var i=0;i0) B[B.length]=C;};return B;};FCKTools.RemoveOuterTags=function(e){e.insertAdjacentHTML('beforeBegin',e.innerHTML);e.parentNode.removeChild(e);};FCKTools.CreateXmlObject=function(A){var B;switch (A){case 'XmlHttp':try { return new XMLHttpRequest();} catch (e) {};B=['MSXML2.XmlHttp','Microsoft.XmlHttp'];break;case 'DOMDocument':B=['MSXML2.DOMDocument','Microsoft.XmlDom'];break;};for (var i=0;i<2;i++){try { return new ActiveXObject(B[i]);}catch (e){}};if (FCKLang.NoActiveX){alert(FCKLang.NoActiveX);FCKLang.NoActiveX=null;};return null;};FCKTools.DisableSelection=function(A){A.unselectable='on';var e,i=0;while ((e=A.all[i++])){switch (e.tagName){case 'IFRAME':case 'TEXTAREA':case 'INPUT':case 'SELECT':break;default:e.unselectable='on';}}};FCKTools.GetScrollPosition=function(A){var B=A.document;var C={ X:B.documentElement.scrollLeft,Y:B.documentElement.scrollTop };if (C.X>0||C.Y>0) return C;return { X:B.body.scrollLeft,Y:B.body.scrollTop };};FCKTools.AddEventListener=function(A,B,C){A.attachEvent('on'+B,C);};FCKTools.RemoveEventListener=function(A,B,C){A.detachEvent('on'+B,C);};FCKTools.AddEventListenerEx=function(A,B,C,D){var o={};o.Source=A;o.Params=D||[];o.Listener=function(ev){return C.apply(o.Source,[ev].concat(o.Params));};if (FCK.IECleanup) FCK.IECleanup.AddItem(null,function() { o.Source=null;o.Params=null;});A.attachEvent('on'+B,o.Listener);A=null;D=null;};FCKTools.GetViewPaneSize=function(A){var B;var C=A.document.documentElement;if (C&&C.clientWidth) B=C;else B=A.document.body;if (B) return { Width:B.clientWidth,Height:B.clientHeight };else return { Width:0,Height:0 };};FCKTools.SaveStyles=function(A){var B=FCKTools.ProtectFormStyles(A);var C={};if (A.className.length>0){C.Class=A.className;A.className='';};var D=A.style.cssText;if (D.length>0){C.Inline=D;A.style.cssText='';};FCKTools.RestoreFormStyles(A,B);return C;};FCKTools.RestoreStyles=function(A,B){var C=FCKTools.ProtectFormStyles(A);A.className=B.Class||'';A.style.cssText=B.Inline||'';FCKTools.RestoreFormStyles(A,C);};FCKTools.RegisterDollarFunction=function(A){A.$=A.document.getElementById;};FCKTools.AppendElement=function(A,B){return A.appendChild(this.GetElementDocument(A).createElement(B));};FCKTools.ToLowerCase=function(A){return A.toLowerCase();}; +var FCKeditorAPI;function InitializeAPI(){var A=window.parent;if (!(FCKeditorAPI=A.FCKeditorAPI)){var B='window.FCKeditorAPI = {Version : "2.6",VersionBuild : "18638",Instances : new Object(),GetInstance : function( name ){return this.Instances[ name ];},_FormSubmit : function(){for ( var name in FCKeditorAPI.Instances ){var oEditor = FCKeditorAPI.Instances[ name ] ;if ( oEditor.GetParentForm && oEditor.GetParentForm() == this )oEditor.UpdateLinkedField() ;}this._FCKOriginalSubmit() ;},_FunctionQueue : {Functions : new Array(),IsRunning : false,Add : function( f ){this.Functions.push( f );if ( !this.IsRunning )this.StartNext();},StartNext : function(){var aQueue = this.Functions ;if ( aQueue.length > 0 ){this.IsRunning = true;aQueue[0].call();}else this.IsRunning = false;},Remove : function( f ){var aQueue = this.Functions;var i = 0, fFunc;while( (fFunc = aQueue[ i ]) ){if ( fFunc == f )aQueue.splice( i,1 );i++ ;}this.StartNext();}}}';if (A.execScript) A.execScript(B,'JavaScript');else{if (FCKBrowserInfo.IsGecko10){eval.call(A,B);}else if(FCKBrowserInfo.IsAIR){FCKAdobeAIR.FCKeditorAPI_Evaluate(A,B);}else if (FCKBrowserInfo.IsSafari||FCKBrowserInfo.IsGecko19){var C=A.document;var D=C.createElement('script');D.appendChild(C.createTextNode(B));C.documentElement.appendChild(D);}else A.eval(B);};FCKeditorAPI=A.FCKeditorAPI;FCKeditorAPI.__Instances=FCKeditorAPI.Instances;};FCKeditorAPI.Instances[FCK.Name]=FCK;};function _AttachFormSubmitToAPI(){var A=FCK.GetParentForm();if (A){FCKTools.AddEventListener(A,'submit',FCK.UpdateLinkedField);if (!A._FCKOriginalSubmit&&(typeof(A.submit)=='function'||(!A.submit.tagName&&!A.submit.length))){A._FCKOriginalSubmit=A.submit;A.submit=FCKeditorAPI._FormSubmit;}}};function FCKeditorAPI_Cleanup(){if (!window.FCKUnloadFlag) return;delete FCKeditorAPI.Instances[FCK.Name];};function FCKeditorAPI_ConfirmCleanup(){window.FCKUnloadFlag=true;};FCKTools.AddEventListener(window,'unload',FCKeditorAPI_Cleanup);FCKTools.AddEventListener(window,'beforeunload',FCKeditorAPI_ConfirmCleanup); +var FCKImagePreloader=function(){this._Images=[];};FCKImagePreloader.prototype={AddImages:function(A){if (typeof(A)=='string') A=A.split(';');this._Images=this._Images.concat(A);},Start:function(){var A=this._Images;this._PreloadCount=A.length;for (var i=0;i]*\>)/i,AfterBody:/(\<\/body\>[\s\S]*$)/i,ToReplace:/___fcktoreplace:([\w]+)/ig,MetaHttpEquiv:/http-equiv\s*=\s*["']?([^"' ]+)/i,HasBaseTag:/]/i,HtmlOpener:/]*>/i,HeadOpener:/]*>/i,HeadCloser:/<\/head\s*>/i,FCK_Class:/\s*FCK__[^ ]*(?=\s+|$)/,ElementName:/(^[a-z_:][\w.\-:]*\w$)|(^[a-z_]$)/,ForceSimpleAmpersand:/___FCKAmp___/g,SpaceNoClose:/\/>/g,EmptyParagraph:/^<(p|div|address|h\d|center)(?=[ >])[^>]*>\s*(<\/\1>)?$/,EmptyOutParagraph:/^<(p|div|address|h\d|center)(?=[ >])[^>]*>(?:\s*| )(<\/\1>)?$/,TagBody:/>]+))/gi,ProtectUrlsA:/]+))/gi,ProtectUrlsArea:/]+))/gi,Html4DocType:/HTML 4\.0 Transitional/i,DocTypeTag:/]*>/i,TagsWithEvent:/<[^\>]+ on\w+[\s\r\n]*=[\s\r\n]*?('|")[\s\S]+?\>/g,EventAttributes:/\s(on\w+)[\s\r\n]*=[\s\r\n]*?('|")([\s\S]*?)\2/g,ProtectedEvents:/\s\w+_fckprotectedatt="([^"]+)"/g,StyleProperties:/\S+\s*:/g,InvalidSelfCloseTags:/(<(?!base|meta|link|hr|br|param|img|area|input)([a-zA-Z0-9:]+)[^>]*)\/>/gi,StyleVariableAttName:/#\(\s*("|')(.+?)\1[^\)]*\s*\)/g,RegExp:/^\/(.*)\/([gim]*)$/,HtmlTag:/<[^\s<>](?:"[^"]*"|'[^']*'|[^<])*>/}; +var FCKListsLib={BlockElements:{ address:1,blockquote:1,center:1,div:1,dl:1,fieldset:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,marquee:1,noscript:1,ol:1,p:1,pre:1,script:1,table:1,ul:1 },NonEmptyBlockElements:{ p:1,div:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,address:1,pre:1,ol:1,ul:1,li:1,td:1,th:1 },InlineChildReqElements:{ abbr:1,acronym:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1 },InlineNonEmptyElements:{ a:1,abbr:1,acronym:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1 },EmptyElements:{ base:1,col:1,meta:1,link:1,hr:1,br:1,param:1,img:1,area:1,input:1 },PathBlockElements:{ address:1,blockquote:1,dl:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,p:1,pre:1,li:1,dt:1,de:1 },PathBlockLimitElements:{ body:1,div:1,td:1,th:1,caption:1,form:1 },StyleBlockElements:{ address:1,div:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,p:1,pre:1 },StyleObjectElements:{ img:1,hr:1,li:1,table:1,tr:1,td:1,embed:1,object:1,ol:1,ul:1 },NonEditableElements:{ button:1,option:1,script:1,iframe:1,textarea:1,object:1,embed:1,map:1,applet:1 },BlockBoundaries:{ p:1,div:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,address:1,pre:1,ol:1,ul:1,li:1,dt:1,de:1,table:1,thead:1,tbody:1,tfoot:1,tr:1,th:1,td:1,caption:1,col:1,colgroup:1,blockquote:1,body:1 },ListBoundaries:{ p:1,div:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,address:1,pre:1,ol:1,ul:1,li:1,dt:1,de:1,table:1,thead:1,tbody:1,tfoot:1,tr:1,th:1,td:1,caption:1,col:1,colgroup:1,blockquote:1,body:1,br:1 }}; +var FCKLanguageManager=FCK.Language={AvailableLanguages:{af:'Afrikaans',ar:'Arabic',bg:'Bulgarian',bn:'Bengali/Bangla',bs:'Bosnian',ca:'Catalan',cs:'Czech',da:'Danish',de:'German',el:'Greek',en:'English','en-au':'English (Australia)','en-ca':'English (Canadian)','en-uk':'English (United Kingdom)',eo:'Esperanto',es:'Spanish',et:'Estonian',eu:'Basque',fa:'Persian',fi:'Finnish',fo:'Faroese',fr:'French','fr-ca':'French (Canada)',gl:'Galician',he:'Hebrew',hi:'Hindi',hr:'Croatian',hu:'Hungarian',it:'Italian',ja:'Japanese',km:'Khmer',ko:'Korean',lt:'Lithuanian',lv:'Latvian',mn:'Mongolian',ms:'Malay',nb:'Norwegian Bokmal',nl:'Dutch',no:'Norwegian',pl:'Polish',pt:'Portuguese (Portugal)','pt-br':'Portuguese (Brazil)',ro:'Romanian',ru:'Russian',sk:'Slovak',sl:'Slovenian',sr:'Serbian (Cyrillic)','sr-latn':'Serbian (Latin)',sv:'Swedish',th:'Thai',tr:'Turkish',uk:'Ukrainian',vi:'Vietnamese',zh:'Chinese Traditional','zh-cn':'Chinese Simplified'},GetActiveLanguage:function(){if (FCKConfig.AutoDetectLanguage){var A;if (navigator.userLanguage) A=navigator.userLanguage.toLowerCase();else if (navigator.language) A=navigator.language.toLowerCase();else{return FCKConfig.DefaultLanguage;};if (A.length>=5){A=A.substr(0,5);if (this.AvailableLanguages[A]) return A;};if (A.length>=2){A=A.substr(0,2);if (this.AvailableLanguages[A]) return A;}};return this.DefaultLanguage;},TranslateElements:function(A,B,C,D){var e=A.getElementsByTagName(B);var E,s;for (var i=0;i0) C+='|'+FCKConfig.AdditionalNumericEntities;FCKXHtmlEntities.EntitiesRegex=new RegExp(C,'g');}; +var FCKXHtml={};FCKXHtml.CurrentJobNum=0;FCKXHtml.GetXHTML=function(A,B,C){FCKDomTools.CheckAndRemovePaddingNode(FCKTools.GetElementDocument(A),FCKConfig.EnterMode);FCKXHtmlEntities.Initialize();this._NbspEntity=(FCKConfig.ProcessHTMLEntities?'nbsp':'#160');var D=FCK.IsDirty();FCKXHtml.SpecialBlocks=[];this.XML=FCKTools.CreateXmlObject('DOMDocument');this.MainNode=this.XML.appendChild(this.XML.createElement('xhtml'));FCKXHtml.CurrentJobNum++;if (B) this._AppendNode(this.MainNode,A);else this._AppendChildNodes(this.MainNode,A,false);var E=this._GetMainXmlString();this.XML=null;if (FCKBrowserInfo.IsSafari) E=E.replace(/^/,'');E=E.substr(7,E.length-15).Trim();E=E.replace(FCKRegexLib.SpaceNoClose,' />');if (FCKConfig.ForceSimpleAmpersand) E=E.replace(FCKRegexLib.ForceSimpleAmpersand,'&');if (C) E=FCKCodeFormatter.Format(E);for (var i=0;i0;if (C) A.appendChild(this.XML.createTextNode(B.replace(FCKXHtmlEntities.EntitiesRegex,FCKXHtml_GetEntity)));return C;};function FCKXHtml_GetEntity(A){var B=FCKXHtmlEntities.Entities[A]||('#'+A.charCodeAt(0));return '#?-:'+B+';';};FCKXHtml.TagProcessors={a:function(A,B){if (B.innerHTML.Trim().length==0&&!B.name) return false;var C=B.getAttribute('_fcksavedurl');if (C!=null) FCKXHtml._AppendAttribute(A,'href',C);if (FCKBrowserInfo.IsIE){if (B.name) FCKXHtml._AppendAttribute(A,'name',B.name);};A=FCKXHtml._AppendChildNodes(A,B,false);return A;},area:function(A,B){var C=B.getAttribute('_fcksavedurl');if (C!=null) FCKXHtml._AppendAttribute(A,'href',C);if (FCKBrowserInfo.IsIE){if (!A.attributes.getNamedItem('coords')){var D=B.getAttribute('coords',2);if (D&&D!='0,0,0') FCKXHtml._AppendAttribute(A,'coords',D);};if (!A.attributes.getNamedItem('shape')){var E=B.getAttribute('shape',2);if (E&&E.length>0) FCKXHtml._AppendAttribute(A,'shape',E.toLowerCase());}};return A;},body:function(A,B){A=FCKXHtml._AppendChildNodes(A,B,false);A.removeAttribute('spellcheck');return A;},iframe:function(A,B){var C=B.innerHTML;if (FCKBrowserInfo.IsGecko) C=FCKTools.HTMLDecode(C);C=C.replace(/\s_fcksavedurl="[^"]*"/g,'');A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem(C)));return A;},img:function(A,B){if (!A.attributes.getNamedItem('alt')) FCKXHtml._AppendAttribute(A,'alt','');var C=B.getAttribute('_fcksavedurl');if (C!=null) FCKXHtml._AppendAttribute(A,'src',C);return A;},li:function(A,B,C){if (C.nodeName.IEquals(['ul','ol'])) return FCKXHtml._AppendChildNodes(A,B,true);var D=FCKXHtml.XML.createElement('ul');B._fckxhtmljob=null;do{FCKXHtml._AppendNode(D,B);do{B=FCKDomTools.GetNextSibling(B);} while (B&&B.nodeType==3&&B.nodeValue.Trim().length==0)} while (B&&B.nodeName.toLowerCase()=='li') return D;},ol:function(A,B,C){if (B.innerHTML.Trim().length==0) return false;var D=C.lastChild;if (D&&D.nodeType==3) D=D.previousSibling;if (D&&D.nodeName.toUpperCase()=='LI'){B._fckxhtmljob=null;FCKXHtml._AppendNode(D,B);return false;};A=FCKXHtml._AppendChildNodes(A,B);return A;},pre:function (A,B){var C=B.firstChild;if (C&&C.nodeType==3) A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem('\r\n')));FCKXHtml._AppendChildNodes(A,B,true);return A;},script:function(A,B){if (!A.attributes.getNamedItem('type')) FCKXHtml._AppendAttribute(A,'type','text/javascript');A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem(B.text)));return A;},span:function(A,B){if (B.innerHTML.length==0) return false;A=FCKXHtml._AppendChildNodes(A,B,false);return A;},style:function(A,B){if (!A.attributes.getNamedItem('type')) FCKXHtml._AppendAttribute(A,'type','text/css');var C=B.innerHTML;if (FCKBrowserInfo.IsIE) C=C.replace(/^(\r\n|\n|\r)/,'');A.appendChild(FCKXHtml.XML.createTextNode(FCKXHtml._AppendSpecialItem(C)));return A;},title:function(A,B){A.appendChild(FCKXHtml.XML.createTextNode(FCK.EditorDocument.title));return A;}};FCKXHtml.TagProcessors.ul=FCKXHtml.TagProcessors.ol; +FCKXHtml._GetMainXmlString=function(){return this.MainNode.xml;};FCKXHtml._AppendAttributes=function(A,B,C,D){var E=B.attributes;for (var n=0;n0) FCKXHtml._AppendAttribute(A,'align',B.align);A=FCKXHtml._AppendChildNodes(A,B,true);return A;};FCKXHtml.TagProcessors['font']=function(A,B){if (A.attributes.length==0) A=FCKXHtml.XML.createDocumentFragment();A=FCKXHtml._AppendChildNodes(A,B);return A;};FCKXHtml.TagProcessors['form']=function(A,B){if (B.acceptCharset&&B.acceptCharset.length>0&&B.acceptCharset!='UNKNOWN') FCKXHtml._AppendAttribute(A,'accept-charset',B.acceptCharset);var C=B.attributes['name'];if (C&&C.value.length>0) FCKXHtml._AppendAttribute(A,'name',C.value);A=FCKXHtml._AppendChildNodes(A,B,true);return A;};FCKXHtml.TagProcessors['input']=function(A,B){if (B.name) FCKXHtml._AppendAttribute(A,'name',B.name);if (B.value&&!A.attributes.getNamedItem('value')) FCKXHtml._AppendAttribute(A,'value',B.value);if (!A.attributes.getNamedItem('type')) FCKXHtml._AppendAttribute(A,'type','text');return A;};FCKXHtml.TagProcessors['label']=function(A,B){if (B.htmlFor.length>0) FCKXHtml._AppendAttribute(A,'for',B.htmlFor);A=FCKXHtml._AppendChildNodes(A,B);return A;};FCKXHtml.TagProcessors['map']=function(A,B){if (!A.attributes.getNamedItem('name')){var C=B.name;if (C) FCKXHtml._AppendAttribute(A,'name',C);};A=FCKXHtml._AppendChildNodes(A,B,true);return A;};FCKXHtml.TagProcessors['meta']=function(A,B){var C=A.attributes.getNamedItem('http-equiv');if (C==null||C.value.length==0){var D=B.outerHTML.match(FCKRegexLib.MetaHttpEquiv);if (D){D=D[1];FCKXHtml._AppendAttribute(A,'http-equiv',D);}};return A;};FCKXHtml.TagProcessors['option']=function(A,B){if (B.selected&&!A.attributes.getNamedItem('selected')) FCKXHtml._AppendAttribute(A,'selected','selected');A=FCKXHtml._AppendChildNodes(A,B);return A;};FCKXHtml.TagProcessors['textarea']=FCKXHtml.TagProcessors['select']=function(A,B){if (B.name) FCKXHtml._AppendAttribute(A,'name',B.name);A=FCKXHtml._AppendChildNodes(A,B);return A;}; +var FCKCodeFormatter={};FCKCodeFormatter.Init=function(){var A=this.Regex={};A.BlocksOpener=/\<(P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|TITLE|META|LINK|BASE|SCRIPT|LINK|TD|TH|AREA|OPTION)[^\>]*\>/gi;A.BlocksCloser=/\<\/(P|DIV|H1|H2|H3|H4|H5|H6|ADDRESS|PRE|OL|UL|LI|TITLE|META|LINK|BASE|SCRIPT|LINK|TD|TH|AREA|OPTION)[^\>]*\>/gi;A.NewLineTags=/\<(BR|HR)[^\>]*\>/gi;A.MainTags=/\<\/?(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR)[^\>]*\>/gi;A.LineSplitter=/\s*\n+\s*/g;A.IncreaseIndent=/^\<(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL)[ \/\>]/i;A.DecreaseIndent=/^\<\/(HTML|HEAD|BODY|FORM|TABLE|TBODY|THEAD|TR|UL|OL)[ \>]/i;A.FormatIndentatorRemove=new RegExp('^'+FCKConfig.FormatIndentator);A.ProtectedTags=/(]*>)([\s\S]*?)(<\/PRE>)/gi;};FCKCodeFormatter._ProtectData=function(A,B,C,D){return B+'___FCKpd___'+FCKCodeFormatter.ProtectedData.AddItem(C)+D;};FCKCodeFormatter.Format=function(A){if (!this.Regex) this.Init();FCKCodeFormatter.ProtectedData=[];var B=A.replace(this.Regex.ProtectedTags,FCKCodeFormatter._ProtectData);B=B.replace(this.Regex.BlocksOpener,'\n$&');B=B.replace(this.Regex.BlocksCloser,'$&\n');B=B.replace(this.Regex.NewLineTags,'$&\n');B=B.replace(this.Regex.MainTags,'\n$&\n');var C='';var D=B.split(this.Regex.LineSplitter);B='';for (var i=0;iB[i]) return 1;};if (A.lengthB.length) return 1;return 0;};FCKUndo._CheckIsBookmarksEqual=function(A,B){if (!(A&&B)) return false;if (FCKBrowserInfo.IsIE){var C=A[1].search(A[0].StartId);var D=B[1].search(B[0].StartId);var E=A[1].search(A[0].EndId);var F=B[1].search(B[0].EndId);return C==D&&E==F;}else{return this._CompareCursors(A.Start,B.Start)==0&&this._CompareCursors(A.End,B.End)==0;}};FCKUndo.SaveUndoStep=function(){if (FCK.EditMode!=0||this.SaveLocked) return;if (this.SavedData.length) this.Changed=true;var A=FCK.EditorDocument.body.innerHTML;var B=this._GetBookmark();this.SavedData=this.SavedData.slice(0,this.CurrentIndex+1);if (this.CurrentIndex>0&&A==this.SavedData[this.CurrentIndex][0]&&this._CheckIsBookmarksEqual(B,this.SavedData[this.CurrentIndex][1])) return;else if (this.CurrentIndex==0&&this.SavedData.length&&A==this.SavedData[0][0]){this.SavedData[0][1]=B;return;};if (this.CurrentIndex+1>=FCKConfig.MaxUndoLevels) this.SavedData.shift();else this.CurrentIndex++;this.SavedData[this.CurrentIndex]=[A,B];FCK.Events.FireEvent("OnSelectionChange");};FCKUndo.CheckUndoState=function(){return (this.Changed||this.CurrentIndex>0);};FCKUndo.CheckRedoState=function(){return (this.CurrentIndex<(this.SavedData.length-1));};FCKUndo.Undo=function(){if (this.CheckUndoState()){if (this.CurrentIndex==(this.SavedData.length-1)){this.SaveUndoStep();};this._ApplyUndoLevel(--this.CurrentIndex);FCK.Events.FireEvent("OnSelectionChange");}};FCKUndo.Redo=function(){if (this.CheckRedoState()){this._ApplyUndoLevel(++this.CurrentIndex);FCK.Events.FireEvent("OnSelectionChange");}};FCKUndo._ApplyUndoLevel=function(A){var B=this.SavedData[A];if (!B) return;if (FCKBrowserInfo.IsIE){if (B[1]&&B[1][1]) FCK.SetInnerHtml(B[1][1]);else FCK.SetInnerHtml(B[0]);}else FCK.EditorDocument.body.innerHTML=B[0];this._SelectBookmark(B[1]);this.TypesCount=0;this.Changed=false;this.Typing=false;}; +var FCKEditingArea=function(A){this.TargetElement=A;this.Mode=0;if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKEditingArea_Cleanup);};FCKEditingArea.prototype.Start=function(A,B){var C=this.TargetElement;var D=FCKTools.GetElementDocument(C);while(C.firstChild) C.removeChild(C.firstChild);if (this.Mode==0){if (FCK_IS_CUSTOM_DOMAIN) A=''+A;if (FCKBrowserInfo.IsIE) A=A.replace(/(]*?)\s*\/?>(?!\s*<\/base>)/gi,'$1>');else if (!B){var E=A.match(FCKRegexLib.BeforeBody);var F=A.match(FCKRegexLib.AfterBody);if (E&&F){var G=A.substr(E[1].length,A.length-E[1].length-F[1].length);A=E[1]+' '+F[1];if (FCKBrowserInfo.IsGecko&&(G.length==0||FCKRegexLib.EmptyParagraph.test(G))) G='
      ';this._BodyHTML=G;}else this._BodyHTML=A;};var H=this.IFrame=D.createElement('iframe');var I='';H.frameBorder=0;H.width=H.height='100%';if (FCK_IS_CUSTOM_DOMAIN&&FCKBrowserInfo.IsIE){window._FCKHtmlToLoad=I+A;H.src='javascript:void( (function(){document.open() ;document.domain="'+document.domain+'" ;document.write( window.parent._FCKHtmlToLoad );document.close() ;window.parent._FCKHtmlToLoad = null ;})() )';}else if (!FCKBrowserInfo.IsGecko){H.src='javascript:void(0)';};C.appendChild(H);this.Window=H.contentWindow;if (!FCK_IS_CUSTOM_DOMAIN||!FCKBrowserInfo.IsIE){var J=this.Window.document;J.open();J.write(I+A);J.close();};if (FCKBrowserInfo.IsAIR) FCKAdobeAIR.EditingArea_Start(J,A);if (FCKBrowserInfo.IsGecko10&&!B){this.Start(A,true);return;};if (H.readyState&&H.readyState!='completed'){var K=this;(H.onreadystatechange=function(){if (H.readyState=='complete'){H.onreadystatechange=null;K.Window._FCKEditingArea=K;FCKEditingArea_CompleteStart.call(K.Window);}})();}else{this.Window._FCKEditingArea=this;if (FCKBrowserInfo.IsGecko10) this.Window.setTimeout(FCKEditingArea_CompleteStart,500);else FCKEditingArea_CompleteStart.call(this.Window);}}else{var L=this.Textarea=D.createElement('textarea');L.className='SourceField';L.dir='ltr';FCKDomTools.SetElementStyles(L,{width:'100%',height:'100%',border:'none',resize:'none',outline:'none'});C.appendChild(L);L.value=A;FCKTools.RunFunction(this.OnLoad);}};function FCKEditingArea_CompleteStart(){if (!this.document.body){this.setTimeout(FCKEditingArea_CompleteStart,50);return;};var A=this._FCKEditingArea;A.Document=A.Window.document;A.MakeEditable();FCKTools.RunFunction(A.OnLoad);};FCKEditingArea.prototype.MakeEditable=function(){var A=this.Document;if (FCKBrowserInfo.IsIE){A.body.disabled=true;A.body.contentEditable=true;A.body.removeAttribute("disabled");}else{try{A.body.spellcheck=(this.FFSpellChecker!==false);if (this._BodyHTML){A.body.innerHTML=this._BodyHTML;this._BodyHTML=null;};A.designMode='on';A.execCommand('enableObjectResizing',false,!FCKConfig.DisableObjectResizing);A.execCommand('enableInlineTableEditing',false,!FCKConfig.DisableFFTableHandles);}catch (e){FCKTools.AddEventListener(this.Window.frameElement,'DOMAttrModified',FCKEditingArea_Document_AttributeNodeModified);}}};function FCKEditingArea_Document_AttributeNodeModified(A){var B=A.currentTarget.contentWindow._FCKEditingArea;if (B._timer) window.clearTimeout(B._timer);B._timer=FCKTools.SetTimeout(FCKEditingArea_MakeEditableByMutation,1000,B);};function FCKEditingArea_MakeEditableByMutation(){delete this._timer;FCKTools.RemoveEventListener(this.Window.frameElement,'DOMAttrModified',FCKEditingArea_Document_AttributeNodeModified);this.MakeEditable();};FCKEditingArea.prototype.Focus=function(){try{if (this.Mode==0){if (FCKBrowserInfo.IsIE) this._FocusIE();else this.Window.focus();}else{var A=FCKTools.GetElementDocument(this.Textarea);if ((!A.hasFocus||A.hasFocus())&&A.activeElement==this.Textarea) return;this.Textarea.focus();}}catch(e) {}};FCKEditingArea.prototype._FocusIE=function(){this.Document.body.setActive();this.Window.focus();var A=this.Document.selection.createRange();var B=A.parentElement();var C=B.nodeName.toLowerCase();if (B.childNodes.length>0||!(FCKListsLib.BlockElements[C]||FCKListsLib.NonEmptyBlockElements[C])){return;};A=new FCKDomRange(this.Window);A.MoveToElementEditStart(B);A.Select();};function FCKEditingArea_Cleanup(){if (this.Document) this.Document.body.innerHTML="";this.TargetElement=null;this.IFrame=null;this.Document=null;this.Textarea=null;if (this.Window){this.Window._FCKEditingArea=null;this.Window=null;}}; +var FCKKeystrokeHandler=function(A){this.Keystrokes={};this.CancelCtrlDefaults=(A!==false);};FCKKeystrokeHandler.prototype.AttachToElement=function(A){FCKTools.AddEventListenerEx(A,'keydown',_FCKKeystrokeHandler_OnKeyDown,this);if (FCKBrowserInfo.IsGecko10||FCKBrowserInfo.IsOpera||(FCKBrowserInfo.IsGecko&&FCKBrowserInfo.IsMac)) FCKTools.AddEventListenerEx(A,'keypress',_FCKKeystrokeHandler_OnKeyPress,this);};FCKKeystrokeHandler.prototype.SetKeystrokes=function(){for (var i=0;i40))){B._CancelIt=true;if (A.preventDefault) return A.preventDefault();A.returnValue=false;A.cancelBubble=true;return false;};return true;};function _FCKKeystrokeHandler_OnKeyPress(A,B){if (B._CancelIt){if (A.preventDefault) return A.preventDefault();return false;};return true;}; +FCK.DTD=(function(){var X=FCKTools.Merge;var A,L,J,M,N,O,D,H,P,K,Q,F,G,C,B,E,I;A={isindex:1,fieldset:1};B={input:1,button:1,select:1,textarea:1,label:1};C=X({a:1},B);D=X({iframe:1},C);E={hr:1,ul:1,menu:1,div:1,blockquote:1,noscript:1,table:1,center:1,address:1,dir:1,pre:1,h5:1,dl:1,h4:1,noframes:1,h6:1,ol:1,h1:1,h3:1,h2:1};F={ins:1,del:1,script:1};G=X({b:1,acronym:1,bdo:1,'var':1,'#':1,abbr:1,code:1,br:1,i:1,cite:1,kbd:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,dfn:1,span:1},F);H=X({sub:1,img:1,object:1,sup:1,basefont:1,map:1,applet:1,font:1,big:1,small:1},G);I=X({p:1},H);J=X({iframe:1},H,B);K={img:1,noscript:1,br:1,kbd:1,center:1,button:1,basefont:1,h5:1,h4:1,samp:1,h6:1,ol:1,h1:1,h3:1,h2:1,form:1,font:1,'#':1,select:1,menu:1,ins:1,abbr:1,label:1,code:1,table:1,script:1,cite:1,input:1,iframe:1,strong:1,textarea:1,noframes:1,big:1,small:1,span:1,hr:1,sub:1,bdo:1,'var':1,div:1,object:1,sup:1,strike:1,dir:1,map:1,dl:1,applet:1,del:1,isindex:1,fieldset:1,ul:1,b:1,acronym:1,a:1,blockquote:1,i:1,u:1,s:1,tt:1,address:1,q:1,pre:1,p:1,em:1,dfn:1};L=X({a:1},J);M={tr:1};N={'#':1};O=X({param:1},K);P=X({form:1},A,D,E,I);Q={li:1};return {col:{},tr:{td:1,th:1},img:{},colgroup:{col:1},noscript:P,td:P,br:{},th:P,center:P,kbd:L,button:X(I,E),basefont:{},h5:L,h4:L,samp:L,h6:L,ol:Q,h1:L,h3:L,option:N,h2:L,form:X(A,D,E,I),select:{optgroup:1,option:1},font:J,ins:P,menu:Q,abbr:L,label:L,table:{thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1},code:L,script:N,tfoot:M,cite:L,li:P,input:{},iframe:P,strong:J,textarea:N,noframes:P,big:J,small:J,span:J,hr:{},dt:L,sub:J,optgroup:{option:1},param:{},bdo:L,'var':J,div:P,object:O,sup:J,dd:P,strike:J,area:{},dir:Q,map:X({area:1,form:1,p:1},A,F,E),applet:O,dl:{dt:1,dd:1},del:P,isindex:{},fieldset:X({legend:1},K),thead:M,ul:Q,acronym:L,b:J,a:J,blockquote:P,caption:L,i:J,u:J,tbody:M,s:L,address:X(D,I),tt:J,legend:L,q:L,pre:X(G,C),p:L,em:J,dfn:L};})(); +var FCKStyle=function(A){this.Element=(A.Element||'span').toLowerCase();this._StyleDesc=A;};FCKStyle.prototype={GetType:function(){var A=this.GetType_$;if (A!=undefined) return A;var B=this.Element;if (B=='#'||FCKListsLib.StyleBlockElements[B]) A=0;else if (FCKListsLib.StyleObjectElements[B]) A=2;else A=1;return (this.GetType_$=A);},ApplyToSelection:function(A){var B=new FCKDomRange(A);B.MoveToSelection();this.ApplyToRange(B,true);},ApplyToRange:function(A,B,C){switch (this.GetType()){case 0:this.ApplyToRange=this._ApplyBlockStyle;break;case 1:this.ApplyToRange=this._ApplyInlineStyle;break;default:return;};this.ApplyToRange(A,B,C);},ApplyToObject:function(A){if (!A) return;this.BuildElement(null,A);},RemoveFromSelection:function(A){var B=new FCKDomRange(A);B.MoveToSelection();this.RemoveFromRange(B,true);},RemoveFromRange:function(A,B,C){var D;var E=this._GetAttribsForComparison();var F=this._GetOverridesForComparison();if (A.CheckIsCollapsed()){var D=A.CreateBookmark(true);var H=A.GetBookmarkNode(D,true);var I=new FCKElementPath(H.parentNode);var J=[];var K=!FCKDomTools.GetNextSibling(H);var L=K||!FCKDomTools.GetPreviousSibling(H);var M;var N=-1;for (var i=0;i=0;i--){var E=D[i];for (var F in B){if (FCKDomTools.HasAttribute(E,F)){switch (F){case 'style':this._RemoveStylesFromElement(E);break;case 'class':if (FCKDomTools.GetAttributeValue(E,F)!=this.GetFinalAttributeValue(F)) continue;default:FCKDomTools.RemoveAttribute(E,F);}}};this._RemoveOverrides(E,C[this.Element]);this._RemoveNoAttribElement(E);};for (var G in C){if (G!=this.Element){D=A.getElementsByTagName(G);for (var i=D.length-1;i>=0;i--){var E=D[i];this._RemoveOverrides(E,C[G]);this._RemoveNoAttribElement(E);}}}},_RemoveStylesFromElement:function(A){var B=A.style.cssText;var C=this.GetFinalStyleValue();if (B.length>0&&C.length==0) return;C='(^|;)\\s*('+C.replace(/\s*([^ ]+):.*?(;|$)/g,'$1|').replace(/\|$/,'')+'):[^;]+';var D=new RegExp(C,'gi');B=B.replace(D,'').Trim();if (B.length==0||B==';') FCKDomTools.RemoveAttribute(A,'style');else A.style.cssText=B.replace(D,'');},_RemoveOverrides:function(A,B){var C=B&&B.Attributes;if (C){for (var i=0;i0) C.style.cssText=this.GetFinalStyleValue();return C;},_CompareAttributeValues:function(A,B,C){if (A=='style'&&B&&C){B=B.replace(/;$/,'').toLowerCase();C=C.replace(/;$/,'').toLowerCase();};return (B==C||((B===null||B==='')&&(C===null||C==='')))},GetFinalAttributeValue:function(A){var B=this._StyleDesc.Attributes;var B=B?B[A]:null;if (!B&&A=='style') return this.GetFinalStyleValue();if (B&&this._Variables) B=B.Replace(FCKRegexLib.StyleVariableAttName,this._GetVariableReplace,this);return B;},GetFinalStyleValue:function(){var A=this._GetStyleText();if (A.length>0&&this._Variables){A=A.Replace(FCKRegexLib.StyleVariableAttName,this._GetVariableReplace,this);A=FCKTools.NormalizeCssText(A);};return A;},_GetVariableReplace:function(){return this._Variables[arguments[2]]||arguments[0];},SetVariable:function(A,B){var C=this._Variables;if (!C) C=this._Variables={};this._Variables[A]=B;},_FromPre:function(A,B,C){var D=B.innerHTML;D=D.replace(/(\r\n|\r)/g,'\n');D=D.replace(/^[ \t]*\n/,'');D=D.replace(/\n$/,'');D=D.replace(/^[ \t]+|[ \t]+$/g,function(match,offset,s){if (match.length==1) return ' ';else if (offset==0) return new Array(match.length).join(' ')+' ';else return ' '+new Array(match.length).join(' ');});var E=new FCKHtmlIterator(D);var F=[];E.Each(function(isTag,value){if (!isTag){value=value.replace(/\n/g,'
      ');value=value.replace(/[ \t]{2,}/g,function (match){return new Array(match.length).join(' ')+' ';});};F.push(value);});C.innerHTML=F.join('');return C;},_ToPre:function(A,B,C){var D=B.innerHTML.Trim();D=D.replace(/[ \t\r\n]*(]*>)[ \t\r\n]*/gi,'
      ');var E=new FCKHtmlIterator(D);var F=[];E.Each(function(isTag,value){if (!isTag) value=value.replace(/([ \t\n\r]+| )/g,' ');else if (isTag&&value=='
      ') value='\n';F.push(value);});if (FCKBrowserInfo.IsIE){var G=A.createElement('div');G.appendChild(C);C.outerHTML='
      \n'+F.join('')+'
      ';C=G.removeChild(G.firstChild);}else C.innerHTML=F.join('');return C;},_ApplyBlockStyle:function(A,B,C){var D;if (B) D=A.CreateBookmark();var E=new FCKDomRangeIterator(A);E.EnforceRealBlocks=true;var F;var G=A.Window.document;var H=[];var I=[];while((F=E.GetNextParagraph())){var J=this.BuildElement(G);var K=J.nodeName.IEquals('pre');var L=F.nodeName.IEquals('pre');if (K&&!L){J=this._ToPre(G,F,J);H.push(J);}else if (!K&&L){J=this._FromPre(G,F,J);I.push(J);}else FCKDomTools.MoveChildren(F,J);F.parentNode.insertBefore(J,F);FCKDomTools.RemoveNode(F);};for (var i=0;i0){A.InsertNode(I);this.RemoveFromElement(I);this._MergeSiblings(I,this._GetAttribsForComparison());if (!FCKBrowserInfo.IsIE) I.normalize();};A.Release(true);}};this._FixBookmarkStart(K);if (B) A.SelectBookmark(J);if (C) A.MoveToBookmark(J);},_FixBookmarkStart:function(A){var B;while ((B=A.nextSibling)){if (B.nodeType==1&&FCKListsLib.InlineNonEmptyElements[B.nodeName.toLowerCase()]){if (!B.firstChild) FCKDomTools.RemoveNode(B);else FCKDomTools.MoveNode(A,B,true);continue;};if (B.nodeType==3&&B.length==0){FCKDomTools.RemoveNode(B);continue;};break;}},_MergeSiblings:function(A,B){if (!A||A.nodeType!=1||!FCKListsLib.InlineNonEmptyElements[A.nodeName.toLowerCase()]) return;this._MergeNextSibling(A,B);this._MergePreviousSibling(A,B);},_MergeNextSibling:function(A,B){var C=A.nextSibling;var D=(C&&C.nodeType==1&&C.getAttribute('_fck_bookmark'));if (D) C=C.nextSibling;if (C&&C.nodeType==1&&C.nodeName==A.nodeName){if (!B) B=this._CreateElementAttribsForComparison(A);if (this._CheckAttributesMatch(C,B)){var E=A.lastChild;if (D) FCKDomTools.MoveNode(A.nextSibling,A);FCKDomTools.MoveChildren(C,A);FCKDomTools.RemoveNode(C);if (E) this._MergeNextSibling(E);}}},_MergePreviousSibling:function(A,B){var C=A.previousSibling;var D=(C&&C.nodeType==1&&C.getAttribute('_fck_bookmark'));if (D) C=C.previousSibling;if (C&&C.nodeType==1&&C.nodeName==A.nodeName){if (!B) B=this._CreateElementAttribsForComparison(A);if (this._CheckAttributesMatch(C,B)){var E=A.firstChild;if (D) FCKDomTools.MoveNode(A.previousSibling,A,true);FCKDomTools.MoveChildren(C,A,true);FCKDomTools.RemoveNode(C);if (E) this._MergePreviousSibling(E);}}},_GetStyleText:function(){var A=this._StyleDesc.Styles;var B=(this._StyleDesc.Attributes?this._StyleDesc.Attributes['style']||'':'');if (B.length>0) B+=';';for (var C in A) B+=C+':'+A[C]+';';if (B.length>0&&!(/#\(/.test(B))){B=FCKTools.NormalizeCssText(B);};return (this._GetStyleText=function() { return B;})();},_GetAttribsForComparison:function(){var A=this._GetAttribsForComparison_$;if (A) return A;A={};var B=this._StyleDesc.Attributes;if (B){for (var C in B){A[C.toLowerCase()]=B[C].toLowerCase();}};if (this._GetStyleText().length>0){A['style']=this._GetStyleText().toLowerCase();};FCKTools.AppendLengthProperty(A,'_length');return (this._GetAttribsForComparison_$=A);},_GetOverridesForComparison:function(){var A=this._GetOverridesForComparison_$;if (A) return A;A={};var B=this._StyleDesc.Overrides;if (B){if (!FCKTools.IsArray(B)) B=[B];for (var i=0;i0) return true;};B=B.nextSibling;};return false;}}; +var FCKElementPath=function(A){var B=null;var C=null;var D=[];var e=A;while (e){if (e.nodeType==1){if (!this.LastElement) this.LastElement=e;var E=e.nodeName.toLowerCase();if (FCKBrowserInfo.IsIE&&e.scopeName!='HTML') E=e.scopeName.toLowerCase()+':'+E;if (!C){if (!B&&FCKListsLib.PathBlockElements[E]!=null) B=e;if (FCKListsLib.PathBlockLimitElements[E]!=null){if (!B&&E=='div'&&!FCKElementPath._CheckHasBlock(e)) B=e;else C=e;}};D.push(e);if (E=='body') break;};e=e.parentNode;};this.Block=B;this.BlockLimit=C;this.Elements=D;};FCKElementPath._CheckHasBlock=function(A){var B=A.childNodes;for (var i=0,count=B.length;i0){if (D.nodeType==3){var G=D.nodeValue.substr(0,E).Trim();if (G.length!=0) return A.IsStartOfBlock=false;}else F=D.childNodes[E-1];};if (!F) F=FCKDomTools.GetPreviousSourceNode(D,true,null,C);while (F){switch (F.nodeType){case 1:if (!FCKListsLib.InlineChildReqElements[F.nodeName.toLowerCase()]) return A.IsStartOfBlock=false;break;case 3:if (F.nodeValue.Trim().length>0) return A.IsStartOfBlock=false;};F=FCKDomTools.GetPreviousSourceNode(F,false,null,C);};return A.IsStartOfBlock=true;},CheckEndOfBlock:function(A){var B=this._Cache.IsEndOfBlock;if (B!=undefined) return B;var C=this.EndBlock||this.EndBlockLimit;var D=this._Range.endContainer;var E=this._Range.endOffset;var F;if (D.nodeType==3){var G=D.nodeValue;if (E0) return this._Cache.IsEndOfBlock=false;};F=FCKDomTools.GetNextSourceNode(F,false,null,C);};if (A) this.Select();return this._Cache.IsEndOfBlock=true;},CreateBookmark:function(A){var B={StartId:(new Date()).valueOf()+Math.floor(Math.random()*1000)+'S',EndId:(new Date()).valueOf()+Math.floor(Math.random()*1000)+'E'};var C=this.Window.document;var D;var E;var F;if (!this.CheckIsCollapsed()){E=C.createElement('span');E.style.display='none';E.id=B.EndId;E.setAttribute('_fck_bookmark',true);E.innerHTML=' ';F=this.Clone();F.Collapse(false);F.InsertNode(E);};D=C.createElement('span');D.style.display='none';D.id=B.StartId;D.setAttribute('_fck_bookmark',true);D.innerHTML=' ';F=this.Clone();F.Collapse(true);F.InsertNode(D);if (A){B.StartNode=D;B.EndNode=E;};if (E){this.SetStart(D,4);this.SetEnd(E,3);}else this.MoveToPosition(D,4);return B;},GetBookmarkNode:function(A,B){var C=this.Window.document;if (B) return A.StartNode||C.getElementById(A.StartId);else return A.EndNode||C.getElementById(A.EndId);},MoveToBookmark:function(A,B){var C=this.GetBookmarkNode(A,true);var D=this.GetBookmarkNode(A,false);this.SetStart(C,3);if (!B) FCKDomTools.RemoveNode(C);if (D){this.SetEnd(D,3);if (!B) FCKDomTools.RemoveNode(D);}else this.Collapse(true);this._UpdateElementInfo();},CreateBookmark2:function(){if (!this._Range) return { "Start":0,"End":0 };var A={"Start":[this._Range.startOffset],"End":[this._Range.endOffset]};var B=this._Range.startContainer.previousSibling;var C=this._Range.endContainer.previousSibling;var D=this._Range.startContainer;var E=this._Range.endContainer;while (B&&B.nodeType==3){A.Start[0]+=B.length;D=B;B=B.previousSibling;};while (C&&C.nodeType==3){A.End[0]+=C.length;E=C;C=C.previousSibling;};if (D.nodeType==1&&D.childNodes[A.Start[0]]&&D.childNodes[A.Start[0]].nodeType==3){var F=D.childNodes[A.Start[0]];var G=0;while (F.previousSibling&&F.previousSibling.nodeType==3){F=F.previousSibling;G+=F.length;};D=F;A.Start[0]=G;};if (E.nodeType==1&&E.childNodes[A.End[0]]&&E.childNodes[A.End[0]].nodeType==3){var F=E.childNodes[A.End[0]];var G=0;while (F.previousSibling&&F.previousSibling.nodeType==3){F=F.previousSibling;G+=F.length;};E=F;A.End[0]=G;};A.Start=FCKDomTools.GetNodeAddress(D,true).concat(A.Start);A.End=FCKDomTools.GetNodeAddress(E,true).concat(A.End);return A;},MoveToBookmark2:function(A){var B=FCKDomTools.GetNodeFromAddress(this.Window.document,A.Start.slice(0,-1),true);var C=FCKDomTools.GetNodeFromAddress(this.Window.document,A.End.slice(0,-1),true);this.Release(true);this._Range=new FCKW3CRange(this.Window.document);var D=A.Start[A.Start.length-1];var E=A.End[A.End.length-1];while (B.nodeType==3&&D>B.length){if (!B.nextSibling||B.nextSibling.nodeType!=3) break;D-=B.length;B=B.nextSibling;};while (C.nodeType==3&&E>C.length){if (!C.nextSibling||C.nextSibling.nodeType!=3) break;E-=C.length;C=C.nextSibling;};this._Range.setStart(B,D);this._Range.setEnd(C,E);this._UpdateElementInfo();},MoveToPosition:function(A,B){this.SetStart(A,B);this.Collapse(true);},SetStart:function(A,B,C){var D=this._Range;if (!D) D=this._Range=this.CreateRange();switch(B){case 1:D.setStart(A,0);break;case 2:D.setStart(A,A.childNodes.length);break;case 3:D.setStartBefore(A);break;case 4:D.setStartAfter(A);};if (!C) this._UpdateElementInfo();},SetEnd:function(A,B,C){var D=this._Range;if (!D) D=this._Range=this.CreateRange();switch(B){case 1:D.setEnd(A,0);break;case 2:D.setEnd(A,A.childNodes.length);break;case 3:D.setEndBefore(A);break;case 4:D.setEndAfter(A);};if (!C) this._UpdateElementInfo();},Expand:function(A){var B,oSibling;switch (A){case 'inline_elements':if (this._Range.startOffset==0){B=this._Range.startContainer;if (B.nodeType!=1) B=B.previousSibling?null:B.parentNode;if (B){while (FCKListsLib.InlineNonEmptyElements[B.nodeName.toLowerCase()]){this._Range.setStartBefore(B);if (B!=B.parentNode.firstChild) break;B=B.parentNode;}}};B=this._Range.endContainer;var C=this._Range.endOffset;if ((B.nodeType==3&&C>=B.nodeValue.length)||(B.nodeType==1&&C>=B.childNodes.length)||(B.nodeType!=1&&B.nodeType!=3)){if (B.nodeType!=1) B=B.nextSibling?null:B.parentNode;if (B){while (FCKListsLib.InlineNonEmptyElements[B.nodeName.toLowerCase()]){this._Range.setEndAfter(B);if (B!=B.parentNode.lastChild) break;B=B.parentNode;}}};break;case 'block_contents':case 'list_contents':var D=FCKListsLib.BlockBoundaries;if (A=='list_contents'||FCKConfig.EnterMode=='br') D=FCKListsLib.ListBoundaries;if (this.StartBlock&&FCKConfig.EnterMode!='br'&&A=='block_contents') this.SetStart(this.StartBlock,1);else{B=this._Range.startContainer;if (B.nodeType==1){var E=B.childNodes[this._Range.startOffset];if (E) B=FCKDomTools.GetPreviousSourceNode(E,true);else B=B.lastChild||B;};while (B&&(B.nodeType!=1||(B!=this.StartBlockLimit&&!D[B.nodeName.toLowerCase()]))){this._Range.setStartBefore(B);B=B.previousSibling||B.parentNode;}};if (this.EndBlock&&FCKConfig.EnterMode!='br'&&A=='block_contents'&&this.EndBlock.nodeName.toLowerCase()!='li') this.SetEnd(this.EndBlock,2);else{B=this._Range.endContainer;if (B.nodeType==1) B=B.childNodes[this._Range.endOffset]||B.lastChild;while (B&&(B.nodeType!=1||(B!=this.StartBlockLimit&&!D[B.nodeName.toLowerCase()]))){this._Range.setEndAfter(B);B=B.nextSibling||B.parentNode;};if (B&&B.nodeName.toLowerCase()=='br') this._Range.setEndAfter(B);};this._UpdateElementInfo();}},SplitBlock:function(A){var B=A||FCKConfig.EnterMode;if (!this._Range) this.MoveToSelection();if (this.StartBlockLimit==this.EndBlockLimit){var C=this.StartBlock;var D=this.EndBlock;var E=null;if (B!='br'){if (!C){C=this.FixBlock(true,B);D=this.EndBlock;};if (!D) D=this.FixBlock(false,B);};var F=(C!=null&&this.CheckStartOfBlock());var G=(D!=null&&this.CheckEndOfBlock());if (!this.CheckIsEmpty()) this.DeleteContents();if (C&&D&&C==D){if (G){E=new FCKElementPath(this.StartContainer);this.MoveToPosition(D,4);D=null;}else if (F){E=new FCKElementPath(this.StartContainer);this.MoveToPosition(C,3);C=null;}else{this.SetEnd(C,2);var H=this.ExtractContents();D=C.cloneNode(false);D.removeAttribute('id',false);H.AppendTo(D);FCKDomTools.InsertAfterNode(C,D);this.MoveToPosition(C,4);if (FCKBrowserInfo.IsGecko&&!C.nodeName.IEquals(['ul','ol'])) FCKTools.AppendBogusBr(C);}};return {PreviousBlock:C,NextBlock:D,WasStartOfBlock:F,WasEndOfBlock:G,ElementPath:E};};return null;},FixBlock:function(A,B){var C=this.CreateBookmark();this.Collapse(A);this.Expand('block_contents');var D=this.Window.document.createElement(B);this.ExtractContents().AppendTo(D);FCKDomTools.TrimNode(D);this.InsertNode(D);this.MoveToBookmark(C);return D;},Release:function(A){if (!A) this.Window=null;this.StartNode=null;this.StartContainer=null;this.StartBlock=null;this.StartBlockLimit=null;this.EndNode=null;this.EndContainer=null;this.EndBlock=null;this.EndBlockLimit=null;this._Range=null;this._Cache=null;},CheckHasRange:function(){return!!this._Range;},GetTouchedStartNode:function(){var A=this._Range;var B=A.startContainer;if (A.collapsed||B.nodeType!=1) return B;return B.childNodes[A.startOffset]||B;},GetTouchedEndNode:function(){var A=this._Range;var B=A.endContainer;if (A.collapsed||B.nodeType!=1) return B;return B.childNodes[A.endOffset-1]||B;}}; +FCKDomRange.prototype.MoveToSelection=function(){this.Release(true);this._Range=new FCKW3CRange(this.Window.document);var A=this.Window.document.selection;if (A.type!='Control'){var B=this._GetSelectionMarkerTag(true);var C=this._GetSelectionMarkerTag(false);if (!B&&!C){this._Range.setStart(this.Window.document.body,0);this._UpdateElementInfo();return;};this._Range.setStart(B.parentNode,FCKDomTools.GetIndexOf(B));B.parentNode.removeChild(B);this._Range.setEnd(C.parentNode,FCKDomTools.GetIndexOf(C));C.parentNode.removeChild(C);this._UpdateElementInfo();}else{var D=A.createRange().item(0);if (D){this._Range.setStartBefore(D);this._Range.setEndAfter(D);this._UpdateElementInfo();}}};FCKDomRange.prototype.Select=function(A){if (this._Range) this.SelectBookmark(this.CreateBookmark(true),A);};FCKDomRange.prototype.SelectBookmark=function(A,B){var C=this.CheckIsCollapsed();var D;var E;var F=this.GetBookmarkNode(A,true);if (!F) return;var G;if (!C) G=this.GetBookmarkNode(A,false);var H=this.Window.document.body.createTextRange();H.moveToElementText(F);H.moveStart('character',1);if (G){var I=this.Window.document.body.createTextRange();I.moveToElementText(G);H.setEndPoint('EndToEnd',I);H.moveEnd('character',-1);}else{D=(B||!F.previousSibling||F.previousSibling.nodeName.toLowerCase()=='br')&&!F.nextSibing;E=this.Window.document.createElement('span');E.innerHTML='';F.parentNode.insertBefore(E,F);if (D){F.parentNode.insertBefore(this.Window.document.createTextNode('\ufeff'),F);}};if (!this._Range) this._Range=this.CreateRange();this._Range.setStartBefore(F);F.parentNode.removeChild(F);if (C){if (D){H.moveStart('character',-1);H.select();this.Window.document.selection.clear();}else H.select();FCKDomTools.RemoveNode(E);}else{this._Range.setEndBefore(G);G.parentNode.removeChild(G);H.select();}};FCKDomRange.prototype._GetSelectionMarkerTag=function(A){var B=this.Window.document;var C=B.selection;var D;try{D=C.createRange();}catch (e){return null;};if (D.parentElement().document!=B) return null;D.collapse(A===true);var E='fck_dom_range_temp_'+(new Date()).valueOf()+'_'+Math.floor(Math.random()*1000);D.pasteHTML('');return B.getElementById(E);}; +var FCKDomRangeIterator=function(A){this.Range=A;this.ForceBrBreak=false;this.EnforceRealBlocks=false;};FCKDomRangeIterator.CreateFromSelection=function(A){var B=new FCKDomRange(A);B.MoveToSelection();return new FCKDomRangeIterator(B);};FCKDomRangeIterator.prototype={GetNextParagraph:function(){var A;var B;var C;var D;var E;var F=this.ForceBrBreak?FCKListsLib.ListBoundaries:FCKListsLib.BlockBoundaries;if (!this._LastNode){var B=this.Range.Clone();B.Expand(this.ForceBrBreak?'list_contents':'block_contents');this._NextNode=B.GetTouchedStartNode();this._LastNode=B.GetTouchedEndNode();B=null;};var H=this._NextNode;var I=this._LastNode;this._NextNode=null;while (H){var J=false;var K=(H.nodeType!=1);var L=false;if (!K){var M=H.nodeName.toLowerCase();if (F[M]&&(!FCKBrowserInfo.IsIE||H.scopeName=='HTML')){if (M=='br') K=true;else if (!B&&H.childNodes.length==0&&M!='hr'){A=H;C=H==I;break;};if (B){B.SetEnd(H,3,true);if (M!='br') this._NextNode=H;};J=true;}else{if (H.firstChild){if (!B){B=new FCKDomRange(this.Range.Window);B.SetStart(H,3,true);};H=H.firstChild;continue;};K=true;}}else if (H.nodeType==3){if (/^[\r\n\t ]+$/.test(H.nodeValue)) K=false;};if (K&&!B){B=new FCKDomRange(this.Range.Window);B.SetStart(H,3,true);};C=((!J||K)&&H==I);if (B&&!J){while (!H.nextSibling&&!C){var N=H.parentNode;if (F[N.nodeName.toLowerCase()]){J=true;C=C||(N==I);break;};H=N;K=true;C=(H==I);L=true;}};if (K) B.SetEnd(H,4,true);if ((J||C)&&B){B._UpdateElementInfo();if (B.StartNode==B.EndNode&&B.StartNode.parentNode==B.StartBlockLimit&&B.StartNode.getAttribute&&B.StartNode.getAttribute('_fck_bookmark')) B=null;else break;};if (C) break;H=FCKDomTools.GetNextSourceNode(H,L,null,I);};if (!A){if (!B){this._NextNode=null;return null;};A=B.StartBlock;if (!A&&!this.EnforceRealBlocks&&B.StartBlockLimit.nodeName.IEquals('DIV','TH','TD')&&B.CheckStartOfBlock()&&B.CheckEndOfBlock()){A=B.StartBlockLimit;}else if (!A||(this.EnforceRealBlocks&&A.nodeName.toLowerCase()=='li')){A=this.Range.Window.document.createElement(FCKConfig.EnterMode=='p'?'p':'div');B.ExtractContents().AppendTo(A);FCKDomTools.TrimNode(A);B.InsertNode(A);D=true;E=true;}else if (A.nodeName.toLowerCase()!='li'){if (!B.CheckStartOfBlock()||!B.CheckEndOfBlock()){A=A.cloneNode(false);B.ExtractContents().AppendTo(A);FCKDomTools.TrimNode(A);var O=B.SplitBlock();D=!O.WasStartOfBlock;E=!O.WasEndOfBlock;B.InsertNode(A);}}else if (!C){this._NextNode=A==I?null:FCKDomTools.GetNextSourceNode(B.EndNode,true,null,I);return A;}};if (D){var P=A.previousSibling;if (P&&P.nodeType==1){if (P.nodeName.toLowerCase()=='br') P.parentNode.removeChild(P);else if (P.lastChild&&P.lastChild.nodeName.IEquals('br')) P.removeChild(P.lastChild);}};if (E){var Q=A.lastChild;if (Q&&Q.nodeType==1&&Q.nodeName.toLowerCase()=='br') A.removeChild(Q);};if (!this._NextNode) this._NextNode=(C||A==I)?null:FCKDomTools.GetNextSourceNode(A,true,null,I);return A;}}; +var FCKDocumentFragment=function(A){this._Document=A;this.RootNode=A.createElement('div');};FCKDocumentFragment.prototype={AppendTo:function(A){FCKDomTools.MoveChildren(this.RootNode,A);},AppendHtml:function(A){var B=this._Document.createElement('div');B.innerHTML=A;FCKDomTools.MoveChildren(B,this.RootNode);},InsertAfterNode:function(A){var B=this.RootNode;var C;while((C=B.lastChild)) FCKDomTools.InsertAfterNode(A,B.removeChild(C));}}; +var FCKW3CRange=function(A){this._Document=A;this.startContainer=null;this.startOffset=null;this.endContainer=null;this.endOffset=null;this.collapsed=true;};FCKW3CRange.CreateRange=function(A){return new FCKW3CRange(A);};FCKW3CRange.CreateFromRange=function(A,B){var C=FCKW3CRange.CreateRange(A);C.setStart(B.startContainer,B.startOffset);C.setEnd(B.endContainer,B.endOffset);return C;};FCKW3CRange.prototype={_UpdateCollapsed:function(){this.collapsed=(this.startContainer==this.endContainer&&this.startOffset==this.endOffset);},setStart:function(A,B){this.startContainer=A;this.startOffset=B;if (!this.endContainer){this.endContainer=A;this.endOffset=B;};this._UpdateCollapsed();},setEnd:function(A,B){this.endContainer=A;this.endOffset=B;if (!this.startContainer){this.startContainer=A;this.startOffset=B;};this._UpdateCollapsed();},setStartAfter:function(A){this.setStart(A.parentNode,FCKDomTools.GetIndexOf(A)+1);},setStartBefore:function(A){this.setStart(A.parentNode,FCKDomTools.GetIndexOf(A));},setEndAfter:function(A){this.setEnd(A.parentNode,FCKDomTools.GetIndexOf(A)+1);},setEndBefore:function(A){this.setEnd(A.parentNode,FCKDomTools.GetIndexOf(A));},collapse:function(A){if (A){this.endContainer=this.startContainer;this.endOffset=this.startOffset;}else{this.startContainer=this.endContainer;this.startOffset=this.endOffset;};this.collapsed=true;},selectNodeContents:function(A){this.setStart(A,0);this.setEnd(A,A.nodeType==3?A.data.length:A.childNodes.length);},insertNode:function(A){var B=this.startContainer;var C=this.startOffset;if (B.nodeType==3){B.splitText(C);if (B==this.endContainer) this.setEnd(B.nextSibling,this.endOffset-this.startOffset);FCKDomTools.InsertAfterNode(B,A);return;}else{B.insertBefore(A,B.childNodes[C]||null);if (B==this.endContainer){this.endOffset++;this.collapsed=false;}}},deleteContents:function(){if (this.collapsed) return;this._ExecContentsAction(0);},extractContents:function(){var A=new FCKDocumentFragment(this._Document);if (!this.collapsed) this._ExecContentsAction(1,A);return A;},cloneContents:function(){var A=new FCKDocumentFragment(this._Document);if (!this.collapsed) this._ExecContentsAction(2,A);return A;},_ExecContentsAction:function(A,B){var C=this.startContainer;var D=this.endContainer;var E=this.startOffset;var F=this.endOffset;var G=false;var H=false;if (D.nodeType==3) D=D.splitText(F);else{if (D.childNodes.length>0){if (F>D.childNodes.length-1){D=FCKDomTools.InsertAfterNode(D.lastChild,this._Document.createTextNode(''));H=true;}else D=D.childNodes[F];}};if (C.nodeType==3){C.splitText(E);if (C==D) D=C.nextSibling;}else{if (E==0){C=C.insertBefore(this._Document.createTextNode(''),C.firstChild);G=true;}else if (E>C.childNodes.length-1){C=C.appendChild(this._Document.createTextNode(''));G=true;}else C=C.childNodes[E].previousSibling;};var I=FCKDomTools.GetParents(C);var J=FCKDomTools.GetParents(D);var i,topStart,topEnd;for (i=0;i0&&levelStartNode!=D) levelClone=K.appendChild(levelStartNode.cloneNode(levelStartNode==D));if (!I[k]||levelStartNode.parentNode!=I[k].parentNode){currentNode=levelStartNode.previousSibling;while(currentNode){if (currentNode==I[k]||currentNode==C) break;currentSibling=currentNode.previousSibling;if (A==2) K.insertBefore(currentNode.cloneNode(true),K.firstChild);else{currentNode.parentNode.removeChild(currentNode);if (A==1) K.insertBefore(currentNode,K.firstChild);};currentNode=currentSibling;}};if (K) K=levelClone;};if (A==2){var L=this.startContainer;if (L.nodeType==3){L.data+=L.nextSibling.data;L.parentNode.removeChild(L.nextSibling);};var M=this.endContainer;if (M.nodeType==3&&M.nextSibling){M.data+=M.nextSibling.data;M.parentNode.removeChild(M.nextSibling);}}else{if (topStart&&topEnd&&(C.parentNode!=topStart.parentNode||D.parentNode!=topEnd.parentNode)){var N=FCKDomTools.GetIndexOf(topEnd);if (G&&topEnd.parentNode==C.parentNode) N--;this.setStart(topEnd.parentNode,N);};this.collapse(true);};if(G) C.parentNode.removeChild(C);if(H&&D.parentNode) D.parentNode.removeChild(D);},cloneRange:function(){return FCKW3CRange.CreateFromRange(this._Document,this);}}; +var FCKEnterKey=function(A,B,C,D){this.Window=A;this.EnterMode=B||'p';this.ShiftEnterMode=C||'br';var E=new FCKKeystrokeHandler(false);E._EnterKey=this;E.OnKeystroke=FCKEnterKey_OnKeystroke;E.SetKeystrokes([[13,'Enter'],[SHIFT+13,'ShiftEnter'],[9,'Tab'],[8,'Backspace'],[CTRL+8,'CtrlBackspace'],[46,'Delete']]);if (D>0){this.TabText='';while (D-->0) this.TabText+='\xa0';};E.AttachToElement(A.document);};function FCKEnterKey_OnKeystroke(A,B){var C=this._EnterKey;try{switch (B){case 'Enter':return C.DoEnter();break;case 'ShiftEnter':return C.DoShiftEnter();break;case 'Backspace':return C.DoBackspace();break;case 'Delete':return C.DoDelete();break;case 'Tab':return C.DoTab();break;case 'CtrlBackspace':return C.DoCtrlBackspace();break;}}catch (e){};return false;};FCKEnterKey.prototype.DoEnter=function(A,B){FCKUndo.SaveUndoStep();this._HasShift=(B===true);var C=FCKSelection.GetParentElement();var D=new FCKElementPath(C);var E=A||this.EnterMode;if (E=='br'||D.Block&&D.Block.tagName.toLowerCase()=='pre') return this._ExecuteEnterBr();else return this._ExecuteEnterBlock(E);};FCKEnterKey.prototype.DoShiftEnter=function(){return this.DoEnter(this.ShiftEnterMode,true);};FCKEnterKey.prototype.DoBackspace=function(){var A=false;var B=new FCKDomRange(this.Window);B.MoveToSelection();if (FCKBrowserInfo.IsIE&&this._CheckIsAllContentsIncluded(B,this.Window.document.body)){this._FixIESelectAllBug(B);return true;};var C=B.CheckIsCollapsed();if (!C){if (FCKBrowserInfo.IsIE&&this.Window.document.selection.type.toLowerCase()=="control"){var D=this.Window.document.selection.createRange();for (var i=D.length-1;i>=0;i--){var E=D.item(i);E.parentNode.removeChild(E);};return true;};return false;};var F=B.StartBlock;var G=B.EndBlock;if (B.StartBlockLimit==B.EndBlockLimit&&F&&G){if (!C){var H=B.CheckEndOfBlock();B.DeleteContents();if (F!=G){B.SetStart(G,1);B.SetEnd(G,1);};B.Select();A=(F==G);};if (B.CheckStartOfBlock()){var I=B.StartBlock;var J=FCKDomTools.GetPreviousSourceElement(I,true,['BODY',B.StartBlockLimit.nodeName],['UL','OL']);A=this._ExecuteBackspace(B,J,I);}else if (FCKBrowserInfo.IsGeckoLike){B.Select();}};B.Release();return A;};FCKEnterKey.prototype.DoCtrlBackspace=function(){FCKUndo.SaveUndoStep();var A=new FCKDomRange(this.Window);A.MoveToSelection();if (FCKBrowserInfo.IsIE&&this._CheckIsAllContentsIncluded(A,this.Window.document.body)){this._FixIESelectAllBug(A);return true;};return false;};FCKEnterKey.prototype._ExecuteBackspace=function(A,B,C){var D=false;if (!B&&C&&C.nodeName.IEquals('LI')&&C.parentNode.parentNode.nodeName.IEquals('LI')){this._OutdentWithSelection(C,A);return true;};if (B&&B.nodeName.IEquals('LI')){var E=FCKDomTools.GetLastChild(B,['UL','OL']);while (E){B=FCKDomTools.GetLastChild(E,'LI');E=FCKDomTools.GetLastChild(B,['UL','OL']);}};if (B&&C){if (C.nodeName.IEquals('LI')&&!B.nodeName.IEquals('LI')){this._OutdentWithSelection(C,A);return true;};var F=C.parentNode;var G=B.nodeName.toLowerCase();if (FCKListsLib.EmptyElements[G]!=null||G=='table'){FCKDomTools.RemoveNode(B);D=true;}else{FCKDomTools.RemoveNode(C);while (F.innerHTML.Trim().length==0){var H=F.parentNode;H.removeChild(F);F=H;};FCKDomTools.LTrimNode(C);FCKDomTools.RTrimNode(B);A.SetStart(B,2,true);A.Collapse(true);var I=A.CreateBookmark(true);if (!C.tagName.IEquals(['TABLE'])) FCKDomTools.MoveChildren(C,B);A.SelectBookmark(I);D=true;}};return D;};FCKEnterKey.prototype.DoDelete=function(){FCKUndo.SaveUndoStep();var A=false;var B=new FCKDomRange(this.Window);B.MoveToSelection();if (FCKBrowserInfo.IsIE&&this._CheckIsAllContentsIncluded(B,this.Window.document.body)){this._FixIESelectAllBug(B);return true;};if (B.CheckIsCollapsed()&&B.CheckEndOfBlock(FCKBrowserInfo.IsGeckoLike)){var C=B.StartBlock;var D=FCKTools.GetElementAscensor(C,'td');var E=FCKDomTools.GetNextSourceElement(C,true,[B.StartBlockLimit.nodeName],['UL','OL','TR'],true);if (D){var F=FCKTools.GetElementAscensor(E,'td');if (F!=D) return true;};A=this._ExecuteBackspace(B,C,E);};B.Release();return A;};FCKEnterKey.prototype.DoTab=function(){var A=new FCKDomRange(this.Window);A.MoveToSelection();var B=A._Range.startContainer;while (B){if (B.nodeType==1){var C=B.tagName.toLowerCase();if (C=="tr"||C=="td"||C=="th"||C=="tbody"||C=="table") return false;else break;};B=B.parentNode;};if (this.TabText){A.DeleteContents();A.InsertNode(this.Window.document.createTextNode(this.TabText));A.Collapse(false);A.Select();};return true;};FCKEnterKey.prototype._ExecuteEnterBlock=function(A,B){var C=B||new FCKDomRange(this.Window);var D=C.SplitBlock(A);if (D){var E=D.PreviousBlock;var F=D.NextBlock;var G=D.WasStartOfBlock;var H=D.WasEndOfBlock;if (F){if (F.parentNode.nodeName.IEquals('li')){FCKDomTools.BreakParent(F,F.parentNode);FCKDomTools.MoveNode(F,F.nextSibling,true);}}else if (E&&E.parentNode.nodeName.IEquals('li')){FCKDomTools.BreakParent(E,E.parentNode);C.MoveToElementEditStart(E.nextSibling);FCKDomTools.MoveNode(E,E.previousSibling);};if (!G&&!H){if (F.nodeName.IEquals('li')&&F.firstChild&&F.firstChild.nodeName.IEquals(['ul','ol'])) F.insertBefore(FCKTools.GetElementDocument(F).createTextNode('\xa0'),F.firstChild);if (F) C.MoveToElementEditStart(F);}else{if (G&&H&&E.tagName.toUpperCase()=='LI'){C.MoveToElementStart(E);this._OutdentWithSelection(E,C);C.Release();return true;};var I;if (E){var J=E.tagName.toUpperCase();if (!this._HasShift&&!(/^H[1-6]$/).test(J)){I=FCKDomTools.CloneElement(E);}}else if (F) I=FCKDomTools.CloneElement(F);if (!I) I=this.Window.document.createElement(A);var K=D.ElementPath;if (K){for (var i=0,len=K.Elements.length;i=0&&(C=B[i--])){if (C.name.length>0){if (C.innerHTML!==''){if (FCKBrowserInfo.IsIE) C.className+=' FCK__AnchorC';}else{var D=FCKDocumentProcessor_CreateFakeImage('FCK__Anchor',C.cloneNode(true));D.setAttribute('_fckanchor','true',0);C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}}}};var FCKPageBreaksProcessor=FCKDocumentProcessor.AppendNew();FCKPageBreaksProcessor.ProcessDocument=function(A){var B=A.getElementsByTagName('DIV');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){if (C.style.pageBreakAfter=='always'&&C.childNodes.length==1&&C.childNodes[0].style&&C.childNodes[0].style.display=='none'){var D=FCKDocumentProcessor_CreateFakeImage('FCK__PageBreak',C.cloneNode(true));C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}};FCKEmbedAndObjectProcessor=(function(){var A=[];var B=function(el){var C=el.cloneNode(true);var D;var E=D=FCKDocumentProcessor_CreateFakeImage('FCK__UnknownObject',C);FCKEmbedAndObjectProcessor.RefreshView(E,el);for (var i=0;i=0;i--) B(F[i]);var G=doc.getElementsByTagName('embed');for (var i=G.length-1;i>=0;i--) B(G[i]);});},RefreshView:function(placeHolder,original){if (original.getAttribute('width')>0) placeHolder.style.width=FCKTools.ConvertHtmlSizeToStyle(original.getAttribute('width'));if (original.getAttribute('height')>0) placeHolder.style.height=FCKTools.ConvertHtmlSizeToStyle(original.getAttribute('height'));},AddCustomHandler:function(func){A.push(func);}});})();FCK.GetRealElement=function(A){var e=FCKTempBin.Elements[A.getAttribute('_fckrealelement')];if (A.getAttribute('_fckflash')){if (A.style.width.length>0) e.width=FCKTools.ConvertStyleSizeToHtml(A.style.width);if (A.style.height.length>0) e.height=FCKTools.ConvertStyleSizeToHtml(A.style.height);};return e;};if (FCKBrowserInfo.IsIE){FCKDocumentProcessor.AppendNew().ProcessDocument=function(A){var B=A.getElementsByTagName('HR');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){var D=A.createElement('hr');D.mergeAttributes(C,true);FCKDomTools.InsertAfterNode(C,D);C.parentNode.removeChild(C);}}};FCKDocumentProcessor.AppendNew().ProcessDocument=function(A){var B=A.getElementsByTagName('INPUT');var C;var i=B.length-1;while (i>=0&&(C=B[i--])){if (C.type=='hidden'){var D=FCKDocumentProcessor_CreateFakeImage('FCK__InputHidden',C.cloneNode(true));D.setAttribute('_fckinputhidden','true',0);C.parentNode.insertBefore(D,C);C.parentNode.removeChild(C);}}};FCKEmbedAndObjectProcessor.AddCustomHandler(function(A,B){if (!(A.nodeName.IEquals('embed')&&(A.type=='application/x-shockwave-flash'||/\.swf($|#|\?)/i.test(A.src)))) return;B.className='FCK__Flash';B.setAttribute('_fckflash','true',0);}); +var FCKSelection=FCK.Selection={GetParentBlock:function(){var A=this.GetParentElement();while (A){if (FCKListsLib.BlockBoundaries[A.nodeName.toLowerCase()]) break;A=A.parentNode;};return A;},ApplyStyle:function(A){FCKStyles.ApplyStyle(new FCKStyle(A));}}; +FCKSelection.GetType=function(){try{var A=FCKSelection.GetSelection().type;if (A=='Control'||A=='Text') return A;if (this.GetSelection().createRange().parentElement) return 'Text';}catch(e){};return 'None';};FCKSelection.GetSelectedElement=function(){if (this.GetType()=='Control'){var A=this.GetSelection().createRange();if (A&&A.item) return this.GetSelection().createRange().item(0);};return null;};FCKSelection.GetParentElement=function(){switch (this.GetType()){case 'Control':var A=FCKSelection.GetSelectedElement();return A?A.parentElement:null;case 'None':return null;default:return this.GetSelection().createRange().parentElement();}};FCKSelection.GetBoundaryParentElement=function(A){switch (this.GetType()){case 'Control':var B=FCKSelection.GetSelectedElement();return B?B.parentElement:null;case 'None':return null;default:var C=FCK.EditorDocument;var D=C.selection.createRange();D.collapse(A!==false);var B=D.parentElement();return FCKTools.GetElementDocument(B)==C?B:null;}};FCKSelection.SelectNode=function(A){FCK.Focus();this.GetSelection().empty();var B;try{B=FCK.EditorDocument.body.createControlRange();B.addElement(A);}catch(e){B=FCK.EditorDocument.body.createTextRange();B.moveToElementText(A);};B.select();};FCKSelection.Collapse=function(A){FCK.Focus();if (this.GetType()=='Text'){var B=this.GetSelection().createRange();B.collapse(A==null||A===true);B.select();}};FCKSelection.HasAncestorNode=function(A){var B;if (this.GetSelection().type=="Control"){B=this.GetSelectedElement();}else{var C=this.GetSelection().createRange();B=C.parentElement();};while (B){if (B.tagName==A) return true;B=B.parentNode;};return false;};FCKSelection.MoveToAncestorNode=function(A){var B,oRange;if (!FCK.EditorDocument) return null;if (this.GetSelection().type=="Control"){oRange=this.GetSelection().createRange();for (i=0;i=0;i--){if (C[i]) FCKTableHandler.DeleteRows(C[i]);};return;};var E=FCKTools.GetElementAscensor(A,'TABLE');if (E.rows.length==1){FCKTableHandler.DeleteTable(E);return;};A.parentNode.removeChild(A);};FCKTableHandler.DeleteTable=function(A){if (!A){A=FCKSelection.GetSelectedElement();if (!A||A.tagName!='TABLE') A=FCKSelection.MoveToAncestorNode('TABLE');};if (!A) return;FCKSelection.SelectNode(A);FCKSelection.Collapse();if (A.parentNode.childNodes.length==1) A.parentNode.parentNode.removeChild(A.parentNode);else A.parentNode.removeChild(A);};FCKTableHandler.InsertColumn=function(A){var B=null;var C=this.GetSelectedCells();if (C&&C.length) B=C[A?0:(C.length-1)];if (!B) return;var D=FCKTools.GetElementAscensor(B,'TABLE');var E=B.cellIndex;for (var i=0;i=0;i--){if (B[i]) FCKTableHandler.DeleteColumns(B[i]);};return;};if (!A) return;var C=FCKTools.GetElementAscensor(A,'TABLE');var D=A.cellIndex;for (var i=C.rows.length-1;i>=0;i--){var E=C.rows[i];if (D==0&&E.cells.length==1){FCKTableHandler.DeleteRows(E);continue;};if (E.cells[D]) E.removeChild(E.cells[D]);}};FCKTableHandler.InsertCell=function(A,B){var C=null;var D=this.GetSelectedCells();if (D&&D.length) C=D[B?0:(D.length-1)];if (!C) return null;var E=FCK.EditorDocument.createElement('TD');if (FCKBrowserInfo.IsGeckoLike) FCKTools.AppendBogusBr(E);if (!B&&C.cellIndex==C.parentNode.cells.length-1) C.parentNode.appendChild(E);else C.parentNode.insertBefore(E,B?C:C.nextSibling);return E;};FCKTableHandler.DeleteCell=function(A){if (A.parentNode.cells.length==1){FCKTableHandler.DeleteRows(FCKTools.GetElementAscensor(A,'TR'));return;};A.parentNode.removeChild(A);};FCKTableHandler.DeleteCells=function(){var A=FCKTableHandler.GetSelectedCells();for (var i=A.length-1;i>=0;i--){FCKTableHandler.DeleteCell(A[i]);}};FCKTableHandler._MarkCells=function(A,B){for (var i=0;i=E.height){for (D=F;D0){var L=K.removeChild(K.firstChild);if (L.nodeType!=1||(L.getAttribute('type',2)!='_moz'&&L.getAttribute('_moz_dirty')!=null)){I.appendChild(L);J++;}}};if (J>0) I.appendChild(FCKTools.GetElementDocument(B).createElement('br'));};this._ReplaceCellsByMarker(C,'_SelectedCells',B);this._UnmarkCells(A,'_SelectedCells');this._InstallTableMap(C,B.parentNode.parentNode);B.appendChild(I);if (FCKBrowserInfo.IsGeckoLike&&(!B.firstChild)) FCKTools.AppendBogusBr(B);this._MoveCaretToCell(B,false);};FCKTableHandler.MergeRight=function(){var A=this.GetMergeRightTarget();if (A==null) return;var B=A.refCell;var C=A.tableMap;var D=A.nextCell;var E=FCK.EditorDocument.createDocumentFragment();while (D&&D.childNodes&&D.childNodes.length>0) E.appendChild(D.removeChild(D.firstChild));D.parentNode.removeChild(D);B.appendChild(E);this._MarkCells([D],'_Replace');this._ReplaceCellsByMarker(C,'_Replace',B);this._InstallTableMap(C,B.parentNode.parentNode);this._MoveCaretToCell(B,false);};FCKTableHandler.MergeDown=function(){var A=this.GetMergeDownTarget();if (A==null) return;var B=A.refCell;var C=A.tableMap;var D=A.nextCell;var E=FCKTools.GetElementDocument(B).createDocumentFragment();while (D&&D.childNodes&&D.childNodes.length>0) E.appendChild(D.removeChild(D.firstChild));if (E.firstChild) E.insertBefore(FCKTools.GetElementDocument(D).createElement('br'),E.firstChild);B.appendChild(E);this._MarkCells([D],'_Replace');this._ReplaceCellsByMarker(C,'_Replace',B);this._InstallTableMap(C,B.parentNode.parentNode);this._MoveCaretToCell(B,false);};FCKTableHandler.HorizontalSplitCell=function(){var A=FCKTableHandler.GetSelectedCells();if (A.length!=1) return;var B=A[0];var C=this._CreateTableMap(B.parentNode.parentNode);var D=B.parentNode.rowIndex;var E=FCKTableHandler._GetCellIndexSpan(C,D,B);var F=isNaN(B.colSpan)?1:B.colSpan;if (F>1){var G=Math.ceil(F/2);var H=FCKTools.GetElementDocument(B).createElement('td');if (FCKBrowserInfo.IsGeckoLike) FCKTools.AppendBogusBr(H);var I=E+G;var J=E+F;var K=isNaN(B.rowSpan)?1:B.rowSpan;for (var r=D;r1){B.rowSpan=Math.ceil(E/2);var G=F+Math.ceil(E/2);var H=null;for (var i=D+1;i0){var C=B.rows[0];C.parentNode.removeChild(C);};for (var i=0;iE) E=j;if (D._colScanned===true) continue;if (A[i][j-1]==D) D.colSpan++;if (A[i][j+1]!=D) D._colScanned=true;}};for (var i=0;i<=E;i++){for (var j=0;j=0&&C.compareEndPoints('StartToEnd',E)<=0)||(C.compareEndPoints('EndToStart',E)>=0&&C.compareEndPoints('EndToEnd',E)<=0)){B[B.length]=D.cells[i];}}}};return B;}; +var FCKXml=function(){this.Error=false;};FCKXml.GetAttribute=function(A,B,C){var D=A.attributes.getNamedItem(B);return D?D.value:C;};FCKXml.TransformToObject=function(A){if (!A) return null;var B={};var C=A.attributes;for (var i=0;i ';var A=FCKDocumentProcessor_CreateFakeImage('FCK__PageBreak',e);var B=new FCKDomRange(FCK.EditorWindow);B.MoveToSelection();var C=B.SplitBlock();B.InsertNode(A);FCK.Events.FireEvent('OnSelectionChange');};FCKPageBreakCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;return 0;};var FCKUnlinkCommand=function(){this.Name='Unlink';};FCKUnlinkCommand.prototype.Execute=function(){FCKUndo.SaveUndoStep();if (FCKBrowserInfo.IsGeckoLike){var A=FCK.Selection.MoveToAncestorNode('A');if (A) FCKTools.RemoveOuterTags(A);return;};FCK.ExecuteNamedCommand(this.Name);};FCKUnlinkCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;var A=FCK.GetNamedCommandState(this.Name);if (A==0&&FCK.EditMode==0){var B=FCKSelection.MoveToAncestorNode('A');var C=(B&&B.name.length>0&&B.href.length==0);if (C) A=-1;};return A;};var FCKSelectAllCommand=function(){this.Name='SelectAll';};FCKSelectAllCommand.prototype.Execute=function(){if (FCK.EditMode==0){FCK.ExecuteNamedCommand('SelectAll');}else{var A=FCK.EditingArea.Textarea;if (FCKBrowserInfo.IsIE){A.createTextRange().execCommand('SelectAll');}else{A.selectionStart=0;A.selectionEnd=A.value.length;};A.focus();}};FCKSelectAllCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;return 0;};var FCKPasteCommand=function(){this.Name='Paste';};FCKPasteCommand.prototype={Execute:function(){if (FCKBrowserInfo.IsIE) FCK.Paste();else FCK.ExecuteNamedCommand('Paste');},GetState:function(){if (FCK.EditMode!=0) return -1;return FCK.GetNamedCommandState('Paste');}};var FCKRuleCommand=function(){this.Name='Rule';};FCKRuleCommand.prototype={Execute:function(){FCKUndo.SaveUndoStep();FCK.InsertElement('hr');},GetState:function(){if (FCK.EditMode!=0) return -1;return FCK.GetNamedCommandState('InsertHorizontalRule');}};var FCKCutCopyCommand=function(A){this.Name=A?'Cut':'Copy';};FCKCutCopyCommand.prototype={Execute:function(){var A=false;if (FCKBrowserInfo.IsIE){var B=function(){A=true;};var C='on'+this.Name.toLowerCase();FCK.EditorDocument.body.attachEvent(C,B);FCK.ExecuteNamedCommand(this.Name);FCK.EditorDocument.body.detachEvent(C,B);}else{try{FCK.ExecuteNamedCommand(this.Name);A=true;}catch(e){}};if (!A) alert(FCKLang['PasteError'+this.Name]);},GetState:function(){return FCK.EditMode!=0?-1:FCK.GetNamedCommandState('Cut');}};var FCKAnchorDeleteCommand=function(){this.Name='AnchorDelete';};FCKAnchorDeleteCommand.prototype={Execute:function(){if (FCK.Selection.GetType()=='Control'){FCK.Selection.Delete();}else{var A=FCK.Selection.GetSelectedElement();if (A){if (A.tagName=='IMG'&&A.getAttribute('_fckanchor')) oAnchor=FCK.GetRealElement(A);else A=null;};if (!A){oAnchor=FCK.Selection.MoveToAncestorNode('A');if (oAnchor) FCK.Selection.SelectNode(oAnchor);};if (oAnchor.href.length!=0){oAnchor.removeAttribute('name');if (FCKBrowserInfo.IsIE) oAnchor.className=oAnchor.className.replace(FCKRegexLib.FCK_Class,'');return;};if (A){A.parentNode.removeChild(A);return;};if (oAnchor.innerHTML.length==0){oAnchor.parentNode.removeChild(oAnchor);return;};FCKTools.RemoveOuterTags(oAnchor);};if (FCKBrowserInfo.IsGecko) FCK.Selection.Collapse(true);},GetState:function(){if (FCK.EditMode!=0) return -1;return FCK.GetNamedCommandState('Unlink');}}; +var FCKShowBlockCommand=function(A,B){this.Name=A;if (B!=undefined) this._SavedState=B;else this._SavedState=null;};FCKShowBlockCommand.prototype.Execute=function(){var A=this.GetState();if (A==-1) return;var B=FCK.EditorDocument.body;if (A==1) B.className=B.className.replace(/(^| )FCK__ShowBlocks/g,'');else B.className+=' FCK__ShowBlocks';FCK.Events.FireEvent('OnSelectionChange');};FCKShowBlockCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;if (!FCK.EditorDocument) return 0;if (/FCK__ShowBlocks(?:\s|$)/.test(FCK.EditorDocument.body.className)) return 1;return 0;};FCKShowBlockCommand.prototype.SaveState=function(){this._SavedState=this.GetState();};FCKShowBlockCommand.prototype.RestoreState=function(){if (this._SavedState!=null&&this.GetState()!=this._SavedState) this.Execute();}; +var FCKSpellCheckCommand=function(){this.Name='SpellCheck';this.IsEnabled=(FCKConfig.SpellChecker=='ieSpell'||FCKConfig.SpellChecker=='SpellerPages');};FCKSpellCheckCommand.prototype.Execute=function(){switch (FCKConfig.SpellChecker){case 'ieSpell':this._RunIeSpell();break;case 'SpellerPages':FCKDialog.OpenDialog('FCKDialog_SpellCheck','Spell Check','dialog/fck_spellerpages.html',440,480);break;}};FCKSpellCheckCommand.prototype._RunIeSpell=function(){try{var A=new ActiveXObject("ieSpell.ieSpellExtension");A.CheckAllLinkedDocuments(FCK.EditorDocument);}catch(e){if(e.number==-2146827859){if (confirm(FCKLang.IeSpellDownload)) window.open(FCKConfig.IeSpellDownloadUrl,'IeSpellDownload');}else alert('Error Loading ieSpell: '+e.message+' ('+e.number+')');}};FCKSpellCheckCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;return this.IsEnabled?0:-1;}; +var FCKTextColorCommand=function(A){this.Name=A=='ForeColor'?'TextColor':'BGColor';this.Type=A;var B;if (FCKBrowserInfo.IsIE) B=window;else if (FCK.ToolbarSet._IFrame) B=FCKTools.GetElementWindow(FCK.ToolbarSet._IFrame);else B=window.parent;this._Panel=new FCKPanel(B);this._Panel.AppendStyleSheet(FCKConfig.SkinEditorCSS);this._Panel.MainNode.className='FCK_Panel';this._CreatePanelBody(this._Panel.Document,this._Panel.MainNode);FCK.ToolbarSet.ToolbarItems.GetItem(this.Name).RegisterPanel(this._Panel);FCKTools.DisableSelection(this._Panel.Document.body);};FCKTextColorCommand.prototype.Execute=function(A,B,C){this._Panel.Show(A,B,C);};FCKTextColorCommand.prototype.SetColor=function(A){FCKUndo.SaveUndoStep();var B=FCKStyles.GetStyle('_FCK_'+(this.Type=='ForeColor'?'Color':'BackColor'));if (!A||A.length==0) FCK.Styles.RemoveStyle(B);else{B.SetVariable('Color',A);FCKStyles.ApplyStyle(B);};FCKUndo.SaveUndoStep();FCK.Focus();FCK.Events.FireEvent('OnSelectionChange');};FCKTextColorCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;return 0;};function FCKTextColorCommand_OnMouseOver(){this.className='ColorSelected';};function FCKTextColorCommand_OnMouseOut(){this.className='ColorDeselected';};function FCKTextColorCommand_OnClick(A,B,C){this.className='ColorDeselected';B.SetColor(C);B._Panel.Hide();};function FCKTextColorCommand_AutoOnClick(A,B){this.className='ColorDeselected';B.SetColor('');B._Panel.Hide();};function FCKTextColorCommand_MoreOnClick(A,B){this.className='ColorDeselected';B._Panel.Hide();FCKDialog.OpenDialog('FCKDialog_Color',FCKLang.DlgColorTitle,'dialog/fck_colorselector.html',410,320,FCKTools.Bind(B,B.SetColor));};FCKTextColorCommand.prototype._CreatePanelBody=function(A,B){function CreateSelectionDiv(){var C=A.createElement("DIV");C.className='ColorDeselected';FCKTools.AddEventListenerEx(C,'mouseover',FCKTextColorCommand_OnMouseOver);FCKTools.AddEventListenerEx(C,'mouseout',FCKTextColorCommand_OnMouseOut);return C;};var D=B.appendChild(A.createElement("TABLE"));D.className='ForceBaseFont';D.style.tableLayout='fixed';D.cellPadding=0;D.cellSpacing=0;D.border=0;D.width=150;var E=D.insertRow(-1).insertCell(-1);E.colSpan=8;var C=E.appendChild(CreateSelectionDiv());C.innerHTML='\n \n \n \n \n
      '+FCKLang.ColorAutomatic+'
      ';FCKTools.AddEventListenerEx(C,'click',FCKTextColorCommand_AutoOnClick,this);if (!FCKBrowserInfo.IsIE) C.style.width='96%';var G=FCKConfig.FontColors.toString().split(',');var H=0;while (H
      ';if (H>=G.length) C.style.visibility='hidden';else FCKTools.AddEventListenerEx(C,'click',FCKTextColorCommand_OnClick,[this,L]);}};if (FCKConfig.EnableMoreFontColors){E=D.insertRow(-1).insertCell(-1);E.colSpan=8;C=E.appendChild(CreateSelectionDiv());C.innerHTML='
      '+FCKLang.ColorMoreColors+'
      ';FCKTools.AddEventListenerEx(C,'click',FCKTextColorCommand_MoreOnClick,this);};if (!FCKBrowserInfo.IsIE) C.style.width='96%';}; +var FCKPastePlainTextCommand=function(){this.Name='PasteText';};FCKPastePlainTextCommand.prototype.Execute=function(){FCK.PasteAsPlainText();};FCKPastePlainTextCommand.prototype.GetState=function(){if (FCK.EditMode!=0) return -1;return FCK.GetNamedCommandState('Paste');}; +var FCKPasteWordCommand=function(){this.Name='PasteWord';};FCKPasteWordCommand.prototype.Execute=function(){FCK.PasteFromWord();};FCKPasteWordCommand.prototype.GetState=function(){if (FCK.EditMode!=0||FCKConfig.ForcePasteAsPlainText) return -1;else return FCK.GetNamedCommandState('Paste');}; +var FCKTableCommand=function(A){this.Name=A;};FCKTableCommand.prototype.Execute=function(){FCKUndo.SaveUndoStep();if (!FCKBrowserInfo.IsGecko){switch (this.Name){case 'TableMergeRight':return FCKTableHandler.MergeRight();case 'TableMergeDown':return FCKTableHandler.MergeDown();}};switch (this.Name){case 'TableInsertRowAfter':return FCKTableHandler.InsertRow(false);case 'TableInsertRowBefore':return FCKTableHandler.InsertRow(true);case 'TableDeleteRows':return FCKTableHandler.DeleteRows();case 'TableInsertColumnAfter':return FCKTableHandler.InsertColumn(false);case 'TableInsertColumnBefore':return FCKTableHandler.InsertColumn(true);case 'TableDeleteColumns':return FCKTableHandler.DeleteColumns();case 'TableInsertCellAfter':return FCKTableHandler.InsertCell(null,false);case 'TableInsertCellBefore':return FCKTableHandler.InsertCell(null,true);case 'TableDeleteCells':return FCKTableHandler.DeleteCells();case 'TableMergeCells':return FCKTableHandler.MergeCells();case 'TableHorizontalSplitCell':return FCKTableHandler.HorizontalSplitCell();case 'TableVerticalSplitCell':return FCKTableHandler.VerticalSplitCell();case 'TableDelete':return FCKTableHandler.DeleteTable();default:return alert(FCKLang.UnknownCommand.replace(/%1/g,this.Name));}};FCKTableCommand.prototype.GetState=function(){if (FCK.EditorDocument!=null&&FCKSelection.HasAncestorNode('TABLE')){switch (this.Name){case 'TableHorizontalSplitCell':case 'TableVerticalSplitCell':if (FCKTableHandler.GetSelectedCells().length==1) return 0;else return -1;case 'TableMergeCells':if (FCKTableHandler.CheckIsSelectionRectangular()&&FCKTableHandler.GetSelectedCells().length>1) return 0;else return -1;case 'TableMergeRight':return FCKTableHandler.GetMergeRightTarget()?0:-1;case 'TableMergeDown':return FCKTableHandler.GetMergeDownTarget()?0:-1;default:return 0;}}else return -1;}; +var FCKFitWindow=function(){this.Name='FitWindow';};FCKFitWindow.prototype.Execute=function(){var A=window.frameElement;var B=A.style;var C=parent;var D=C.document.documentElement;var E=C.document.body;var F=E.style;var G;if (!this.IsMaximized){if(FCKBrowserInfo.IsIE) C.attachEvent('onresize',FCKFitWindow_Resize);else C.addEventListener('resize',FCKFitWindow_Resize,true);this._ScrollPos=FCKTools.GetScrollPosition(C);G=A;while((G=G.parentNode)){if (G.nodeType==1){G._fckSavedStyles=FCKTools.SaveStyles(G);G.style.zIndex=FCKConfig.FloatingPanelsZIndex-1;}};if (FCKBrowserInfo.IsIE){this.documentElementOverflow=D.style.overflow;D.style.overflow='hidden';F.overflow='hidden';}else{F.overflow='hidden';F.width='0px';F.height='0px';};this._EditorFrameStyles=FCKTools.SaveStyles(A);var H=FCKTools.GetViewPaneSize(C);B.position="absolute";B.zIndex=FCKConfig.FloatingPanelsZIndex-1;B.left="0px";B.top="0px";B.width=H.Width+"px";B.height=H.Height+"px";if (!FCKBrowserInfo.IsIE){B.borderRight=B.borderBottom="9999px solid white";B.backgroundColor="white";};C.scrollTo(0,0);var I=FCKTools.GetWindowPosition(C,A);if (I.x!=0) B.left=(-1*I.x)+"px";if (I.y!=0) B.top=(-1*I.y)+"px";this.IsMaximized=true;}else{if(FCKBrowserInfo.IsIE) C.detachEvent("onresize",FCKFitWindow_Resize);else C.removeEventListener("resize",FCKFitWindow_Resize,true);G=A;while((G=G.parentNode)){if (G._fckSavedStyles){FCKTools.RestoreStyles(G,G._fckSavedStyles);G._fckSavedStyles=null;}};if (FCKBrowserInfo.IsIE) D.style.overflow=this.documentElementOverflow;FCKTools.RestoreStyles(A,this._EditorFrameStyles);C.scrollTo(this._ScrollPos.X,this._ScrollPos.Y);this.IsMaximized=false;};FCKToolbarItems.GetItem('FitWindow').RefreshState();if (FCK.EditMode==0) FCK.EditingArea.MakeEditable();FCK.Focus();};FCKFitWindow.prototype.GetState=function(){if (FCKConfig.ToolbarLocation!='In') return -1;else return (this.IsMaximized?1:0);};function FCKFitWindow_Resize(){var A=FCKTools.GetViewPaneSize(parent);var B=window.frameElement.style;B.width=A.Width+'px';B.height=A.Height+'px';}; +var FCKListCommand=function(A,B){this.Name=A;this.TagName=B;};FCKListCommand.prototype={GetState:function(){if (FCK.EditMode!=0||!FCK.EditorWindow) return -1;var A=FCKSelection.GetBoundaryParentElement(true);var B=A;while (B){if (B.nodeName.IEquals(['ul','ol'])) break;B=B.parentNode;};if (B&&B.nodeName.IEquals(this.TagName)) return 1;else return 0;},Execute:function(){FCKUndo.SaveUndoStep();var A=FCK.EditorDocument;var B=new FCKDomRange(FCK.EditorWindow);B.MoveToSelection();var C=this.GetState();if (C==0){FCKDomTools.TrimNode(A.body);if (!A.body.firstChild){var D=A.createElement('p');A.body.appendChild(D);B.MoveToNodeContents(D);}};var E=B.CreateBookmark();var F=[];var G={};var H=new FCKDomRangeIterator(B);var I;H.ForceBrBreak=(C==0);var J=true;var K=null;while (J){while ((I=H.GetNextParagraph())){var L=new FCKElementPath(I);var M=null;var N=false;var O=L.BlockLimit;for (var i=L.Elements.length-1;i>=0;i--){var P=L.Elements[i];if (P.nodeName.IEquals(['ol','ul'])){if (O._FCK_ListGroupObject) O._FCK_ListGroupObject=null;var Q=P._FCK_ListGroupObject;if (Q) Q.contents.push(I);else{Q={ 'root':P,'contents':[I] };F.push(Q);FCKDomTools.SetElementMarker(G,P,'_FCK_ListGroupObject',Q);};N=true;break;}};if (N) continue;var R=O;if (R._FCK_ListGroupObject) R._FCK_ListGroupObject.contents.push(I);else{var Q={ 'root':R,'contents':[I] };FCKDomTools.SetElementMarker(G,R,'_FCK_ListGroupObject',Q);F.push(Q);}};if (FCKBrowserInfo.IsIE) J=false;else{if (K==null){K=[];var T=FCKSelection.GetSelection();if (T&&F.length==0) K.push(T.getRangeAt(0));for (var i=1;T&&i0){var Q=F.shift();if (C==0){if (Q.root.nodeName.IEquals(['ul','ol'])) this._ChangeListType(Q,G,W);else this._CreateList(Q,W);}else if (C==1&&Q.root.nodeName.IEquals(['ul','ol'])) this._RemoveList(Q,G);};for (var i=0;iC[i-1].indent+1){var H=C[i-1].indent+1-C[i].indent;var I=C[i].indent;while (C[i]&&C[i].indent>=I){C[i].indent+=H;i++;};i--;}};var J=FCKDomTools.ArrayToList(C,B);if (A.root.nextSibling==null||A.root.nextSibling.nodeName.IEquals('br')){if (J.listNode.lastChild.nodeName.IEquals('br')) J.listNode.removeChild(J.listNode.lastChild);};A.root.parentNode.replaceChild(J.listNode,A.root);}}; +var FCKJustifyCommand=function(A){this.AlignValue=A;var B=FCKConfig.ContentLangDirection.toLowerCase();this.IsDefaultAlign=(A=='left'&&B=='ltr')||(A=='right'&&B=='rtl');var C=this._CssClassName=(function(){var D=FCKConfig.JustifyClasses;if (D){switch (A){case 'left':return D[0]||null;case 'center':return D[1]||null;case 'right':return D[2]||null;case 'justify':return D[3]||null;}};return null;})();if (C&&C.length>0) this._CssClassRegex=new RegExp('(?:^|\\s+)'+C+'(?=$|\\s)');};FCKJustifyCommand._GetClassNameRegex=function(){var A=FCKJustifyCommand._ClassRegex;if (A!=undefined) return A;var B=[];var C=FCKConfig.JustifyClasses;if (C){for (var i=0;i<4;i++){var D=C[i];if (D&&D.length>0) B.push(D);}};if (B.length>0) A=new RegExp('(?:^|\\s+)(?:'+B.join('|')+')(?=$|\\s)');else A=null;return FCKJustifyCommand._ClassRegex=A;};FCKJustifyCommand.prototype={Execute:function(){FCKUndo.SaveUndoStep();var A=new FCKDomRange(FCK.EditorWindow);A.MoveToSelection();var B=this.GetState();if (B==-1) return;var C=A.CreateBookmark();var D=this._CssClassName;var E=new FCKDomRangeIterator(A);var F;while ((F=E.GetNextParagraph())){F.removeAttribute('align');if (D){var G=F.className.replace(FCKJustifyCommand._GetClassNameRegex(),'');if (B==0){if (G.length>0) G+=' ';F.className=G+D;}else if (G.length==0) FCKDomTools.RemoveAttribute(F,'class');}else{var H=F.style;if (B==0) H.textAlign=this.AlignValue;else{H.textAlign='';if (H.cssText.length==0) F.removeAttribute('style');}}};A.MoveToBookmark(C);A.Select();FCK.Focus();FCK.Events.FireEvent('OnSelectionChange');},GetState:function(){if (FCK.EditMode!=0||!FCK.EditorWindow) return -1;var A=new FCKElementPath(FCKSelection.GetBoundaryParentElement(true));var B=A.Block||A.BlockLimit;if (!B||B.nodeName.toLowerCase()=='body') return 0;var C;if (FCKBrowserInfo.IsIE) C=B.currentStyle.textAlign;else C=FCK.EditorWindow.getComputedStyle(B,'').getPropertyValue('text-align');C=C.replace(/(-moz-|-webkit-|start|auto)/i,'');if ((!C&&this.IsDefaultAlign)||C==this.AlignValue) return 1;return 0;}}; +var FCKIndentCommand=function(A,B){this.Name=A;this.Offset=B;this.IndentCSSProperty=FCKConfig.ContentLangDirection.IEquals('ltr')?'marginLeft':'marginRight';};FCKIndentCommand._InitIndentModeParameters=function(){if (FCKConfig.IndentClasses&&FCKConfig.IndentClasses.length>0){this._UseIndentClasses=true;this._IndentClassMap={};for (var i=0;i0?H+' ':'')+FCKConfig.IndentClasses[G-1];}else{var I=parseInt(E.style[this.IndentCSSProperty],10);if (isNaN(I)) I=0;I+=this.Offset;I=Math.max(I,0);I=Math.ceil(I/this.Offset)*this.Offset;E.style[this.IndentCSSProperty]=I?I+FCKConfig.IndentUnit:'';if (E.getAttribute('style')=='') E.removeAttribute('style');}}},_IndentList:function(A,B){var C=A.StartContainer;var D=A.EndContainer;while (C&&C.parentNode!=B) C=C.parentNode;while (D&&D.parentNode!=B) D=D.parentNode;if (!C||!D) return;var E=C;var F=[];var G=false;while (G==false){if (E==D) G=true;F.push(E);E=E.nextSibling;};if (F.length<1) return;var H=FCKDomTools.GetParents(B);for (var i=0;iN;i++) M[i].indent+=I;var O=FCKDomTools.ArrayToList(M);if (O) B.parentNode.replaceChild(O.listNode,B);FCKDomTools.ClearAllMarkers(L);}}; +var FCKBlockQuoteCommand=function(){};FCKBlockQuoteCommand.prototype={Execute:function(){FCKUndo.SaveUndoStep();var A=this.GetState();var B=new FCKDomRange(FCK.EditorWindow);B.MoveToSelection();var C=B.CreateBookmark();if (FCKBrowserInfo.IsIE){var D=B.GetBookmarkNode(C,true);var E=B.GetBookmarkNode(C,false);var F;if (D&&D.parentNode.nodeName.IEquals('blockquote')&&!D.previousSibling){F=D;while ((F=F.nextSibling)){if (FCKListsLib.BlockElements[F.nodeName.toLowerCase()]) FCKDomTools.MoveNode(D,F,true);}};if (E&&E.parentNode.nodeName.IEquals('blockquote')&&!E.previousSibling){F=E;while ((F=F.nextSibling)){if (FCKListsLib.BlockElements[F.nodeName.toLowerCase()]){if (F.firstChild==D) FCKDomTools.InsertAfterNode(D,E);else FCKDomTools.MoveNode(E,F,true);}}}};var G=new FCKDomRangeIterator(B);var H;if (A==0){G.EnforceRealBlocks=true;var I=[];while ((H=G.GetNextParagraph())) I.push(H);if (I.length<1){para=B.Window.document.createElement(FCKConfig.EnterMode.IEquals('p')?'p':'div');B.InsertNode(para);para.appendChild(B.Window.document.createTextNode('\ufeff'));B.MoveToBookmark(C);B.MoveToNodeContents(para);B.Collapse(true);C=B.CreateBookmark();I.push(para);};var J=I[0].parentNode;var K=[];for (var i=0;i0){H=I.shift();while (H.parentNode!=J) H=H.parentNode;if (H!=L) K.push(H);L=H;};while (K.length>0){H=K.shift();if (H.nodeName.IEquals('blockquote')){var M=FCKTools.GetElementDocument(H).createDocumentFragment();while (H.firstChild){M.appendChild(H.removeChild(H.firstChild));I.push(M.lastChild);};H.parentNode.replaceChild(M,H);}else I.push(H);};var N=B.Window.document.createElement('blockquote');J.insertBefore(N,I[0]);while (I.length>0){H=I.shift();N.appendChild(H);}}else if (A==1){var O=[];while ((H=G.GetNextParagraph())){var P=null;var Q=null;while (H.parentNode){if (H.parentNode.nodeName.IEquals('blockquote')){P=H.parentNode;Q=H;break;};H=H.parentNode;};if (P&&Q) O.push(Q);};var R=[];while (O.length>0){var S=O.shift();var N=S.parentNode;if (S==S.parentNode.firstChild){N.parentNode.insertBefore(N.removeChild(S),N);if (!N.firstChild) N.parentNode.removeChild(N);}else if (S==S.parentNode.lastChild){N.parentNode.insertBefore(N.removeChild(S),N.nextSibling);if (!N.firstChild) N.parentNode.removeChild(N);}else FCKDomTools.BreakParent(S,S.parentNode,B);R.push(S);};if (FCKConfig.EnterMode.IEquals('br')){while (R.length){var S=R.shift();var W=true;if (S.nodeName.IEquals('div')){var M=FCKTools.GetElementDocument(S).createDocumentFragment();var Y=W&&S.previousSibling&&!FCKListsLib.BlockBoundaries[S.previousSibling.nodeName.toLowerCase()];if (W&&Y) M.appendChild(FCKTools.GetElementDocument(S).createElement('br'));var Z=S.nextSibling&&!FCKListsLib.BlockBoundaries[S.nextSibling.nodeName.toLowerCase()];while (S.firstChild) M.appendChild(S.removeChild(S.firstChild));if (Z) M.appendChild(FCKTools.GetElementDocument(S).createElement('br'));S.parentNode.replaceChild(M,S);W=false;}}}};B.MoveToBookmark(C);B.Select();FCK.Focus();FCK.Events.FireEvent('OnSelectionChange');},GetState:function(){if (FCK.EditMode!=0||!FCK.EditorWindow) return -1;var A=new FCKElementPath(FCKSelection.GetBoundaryParentElement(true));var B=A.Block||A.BlockLimit;if (!B||B.nodeName.toLowerCase()=='body') return 0;for (var i=0;i';B.open();B.write(''+F+'<\/head><\/body><\/html>');B.close();if(FCKBrowserInfo.IsAIR) FCKAdobeAIR.Panel_Contructor(B,window.document.location);FCKTools.AddEventListenerEx(E,'focus',FCKPanel_Window_OnFocus,this);FCKTools.AddEventListenerEx(E,'blur',FCKPanel_Window_OnBlur,this);};B.dir=FCKLang.Dir;FCKTools.AddEventListener(B,'contextmenu',FCKTools.CancelEvent);this.MainNode=B.body.appendChild(B.createElement('DIV'));this.MainNode.style.cssFloat=this.IsRTL?'right':'left';};FCKPanel.prototype.AppendStyleSheet=function(A){FCKTools.AppendStyleSheet(this.Document,A);};FCKPanel.prototype.Preload=function(x,y,A){if (this._Popup) this._Popup.show(x,y,0,0,A);};FCKPanel.prototype.Show=function(x,y,A,B,C){var D;var E=this.MainNode;if (this._Popup){this._Popup.show(x,y,0,0,A);FCKDomTools.SetElementStyles(E,{B:B?B+'px':'',C:C?C+'px':''});D=E.offsetWidth;if (this.IsRTL){if (this.IsContextMenu) x=x-D+1;else if (A) x=(x*-1)+A.offsetWidth-D;};this._Popup.show(x,y,D,E.offsetHeight,A);if (this.OnHide){if (this._Timer) CheckPopupOnHide.call(this,true);this._Timer=FCKTools.SetInterval(CheckPopupOnHide,100,this);}}else{if (typeof(FCK.ToolbarSet.CurrentInstance.FocusManager)!='undefined') FCK.ToolbarSet.CurrentInstance.FocusManager.Lock();if (this.ParentPanel){this.ParentPanel.Lock();FCKPanel_Window_OnBlur(null,this.ParentPanel);};if (FCKBrowserInfo.IsGecko&&FCKBrowserInfo.IsMac){this._IFrame.scrolling='';FCKTools.RunFunction(function(){ this._IFrame.scrolling='no';},this);};if (FCK.ToolbarSet.CurrentInstance.GetInstanceObject('FCKPanel')._OpenedPanel&&FCK.ToolbarSet.CurrentInstance.GetInstanceObject('FCKPanel')._OpenedPanel!=this) FCK.ToolbarSet.CurrentInstance.GetInstanceObject('FCKPanel')._OpenedPanel.Hide(false,true);FCKDomTools.SetElementStyles(E,{B:B?B+'px':'',C:C?C+'px':''});D=E.offsetWidth;if (!B) this._IFrame.width=1;if (!C) this._IFrame.height=1;D=E.offsetWidth||E.firstChild.offsetWidth;var F=FCKTools.GetDocumentPosition(this._Window,A.nodeType==9?(FCKTools.IsStrictMode(A)?A.documentElement:A.body):A);var G=FCKDomTools.GetPositionedAncestor(this._IFrame.parentNode);if (G){var H=FCKTools.GetDocumentPosition(FCKTools.GetElementWindow(G),G);F.x-=H.x;F.y-=H.y;};if (this.IsRTL&&!this.IsContextMenu) x=(x*-1);x+=F.x;y+=F.y;if (this.IsRTL){if (this.IsContextMenu) x=x-D+1;else if (A) x=x+A.offsetWidth-D;}else{var I=FCKTools.GetViewPaneSize(this._Window);var J=FCKTools.GetScrollPosition(this._Window);var K=I.Height+J.Y;var L=I.Width+J.X;if ((x+D)>L) x-=x+D-L;if ((y+E.offsetHeight)>K) y-=y+E.offsetHeight-K;};FCKDomTools.SetElementStyles(this._IFrame,{left:x+'px',top:y+'px'});this._IFrame.contentWindow.focus();this._IsOpened=true;var M=this;this._resizeTimer=setTimeout(function(){var N=E.offsetWidth||E.firstChild.offsetWidth;var O=E.offsetHeight;M._IFrame.width=N;M._IFrame.height=O;},0);FCK.ToolbarSet.CurrentInstance.GetInstanceObject('FCKPanel')._OpenedPanel=this;};FCKTools.RunFunction(this.OnShow,this);};FCKPanel.prototype.Hide=function(A,B){if (this._Popup) this._Popup.hide();else{if (!this._IsOpened||this._LockCounter>0) return;if (typeof(FCKFocusManager)!='undefined'&&!B) FCKFocusManager.Unlock();this._IFrame.width=this._IFrame.height=0;this._IsOpened=false;if (this._resizeTimer){clearTimeout(this._resizeTimer);this._resizeTimer=null;};if (this.ParentPanel) this.ParentPanel.Unlock();if (!A) FCKTools.RunFunction(this.OnHide,this);}};FCKPanel.prototype.CheckIsOpened=function(){if (this._Popup) return this._Popup.isOpen;else return this._IsOpened;};FCKPanel.prototype.CreateChildPanel=function(){var A=this._Popup?FCKTools.GetDocumentWindow(this.Document):this._Window;var B=new FCKPanel(A);B.ParentPanel=this;return B;};FCKPanel.prototype.Lock=function(){this._LockCounter++;};FCKPanel.prototype.Unlock=function(){if (--this._LockCounter==0&&!this.HasFocus) this.Hide();};function FCKPanel_Window_OnFocus(e,A){A.HasFocus=true;};function FCKPanel_Window_OnBlur(e,A){A.HasFocus=false;if (A._LockCounter==0) FCKTools.RunFunction(A.Hide,A);};function CheckPopupOnHide(A){if (A||!this._Popup.isOpen){window.clearInterval(this._Timer);this._Timer=null;FCKTools.RunFunction(this.OnHide,this);}};function FCKPanel_Cleanup(){this._Popup=null;this._Window=null;this.Document=null;this.MainNode=null;}; +var FCKIcon=function(A){var B=A?typeof(A):'undefined';switch (B){case 'number':this.Path=FCKConfig.SkinPath+'fck_strip.gif';this.Size=16;this.Position=A;break;case 'undefined':this.Path=FCK_SPACER_PATH;break;case 'string':this.Path=A;break;default:this.Path=A[0];this.Size=A[1];this.Position=A[2];}};FCKIcon.prototype.CreateIconElement=function(A){var B,eIconImage;if (this.Position){var C='-'+((this.Position-1)*this.Size)+'px';if (FCKBrowserInfo.IsIE){B=A.createElement('DIV');eIconImage=B.appendChild(A.createElement('IMG'));eIconImage.src=this.Path;eIconImage.style.top=C;}else{B=A.createElement('IMG');B.src=FCK_SPACER_PATH;B.style.backgroundPosition='0px '+C;B.style.backgroundImage='url("'+this.Path+'")';}}else{if (FCKBrowserInfo.IsIE){B=A.createElement('DIV');eIconImage=B.appendChild(A.createElement('IMG'));eIconImage.src=this.Path?this.Path:FCK_SPACER_PATH;}else{B=A.createElement('IMG');B.src=this.Path?this.Path:FCK_SPACER_PATH;}};B.className='TB_Button_Image';return B;}; +var FCKToolbarButtonUI=function(A,B,C,D,E,F){this.Name=A;this.Label=B||A;this.Tooltip=C||this.Label;this.Style=E||0;this.State=F||0;this.Icon=new FCKIcon(D);if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKToolbarButtonUI_Cleanup);};FCKToolbarButtonUI.prototype._CreatePaddingElement=function(A){var B=A.createElement('IMG');B.className='TB_Button_Padding';B.src=FCK_SPACER_PATH;return B;};FCKToolbarButtonUI.prototype.Create=function(A){var B=FCKTools.GetElementDocument(A);var C=this.MainElement=B.createElement('DIV');C.title=this.Tooltip;if (FCKBrowserInfo.IsGecko) C.onmousedown=FCKTools.CancelEvent;FCKTools.AddEventListenerEx(C,'mouseover',FCKToolbarButtonUI_OnMouseOver,this);FCKTools.AddEventListenerEx(C,'mouseout',FCKToolbarButtonUI_OnMouseOut,this);FCKTools.AddEventListenerEx(C,'click',FCKToolbarButtonUI_OnClick,this);this.ChangeState(this.State,true);if (this.Style==0&&!this.ShowArrow){C.appendChild(this.Icon.CreateIconElement(B));}else{var D=C.appendChild(B.createElement('TABLE'));D.cellPadding=0;D.cellSpacing=0;var E=D.insertRow(-1);var F=E.insertCell(-1);if (this.Style==0||this.Style==2) F.appendChild(this.Icon.CreateIconElement(B));else F.appendChild(this._CreatePaddingElement(B));if (this.Style==1||this.Style==2){F=E.insertCell(-1);F.className='TB_Button_Text';F.noWrap=true;F.appendChild(B.createTextNode(this.Label));};if (this.ShowArrow){if (this.Style!=0){E.insertCell(-1).appendChild(this._CreatePaddingElement(B));};F=E.insertCell(-1);var G=F.appendChild(B.createElement('IMG'));G.src=FCKConfig.SkinPath+'images/toolbar.buttonarrow.gif';G.width=5;G.height=3;};F=E.insertCell(-1);F.appendChild(this._CreatePaddingElement(B));};A.appendChild(C);};FCKToolbarButtonUI.prototype.ChangeState=function(A,B){if (!B&&this.State==A) return;var e=this.MainElement;if (!e) return;switch (parseInt(A,10)){case 0:e.className='TB_Button_Off';break;case 1:e.className='TB_Button_On';break;case -1:e.className='TB_Button_Disabled';break;};this.State=A;};function FCKToolbarButtonUI_OnMouseOver(A,B){if (B.State==0) this.className='TB_Button_Off_Over';else if (B.State==1) this.className='TB_Button_On_Over';};function FCKToolbarButtonUI_OnMouseOut(A,B){if (B.State==0) this.className='TB_Button_Off';else if (B.State==1) this.className='TB_Button_On';};function FCKToolbarButtonUI_OnClick(A,B){if (B.OnClick&&B.State!=-1) B.OnClick(B);};function FCKToolbarButtonUI_Cleanup(){this.MainElement=null;}; +var FCKToolbarButton=function(A,B,C,D,E,F,G){this.CommandName=A;this.Label=B;this.Tooltip=C;this.Style=D;this.SourceView=E?true:false;this.ContextSensitive=F?true:false;if (G==null) this.IconPath=FCKConfig.SkinPath+'toolbar/'+A.toLowerCase()+'.gif';else if (typeof(G)=='number') this.IconPath=[FCKConfig.SkinPath+'fck_strip.gif',16,G];else this.IconPath=G;};FCKToolbarButton.prototype.Create=function(A){this._UIButton=new FCKToolbarButtonUI(this.CommandName,this.Label,this.Tooltip,this.IconPath,this.Style);this._UIButton.OnClick=this.Click;this._UIButton._ToolbarButton=this;this._UIButton.Create(A);};FCKToolbarButton.prototype.RefreshState=function(){var A=this._UIButton;if (!A) return;var B=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetState();if (B==A.State) return;A.ChangeState(B);};FCKToolbarButton.prototype.Click=function(){var A=this._ToolbarButton||this;FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(A.CommandName).Execute();};FCKToolbarButton.prototype.Enable=function(){this.RefreshState();};FCKToolbarButton.prototype.Disable=function(){this._UIButton.ChangeState(-1);}; +var FCKSpecialCombo=function(A,B,C,D,E){this.FieldWidth=B||100;this.PanelWidth=C||150;this.PanelMaxHeight=D||150;this.Label=' ';this.Caption=A;this.Tooltip=A;this.Style=2;this.Enabled=true;this.Items={};this._Panel=new FCKPanel(E||window);this._Panel.AppendStyleSheet(FCKConfig.SkinEditorCSS);this._PanelBox=this._Panel.MainNode.appendChild(this._Panel.Document.createElement('DIV'));this._PanelBox.className='SC_Panel';this._PanelBox.style.width=this.PanelWidth+'px';this._PanelBox.innerHTML='
      ';this._ItemsHolderEl=this._PanelBox.getElementsByTagName('TD')[0];if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKSpecialCombo_Cleanup);};function FCKSpecialCombo_ItemOnMouseOver(){this.className+=' SC_ItemOver';};function FCKSpecialCombo_ItemOnMouseOut(){this.className=this.originalClass;};function FCKSpecialCombo_ItemOnClick(A,B,C){this.className=this.originalClass;B._Panel.Hide();B.SetLabel(this.FCKItemLabel);if (typeof(B.OnSelect)=='function') B.OnSelect(C,this);};FCKSpecialCombo.prototype.ClearItems=function (){if (this.Items) this.Items={};var A=this._ItemsHolderEl;while (A.firstChild) A.removeChild(A.firstChild);};FCKSpecialCombo.prototype.AddItem=function(A,B,C,D){var E=this._ItemsHolderEl.appendChild(this._Panel.Document.createElement('DIV'));E.className=E.originalClass='SC_Item';E.innerHTML=B;E.FCKItemLabel=C||A;E.Selected=false;if (FCKBrowserInfo.IsIE) E.style.width='100%';if (D) E.style.backgroundColor=D;FCKTools.AddEventListenerEx(E,'mouseover',FCKSpecialCombo_ItemOnMouseOver);FCKTools.AddEventListenerEx(E,'mouseout',FCKSpecialCombo_ItemOnMouseOut);FCKTools.AddEventListenerEx(E,'click',FCKSpecialCombo_ItemOnClick,[this,A]);this.Items[A.toString().toLowerCase()]=E;return E;};FCKSpecialCombo.prototype.SelectItem=function(A){if (typeof A=='string') A=this.Items[A.toString().toLowerCase()];if (A){A.className=A.originalClass='SC_ItemSelected';A.Selected=true;}};FCKSpecialCombo.prototype.SelectItemByLabel=function(A,B){for (var C in this.Items){var D=this.Items[C];if (D.FCKItemLabel==A){D.className=D.originalClass='SC_ItemSelected';D.Selected=true;if (B) this.SetLabel(A);}}};FCKSpecialCombo.prototype.DeselectAll=function(A){for (var i in this.Items){if (!this.Items[i]) continue;this.Items[i].className=this.Items[i].originalClass='SC_Item';this.Items[i].Selected=false;};if (A) this.SetLabel('');};FCKSpecialCombo.prototype.SetLabelById=function(A){A=A?A.toString().toLowerCase():'';var B=this.Items[A];this.SetLabel(B?B.FCKItemLabel:'');};FCKSpecialCombo.prototype.SetLabel=function(A){A=(!A||A.length==0)?' ':A;if (A==this.Label) return;this.Label=A;var B=this._LabelEl;if (B){B.innerHTML=A;FCKTools.DisableSelection(B);}};FCKSpecialCombo.prototype.SetEnabled=function(A){this.Enabled=A;if (this._OuterTable) this._OuterTable.className=A?'':'SC_FieldDisabled';};FCKSpecialCombo.prototype.Create=function(A){var B=FCKTools.GetElementDocument(A);var C=this._OuterTable=A.appendChild(B.createElement('TABLE'));C.cellPadding=0;C.cellSpacing=0;C.insertRow(-1);var D;var E;switch (this.Style){case 0:D='TB_ButtonType_Icon';E=false;break;case 1:D='TB_ButtonType_Text';E=false;break;case 2:E=true;break;};if (this.Caption&&this.Caption.length>0&&E){var F=C.rows[0].insertCell(-1);F.innerHTML=this.Caption;F.className='SC_FieldCaption';};var G=FCKTools.AppendElement(C.rows[0].insertCell(-1),'div');if (E){G.className='SC_Field';G.style.width=this.FieldWidth+'px';G.innerHTML='
       
      ';this._LabelEl=G.getElementsByTagName('label')[0];this._LabelEl.innerHTML=this.Label;}else{G.className='TB_Button_Off';G.innerHTML='
      '+this.Caption+'
      ';};FCKTools.AddEventListenerEx(G,'mouseover',FCKSpecialCombo_OnMouseOver,this);FCKTools.AddEventListenerEx(G,'mouseout',FCKSpecialCombo_OnMouseOut,this);FCKTools.AddEventListenerEx(G,'click',FCKSpecialCombo_OnClick,this);FCKTools.DisableSelection(this._Panel.Document.body);};function FCKSpecialCombo_Cleanup(){this._LabelEl=null;this._OuterTable=null;this._ItemsHolderEl=null;this._PanelBox=null;if (this.Items){for (var A in this.Items) this.Items[A]=null;}};function FCKSpecialCombo_OnMouseOver(A,B){if (B.Enabled){switch (B.Style){case 0:this.className='TB_Button_On_Over';break;case 1:this.className='TB_Button_On_Over';break;case 2:this.className='SC_Field SC_FieldOver';break;}}};function FCKSpecialCombo_OnMouseOut(A,B){switch (B.Style){case 0:this.className='TB_Button_Off';break;case 1:this.className='TB_Button_Off';break;case 2:this.className='SC_Field';break;}};function FCKSpecialCombo_OnClick(e,A){if (A.Enabled){var B=A._Panel;var C=A._PanelBox;var D=A._ItemsHolderEl;var E=A.PanelMaxHeight;if (A.OnBeforeClick) A.OnBeforeClick(A);if (FCKBrowserInfo.IsIE) B.Preload(0,this.offsetHeight,this);if (D.offsetHeight>E) C.style.height=E+'px';else C.style.height='';B.Show(0,this.offsetHeight,this);}}; +var FCKToolbarSpecialCombo=function(){this.SourceView=false;this.ContextSensitive=true;this.FieldWidth=null;this.PanelWidth=null;this.PanelMaxHeight=null;};FCKToolbarSpecialCombo.prototype.DefaultLabel='';function FCKToolbarSpecialCombo_OnSelect(A,B){FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).Execute(A,B);};FCKToolbarSpecialCombo.prototype.Create=function(A){this._Combo=new FCKSpecialCombo(this.GetLabel(),this.FieldWidth,this.PanelWidth,this.PanelMaxHeight,FCKBrowserInfo.IsIE?window:FCKTools.GetElementWindow(A).parent);this._Combo.Tooltip=this.Tooltip;this._Combo.Style=this.Style;this.CreateItems(this._Combo);this._Combo.Create(A);this._Combo.CommandName=this.CommandName;this._Combo.OnSelect=FCKToolbarSpecialCombo_OnSelect;};function FCKToolbarSpecialCombo_RefreshActiveItems(A,B){A.DeselectAll();A.SelectItem(B);A.SetLabelById(B);};FCKToolbarSpecialCombo.prototype.RefreshState=function(){var A;var B=FCK.ToolbarSet.CurrentInstance.Commands.GetCommand(this.CommandName).GetState();if (B!=-1){A=1;if (this.RefreshActiveItems) this.RefreshActiveItems(this._Combo,B);else{if (this._LastValue!==B){this._LastValue=B;if (!B||B.length==0){this._Combo.DeselectAll();this._Combo.SetLabel(this.DefaultLabel);}else FCKToolbarSpecialCombo_RefreshActiveItems(this._Combo,B);}}}else A=-1;if (A==this.State) return;if (A==-1){this._Combo.DeselectAll();this._Combo.SetLabel('');};this.State=A;this._Combo.SetEnabled(A!=-1);};FCKToolbarSpecialCombo.prototype.Enable=function(){this.RefreshState();};FCKToolbarSpecialCombo.prototype.Disable=function(){this.State=-1;this._Combo.DeselectAll();this._Combo.SetLabel('');this._Combo.SetEnabled(false);}; +var FCKToolbarStyleCombo=function(A,B){if (A===false) return;this.CommandName='Style';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;this.DefaultLabel=FCKConfig.DefaultStyleLabel||'';};FCKToolbarStyleCombo.prototype=new FCKToolbarSpecialCombo;FCKToolbarStyleCombo.prototype.GetLabel=function(){return FCKLang.Style;};FCKToolbarStyleCombo.prototype.GetStyles=function(){var A={};var B=FCK.ToolbarSet.CurrentInstance.Styles.GetStyles();for (var C in B){var D=B[C];if (!D.IsCore) A[C]=D;};return A;};FCKToolbarStyleCombo.prototype.CreateItems=function(A){var B=A._Panel.Document;FCKTools.AppendStyleSheet(B,FCKConfig.ToolbarComboPreviewCSS);FCKTools.AppendStyleString(B,FCKConfig.EditorAreaStyles);B.body.className+=' ForceBaseFont';FCKConfig.ApplyBodyAttributes(B.body);var C=this.GetStyles();for (var D in C){var E=C[D];var F=E.GetType()==2?D:FCKToolbarStyleCombo_BuildPreview(E,E.Label||D);var G=A.AddItem(D,F);G.Style=E;};A.OnBeforeClick=this.StyleCombo_OnBeforeClick;};FCKToolbarStyleCombo.prototype.RefreshActiveItems=function(A){var B=FCK.ToolbarSet.CurrentInstance.Selection.GetBoundaryParentElement(true);if (B){var C=new FCKElementPath(B);var D=C.Elements;for (var e=0;e');var E=A.Element;if (E=='bdo') E='span';D=['<',E];var F=A._StyleDesc.Attributes;if (F){for (var G in F){D.push(' ',G,'="',A.GetFinalAttributeValue(G),'"');}};if (A._GetStyleText().length>0) D.push(' style="',A.GetFinalStyleValue(),'"');D.push('>',B,'');if (C==0) D.push('');return D.join('');}; +var FCKToolbarFontFormatCombo=function(A,B){if (A===false) return;this.CommandName='FontFormat';this.Label=this.GetLabel();this.Tooltip=A?A:this.Label;this.Style=B?B:2;this.NormalLabel='Normal';this.PanelWidth=190;this.DefaultLabel=FCKConfig.DefaultFontFormatLabel||'';};FCKToolbarFontFormatCombo.prototype=new FCKToolbarStyleCombo(false);FCKToolbarFontFormatCombo.prototype.GetLabel=function(){return FCKLang.FontFormat;};FCKToolbarFontFormatCombo.prototype.GetStyles=function(){var A={};var B=FCKLang['FontFormats'].split(';');var C={p:B[0],pre:B[1],address:B[2],h1:B[3],h2:B[4],h3:B[5],h4:B[6],h5:B[7],h6:B[8],div:B[9]||(B[0]+' (DIV)')};var D=FCKConfig.FontFormats.split(';');for (var i=0;i';G.open();G.write(''+H+''+document.getElementById('xToolbarSpace').innerHTML+'');G.close();if(FCKBrowserInfo.IsAIR) FCKAdobeAIR.ToolbarSet_InitOutFrame(G);FCKTools.AddEventListener(G,'contextmenu',FCKTools.CancelEvent);FCKTools.AppendStyleSheet(G,FCKConfig.SkinEditorCSS);B=D.__FCKToolbarSet=new FCKToolbarSet(G);B._IFrame=F;if (FCK.IECleanup) FCK.IECleanup.AddItem(D,FCKToolbarSet_Target_Cleanup);};B.CurrentInstance=FCK;if (!B.ToolbarItems) B.ToolbarItems=FCKToolbarItems;FCK.AttachToOnSelectionChange(B.RefreshItemsState);return B;};function FCK_OnBlur(A){var B=A.ToolbarSet;if (B.CurrentInstance==A) B.Disable();};function FCK_OnFocus(A){var B=A.ToolbarSet;var C=A||FCK;B.CurrentInstance.FocusManager.RemoveWindow(B._IFrame.contentWindow);B.CurrentInstance=C;C.FocusManager.AddWindow(B._IFrame.contentWindow,true);B.Enable();};function FCKToolbarSet_Cleanup(){this._TargetElement=null;this._IFrame=null;};function FCKToolbarSet_Target_Cleanup(){this.__FCKToolbarSet=null;};var FCKToolbarSet=function(A){this._Document=A;this._TargetElement=A.getElementById('xToolbar');var B=A.getElementById('xExpandHandle');var C=A.getElementById('xCollapseHandle');B.title=FCKLang.ToolbarExpand;FCKTools.AddEventListener(B,'click',FCKToolbarSet_Expand_OnClick);C.title=FCKLang.ToolbarCollapse;FCKTools.AddEventListener(C,'click',FCKToolbarSet_Collapse_OnClick);if (!FCKConfig.ToolbarCanCollapse||FCKConfig.ToolbarStartExpanded) this.Expand();else this.Collapse();C.style.display=FCKConfig.ToolbarCanCollapse?'':'none';if (FCKConfig.ToolbarCanCollapse) C.style.display='';else A.getElementById('xTBLeftBorder').style.display='';this.Toolbars=[];this.IsLoaded=false;if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKToolbarSet_Cleanup);};function FCKToolbarSet_Expand_OnClick(){FCK.ToolbarSet.Expand();};function FCKToolbarSet_Collapse_OnClick(){FCK.ToolbarSet.Collapse();};FCKToolbarSet.prototype.Expand=function(){this._ChangeVisibility(false);};FCKToolbarSet.prototype.Collapse=function(){this._ChangeVisibility(true);};FCKToolbarSet.prototype._ChangeVisibility=function(A){this._Document.getElementById('xCollapsed').style.display=A?'':'none';this._Document.getElementById('xExpanded').style.display=A?'none':'';if (FCKBrowserInfo.IsGecko){FCKTools.RunFunction(window.onresize);}};FCKToolbarSet.prototype.Load=function(A){this.Name=A;this.Items=[];this.ItemsWysiwygOnly=[];this.ItemsContextSensitive=[];this._TargetElement.innerHTML='';var B=FCKConfig.ToolbarSets[A];if (!B){alert(FCKLang.UnknownToolbarSet.replace(/%1/g,A));return;};this.Toolbars=[];for (var x=0;x0) break;}catch (e){break;};D=D.parent;};var E=D.document;var F=function(){if (!B) B=FCKConfig.FloatingPanelsZIndex+999;return++B;};var G=function(){if (!C) return;var H=FCKTools.IsStrictMode(E)?E.documentElement:E.body;FCKDomTools.SetElementStyles(C,{'width':Math.max(H.scrollWidth,H.clientWidth,E.scrollWidth||0)-1+'px','height':Math.max(H.scrollHeight,H.clientHeight,E.scrollHeight||0)-1+'px'});};var I=function(element){element.style.cssText='margin:0;padding:0;border:0;background-color:transparent;background-image:none;';};return {OpenDialog:function(dialogName,dialogTitle,dialogPage,width,height,customValue,parentWindow,resizable){if (!A) this.DisplayMainCover();var J={Title:dialogTitle,Page:dialogPage,Editor:window,CustomValue:customValue,TopWindow:D};FCK.ToolbarSet.CurrentInstance.Selection.Save();var K=FCKTools.GetViewPaneSize(D);var L=FCKTools.GetScrollPosition(D);var M=Math.max(L.Y+(K.Height-height-20)/2,0);var N=Math.max(L.X+(K.Width-width-20)/2,0);var O=E.createElement('iframe');I(O);O.src=FCKConfig.BasePath+'fckdialog.html';O.frameBorder=0;O.allowTransparency=true;FCKDomTools.SetElementStyles(O,{'position':'absolute','top':M+'px','left':N+'px','width':width+'px','height':height+'px','zIndex':F()});O._DialogArguments=J;E.body.appendChild(O);O._ParentDialog=A;A=O;},OnDialogClose:function(dialogWindow){var O=dialogWindow.frameElement;FCKDomTools.RemoveNode(O);if (O._ParentDialog){A=O._ParentDialog;O._ParentDialog.contentWindow.SetEnabled(true);}else{if (!FCKBrowserInfo.IsIE) FCK.Focus();this.HideMainCover();setTimeout(function(){ A=null;},0);FCK.ToolbarSet.CurrentInstance.Selection.Release();}},DisplayMainCover:function(){C=E.createElement('div');I(C);FCKDomTools.SetElementStyles(C,{'position':'absolute','zIndex':F(),'top':'0px','left':'0px','backgroundColor':FCKConfig.BackgroundBlockerColor});FCKDomTools.SetOpacity(C,FCKConfig.BackgroundBlockerOpacity);if (FCKBrowserInfo.IsIE&&!FCKBrowserInfo.IsIE7){var Q=E.createElement('iframe');I(Q);Q.hideFocus=true;Q.frameBorder=0;Q.src=FCKTools.GetVoidUrl();FCKDomTools.SetElementStyles(Q,{'width':'100%','height':'100%','position':'absolute','left':'0px','top':'0px','filter':'progid:DXImageTransform.Microsoft.Alpha(opacity=0)'});C.appendChild(Q);};FCKTools.AddEventListener(D,'resize',G);G();E.body.appendChild(C);FCKFocusManager.Lock();},HideMainCover:function(){FCKDomTools.RemoveNode(C);FCKFocusManager.Unlock();},GetCover:function(){return C;}};})(); +var FCKMenuItem=function(A,B,C,D,E,F){this.Name=B;this.Label=C||B;this.IsDisabled=E;this.Icon=new FCKIcon(D);this.SubMenu=new FCKMenuBlockPanel();this.SubMenu.Parent=A;this.SubMenu.OnClick=FCKTools.CreateEventListener(FCKMenuItem_SubMenu_OnClick,this);this.CustomData=F;if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKMenuItem_Cleanup);};FCKMenuItem.prototype.AddItem=function(A,B,C,D,E){this.HasSubMenu=true;return this.SubMenu.AddItem(A,B,C,D,E);};FCKMenuItem.prototype.AddSeparator=function(){this.SubMenu.AddSeparator();};FCKMenuItem.prototype.Create=function(A){var B=this.HasSubMenu;var C=FCKTools.GetElementDocument(A);var r=this.MainElement=A.insertRow(-1);r.className=this.IsDisabled?'MN_Item_Disabled':'MN_Item';if (!this.IsDisabled){FCKTools.AddEventListenerEx(r,'mouseover',FCKMenuItem_OnMouseOver,[this]);FCKTools.AddEventListenerEx(r,'click',FCKMenuItem_OnClick,[this]);if (!B) FCKTools.AddEventListenerEx(r,'mouseout',FCKMenuItem_OnMouseOut,[this]);};var D=r.insertCell(-1);D.className='MN_Icon';D.appendChild(this.Icon.CreateIconElement(C));D=r.insertCell(-1);D.className='MN_Label';D.noWrap=true;D.appendChild(C.createTextNode(this.Label));D=r.insertCell(-1);if (B){D.className='MN_Arrow';var E=D.appendChild(C.createElement('IMG'));E.src=FCK_IMAGES_PATH+'arrow_'+FCKLang.Dir+'.gif';E.width=4;E.height=7;this.SubMenu.Create();this.SubMenu.Panel.OnHide=FCKTools.CreateEventListener(FCKMenuItem_SubMenu_OnHide,this);}};FCKMenuItem.prototype.Activate=function(){this.MainElement.className='MN_Item_Over';if (this.HasSubMenu){this.SubMenu.Show(this.MainElement.offsetWidth+2,-2,this.MainElement);};FCKTools.RunFunction(this.OnActivate,this);};FCKMenuItem.prototype.Deactivate=function(){this.MainElement.className='MN_Item';if (this.HasSubMenu) this.SubMenu.Hide();};function FCKMenuItem_SubMenu_OnClick(A,B){FCKTools.RunFunction(B.OnClick,B,[A]);};function FCKMenuItem_SubMenu_OnHide(A){A.Deactivate();};function FCKMenuItem_OnClick(A,B){if (B.HasSubMenu) B.Activate();else{B.Deactivate();FCKTools.RunFunction(B.OnClick,B,[B]);}};function FCKMenuItem_OnMouseOver(A,B){B.Activate();};function FCKMenuItem_OnMouseOut(A,B){B.Deactivate();};function FCKMenuItem_Cleanup(){this.MainElement=null;}; +var FCKMenuBlock=function(){this._Items=[];};FCKMenuBlock.prototype.Count=function(){return this._Items.length;};FCKMenuBlock.prototype.AddItem=function(A,B,C,D,E){var F=new FCKMenuItem(this,A,B,C,D,E);F.OnClick=FCKTools.CreateEventListener(FCKMenuBlock_Item_OnClick,this);F.OnActivate=FCKTools.CreateEventListener(FCKMenuBlock_Item_OnActivate,this);this._Items.push(F);return F;};FCKMenuBlock.prototype.AddSeparator=function(){this._Items.push(new FCKMenuSeparator());};FCKMenuBlock.prototype.RemoveAllItems=function(){this._Items=[];var A=this._ItemsTable;if (A){while (A.rows.length>0) A.deleteRow(0);}};FCKMenuBlock.prototype.Create=function(A){if (!this._ItemsTable){if (FCK.IECleanup) FCK.IECleanup.AddItem(this,FCKMenuBlock_Cleanup);this._Window=FCKTools.GetElementWindow(A);var B=FCKTools.GetElementDocument(A);var C=A.appendChild(B.createElement('table'));C.cellPadding=0;C.cellSpacing=0;FCKTools.DisableSelection(C);var D=C.insertRow(-1).insertCell(-1);D.className='MN_Menu';var E=this._ItemsTable=D.appendChild(B.createElement('table'));E.cellPadding=0;E.cellSpacing=0;};for (var i=0;i0&&F.href.length==0);if (G) return;menu.AddSeparator();if (E) menu.AddItem('Link',FCKLang.EditLink,34);menu.AddItem('Unlink',FCKLang.RemoveLink,35);}}};case 'Image':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&!tag.getAttribute('_fckfakelement')){menu.AddSeparator();menu.AddItem('Image',FCKLang.ImageProperties,37);}}};case 'Anchor':return {AddItems:function(menu,tag,tagName){var F=FCKSelection.MoveToAncestorNode('A');var G=(F&&F.name.length>0);if (G||(tagName=='IMG'&&tag.getAttribute('_fckanchor'))){menu.AddSeparator();menu.AddItem('Anchor',FCKLang.AnchorProp,36);menu.AddItem('AnchorDelete',FCKLang.AnchorDelete);}}};case 'Flash':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&tag.getAttribute('_fckflash')){menu.AddSeparator();menu.AddItem('Flash',FCKLang.FlashProperties,38);}}};case 'Form':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('FORM')){menu.AddSeparator();menu.AddItem('Form',FCKLang.FormProp,48);}}};case 'Checkbox':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='checkbox'){menu.AddSeparator();menu.AddItem('Checkbox',FCKLang.CheckboxProp,49);}}};case 'Radio':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='radio'){menu.AddSeparator();menu.AddItem('Radio',FCKLang.RadioButtonProp,50);}}};case 'TextField':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&(tag.type=='text'||tag.type=='password')){menu.AddSeparator();menu.AddItem('TextField',FCKLang.TextFieldProp,51);}}};case 'HiddenField':return {AddItems:function(menu,tag,tagName){if (tagName=='IMG'&&tag.getAttribute('_fckinputhidden')){menu.AddSeparator();menu.AddItem('HiddenField',FCKLang.HiddenFieldProp,56);}}};case 'ImageButton':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&tag.type=='image'){menu.AddSeparator();menu.AddItem('ImageButton',FCKLang.ImageButtonProp,55);}}};case 'Button':return {AddItems:function(menu,tag,tagName){if (tagName=='INPUT'&&(tag.type=='button'||tag.type=='submit'||tag.type=='reset')){menu.AddSeparator();menu.AddItem('Button',FCKLang.ButtonProp,54);}}};case 'Select':return {AddItems:function(menu,tag,tagName){if (tagName=='SELECT'){menu.AddSeparator();menu.AddItem('Select',FCKLang.SelectionFieldProp,53);}}};case 'Textarea':return {AddItems:function(menu,tag,tagName){if (tagName=='TEXTAREA'){menu.AddSeparator();menu.AddItem('Textarea',FCKLang.TextareaProp,52);}}};case 'BulletedList':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('UL')){menu.AddSeparator();menu.AddItem('BulletedList',FCKLang.BulletedListProp,27);}}};case 'NumberedList':return {AddItems:function(menu,tag,tagName){if (FCKSelection.HasAncestorNode('OL')){menu.AddSeparator();menu.AddItem('NumberedList',FCKLang.NumberedListProp,26);}}};};return null;};function FCK_ContextMenu_OnBeforeOpen(){FCK.Events.FireEvent('OnSelectionChange');var A,sTagName;if ((A=FCKSelection.GetSelectedElement())) sTagName=A.tagName;var B=FCK.ContextMenu._InnerContextMenu;B.RemoveAllItems();var C=FCK.ContextMenu.Listeners;for (var i=0;i0){D=A.substr(0,B.index);this._sourceHtml=A.substr(B.index);}else{C=true;D=B[0];this._sourceHtml=A.substr(B[0].length);}}else{D=A;this._sourceHtml=null;};return { 'isTag':C,'value':D };},Each:function(A){var B;while ((B=this.Next())) A(B.isTag,B.value);}};var FCKHtmlIterator=function(A){this._sourceHtml=A;};FCKHtmlIterator.prototype={Next:function(){var A=this._sourceHtml;if (A==null) return null;var B=FCKRegexLib.HtmlTag.exec(A);var C=false;var D="";if (B){if (B.index>0){D=A.substr(0,B.index);this._sourceHtml=A.substr(B.index);}else{C=true;D=B[0];this._sourceHtml=A.substr(B[0].length);}}else{D=A;this._sourceHtml=null;};return { 'isTag':C,'value':D };},Each:function(A){var B;while ((B=this.Next())) A(B.isTag,B.value);}}; +var FCKPlugin=function(A,B,C){this.Name=A;this.BasePath=C?C:FCKConfig.PluginsPath;this.Path=this.BasePath+A+'/';if (!B||B.length==0) this.AvailableLangs=[];else this.AvailableLangs=B.split(',');};FCKPlugin.prototype.Load=function(){if (this.AvailableLangs.length>0){var A;if (this.AvailableLangs.IndexOf(FCKLanguageManager.ActiveLanguage.Code)>=0) A=FCKLanguageManager.ActiveLanguage.Code;else A=this.AvailableLangs[0];LoadScript(this.Path+'lang/'+A+'.js');};LoadScript(this.Path+'fckplugin.js');}; +var FCKPlugins=FCK.Plugins={};FCKPlugins.ItemsCount=0;FCKPlugins.Items={};FCKPlugins.Load=function(){var A=FCKPlugins.Items;for (var i=0;i", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Geen plekhouers beskikbaar in dokument}", DlgLnkEMail : "E-Mail Adres", DlgLnkEMailSubject : "Boodskap Opskrif", DlgLnkEMailBody : "Boodskap Inhoud", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Kant Kleur", DlgCellBtnSelect : "Keuse...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "Vind", DlgFindFindBtn : "Vind", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Ignoreer karakter soort defenisies", DlgPasteRemoveStyles : "Verweider Styl defenisies", -DlgPasteCleanBox : "Maak Box Skoon", // Color Picker ColorAutomatic : "Automaties", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Lesensie", DlgAboutVersion : "weergawe", DlgAboutInfo : "Vir meer informasie gaan na " -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ar.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ar.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ar.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "?????/????? ????", RemoveLink : "????? ????", Anchor : "?????/????? ????? ??????", +AnchorDelete : "????? ????? ??????", InsertImageLbl : "????", InsertImage : "?????/????? ????", InsertFlashLbl : "????", @@ -70,6 +71,7 @@ BlockJustify : "???", DecreaseIndent : "????? ??????? ???????", IncreaseIndent : "????? ??????? ???????", +Blockquote : "??????", Undo : "?????", Redo : "?????", NumberedListLbl : "????? ????", @@ -103,20 +105,27 @@ ImageButton : "?? ????", FitWindow : "????? ??? ??????", +ShowBlocks : "???? ??????", // Context Menu EditLink : "????? ????", CellCM : "????", RowCM : "??", ColumnCM : "????", -InsertRow : "????? ??", +InsertRowAfter : "????? ?? ???", +InsertRowBefore : "????? ?? ???", DeleteRows : "??? ????", -InsertColumn : "????? ????", +InsertColumnAfter : "????? ???? ???", +InsertColumnBefore : "????? ???? ???", DeleteColumns : "??? ?????", -InsertCell : "????? ????", +InsertCellAfter : "????? ???? ???", +InsertCellBefore : "????? ???? ???", DeleteCells : "??? ?????", MergeCells : "??? ?????", -SplitCell : "????? ????", +MergeRight : "??? ??????", +MergeDown : "??? ??????", +HorizontalSplitCell : "????? ?????? ??????", +VerticalSplitCell : "????? ?????? ???????", TableDelete : "??? ??????", CellProperties : "????? ??????", TableProperties : "????? ??????", @@ -134,7 +143,7 @@ TextareaProp : "????? ????? ????", FormProp : "????? ???????", -FontFormats : "????;?????;???;??????? 1;??????? 2;??????? 3;??????? 4;??????? 5;??????? 6", //REVIEW : Check _getfontformat.html +FontFormats : "????;?????;???;??????? 1;??????? 2;??????? 3;??????? 4;??????? 5;??????? 6", // Alerts and Messages ProcessingXHTML : "????? ?????? ????? ??? ???????? XHTML. ?? ?????? ??????...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "???? ????? ??????", DlgLnkAnchorByName : "??? ??? ???????", DlgLnkAnchorById : "??? ????? ??????", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(?? ???? ?????? ?????? ?? ??? ???????)", DlgLnkEMail : "????? ???? ????????", DlgLnkEMailSubject : "????? ???????", DlgLnkEMailBody : "????? ???????", @@ -322,6 +331,9 @@ DlgCellBorderColor : "??? ??????", DlgCellBtnSelect : "????...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "??? ????????", + // Find Dialog DlgFindTitle : "???", DlgFindFindBtn : "????", @@ -344,10 +356,9 @@ PasteFromWord : "??? ?? ????", DlgPasteMsg2 : "???? ???? ??????? ???????? ???? (Ctrl+V) ?? ???? ????????? ?? ???? ?? ?????.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "????? ???????? ?????? ?????? ???????? ?? ????? ??? ?????? ?? ?????? ?????? ??????? ??? ??? ???? ??? ??????? ??? ???? ?? ??? ???????.", DlgPasteIgnoreFont : "????? ??????? ????? ??????", DlgPasteRemoveStyles : "????? ??????? ???????", -DlgPasteCleanBox : "???? ????? ???????", // Color Picker ColorAutomatic : "??????", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "???????", DlgAboutVersion : "???????", DlgAboutInfo : "????? ?? ????????? ???? ??????" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/bg.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/bg.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/bg.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "§¥§à§Ò§Ñ§Ó§Ú/§²§Ö§Õ§Ñ§Ü§ä§Ú§â§Ñ§Û §Ó§â§ì§Ù§Ü§Ñ", RemoveLink : "§ª§Ù§ä§â§Ú§Û §Ó§â§ì§Ù§Ü§Ñ", Anchor : "§¥§à§Ò§Ñ§Ó§Ú/§²§Ö§Õ§Ñ§Ü§ä§Ú§â§Ñ§Û §Ü§à§ä§Ó§Ñ", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "§ª§Ù§à§Ò§â§Ñ§Ø§Ö§ß§Ú§Ö", InsertImage : "§¥§à§Ò§Ñ§Ó§Ú/§²§Ö§Õ§Ñ§Ü§ä§Ú§â§Ñ§Û §Ú§Ù§à§Ò§â§Ñ§Ø§Ö§ß§Ú§Ö", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "§¥§Ó§å§ã§ä§â§Ñ§ß§ß§à §á§à§Õ§â§Ñ§Ó§ß§ñ§Ó§Ñ§ß§Ö", DecreaseIndent : "§¯§Ñ§Þ§Ñ§Ý§Ú §à§ä§ã§ä§ì§á§Ñ", IncreaseIndent : "§µ§Ó§Ö§Ý§Ú§é§Ú §à§ä§ã§ä§ì§á§Ñ", +Blockquote : "Blockquote", //MISSING Undo : "§°§ä§Þ§Ö§ß§Ú", Redo : "§±§à§Ó§ä§à§â§Ú", NumberedListLbl : "§¯§å§Þ§Ö§â§Ú§â§Ñ§ß §ã§á§Ú§ã§ì§Ü", @@ -103,20 +105,27 @@ ImageButton : "§¢§å§ä§à§ß-§Ú§Ù§à§Ò§â§Ñ§Ø§Ö§ß§Ú§Ö", FitWindow : "Maximize the editor size", //MISSING +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "§²§Ö§Õ§Ñ§Ü§ä§Ú§â§Ñ§Û §Ó§â§ì§Ù§Ü§Ñ", CellCM : "Cell", //MISSING RowCM : "Row", //MISSING ColumnCM : "Column", //MISSING -InsertRow : "§¥§à§Ò§Ñ§Ó§Ú §â§Ö§Õ", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "§ª§Ù§ä§â§Ú§Û §â§Ö§Õ§à§Ó§Ö§ä§Ö", -InsertColumn : "§¥§à§Ò§Ñ§Ó§Ú §Ü§à§Ý§à§ß§Ñ", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "§ª§Ù§ä§â§Ú§Û §Ü§à§Ý§à§ß§Ú§ä§Ö", -InsertCell : "§¥§à§Ò§Ñ§Ó§Ú §Ü§Ý§Ö§ä§Ü§Ñ", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "§ª§Ù§ä§â§Ú§Û §Ü§Ý§Ö§ä§Ü§Ú§ä§Ö", MergeCells : "§°§Ò§Ö§Õ§Ú§ß§Ú §Ü§Ý§Ö§ä§Ü§Ú§ä§Ö", -SplitCell : "§²§Ñ§Ù§Õ§Ö§Ý§Ú §Ü§Ý§Ö§ä§Ü§Ñ§ä§Ñ", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "§ª§Ù§ä§â§Ú§Û §ä§Ñ§Ò§Ý§Ú§è§Ñ§ä§Ñ", CellProperties : "§±§Ñ§â§Ñ§Þ§Ö§ä§â§Ú §ß§Ñ §Ü§Ý§Ö§ä§Ü§Ñ§ä§Ñ", TableProperties : "§±§Ñ§â§Ñ§Þ§Ö§ä§â§Ú §ß§Ñ §ä§Ñ§Ò§Ý§Ú§è§Ñ§ä§Ñ", @@ -134,7 +143,7 @@ TextareaProp : "§±§Ñ§â§Ñ§Þ§Ö§ä§â§Ú §ß§Ñ §ä§Ö§Ü§ã§ä§à§Ó§Ñ§ä§Ñ §à§Ò§Ý§Ñ§ã§ä", FormProp : "§±§Ñ§â§Ñ§Þ§Ö§ä§â§Ú §ß§Ñ §æ§à§â§Þ§å§Ý§ñ§â§Ñ", -FontFormats : "§¯§à§â§Þ§Ñ§Ý§Ö§ß;§¶§à§â§Þ§Ñ§ä§Ú§â§Ñ§ß;§¡§Õ§â§Ö§ã;§©§Ñ§Ô§Ý§Ñ§Ó§Ú§Ö 1;§©§Ñ§Ô§Ý§Ñ§Ó§Ú§Ö 2;§©§Ñ§Ô§Ý§Ñ§Ó§Ú§Ö 3;§©§Ñ§Ô§Ý§Ñ§Ó§Ú§Ö 4;§©§Ñ§Ô§Ý§Ñ§Ó§Ú§Ö 5;§©§Ñ§Ô§Ý§Ñ§Ó§Ú§Ö 6;§±§Ñ§â§Ñ§Ô§â§Ñ§æ (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "§¯§à§â§Þ§Ñ§Ý§Ö§ß;§¶§à§â§Þ§Ñ§ä§Ú§â§Ñ§ß;§¡§Õ§â§Ö§ã;§©§Ñ§Ô§Ý§Ñ§Ó§Ú§Ö 1;§©§Ñ§Ô§Ý§Ñ§Ó§Ú§Ö 2;§©§Ñ§Ô§Ý§Ñ§Ó§Ú§Ö 3;§©§Ñ§Ô§Ý§Ñ§Ó§Ú§Ö 4;§©§Ñ§Ô§Ý§Ñ§Ó§Ú§Ö 5;§©§Ñ§Ô§Ý§Ñ§Ó§Ú§Ö 6;§±§Ñ§â§Ñ§Ô§â§Ñ§æ (DIV)", // Alerts and Messages ProcessingXHTML : "§°§Ò§â§Ñ§Ò§à§ä§Ü§Ñ §ß§Ñ XHTML. §®§à§Ý§ñ §Ú§Ù§é§Ñ§Ü§Ñ§Û§ä§Ö...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "§ª§Ù§Ò§Ö§â§Ö§ä§Ö §Ü§à§ä§Ó§Ñ", DlgLnkAnchorByName : "§±§à §Ú§Þ§Ö §ß§Ñ §Ü§à§ä§Ó§Ñ§ä§Ñ", DlgLnkAnchorById : "§±§à §Ú§Õ§Ö§ß§ä§Ú§æ§Ú§Ü§Ñ§ä§à§â §ß§Ñ §Ö§Ý§Ö§Þ§Ö§ß§ä", -DlgLnkNoAnchors : "<§¯§ñ§Þ§Ñ §Ü§à§ä§Ó§Ú §Ó §ä§Ö§Ü§å§ë§Ú§ñ §Õ§à§Ü§å§Þ§Ö§ß§ä>", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(§¯§ñ§Þ§Ñ §Ü§à§ä§Ó§Ú §Ó §ä§Ö§Ü§å§ë§Ú§ñ §Õ§à§Ü§å§Þ§Ö§ß§ä)", DlgLnkEMail : "§¡§Õ§â§Ö§ã §Ù§Ñ §Ö-§á§à§ë§Ñ", DlgLnkEMailSubject : "§´§Ö§Þ§Ñ §ß§Ñ §á§Ú§ã§Þ§à§ä§à", DlgLnkEMailBody : "§´§Ö§Ü§ã§ä §ß§Ñ §á§Ú§ã§Þ§à§ä§à", @@ -322,6 +331,9 @@ DlgCellBorderColor : "§è§Ó§ñ§ä §ß§Ñ §â§Ñ§Þ§Ü§Ñ§ä§Ñ", DlgCellBtnSelect : "§ª§Ù§Ò§Ö§â§Ö§ä§Ö...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "§´§ì§â§ã§Ú", DlgFindFindBtn : "§´§ì§â§ã§Ú", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "§ª§Ô§ß§à§â§Ú§â§Ñ§Û §ê§â§Ú§æ§ä§à§Ó§Ú§ä§Ö §Õ§Ö§æ§Ú§ß§Ú§è§Ú§Ú", DlgPasteRemoveStyles : "§ª§Ù§ä§â§Ú§Û §ã§ä§Ú§Ý§à§Ó§Ú§ä§Ö §Õ§Ö§æ§Ú§ß§Ú§è§Ú§Ú", -DlgPasteCleanBox : "§ª§Ù§é§Ú§ã§ä§Ú", // Color Picker ColorAutomatic : "§±§à §á§à§Õ§â§Ñ§Ù§Ò§Ú§â§Ñ§ß§Ö", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "License", //MISSING DlgAboutVersion : "§Ó§Ö§â§ã§Ú§ñ", DlgAboutInfo : "§©§Ñ §á§à§Ó§Ö§é§Ö §Ú§ß§æ§à§â§Þ§Ñ§è§Ú§ñ §á§à§ã§Ö§ä§Ö§ä§Ö" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/bn.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/bn.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/bn.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "???? ????? ??", RemoveLink : "???? ????", Anchor : "??????", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "???? ????? ????? ??", InsertImage : "??? ????? ??", InsertFlashLbl : "????? ????? ????? ??", @@ -70,6 +71,7 @@ BlockJustify : "???? ?????????", DecreaseIndent : "??????? ????", IncreaseIndent : "??????? ?????", +Blockquote : "Blockquote", //MISSING Undo : "????", Redo : "??-??", NumberedListLbl : "???????? ??????? ?????", @@ -103,20 +105,27 @@ ImageButton : "???? ????", FitWindow : "?????? ??? ??", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "???? ???????", CellCM : "???", RowCM : "??", ColumnCM : "????", -InsertRow : "?? ????? ??", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "?? ???? ???", -InsertColumn : "???? ????? ??", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "???? ???? ???", -InsertCell : "??? ????? ??", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "??? ???? ???", MergeCells : "??? ???? ???", -SplitCell : "??? ????? ??", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "????? ????? ??", CellProperties : "????? ???????????", TableProperties : "????? ??????????", @@ -134,7 +143,7 @@ TextareaProp : "?????? ????? ??????????", FormProp : "???? ??????????", -FontFormats : "??????;????????;??????;?????? ?;?????? ?;?????? ?;?????? ?;?????? ?;?????? ?;?????? (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "??????;????????;??????;?????? ?;?????? ?;?????? ?;?????? ?;?????? ?;?????? ?;?????? (DIV)", // Alerts and Messages ProcessingXHTML : "XHTML ?????? ??? ?????", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "???? ?????", DlgLnkAnchorByName : "?????? ??? ????", DlgLnkAnchorById : "?????? ???? ????", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(No anchors available in the document)", //MISSING DlgLnkEMail : "????? ??????", DlgLnkEMailSubject : "??????? ????", DlgLnkEMailBody : "??????? ???", @@ -322,6 +331,9 @@ DlgCellBorderColor : "???????? ??", DlgCellBtnSelect : "????? ??", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "?????", DlgFindFindBtn : "?????", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "???? ??? ???????? ????? ????", DlgPasteRemoveStyles : "?????? ???????? ????? ???", -DlgPasteCleanBox : "????? ???????? ????", // Color Picker ColorAutomatic : "????????", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "????????", DlgAboutVersion : "??????", DlgAboutInfo : "??? ?????? ???? ???" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/bs.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/bs.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/bs.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Ubaci/Izmjeni link", RemoveLink : "Izbri«Þi link", Anchor : "Insert/Edit Anchor", //MISSING +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Slika", InsertImage : "Ubaci/Izmjeni sliku", InsertFlashLbl : "Flash", //MISSING @@ -70,6 +71,7 @@ BlockJustify : "Puno poravnanje", DecreaseIndent : "Smanji uvod", IncreaseIndent : "Pove©Áaj uvod", +Blockquote : "Blockquote", //MISSING Undo : "Vrati", Redo : "Ponovi", NumberedListLbl : "Numerisana lista", @@ -103,20 +105,27 @@ ImageButton : "Image Button", //MISSING FitWindow : "Maximize the editor size", //MISSING +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "Izmjeni link", CellCM : "Cell", //MISSING RowCM : "Row", //MISSING ColumnCM : "Column", //MISSING -InsertRow : "Ubaci red", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Bri«Þi redove", -InsertColumn : "Ubaci kolonu", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "Bri«Þi kolone", -InsertCell : "Ubaci ©Áeliju", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "Bri«Þi ©Áelije", MergeCells : "Spoji ©Áelije", -SplitCell : "Razdvoji ©Áeliju", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Delete Table", //MISSING CellProperties : "Svojstva ©Áelije", TableProperties : "Svojstva tabele", @@ -134,7 +143,7 @@ TextareaProp : "Textarea Properties", //MISSING FormProp : "Form Properties", //MISSING -FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6", // Alerts and Messages ProcessingXHTML : "Procesiram XHTML. Molim sa«²ekajte...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Izaberi sidro", DlgLnkAnchorByName : "Po nazivu sidra", DlgLnkAnchorById : "Po Id-u elementa", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Nema dostupnih sidra na stranici)", DlgLnkEMail : "E-Mail Adresa", DlgLnkEMailSubject : "Subjekt poruke", DlgLnkEMailBody : "Poruka", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Boja okvira", DlgCellBtnSelect : "Selektuj...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "Na©Ãi", DlgFindFindBtn : "Na©Ãi", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Ignore Font Face definitions", //MISSING DlgPasteRemoveStyles : "Remove Styles definitions", //MISSING -DlgPasteCleanBox : "Clean Up Box", //MISSING // Color Picker ColorAutomatic : "Automatska", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "License", //MISSING DlgAboutVersion : "verzija", DlgAboutInfo : "Za vi«Þe informacija posjetite" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ca.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ca.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ca.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -26,13 +26,13 @@ // Language direction : "ltr" (left to right) or "rtl" (right to left). Dir : "ltr", -ToolbarCollapse : "Col?lapsa la barra", -ToolbarExpand : "Amplia la barra", +ToolbarCollapse : "Redueix la barra d'eines", +ToolbarExpand : "Amplia la barra d'eines", // Toolbar Items and Context Menu Save : "Desa", NewPage : "Nova P«¢gina", -Preview : "Vista Pr«²via", +Preview : "Visualitzaci«Ñ pr«²via", Cut : "Retalla", Copy : "Copia", Paste : "Enganxa", @@ -45,6 +45,7 @@ InsertLink : "Insereix/Edita enlla«®", RemoveLink : "Elimina enlla«®", Anchor : "Insereix/Edita «¢ncora", +AnchorDelete : "Elimina «¢ncora", InsertImageLbl : "Imatge", InsertImage : "Insereix/Edita imatge", InsertFlashLbl : "Flash", @@ -57,25 +58,26 @@ InsertSpecialChar : "Insereix car«¢cter especial", InsertSmileyLbl : "Icona", InsertSmiley : "Insereix icona", -About : "Quant a FCKeditor", +About : "Quant a l'FCKeditor", Bold : "Negreta", Italic : "Cursiva", Underline : "Subratllat", StrikeThrough : "Barrat", Subscript : "Sub«¿ndex", Superscript : "Super«¿ndex", -LeftJustify : "Aliniament esquerra", -CenterJustify : "Aliniament centrat", -RightJustify : "Aliniament dreta", -BlockJustify : "Justifica", -DecreaseIndent : "Sagna el text", -IncreaseIndent : "Treu el sagnat del text", +LeftJustify : "Alinia a l'esquerra", +CenterJustify : "Centrat", +RightJustify : "Alinia a la dreta", +BlockJustify : "Justificat", +DecreaseIndent : "Redueix el sagnat", +IncreaseIndent : "Augmenta el sagnat", +Blockquote : "Bloc de cita", Undo : "Desf«±s", Redo : "Ref«±s", NumberedListLbl : "Llista numerada", -NumberedList : "Aplica o elimina la llista numerada", +NumberedList : "Numeraci«Ñ activada/desactivada", BulletedListLbl : "Llista de pics", -BulletedList : "Aplica o elimina la llista de pics", +BulletedList : "Pics activats/descativats", ShowTableBorders : "Mostra les vores de les taules", ShowDetails : "Mostra detalls", Style : "Estil", @@ -103,20 +105,27 @@ ImageButton : "Bot«Ñ d'imatge", FitWindow : "Maximiza la mida de l'editor", +ShowBlocks : "Mostra els blocs", // Context Menu EditLink : "Edita l'enlla«®", CellCM : "Cel?la", RowCM : "Fila", ColumnCM : "Columna", -InsertRow : "Insereix una fila", +InsertRowAfter : "Insereix fila darrera", +InsertRowBefore : "Insereix fila abans de", DeleteRows : "Suprimeix una fila", -InsertColumn : "Afegeix una columna", +InsertColumnAfter : "Insereix columna darrera", +InsertColumnBefore : "Insereix columna abans de", DeleteColumns : "Suprimeix una columna", -InsertCell : "Insereix una cel?la", +InsertCellAfter : "Insereix cel?la darrera", +InsertCellBefore : "Insereix cel?la abans de", DeleteCells : "Suprimeix les cel?les", MergeCells : "Fusiona les cel?les", -SplitCell : "Separa les cel?les", +MergeRight : "Fusiona cap a la dreta", +MergeDown : "Fusiona cap avall", +HorizontalSplitCell : "Divideix la cel?la horitzontalment", +VerticalSplitCell : "Divideix la cel?la verticalment", TableDelete : "Suprimeix la taula", CellProperties : "Propietats de la cel?la", TableProperties : "Propietats de la taula", @@ -134,7 +143,7 @@ TextareaProp : "Propietats de l'«¢rea de text", FormProp : "Propietats del formulari", -FontFormats : "Normal;Formatejat;Adre«®a;Encap«®alament 1;Encap«®alament 2;Encap«®alament 3;Encap«®alament 4;Encap«®alament 5;Encap«®alament 6", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatejat;Adre«®a;Encap«®alament 1;Encap«®alament 2;Encap«®alament 3;Encap«®alament 4;Encap«®alament 5;Encap«®alament 6;Normal (DIV)", // Alerts and Messages ProcessingXHTML : "Processant XHTML. Si us plau esperi...", @@ -222,15 +231,15 @@ DlgLnkType : "Tipus d'enlla«®", DlgLnkTypeURL : "URL", DlgLnkTypeAnchor : "ª¢ncora en aquesta p«¢gina", -DlgLnkTypeEMail : "E-Mail", +DlgLnkTypeEMail : "Correu electr«Ònic", DlgLnkProto : "Protocol", DlgLnkProtoOther : "", DlgLnkURL : "URL", DlgLnkAnchorSel : "Selecciona una «¢ncora", DlgLnkAnchorByName : "Per nom d'«¢ncora", DlgLnkAnchorById : "Per Id d'element", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) -DlgLnkEMail : "Adre«®a d'E-Mail", +DlgLnkNoAnchors : "(No hi ha «¢ncores disponibles en aquest document)", +DlgLnkEMail : "Adre«®a de correu electr«Ònic", DlgLnkEMailSubject : "Assumpte del missatge", DlgLnkEMailBody : "Cos del missatge", DlgLnkUpload : "Puja", @@ -260,7 +269,7 @@ DlgLnkPopTop : "Posici«Ñ dalt", DlnLnkMsgNoUrl : "Si us plau, escrigui l'enlla«® URL", -DlnLnkMsgNoEMail : "Si us plau, escrigui l'adre«®a e-mail", +DlnLnkMsgNoEMail : "Si us plau, escrigui l'adre«®a correu electr«Ònic", DlnLnkMsgNoAnchor : "Si us plau, escrigui l'«¢ncora", DlnLnkMsgInvPopName : "El nom de la finestra emergent ha de comen«®ar amb una lletra i no pot tenir espais", @@ -280,7 +289,7 @@ DlgTableTitle : "Propietats de la taula", DlgTableRows : "Files", DlgTableColumns : "Columnes", -DlgTableBorder : "Tamany vora", +DlgTableBorder : "Mida vora", DlgTableAlign : "Alineaci«Ñ", DlgTableAlignNotSet : "", DlgTableAlignLeft : "Esquerra", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Color de la vora", DlgCellBtnSelect : "Seleccioneu...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Cerca i reempla«®a", + // Find Dialog DlgFindTitle : "Cerca", DlgFindFindBtn : "Cerca", @@ -331,23 +343,22 @@ DlgReplaceTitle : "Reempla«®a", DlgReplaceFindLbl : "Cerca:", DlgReplaceReplaceLbl : "Rempla«®a amb:", -DlgReplaceCaseChk : "Sensible a maj«âscules", +DlgReplaceCaseChk : "Distingeix maj«âscules/min«âscules", DlgReplaceReplaceBtn : "Reempla«®a", -DlgReplaceReplAllBtn : "Reempla«®a'ls tots", -DlgReplaceWordChk : "Cerca paraula completa", +DlgReplaceReplAllBtn : "Reempla«®a-ho tot", +DlgReplaceWordChk : "Nom«±s paraules completes", // Paste Operations / Dialog PasteErrorCut : "La seguretat del vostre navegador no permet executar autom«¢ticament les operacions de retallar. Si us plau, utilitzeu el teclat (Ctrl+X).", PasteErrorCopy : "La seguretat del vostre navegador no permet executar autom«¢ticament les operacions de copiar. Si us plau, utilitzeu el teclat (Ctrl+C).", -PasteAsText : "Enganxa com a text sense format", +PasteAsText : "Enganxa com a text no formatat", PasteFromWord : "Enganxa com a Word", DlgPasteMsg2 : "Si us plau, enganxeu dins del seg«äent camp utilitzant el teclat (Ctrl+V) i premeu OK.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "A causa de la configuraci«Ñ de seguretat del vostre navegador, l'editor no pot accedir al porta-retalls directament. Enganxeu-ho un altre cop en aquesta finestra.", DlgPasteIgnoreFont : "Ignora definicions de font", DlgPasteRemoveStyles : "Elimina definicions d'estil", -DlgPasteCleanBox : "Neteja camp", // Color Picker ColorAutomatic : "Autom«¢tic", @@ -363,20 +374,20 @@ // Speller Pages Dialog DlgSpellNotInDic : "No «±s al diccionari", -DlgSpellChangeTo : "Canvia a", +DlgSpellChangeTo : "Reempla«®a amb", DlgSpellBtnIgnore : "Ignora", DlgSpellBtnIgnoreAll : "Ignora-les totes", DlgSpellBtnReplace : "Canvia", DlgSpellBtnReplaceAll : "Canvia-les totes", DlgSpellBtnUndo : "Desf«±s", -DlgSpellNoSuggestions : "Cap suger«²ncia", -DlgSpellProgress : "Comprovaci«Ñ ortogr«¢fica en progr«±s", -DlgSpellNoMispell : "Comprovaci«Ñ ortogr«¢fica completada", -DlgSpellNoChanges : "Comprovaci«Ñ ortogr«¢fica: cap paraulada canviada", -DlgSpellOneChange : "Comprovaci«Ñ ortogr«¢fica: una paraula canviada", -DlgSpellManyChanges : "Comprovaci«Ñ ortogr«¢fica %1 paraules canviades", +DlgSpellNoSuggestions : "Cap suggeriment", +DlgSpellProgress : "Verificaci«Ñ ortogr«¢fica en curs...", +DlgSpellNoMispell : "Verificaci«Ñ ortogr«¢fica acabada: no hi ha cap paraula mal escrita", +DlgSpellNoChanges : "Verificaci«Ñ ortogr«¢fica: no s'ha canviat cap paraula", +DlgSpellOneChange : "Verificaci«Ñ ortogr«¢fica: s'ha canviat una paraula", +DlgSpellManyChanges : "Verificaci«Ñ ortogr«¢fica: s'han canviat %1 paraules", -IeSpellDownload : "Comprovaci«Ñ ortogr«¢fica no instal?lada. Voleu descarregar-ho ara?", +IeSpellDownload : "Verificaci«Ñ ortogr«¢fica no instal?lada. Voleu descarregar-ho ara?", // Button Dialog DlgButtonText : "Text (Valor)", @@ -398,7 +409,7 @@ // Select Field Dialog DlgSelectName : "Nom", DlgSelectValue : "Valor", -DlgSelectSize : "Tamany", +DlgSelectSize : "Mida", DlgSelectLines : "L«¿nies", DlgSelectChkMulti : "Permet m«âltiples seleccions", DlgSelectOpAvail : "Opcions disponibles", @@ -419,8 +430,8 @@ // Text Field Dialog DlgTextName : "Nom", DlgTextValue : "Valor", -DlgTextCharWidth : "Amplada de car«¢cter", -DlgTextMaxChars : "M«¢xim de car«¢cters", +DlgTextCharWidth : "Amplada", +DlgTextMaxChars : "Nombre m«¢xim de car«¢cters", DlgTextType : "Tipus", DlgTextTypeText : "Text", DlgTextTypePass : "Contrasenya", @@ -440,20 +451,20 @@ DlgLstTypeNumbers : "N«âmeros (1, 2, 3)", DlgLstTypeLCase : "Lletres min«âscules (a, b, c)", DlgLstTypeUCase : "Lletres maj«âscules (A, B, C)", -DlgLstTypeSRoman : "N«âmeros romans min«âscules (i, ii, iii)", -DlgLstTypeLRoman : "N«âmeros romans maj«âscules (I, II, III)", +DlgLstTypeSRoman : "N«âmeros romans en min«âscules (i, ii, iii)", +DlgLstTypeLRoman : "N«âmeros romans en maj«âscules (I, II, III)", // Document Properties Dialog DlgDocGeneralTab : "General", DlgDocBackTab : "Fons", DlgDocColorsTab : "Colors i marges", -DlgDocMetaTab : "Dades Meta", +DlgDocMetaTab : "Metadades", DlgDocPageTitle : "T«¿tol de la p«¢gina", -DlgDocLangDir : "Direcci«Ñ llenguatge", +DlgDocLangDir : "Direcci«Ñ idioma", DlgDocLangDirLTR : "Esquerra a dreta (LTR)", DlgDocLangDirRTL : "Dreta a esquerra (RTL)", -DlgDocLangCode : "Codi de llenguatge", +DlgDocLangCode : "Codi d'idioma", DlgDocCharSet : "Codificaci«Ñ de conjunt de car«¢cters", DlgDocCharSetCE : "Centreeuropeu", DlgDocCharSetCT : "Xin«²s tradicional (Big5)", @@ -467,7 +478,7 @@ DlgDocCharSetOther : "Una altra codificaci«Ñ de car«¢cters", DlgDocDocType : "Cap«®alera de tipus de document", -DlgDocDocTypeOther : "Altra Cap«®alera de tipus de document", +DlgDocDocTypeOther : "Un altra cap«®alera de tipus de document", DlgDocIncXHTML : "Incloure declaracions XHTML", DlgDocBgColor : "Color de fons", DlgDocBgImage : "URL de la imatge de fons", @@ -490,7 +501,7 @@ // Templates Dialog Templates : "Plantilles", DlgTemplatesTitle : "Contingut plantilles", -DlgTemplatesSelMsg : "Si us plau, seleccioneu la plantilla per obrir en l'editor
      (el contingut actual no ser«¢ enregistrat):", +DlgTemplatesSelMsg : "Si us plau, seleccioneu la plantilla per obrir a l'editor
      (el contingut actual no ser«¢ enregistrat):", DlgTemplatesLoading : "Carregant la llista de plantilles. Si us plau, espereu...", DlgTemplatesNoTpl : "(No hi ha plantilles definides)", DlgTemplatesReplace : "Reempla«®a el contingut actual", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Llic«²ncia", DlgAboutVersion : "versi«Ñ", DlgAboutInfo : "Per a m«±s informaci«Ñ aneu a" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/cs.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/cs.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/cs.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Vlo«öit/zm«µnit odkaz", RemoveLink : "Odstranit odkaz", Anchor : "Vlo«ö«¿t/zm«µnit z«¡lo«öku", +AnchorDelete : "Odstranit kotvu", InsertImageLbl : "Obr«¡zek", InsertImage : "Vlo«öit/zm«µnit obr«¡zek", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Zarovnat do bloku", DecreaseIndent : "Zmen«Þit odsazen«¿", IncreaseIndent : "Zv«µt«Þit odsazen«¿", +Blockquote : "Citace", Undo : "Zp«µt", Redo : "Znovu", NumberedListLbl : "ª­«¿slov«¡n«¿", @@ -103,20 +105,27 @@ ImageButton : "Obr«¡zkov«± tla«­«¿tko", FitWindow : "Maximalizovat velikost editoru", +ShowBlocks : "Uk«¡zat bloky", // Context Menu EditLink : "Zm«µnit odkaz", CellCM : "Bu«Îka", RowCM : "ªÚ«¡dek", ColumnCM : "Sloupec", -InsertRow : "Vlo«öit «Ú«¡dek", -DeleteRows : "Smazat «Ú«¡dek", -InsertColumn : "Vlo«öit sloupec", +InsertRowAfter : "Vlo«öit «Ú«¡dek za", +InsertRowBefore : "Vlo«öit «Ú«¡dek p«Úed", +DeleteRows : "Smazat «Ú«¡dky", +InsertColumnAfter : "Vlo«öit sloupec za", +InsertColumnBefore : "Vlo«öit sloupec p«Úed", DeleteColumns : "Smazat sloupec", -InsertCell : "Vlo«öit bu«Îku", +InsertCellAfter : "Vlo«öit bu«Îku za", +InsertCellBefore : "Vlo«öit bu«Îku p«Úed", DeleteCells : "Smazat bu«Îky", MergeCells : "Slou«­it bu«Îky", -SplitCell : "Rozd«µlit bu«Îku", +MergeRight : "Slou«­it doprava", +MergeDown : "Slou«­it dol«ë", +HorizontalSplitCell : "Rozd«µlit bu«Îky vodorovn«µ", +VerticalSplitCell : "Rozd«µlit bu«Îky svisle", TableDelete : "Smazat tabulku", CellProperties : "Vlastnosti bu«Îky", TableProperties : "Vlastnosti tabulky", @@ -134,7 +143,7 @@ TextareaProp : "Vlastnosti textov«± oblasti", FormProp : "Vlastnosti formul«¡«Úe", -FontFormats : "Norm«¡ln«¿;Form«¡tovan«ò;Adresa;Nadpis 1;Nadpis 2;Nadpis 3;Nadpis 4;Nadpis 5;Nadpis 6", //REVIEW : Check _getfontformat.html +FontFormats : "Norm«¡ln«¿;Naform«¡tov«¡no;Adresa;Nadpis 1;Nadpis 2;Nadpis 3;Nadpis 4;Nadpis 5;Nadpis 6;Norm«¡ln«¿ (DIV)", // Alerts and Messages ProcessingXHTML : "Prob«¿h«¡ zpracov«¡n«¿ XHTML. Pros«¿m «­ekejte...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Vybrat kotvu", DlgLnkAnchorByName : "Podle jm«±na kotvy", DlgLnkAnchorById : "Podle Id objektu", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Ve str«¡nce nen«¿ definov«¡na «ö«¡dn«¡ kotva!)", DlgLnkEMail : "E-Mailov«¡ adresa", DlgLnkEMailSubject : "P«Úedm«µt zpr«¡vy", DlgLnkEMailBody : "T«µlo zpr«¡vy", @@ -262,7 +271,7 @@ DlnLnkMsgNoUrl : "Zadejte pros«¿m URL odkazu", DlnLnkMsgNoEMail : "Zadejte pros«¿m e-mailovou adresu", DlnLnkMsgNoAnchor : "Vyberte pros«¿m kotvu", -DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces", //MISSING +DlnLnkMsgInvPopName : "N«¡zev vyskakovac«¿ho okna mus«¿ za«­«¿nat p«¿smenem a nesm«¿ obsahovat mezery", // Color Dialog DlgColorTitle : "V«òb«µr barvy", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Barva ohrani«­en«¿", DlgCellBtnSelect : "V«òb«µr...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Naj«¿t a nahradit", + // Find Dialog DlgFindTitle : "Hledat", DlgFindFindBtn : "Hledat", @@ -344,10 +356,9 @@ PasteFromWord : "Vlo«öit text z Wordu", DlgPasteMsg2 : "Do n«¡sleduj«¿c«¿ho pole vlo«öte po«öadovan«ò obsah pomoc«¿ kl«¡vesnice (Ctrl+V) a stiskn«µte OK.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "Z d«ëvod«ë nastaven«¿ bezpe«­nosti Va«Þeho prohl«¿«öe«­e nem«ë«öe editor p«Úistupovat p«Ú«¿mo do schr«¡nky. Obsah schr«¡nky pros«¿m vlo«öte znovu do tohoto okna.", DlgPasteIgnoreFont : "Ignorovat p«¿smo", DlgPasteRemoveStyles : "Odstranit styly", -DlgPasteCleanBox : "Vy«­istit", // Color Picker ColorAutomatic : "Automaticky", @@ -381,9 +392,9 @@ // Button Dialog DlgButtonText : "Popisek", DlgButtonType : "Typ", -DlgButtonTypeBtn : "Button", //MISSING -DlgButtonTypeSbm : "Submit", //MISSING -DlgButtonTypeRst : "Reset", //MISSING +DlgButtonTypeBtn : "Tla«­«¿tko", +DlgButtonTypeSbm : "Odeslat", +DlgButtonTypeRst : "Obnovit", // Checkbox and Radio Button Dialogs DlgCheckboxName : "N«¡zev", @@ -432,7 +443,7 @@ // Bulleted List Dialog BulletedListProp : "Vlastnosti odr«¡«öek", NumberedListProp : "Vlastnosti «­«¿slovan«±ho seznamu", -DlgLstStart : "Start", //MISSING +DlgLstStart : "Za«­«¡tek", DlgLstType : "Typ", DlgLstTypeCircle : "Kru«önice", DlgLstTypeDisc : "Kruh", @@ -455,15 +466,15 @@ DlgDocLangDirRTL : "Zprava doleva", DlgDocLangCode : "K«Ñd jazyku", DlgDocCharSet : "Znakov«¡ sada", -DlgDocCharSetCE : "Central European", //MISSING -DlgDocCharSetCT : "Chinese Traditional (Big5)", //MISSING -DlgDocCharSetCR : "Cyrillic", //MISSING -DlgDocCharSetGR : "Greek", //MISSING -DlgDocCharSetJP : "Japanese", //MISSING -DlgDocCharSetKR : "Korean", //MISSING -DlgDocCharSetTR : "Turkish", //MISSING -DlgDocCharSetUN : "Unicode (UTF-8)", //MISSING -DlgDocCharSetWE : "Western European", //MISSING +DlgDocCharSetCE : "St«Úedoevropsk«± jazyky", +DlgDocCharSetCT : "Tradi«­n«¿ «­«¿n«Þtina (Big5)", +DlgDocCharSetCR : "Cyrilice", +DlgDocCharSetGR : "ªÚe«­tina", +DlgDocCharSetJP : "Japon«Þtina", +DlgDocCharSetKR : "Korej«Þtina", +DlgDocCharSetTR : "Ture«­tina", +DlgDocCharSetUN : "Unicode (UTF-8)", +DlgDocCharSetWE : "Z«¡padoevropsk«± jazyky", DlgDocCharSetOther : "Dal«Þ«¿ znakov«¡ sada", DlgDocDocType : "Typ dokumentu", @@ -493,7 +504,7 @@ DlgTemplatesSelMsg : "Pros«¿m zvolte «Þablonu pro otev«Úen«¿ v editoru
      (aktu«¡ln«¿ obsah editoru bude ztracen):", DlgTemplatesLoading : "Nahr«¡v«¡m p«Úeheld «Þablon. Pros«¿m «­ekejte...", DlgTemplatesNoTpl : "(Nen«¿ definov«¡na «ö«¡dn«¡ «Þablona)", -DlgTemplatesReplace : "Replace actual contents", //MISSING +DlgTemplatesReplace : "Nahradit aktu«¡ln«¿ obsah", // About Dialog DlgAboutAboutTab : "O aplikaci", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Licence", DlgAboutVersion : "verze", DlgAboutInfo : "V«¿ce informac«¿ z«¿sk«¡te na" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/da.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/da.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/da.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Inds©Át/rediger hyperlink", RemoveLink : "Fjern hyperlink", Anchor : "Inds©Át/rediger bogm©Árke", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Inds©Át billede", InsertImage : "Inds©Át/rediger billede", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Lige margener", DecreaseIndent : "Formindsk indrykning", IncreaseIndent : "For©Ìg indrykning", +Blockquote : "Blockquote", //MISSING Undo : "Fortryd", Redo : "Annuller fortryd", NumberedListLbl : "Talopstilling", @@ -103,20 +105,27 @@ ImageButton : "Inds©Át billedknap", FitWindow : "Maksimer editor vinduet", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "Rediger hyperlink", CellCM : "Celle", RowCM : "R©Ákke", ColumnCM : "Kolonne", -InsertRow : "Inds©Át r©Ákke", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Slet r©Ákke", -InsertColumn : "Inds©Át kolonne", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "Slet kolonne", -InsertCell : "Inds©Át celle", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "Slet celle", MergeCells : "Flet celler", -SplitCell : "Opdel celle", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Slet tabel", CellProperties : "Egenskaber for celle", TableProperties : "Egenskaber for tabel", @@ -134,7 +143,7 @@ TextareaProp : "Egenskaber for tekstboks", FormProp : "Egenskaber for formular", -FontFormats : "Normal;Formateret;Adresse;Overskrift 1;Overskrift 2;Overskrift 3;Overskrift 4;Overskrift 5;Overskrift 6;Normal (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formateret;Adresse;Overskrift 1;Overskrift 2;Overskrift 3;Overskrift 4;Overskrift 5;Overskrift 6;Normal (DIV)", // Alerts and Messages ProcessingXHTML : "Behandler XHTML...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "V©Álg et anker", DlgLnkAnchorByName : "Efter anker navn", DlgLnkAnchorById : "Efter element Id", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Ingen bogm©Árker dokumentet)", DlgLnkEMail : "E-mailadresse", DlgLnkEMailSubject : "Emne", DlgLnkEMailBody : "Br©Ìdtekst", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Rammefarve", DlgCellBtnSelect : "V©Álg...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "Find", DlgFindFindBtn : "Find", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Ignorer font definitioner", DlgPasteRemoveStyles : "Ignorer typografi", -DlgPasteCleanBox : "Slet indhold", // Color Picker ColorAutomatic : "Automatisk", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Licens", DlgAboutVersion : "version", DlgAboutInfo : "For yderlig information g«© til" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/de.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/de.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/de.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Link einf«ägen/editieren", RemoveLink : "Link entfernen", Anchor : "Anker einf«ägen/editieren", +AnchorDelete : "Anker entfernen", InsertImageLbl : "Bild", InsertImage : "Bild einf«ägen/editieren", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Blocksatz", DecreaseIndent : "Einzug verringern", IncreaseIndent : "Einzug erh«Óhen", +Blockquote : "Zitatblock", Undo : "R«äckg«£ngig", Redo : "Wiederherstellen", NumberedListLbl : "Nummerierte Liste", @@ -85,7 +87,7 @@ TextColor : "Textfarbe", BGColor : "Hintergrundfarbe", Source : "Quellcode", -Find : "Finden", +Find : "Suchen", Replace : "Ersetzen", SpellCheck : "Rechtschreibpr«äfung", UniversalKeyboard : "Universal-Tastatur", @@ -103,38 +105,45 @@ ImageButton : "Bildbutton", FitWindow : "Editor maximieren", +ShowBlocks : "Bl«Ócke anzeigen", // Context Menu EditLink : "Link editieren", CellCM : "Zelle", RowCM : "Zeile", ColumnCM : "Spalte", -InsertRow : "Zeile einf«ägen", +InsertRowAfter : "Zeile unterhalb einf«ägen", +InsertRowBefore : "Zeile oberhalb einf«ägen", DeleteRows : "Zeile entfernen", -InsertColumn : "Spalte einf«ägen", +InsertColumnAfter : "Spalte rechts danach einf«ägen", +InsertColumnBefore : "Spalte links davor einf«ägen", DeleteColumns : "Spalte l«Óschen", -InsertCell : "Zelle einf«ägen", +InsertCellAfter : "Zelle danach einf«ägen", +InsertCellBefore : "Zelle davor einf«ägen", DeleteCells : "Zelle l«Óschen", -MergeCells : "Zellen vereinen", -SplitCell : "Zelle teilen", +MergeCells : "Zellen verbinden", +MergeRight : "nach rechts verbinden", +MergeDown : "nach unten verbinden", +HorizontalSplitCell : "Zelle horizontal teilen", +VerticalSplitCell : "Zelle vertikal teilen", TableDelete : "Tabelle l«Óschen", -CellProperties : "Zellen Eigenschaften", -TableProperties : "Tabellen Eigenschaften", -ImageProperties : "Bild Eigenschaften", -FlashProperties : "Flash Eigenschaften", +CellProperties : "Zellen-Eigenschaften", +TableProperties : "Tabellen-Eigenschaften", +ImageProperties : "Bild-Eigenschaften", +FlashProperties : "Flash-Eigenschaften", -AnchorProp : "Anker Eigenschaften", -ButtonProp : "Button Eigenschaften", -CheckboxProp : "Checkbox Eigenschaften", -HiddenFieldProp : "Verstecktes Feld Eigenschaften", -RadioButtonProp : "Optionsfeld Eigenschaften", -ImageButtonProp : "Bildbutton Eigenschaften", +AnchorProp : "Anker-Eigenschaften", +ButtonProp : "Button-Eigenschaften", +CheckboxProp : "Checkbox-Eigenschaften", +HiddenFieldProp : "Verstecktes Feld-Eigenschaften", +RadioButtonProp : "Optionsfeld-Eigenschaften", +ImageButtonProp : "Bildbutton-Eigenschaften", TextFieldProp : "Textfeld (einzeilig) Eigenschaften", -SelectionFieldProp : "Auswahlfeld Eigenschaften", +SelectionFieldProp : "Auswahlfeld-Eigenschaften", TextareaProp : "Textfeld (mehrzeilig) Eigenschaften", -FormProp : "Formular Eigenschaften", +FormProp : "Formular-Eigenschaften", -FontFormats : "Normal;Formatiert;Addresse;ªäberschrift 1;ªäberschrift 2;ªäberschrift 3;ªäberschrift 4;ªäberschrift 5;ªäberschrift 6;Normal (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatiert;Addresse;ªäberschrift 1;ªäberschrift 2;ªäberschrift 3;ªäberschrift 4;ªäberschrift 5;ªäberschrift 6;Normal (DIV)", // Alerts and Messages ProcessingXHTML : "Bearbeite XHTML. Bitte warten...", @@ -160,24 +169,24 @@ DlgAlertUrl : "Bitte tragen Sie die URL ein", // General Dialogs Labels -DlgGenNotSet : "< nichts >", +DlgGenNotSet : "", DlgGenId : "ID", DlgGenLangDir : "Schreibrichtung", DlgGenLangDirLtr : "Links nach Rechts (LTR)", DlgGenLangDirRtl : "Rechts nach Links (RTL)", DlgGenLangCode : "Sprachenk«ärzel", -DlgGenAccessKey : "Schl«ässel", +DlgGenAccessKey : "Zugriffstaste", DlgGenName : "Name", -DlgGenTabIndex : "Tab Index", +DlgGenTabIndex : "Tab-Index", DlgGenLongDescr : "Langform URL", DlgGenClass : "Stylesheet Klasse", DlgGenTitle : "Titel Beschreibung", -DlgGenContType : "Content Beschreibung", +DlgGenContType : "Inhaltstyp", DlgGenLinkCharset : "Ziel-Zeichensatz", DlgGenStyle : "Style", // Image Dialog -DlgImgTitle : "Bild Eigenschaften", +DlgImgTitle : "Bild-Eigenschaften", DlgImgInfoTab : "Bild-Info", DlgImgBtnUpload : "Zum Server senden", DlgImgURL : "Bildauswahl", @@ -205,7 +214,7 @@ DlgImgLinkTab : "Link", // Flash Dialog -DlgFlashTitle : "Flash Eigenschaften", +DlgFlashTitle : "Flash-Eigenschaften", DlgFlashChkPlay : "autom. Abspielen", DlgFlashChkLoop : "Endlosschleife", DlgFlashChkMenu : "Flash-Men«ä aktivieren", @@ -216,7 +225,7 @@ // Link Dialog DlgLnkWindowTitle : "Link", -DlgLnkInfoTab : "Link Info", +DlgLnkInfoTab : "Link-Info", DlgLnkTargetTab : "Zielseite", DlgLnkType : "Link-Typ", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Anker ausw«£hlen", DlgLnkAnchorByName : "nach Anker Name", DlgLnkAnchorById : "nach Element Id", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(keine Anker im Dokument vorhanden)", DlgLnkEMail : "E-Mail Addresse", DlgLnkEMailSubject : "Betreffzeile", DlgLnkEMailBody : "Nachrichtentext", @@ -243,9 +252,9 @@ DlgLnkTargetParent : "Oberes Fenster (_parent)", DlgLnkTargetSelf : "Gleiches Fenster (_self)", DlgLnkTargetTop : "Oberstes Fenster (_top)", -DlgLnkTargetFrameName : "Ziel-Fenster Name", -DlgLnkPopWinName : "Pop-up Fenster Name", -DlgLnkPopWinFeat : "Pop-up Fenster Eigenschaften", +DlgLnkTargetFrameName : "Ziel-Fenster-Name", +DlgLnkPopWinName : "Pop-up Fenster-Name", +DlgLnkPopWinFeat : "Pop-up Fenster-Eigenschaften", DlgLnkPopResize : "Vergr«Ó©Îerbar", DlgLnkPopLocation : "Adress-Leiste", DlgLnkPopMenu : "Men«ä-Leiste", @@ -277,12 +286,12 @@ DlgSpecialCharTitle : "Sonderzeichen ausw«£hlen", // Table Dialog -DlgTableTitle : "Tabellen Eigenschaften", +DlgTableTitle : "Tabellen-Eigenschaften", DlgTableRows : "Zeile", DlgTableColumns : "Spalte", DlgTableBorder : "Rahmen", DlgTableAlign : "Ausrichtung", -DlgTableAlignNotSet : "", +DlgTableAlignNotSet : "", DlgTableAlignLeft : "Links", DlgTableAlignCenter : "Zentriert", DlgTableAlignRight : "Rechts", @@ -302,16 +311,16 @@ DlgCellWidthPc : "%", DlgCellHeight : "H«Óhe", DlgCellWordWrap : "Umbruch", -DlgCellWordWrapNotSet : "", +DlgCellWordWrapNotSet : "", DlgCellWordWrapYes : "Ja", DlgCellWordWrapNo : "Nein", DlgCellHorAlign : "Horizontale Ausrichtung", -DlgCellHorAlignNotSet : "", +DlgCellHorAlignNotSet : "", DlgCellHorAlignLeft : "Links", DlgCellHorAlignCenter : "Zentriert", DlgCellHorAlignRight: "Rechts", DlgCellVerAlign : "Vertikale Ausrichtung", -DlgCellVerAlignNotSet : "", +DlgCellVerAlignNotSet : "", DlgCellVerAlignTop : "Oben", DlgCellVerAlignMiddle : "Mitte", DlgCellVerAlignBottom : "Unten", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Rahmenfarbe", DlgCellBtnSelect : "Auswahl...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Suchen und Ersetzen", + // Find Dialog DlgFindTitle : "Finden", DlgFindFindBtn : "Finden", @@ -343,21 +355,20 @@ PasteAsText : "Als Text einf«ägen", PasteFromWord : "Aus Word einf«ägen", -DlgPasteMsg2 : "Bitte f«ägen Sie den Text in der folgenden Box «äber die Tastatur (mit Ctrl+V) ein und best«£tigen Sie mit OK.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteMsg2 : "Bitte f«ägen Sie den Text in der folgenden Box «äber die Tastatur (mit Strg+V) ein und best«£tigen Sie mit OK.", +DlgPasteSec : "Aufgrund von Sicherheitsbeschr«£nkungen Ihres Browsers kann der Editor nicht direkt auf die Zwischenablage zugreifen. Bitte f«ägen Sie den Inhalt erneut in diesem Fenster ein.", DlgPasteIgnoreFont : "Ignoriere Schriftart-Definitionen", DlgPasteRemoveStyles : "Entferne Style-Definitionen", -DlgPasteCleanBox : "Inhalt aufr«£umen", // Color Picker ColorAutomatic : "Automatisch", ColorMoreColors : "Weitere Farben...", // Document Properties -DocProps : "Dokument Eigenschaften", +DocProps : "Dokument-Eigenschaften", // Anchor Dialog -DlgAnchorTitle : "Anker Eigenschaften", +DlgAnchorTitle : "Anker-Eigenschaften", DlgAnchorName : "Anker Name", DlgAnchorErrorName : "Bitte geben Sie den Namen des Ankers ein", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Lizenz", DlgAboutVersion : "Version", DlgAboutInfo : "F«är weitere Informationen siehe" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/el.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/el.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/el.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "¦¥¦É¦Ò¦Á¦Ã¦Ø¦Ã¦ó/¦¬¦Å¦Ó¦Á¦Â¦Ï¦Ë¦ó ¦²¦Ô¦Í¦Ä¦ò¦Ò¦Ì¦Ï¦Ô (Link)", RemoveLink : "¦¡¦Õ¦Á¦ô¦Ñ¦Å¦Ò¦Ç ¦²¦Ô¦Í¦Ä¦ò¦Ò¦Ì¦Ï¦Ô (Link)", Anchor : "¦¥¦É¦Ò¦Á¦Ã¦Ø¦Ã¦ó/¦Å¦Ð¦Å¦Î¦Å¦Ñ¦Ã¦Á¦Ò¦ô¦Á Anchor", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "¦¥¦É¦Ê¦÷¦Í¦Á", InsertImage : "¦¥¦É¦Ò¦Á¦Ã¦Ø¦Ã¦ó/¦¬¦Å¦Ó¦Á¦Â¦Ï¦Ë¦ó ¦¥¦É¦Ê¦÷¦Í¦Á¦ø", InsertFlashLbl : "¦¥¦É¦Ò¦Á¦Ã¦Ø¦Ã¦ó Flash", @@ -70,6 +71,7 @@ BlockJustify : "¦°¦Ë¦ó¦Ñ¦Ç¦ø ¦²¦Ó¦Ï¦ô¦Ö¦É¦Ò¦Ç (Block)", DecreaseIndent : "¦¬¦Å¦ô¦Ø¦Ò¦Ç ¦¥¦Ò¦Ï¦Ö¦ó¦ø", IncreaseIndent : "¦¡¦ù¦Î¦Ç¦Ò¦Ç ¦¥¦Ò¦Ï¦Ö¦ó¦ø", +Blockquote : "Blockquote", //MISSING Undo : "¦¡¦Í¦Á¦ô¦Ñ¦Å¦Ò¦Ç", Redo : "¦¥¦Ð¦Á¦Í¦Á¦Õ¦Ï¦Ñ¦ñ", NumberedListLbl : "¦«¦ô¦Ò¦Ó¦Á ¦Ì¦Å ¦¡¦Ñ¦É¦È¦Ì¦Ï¦ù¦ø", @@ -103,20 +105,27 @@ ImageButton : "¦ª¦Ï¦Ô¦Ì¦Ð¦ô ¦Å¦É¦Ê¦÷¦Í¦Á¦ø", FitWindow : "¦¬¦Å¦Ã¦É¦Ò¦Ó¦Ï¦Ð¦Ï¦ô¦Ç¦Ò¦Ç ¦Ð¦Ñ¦Ï¦Ã¦Ñ¦ñ¦Ì¦Ì¦Á¦Ó¦Ï¦ø", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "¦¬¦Å¦Ó¦Á¦Â¦Ï¦Ë¦ó ¦²¦Ô¦Í¦Ä¦ò¦Ò¦Ì¦Ï¦Ô (Link)", CellCM : "¦ª¦Å¦Ë¦ô", RowCM : "¦²¦Å¦É¦Ñ¦ñ", ColumnCM : "¦²¦Ó¦ó¦Ë¦Ç", -InsertRow : "¦¥¦É¦Ò¦Á¦Ã¦Ø¦Ã¦ó ¦£¦Ñ¦Á¦Ì¦Ì¦ó¦ø", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "¦¤¦É¦Á¦Ã¦Ñ¦Á¦Õ¦ó ¦£¦Ñ¦Á¦Ì¦Ì¦ü¦Í", -InsertColumn : "¦¥¦É¦Ò¦Á¦Ã¦Ø¦Ã¦ó ¦ª¦Ï¦Ë¦ü¦Í¦Á¦ø", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "¦¤¦É¦Á¦Ã¦Ñ¦Á¦Õ¦ó ¦ª¦Ï¦Ë¦Ø¦Í¦ü¦Í", -InsertCell : "¦¥¦É¦Ò¦Á¦Ã¦Ø¦Ã¦ó ¦ª¦Å¦Ë¦É¦Ï¦ù", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "¦¤¦É¦Á¦Ã¦Ñ¦Á¦Õ¦ó ¦ª¦Å¦Ë¦É¦ü¦Í", MergeCells : "¦¥¦Í¦Ï¦Ð¦Ï¦ô¦Ç¦Ò¦Ç ¦ª¦Å¦Ë¦É¦ü¦Í", -SplitCell : "¦¤¦É¦Á¦Ö¦Ø¦Ñ¦É¦Ò¦Ì¦÷¦ø ¦ª¦Å¦Ë¦É¦Ï¦ù", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "¦¤¦É¦Á¦Ã¦Ñ¦Á¦Õ¦ó ¦Ð¦ô¦Í¦Á¦Ê¦Á", CellProperties : "¦©¦Ä¦É¦÷¦Ó¦Ç¦Ó¦Å¦ø ¦ª¦Å¦Ë¦É¦Ï¦ù", TableProperties : "¦©¦Ä¦É¦÷¦Ó¦Ç¦Ó¦Å¦ø ¦°¦ô¦Í¦Á¦Ê¦Á", @@ -134,7 +143,7 @@ TextareaProp : "¦©¦Ä¦É¦÷¦Ó¦Ç¦Ó¦Å¦ø ¦Ð¦Å¦Ñ¦É¦Ï¦Ö¦ó¦ø ¦Ê¦Å¦É¦Ì¦ò¦Í¦Ï¦Ô", FormProp : "¦©¦Ä¦É¦÷¦Ó¦Ç¦Ó¦Å¦ø ¦Õ¦÷¦Ñ¦Ì¦Á¦ø", -FontFormats : "¦ª¦Á¦Í¦Ï¦Í¦É¦Ê¦÷;¦¬¦Ï¦Ñ¦Õ¦Ï¦Ð¦Ï¦É¦Ç¦Ì¦ò¦Í¦Ï;¦¤¦É¦Å¦ù¦È¦Ô¦Í¦Ò¦Ç;¦¥¦Ð¦É¦Ê¦Å¦Õ¦Á¦Ë¦ô¦Ä¦Á 1;¦¥¦Ð¦É¦Ê¦Å¦Õ¦Á¦Ë¦ô¦Ä¦Á 2;¦¥¦Ð¦É¦Ê¦Å¦Õ¦Á¦Ë¦ô¦Ä¦Á 3;¦¥¦Ð¦É¦Ê¦Å¦Õ¦Á¦Ë¦ô¦Ä¦Á 4;¦¥¦Ð¦É¦Ê¦Å¦Õ¦Á¦Ë¦ô¦Ä¦Á 5;¦¥¦Ð¦É¦Ê¦Å¦Õ¦Á¦Ë¦ô¦Ä¦Á 6", //REVIEW : Check _getfontformat.html +FontFormats : "¦ª¦Á¦Í¦Ï¦Í¦É¦Ê¦÷;¦¬¦Ï¦Ñ¦Õ¦Ï¦Ð¦Ï¦É¦Ç¦Ì¦ò¦Í¦Ï;¦¤¦É¦Å¦ù¦È¦Ô¦Í¦Ò¦Ç;¦¥¦Ð¦É¦Ê¦Å¦Õ¦Á¦Ë¦ô¦Ä¦Á 1;¦¥¦Ð¦É¦Ê¦Å¦Õ¦Á¦Ë¦ô¦Ä¦Á 2;¦¥¦Ð¦É¦Ê¦Å¦Õ¦Á¦Ë¦ô¦Ä¦Á 3;¦¥¦Ð¦É¦Ê¦Å¦Õ¦Á¦Ë¦ô¦Ä¦Á 4;¦¥¦Ð¦É¦Ê¦Å¦Õ¦Á¦Ë¦ô¦Ä¦Á 5;¦¥¦Ð¦É¦Ê¦Å¦Õ¦Á¦Ë¦ô¦Ä¦Á 6", // Alerts and Messages ProcessingXHTML : "¦¥¦Ð¦Å¦Î¦Å¦Ñ¦Ã¦Á¦Ò¦ô¦Á XHTML. ¦°¦Á¦Ñ¦Á¦Ê¦Á¦Ë¦ü ¦Ð¦Å¦Ñ¦É¦Ì¦ò¦Í¦Å¦Ó¦Å...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "¦¥¦Ð¦É¦Ë¦ò¦Î¦Ó¦Å ¦Ì¦É¦Á ¦ñ¦Ã¦Ê¦Ô¦Ñ¦Á", DlgLnkAnchorByName : "¦¢¦ñ¦Ò¦Å¦É ¦Ó¦Ï¦Ô ¦¯¦Í¦÷¦Ì¦Á¦Ó¦Ï¦ø (Name) ¦Ó¦Ç¦ø ¦ñ¦Ã¦Ê¦Ô¦Ñ¦Á¦ø", DlgLnkAnchorById : "¦¢¦ñ¦Ò¦Å¦É ¦Ó¦Ï¦Ô Element Id", -DlgLnkNoAnchors : "<¦¤¦Å¦Í ¦Ô¦Ð¦ñ¦Ñ¦Ö¦Ï¦Ô¦Í ¦ñ¦Ã¦Ê¦Ô¦Ñ¦Å¦ø ¦Ò¦Ó¦Ï ¦Ê¦Å¦ô¦Ì¦Å¦Í¦Ï>", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(¦¤¦Å¦Í ¦Ô¦Ð¦ñ¦Ñ¦Ö¦Ï¦Ô¦Í ¦ñ¦Ã¦Ê¦Ô¦Ñ¦Å¦ø ¦Ò¦Ó¦Ï ¦Ê¦Å¦ô¦Ì¦Å¦Í¦Ï)", DlgLnkEMail : "¦¤¦É¦Å¦ù¦È¦Ô¦Í¦Ò¦Ç ¦§¦Ë¦Å¦Ê¦Ó¦Ñ¦Ï¦Í¦É¦Ê¦Ï¦ù ¦³¦Á¦Ö¦Ô¦Ä¦Ñ¦Ï¦Ì¦Å¦ô¦Ï¦Ô", DlgLnkEMailSubject : "¦¨¦ò¦Ì¦Á ¦¬¦Ç¦Í¦ù¦Ì¦Á¦Ó¦Ï¦ø", DlgLnkEMailBody : "¦ª¦Å¦ô¦Ì¦Å¦Í¦Ï ¦¬¦Ç¦Í¦ù¦Ì¦Á¦Ó¦Ï¦ø", @@ -322,6 +331,9 @@ DlgCellBorderColor : "¦¶¦Ñ¦ü¦Ì¦Á ¦°¦Å¦Ñ¦É¦È¦Ø¦Ñ¦ô¦Ï¦Ô", DlgCellBtnSelect : "¦¥¦Ð¦É¦Ë¦Ï¦Ã¦ó...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "¦¡¦Í¦Á¦Æ¦ó¦Ó¦Ç¦Ò¦Ç", DlgFindFindBtn : "¦¡¦Í¦Á¦Æ¦ó¦Ó¦Ç¦Ò¦Ç", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "¦¡¦Ã¦Í¦÷¦Ç¦Ò¦Ç ¦Ð¦Ñ¦Ï¦Ä¦É¦Á¦Ã¦Ñ¦Á¦Õ¦ü¦Í ¦Ã¦Ñ¦Á¦Ì¦Ì¦Á¦Ó¦Ï¦Ò¦Å¦É¦Ñ¦ñ¦ø", DlgPasteRemoveStyles : "¦¡¦Õ¦Á¦ô¦Ñ¦Å¦Ò¦Ç ¦Ð¦Ñ¦Ï¦Ä¦É¦Á¦Ã¦Ñ¦Á¦Õ¦ü¦Í ¦Ò¦Ó¦ù¦Ë", -DlgPasteCleanBox : "¦ª¦Ï¦Ô¦Ó¦ô ¦Å¦Ê¦Á¦È¦ñ¦Ñ¦É¦Ò¦Ç¦ø", // Color Picker ColorAutomatic : "¦¡¦Ô¦Ó¦÷¦Ì¦Á¦Ó¦Ï", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "¦á¦Ä¦Å¦É¦Á", DlgAboutVersion : "¦ò¦Ê¦Ä¦Ï¦Ò¦Ç", DlgAboutInfo : "¦£¦É¦Á ¦Ð¦Å¦Ñ¦É¦Ò¦Ò¦÷¦Ó¦Å¦Ñ¦Å¦ø ¦Ð¦Ë¦Ç¦Ñ¦Ï¦Õ¦Ï¦Ñ¦ô¦Å¦ø" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en-au.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en-au.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en-au.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Insert/Edit Link", RemoveLink : "Remove Link", Anchor : "Insert/Edit Anchor", +AnchorDelete : "Remove Anchor", InsertImageLbl : "Image", InsertImage : "Insert/Edit Image", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Block Justify", DecreaseIndent : "Decrease Indent", IncreaseIndent : "Increase Indent", +Blockquote : "Blockquote", Undo : "Undo", Redo : "Redo", NumberedListLbl : "Numbered List", @@ -103,20 +105,27 @@ ImageButton : "Image Button", FitWindow : "Maximize the editor size", +ShowBlocks : "Show Blocks", // Context Menu EditLink : "Edit Link", CellCM : "Cell", RowCM : "Row", ColumnCM : "Column", -InsertRow : "Insert Row", +InsertRowAfter : "Insert Row After", +InsertRowBefore : "Insert Row Before", DeleteRows : "Delete Rows", -InsertColumn : "Insert Column", +InsertColumnAfter : "Insert Column After", +InsertColumnBefore : "Insert Column Before", DeleteColumns : "Delete Columns", -InsertCell : "Insert Cell", +InsertCellAfter : "Insert Cell After", +InsertCellBefore : "Insert Cell Before", DeleteCells : "Delete Cells", MergeCells : "Merge Cells", -SplitCell : "Split Cell", +MergeRight : "Merge Right", +MergeDown : "Merge Down", +HorizontalSplitCell : "Split Cell Horizontally", +VerticalSplitCell : "Split Cell Vertically", TableDelete : "Delete Table", CellProperties : "Cell Properties", TableProperties : "Table Properties", @@ -134,7 +143,7 @@ TextareaProp : "Textarea Properties", FormProp : "Form Properties", -FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", // Alerts and Messages ProcessingXHTML : "Processing XHTML. Please wait...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Select an Anchor", DlgLnkAnchorByName : "By Anchor Name", DlgLnkAnchorById : "By Element Id", -DlgLnkNoAnchors : "(No anchors available in the document)", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(No anchors available in the document)", DlgLnkEMail : "E-Mail Address", DlgLnkEMailSubject : "Message Subject", DlgLnkEMailBody : "Message Body", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Border Colour", DlgCellBtnSelect : "Select...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", + // Find Dialog DlgFindTitle : "Find", DlgFindFindBtn : "Find", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", DlgPasteIgnoreFont : "Ignore Font Face definitions", DlgPasteRemoveStyles : "Remove Styles definitions", -DlgPasteCleanBox : "Clean Up Box", // Color Picker ColorAutomatic : "Automatic", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "License", DlgAboutVersion : "version", DlgAboutInfo : "For further information go to" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en-ca.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en-ca.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en-ca.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Insert/Edit Link", RemoveLink : "Remove Link", Anchor : "Insert/Edit Anchor", +AnchorDelete : "Remove Anchor", InsertImageLbl : "Image", InsertImage : "Insert/Edit Image", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Block Justify", DecreaseIndent : "Decrease Indent", IncreaseIndent : "Increase Indent", +Blockquote : "Blockquote", Undo : "Undo", Redo : "Redo", NumberedListLbl : "Numbered List", @@ -103,20 +105,27 @@ ImageButton : "Image Button", FitWindow : "Maximize the editor size", +ShowBlocks : "Show Blocks", // Context Menu EditLink : "Edit Link", CellCM : "Cell", RowCM : "Row", ColumnCM : "Column", -InsertRow : "Insert Row", +InsertRowAfter : "Insert Row After", +InsertRowBefore : "Insert Row Before", DeleteRows : "Delete Rows", -InsertColumn : "Insert Column", +InsertColumnAfter : "Insert Column After", +InsertColumnBefore : "Insert Column Before", DeleteColumns : "Delete Columns", -InsertCell : "Insert Cell", +InsertCellAfter : "Insert Cell After", +InsertCellBefore : "Insert Cell Before", DeleteCells : "Delete Cells", MergeCells : "Merge Cells", -SplitCell : "Split Cell", +MergeRight : "Merge Right", +MergeDown : "Merge Down", +HorizontalSplitCell : "Split Cell Horizontally", +VerticalSplitCell : "Split Cell Vertically", TableDelete : "Delete Table", CellProperties : "Cell Properties", TableProperties : "Table Properties", @@ -134,7 +143,7 @@ TextareaProp : "Textarea Properties", FormProp : "Form Properties", -FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", // Alerts and Messages ProcessingXHTML : "Processing XHTML. Please wait...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Select an Anchor", DlgLnkAnchorByName : "By Anchor Name", DlgLnkAnchorById : "By Element Id", -DlgLnkNoAnchors : "(No anchors available in the document)", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(No anchors available in the document)", DlgLnkEMail : "E-Mail Address", DlgLnkEMailSubject : "Message Subject", DlgLnkEMailBody : "Message Body", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Border Colour", DlgCellBtnSelect : "Select...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", + // Find Dialog DlgFindTitle : "Find", DlgFindFindBtn : "Find", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", DlgPasteIgnoreFont : "Ignore Font Face definitions", DlgPasteRemoveStyles : "Remove Styles definitions", -DlgPasteCleanBox : "Clean Up Box", // Color Picker ColorAutomatic : "Automatic", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "License", DlgAboutVersion : "version", DlgAboutInfo : "For further information go to" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en-uk.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en-uk.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en-uk.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Insert/Edit Link", RemoveLink : "Remove Link", Anchor : "Insert/Edit Anchor", +AnchorDelete : "Remove Anchor", InsertImageLbl : "Image", InsertImage : "Insert/Edit Image", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Block Justify", DecreaseIndent : "Decrease Indent", IncreaseIndent : "Increase Indent", +Blockquote : "Blockquote", Undo : "Undo", Redo : "Redo", NumberedListLbl : "Numbered List", @@ -103,20 +105,27 @@ ImageButton : "Image Button", FitWindow : "Maximize the editor size", +ShowBlocks : "Show Blocks", // Context Menu EditLink : "Edit Link", CellCM : "Cell", RowCM : "Row", ColumnCM : "Column", -InsertRow : "Insert Row", +InsertRowAfter : "Insert Row After", +InsertRowBefore : "Insert Row Before", DeleteRows : "Delete Rows", -InsertColumn : "Insert Column", +InsertColumnAfter : "Insert Column After", +InsertColumnBefore : "Insert Column Before", DeleteColumns : "Delete Columns", -InsertCell : "Insert Cell", +InsertCellAfter : "Insert Cell After", +InsertCellBefore : "Insert Cell Before", DeleteCells : "Delete Cells", MergeCells : "Merge Cells", -SplitCell : "Split Cell", +MergeRight : "Merge Right", +MergeDown : "Merge Down", +HorizontalSplitCell : "Split Cell Horizontally", +VerticalSplitCell : "Split Cell Vertically", TableDelete : "Delete Table", CellProperties : "Cell Properties", TableProperties : "Table Properties", @@ -134,7 +143,7 @@ TextareaProp : "Textarea Properties", FormProp : "Form Properties", -FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", // Alerts and Messages ProcessingXHTML : "Processing XHTML. Please wait...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Select an Anchor", DlgLnkAnchorByName : "By Anchor Name", DlgLnkAnchorById : "By Element Id", -DlgLnkNoAnchors : "(No anchors available in the document)", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(No anchors available in the document)", DlgLnkEMail : "E-Mail Address", DlgLnkEMailSubject : "Message Subject", DlgLnkEMailBody : "Message Body", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Border Colour", DlgCellBtnSelect : "Select...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", + // Find Dialog DlgFindTitle : "Find", DlgFindFindBtn : "Find", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", DlgPasteIgnoreFont : "Ignore Font Face definitions", DlgPasteRemoveStyles : "Remove Styles definitions", -DlgPasteCleanBox : "Clean Up Box", // Color Picker ColorAutomatic : "Automatic", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "License", DlgAboutVersion : "version", DlgAboutInfo : "For further information go to" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/en.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Insert/Edit Link", RemoveLink : "Remove Link", Anchor : "Insert/Edit Anchor", +AnchorDelete : "Remove Anchor", InsertImageLbl : "Image", InsertImage : "Insert/Edit Image", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Block Justify", DecreaseIndent : "Decrease Indent", IncreaseIndent : "Increase Indent", +Blockquote : "Blockquote", Undo : "Undo", Redo : "Redo", NumberedListLbl : "Numbered List", @@ -103,20 +105,27 @@ ImageButton : "Image Button", FitWindow : "Maximize the editor size", +ShowBlocks : "Show Blocks", // Context Menu EditLink : "Edit Link", CellCM : "Cell", RowCM : "Row", ColumnCM : "Column", -InsertRow : "Insert Row", +InsertRowAfter : "Insert Row After", +InsertRowBefore : "Insert Row Before", DeleteRows : "Delete Rows", -InsertColumn : "Insert Column", +InsertColumnAfter : "Insert Column After", +InsertColumnBefore : "Insert Column Before", DeleteColumns : "Delete Columns", -InsertCell : "Insert Cell", +InsertCellAfter : "Insert Cell After", +InsertCellBefore : "Insert Cell Before", DeleteCells : "Delete Cells", MergeCells : "Merge Cells", -SplitCell : "Split Cell", +MergeRight : "Merge Right", +MergeDown : "Merge Down", +HorizontalSplitCell : "Split Cell Horizontally", +VerticalSplitCell : "Split Cell Vertically", TableDelete : "Delete Table", CellProperties : "Cell Properties", TableProperties : "Table Properties", @@ -134,7 +143,7 @@ TextareaProp : "Textarea Properties", FormProp : "Form Properties", -FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", // Alerts and Messages ProcessingXHTML : "Processing XHTML. Please wait...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Select an Anchor", DlgLnkAnchorByName : "By Anchor Name", DlgLnkAnchorById : "By Element Id", -DlgLnkNoAnchors : "(No anchors available in the document)", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(No anchors available in the document)", DlgLnkEMail : "E-Mail Address", DlgLnkEMailSubject : "Message Subject", DlgLnkEMailBody : "Message Body", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Border Color", DlgCellBtnSelect : "Select...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", + // Find Dialog DlgFindTitle : "Find", DlgFindFindBtn : "Find", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", DlgPasteIgnoreFont : "Ignore Font Face definitions", DlgPasteRemoveStyles : "Remove Styles definitions", -DlgPasteCleanBox : "Clean Up Box", // Color Picker ColorAutomatic : "Automatic", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "License", DlgAboutVersion : "version", DlgAboutInfo : "For further information go to" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/eo.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/eo.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/eo.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Enmeti/ªÝan«ºi Ligilon", RemoveLink : "Forigi Ligilon", Anchor : "Enmeti/ªÝan«ºi Ankron", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Bildo", InsertImage : "Enmeti/ªÝan«ºi Bildon", InsertFlashLbl : "Flash", //MISSING @@ -70,6 +71,7 @@ BlockJustify : "ªºisrandigi Amba«æflanke", DecreaseIndent : "Malpligrandigi Krommar«ºenon", IncreaseIndent : "Pligrandigi Krommar«ºenon", +Blockquote : "Blockquote", //MISSING Undo : "Malfari", Redo : "Refari", NumberedListLbl : "Numera Listo", @@ -103,20 +105,27 @@ ImageButton : "Bildbutono", FitWindow : "Maximize the editor size", //MISSING +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "Modifier Ligilon", CellCM : "Cell", //MISSING RowCM : "Row", //MISSING ColumnCM : "Column", //MISSING -InsertRow : "Enmeti Linion", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Forigi Liniojn", -InsertColumn : "Enmeti Kolumnon", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "Forigi Kolumnojn", -InsertCell : "Enmeti ª¬elon", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "Forigi ª¬elojn", MergeCells : "Kunfandi ª¬elojn", -SplitCell : "Dividi ª¬elojn", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Delete Table", //MISSING CellProperties : "Atributoj de ª¬elo", TableProperties : "Atributoj de Tabelo", @@ -134,7 +143,7 @@ TextareaProp : "Atributoj de Teksta Areo", FormProp : "Formularaj Atributoj", -FontFormats : "Normala;Formatita;Adreso;Titolo 1;Titolo 2;Titolo 3;Titolo 4;Titolo 5;Titolo 6;Paragrafo (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normala;Formatita;Adreso;Titolo 1;Titolo 2;Titolo 3;Titolo 4;Titolo 5;Titolo 6;Paragrafo (DIV)", // Alerts and Messages ProcessingXHTML : "Traktado de XHTML. Bonvolu pacienci...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Elekti Ankron", DlgLnkAnchorByName : "Per Ankronomo", DlgLnkAnchorById : "Per Elementidentigilo", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "", DlgLnkEMail : "Retadreso", DlgLnkEMailSubject : "Temlinio", DlgLnkEMailBody : "Mesa«ºa korpo", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Bordero", DlgCellBtnSelect : "Elekti...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "Ser«¬i", DlgFindFindBtn : "Ser«¬i", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Ignore Font Face definitions", //MISSING DlgPasteRemoveStyles : "Remove Styles definitions", //MISSING -DlgPasteCleanBox : "Clean Up Box", //MISSING // Color Picker ColorAutomatic : "A«ætomata", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "License", //MISSING DlgAboutVersion : "versio", DlgAboutInfo : "Por pli da informoj, vizitu" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/es.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/es.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/es.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Insertar/Editar V«¿nculo", RemoveLink : "Eliminar V«¿nculo", Anchor : "Referencia", +AnchorDelete : "Eliminar Referencia", InsertImageLbl : "Imagen", InsertImage : "Insertar/Editar Imagen", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Justificado", DecreaseIndent : "Disminuir Sangr«¿a", IncreaseIndent : "Aumentar Sangr«¿a", +Blockquote : "Cita", Undo : "Deshacer", Redo : "Rehacer", NumberedListLbl : "Numeraci«Ñn", @@ -103,20 +105,27 @@ ImageButton : "Bot«Ñn Imagen", FitWindow : "Maximizar el tama«Ðo del editor", +ShowBlocks : "Mostrar bloques", // Context Menu EditLink : "Editar V«¿nculo", CellCM : "Celda", RowCM : "Fila", ColumnCM : "Columna", -InsertRow : "Insertar Fila", +InsertRowAfter : "Insertar fila en la parte inferior", +InsertRowBefore : "Insertar fila en la parte superior", DeleteRows : "Eliminar Filas", -InsertColumn : "Insertar Columna", +InsertColumnAfter : "Insertar columna a la derecha", +InsertColumnBefore : "Insertar columna a la izquierda", DeleteColumns : "Eliminar Columnas", -InsertCell : "Insertar Celda", +InsertCellAfter : "Insertar celda a la derecha", +InsertCellBefore : "Insertar celda a la izquierda", DeleteCells : "Eliminar Celdas", MergeCells : "Combinar Celdas", -SplitCell : "Dividir Celda", +MergeRight : "Combinar a la derecha", +MergeDown : "Combinar hacia abajo", +HorizontalSplitCell : "Dividir la celda horizontalmente", +VerticalSplitCell : "Dividir la celda verticalmente", TableDelete : "Eliminar Tabla", CellProperties : "Propiedades de Celda", TableProperties : "Propiedades de Tabla", @@ -134,7 +143,7 @@ TextareaProp : "Propiedades de Area de Texto", FormProp : "Propiedades de Formulario", -FontFormats : "Normal;Con formato;Direcci«Ñn;Encabezado 1;Encabezado 2;Encabezado 3;Encabezado 4;Encabezado 5;Encabezado 6;Normal (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Con formato;Direcci«Ñn;Encabezado 1;Encabezado 2;Encabezado 3;Encabezado 4;Encabezado 5;Encabezado 6;Normal (DIV)", // Alerts and Messages ProcessingXHTML : "Procesando XHTML. Por favor, espere...", @@ -162,10 +171,10 @@ // General Dialogs Labels DlgGenNotSet : "", DlgGenId : "Id", -DlgGenLangDir : "Orientaci«Ñn de idioma", +DlgGenLangDir : "Orientaci«Ñn", DlgGenLangDirLtr : "Izquierda a Derecha (LTR)", DlgGenLangDirRtl : "Derecha a Izquierda (RTL)", -DlgGenLangCode : "C«Ñdigo de idioma", +DlgGenLangCode : "C«Ñd. de idioma", DlgGenAccessKey : "Clave de Acceso", DlgGenName : "Nombre", DlgGenTabIndex : "Indice de tabulaci«Ñn", @@ -201,7 +210,7 @@ DlgImgAlignTextTop : "Tope del texto", DlgImgAlignTop : "Tope", DlgImgPreview : "Vista Previa", -DlgImgAlertUrl : "Por favor tipee el URL de la imagen", +DlgImgAlertUrl : "Por favor escriba la URL de la imagen", DlgImgLinkTab : "V«¿nculo", // Flash Dialog @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Seleccionar una referencia", DlgLnkAnchorByName : "Por Nombre de Referencia", DlgLnkAnchorById : "Por ID de elemento", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(No hay referencias disponibles en el documento)", DlgLnkEMail : "Direcci«Ñn de E-Mail", DlgLnkEMailSubject : "T«¿tulo del Mensaje", DlgLnkEMailBody : "Cuerpo del Mensaje", @@ -262,7 +271,7 @@ DlnLnkMsgNoUrl : "Por favor tipee el v«¿nculo URL", DlnLnkMsgNoEMail : "Por favor tipee la direcci«Ñn de e-mail", DlnLnkMsgNoAnchor : "Por favor seleccione una referencia", -DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces", //MISSING +DlnLnkMsgInvPopName : "El nombre debe empezar con un caracter alfanum«±rico y no debe contener espacios", // Color Dialog DlgColorTitle : "Seleccionar Color", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Color de Borde", DlgCellBtnSelect : "Seleccione...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Buscar y Reemplazar", + // Find Dialog DlgFindTitle : "Buscar", DlgFindFindBtn : "Buscar", @@ -344,10 +356,9 @@ PasteFromWord : "Pegar desde Word", DlgPasteMsg2 : "Por favor pegue dentro del cuadro utilizando el teclado (Ctrl+V); luego presione OK.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "Debido a la configuraci«Ñn de seguridad de su navegador, el editor no tiene acceso al portapapeles. Es necesario que lo pegue de nuevo en esta ventana.", DlgPasteIgnoreFont : "Ignorar definiciones de fuentes", DlgPasteRemoveStyles : "Remover definiciones de estilo", -DlgPasteCleanBox : "Borrar el contenido del cuadro", // Color Picker ColorAutomatic : "Autom«¡tico", @@ -381,9 +392,9 @@ // Button Dialog DlgButtonText : "Texto (Valor)", DlgButtonType : "Tipo", -DlgButtonTypeBtn : "Button", //MISSING -DlgButtonTypeSbm : "Submit", //MISSING -DlgButtonTypeRst : "Reset", //MISSING +DlgButtonTypeBtn : "Boton", +DlgButtonTypeSbm : "Enviar", +DlgButtonTypeRst : "Reestablecer", // Checkbox and Radio Button Dialogs DlgCheckboxName : "Nombre", @@ -432,7 +443,7 @@ // Bulleted List Dialog BulletedListProp : "Propiedades de Vi«Ðetas", NumberedListProp : "Propiedades de Numeraciones", -DlgLstStart : "Start", //MISSING +DlgLstStart : "Inicio", DlgLstType : "Tipo", DlgLstTypeCircle : "C«¿rculo", DlgLstTypeDisc : "Disco", @@ -455,15 +466,15 @@ DlgDocLangDirRTL : "Der. a Izquierda (RTL)", DlgDocLangCode : "C«Ñdigo de Idioma", DlgDocCharSet : "Codif. de Conjunto de Caracteres", -DlgDocCharSetCE : "Central European", //MISSING -DlgDocCharSetCT : "Chinese Traditional (Big5)", //MISSING -DlgDocCharSetCR : "Cyrillic", //MISSING -DlgDocCharSetGR : "Greek", //MISSING -DlgDocCharSetJP : "Japanese", //MISSING -DlgDocCharSetKR : "Korean", //MISSING -DlgDocCharSetTR : "Turkish", //MISSING -DlgDocCharSetUN : "Unicode (UTF-8)", //MISSING -DlgDocCharSetWE : "Western European", //MISSING +DlgDocCharSetCE : "Centro Europeo", +DlgDocCharSetCT : "Chino Tradicional (Big5)", +DlgDocCharSetCR : "Cir«¿lico", +DlgDocCharSetGR : "Griego", +DlgDocCharSetJP : "Japon«±s", +DlgDocCharSetKR : "Coreano", +DlgDocCharSetTR : "Turco", +DlgDocCharSetUN : "Unicode (UTF-8)", +DlgDocCharSetWE : "Europeo occidental", DlgDocCharSetOther : "Otra Codificaci«Ñn", DlgDocDocType : "Encabezado de Tipo de Documento", @@ -493,7 +504,7 @@ DlgTemplatesSelMsg : "Por favor selecciona la plantilla a abrir en el editor
      (el contenido actual se perder«¡):", DlgTemplatesLoading : "Cargando lista de Plantillas. Por favor, aguarde...", DlgTemplatesNoTpl : "(No hay plantillas definidas)", -DlgTemplatesReplace : "Replace actual contents", //MISSING +DlgTemplatesReplace : "Reemplazar el contenido actual", // About Dialog DlgAboutAboutTab : "Acerca de", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Licencia", DlgAboutVersion : "versi«Ñn", DlgAboutInfo : "Para mayor informaci«Ñn por favor dirigirse a" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/et.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/et.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/et.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -42,15 +42,16 @@ SelectAll : "Vali k«Øik", RemoveFormat : "Eemalda vorming", InsertLinkLbl : "Link", -InsertLink : "Sisesta/Muuda link", +InsertLink : "Sisesta link / Muuda linki", RemoveLink : "Eemalda link", -Anchor : "Sisesta/Muuda ankur", +Anchor : "Sisesta ankur / Muuda ankrut", +AnchorDelete : "Eemalda ankur", InsertImageLbl : "Pilt", -InsertImage : "Sisesta/Muuda pilt", +InsertImage : "Sisesta pilt / Muuda pilti", InsertFlashLbl : "Flash", -InsertFlash : "Sisesta/Muuda flash", +InsertFlash : "Sisesta flash / Muuda flashi", InsertTableLbl : "Tabel", -InsertTable : "Sisesta/Muuda tabel", +InsertTable : "Sisesta tabel / Muuda tabelit", InsertLineLbl : "Joon", InsertLine : "Sisesta horisontaaljoon", InsertSpecialCharLbl: "Erim«£rgid", @@ -58,10 +59,10 @@ InsertSmileyLbl : "Emotikon", InsertSmiley : "Sisesta emotikon", About : "FCKeditor teave", -Bold : "Rasvane kiri", -Italic : "Kursiiv kiri", -Underline : "Allajoonitud kiri", -StrikeThrough : "L«£bijoonitud kiri", +Bold : "Paks", +Italic : "Kursiiv", +Underline : "Allajoonitud", +StrikeThrough : "L«£bijoonitud", Subscript : "Allindeks", Superscript : "ªälaindeks", LeftJustify : "Vasakjoondus", @@ -70,6 +71,7 @@ BlockJustify : "R«Ó«Ópjoondus", DecreaseIndent : "V«£henda taanet", IncreaseIndent : "Suurenda taanet", +Blockquote : "Blokktsitaat", Undo : "V«Øta tagasi", Redo : "Korda toimingut", NumberedListLbl : "Nummerdatud loetelu", @@ -90,7 +92,7 @@ SpellCheck : "Kontrolli «Øigekirja", UniversalKeyboard : "Universaalne klaviatuur", PageBreakLbl : "Lehepiir", -PageBreak : "Sisesta lehevahetus koht", +PageBreak : "Sisesta lehevahetuskoht", Form : "Vorm", Checkbox : "M«£rkeruut", @@ -103,24 +105,31 @@ ImageButton : "Piltnupp", FitWindow : "Maksimeeri redaktori m«Ø«Øtmed", +ShowBlocks : "N«£ita blokke", // Context Menu EditLink : "Muuda linki", CellCM : "Lahter", RowCM : "Rida", ColumnCM : "Veerg", -InsertRow : "Lisa rida", -DeleteRows : "Eemalda ridu", -InsertColumn : "Lisa veerg", +InsertRowAfter : "Sisesta rida peale", +InsertRowBefore : "Sisesta rida enne", +DeleteRows : "Eemalda read", +InsertColumnAfter : "Sisesta veerg peale", +InsertColumnBefore : "Sisesta veerg enne", DeleteColumns : "Eemalda veerud", -InsertCell : "Lisa lahter", +InsertCellAfter : "Sisesta lahter peale", +InsertCellBefore : "Sisesta lahter enne", DeleteCells : "Eemalda lahtrid", MergeCells : "ªähenda lahtrid", -SplitCell : "Lahuta lahtrid", +MergeRight : "ªähenda paremale", +MergeDown : "ªähenda alla", +HorizontalSplitCell : "Poolita lahter horisontaalselt", +VerticalSplitCell : "Poolita lahter vertikaalselt", TableDelete : "Kustuta tabel", CellProperties : "Lahtri atribuudid", TableProperties : "Tabeli atribuudid", -ImageProperties : "Pildi atribuudid", +ImageProperties : "Pildi atribuudid", FlashProperties : "Flash omadused", AnchorProp : "Ankru omadused", @@ -134,18 +143,18 @@ TextareaProp : "Tekstiala omadused", FormProp : "Vormi omadused", -FontFormats : "Tavaline;Vormindatud;Aadress;Pealkiri 1;Pealkiri 2;Pealkiri 3;Pealkiri 4;Pealkiri 5;Pealkiri 6", //REVIEW : Check _getfontformat.html +FontFormats : "Tavaline;Vormindatud;Aadress;Pealkiri 1;Pealkiri 2;Pealkiri 3;Pealkiri 4;Pealkiri 5;Pealkiri 6;Tavaline (DIV)", // Alerts and Messages -ProcessingXHTML : "T«Ó«Ótlen XHTML. Palun oota...", +ProcessingXHTML : "T«Ó«Ótlen XHTML'i. Palun oota...", Done : "Tehtud", -PasteWordConfirm : "Tekst, mida soovid lisada paistab p«£rinevat Wordist. Kas soovid seda enne kleepimist puhastada?", +PasteWordConfirm : "Tekst, mida soovid lisada paistab p«£rinevat Word'ist. Kas soovid seda enne kleepimist puhastada?", NotCompatiblePaste : "See k«£sk on saadaval ainult Internet Explorer versioon 5.5 v«Øi uuema puhul. Kas soovid kleepida ilma puhastamata?", -UnknownToolbarItem : "Tundmatu t«Ó«Óriistariba «äksus \"%1\"", +UnknownToolbarItem : "Tundmatu t«Ó«Óriistarea «äksus \"%1\"", UnknownCommand : "Tundmatu k«£sunimi \"%1\"", NotImplemented : "K«£sku ei t«£idetud", UnknownToolbarSet : "T«Ó«Óriistariba \"%1\" ei eksisteeri", -NoActiveX : "Sinu interneti sirvija turvalisuse seaded v«Øivad limiteerida m«Øningaid tekstirdaktori kasutus v«Øimalusi. Sa peaksid v«Øimaldama valiku \"Run ActiveX controls and plug-ins\" oma sirvija seadetes. Muidu v«Øid sa t«£heldada vigu tekstiredaktori t«Ó«Ós ja m«£rgata puuduvaid funktsioone.", +NoActiveX : "Sinu veebisirvija turvalisuse seaded v«Øivad limiteerida m«Øningaid tekstirdaktori kasutusv«Øimalusi. Sa peaksid v«Øimaldama valiku \"Run ActiveX controls and plug-ins\" oma veebisirvija seadetes. Muidu v«Øid sa t«£heldada vigu tekstiredaktori t«Ó«Ós ja m«£rgata puuduvaid funktsioone.", BrowseServerBlocked : "Ressursside sirvija avamine eba«Ønnestus. V«Øimalda pop-up akende avanemine.", DialogBlocked : "Ei olenud v«Øimalik avada dialoogi akent. V«Øimalda pop-up akende avanemine.", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Vali ankur", DlgLnkAnchorByName : "Ankru nime j«£rgi", DlgLnkAnchorById : "Elemendi id j«£rgi", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Selles dokumendis ei ole ankruid)", DlgLnkEMail : "E-posti aadress", DlgLnkEMailSubject : "S«Ønumi teema", DlgLnkEMailBody : "S«Ønumi tekst", @@ -240,7 +249,7 @@ DlgLnkTargetFrame : "", DlgLnkTargetPopup : "", DlgLnkTargetBlank : "Uus aken (_blank)", -DlgLnkTargetParent : "Vanem aken (_parent)", +DlgLnkTargetParent : "Esivanem aken (_parent)", DlgLnkTargetSelf : "Sama aken (_self)", DlgLnkTargetTop : "Pealmine aken (_top)", DlgLnkTargetFrameName : "Sihtm«£rk raami nimi", @@ -262,7 +271,7 @@ DlnLnkMsgNoUrl : "Palun kirjuta lingi URL", DlnLnkMsgNoEMail : "Palun kirjuta E-Posti aadress", DlnLnkMsgNoAnchor : "Palun vali ankur", -DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces", //MISSING +DlnLnkMsgInvPopName : "H«äpikakna nimi peab algama alfabeetilise t«£hega ja ei tohi sisaldada t«ähikuid", // Color Dialog DlgColorTitle : "Vali v«£rv", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Joone v«£rv", DlgCellBtnSelect : "Vali...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Otsi ja asenda", + // Find Dialog DlgFindTitle : "Otsi", DlgFindFindBtn : "Otsi", @@ -337,17 +349,16 @@ DlgReplaceWordChk : "Otsi terviklike s«Ønu", // Paste Operations / Dialog -PasteErrorCut : "Sinu interneti sirvija turvaseaded ei luba redaktoril automaatselt l«Øigata. Palun kasutage selleks klaviatuuri klahvikombinatsiooni (Ctrl+X).", -PasteErrorCopy : "Sinu interneti sirvija turvaseaded ei luba redaktoril automaatselt kopeerida. Palun kasutage selleks klaviatuuri klahvikombinatsiooni (Ctrl+C).", +PasteErrorCut : "Sinu veebisirvija turvaseaded ei luba redaktoril automaatselt l«Øigata. Palun kasutage selleks klaviatuuri klahvikombinatsiooni (Ctrl+X).", +PasteErrorCopy : "Sinu veebisirvija turvaseaded ei luba redaktoril automaatselt kopeerida. Palun kasutage selleks klaviatuuri klahvikombinatsiooni (Ctrl+C).", PasteAsText : "Kleebi tavalise tekstina", PasteFromWord : "Kleebi Wordist", DlgPasteMsg2 : "Palun kleebi j«£rgnevasse kasti kasutades klaviatuuri klahvikombinatsiooni (Ctrl+V) ja vajuta seej«£rel OK.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "Sinu veebisirvija turvaseadete t«Øttu, ei oma redaktor otsest ligip«£«£su l«Øikelaua andmetele. Sa pead kleepima need uuesti siia aknasse.", DlgPasteIgnoreFont : "Ignoreeri kirja definitsioone", DlgPasteRemoveStyles : "Eemalda stiilide definitsioonid", -DlgPasteCleanBox : "Puhasta «£ra kast", // Color Picker ColorAutomatic : "Automaatne", @@ -381,9 +392,9 @@ // Button Dialog DlgButtonText : "Tekst (v«£«£rtus)", DlgButtonType : "T«ä«äp", -DlgButtonTypeBtn : "Button", //MISSING -DlgButtonTypeSbm : "Submit", //MISSING -DlgButtonTypeRst : "Reset", //MISSING +DlgButtonTypeBtn : "Nupp", +DlgButtonTypeSbm : "Saada", +DlgButtonTypeRst : "L«£htesta", // Checkbox and Radio Button Dialogs DlgCheckboxName : "Nimi", @@ -432,7 +443,7 @@ // Bulleted List Dialog BulletedListProp : "T«£pitud loetelu omadused", NumberedListProp : "Nummerdatud loetelu omadused", -DlgLstStart : "Start", //MISSING +DlgLstStart : "Alusta", DlgLstType : "T«ä«äp", DlgLstTypeCircle : "Ring", DlgLstTypeDisc : "Ketas", @@ -455,15 +466,15 @@ DlgDocLangDirRTL : "Paremalt vasakule (RTL)", DlgDocLangCode : "Keele kood", DlgDocCharSet : "M«£rgistiku kodeering", -DlgDocCharSetCE : "Central European", //MISSING -DlgDocCharSetCT : "Chinese Traditional (Big5)", //MISSING -DlgDocCharSetCR : "Cyrillic", //MISSING -DlgDocCharSetGR : "Greek", //MISSING -DlgDocCharSetJP : "Japanese", //MISSING -DlgDocCharSetKR : "Korean", //MISSING -DlgDocCharSetTR : "Turkish", //MISSING -DlgDocCharSetUN : "Unicode (UTF-8)", //MISSING -DlgDocCharSetWE : "Western European", //MISSING +DlgDocCharSetCE : "Kesk-Euroopa", +DlgDocCharSetCT : "Hiina traditsiooniline (Big5)", +DlgDocCharSetCR : "Kirillisa", +DlgDocCharSetGR : "Kreeka", +DlgDocCharSetJP : "Jaapani", +DlgDocCharSetKR : "Korea", +DlgDocCharSetTR : "T«ärgi", +DlgDocCharSetUN : "Unicode (UTF-8)", +DlgDocCharSetWE : "L«£«£ne-Euroopa", DlgDocCharSetOther : "ªälej«£«£nud m«£rgistike kodeeringud", DlgDocDocType : "Dokumendi t«ä«äpp«£is", @@ -493,12 +504,12 @@ DlgTemplatesSelMsg : "Palun vali «Þabloon, et avada see redaktoris
      (praegune sisu l«£heb kaotsi):", DlgTemplatesLoading : "Laen «Þabloonide nimekirja. Palun oota...", DlgTemplatesNoTpl : "(ªähtegi «Þablooni ei ole defineeritud)", -DlgTemplatesReplace : "Replace actual contents", //MISSING +DlgTemplatesReplace : "Asenda tegelik sisu", // About Dialog DlgAboutAboutTab : "Teave", -DlgAboutBrowserInfoTab : "Interneti sirvija info", +DlgAboutBrowserInfoTab : "Veebisirvija info", DlgAboutLicenseTab : "Litsents", DlgAboutVersion : "versioon", DlgAboutInfo : "T«£psema info saamiseks mine" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/eu.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/eu.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/eu.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -46,6 +46,7 @@ InsertLink : "Txertatu/Editatu Esteka", RemoveLink : "Kendu Esteka", Anchor : "Aingura", +AnchorDelete : "Ezabatu Aingura", InsertImageLbl : "Irudia", InsertImage : "Txertatu/Editatu Irudia", InsertFlashLbl : "Flasha", @@ -71,6 +72,7 @@ BlockJustify : "Justifikatu", DecreaseIndent : "Txikitu Koska", IncreaseIndent : "Handitu Koska", +Blockquote : "Aipamen blokea", Undo : "Desegin", Redo : "Berregin", NumberedListLbl : "Zenbakidun Zerrenda", @@ -104,20 +106,27 @@ ImageButton : "Irudi Botoia", FitWindow : "Maximizatu editorearen tamaina", +ShowBlocks : "Blokeak erakutsi", // Context Menu EditLink : "Aldatu Esteka", CellCM : "Gelaxka", RowCM : "Errenkada", ColumnCM : "Zutabea", -InsertRow : "Txertatu Errenkada", +InsertRowAfter : "Txertatu Lerroa Ostean", +InsertRowBefore : "Txertatu Lerroa Aurretik", DeleteRows : "Ezabatu Errenkadak", -InsertColumn : "Txertatu Zutabea", +InsertColumnAfter : "Txertatu Zutabea Ostean", +InsertColumnBefore : "Txertatu Zutabea Aurretik", DeleteColumns : "Ezabatu Zutabeak", -InsertCell : "Txertatu Gelaxka", +InsertCellAfter : "Txertatu Gelaxka Ostean", +InsertCellBefore : "Txertatu Gelaxka Aurretik", DeleteCells : "Kendu Gelaxkak", MergeCells : "Batu Gelaxkak", -SplitCell : "Zatitu Gelaxka", +MergeRight : "Elkartu Eskumara", +MergeDown : "Elkartu Behera", +HorizontalSplitCell : "Banatu Gelaxkak Horizontalki", +VerticalSplitCell : "Banatu Gelaxkak Bertikalki", TableDelete : "Ezabatu Taula", CellProperties : "Gelaxkaren Ezaugarriak", TableProperties : "Taularen Ezaugarriak", @@ -135,7 +144,7 @@ TextareaProp : "Testu-arearen Ezaugarriak", FormProp : "Formularioaren Ezaugarriak", -FontFormats : "Arrunta;Formateatua;Helbidea;Izenburua 1;Izenburua 2;Izenburua 3;Izenburua 4;Izenburua 5;Izenburua 6;Paragrafoa (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Arrunta;Formateatua;Helbidea;Izenburua 1;Izenburua 2;Izenburua 3;Izenburua 4;Izenburua 5;Izenburua 6;Paragrafoa (DIV)", // Alerts and Messages ProcessingXHTML : "XHTML Prozesatzen. Itxaron mesedez...", @@ -230,7 +239,7 @@ DlgLnkAnchorSel : "Aingura bat hautatu", DlgLnkAnchorByName : "Aingura izenagatik", DlgLnkAnchorById : "Elementuaren ID-gatik", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Ez daude aingurak eskuragarri dokumentuan)", DlgLnkEMail : "ePosta Helbidea", DlgLnkEMailSubject : "Mezuaren Gaia", DlgLnkEMailBody : "Mezuaren Gorputza", @@ -263,7 +272,7 @@ DlnLnkMsgNoUrl : "Mesedez URL esteka idatzi", DlnLnkMsgNoEMail : "Mesedez ePosta helbidea idatzi", DlnLnkMsgNoAnchor : "Mesedez aingura bat aukeratu", -DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces", //MISSING +DlnLnkMsgInvPopName : "Popup lehioaren izenak karaktere alfabetiko batekin hasi behar du eta eta ezin du zuriunerik izan", // Color Dialog DlgColorTitle : "Kolore Aukeraketa", @@ -323,6 +332,9 @@ DlgCellBorderColor : "Ertzako Kolorea", DlgCellBtnSelect : "Aukertau...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Bilatu eta Ordeztu", + // Find Dialog DlgFindTitle : "Bilaketa", DlgFindFindBtn : "Bilatu", @@ -345,10 +357,9 @@ PasteFromWord : "Word-etik itsatsi", DlgPasteMsg2 : "Mesedez teklatua erabilita (Ctrl+V) ondorego eremuan testua itsatsi eta OK sakatu.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "Nabigatzailearen segurtasun ezarpenak direla eta, editoreak ezin du arbela zuzenean erabili. Leiho honetan berriro itsatsi behar duzu.", DlgPasteIgnoreFont : "Letra Motaren definizioa ezikusi", DlgPasteRemoveStyles : "Estilo definizioak kendu", -DlgPasteCleanBox : "Testu-eremua Garbitu", // Color Picker ColorAutomatic : "Automatikoa", @@ -382,9 +393,9 @@ // Button Dialog DlgButtonText : "Testua (Balorea)", DlgButtonType : "Mota", -DlgButtonTypeBtn : "Button", //MISSING -DlgButtonTypeSbm : "Submit", //MISSING -DlgButtonTypeRst : "Reset", //MISSING +DlgButtonTypeBtn : "Botoia", +DlgButtonTypeSbm : "Bidali", +DlgButtonTypeRst : "Garbitu", // Checkbox and Radio Button Dialogs DlgCheckboxName : "Izena", @@ -433,7 +444,7 @@ // Bulleted List Dialog BulletedListProp : "Buletdun Zerrendaren Ezarpenak", NumberedListProp : "Zenbakidun Zerrendaren Ezarpenak", -DlgLstStart : "Start", //MISSING +DlgLstStart : "Hasiera", DlgLstType : "Mota", DlgLstTypeCircle : "Zirkulua", DlgLstTypeDisc : "Diskoa", @@ -456,16 +467,16 @@ DlgDocLangDirRTL : "Eskumatik ezkerrera (RTL)", DlgDocLangCode : "Hizkuntzaren Kodea", DlgDocCharSet : "Karaktere Multzoaren Kodeketa", -DlgDocCharSetCE : "Central European", //MISSING -DlgDocCharSetCT : "Chinese Traditional (Big5)", //MISSING -DlgDocCharSetCR : "Cyrillic", //MISSING -DlgDocCharSetGR : "Greek", //MISSING -DlgDocCharSetJP : "Japanese", //MISSING -DlgDocCharSetKR : "Korean", //MISSING -DlgDocCharSetTR : "Turkish", //MISSING -DlgDocCharSetUN : "Unicode (UTF-8)", //MISSING -DlgDocCharSetWE : "Western European", //MISSING -DlgDocCharSetOther : "Beste Karaktere Multzoaren Kodeketa", +DlgDocCharSetCE : "Erdialdeko Europakoa", +DlgDocCharSetCT : "Txinatar Tradizionala (Big5)", +DlgDocCharSetCR : "Zirilikoa", +DlgDocCharSetGR : "Grekoa", +DlgDocCharSetJP : "Japoniarra", +DlgDocCharSetKR : "Korearra", +DlgDocCharSetTR : "Turkiarra", +DlgDocCharSetUN : "Unicode (UTF-8)", +DlgDocCharSetWE : "Mendebaldeko Europakoa", +DlgDocCharSetOther : "Beste Karaktere Multzoko Kodeketa", DlgDocDocType : "Document Type Goiburua", DlgDocDocTypeOther : "Beste Document Type Goiburua", @@ -494,7 +505,7 @@ DlgTemplatesSelMsg : "Mesedez txantiloia aukeratu editorean kargatzeko
      (orain dauden edukiak galduko dira):", DlgTemplatesLoading : "Txantiloiak kargatzen. Itxaron mesedez...", DlgTemplatesNoTpl : "(Ez dago definitutako txantiloirik)", -DlgTemplatesReplace : "Replace actual contents", //MISSING +DlgTemplatesReplace : "Ordeztu oraingo edukiak", // About Dialog DlgAboutAboutTab : "Honi buruz", @@ -502,4 +513,4 @@ DlgAboutLicenseTab : "Lizentzia", DlgAboutVersion : "bertsioa", DlgAboutInfo : "Informazio gehiago eskuratzeko hona joan" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fa.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fa.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fa.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "???????/?????? ??????", RemoveLink : "??????? ?????", Anchor : "???????/?????? ?????", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "?????", InsertImage : "???????/?????? ??????", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "????????", DecreaseIndent : "???? ???????", IncreaseIndent : "?????? ???????", +Blockquote : "Blockquote", //MISSING Undo : "??????", Redo : "???????", NumberedListLbl : "????? ?????????", @@ -103,20 +105,27 @@ ImageButton : "????? ??????", FitWindow : "??????????? ???????? ????????", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "?????? ?????", CellCM : "????", RowCM : "???", ColumnCM : "????", -InsertRow : "??????? ???", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "??? ?????", -InsertColumn : "??????? ????", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "??? ??????", -InsertCell : "??????? ????", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "??? ??????", MergeCells : "????? ??????", -SplitCell : "??????? ????", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "???????? ????", CellProperties : "???????? ????", TableProperties : "???????? ????", @@ -134,12 +143,12 @@ TextareaProp : "???????? ?????? ????", FormProp : "???????? ???", -FontFormats : "?????;????????;????;?????? 1;?????? 2;?????? 3;?????? 4;?????? 5;?????? 6;???;(DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "?????;????????;????;?????? 1;?????? 2;?????? 3;?????? 4;?????? 5;?????? 6;???;(DIV)", // Alerts and Messages ProcessingXHTML : "?????? XHTML. ???? ??? ????...", Done : "????? ??", -PasteWordConfirm : "??? ??? ???. ??? ????????? ??? ?? ??????? ?? ?? ???????? ????? Word ???? ?? ????????? ???????? ?? ??? ?????? ??", +PasteWordConfirm : "???? ?? ????????? ???????? ?? ??? ?????? ?? Word ??? ??? ???. ??? ????????? ??? ?? ??????? ?? ?? ???????? ?????", NotCompatiblePaste : "??? ????? ???? ?????? Internet Explorer ?? ????? 5.5 ?? ?????? ?? ????? ???. ??? ????????? ???? ????????? ??? ?? ?????????", UnknownToolbarItem : "????? ????????? ???????? \"%1\"", UnknownCommand : "??? ????? ???????? \"%1\"", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "?? ???? ????????", DlgLnkAnchorByName : "?? ??? ????", DlgLnkAnchorById : "?? ?????? ?????", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(?? ??? ??? ????? ??????? ????)", DlgLnkEMail : "????? ??? ??????????", DlgLnkEMailSubject : "????? ????", DlgLnkEMailBody : "??? ????", @@ -246,7 +255,7 @@ DlgLnkTargetFrameName : "??? ???? ????", DlgLnkPopWinName : "??? ?????? ?????", DlgLnkPopWinFeat : "???????? ?????? ?????", -DlgLnkPopResize : "???? ???? ??????", +DlgLnkPopResize : "???? ????? ??????", DlgLnkPopLocation : "???? ??????", DlgLnkPopMenu : "???? ???", DlgLnkPopScroll : "???????? ??????", @@ -322,6 +331,9 @@ DlgCellBorderColor : "??? ???", DlgCellBtnSelect : "????????...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "?????", DlgFindFindBtn : "?????", @@ -344,10 +356,9 @@ PasteFromWord : "??????? ?? Word", DlgPasteMsg2 : "???? ??? ?? ?? ??????? (Ctrl+V) ?? ??? ????? ???? ???????? ? ????? ?? ?????.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "?? ???? ??????? ?????? ?????? ???? ???????? ????????? ?????? ?????? ?? ???????? clipboard ????? ????. ??? ???? ?????? ???? ?? ??? ????? ????????.", DlgPasteIgnoreFont : "???????? ?? ?????? ??? ???", DlgPasteRemoveStyles : "???????? ?? ?????? ??? (style)", -DlgPasteCleanBox : "???????? ?????", // Color Picker ColorAutomatic : "??????", @@ -362,8 +373,8 @@ DlgAnchorErrorName : "???? ??? ???? ?? ???????", // Speller Pages Dialog -DlgSpellNotInDic : "?? ????????? ????? ????", -DlgSpellChangeTo : "???? ??", +DlgSpellNotInDic : "?? ????????? ???? ???", +DlgSpellChangeTo : "????? ??", DlgSpellBtnIgnore : "????????", DlgSpellBtnIgnoreAll : "???????? ???", DlgSpellBtnReplace : "????????", @@ -372,9 +383,9 @@ DlgSpellNoSuggestions : "- ???????? ???? -", DlgSpellProgress : "????? ???? ?? ??? ?????...", DlgSpellNoMispell : "????? ???? ????? ??. ??? ?????????? ???? ???", -DlgSpellNoChanges : "????? ???? ????? ??. ??? ??????? ???? ?????", -DlgSpellOneChange : "????? ???? ????? ??. ?? ???? ???? ????", -DlgSpellManyChanges : "????? ???? ????? ??. %1 ???? ???? ????", +DlgSpellNoChanges : "????? ???? ????? ??. ??? ??????? ????? ?????", +DlgSpellOneChange : "????? ???? ????? ??. ?? ???? ????? ????", +DlgSpellManyChanges : "????? ???? ????? ??. %1 ???? ????? ????", IeSpellDownload : "???????????? ???? ??? ???? ???. ??? ????????? ?? ?? ???????? ?????? ?????", @@ -392,7 +403,7 @@ // Form Dialog DlgFormName : "???", -DlgFormAction : "?????", +DlgFormAction : "??????", DlgFormMethod : "???", // Select Field Dialog @@ -401,15 +412,15 @@ DlgSelectSize : "??????", DlgSelectLines : "????", DlgSelectChkMulti : "????? ??????? ????? ????", -DlgSelectOpAvail : "????????? ?????", +DlgSelectOpAvail : "????????? ???????", DlgSelectOpText : "???", DlgSelectOpValue : "?????", -DlgSelectBtnAdd : "?????", +DlgSelectBtnAdd : "??????", DlgSelectBtnModify : "??????", DlgSelectBtnUp : "????", DlgSelectBtnDown : "?????", DlgSelectBtnSetValue : "????? ?? ????? ????? ????????", -DlgSelectBtnDelete : "???", +DlgSelectBtnDelete : "????????", // Textarea Dialog DlgTextareaName : "???", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "?????????", DlgAboutVersion : "?????", DlgAboutInfo : "???? ????? ????? ?? ??? ????? ?????" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fi.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fi.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fi.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Lis«£«£ linkki/muokkaa linkki«£", RemoveLink : "Poista linkki", Anchor : "Lis«£«£ ankkuri/muokkaa ankkuria", +AnchorDelete : "Poista ankkuri", InsertImageLbl : "Kuva", InsertImage : "Lis«£«£ kuva/muokkaa kuvaa", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Tasaa molemmat reunat", DecreaseIndent : "Pienenn«£ sisennyst«£", IncreaseIndent : "Suurenna sisennyst«£", +Blockquote : "Lainaus", Undo : "Kumoa", Redo : "Toista", NumberedListLbl : "Numerointi", @@ -103,20 +105,27 @@ ImageButton : "Kuvapainike", FitWindow : "Suurenna editori koko ikkunaan", +ShowBlocks : "N«£yt«£ elementit", // Context Menu EditLink : "Muokkaa linkki«£", CellCM : "Solu", RowCM : "Rivi", ColumnCM : "Sarake", -InsertRow : "Lis«£«£ rivi", +InsertRowAfter : "Lis«£«£ rivi alapuolelle", +InsertRowBefore : "Lis«£«£ rivi yl«£puolelle", DeleteRows : "Poista rivit", -InsertColumn : "Lis«£«£ sarake", +InsertColumnAfter : "Lis«£«£ sarake oikealle", +InsertColumnBefore : "Lis«£«£ sarake vasemmalle", DeleteColumns : "Poista sarakkeet", -InsertCell : "Lis«£«£ solu", +InsertCellAfter : "Lis«£«£ solu per«£«£n", +InsertCellBefore : "Lis«£«£ solu eteen", DeleteCells : "Poista solut", MergeCells : "Yhdist«£ solut", -SplitCell : "Jaa solu", +MergeRight : "Yhdist«£ oikealla olevan kanssa", +MergeDown : "Yhdist«£ alla olevan kanssa", +HorizontalSplitCell : "Jaa solu vaakasuunnassa", +VerticalSplitCell : "Jaa solu pystysuunnassa", TableDelete : "Poista taulu", CellProperties : "Solun ominaisuudet", TableProperties : "Taulun ominaisuudet", @@ -134,7 +143,7 @@ TextareaProp : "Tekstilaatikon ominaisuudet", FormProp : "Lomakkeen ominaisuudet", -FontFormats : "Normaali;Muotoiltu;Osoite;Otsikko 1;Otsikko 2;Otsikko 3;Otsikko 4;Otsikko 5;Otsikko 6", //REVIEW : Check _getfontformat.html +FontFormats : "Normaali;Muotoiltu;Osoite;Otsikko 1;Otsikko 2;Otsikko 3;Otsikko 4;Otsikko 5;Otsikko 6", // Alerts and Messages ProcessingXHTML : "Prosessoidaan XHTML:«£«£. Odota hetki...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Valitse ankkuri", DlgLnkAnchorByName : "Ankkurin nimen mukaan", DlgLnkAnchorById : "Ankkurin ID:n mukaan", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Ei ankkureita t«£ss«£ dokumentissa)", DlgLnkEMail : "S«£hk«Ópostiosoite", DlgLnkEMailSubject : "Aihe", DlgLnkEMailBody : "Viesti", @@ -262,7 +271,7 @@ DlnLnkMsgNoUrl : "Linkille on kirjoitettava URL", DlnLnkMsgNoEMail : "Kirjoita s«£hk«Ópostiosoite", DlnLnkMsgNoAnchor : "Valitse ankkuri", -DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces", //MISSING +DlnLnkMsgInvPopName : "Popup-ikkunan nimi pit«£«£ alkaa aakkosella ja ei saa sis«£lt«£«£ v«£lej«£", // Color Dialog DlgColorTitle : "Valitse v«£ri", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Rajan v«£ri", DlgCellBtnSelect : "Valitse...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Etsi ja korvaa", + // Find Dialog DlgFindTitle : "Etsi", DlgFindFindBtn : "Etsi", @@ -344,10 +356,9 @@ PasteFromWord : "Liit«£ Wordista", DlgPasteMsg2 : "Liit«£ painamalla (Ctrl+V) ja painamalla OK.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "Selaimesi turva-asetukset eiv«£t salli editorin k«£ytt«£«£ leikep«Óyt«£«£ suoraan. Sinun pit«£«£ suorittaa liitt«£minen t«£ss«£ ikkunassa.", DlgPasteIgnoreFont : "J«£t«£ huomioimatta fonttim«£«£ritykset", DlgPasteRemoveStyles : "Poista tyylim«£«£ritykset", -DlgPasteCleanBox : "Tyhjenn«£", // Color Picker ColorAutomatic : "Automaattinen", @@ -381,9 +392,9 @@ // Button Dialog DlgButtonText : "Teksti (arvo)", DlgButtonType : "Tyyppi", -DlgButtonTypeBtn : "Button", //MISSING -DlgButtonTypeSbm : "Submit", //MISSING -DlgButtonTypeRst : "Reset", //MISSING +DlgButtonTypeBtn : "Painike", +DlgButtonTypeSbm : "L«£het«£", +DlgButtonTypeRst : "Tyhjenn«£", // Checkbox and Radio Button Dialogs DlgCheckboxName : "Nimi", @@ -432,7 +443,7 @@ // Bulleted List Dialog BulletedListProp : "Luettelon ominaisuudet", NumberedListProp : "Numeroinnin ominaisuudet", -DlgLstStart : "Start", //MISSING +DlgLstStart : "Alku", DlgLstType : "Tyyppi", DlgLstTypeCircle : "Keh«£", DlgLstTypeDisc : "Ympyr«£", @@ -454,17 +465,17 @@ DlgDocLangDirLTR : "Vasemmalta oikealle (LTR)", DlgDocLangDirRTL : "Oikealta vasemmalle (RTL)", DlgDocLangCode : "Kielikoodi", -DlgDocCharSet : "Merkist«£koodaus", -DlgDocCharSetCE : "Central European", //MISSING -DlgDocCharSetCT : "Chinese Traditional (Big5)", //MISSING -DlgDocCharSetCR : "Cyrillic", //MISSING -DlgDocCharSetGR : "Greek", //MISSING -DlgDocCharSetJP : "Japanese", //MISSING -DlgDocCharSetKR : "Korean", //MISSING -DlgDocCharSetTR : "Turkish", //MISSING -DlgDocCharSetUN : "Unicode (UTF-8)", //MISSING -DlgDocCharSetWE : "Western European", //MISSING -DlgDocCharSetOther : "Muu merkist«£koodaus", +DlgDocCharSet : "Merkist«Ókoodaus", +DlgDocCharSetCE : "Keskieurooppalainen", +DlgDocCharSetCT : "Kiina, perinteinen (Big5)", +DlgDocCharSetCR : "Kyrillinen", +DlgDocCharSetGR : "Kreikka", +DlgDocCharSetJP : "Japani", +DlgDocCharSetKR : "Korealainen", +DlgDocCharSetTR : "Turkkilainen", +DlgDocCharSetUN : "Unicode (UTF-8)", +DlgDocCharSetWE : "L«£nsieurooppalainen", +DlgDocCharSetOther : "Muu merkist«Ókoodaus", DlgDocDocType : "Dokumentin tyyppi", DlgDocDocTypeOther : "Muu dokumentin tyyppi", @@ -493,7 +504,7 @@ DlgTemplatesSelMsg : "Valitse pohja editoriin
      (aiempi sis«£lt«Ó menetet«£«£n):", DlgTemplatesLoading : "Ladataan listaa pohjista. Hetkinen...", DlgTemplatesNoTpl : "(Ei m«£«£riteltyj«£ pohjia)", -DlgTemplatesReplace : "Replace actual contents", //MISSING +DlgTemplatesReplace : "Korvaa editorin koko sis«£lt«Ó", // About Dialog DlgAboutAboutTab : "Editorista", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Lisenssi", DlgAboutVersion : "versio", DlgAboutInfo : "Lis«£«£ tietoa osoitteesta" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fo.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fo.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fo.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Ger/broyt tilkn«òti", RemoveLink : "Strika tilkn«òti", Anchor : "Ger/broyt marknastein", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Myndir", InsertImage : "Set inn/broyt mynd", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Javnir tekstkantar", DecreaseIndent : "Minka reglubrotarinntriv", IncreaseIndent : "©¬kja reglubrotarinntriv", +Blockquote : "Blockquote", //MISSING Undo : "Angra", Redo : "Vend aftur", NumberedListLbl : "Talmerktur listi", @@ -103,20 +105,27 @@ ImageButton : "Myndakn©Ìttur", FitWindow : "Set tekstvi©Ãgera til fulla st©Ìdd", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "Broyt tilkn«òti", CellCM : "Meski", RowCM : "Ra©Ã", ColumnCM : "Kolonna", -InsertRow : "N«òtt ra©Ã", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Strika r©Ì©Ãir", -InsertColumn : "N«òggj kolonna", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "Strika kolonnur", -InsertCell : "N«òggjur meski", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "Strika meskar", MergeCells : "Fl©Átta meskar", -SplitCell : "B«òt sundur meskar", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Strika tabell", CellProperties : "Meskueginleikar", TableProperties : "Tabelleginleikar", @@ -134,7 +143,7 @@ TextareaProp : "Eginleikar fyri tekstumr«¡©Ãi", FormProp : "Eginleikar fyri Form", -FontFormats : "Vanligt;Sni©Ãgivi©Ã;Adressa;Yvirskrift 1;Yvirskrift 2;Yvirskrift 3;Yvirskrift 4;Yvirskrift 5;Yvirskrift 6", //REVIEW : Check _getfontformat.html +FontFormats : "Vanligt;Sni©Ãgivi©Ã;Adressa;Yvirskrift 1;Yvirskrift 2;Yvirskrift 3;Yvirskrift 4;Yvirskrift 5;Yvirskrift 6", // Alerts and Messages ProcessingXHTML : "XHTML ver©Ãur vi©Ãgj©Ìrt. B«¿©Ãa vi©Ã...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Vel ein marknastein", DlgLnkAnchorByName : "Eftir navni «¡ marknasteini", DlgLnkAnchorById : "Eftir element Id", -DlgLnkNoAnchors : "(Eingir marknasteinar eru «¿ hesum dokumenti©Ã)", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Eingir marknasteinar eru «¿ hesum dokumenti©Ã)", DlgLnkEMail : "Teldupost-adressa", DlgLnkEMailSubject : "Evni", DlgLnkEMailBody : "Brey©Ãtekstur", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Litur «¡ borda", DlgCellBtnSelect : "Vel...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "Finn", DlgFindFindBtn : "Finn", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Forfj«Ñna Font definiti«Ñnirnar", DlgPasteRemoveStyles : "Strika Styles definiti«Ñnir", -DlgPasteCleanBox : "Reinskanarkassi", // Color Picker ColorAutomatic : "Av s©Ár sj«¡lvum", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "License", DlgAboutVersion : "version", DlgAboutInfo : "Fyri fleiri uppl«òsingar, far til" -}; \ No newline at end of file +}; Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fr-ca.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fr-ca.js (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fr-ca.js 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,515 @@ +?/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * Canadian French language file. + */ + +var FCKLang = +{ +// Language direction : "ltr" (left to right) or "rtl" (right to left). +Dir : "ltr", + +ToolbarCollapse : "Masquer Outils", +ToolbarExpand : "Afficher Outils", + +// Toolbar Items and Context Menu +Save : "Sauvegarder", +NewPage : "Nouvelle page", +Preview : "Previsualiser", +Cut : "Couper", +Copy : "Copier", +Paste : "Coller", +PasteText : "Coller en tant que texte", +PasteWord : "Coller en tant que Word (format«±)", +Print : "Imprimer", +SelectAll : "Tout s«±lectionner", +RemoveFormat : "Supprimer le formatage", +InsertLinkLbl : "Lien", +InsertLink : "Ins«±rer/modifier le lien", +RemoveLink : "Supprimer le lien", +Anchor : "Ins«±rer/modifier l'ancre", +AnchorDelete : "Supprimer l'ancre", +InsertImageLbl : "Image", +InsertImage : "Ins«±rer/modifier l'image", +InsertFlashLbl : "Animation Flash", +InsertFlash : "Ins«±rer/modifier l'animation Flash", +InsertTableLbl : "Tableau", +InsertTable : "Ins«±rer/modifier le tableau", +InsertLineLbl : "S«±parateur", +InsertLine : "Ins«±rer un s«±parateur", +InsertSpecialCharLbl: "Caract«²res sp«±ciaux", +InsertSpecialChar : "Ins«±rer un caract«²re sp«±cial", +InsertSmileyLbl : "Emoticon", +InsertSmiley : "Ins«±rer un Emoticon", +About : "A propos de FCKeditor", +Bold : "Gras", +Italic : "Italique", +Underline : "Soulign«±", +StrikeThrough : "Barrer", +Subscript : "Indice", +Superscript : "Exposant", +LeftJustify : "Aligner «¢ gauche", +CenterJustify : "Centrer", +RightJustify : "Aligner «¢ Droite", +BlockJustify : "Texte justifi«±", +DecreaseIndent : "Diminuer le retrait", +IncreaseIndent : "Augmenter le retrait", +Blockquote : "Citation", +Undo : "Annuler", +Redo : "Refaire", +NumberedListLbl : "Liste num«±rot«±e", +NumberedList : "Ins«±rer/supprimer la liste num«±rot«±e", +BulletedListLbl : "Liste «¢ puces", +BulletedList : "Ins«±rer/supprimer la liste «¢ puces", +ShowTableBorders : "Afficher les bordures du tableau", +ShowDetails : "Afficher les caract«²res invisibles", +Style : "Style", +FontFormat : "Format", +Font : "Police", +FontSize : "Taille", +TextColor : "Couleur de caract«²re", +BGColor : "Couleur de fond", +Source : "Source", +Find : "Chercher", +Replace : "Remplacer", +SpellCheck : "Orthographe", +UniversalKeyboard : "Clavier universel", +PageBreakLbl : "Saut de page", +PageBreak : "Ins«±rer un saut de page", + +Form : "Formulaire", +Checkbox : "Case «¢ cocher", +RadioButton : "Bouton radio", +TextField : "Champ texte", +Textarea : "Zone de texte", +HiddenField : "Champ cach«±", +Button : "Bouton", +SelectionField : "Champ de s«±lection", +ImageButton : "Bouton image", + +FitWindow : "Edition pleine page", +ShowBlocks : "Afficher les blocs", + +// Context Menu +EditLink : "Modifier le lien", +CellCM : "Cellule", +RowCM : "Ligne", +ColumnCM : "Colonne", +InsertRowAfter : "Ins«±rer une ligne apr«²s", +InsertRowBefore : "Ins«±rer une ligne avant", +DeleteRows : "Supprimer des lignes", +InsertColumnAfter : "Ins«±rer une colonne apr«²s", +InsertColumnBefore : "Ins«±rer une colonne avant", +DeleteColumns : "Supprimer des colonnes", +InsertCellAfter : "Ins«±rer une cellule apr«²s", +InsertCellBefore : "Ins«±rer une cellule avant", +DeleteCells : "Supprimer des cellules", +MergeCells : "Fusionner les cellules", +MergeRight : "Fusionner «¢ droite", +MergeDown : "Fusionner en bas", +HorizontalSplitCell : "Scinder la cellule horizontalement", +VerticalSplitCell : "Scinder la cellule verticalement", +TableDelete : "Supprimer le tableau", +CellProperties : "Propri«±t«±s de cellule", +TableProperties : "Propri«±t«±s du tableau", +ImageProperties : "Propri«±t«±s de l'image", +FlashProperties : "Propri«±t«±s de l'animation Flash", + +AnchorProp : "Propri«±t«±s de l'ancre", +ButtonProp : "Propri«±t«±s du bouton", +CheckboxProp : "Propri«±t«±s de la case «¢ cocher", +HiddenFieldProp : "Propri«±t«±s du champ cach«±", +RadioButtonProp : "Propri«±t«±s du bouton radio", +ImageButtonProp : "Propri«±t«±s du bouton image", +TextFieldProp : "Propri«±t«±s du champ texte", +SelectionFieldProp : "Propri«±t«±s de la liste/du menu", +TextareaProp : "Propri«±t«±s de la zone de texte", +FormProp : "Propri«±t«±s du formulaire", + +FontFormats : "Normal;Format«±;Adresse;En-t«´te 1;En-t«´te 2;En-t«´te 3;En-t«´te 4;En-t«´te 5;En-t«´te 6;Normal (DIV)", + +// Alerts and Messages +ProcessingXHTML : "Calcul XHTML. Veuillez patienter...", +Done : "Termin«±", +PasteWordConfirm : "Le texte «¢ coller semble provenir de Word. D«±sirez-vous le nettoyer avant de coller?", +NotCompatiblePaste : "Cette commande n«±cessite Internet Explorer version 5.5 et plus. Souhaitez-vous coller sans nettoyage?", +UnknownToolbarItem : "ª±l«±ment de barre d'outil inconnu \"%1\"", +UnknownCommand : "Nom de commande inconnu \"%1\"", +NotImplemented : "Commande indisponible", +UnknownToolbarSet : "La barre d'outils \"%1\" n'existe pas", +NoActiveX : "Les param«²tres de s«±curit«± de votre navigateur peuvent limiter quelques fonctionnalit«±s de l'«±diteur. Veuillez activer l'option \"Ex«±cuter les contr«Ôles ActiveX et les plug-ins\". Il se peut que vous rencontriez des erreurs et remarquiez quelques limitations.", +BrowseServerBlocked : "Le navigateur n'a pas pu «´tre ouvert. Assurez-vous que les bloqueurs de popups soient d«±sactiv«±s.", +DialogBlocked : "La fen«´tre de dialogue n'a pas pu s'ouvrir. Assurez-vous que les bloqueurs de popups soient d«±sactiv«±s.", + +// Dialogs +DlgBtnOK : "OK", +DlgBtnCancel : "Annuler", +DlgBtnClose : "Fermer", +DlgBtnBrowseServer : "Parcourir le serveur", +DlgAdvancedTag : "Avanc«±e", +DlgOpOther : "", +DlgInfoTab : "Info", +DlgAlertUrl : "Veuillez saisir l'URL", + +// General Dialogs Labels +DlgGenNotSet : "", +DlgGenId : "Id", +DlgGenLangDir : "Sens d'«±criture", +DlgGenLangDirLtr : "De gauche «¢ droite (LTR)", +DlgGenLangDirRtl : "De droite «¢ gauche (RTL)", +DlgGenLangCode : "Code langue", +DlgGenAccessKey : "ª±quivalent clavier", +DlgGenName : "Nom", +DlgGenTabIndex : "Ordre de tabulation", +DlgGenLongDescr : "URL de description longue", +DlgGenClass : "Classes de feuilles de style", +DlgGenTitle : "Titre", +DlgGenContType : "Type de contenu", +DlgGenLinkCharset : "Encodage de caract«²re", +DlgGenStyle : "Style", + +// Image Dialog +DlgImgTitle : "Propri«±t«±s de l'image", +DlgImgInfoTab : "Informations sur l'image", +DlgImgBtnUpload : "Envoyer sur le serveur", +DlgImgURL : "URL", +DlgImgUpload : "T«±l«±charger", +DlgImgAlt : "Texte de remplacement", +DlgImgWidth : "Largeur", +DlgImgHeight : "Hauteur", +DlgImgLockRatio : "Garder les proportions", +DlgBtnResetSize : "Taille originale", +DlgImgBorder : "Bordure", +DlgImgHSpace : "Espacement horizontal", +DlgImgVSpace : "Espacement vertical", +DlgImgAlign : "Alignement", +DlgImgAlignLeft : "Gauche", +DlgImgAlignAbsBottom: "Abs Bas", +DlgImgAlignAbsMiddle: "Abs Milieu", +DlgImgAlignBaseline : "Bas du texte", +DlgImgAlignBottom : "Bas", +DlgImgAlignMiddle : "Milieu", +DlgImgAlignRight : "Droite", +DlgImgAlignTextTop : "Haut du texte", +DlgImgAlignTop : "Haut", +DlgImgPreview : "Pr«±visualisation", +DlgImgAlertUrl : "Veuillez saisir l'URL de l'image", +DlgImgLinkTab : "Lien", + +// Flash Dialog +DlgFlashTitle : "Propri«±t«±s de l'animation Flash", +DlgFlashChkPlay : "Lecture automatique", +DlgFlashChkLoop : "Boucle", +DlgFlashChkMenu : "Activer le menu Flash", +DlgFlashScale : "Affichage", +DlgFlashScaleAll : "Par d«±faut (tout montrer)", +DlgFlashScaleNoBorder : "Sans bordure", +DlgFlashScaleFit : "Ajuster aux dimensions", + +// Link Dialog +DlgLnkWindowTitle : "Propri«±t«±s du lien", +DlgLnkInfoTab : "Informations sur le lien", +DlgLnkTargetTab : "Destination", + +DlgLnkType : "Type de lien", +DlgLnkTypeURL : "URL", +DlgLnkTypeAnchor : "Ancre dans cette page", +DlgLnkTypeEMail : "E-Mail", +DlgLnkProto : "Protocole", +DlgLnkProtoOther : "", +DlgLnkURL : "URL", +DlgLnkAnchorSel : "S«±lectionner une ancre", +DlgLnkAnchorByName : "Par nom", +DlgLnkAnchorById : "Par id", +DlgLnkNoAnchors : "(Pas d'ancre disponible dans le document)", +DlgLnkEMail : "Adresse E-Mail", +DlgLnkEMailSubject : "Sujet du message", +DlgLnkEMailBody : "Corps du message", +DlgLnkUpload : "T«±l«±charger", +DlgLnkBtnUpload : "Envoyer sur le serveur", + +DlgLnkTarget : "Destination", +DlgLnkTargetFrame : "", +DlgLnkTargetPopup : "", +DlgLnkTargetBlank : "Nouvelle fen«´tre (_blank)", +DlgLnkTargetParent : "Fen«´tre m«²re (_parent)", +DlgLnkTargetSelf : "M«´me fen«´tre (_self)", +DlgLnkTargetTop : "Fen«´tre sup«±rieure (_top)", +DlgLnkTargetFrameName : "Nom du cadre de destination", +DlgLnkPopWinName : "Nom de la fen«´tre popup", +DlgLnkPopWinFeat : "Caract«±ristiques de la fen«´tre popup", +DlgLnkPopResize : "Taille modifiable", +DlgLnkPopLocation : "Barre d'adresses", +DlgLnkPopMenu : "Barre de menu", +DlgLnkPopScroll : "Barres de d«±filement", +DlgLnkPopStatus : "Barre d'«±tat", +DlgLnkPopToolbar : "Barre d'outils", +DlgLnkPopFullScrn : "Plein «±cran (IE)", +DlgLnkPopDependent : "D«±pendante (Netscape)", +DlgLnkPopWidth : "Largeur", +DlgLnkPopHeight : "Hauteur", +DlgLnkPopLeft : "Position «¢ partir de la gauche", +DlgLnkPopTop : "Position «¢ partir du haut", + +DlnLnkMsgNoUrl : "Veuillez saisir l'URL", +DlnLnkMsgNoEMail : "Veuillez saisir l'adresse e-mail", +DlnLnkMsgNoAnchor : "Veuillez s«±lectionner une ancre", +DlnLnkMsgInvPopName : "Le nom de la fen«´tre popup doit commencer par une lettre et ne doit pas contenir d'espace", + +// Color Dialog +DlgColorTitle : "S«±lectionner", +DlgColorBtnClear : "Effacer", +DlgColorHighlight : "Pr«±visualisation", +DlgColorSelected : "S«±lectionn«±", + +// Smiley Dialog +DlgSmileyTitle : "Ins«±rer un Emoticon", + +// Special Character Dialog +DlgSpecialCharTitle : "Ins«±rer un caract«²re sp«±cial", + +// Table Dialog +DlgTableTitle : "Propri«±t«±s du tableau", +DlgTableRows : "Lignes", +DlgTableColumns : "Colonnes", +DlgTableBorder : "Taille de la bordure", +DlgTableAlign : "Alignement", +DlgTableAlignNotSet : "", +DlgTableAlignLeft : "Gauche", +DlgTableAlignCenter : "Centr«±", +DlgTableAlignRight : "Droite", +DlgTableWidth : "Largeur", +DlgTableWidthPx : "pixels", +DlgTableWidthPc : "pourcentage", +DlgTableHeight : "Hauteur", +DlgTableCellSpace : "Espacement", +DlgTableCellPad : "Contour", +DlgTableCaption : "Titre", +DlgTableSummary : "R«±sum«±", + +// Table Cell Dialog +DlgCellTitle : "Propri«±t«±s de la cellule", +DlgCellWidth : "Largeur", +DlgCellWidthPx : "pixels", +DlgCellWidthPc : "pourcentage", +DlgCellHeight : "Hauteur", +DlgCellWordWrap : "Retour «¢ la ligne", +DlgCellWordWrapNotSet : "", +DlgCellWordWrapYes : "Oui", +DlgCellWordWrapNo : "Non", +DlgCellHorAlign : "Alignement horizontal", +DlgCellHorAlignNotSet : "", +DlgCellHorAlignLeft : "Gauche", +DlgCellHorAlignCenter : "Centr«±", +DlgCellHorAlignRight: "Droite", +DlgCellVerAlign : "Alignement vertical", +DlgCellVerAlignNotSet : "", +DlgCellVerAlignTop : "Haut", +DlgCellVerAlignMiddle : "Milieu", +DlgCellVerAlignBottom : "Bas", +DlgCellVerAlignBaseline : "Bas du texte", +DlgCellRowSpan : "Lignes fusionn«±es", +DlgCellCollSpan : "Colonnes fusionn«±es", +DlgCellBackColor : "Couleur de fond", +DlgCellBorderColor : "Couleur de bordure", +DlgCellBtnSelect : "S«±lectionner...", + +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Chercher et Remplacer", + +// Find Dialog +DlgFindTitle : "Chercher", +DlgFindFindBtn : "Chercher", +DlgFindNotFoundMsg : "Le texte indiqu«± est introuvable.", + +// Replace Dialog +DlgReplaceTitle : "Remplacer", +DlgReplaceFindLbl : "Rechercher:", +DlgReplaceReplaceLbl : "Remplacer par:", +DlgReplaceCaseChk : "Respecter la casse", +DlgReplaceReplaceBtn : "Remplacer", +DlgReplaceReplAllBtn : "Tout remplacer", +DlgReplaceWordChk : "Mot entier", + +// Paste Operations / Dialog +PasteErrorCut : "Les param«²tres de s«±curit«± de votre navigateur emp«´chent l'«±diteur de couper automatiquement vos donn«±es. Veuillez utiliser les «±quivalents claviers (Ctrl+X).", +PasteErrorCopy : "Les param«²tres de s«±curit«± de votre navigateur emp«´chent l'«±diteur de copier automatiquement vos donn«±es. Veuillez utiliser les «±quivalents claviers (Ctrl+C).", + +PasteAsText : "Coller comme texte", +PasteFromWord : "Coller «¢ partir de Word", + +DlgPasteMsg2 : "Veuillez coller dans la zone ci-dessous en utilisant le clavier (Ctrl+V) et appuyer sur OK.", +DlgPasteSec : "A cause des param«²tres de s«±curit«± de votre navigateur, l'«±diteur ne peut acc«±der au presse-papier directement. Vous devez coller «¢ nouveau le contenu dans cette fen«´tre.", +DlgPasteIgnoreFont : "Ignorer les polices de caract«²res", +DlgPasteRemoveStyles : "Supprimer les styles", + +// Color Picker +ColorAutomatic : "Automatique", +ColorMoreColors : "Plus de couleurs...", + +// Document Properties +DocProps : "Propri«±t«±s du document", + +// Anchor Dialog +DlgAnchorTitle : "Propri«±t«±s de l'ancre", +DlgAnchorName : "Nom de l'ancre", +DlgAnchorErrorName : "Veuillez saisir le nom de l'ancre", + +// Speller Pages Dialog +DlgSpellNotInDic : "Pas dans le dictionnaire", +DlgSpellChangeTo : "Changer en", +DlgSpellBtnIgnore : "Ignorer", +DlgSpellBtnIgnoreAll : "Ignorer tout", +DlgSpellBtnReplace : "Remplacer", +DlgSpellBtnReplaceAll : "Remplacer tout", +DlgSpellBtnUndo : "Annuler", +DlgSpellNoSuggestions : "- Pas de suggestion -", +DlgSpellProgress : "V«±rification d'orthographe en cours...", +DlgSpellNoMispell : "V«±rification d'orthographe termin«±e: pas d'erreur trouv«±e", +DlgSpellNoChanges : "V«±rification d'orthographe termin«±e: Pas de modifications", +DlgSpellOneChange : "V«±rification d'orthographe termin«±e: Un mot modifi«±", +DlgSpellManyChanges : "V«±rification d'orthographe termin«±e: %1 mots modifi«±s", + +IeSpellDownload : "Le Correcteur d'orthographe n'est pas install«±. Souhaitez-vous le t«±l«±charger maintenant?", + +// Button Dialog +DlgButtonText : "Texte (Valeur)", +DlgButtonType : "Type", +DlgButtonTypeBtn : "Bouton", +DlgButtonTypeSbm : "Soumettre", +DlgButtonTypeRst : "R«±initialiser", + +// Checkbox and Radio Button Dialogs +DlgCheckboxName : "Nom", +DlgCheckboxValue : "Valeur", +DlgCheckboxSelected : "S«±lectionn«±", + +// Form Dialog +DlgFormName : "Nom", +DlgFormAction : "Action", +DlgFormMethod : "M«±thode", + +// Select Field Dialog +DlgSelectName : "Nom", +DlgSelectValue : "Valeur", +DlgSelectSize : "Taille", +DlgSelectLines : "lignes", +DlgSelectChkMulti : "S«±lection multiple", +DlgSelectOpAvail : "Options disponibles", +DlgSelectOpText : "Texte", +DlgSelectOpValue : "Valeur", +DlgSelectBtnAdd : "Ajouter", +DlgSelectBtnModify : "Modifier", +DlgSelectBtnUp : "Monter", +DlgSelectBtnDown : "Descendre", +DlgSelectBtnSetValue : "Valeur s«±lectionn«±e", +DlgSelectBtnDelete : "Supprimer", + +// Textarea Dialog +DlgTextareaName : "Nom", +DlgTextareaCols : "Colonnes", +DlgTextareaRows : "Lignes", + +// Text Field Dialog +DlgTextName : "Nom", +DlgTextValue : "Valeur", +DlgTextCharWidth : "Largeur en caract«²res", +DlgTextMaxChars : "Nombre maximum de caract«²res", +DlgTextType : "Type", +DlgTextTypeText : "Texte", +DlgTextTypePass : "Mot de passe", + +// Hidden Field Dialog +DlgHiddenName : "Nom", +DlgHiddenValue : "Valeur", + +// Bulleted List Dialog +BulletedListProp : "Propri«±t«±s de liste «¢ puces", +NumberedListProp : "Propri«±t«±s de liste num«±rot«±e", +DlgLstStart : "D«±but", +DlgLstType : "Type", +DlgLstTypeCircle : "Cercle", +DlgLstTypeDisc : "Disque", +DlgLstTypeSquare : "Carr«±", +DlgLstTypeNumbers : "Nombres (1, 2, 3)", +DlgLstTypeLCase : "Lettres minuscules (a, b, c)", +DlgLstTypeUCase : "Lettres majuscules (A, B, C)", +DlgLstTypeSRoman : "Chiffres romains minuscules (i, ii, iii)", +DlgLstTypeLRoman : "Chiffres romains majuscules (I, II, III)", + +// Document Properties Dialog +DlgDocGeneralTab : "G«±n«±ral", +DlgDocBackTab : "Fond", +DlgDocColorsTab : "Couleurs et Marges", +DlgDocMetaTab : "M«±ta-Donn«±es", + +DlgDocPageTitle : "Titre de la page", +DlgDocLangDir : "Sens d'«±criture", +DlgDocLangDirLTR : "De la gauche vers la droite (LTR)", +DlgDocLangDirRTL : "De la droite vers la gauche (RTL)", +DlgDocLangCode : "Code langue", +DlgDocCharSet : "Encodage de caract«²re", +DlgDocCharSetCE : "Europe Centrale", +DlgDocCharSetCT : "Chinois Traditionnel (Big5)", +DlgDocCharSetCR : "Cyrillique", +DlgDocCharSetGR : "Grecque", +DlgDocCharSetJP : "Japonais", +DlgDocCharSetKR : "Cor«±en", +DlgDocCharSetTR : "Turcque", +DlgDocCharSetUN : "Unicode (UTF-8)", +DlgDocCharSetWE : "Occidental", +DlgDocCharSetOther : "Autre encodage de caract«²re", + +DlgDocDocType : "Type de document", +DlgDocDocTypeOther : "Autre type de document", +DlgDocIncXHTML : "Inclure les d«±clarations XHTML", +DlgDocBgColor : "Couleur de fond", +DlgDocBgImage : "Image de fond", +DlgDocBgNoScroll : "Image fixe sans d«±filement", +DlgDocCText : "Texte", +DlgDocCLink : "Lien", +DlgDocCVisited : "Lien visit«±", +DlgDocCActive : "Lien activ«±", +DlgDocMargins : "Marges", +DlgDocMaTop : "Haut", +DlgDocMaLeft : "Gauche", +DlgDocMaRight : "Droite", +DlgDocMaBottom : "Bas", +DlgDocMeIndex : "Mots-cl«±s (s«±par«±s par des virgules)", +DlgDocMeDescr : "Description", +DlgDocMeAuthor : "Auteur", +DlgDocMeCopy : "Copyright", +DlgDocPreview : "Pr«±visualisation", + +// Templates Dialog +Templates : "Mod«²les", +DlgTemplatesTitle : "Mod«²les de contenu", +DlgTemplatesSelMsg : "S«±lectionner le mod«²le «¢ ouvrir dans l'«±diteur
      (le contenu actuel sera remplac«±):", +DlgTemplatesLoading : "Chargement de la liste des mod«²les. Veuillez patienter...", +DlgTemplatesNoTpl : "(Aucun mod«²le disponible)", +DlgTemplatesReplace : "Remplacer tout le contenu actuel", + +// About Dialog +DlgAboutAboutTab : "ª¡ propos de", +DlgAboutBrowserInfoTab : "Navigateur", +DlgAboutLicenseTab : "License", +DlgAboutVersion : "Version", +DlgAboutInfo : "Pour plus d'informations, visiter" +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fr.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fr.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/fr.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Ins«±rer/modifier le lien", RemoveLink : "Supprimer le lien", Anchor : "Ins«±rer/modifier l'ancre", +AnchorDelete : "Supprimer l'ancre", InsertImageLbl : "Image", InsertImage : "Ins«±rer/modifier l'image", InsertFlashLbl : "Animation Flash", @@ -70,6 +71,7 @@ BlockJustify : "Texte justifi«±", DecreaseIndent : "Diminuer le retrait", IncreaseIndent : "Augmenter le retrait", +Blockquote : "Citation", Undo : "Annuler", Redo : "Refaire", NumberedListLbl : "Liste num«±rot«±e", @@ -103,20 +105,27 @@ ImageButton : "Bouton image", FitWindow : "Edition pleine page", +ShowBlocks : "Afficher les blocs", // Context Menu EditLink : "Modifier le lien", CellCM : "Cellule", RowCM : "Ligne", ColumnCM : "Colonne", -InsertRow : "Ins«±rer une ligne", +InsertRowAfter : "Ins«±rer une ligne apr«²s", +InsertRowBefore : "Ins«±rer une ligne avant", DeleteRows : "Supprimer des lignes", -InsertColumn : "Ins«±rer une colonne", +InsertColumnAfter : "Ins«±rer une colonne apr«²s", +InsertColumnBefore : "Ins«±rer une colonne avant", DeleteColumns : "Supprimer des colonnes", -InsertCell : "Ins«±rer une cellule", +InsertCellAfter : "Ins«±rer une cellule apr«²s", +InsertCellBefore : "Ins«±rer une cellule avant", DeleteCells : "Supprimer des cellules", MergeCells : "Fusionner les cellules", -SplitCell : "Scinder les cellules", +MergeRight : "Fusionner «¢ droite", +MergeDown : "Fusionner en bas", +HorizontalSplitCell : "Scinder la cellule horizontalement", +VerticalSplitCell : "Scinder la cellule verticalement", TableDelete : "Supprimer le tableau", CellProperties : "Propri«±t«±s de cellule", TableProperties : "Propri«±t«±s du tableau", @@ -134,7 +143,7 @@ TextareaProp : "Propri«±t«±s de la zone de texte", FormProp : "Propri«±t«±s du formulaire", -FontFormats : "Normal;Format«±;Adresse;En-t«´te 1;En-t«´te 2;En-t«´te 3;En-t«´te 4;En-t«´te 5;En-t«´te 6;Normal (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Format«±;Adresse;En-t«´te 1;En-t«´te 2;En-t«´te 3;En-t«´te 4;En-t«´te 5;En-t«´te 6;Normal (DIV)", // Alerts and Messages ProcessingXHTML : "Calcul XHTML. Veuillez patienter...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "S«±lectionner une ancre", DlgLnkAnchorByName : "Par nom", DlgLnkAnchorById : "Par id", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Pas d'ancre disponible dans le document)", DlgLnkEMail : "Adresse E-Mail", DlgLnkEMailSubject : "Sujet du message", DlgLnkEMailBody : "Corps du message", @@ -237,7 +246,7 @@ DlgLnkBtnUpload : "Envoyer sur le serveur", DlgLnkTarget : "Destination", -DlgLnkTargetFrame : "", +DlgLnkTargetFrame : "", DlgLnkTargetPopup : "", DlgLnkTargetBlank : "Nouvelle fen«´tre (_blank)", DlgLnkTargetParent : "Fen«´tre m«²re (_parent)", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Bordure", DlgCellBtnSelect : "Choisir...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Chercher et Remplacer", + // Find Dialog DlgFindTitle : "Chercher", DlgFindFindBtn : "Chercher", @@ -344,10 +356,9 @@ PasteFromWord : "Coller «¢ partir de Word", DlgPasteMsg2 : "Veuillez coller dans la zone ci-dessous en utilisant le clavier (Ctrl+V) et cliquez sur OK.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "A cause des param«²tres de s«±curit«± de votre navigateur, l'«±diteur ne peut acc«±der au presse-papier directement. Vous devez coller «¢ nouveau le contenu dans cette fen«´tre.", DlgPasteIgnoreFont : "Ignorer les polices de caract«²res", DlgPasteRemoveStyles : "Supprimer les styles", -DlgPasteCleanBox : "Effacer le contenu", // Color Picker ColorAutomatic : "Automatique", @@ -459,7 +470,7 @@ DlgDocCharSetCT : "Chinois Traditionnel (Big5)", DlgDocCharSetCR : "Cyrillique", DlgDocCharSetGR : "Grec", -DlgDocCharSetJP : "Japanais", +DlgDocCharSetJP : "Japonais", DlgDocCharSetKR : "Cor«±en", DlgDocCharSetTR : "Turc", DlgDocCharSetUN : "Unicode (UTF-8)", @@ -498,7 +509,7 @@ // About Dialog DlgAboutAboutTab : "A propos de", DlgAboutBrowserInfoTab : "Navigateur", -DlgAboutLicenseTab : "License", -DlgAboutVersion : "version", +DlgAboutLicenseTab : "Licence", +DlgAboutVersion : "Version", DlgAboutInfo : "Pour plus d'informations, aller «¢" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/gl.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/gl.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/gl.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Inserir/Editar Ligaz«Ñn", RemoveLink : "Eliminar Ligaz«Ñn", Anchor : "Inserir/Editar Referencia", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Imaxe", InsertImage : "Inserir/Editar Imaxe", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Xustificado", DecreaseIndent : "Disminuir Sangr«¿a", IncreaseIndent : "Aumentar Sangr«¿a", +Blockquote : "Blockquote", //MISSING Undo : "Desfacer", Redo : "Refacer", NumberedListLbl : "Lista Numerada", @@ -103,20 +105,27 @@ ImageButton : "Bot«Ñn de Imaxe", FitWindow : "Maximizar o tama«Ðo do editor", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "Editar Ligaz«Ñn", CellCM : "Cela", RowCM : "Fila", ColumnCM : "Columna", -InsertRow : "Inserir Fila", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Borrar Filas", -InsertColumn : "Inserir Columna", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "Borrar Columnas", -InsertCell : "Inserir Cela", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "Borrar Cela", MergeCells : "Unir Celas", -SplitCell : "Partir Celas", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Borrar T«¡boa", CellProperties : "Propriedades da Cela", TableProperties : "Propriedades da T«¡boa", @@ -134,7 +143,7 @@ TextareaProp : "Propriedades da ª¡rea de Texto", FormProp : "Propriedades do Formulario", -FontFormats : "Normal;Formateado;Enderezo;Enacabezado 1;Encabezado 2;Encabezado 3;Encabezado 4;Encabezado 5;Encabezado 6;Paragraph (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formateado;Enderezo;Enacabezado 1;Encabezado 2;Encabezado 3;Encabezado 4;Encabezado 5;Encabezado 6;Paragraph (DIV)", // Alerts and Messages ProcessingXHTML : "Procesando XHTML. Por facor, agarde...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Seleccionar unha Referencia", DlgLnkAnchorByName : "Por Nome de Referencia", DlgLnkAnchorById : "Por Element Id", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Non hai referencias disponibles no documento)", DlgLnkEMail : "Enderezo de E-Mail", DlgLnkEMailSubject : "Asunto do Mensaxe", DlgLnkEMailBody : "Corpo do Mensaxe", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Color de Borde", DlgCellBtnSelect : "Seleccionar...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "Procurar", DlgFindFindBtn : "Procurar", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Ignorar as definici«Ñns de Tipograf«¿a", DlgPasteRemoveStyles : "Eliminar as definici«Ñns de Estilos", -DlgPasteCleanBox : "Limpar o Cadro", // Color Picker ColorAutomatic : "Autom«¡tico", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Licencia", DlgAboutVersion : "versi«Ñn", DlgAboutInfo : "Para m«¡is informaci«Ñn visitar:" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/he.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/he.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/he.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "?????/????? ?????", RemoveLink : "???? ??????", Anchor : "?????/????? ????? ?????", +AnchorDelete : "??? ????? ?????", InsertImageLbl : "?????", InsertImage : "?????/????? ?????", InsertFlashLbl : "????", @@ -70,6 +71,7 @@ BlockJustify : "????? ???????", DecreaseIndent : "????? ?????????", IncreaseIndent : "????? ?????????", +Blockquote : "???? ?????", Undo : "????? ??? ?????", Redo : "???? ?? ??? ?????", NumberedListLbl : "????? ???????", @@ -103,20 +105,27 @@ ImageButton : "????? ?????", FitWindow : "???? ?? ???? ?????", +ShowBlocks : "??? ??????", // Context Menu EditLink : "????? ?????", CellCM : "??", RowCM : "????", ColumnCM : "?????", -InsertRow : "????? ????", +InsertRowAfter : "???? ???? ????", +InsertRowBefore : "???? ???? ????", DeleteRows : "????? ?????", -InsertColumn : "????? ?????", +InsertColumnAfter : "???? ????? ????", +InsertColumnBefore : "???? ????? ????", DeleteColumns : "????? ??????", -InsertCell : "????? ??", +InsertCellAfter : "???? ?? ????", +InsertCellBefore : "???? ?? ????", DeleteCells : "????? ????", MergeCells : "????? ????", -SplitCell : "????? ????", +MergeRight : "??? ?????", +MergeDown : "??? ????", +HorizontalSplitCell : "??? ?? ??????", +VerticalSplitCell : "??? ?? ?????", TableDelete : "??? ????", CellProperties : "?????? ???", TableProperties : "?????? ?????", @@ -134,7 +143,7 @@ TextareaProp : "?????? ????? ????", FormProp : "?????? ????", -FontFormats : "??????;???;?????;?????;????? 2;????? 3;????? 4;????? 5;????? 6", //REVIEW : Check _getfontformat.html +FontFormats : "??????;???;?????;?????;????? 2;????? 3;????? 4;????? 5;????? 6", // Alerts and Messages ProcessingXHTML : "???? XHTML, ?? ??????...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "????? ????", DlgLnkAnchorByName : "??''? ?? ?????", DlgLnkAnchorById : "??''? ????? (Id) ?????", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(??? ?????? ?????? ???)", DlgLnkEMail : "????? ????''?", DlgLnkEMailSubject : "???? ??????", DlgLnkEMailBody : "??? ??????", @@ -322,6 +331,9 @@ DlgCellBorderColor : "??? ?????", DlgCellBtnSelect : "?????...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "??? ?????", + // Find Dialog DlgFindTitle : "?????", DlgFindFindBtn : "?????", @@ -344,10 +356,9 @@ PasteFromWord : "????? ?-????", DlgPasteMsg2 : "??? ???? ???? ?????? ??????? (Ctrl+V) ???? ?? ?????.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "??? ?????? ????? ??????, ?? ???? ???? ?? ??? ??????? (clipboard) ????? ?????.??? ??? ???? ??? ????? ??.", DlgPasteIgnoreFont : "????? ??????? ??? ????", DlgPasteRemoveStyles : "??? ?????? ?????", -DlgPasteCleanBox : "????? ?????", // Color Picker ColorAutomatic : "???????", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "?????", DlgAboutVersion : "?????", DlgAboutInfo : "???? ???? ???? ????? ???:" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/hi.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/hi.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/hi.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "???? ???????/??????", RemoveLink : "???? ??????", Anchor : "???? ???????/??????", +AnchorDelete : "???? ??????", InsertImageLbl : "??????", InsertImage : "?????? ???????/??????", InsertFlashLbl : "?????", @@ -70,6 +71,7 @@ BlockJustify : "????? ????????", DecreaseIndent : "???????? ?? ????", IncreaseIndent : "???????? ??????", +Blockquote : "?????-???", Undo : "?????", Redo : "????", NumberedListLbl : "????? ????", @@ -103,22 +105,29 @@ ImageButton : "?????? ???", FitWindow : "????? ???? ?? ??? ???? ?? ??????", +ShowBlocks : "????? ???????", // Context Menu EditLink : "???? ??????", CellCM : "????", RowCM : "??????", ColumnCM : "????", -InsertRow : "?????? ??????? ????", +InsertRowAfter : "??? ??? ?????? ?????", +InsertRowBefore : "???? ?????? ?????", DeleteRows : "????????? ????? ????", -InsertColumn : "???? ??????? ????", -DeleteColumns : "???? ????? ????", -InsertCell : "??? ??????? ????", -DeleteCells : "??? ????? ????", -MergeCells : "??? ???????", -SplitCell : "??? ??? ????", +InsertColumnAfter : "??? ??? ???? ?????", +InsertColumnBefore : "???? ???? ?????", +DeleteColumns : "???? ????? ????", +InsertCellAfter : "??? ??? ??? ?????", +InsertCellBefore : "???? ??? ?????", +DeleteCells : "??? ????? ????", +MergeCells : "??? ???????", +MergeRight : "????? ????", +MergeDown : "???? ???? ????", +HorizontalSplitCell : "??? ?? ??????? ?????? ??? ??????? ????", +VerticalSplitCell : "??? ?? ???????? ??? ??????? ????", TableDelete : "???? ????? ????", -CellProperties : "??? ??????????", +CellProperties : "??? ??????????", TableProperties : "???? ??????????", ImageProperties : "?????? ??????????", FlashProperties : "????? ??????????", @@ -134,7 +143,7 @@ TextareaProp : "??????? ????? ??????????", FormProp : "????? ??????????", -FontFormats : "??????;?????????;???;?????? 1;?????? 2;?????? 3;?????? 4;?????? 5;?????? 6;?????? (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "??????;?????????;???;?????? 1;?????? 2;?????? 3;?????? 4;?????? 5;?????? 6;?????? (DIV)", // Alerts and Messages ProcessingXHTML : "XHTML ??????? ?? ??? ??? ??? ?????...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "???? ?????", DlgLnkAnchorByName : "???? ??? ??", DlgLnkAnchorById : "???????? Id ??", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(??????????? ??? ?????? ?? ??????)", DlgLnkEMail : "?-??? ???", DlgLnkEMailSubject : "????? ????", DlgLnkEMailBody : "?????", @@ -279,7 +288,7 @@ // Table Dialog DlgTableTitle : "???? ??????????", DlgTableRows : "?????????", -DlgTableColumns : "????", +DlgTableColumns : "????", DlgTableBorder : "?????? ????", DlgTableAlign : "???????????", DlgTableAlignNotSet : "", @@ -287,18 +296,18 @@ DlgTableAlignCenter : "??? ???", DlgTableAlignRight : "?????", DlgTableWidth : "?????", -DlgTableWidthPx : "???????", +DlgTableWidthPx : "???????", DlgTableWidthPc : "???????", DlgTableHeight : "?????", -DlgTableCellSpace : "??? ????", -DlgTableCellPad : "??? ??????", +DlgTableCellSpace : "??? ????", +DlgTableCellPad : "??? ??????", DlgTableCaption : "??????", DlgTableSummary : "??????", // Table Cell Dialog -DlgCellTitle : "??? ??????????", +DlgCellTitle : "??? ??????????", DlgCellWidth : "?????", -DlgCellWidthPx : "???????", +DlgCellWidthPx : "???????", DlgCellWidthPc : "???????", DlgCellHeight : "?????", DlgCellWordWrap : "???? ???", @@ -317,11 +326,14 @@ DlgCellVerAlignBottom : "????", DlgCellVerAlignBaseline : "???????", DlgCellRowSpan : "?????? ?????", -DlgCellCollSpan : "???? ?????", +DlgCellCollSpan : "???? ?????", DlgCellBackColor : "???????????? ???", DlgCellBorderColor : "?????? ?? ???", DlgCellBtnSelect : "?????...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "????? ?? ?????", + // Find Dialog DlgFindTitle : "?????", DlgFindFindBtn : "?????", @@ -344,13 +356,12 @@ PasteFromWord : "????? (???? ??)", DlgPasteMsg2 : "Ctrl+V ?? ?????? ???? ????? ???? ?? ??? ?? ????.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "???? ??????? ?? ??????? ???? ??????? ?? ???K? ?????? ?? ????, ????? ???? ?????????? ???? ?? ???? ?? ???? ??. ???? ??? ?? ?????? ??? ?????? ????? ???? ????.", DlgPasteIgnoreFont : "????? ??????? ???????", DlgPasteRemoveStyles : "?????? ??????? ???????", -DlgPasteCleanBox : "????? ??? ????", // Color Picker -ColorAutomatic : "????????", +ColorAutomatic : "????????", ColorMoreColors : "?? ???...", // Document Properties @@ -392,7 +403,7 @@ // Form Dialog DlgFormName : "???", -DlgFormAction : "?????", +DlgFormAction : "??????", DlgFormMethod : "?????", // Select Field Dialog @@ -413,7 +424,7 @@ // Textarea Dialog DlgTextareaName : "???", -DlgTextareaCols : "????", +DlgTextareaCols : "????", DlgTextareaRows : "?????????", // Text Field Dialog @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "????????", DlgAboutVersion : "?????", DlgAboutInfo : "???? ??????? ?? ???? ???? ?????:" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/hr.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/hr.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/hr.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Ubaci/promijeni link", RemoveLink : "Ukloni link", Anchor : "Ubaci/promijeni sidro", +AnchorDelete : "Ukloni sidro", InsertImageLbl : "Slika", InsertImage : "Ubaci/promijeni sliku", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Blok poravnanje", DecreaseIndent : "Pomakni ulijevo", IncreaseIndent : "Pomakni udesno", +Blockquote : "Blockquote", Undo : "Poni«Þti", Redo : "Ponovi", NumberedListLbl : "Broj«­ana lista", @@ -103,20 +105,27 @@ ImageButton : "Image Button", FitWindow : "Pove««aj veli«­inu editora", +ShowBlocks : "Prika«öi blokove", // Context Menu EditLink : "Promijeni link", CellCM : "ª«elija", RowCM : "Red", ColumnCM : "Kolona", -InsertRow : "Ubaci red", +InsertRowAfter : "Ubaci red poslije", +InsertRowBefore : "Ubaci red prije", DeleteRows : "Izbri«Þi redove", -InsertColumn : "Ubaci kolonu", +InsertColumnAfter : "Ubaci kolonu poslije", +InsertColumnBefore : "Ubaci kolonu prije", DeleteColumns : "Izbri«Þi kolone", -InsertCell : "Ubaci ««elije", +InsertCellAfter : "Ubaci ««eliju poslije", +InsertCellBefore : "Ubaci ««eliju prije", DeleteCells : "Izbri«Þi ««elije", MergeCells : "Spoji ««elije", -SplitCell : "Razdvoji ««elije", +MergeRight : "Spoji desno", +MergeDown : "Spoji dolje", +HorizontalSplitCell : "Podijeli ««eliju vodoravno", +VerticalSplitCell : "Podijeli ««eliju okomito", TableDelete : "Izbri«Þi tablicu", CellProperties : "Svojstva ««elije", TableProperties : "Svojstva tablice", @@ -134,7 +143,7 @@ TextareaProp : "Textarea svojstva", FormProp : "Form svojstva", -FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", // Alerts and Messages ProcessingXHTML : "Obra©Âujem XHTML. Molimo pri«­ekajte...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Odaberi sidro", DlgLnkAnchorByName : "Po nazivu sidra", DlgLnkAnchorById : "Po Id elementa", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Nema dostupnih sidra)", DlgLnkEMail : "E-Mail adresa", DlgLnkEMailSubject : "Naslov", DlgLnkEMailBody : "Sadr«öaj poruke", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Boja okvira", DlgCellBtnSelect : "Odaberi...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Prona©Âi i zamijeni", + // Find Dialog DlgFindTitle : "Prona©Âi", DlgFindFindBtn : "Prona©Âi", @@ -344,10 +356,9 @@ PasteFromWord : "Zalijepi iz Worda", DlgPasteMsg2 : "Molimo zaljepite unutar doljnjeg okvira koriste««i tipkovnicu (Ctrl+V) i kliknite OK.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "Zbog sigurnosnih postavki Va«Þeg pretra«öiva«­a, editor nema direktan pristup Va«Þem me©Âuspremniku. Potrebno je ponovno zalijepiti tekst u ovaj prozor.", DlgPasteIgnoreFont : "Zanemari definiciju vrste fonta", DlgPasteRemoveStyles : "Ukloni definicije stilova", -DlgPasteCleanBox : "O«­isti okvir", // Color Picker ColorAutomatic : "Automatski", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Licenca", DlgAboutVersion : "ina«­ica", DlgAboutInfo : "Za vi«Þe informacija posjetite" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/hu.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/hu.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/hu.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Hivatkoz«¡s beilleszt«±se/m«Ñdos«¿t«¡sa", RemoveLink : "Hivatkoz«¡s t«Órl«±se", Anchor : "Horgony beilleszt«±se/szerkeszt«±se", +AnchorDelete : "Horgony elt«¡vol«¿t«¡sa", InsertImageLbl : "K«±p", InsertImage : "K«±p beilleszt«±se/m«Ñdos«¿t«¡sa", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Sorkiz«¡rt", DecreaseIndent : "Beh«âz«¡s cs«Ókkent«±se", IncreaseIndent : "Beh«âz«¡s n«Óvel«±se", +Blockquote : "Id«±zet blokk", Undo : "Visszavon«¡s", Redo : "Ism«±tl«±s", NumberedListLbl : "Sz«¡moz«¡s", @@ -103,20 +105,27 @@ ImageButton : "K«±pgomb", FitWindow : "Maximaliz«¡l«¡s", +ShowBlocks : "Blokkok megjelen«¿t«±se", // Context Menu EditLink : "Hivatkoz«¡s m«Ñdos«¿t«¡sa", CellCM : "Cella", RowCM : "Sor", ColumnCM : "Oszlop", -InsertRow : "Sor besz«âr«¡sa", +InsertRowAfter : "Sor beilleszt«±se az aktu«¡lis sor m«Óg«±", +InsertRowBefore : "Sor beilleszt«±se az aktu«¡lis sor el«±", DeleteRows : "Sorok t«Órl«±se", -InsertColumn : "Oszlop besz«âr«¡sa", +InsertColumnAfter : "Oszlop beilleszt«±se az aktu«¡lis oszlop m«Óg«±", +InsertColumnBefore : "Oszlop beilleszt«±se az aktu«¡lis oszlop el«±", DeleteColumns : "Oszlopok t«Órl«±se", -InsertCell : "Cella besz«âr«¡sa", +InsertCellAfter : "Cella beilleszt«±se az aktu«¡lis cella m«Óg«±", +InsertCellBefore : "Cella beilleszt«±se az aktu«¡lis cella el«±", DeleteCells : "Cell«¡k t«Órl«±se", MergeCells : "Cell«¡k egyes«¿t«±se", -SplitCell : "Cella sz«±tv«¡laszt«¡sa", +MergeRight : "Cell«¡k egyes«¿t«±se jobbra", +MergeDown : "Cell«¡k egyes«¿t«±se lefel«±", +HorizontalSplitCell : "Cell«¡k sz«±tv«¡laszt«¡sa v«¿zszintesen", +VerticalSplitCell : "Cell«¡k sz«±tv«¡laszt«¡sa f«ägg«Ölegesen", TableDelete : "T«¡bl«¡zat t«Órl«±se", CellProperties : "Cella tulajdons«¡gai", TableProperties : "T«¡bl«¡zat tulajdons«¡gai", @@ -134,7 +143,7 @@ TextareaProp : "Sz«Óvegter«älet tulajdons«¡gai", FormProp : "ªèrlap tulajdons«¡gai", -FontFormats : "Norm«¡l;Form«¡zott;C«¿msor;Fejl«±c 1;Fejl«±c 2;Fejl«±c 3;Fejl«±c 4;Fejl«±c 5;Fejl«±c 6;Bekezd«±s (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Norm«¡l;Form«¡zott;C«¿msor;Fejl«±c 1;Fejl«±c 2;Fejl«±c 3;Fejl«±c 4;Fejl«±c 5;Fejl«±c 6;Bekezd«±s (DIV)", // Alerts and Messages ProcessingXHTML : "XHTML feldolgoz«¡sa. K«±rem v«¡rjon...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Horgony v«¡laszt«¡sa", DlgLnkAnchorByName : "Horgony n«±v szerint", DlgLnkAnchorById : "Azonos«¿t«Ñ szerint", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Nincs horgony a dokumentumban)", DlgLnkEMail : "E-Mail c«¿m", DlgLnkEMailSubject : "ªäzenet t«¡rgya", DlgLnkEMailBody : "ªäzenet", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Szeg«±lysz«¿n", DlgCellBtnSelect : "Kiv«¡laszt«¡s...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Keres«±s «±s csere", + // Find Dialog DlgFindTitle : "Keres«±s", DlgFindFindBtn : "Keres«±s", @@ -344,10 +356,9 @@ PasteFromWord : "Beilleszt«±s Word-b«Öl", DlgPasteMsg2 : "M«¡solja be az al«¡bbi mez«Öbe a Ctrl+V billenty«èk lenyom«¡s«¡val, majd nyomjon Rendben-t.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "A b«Óng«±sz«Ö biztons«¡gi be«¡ll«¿t«¡sai miatt a szerkeszt«Ö nem k«±pes hozz«¡f«±rni a v«¡g«Ñlap adataihoz. Illeszd be «âjra ebben az ablakban.", DlgPasteIgnoreFont : "Bet«è form«¡z«¡sok megsz«äntet«±se", DlgPasteRemoveStyles : "St«¿lusok elt«¡vol«¿t«¡sa", -DlgPasteCleanBox : "T«Órl«±s", // Color Picker ColorAutomatic : "Automatikus", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Licensz", DlgAboutVersion : "verzi«Ñ", DlgAboutInfo : "Tov«¡bbi inform«¡ci«Ñk«±rt l«¡togasson el ide:" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/it.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/it.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/it.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Inserisci/Modifica collegamento", RemoveLink : "Elimina collegamento", Anchor : "Inserisci/Modifica Ancora", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Immagine", InsertImage : "Inserisci/Modifica immagine", InsertFlashLbl : "Oggetto Flash", @@ -70,6 +71,7 @@ BlockJustify : "Giustifica", DecreaseIndent : "Riduci rientro", IncreaseIndent : "Aumenta rientro", +Blockquote : "Blockquote", //MISSING Undo : "Annulla", Redo : "Ripristina", NumberedListLbl : "Elenco numerato", @@ -103,20 +105,27 @@ ImageButton : "Bottone immagine", FitWindow : "Massimizza l'area dell'editor", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "Modifica collegamento", CellCM : "Cella", RowCM : "Riga", ColumnCM : "Colonna", -InsertRow : "Inserisci riga", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Elimina righe", -InsertColumn : "Inserisci colonna", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "Elimina colonne", -InsertCell : "Inserisci cella", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "Elimina celle", MergeCells : "Unisce celle", -SplitCell : "Dividi celle", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Cancella Tabella", CellProperties : "Propriet«¢ cella", TableProperties : "Propriet«¢ tabella", @@ -134,7 +143,7 @@ TextareaProp : "Propriet«¢ area di testo", FormProp : "Propriet«¢ modulo", -FontFormats : "Normale;Formattato;Indirizzo;Titolo 1;Titolo 2;Titolo 3;Titolo 4;Titolo 5;Titolo 6;Paragrafo (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normale;Formattato;Indirizzo;Titolo 1;Titolo 2;Titolo 3;Titolo 4;Titolo 5;Titolo 6;Paragrafo (DIV)", // Alerts and Messages ProcessingXHTML : "Elaborazione XHTML in corso. Attendere prego...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Scegli Ancora", DlgLnkAnchorByName : "Per Nome", DlgLnkAnchorById : "Per id elemento", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Nessuna ancora disponibile nel documento)", DlgLnkEMail : "Indirizzo E-Mail", DlgLnkEMailSubject : "Oggetto del messaggio", DlgLnkEMailBody : "Corpo del messaggio", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Colore bordo", DlgCellBtnSelect : "Scegli...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "Trova", DlgFindFindBtn : "Trova", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Ignora le definizioni di Font", DlgPasteRemoveStyles : "Rimuovi le definizioni di Stile", -DlgPasteCleanBox : "Svuota area di testo", // Color Picker ColorAutomatic : "Automatico", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Licenza", DlgAboutVersion : "versione", DlgAboutInfo : "Per maggiori informazioni visitare" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ja.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ja.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ja.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "¥ê¥ó¥¯ÁÞÆþ/ÊÔ½¸", RemoveLink : "¥ê¥ó¥¯ºï½ü", Anchor : "¥¢¥ó¥«¡¼ÁÞÆþ/ÊÔ½¸", +AnchorDelete : "¥¢¥ó¥«¡¼ºï½ü", InsertImageLbl : "¥¤¥á¡¼¥¸", InsertImage : "¥¤¥á¡¼¥¸ÁÞÆþ/ÊÔ½¸", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "ξü·¤¨", DecreaseIndent : "¥¤¥ó¥Ç¥ó¥È²ò½ü", IncreaseIndent : "¥¤¥ó¥Ç¥ó¥È", +Blockquote : "¥Ö¥í¥Ã¥¯°úÍÑ", Undo : "¸µ¤ËÌ᤹", Redo : "¤ä¤êľ¤·", NumberedListLbl : "ÃÊÍîÈÖ¹æ", @@ -103,20 +105,27 @@ ImageButton : "²èÁü¥Ü¥¿¥ó", FitWindow : "¥¨¥Ç¥£¥¿¥µ¥¤¥º¤òºÇÂç¤Ë¤·¤Þ¤¹", +ShowBlocks : "¥Ö¥í¥Ã¥¯É½¼¨", // Context Menu EditLink : "¥ê¥ó¥¯ÊÔ½¸", CellCM : "¥»¥ë", RowCM : "¹Ô", ColumnCM : "¥«¥é¥à", -InsertRow : "¹ÔÁÞÆþ", +InsertRowAfter : "Îó¤Î¸å¤ËÁÞÆþ", +InsertRowBefore : "Îó¤ÎÁ°¤ËÁÞÆþ", DeleteRows : "¹Ôºï½ü", -InsertColumn : "ÎóÁÞÆþ", +InsertColumnAfter : "¥«¥é¥à¤Î¸å¤ËÁÞÆþ", +InsertColumnBefore : "¥«¥é¥à¤ÎÁ°¤ËÁÞÆþ", DeleteColumns : "Îóºï½ü", -InsertCell : "¥»¥ëÁÞÆþ", +InsertCellAfter : "¥»¥ë¤Î¸å¤ËÁÞÆþ", +InsertCellBefore : "¥»¥ë¤ÎÁ°¤ËÁÞÆþ", DeleteCells : "¥»¥ëºï½ü", MergeCells : "¥»¥ë·ë¹ç", -SplitCell : "¥»¥ëʬ³ä", +MergeRight : "±¦¤Ë·ë¹ç", +MergeDown : "²¼¤Ë·ë¹ç", +HorizontalSplitCell : "¥»¥ë¤ò¿åÊ¿Êý¸þʬ³ä", +VerticalSplitCell : "¥»¥ë¤ò¿âľÊý¸þ¤Ëʬ³ä", TableDelete : "¥Æ¡¼¥Ö¥ëºï½ü", CellProperties : "¥»¥ë ¥×¥í¥Ñ¥Æ¥£", TableProperties : "¥Æ¡¼¥Ö¥ë ¥×¥í¥Ñ¥Æ¥£", @@ -134,7 +143,7 @@ TextareaProp : "¥Æ¥­¥¹¥È¥¨¥ê¥¢ ¥×¥í¥Ñ¥Æ¥£", FormProp : "¥Õ¥©¡¼¥à ¥×¥í¥Ñ¥Æ¥£", -FontFormats : "ɸ½à;½ñ¼°ÉÕ¤­;¥¢¥É¥ì¥¹;¸«½Ð¤· 1;¸«½Ð¤· 2;¸«½Ð¤· 3;¸«½Ð¤· 4;¸«½Ð¤· 5;¸«½Ð¤· 6;ɸ½à (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "ɸ½à;½ñ¼°ÉÕ¤­;¥¢¥É¥ì¥¹;¸«½Ð¤· 1;¸«½Ð¤· 2;¸«½Ð¤· 3;¸«½Ð¤· 4;¸«½Ð¤· 5;¸«½Ð¤· 6;ɸ½à (DIV)", // Alerts and Messages ProcessingXHTML : "XHTML½èÍýÃæ. ¤·¤Ð¤é¤¯¤ªÂÔ¤Á¤¯¤À¤µ¤¤...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "¥¢¥ó¥«¡¼¤òÁªÂò", DlgLnkAnchorByName : "¥¢¥ó¥«¡¼Ì¾", DlgLnkAnchorById : "¥¨¥ì¥á¥ó¥ÈID", -DlgLnkNoAnchors : "<¥É¥­¥å¥á¥ó¥È¤Ë¤ª¤¤¤ÆÍøÍѲÄǽ¤Ê¥¢¥ó¥«¡¼¤Ï¤¢¤ê¤Þ¤»¤ó¡£>", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(¥É¥­¥å¥á¥ó¥È¤Ë¤ª¤¤¤ÆÍøÍѲÄǽ¤Ê¥¢¥ó¥«¡¼¤Ï¤¢¤ê¤Þ¤»¤ó¡£)", DlgLnkEMail : "E-Mail ¥¢¥É¥ì¥¹", DlgLnkEMailSubject : "·ï̾", DlgLnkEMailBody : "ËÜʸ", @@ -322,6 +331,9 @@ DlgCellBorderColor : "¥Ü¡¼¥À¡¼¥«¥é¡¼", DlgCellBtnSelect : "ÁªÂò...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "¸¡º÷¤·¤ÆÃÖ´¹", + // Find Dialog DlgFindTitle : "¸¡º÷", DlgFindFindBtn : "¸¡º÷", @@ -344,10 +356,9 @@ PasteFromWord : "¥ï¡¼¥Éʸ¾Ï¤«¤éŽ¤êÉÕ¤±", DlgPasteMsg2 : "¥­¡¼¥Ü¡¼¥É(Ctrl+V)¤ò»ÈÍѤ·¤Æ¡¢¼¡¤ÎÆþÎÏ¥¨¥ê¥¢Æâ¤ÇŽ¤Ã¤Æ¡¢OK¤ò²¡¤·¤Æ¤¯¤À¤µ¤¤¡£", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "¥Ö¥é¥¦¥¶¤Î¥»¥­¥å¥ê¥Æ¥£ÀßÄê¤Ë¤è¤ê¡¢¥¨¥Ç¥£¥¿¤Ï¥¯¥ê¥Ã¥×¥Ü¡¼¥É¡¦¥Ç¡¼¥¿¤ËľÀÜ¥¢¥¯¥»¥¹¤¹¤ë¤³¤È¤¬¤Ç¤­¤Þ¤»¤ó¡£¤³¤Î¥¦¥£¥ó¥É¥¦¤ÏŽ¤êÉÕ¤±Áàºî¤ò¹Ô¤¦ÅÙ¤Ëɽ¼¨¤µ¤ì¤Þ¤¹¡£", DlgPasteIgnoreFont : "Font¥¿¥°¤ÎFace°À­¤ò̵»ë¤·¤Þ¤¹¡£", DlgPasteRemoveStyles : "¥¹¥¿¥¤¥ëÄêµÁ¤òºï½ü¤·¤Þ¤¹¡£", -DlgPasteCleanBox : "ÆþÎÏ¥¨¥ê¥¢¥¯¥ê¥¢", // Color Picker ColorAutomatic : "¼«Æ°", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "¥é¥¤¥»¥ó¥¹", DlgAboutVersion : "¥Ð¡¼¥¸¥ç¥ó", DlgAboutInfo : "¤è¤ê¾Ü¤·¤¤¾ðÊó¤Ï¤³¤Á¤é¤Ç" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/km.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/km.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/km.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "??????/?????? ??????", RemoveLink : "?????????", Anchor : "??????/?????? ??????", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "??????", InsertImage : "??????/?????? ??????", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "??????????", DecreaseIndent : "??????????????????", IncreaseIndent : "???????????????????", +Blockquote : "Blockquote", //MISSING Undo : "?????????", Redo : "??????????", NumberedListLbl : "????????????", @@ -103,20 +105,27 @@ ImageButton : "????????????", FitWindow : "Maximize the editor size", //MISSING +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "????????????", CellCM : "Cell", //MISSING RowCM : "Row", //MISSING ColumnCM : "Column", //MISSING -InsertRow : "??????????????", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "???????????", -InsertColumn : "???????????", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "????????", -InsertCell : "?????? ???", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "??????", MergeCells : "?????????", -SplitCell : "?????????", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "????????", CellProperties : "???????????", TableProperties : "?????????????", @@ -134,7 +143,7 @@ TextareaProp : "?????????????????????????", FormProp : "?????????????", -FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", // Alerts and Messages ProcessingXHTML : "????????????? XHTML ? ????????...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "??????????????", DlgLnkAnchorByName : "??????????????????", DlgLnkAnchorById : "??? Id", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(No anchors available in the document)", //MISSING DlgLnkEMail : "??????", DlgLnkEMailSubject : "?????????????", DlgLnkEMailBody : "??????", @@ -322,6 +331,9 @@ DlgCellBorderColor : "???????", DlgCellBtnSelect : "????????...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "???????", DlgFindFindBtn : "???????", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "??????????????????????????", DlgPasteRemoveStyles : "???????", -DlgPasteCleanBox : "????????????????????", // Color Picker ColorAutomatic : "????????????", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "License", //MISSING DlgAboutVersion : "??????", DlgAboutInfo : "???????????????????? ?????????" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ko.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ko.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ko.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "?? ??/??", RemoveLink : "?? ??", Anchor : "??? ??/??", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "???", InsertImage : "??? ??/??", InsertFlashLbl : "???", @@ -70,6 +71,7 @@ BlockJustify : "?? ??", DecreaseIndent : "????", IncreaseIndent : "????", +Blockquote : "Blockquote", //MISSING Undo : "??", Redo : "???", NumberedListLbl : "???? ??", @@ -102,22 +104,29 @@ SelectionField : "????", ImageButton : "?????", -FitWindow : "Maximize the editor size", //MISSING +FitWindow : "??? ???", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "?? ??", -CellCM : "Cell", //MISSING -RowCM : "Row", //MISSING -ColumnCM : "Column", //MISSING -InsertRow : "??? ??", +CellCM : "?/?(Cell)", +RowCM : "?(Row)", +ColumnCM : "?(Column)", +InsertRowAfter : "?? ? ??", +InsertRowBefore : "?? ? ??", DeleteRows : "??? ??", -InsertColumn : "??? ??", +InsertColumnAfter : "?? ? ??", +InsertColumnBefore : "?? ? ??", DeleteColumns : "??? ??", -InsertCell : "? ??", +InsertCellAfter : "?? ?/? ??", +InsertCellBefore : "?? ?/? ??", DeleteCells : "? ??", MergeCells : "? ???", -SplitCell : "? ???", -TableDelete : "Delete Table", //MISSING +MergeRight : "??? ???", +MergeDown : "?? ???", +HorizontalSplitCell : "?? ???", +VerticalSplitCell : "?? ???", +TableDelete : "? ??", CellProperties : "? ??", TableProperties : "? ??", ImageProperties : "??? ??", @@ -134,7 +143,7 @@ TextareaProp : "???? ??", FormProp : "? ??", -FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6", // Alerts and Messages ProcessingXHTML : "XHTML ???. ??? ???????.", @@ -145,9 +154,9 @@ UnknownCommand : "???? ?????. : \"%1\"", NotImplemented : "??? ???? ?????.", UnknownToolbarSet : "?? ??? ????. : \"%1\"", -NoActiveX : "Your browser's security settings could limit some features of the editor. You must enable the option \"Run ActiveX controls and plug-ins\". You may experience errors and notice missing features.", //MISSING -BrowseServerBlocked : "The resources browser could not be opened. Make sure that all popup blockers are disabled.", //MISSING -DialogBlocked : "It was not possible to open the dialog window. Make sure all popup blockers are disabled.", //MISSING +NoActiveX : "????? ?? ???? ?? ?? ??? ??? ??? ?? ? ????. \"???-?? ??? ??? ?\" ??? ???? ??? ??? ??? ??? ? ????.", +BrowseServerBlocked : "???? ??? ??? ????. ???? ??? ????? ???? ????.", +DialogBlocked : "??? ???? ? ? ????. ???? ??? ????? ???? ????.", // Dialogs DlgBtnOK : "?", @@ -198,7 +207,7 @@ DlgImgAlignBottom : "??", DlgImgAlignMiddle : "??", DlgImgAlignRight : "???", -DlgImgAlignTextTop : "???(Text Top)", +DlgImgAlignTextTop : "????", DlgImgAlignTop : "?", DlgImgPreview : "????", DlgImgAlertUrl : "??? URL? ??????", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "??? ??", DlgLnkAnchorByName : "??? ??", DlgLnkAnchorById : "??? ID", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(??? ???? ????.)", DlgLnkEMail : "??? ??", DlgLnkEMailSubject : "??", DlgLnkEMailBody : "??", @@ -262,7 +271,7 @@ DlnLnkMsgNoUrl : "?? URL? ??????.", DlnLnkMsgNoEMail : "?????? ??????.", DlnLnkMsgNoAnchor : "????? ??????.", -DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces", //MISSING +DlnLnkMsgInvPopName : "???? ???? ??? ???? ????.", // Color Dialog DlgColorTitle : "?? ??", @@ -322,6 +331,9 @@ DlgCellBorderColor : "??? ??", DlgCellBtnSelect : "??", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "?? & ???", + // Find Dialog DlgFindTitle : "??", DlgFindFindBtn : "??", @@ -344,10 +356,9 @@ PasteFromWord : "MS Word ???? ????", DlgPasteMsg2 : "???? (Ctrl+V) ? ???? ???? ???? OK ? ????.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "???? ?? ???? ??, ????? ??? ?? ??? ? ????. ? ?? ?? ???? ????.", DlgPasteIgnoreFont : "?? ?? ??", DlgPasteRemoveStyles : "??? ?? ??", -DlgPasteCleanBox : "??? ??", // Color Picker ColorAutomatic : "????", @@ -493,12 +504,12 @@ DlgTemplatesSelMsg : "????? ??? ???? ??????.
      (???? ??? ??? ?????.):", DlgTemplatesLoading : "??? ??? ????????. ??? ???????.", DlgTemplatesNoTpl : "(???? ????.)", -DlgTemplatesReplace : "Replace actual contents", //MISSING +DlgTemplatesReplace : "?? ?? ???", // About Dialog DlgAboutAboutTab : "About", DlgAboutBrowserInfoTab : "???? ??", DlgAboutLicenseTab : "License", //MISSING DlgAboutVersion : "??", -DlgAboutInfo : "For further information go to" -}; \ No newline at end of file +DlgAboutInfo : "? ?? ??? ???? ?? ???? ????." +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/lt.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/lt.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/lt.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "ªÆterpti/taisyti nuorod«¨", RemoveLink : "Panaikinti nuorod«¨", Anchor : "ªÆterpti/modifikuoti «öym«¸", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Vaizdas", InsertImage : "ªÆterpti/taisyti vaizd«¨", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Lygiuoti abi puses", DecreaseIndent : "Suma«öinti «Ætrauk«¨", IncreaseIndent : "Padidinti «Ætrauk«¨", +Blockquote : "Blockquote", //MISSING Undo : "At«Þaukti", Redo : "Atstatyti", NumberedListLbl : "Numeruotas s«¨ra«Þas", @@ -103,20 +105,27 @@ ImageButton : "Vaizdinis mygtukas", FitWindow : "Maximize the editor size", //MISSING +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "Taisyti nuorod«¨", CellCM : "Cell", //MISSING RowCM : "Row", //MISSING ColumnCM : "Column", //MISSING -InsertRow : "ªÆterpti eilut«¸", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "ªÞalinti eilutes", -InsertColumn : "ªÆterpti stulpel«Æ", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "ªÞalinti stulpelius", -InsertCell : "ªÆterpti langel«Æ", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "ªÞalinti langelius", MergeCells : "Sujungti langelius", -SplitCell : "Skaidyti langelius", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "ªÞalinti lentel«¸", CellProperties : "Langelio savyb«¶s", TableProperties : "Lentel«¶s savyb«¶s", @@ -134,7 +143,7 @@ TextareaProp : "Teksto srities savyb«¶s", FormProp : "Formos savyb«¶s", -FontFormats : "Normalus;Formuotas;Kreipinio;Antra«Þtinis 1;Antra«Þtinis 2;Antra«Þtinis 3;Antra«Þtinis 4;Antra«Þtinis 5;Antra«Þtinis 6", //REVIEW : Check _getfontformat.html +FontFormats : "Normalus;Formuotas;Kreipinio;Antra«Þtinis 1;Antra«Þtinis 2;Antra«Þtinis 3;Antra«Þtinis 4;Antra«Þtinis 5;Antra«Þtinis 6", // Alerts and Messages ProcessingXHTML : "Apdorojamas XHTML. Pra«Þome palaukti...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Pasirinkite «öym«¸", DlgLnkAnchorByName : "Pagal «öym«¶s vard«¨", DlgLnkAnchorById : "Pagal «öym«¶s Id", -DlgLnkNoAnchors : "<ªÞiame dokumente «öymi«ê n«¶ra>", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(ªÞiame dokumente «öymi«ê n«¶ra)", DlgLnkEMail : "El.pa«Þto adresas", DlgLnkEMailSubject : "ªöinut«¶s tema", DlgLnkEMailBody : "ªöinut«¶s turinys", @@ -322,6 +331,9 @@ DlgCellBorderColor : "R«¶melio spalva", DlgCellBtnSelect : "Pa«öym«¶ti...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "Paie«Þka", DlgFindFindBtn : "Surasti", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Ignoruoti «Þrift«ê nustatymus", DlgPasteRemoveStyles : "Pa«Þalinti stili«ê nustatymus", -DlgPasteCleanBox : "Trinti «Ævedimo lauk«¨", // Color Picker ColorAutomatic : "Automatinis", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "License", //MISSING DlgAboutVersion : "versija", DlgAboutInfo : "Papildom«¨ informacij«¨ galima gauti" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/lv.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/lv.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/lv.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Ievietot/Labot hipersaiti", RemoveLink : "No«Ïemt hipersaiti", Anchor : "Ievietot/Labot iez«Åmi", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Att«·ls", InsertImage : "Ievietot/Labot Att«·lu", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Izl«Ådzin«§t malas", DecreaseIndent : "Samazin«§t atk«§pi", IncreaseIndent : "Palielin«§t atk«§pi", +Blockquote : "Blockquote", //MISSING Undo : "Atcelt", Redo : "Atk«§rtot", NumberedListLbl : "Numur«·ts saraksts", @@ -103,20 +105,27 @@ ImageButton : "Att«·lpoga", FitWindow : "Maksimiz«·t redaktora izm«·ru", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "Labot hipersaiti", CellCM : "ªÞ«éna", RowCM : "Rinda", ColumnCM : "Kolonna", -InsertRow : "Ievietot rindu", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Dz«·st rindas", -InsertColumn : "Ievietot kolonnu", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "Dz«·st kolonnas", -InsertCell : "Ievietot r«éti«Ïu", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "Dz«·st r«éti«Ïas", MergeCells : "Apvienot r«éti«Ïas", -SplitCell : "Sadal«Åt r«éti«Ïu", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Dz«·st tabulu", CellProperties : "R«éti«Ïas «Åpa«Þ«Åbas", TableProperties : "Tabulas «Åpa«Þ«Åbas", @@ -134,7 +143,7 @@ TextareaProp : "Teksta laukuma «Åpa«Þ«Åbas", FormProp : "Formas «Åpa«Þ«Åbas", -FontFormats : "Norm«§ls teksts;Format«·ts teksts;Adrese;Virsraksts 1;Virsraksts 2;Virsraksts 3;Virsraksts 4;Virsraksts 5;Virsraksts 6;Rindkopa (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Norm«§ls teksts;Format«·ts teksts;Adrese;Virsraksts 1;Virsraksts 2;Virsraksts 3;Virsraksts 4;Virsraksts 5;Virsraksts 6;Rindkopa (DIV)", // Alerts and Messages ProcessingXHTML : "Tiek apstr«§d«§ts XHTML. L«édzu uzgaidiet...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Izv«·l«·ties iez«Åmi", DlgLnkAnchorByName : "P«·c iez«Åmes nosaukuma", DlgLnkAnchorById : "P«·c elementa ID", -DlgLnkNoAnchors : "<ªÞaj«§ dokument«§ nav iez«Åmju>", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(ªÞaj«§ dokument«§ nav iez«Åmju)", DlgLnkEMail : "E-pasta adrese", DlgLnkEMailSubject : "Zi«Ïas t«·ma", DlgLnkEMailBody : "Zi«Ïas saturs", @@ -322,6 +331,9 @@ DlgCellBorderColor : "R«§mja kr«§sa", DlgCellBtnSelect : "Iez«Åm«·...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "Mekl«·t«§js", DlgFindFindBtn : "Mekl«·t", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Ignor«·t iepriek«Þ nor«§d«Åtos fontus", DlgPasteRemoveStyles : "No«Ïemt nor«§d«Åtos stilus", -DlgPasteCleanBox : "Apstr«§d«§t laukuma saturu", // Color Picker ColorAutomatic : "Autom«§tiska", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Licence", DlgAboutVersion : "versija", DlgAboutInfo : "Papildus inform«§cija ir pieejama" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/mn.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/mn.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/mn.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -44,11 +44,12 @@ InsertLinkLbl : "§­§Ú§ß§Ü", InsertLink : "§­§Ú§ß§Ü §°§â§å§å§Ý§Ñ§ç/§©§Ñ§ã§Ó§Ñ§â§Ý§Ñ§ç", RemoveLink : "§­§Ú§ß§Ü §Ñ§Ó§é §ç§Ñ§ñ§ç", -Anchor : "Insert/Edit Anchor", //MISSING +Anchor : "§·§à§Ý§Ò§à§à§ã §°§â§å§å§Ý§Ñ§ç/§©§Ñ§ã§Ó§Ñ§â§Ý§Ñ§ç", +AnchorDelete : "§·§à§Ý§Ò§à§à§ã §¡§Ó§Ñ§ç", InsertImageLbl : "§©§å§â§Ñ§Ô", InsertImage : "§©§å§â§Ñ§Ô §°§â§å§å§Ý§Ñ§ç/§©§Ñ§ã§Ó§Ñ§â§Ý§Ñ§ç", -InsertFlashLbl : "Flash", //MISSING -InsertFlash : "Insert/Edit Flash", //MISSING +InsertFlashLbl : "§¶§Ý§Ñ§ê", +InsertFlash : "§¶§Ý§Ñ§ê §°§â§å§å§Ý§Ñ§ç/§©§Ñ§ã§Ó§Ñ§â§Ý§Ñ§ç", InsertTableLbl : "§·?§ã§ß§ï§Ô§ä", InsertTable : "§·?§ã§ß§ï§Ô§ä §°§â§å§å§Ý§Ñ§ç/§©§Ñ§ã§Ó§Ñ§â§Ý§Ñ§ç", InsertLineLbl : "§©§å§â§Ñ§Ñ§ã", @@ -70,6 +71,7 @@ BlockJustify : "§¢§Ý§à§Ü §ç§ï§Ý§Ò§ï§â§ï§ï§â §Ò§Ñ§Û§â§Ý§å§å§Ý§Ñ§ç", DecreaseIndent : "§¥§à§Ô§à§Ý §Þ?§â §ß§ï§Þ§ï§ç", IncreaseIndent : "§¥§à§Ô§à§Ý §Þ?§â §ç§Ñ§ã§Ñ§ç", +Blockquote : "§·§Ñ§Û§â§è§Ñ§Ô§Ý§Ñ§ç", Undo : "§·?§é§Ú§ß§Ô?§Û §Ò§à§Ý§Ô§à§ç", Redo : "?§Þ§ß?§ç ?§Û§Ý§Õ§Ý§ï§ï §ã§ï§â§Ô§ï§ï§ç", NumberedListLbl : "§¥§å§Ô§Ñ§Ñ§â§Ý§Ñ§Ô§Õ§ã§Ñ§ß §Ø§Ñ§Ô§ã§Ñ§Ñ§Ý§ä", @@ -87,54 +89,61 @@ Source : "§¬§à§Õ", Find : "§·§Ñ§Û§ç", Replace : "§³§à§Ý§Ú§ç", -SpellCheck : "Check Spelling", //MISSING -UniversalKeyboard : "Universal Keyboard", //MISSING -PageBreakLbl : "Page Break", //MISSING -PageBreak : "Insert Page Break", //MISSING +SpellCheck : "?§Ô§Ú§Û§ß §Õ?§â§ï§ç §ê§Ñ§Ý§Ô§Ñ§ç", +UniversalKeyboard : "§µ§ß§Ú§Ó§Ñ§â§ã§Ñ§Ý §Ô§Ñ§â", +PageBreakLbl : "§·§å§å§Õ§Ñ§ã §ä§å§ã§Ô§Ñ§Ñ§â§Ý§Ñ§ç", +PageBreak : "§·§å§å§Õ§Ñ§ã §ä§å§ã§Ô§Ñ§Ñ§â§Ý§Ñ§Ô§é §à§â§å§å§Ý§Ñ§ç", -Form : "Form", //MISSING -Checkbox : "Checkbox", //MISSING -RadioButton : "Radio Button", //MISSING -TextField : "Text Field", //MISSING -Textarea : "Textarea", //MISSING -HiddenField : "Hidden Field", //MISSING -Button : "Button", //MISSING -SelectionField : "Selection Field", //MISSING -ImageButton : "Image Button", //MISSING +Form : "§¶§à§â§Þ", +Checkbox : "§¹§Ö§Ü§Ò§à§Ü§ã", +RadioButton : "§²§Ñ§Õ§Ú§à §ä§à§Ó§é", +TextField : "§´§Ö§ç§ä §ä§Ñ§Ý§Ò§Ñ§â", +Textarea : "§´§Ö§ç§ä §à§â§é§Ú§ß", +HiddenField : "§¯§å§å§è §ä§Ñ§Ý§Ò§Ñ§â", +Button : "§´§à§Ó§é", +SelectionField : "§³§à§ß§Ô§à§Ô§é §ä§Ñ§Ý§Ò§Ñ§â", +ImageButton : "§©§å§â§Ñ§Ô§ä§Ñ§Û §ä§à§Ó§é", -FitWindow : "Maximize the editor size", //MISSING +FitWindow : "editor-§ß §ç§ï§Þ§Ø§ï§ï§Ô §ä§à§Þ§â§å§å§Ý§Ñ§ç", +ShowBlocks : "Block-§å§å§Õ§í§Ô ?§Ù??§Ý§ï§ç", // Context Menu EditLink : "§·§à§Ý§Ò§à§à§ã §Ù§Ñ§ã§Ó§Ñ§â§Ý§Ñ§ç", -CellCM : "Cell", //MISSING -RowCM : "Row", //MISSING -ColumnCM : "Column", //MISSING -InsertRow : "§®?§â §à§â§å§å§Ý§Ñ§ç", +CellCM : "§¯?§ç/§Ù§Ñ§Û", +RowCM : "§®?§â", +ColumnCM : "§¢§Ñ§Ô§Ñ§ß§Ñ", +InsertRowAfter : "§®?§â §Õ§Ñ§â§Ñ§Ñ §ß§î §à§â§å§å§Ý§Ñ§ç", +InsertRowBefore : "§®?§â ?§Þ§ß? §ß§î §à§â§å§å§Ý§Ñ§ç", DeleteRows : "§®?§â §å§ã§ä§Ô§Ñ§ç", -InsertColumn : "§¢§Ñ§Ô§Ñ§ß§Ñ §à§â§å§å§Ý§Ñ§ç", +InsertColumnAfter : "§¢§Ñ§Ô§Ñ§ß§Ñ §Õ§Ñ§â§Ñ§Ñ §ß§î §à§â§å§å§Ý§Ñ§ç", +InsertColumnBefore : "§¢§Ñ§Ô§Ñ§ß§Ñ ?§Þ§ß? §ß§î §à§â§å§å§Ý§Ñ§ç", DeleteColumns : "§¢§Ñ§Ô§Ñ§ß§Ñ §å§ã§ä§Ô§Ñ§ç", -InsertCell : "§¯?§ç §à§â§å§å§Ý§Ñ§ç", +InsertCellAfter : "§¯?§ç/§Ù§Ñ§Û §Õ§Ñ§â§Ñ§Ñ §ß§î §à§â§å§å§Ý§Ñ§ç", +InsertCellBefore : "§¯?§ç/§Ù§Ñ§Û ?§Þ§ß? §ß§î §à§â§å§å§Ý§Ñ§ç", DeleteCells : "§¯?§ç §å§ã§ä§Ô§Ñ§ç", MergeCells : "§¯?§ç §ß§ï§Ô§ä§ï§ç", -SplitCell : "§¯?§ç §ä§å§ã§Ô§Ñ§Û§â§Ý§Ñ§ç", -TableDelete : "Delete Table", //MISSING -CellProperties : "§·§à§à§ã§à§ß §Ù§Ñ§Û§ß §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", +MergeRight : "§¢§Ñ§â§å§å§ß §ä§Ú§Û§ê §ß§ï§Ô§ä§Ô§ï§ç", +MergeDown : "§¥§à§à§ê §ß§ï§Ô§ä§Ô§ï§ç", +HorizontalSplitCell : "§¯?§ç/§Ù§Ñ§Û§Ô §Ò§à§ã§à§à§Ô§à§à§â §ß§î §ä§å§ã§Ô§Ñ§Ñ§â§Ý§Ñ§ç", +VerticalSplitCell : "§¯?§ç/§Ù§Ñ§Û§Ô §ç?§ß§Õ§Ý?§ß§Ô??§â §ß§î §ä§å§ã§Ô§Ñ§Ñ§â§Ý§Ñ§ç", +TableDelete : "§·?§ã§ß§ï§Ô§ä §å§ã§ä§Ô§Ñ§ç", +CellProperties : "§¯?§ç/§Ù§Ñ§Û §Ù§Ñ§Û§ß §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", TableProperties : "§·?§ã§ß§ï§Ô§ä", ImageProperties : "§©§å§â§Ñ§Ô", -FlashProperties : "Flash Properties", //MISSING +FlashProperties : "§¶§Ý§Ñ§ê §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", -AnchorProp : "Anchor Properties", //MISSING -ButtonProp : "Button Properties", //MISSING -CheckboxProp : "Checkbox Properties", //MISSING -HiddenFieldProp : "Hidden Field Properties", //MISSING -RadioButtonProp : "Radio Button Properties", //MISSING -ImageButtonProp : "Image Button Properties", //MISSING -TextFieldProp : "Text Field Properties", //MISSING -SelectionFieldProp : "Selection Field Properties", //MISSING -TextareaProp : "Textarea Properties", //MISSING -FormProp : "Form Properties", //MISSING +AnchorProp : "§·§à§Ý§Ò§à§à§ã §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", +ButtonProp : "§´§à§Ó§é§ß§í §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", +CheckboxProp : "§¹§Ö§Ü§Ò§à§Ü§ã§ß§í §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", +HiddenFieldProp : "§¯§å§å§è §ä§Ñ§Ý§Ò§Ñ§â§í§ß §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", +RadioButtonProp : "§²§Ñ§Õ§Ú§à §ä§à§Ó§é§ß§í §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", +ImageButtonProp : "§©§å§â§Ô§Ñ§ß §ä§à§Ó§é§ß§í §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", +TextFieldProp : "§´§Ö§Ü§ã§ä §ä§Ñ§Ý§Ò§Ñ§â§í§ß §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", +SelectionFieldProp : "§³§à§Ô§à§Ô§é §ä§Ñ§Ý§Ò§Ñ§â§í§ß §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", +TextareaProp : "§´§Ö§Ü§ã§ä §à§â§é§ß§í §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", +FormProp : "§¶§à§â§Þ §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", -FontFormats : "§·§ï§Ó§Ú§Û§ß;Formatted;§·§Ñ§ñ§Ô;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Paragraph (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "§·§ï§Ó§Ú§Û§ß;Formatted;§·§Ñ§ñ§Ô;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Paragraph (DIV)", // Alerts and Messages ProcessingXHTML : "XHTML ?§Û§Ý §ñ§Ó§è §ñ§Ó§Ñ§Ô§Õ§Ñ§Ø §Ò§Ñ§Û§ß§Ñ. §·?§Ý§ï§ï§ß§ï ??...", @@ -145,19 +154,19 @@ UnknownCommand : "\"%1\" §Ü§à§Þ§Þ§Ñ§ß§Õ §ß§ï§â §Þ§ï§Õ§Ñ§Ô§Õ§ï§ç§Ô?§Û §Ò§Ñ§Û§ß§Ñ", NotImplemented : "§©?§Ó§ê??§â?§Ô§Õ?§ç§Ô?§Û §Ü§à§Þ§Þ§Ñ§ß§Õ", UnknownToolbarSet : "§¢§Ñ§Ô§Ñ§Ø§ß§í §ç§ï§ã§ï§Ô§ä \"%1\" §à§ß§à§à§ç, ??§ã§ï§ï§Ô?§Û §Ò§Ñ§Û§ß§Ñ", -NoActiveX : "Your browser's security settings could limit some features of the editor. You must enable the option \"Run ActiveX controls and plug-ins\". You may experience errors and notice missing features.", //MISSING -BrowseServerBlocked : "The resources browser could not be opened. Make sure that all popup blockers are disabled.", //MISSING -DialogBlocked : "It was not possible to open the dialog window. Make sure all popup blockers are disabled.", //MISSING +NoActiveX : "§´§Ñ§ß§í ?§Ù??§Ý§ï§Ô§é/browser-§ß §ç§Ñ§Þ§Ô§Ñ§Ñ§Ý§Ñ§Ý§ä§í§ß §ä§à§ç§Ú§â§Ô§à§à editor-§ß §Ù§Ñ§â§Ú§Þ §Ò§à§Ý§à§Þ§Ø§Ú§Û§Ô §ç§ñ§Ù§Ô§Ñ§Ñ§â§Ý§Ñ§Ø §Ò§Ñ§Û§ß§Ñ. §´§Ñ \"Run ActiveX controls §Ò§Ñ plug-ins\" §ã§à§ß§Ô§à§Ý§í§Ô §Ú§Õ§Ó§ï§ç§Ú§ä§ï§Û §Ò§à§Ý§Ô§à.", +BrowseServerBlocked : "§¯??§è ?§Ù??§Ô§é §ß§ï§ï§Ø §é§Ñ§Õ§ã§Ñ§ß§Ô?§Û. §¢?§ç popup blocker-§Ô disabled §Ò§à§Ý§Ô§à§ß§à §å§å.", +DialogBlocked : "§·§Ñ§â§Ú§Ý§è§Ñ§ç §è§à§ß§ç§à§ß§Õ §ï§ß§Ú§Û§Ô §ß§ï§ï§ç§ï§Õ §Ò§à§Ý§à§Þ§Ø§Ô?§Û §ï§ï. §¢?§ç popup blocker-§Ô disabled §Ò§à§Ý§Ô§à§ß§à §å§å.", // Dialogs DlgBtnOK : "OK", DlgBtnCancel : "§¢§à§Ý§Ú§ç", DlgBtnClose : "§·§Ñ§Ñ§ç", -DlgBtnBrowseServer : "Browse Server", //MISSING +DlgBtnBrowseServer : "§³§Ö§â§Ó§Ö§â §ç§Ñ§â§å§å§Ý§Ñ§ç", DlgAdvancedTag : "§¯§ï§Þ§ï§Ý§ä", -DlgOpOther : "", //MISSING -DlgInfoTab : "Info", //MISSING -DlgAlertUrl : "Please insert the URL", //MISSING +DlgOpOther : "<§¢§å§ã§Ñ§Õ>", +DlgInfoTab : "§®§ï§Õ§ï§ï§Ý§ï§Ý", +DlgAlertUrl : "URL §à§â§å§å§Ý§ß§Ñ §å§å", // General Dialogs Labels DlgGenNotSet : "<§°§ß§à§à§ç§Ô?§Û>", @@ -185,7 +194,7 @@ DlgImgAlt : "§´§Ñ§Û§Ý§Ò§Ñ§â §ä§Ö§Ü§ã§ä", DlgImgWidth : "?§â§Ô?§ß", DlgImgHeight : "?§ß§Õ?§â", -DlgImgLockRatio : "Lock Ratio", +DlgImgLockRatio : "§²§Ñ§Õ§Ú§à §ä?§Ô§Ø§Ú§ç", DlgBtnResetSize : "§ç§ï§Þ§Ø§ï§ï §Õ§Ñ§ç§Ú§ß §à§ß§à§à§ç", DlgImgBorder : "§·?§â§ï§ï", DlgImgHSpace : "§·?§ß§Õ§Ý?§ß §Ù§Ñ§Û", @@ -202,17 +211,17 @@ DlgImgAlignTop : "§¥§ï§ï§Õ §ä§Ñ§Ý§Õ", DlgImgPreview : "§µ§â§Ú§Õ§é§Ý§Ñ§ß §ç§Ñ§â§Ñ§ç", DlgImgAlertUrl : "§©§å§â§Ñ§Ô§ß§í URL-§í§ß §ä?§â§Ý§Ú§Û§ß §ã§à§ß§Ô§à§ß§à §å§å", -DlgImgLinkTab : "Link", //MISSING +DlgImgLinkTab : "§­§Ú§ß§Ü", // Flash Dialog -DlgFlashTitle : "Flash Properties", //MISSING -DlgFlashChkPlay : "Auto Play", //MISSING -DlgFlashChkLoop : "Loop", //MISSING -DlgFlashChkMenu : "Enable Flash Menu", //MISSING -DlgFlashScale : "Scale", //MISSING -DlgFlashScaleAll : "Show all", //MISSING -DlgFlashScaleNoBorder : "No Border", //MISSING -DlgFlashScaleFit : "Exact Fit", //MISSING +DlgFlashTitle : "§¶§Ý§Ñ§ê §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", +DlgFlashChkPlay : "§¡§Ó§ä§à§Þ§Ñ§ä§Ñ§Ñ§â §ä§à§Ô§Ý§à§ç", +DlgFlashChkLoop : "§¥§Ñ§Ó§ä§Ñ§ç", +DlgFlashChkMenu : "§¶§Ý§Ñ§ê §è§ï§ã §Ú§Õ§Ó§ï§ç§Ø??§Ý§ï§ç", +DlgFlashScale : "?§â§Ô?§Ô§ä§Ô?§ç", +DlgFlashScaleAll : "§¢?§Ô§Õ§Ú§Û§Ô §ç§Ñ§â§å§å§Ý§Ñ§ç", +DlgFlashScaleNoBorder : "§·?§â§ï§ï§Ô?§Û", +DlgFlashScaleFit : "§Á§Ô §ä§Ñ§Ñ§â§å§å§Ý§Ñ§ç", // Link Dialog DlgLnkWindowTitle : "§­§Ú§ß§Ü", @@ -229,9 +238,9 @@ DlgLnkAnchorSel : "§·§à§Ý§Ò§à§à§ã §ã§à§ß§Ô§à§ç", DlgLnkAnchorByName : "§·§à§Ý§Ò§à§à§ã§í§ß §ß§ï§â§ï§ï§â", DlgLnkAnchorById : "§¿§Ý§Ö§Þ§ï§ß§ä Id-§Ô§Ñ§Ñ§â", -DlgLnkNoAnchors : "<§¢§Ñ§â§Ú§Þ§ä §Ò§Ú§é§Ú§Ô §ç§à§Ý§Ò§à§à§ã§Ô?§Û §Ò§Ñ§Û§ß§Ñ>", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(§¢§Ñ§â§Ú§Þ§ä §Ò§Ú§é§Ú§Ô §ç§à§Ý§Ò§à§à§ã§Ô?§Û §Ò§Ñ§Û§ß§Ñ)", DlgLnkEMail : "E-Mail §·§Ñ§ñ§Ô", -DlgLnkEMailSubject : "Message Subject", +DlgLnkEMailSubject : "Message §Ô§Ñ§â§é§Ú§Ô", DlgLnkEMailBody : "Message-§Ú§Û§ß §Ñ§Ô§å§å§Ý§Ô§Ñ", DlgLnkUpload : "§·§å§å§Ý§Ñ§ç", DlgLnkBtnUpload : "??§ß§Ú§Û§Ô §ã§Ö§â§Ó§Ö§â§â?? §Ú§Ý§Ô§ï§ï", @@ -243,7 +252,7 @@ DlgLnkTargetParent : "§¿§è§ï§Ô §è§à§ß§ç (_parent)", DlgLnkTargetSelf : "§´?§ã§ä§ï§Û §è§à§ß§ç (_self)", DlgLnkTargetTop : "§·§Ñ§Þ§Ô§Ú§Û§ß §ä?§â??§ß §Ò§Ñ§Û§ç §è§à§ß§ç (_top)", -DlgLnkTargetFrameName : "Target Frame Name", //MISSING +DlgLnkTargetFrameName : "§°§é§Ú§ç §æ§â§Ö§Þ§í§ß §ß§ï§â", DlgLnkPopWinName : "Popup §è§à§ß§ç§ß§í §ß§ï§â", DlgLnkPopWinFeat : "Popup §è§à§ß§ç§ß§í §à§ß§è§Ý§à§Ô", DlgLnkPopResize : "§·§ï§Þ§Ø§ï§ï ??§â§é§Ý?§ç", @@ -262,7 +271,7 @@ DlnLnkMsgNoUrl : "§­§Ú§ß§Ü URL-§ï§ï §ä?§â?§Ý§Ø??§Ý§ß§ï ??", DlnLnkMsgNoEMail : "§¦-mail §ç§Ñ§ñ§Ô§Ñ§Ñ §ä?§â?§Ý§Ø??§Ý§ß§ï ??", DlnLnkMsgNoAnchor : "§·§à§Ý§Ò§à§à§ã§à§à §ã§à§ß§Ô§à§ß§à §å§å", -DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces", //MISSING +DlnLnkMsgInvPopName : "popup §ß§ï§â §ß§î ?§ã§Ô§ï§ß §ä§ï§Þ§Õ§ï§Ô§ä§ï§ï§â §ï§ç§ï§Ý§ã§ï§ß §Ò§Ñ§Û§ç §Ò§Ñ §ç§à§à§ã§à§ß §Ù§Ñ§Û §Ñ§Ô§å§å§Ý§Ñ§Ñ§Ô?§Û §Ò§Ñ§Û§ç §×§ã§ä§à§Û.", // Color Dialog DlgColorTitle : "?§ß§Ô? §ã§à§ß§Ô§à§ç", @@ -290,10 +299,10 @@ DlgTableWidthPx : "§è§ï§Ô", DlgTableWidthPc : "§ç§å§Ó§î", DlgTableHeight : "?§ß§Õ?§â", -DlgTableCellSpace : "§¯?§ç §ç§à§à§â§à§ß§Õ§í§ß §Ù§Ñ§Û", -DlgTableCellPad : "§¯?§ç §Õ§à§ä§à§â§Ý§à§ç", +DlgTableCellSpace : "§¯?§ç §ç§à§à§â§à§ß§Õ§í§ß §Ù§Ñ§Û (spacing)", +DlgTableCellPad : "§¯?§ç §Õ§à§ä§à§â§Ý§à§ç(padding)", DlgTableCaption : "§´§Ñ§Û§Ý§Ò§Ñ§â", -DlgTableSummary : "Summary", //MISSING +DlgTableSummary : "§´§Ñ§Û§Ý§Ò§Ñ§â", // Table Cell Dialog DlgCellTitle : "§·§à§à§ã§à§ß §Ù§Ñ§Û§ß §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", @@ -316,12 +325,15 @@ DlgCellVerAlignMiddle : "§¥§å§ß§Õ", DlgCellVerAlignBottom : "§¥§à§à§Õ §ä§Ñ§Ý", DlgCellVerAlignBaseline : "Baseline", -DlgCellRowSpan : "§¯§Ú§Û§ä §Þ?§â", -DlgCellCollSpan : "§¯§Ú§Û§ä §Ò§Ñ§Ô§Ñ§ß§Ñ", +DlgCellRowSpan : "§¯§Ú§Û§ä §Þ?§â (span)", +DlgCellCollSpan : "§¯§Ú§Û§ä §Ò§Ñ§Ô§Ñ§ß§Ñ (span)", DlgCellBackColor : "§¶§à§ß§ß§í ?§ß§Ô?", DlgCellBorderColor : "§·?§â§ï§ï§ß§Ú§Û ?§ß§Ô?", DlgCellBtnSelect : "§³§à§ß§Ô§à...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "§·§Ñ§Û §Þ?§ß §¥§Ñ§â§Ø §Ò§Ú§é", + // Find Dialog DlgFindTitle : "§·§Ñ§Û§ç", DlgFindFindBtn : "§·§Ñ§Û§ç", @@ -343,162 +355,161 @@ PasteAsText : "Plain Text-§ï§ï§ã §Ò§å§å§Ý§Ô§Ñ§ç", PasteFromWord : "Word-§à§à§ã §Ò§å§å§Ý§Ô§Ñ§ç", -DlgPasteMsg2 : "Please paste inside the following box using the keyboard (Ctrl+V) and hit OK.", //MISSING -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING -DlgPasteIgnoreFont : "Ignore Font Face definitions", //MISSING -DlgPasteRemoveStyles : "Remove Styles definitions", //MISSING -DlgPasteCleanBox : "Clean Up Box", //MISSING +DlgPasteMsg2 : "(Ctrl+V) §ä§à§Ó§é§Ú§Û§Ô §Ñ§ê§Ú§Ô§Ý§Ñ§ß paste §ç§Ú§Û§ß§ï ??. §®?§ß OK §Õ§Ñ§â.", +DlgPasteSec : "§´§Ñ§ß§í ?§Ù??§Ý§ï§Ô§é/browser/-§ß §ç§Ñ§Þ§Ô§Ñ§Ñ§Ý§Ñ§Ý§ä§í§ß §ä§à§ç§Ú§â§Ô§à§à§ß§à§à§ã §Ò§à§Ý§à§à§Õ editor clipboard ?§Ô?§Ô§Õ?§Ý§â?? §ê§å§å§Õ §ç§Ñ§ß§Õ§Ñ§ç §Ò§à§Ý§à§Þ§Ø§Ô?§Û. §¿§ß§ï §è§à§ß§ç§à§Õ §Õ§Ñ§ç§Ú§ß paste §ç§Ú§Û§ç§Ú§Û§Ô §à§â§à§Ý§Õ.", +DlgPasteIgnoreFont : "§´§à§Õ§à§â§ç§à§Û§Ý§à§Ô§Õ§ã§à§ß Font Face §Ù?§Ó§ê??§â§ß?", +DlgPasteRemoveStyles : "§´§à§Õ§à§â§ç§à§Û§Ý§à§Ô§Õ§ã§à§ß §Ù§Ñ§Ô§Ó§Ñ§â§í§Ô §Ñ§Ó§Ñ§ç", // Color Picker ColorAutomatic : "§¡§Ó§ä§à§Þ§Ñ§ä§Ñ§Ñ§â", ColorMoreColors : "§¯§ï§Þ§ï§Ý§ä ?§ß§Ô?§ß??§Õ...", // Document Properties -DocProps : "Document Properties", //MISSING +DocProps : "§¢§Ñ§â§Ú§Þ§ä §Ò§Ú§é§Ú§Ô §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", // Anchor Dialog -DlgAnchorTitle : "Anchor Properties", //MISSING -DlgAnchorName : "Anchor Name", //MISSING -DlgAnchorErrorName : "Please type the anchor name", //MISSING +DlgAnchorTitle : "§·§à§Ý§Ò§à§à§ã §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", +DlgAnchorName : "§·§à§Ý§Ò§à§à§ã §ß§ï§â", +DlgAnchorErrorName : "§·§à§Ý§Ò§à§à§ã §ä?§â?§Ý §à§â§å§å§Ý§ß§Ñ §å§å", // Speller Pages Dialog -DlgSpellNotInDic : "Not in dictionary", //MISSING -DlgSpellChangeTo : "Change to", //MISSING -DlgSpellBtnIgnore : "Ignore", //MISSING -DlgSpellBtnIgnoreAll : "Ignore All", //MISSING -DlgSpellBtnReplace : "Replace", //MISSING -DlgSpellBtnReplaceAll : "Replace All", //MISSING -DlgSpellBtnUndo : "Undo", //MISSING -DlgSpellNoSuggestions : "- No suggestions -", //MISSING -DlgSpellProgress : "Spell check in progress...", //MISSING -DlgSpellNoMispell : "Spell check complete: No misspellings found", //MISSING -DlgSpellNoChanges : "Spell check complete: No words changed", //MISSING -DlgSpellOneChange : "Spell check complete: One word changed", //MISSING -DlgSpellManyChanges : "Spell check complete: %1 words changed", //MISSING +DlgSpellNotInDic : "§´§à§Ý§î §Ò§Ú§é§Ú§Ô§Ô?§Û", +DlgSpellChangeTo : "??§â§é§Ý?§ç", +DlgSpellBtnIgnore : "§©?§Ó§ê??§â?§ç", +DlgSpellBtnIgnoreAll : "§¢?§Ô§Õ§Ú§Û§Ô §Ù?§Ó§ê??§â?§ç", +DlgSpellBtnReplace : "§¥§Ñ§â§Ø §Ò§Ú§é§Ú§ç", +DlgSpellBtnReplaceAll : "§¢?§Ô§Õ§Ú§Û§Ô §¥§Ñ§â§Ø §Ò§Ú§é§Ú§ç", +DlgSpellBtnUndo : "§¢§å§è§Ñ§Ñ§ç", +DlgSpellNoSuggestions : "- §´§Ñ§Û§Ý§Ò§Ñ§â§Ô?§Û -", +DlgSpellProgress : "§¥?§â§ï§Þ §ê§Ñ§Ý§Ô§Ñ§Ø §Ò§Ñ§Û§Ô§Ñ§Ñ ?§Û§Ý §ñ§Ó§è...", +DlgSpellNoMispell : "§¥?§â§ï§Þ §ê§Ñ§Ý§Ô§Ñ§Ñ§Õ §Õ§å§å§ã§ã§Ñ§ß: §¡§Ý§Õ§Ñ§Ñ §à§Ý§Õ§ã§à§ß§Ô?§Û", +DlgSpellNoChanges : "§¥?§â§ï§Þ §ê§Ñ§Ý§Ô§Ñ§Ñ§Õ §Õ§å§å§ã§ã§Ñ§ß: ?§Ô ??§â§é§Ý?§Ô§Õ??§Ô?§Û", +DlgSpellOneChange : "§¥?§â§ï§Þ §ê§Ñ§Ý§Ô§Ñ§Ñ§Õ §Õ§å§å§ã§ã§Ñ§ß: 1 ?§Ô ??§â§é§Ý?§Ô§Õ§ã?§ß", +DlgSpellManyChanges : "§¥?§â§ï§Þ §ê§Ñ§Ý§Ô§Ñ§Ñ§Õ §Õ§å§å§ã§ã§Ñ§ß: %1 ?§Ô ??§â§é§Ý?§Ô§Õ§ã?§ß", -IeSpellDownload : "Spell checker not installed. Do you want to download it now?", //MISSING +IeSpellDownload : "§¥?§â§ï§Þ §ê§Ñ§Ý§Ô§Ñ§Ô§é §ã§å§å§Ô§Ñ§Ñ§Ô?§Û §Ò§Ñ§Û§ß§Ñ. §´§Ñ§ä§Ñ§Ø §Ñ§Ó§Ñ§ç§í§Ô §ç?§ã§é §Ò§Ñ§Û§ß§Ñ §å§å?", // Button Dialog -DlgButtonText : "Text (Value)", //MISSING -DlgButtonType : "Type", //MISSING -DlgButtonTypeBtn : "Button", //MISSING -DlgButtonTypeSbm : "Submit", //MISSING -DlgButtonTypeRst : "Reset", //MISSING +DlgButtonText : "§´§ï§Ü§ã§ä (§µ§ä§Ô§Ñ)", +DlgButtonType : "§´?§â?§Ý", +DlgButtonTypeBtn : "§´§à§Ó§é", +DlgButtonTypeSbm : "Submit", +DlgButtonTypeRst : "§¢§à§Ý§Ú§ç", // Checkbox and Radio Button Dialogs -DlgCheckboxName : "Name", //MISSING -DlgCheckboxValue : "Value", //MISSING -DlgCheckboxSelected : "Selected", //MISSING +DlgCheckboxName : "§¯§ï§â", +DlgCheckboxValue : "§µ§ä§Ô§Ñ", +DlgCheckboxSelected : "§³§à§ß§Ô§à§Ô§Õ§ã§à§ß", // Form Dialog -DlgFormName : "Name", //MISSING -DlgFormAction : "Action", //MISSING -DlgFormMethod : "Method", //MISSING +DlgFormName : "§¯§ï§â", +DlgFormAction : "?§Û§Ý§Õ§ï§Ý", +DlgFormMethod : "§¡§â§Ô§Ñ", // Select Field Dialog -DlgSelectName : "Name", //MISSING -DlgSelectValue : "Value", //MISSING -DlgSelectSize : "Size", //MISSING -DlgSelectLines : "lines", //MISSING -DlgSelectChkMulti : "Allow multiple selections", //MISSING -DlgSelectOpAvail : "Available Options", //MISSING -DlgSelectOpText : "Text", //MISSING -DlgSelectOpValue : "Value", //MISSING -DlgSelectBtnAdd : "Add", //MISSING -DlgSelectBtnModify : "Modify", //MISSING -DlgSelectBtnUp : "Up", //MISSING -DlgSelectBtnDown : "Down", //MISSING -DlgSelectBtnSetValue : "Set as selected value", //MISSING -DlgSelectBtnDelete : "Delete", //MISSING +DlgSelectName : "§¯§ï§â", +DlgSelectValue : "§µ§ä§Ô§Ñ", +DlgSelectSize : "§·§ï§Þ§Ø§ï§ï", +DlgSelectLines : "§®?§â", +DlgSelectChkMulti : "§°§Ý§à§ß §ã§à§ß§Ô§à§Ý§ä §Ù?§Ó§ê??§â?§ç", +DlgSelectOpAvail : "§ª§Õ§Ó§ï§ç§ä§ï§Û §ã§à§ß§Ô§à§Ý§ä", +DlgSelectOpText : "§´§ï§Ü§ã§ä", +DlgSelectOpValue : "§µ§ä§Ô§Ñ", +DlgSelectBtnAdd : "§¯§ï§Þ§ï§ç", +DlgSelectBtnModify : "??§â§é§Ý?§ç", +DlgSelectBtnUp : "§¥§ï§ï§ê", +DlgSelectBtnDown : "§¥§à§à§ê", +DlgSelectBtnSetValue : "§³§à§ß§Ô§à§Ô§Õ§ã§Ñ§ß §å§ä§Ô§Ñ §à§ß§à§à§ç", +DlgSelectBtnDelete : "§µ§ã§ä§Ô§Ñ§ç", // Textarea Dialog -DlgTextareaName : "Name", //MISSING -DlgTextareaCols : "Columns", //MISSING -DlgTextareaRows : "Rows", //MISSING +DlgTextareaName : "§¯§ï§â", +DlgTextareaCols : "§¢§Ñ§Ô§Ñ§ß§Ñ", +DlgTextareaRows : "§®?§â", // Text Field Dialog -DlgTextName : "Name", //MISSING -DlgTextValue : "Value", //MISSING -DlgTextCharWidth : "Character Width", //MISSING -DlgTextMaxChars : "Maximum Characters", //MISSING -DlgTextType : "Type", //MISSING -DlgTextTypeText : "Text", //MISSING -DlgTextTypePass : "Password", //MISSING +DlgTextName : "§¯§ï§â", +DlgTextValue : "§µ§ä§Ô§Ñ", +DlgTextCharWidth : "§´§ï§Þ§Õ§ï§Ô§ä§í§ß ?§â§Ô?§ß", +DlgTextMaxChars : "§·§Ñ§Þ§Ô§Ú§Û§ß §Ú§ç §ä§ï§Þ§Õ§ï§Ô§ä", +DlgTextType : "§´?§â?§Ý", +DlgTextTypeText : "§´§Ö§Ü§ã§ä", +DlgTextTypePass : "§¯§å§å§è ?§Ô", // Hidden Field Dialog -DlgHiddenName : "Name", //MISSING -DlgHiddenValue : "Value", //MISSING +DlgHiddenName : "§¯§ï§â", +DlgHiddenValue : "§µ§ä§Ô§Ñ", // Bulleted List Dialog -BulletedListProp : "Bulleted List Properties", //MISSING -NumberedListProp : "Numbered List Properties", //MISSING -DlgLstStart : "Start", //MISSING -DlgLstType : "Type", //MISSING -DlgLstTypeCircle : "Circle", //MISSING -DlgLstTypeDisc : "Disc", //MISSING -DlgLstTypeSquare : "Square", //MISSING -DlgLstTypeNumbers : "Numbers (1, 2, 3)", //MISSING -DlgLstTypeLCase : "Lowercase Letters (a, b, c)", //MISSING -DlgLstTypeUCase : "Uppercase Letters (A, B, C)", //MISSING -DlgLstTypeSRoman : "Small Roman Numerals (i, ii, iii)", //MISSING -DlgLstTypeLRoman : "Large Roman Numerals (I, II, III)", //MISSING +BulletedListProp : "Bulleted §Ø§Ñ§Ô§ã§Ñ§Ñ§Ý§í§ß §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", +NumberedListProp : "§¥§å§Ô§Ñ§Ñ§â§Ý§Ñ§ã§Ñ§ß §Ø§Ñ§Ô§ã§Ñ§Ñ§Ý§í§ß §ê§Ú§ß§Ø §é§Ñ§ß§Ñ§â", +DlgLstStart : "§¿§ç§Ý§ï§ç", +DlgLstType : "§´?§â?§Ý", +DlgLstTypeCircle : "§´§à§Û§â§à§Ô", +DlgLstTypeDisc : "§´§Ñ§Û§Ý§Ò§Ñ§â", +DlgLstTypeSquare : "Square", +DlgLstTypeNumbers : "§´§à§à (1, 2, 3)", +DlgLstTypeLCase : "§¨§Ú§Ø§Ú§Ô ?§ã§ï§Ô (a, b, c)", +DlgLstTypeUCase : "§´§à§Þ ?§ã§ï§Ô (A, B, C)", +DlgLstTypeSRoman : "§¨§Ú§Ø§Ú§Ô §²§à§Þ §ä§à§à (i, ii, iii)", +DlgLstTypeLRoman : "§´§à§Þ §²§à§Þ §ä§à§à (I, II, III)", // Document Properties Dialog -DlgDocGeneralTab : "General", //MISSING -DlgDocBackTab : "Background", //MISSING -DlgDocColorsTab : "Colors and Margins", //MISSING -DlgDocMetaTab : "Meta Data", //MISSING +DlgDocGeneralTab : "§¦§â?§ß§ç§Ú§Û", +DlgDocBackTab : "§¶§à§ß§à", +DlgDocColorsTab : "§©§Ñ§ç§í§ß §Ù§Ñ§Û §Ò§Ñ ?§ß§Ô?", +DlgDocMetaTab : "Meta ?§Ô?§Ô§Õ?§Ý", -DlgDocPageTitle : "Page Title", //MISSING -DlgDocLangDir : "Language Direction", //MISSING -DlgDocLangDirLTR : "Left to Right (LTR)", //MISSING -DlgDocLangDirRTL : "Right to Left (RTL)", //MISSING -DlgDocLangCode : "Language Code", //MISSING -DlgDocCharSet : "Character Set Encoding", //MISSING -DlgDocCharSetCE : "Central European", //MISSING -DlgDocCharSetCT : "Chinese Traditional (Big5)", //MISSING -DlgDocCharSetCR : "Cyrillic", //MISSING -DlgDocCharSetGR : "Greek", //MISSING -DlgDocCharSetJP : "Japanese", //MISSING -DlgDocCharSetKR : "Korean", //MISSING -DlgDocCharSetTR : "Turkish", //MISSING -DlgDocCharSetUN : "Unicode (UTF-8)", //MISSING -DlgDocCharSetWE : "Western European", //MISSING -DlgDocCharSetOther : "Other Character Set Encoding", //MISSING +DlgDocPageTitle : "§·§å§å§Õ§Ñ§ã§ß§í §Ô§Ñ§â§é§Ú§Ô", +DlgDocLangDir : "§·§ï§Ý§ß§Ú§Û §é§Ú§Ô§Ý§ï§Ý", +DlgDocLangDirLTR : "§©??§ß§ï§ï§ã §Ò§Ñ§â§å§å§ß§â§å§å (LTR)", +DlgDocLangDirRTL : "§¢§Ñ§â§å§å§ß§Ñ§Ñ§ã §Ù??§ß§â?? (RTL)", +DlgDocLangCode : "§·§ï§Ý§ß§Ú§Û §Ü§à§Õ", +DlgDocCharSet : "Encoding §ä§ï§Þ§Õ§ï§Ô§ä", +DlgDocCharSetCE : "§´?§Ó §Ö§Ó§â§à§á", +DlgDocCharSetCT : "§·§ñ§ä§Ñ§Õ§í§ß §å§Ý§Ñ§Þ§Ø§Ý§Ñ§Ý§ä (Big5)", +DlgDocCharSetCR : "§¬§â§Ú§Ý", +DlgDocCharSetGR : "§¤§â§Ö§Õ", +DlgDocCharSetJP : "§Á§á§à§ß", +DlgDocCharSetKR : "§³§à§Ý§à§ß§Ô§à§ã", +DlgDocCharSetTR : "T§å§â§Ü", +DlgDocCharSetUN : "§À§ß§Ú§Ü§à§Õ (UTF-8)", +DlgDocCharSetWE : "§¢§Ñ§â§å§å§ß §Ö§Ó§â§à§á", +DlgDocCharSetOther : "Encoding-§Õ ??§â §ä§ï§Þ§Õ§ï§Ô§ä §à§ß§à§à§ç", -DlgDocDocType : "Document Type Heading", //MISSING -DlgDocDocTypeOther : "Other Document Type Heading", //MISSING -DlgDocIncXHTML : "Include XHTML Declarations", //MISSING -DlgDocBgColor : "Background Color", //MISSING -DlgDocBgImage : "Background Image URL", //MISSING -DlgDocBgNoScroll : "Nonscrolling Background", //MISSING -DlgDocCText : "Text", //MISSING -DlgDocCLink : "Link", //MISSING -DlgDocCVisited : "Visited Link", //MISSING -DlgDocCActive : "Active Link", //MISSING -DlgDocMargins : "Page Margins", //MISSING -DlgDocMaTop : "Top", //MISSING -DlgDocMaLeft : "Left", //MISSING -DlgDocMaRight : "Right", //MISSING -DlgDocMaBottom : "Bottom", //MISSING -DlgDocMeIndex : "Document Indexing Keywords (comma separated)", //MISSING -DlgDocMeDescr : "Document Description", //MISSING -DlgDocMeAuthor : "Author", //MISSING -DlgDocMeCopy : "Copyright", //MISSING -DlgDocPreview : "Preview", //MISSING +DlgDocDocType : "§¢§Ñ§â§Ú§Þ§ä §Ò§Ú§é§Ô§Ú§Û§ß §ä?§â?§Ý Heading", +DlgDocDocTypeOther : "§¢§å§ã§Ñ§Õ §Ò§Ñ§â§Ú§Þ§ä §Ò§Ú§é§Ô§Ú§Û§ß §ä?§â?§Ý Heading", +DlgDocIncXHTML : "XHTML §Ñ§Ô§å§å§Ý§Ø §Ù§Ñ§â§Ý§Ñ§ç", +DlgDocBgColor : "§¶§à§ß§à ?§ß§Ô?", +DlgDocBgImage : "§¶§à§ß§à §Ù§å§â§Ñ§Ô§ß§í URL", +DlgDocBgNoScroll : "§¤?§Û§Õ§ï§Ô§Ô?§Û §æ§à§ß§à", +DlgDocCText : "§´§Ö§Ü§ã§ä", +DlgDocCLink : "§­§Ú§ß§Ü", +DlgDocCVisited : "§©§à§é§Ú§Ý§ã§à§ß §Ý§Ú§ß§Ü", +DlgDocCActive : "§ª§Õ§Ó§ï§ç§Ú§ä§ï§Û §Ý§Ú§ß§Ü", +DlgDocMargins : "§·§å§å§Õ§Ñ§ã§ß§í §Ù§Ñ§ç§í§ß §Ù§Ñ§Û", +DlgDocMaTop : "§¥§ï§ï§Õ §ä§Ñ§Ý", +DlgDocMaLeft : "§©??§ß §ä§Ñ§Ý", +DlgDocMaRight : "§¢§Ñ§â§å§å§ß §ä§Ñ§Ý", +DlgDocMaBottom : "§¥§à§à§Õ §ä§Ñ§Ý", +DlgDocMeIndex : "§¢§Ñ§â§Ú§Þ§ä §Ò§Ú§é§Ô§Ú§Û§ß §Ú§ß§Õ§Ö§Ü§ã §ä?§Ý§ç??§â ?§Ô (§ä§Ñ§ã§Ý§Ñ§Ý§Ñ§Ñ§â §ä§å§ã§Ô§Ñ§Ñ§â§Ý§Ñ§Ô§Õ§Ñ§ß§Ñ)", +DlgDocMeDescr : "§¢§Ñ§â§Ú§Þ§ä §Ò§Ú§é§Ô§Ú§Û§ß §ä§Ñ§Û§Ý§Ò§Ñ§â", +DlgDocMeAuthor : "§©§à§ç§Ú§à§Ô§é", +DlgDocMeCopy : "§©§à§ç§Ú§à§Ô§é§Ú§Û§ß §ï§â§ç", +DlgDocPreview : "§·§Ñ§â§Ñ§ç", // Templates Dialog -Templates : "Templates", //MISSING -DlgTemplatesTitle : "Content Templates", //MISSING -DlgTemplatesSelMsg : "Please select the template to open in the editor
      (the actual contents will be lost):", //MISSING -DlgTemplatesLoading : "Loading templates list. Please wait...", //MISSING -DlgTemplatesNoTpl : "(No templates defined)", //MISSING -DlgTemplatesReplace : "Replace actual contents", //MISSING +Templates : "§©§Ñ§Ô§Ó§Ñ§â§å§å§Õ", +DlgTemplatesTitle : "§©§Ñ§Ô§Ó§Ñ§â§í§ß §Ñ§Ô§å§å§Ý§Ô§Ñ", +DlgTemplatesSelMsg : "§©§Ñ§Ô§Ó§Ñ§â§í§Ô §ß§ï§ï§Ø editor-§â?? §ã§à§ß§Ô§à§Ø §à§â§å§å§Ý§ß§Ñ §å§å
      (§°§Õ§à§à§Ô§Ú§Û§ß §Ñ§Ô§å§å§Ý§Ý§Ñ§Ô§í§Ô §å§ã§ä§Ñ§Ø §Þ§Ñ§Ô§Ñ§Õ§Ô?§Û):", +DlgTemplatesLoading : "§©§Ñ§Ô§Ó§Ñ§â§å§å§Õ§í§Ô §Ñ§é§Ñ§Ñ§Ý§Ý§Ñ§Ø §Ò§Ñ§Û§ß§Ñ. §´?§â §ç?§Ý§ï§ï§ß§ï ??...", +DlgTemplatesNoTpl : "(§©§Ñ§Ô§Ó§Ñ§â §ä§à§Õ§à§â§ç§à§Û§Ý§à§Ô§Õ§à§à§Ô?§Û §Ò§Ñ§Û§ß§Ñ)", +DlgTemplatesReplace : "§°§Õ§à§à§Ô§Ú§Û§ß §Ñ§Ô§å§å§Ý§Ý§Ñ§Ô§í§Ô §Õ§Ñ§â§Ø §Ò§Ú§é§Ú§ç", // About Dialog -DlgAboutAboutTab : "About", //MISSING -DlgAboutBrowserInfoTab : "Browser Info", //MISSING -DlgAboutLicenseTab : "License", //MISSING +DlgAboutAboutTab : "§´§å§ç§Ñ§Û", +DlgAboutBrowserInfoTab : "§®§ï§Õ§ï§ï§Ý§ï§Ý ?§Ù??§Ý§ï§Ô§é", +DlgAboutLicenseTab : "§­§Ú§è§Ö§ß§Ù", DlgAboutVersion : "§·§å§Ó§Ú§Ý§Ò§Ñ§â", DlgAboutInfo : "§®§ï§Õ§ï§ï§Ý§Ý§ï§ï§â §ä§å§ã§Ý§Ñ§ç" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ms.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ms.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ms.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Masukkan/Sunting Sambungan", RemoveLink : "Buang Sambungan", Anchor : "Masukkan/Sunting Pautan", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Gambar", InsertImage : "Masukkan/Sunting Gambar", InsertFlashLbl : "Flash", //MISSING @@ -70,6 +71,7 @@ BlockJustify : "Jajaran Blok", DecreaseIndent : "Kurangkan Inden", IncreaseIndent : "Tambahkan Inden", +Blockquote : "Blockquote", //MISSING Undo : "Batalkan", Redo : "Ulangkan", NumberedListLbl : "Senarai bernombor", @@ -103,20 +105,27 @@ ImageButton : "Butang Bergambar", FitWindow : "Maximize the editor size", //MISSING +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "Sunting Sambungan", CellCM : "Cell", //MISSING RowCM : "Row", //MISSING ColumnCM : "Column", //MISSING -InsertRow : "Masukkan Baris", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Buangkan Baris", -InsertColumn : "Masukkan Lajur", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "Buangkan Lajur", -InsertCell : "Masukkan Sel", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "Buangkan Sel-sel", MergeCells : "Cantumkan Sel-sel", -SplitCell : "Bahagikan Sel", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Delete Table", //MISSING CellProperties : "Ciri-ciri Sel", TableProperties : "Ciri-ciri Jadual", @@ -134,7 +143,7 @@ TextareaProp : "Ciri-ciri Textarea", FormProp : "Ciri-ciri Borang", -FontFormats : "Normal;Telah Diformat;Alamat;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Perenggan (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Telah Diformat;Alamat;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Perenggan (DIV)", // Alerts and Messages ProcessingXHTML : "Memproses XHTML. Sila tunggu...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Sila pilih pautan", DlgLnkAnchorByName : "dengan menggunakan nama pautan", DlgLnkAnchorById : "dengan menggunakan ID elemen", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Tiada pautan terdapat dalam dokumen ini)", DlgLnkEMail : "Alamat E-Mail", DlgLnkEMailSubject : "Subjek Mesej", DlgLnkEMailBody : "Isi Kandungan Mesej", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Warna Border", DlgCellBtnSelect : "Pilih...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "Carian", DlgFindFindBtn : "Cari", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Ignore Font Face definitions", //MISSING DlgPasteRemoveStyles : "Remove Styles definitions", //MISSING -DlgPasteCleanBox : "Clean Up Box", //MISSING // Color Picker ColorAutomatic : "Otomatik", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "License", //MISSING DlgAboutVersion : "versi", DlgAboutInfo : "Untuk maklumat lanjut sila pergi ke" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/nb.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/nb.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/nb.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -39,12 +39,13 @@ PasteText : "Lim inn som ren tekst", PasteWord : "Lim inn fra Word", Print : "Skriv ut", -SelectAll : "Velg alle", +SelectAll : "Merk alt", RemoveFormat : "Fjern format", InsertLinkLbl : "Lenke", InsertLink : "Sett inn/Rediger lenke", RemoveLink : "Fjern lenke", Anchor : "Sett inn/Rediger anker", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Bilde", InsertImage : "Sett inn/Rediger bilde", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Blokkjuster", DecreaseIndent : "Senk niv«©", IncreaseIndent : "©¬k niv«©", +Blockquote : "Blockquote", //MISSING Undo : "Angre", Redo : "Gj©Ìr om", NumberedListLbl : "Numrert liste", @@ -103,20 +105,27 @@ ImageButton : "Bildeknapp", FitWindow : "Maksimer st©Ìrrelsen p«© redigeringsverkt©Ìyet", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "Rediger lenke", CellCM : "Celle", RowCM : "Rader", ColumnCM : "Kolonne", -InsertRow : "Sett inn rad", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Slett rader", -InsertColumn : "Sett inn kolonne", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "Slett kolonner", -InsertCell : "Sett inn celle", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "Slett celler", MergeCells : "Sl«© sammen celler", -SplitCell : "Splitt celler", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Slett tabell", CellProperties : "Celleegenskaper", TableProperties : "Tabellegenskaper", @@ -134,7 +143,7 @@ TextareaProp : "Tekstfeltegenskaper", FormProp : "Skjemaegenskaper", -FontFormats : "Normal;Formatert;Adresse;Tittel 1;Tittel 2;Tittel 3;Tittel 4;Tittel 5;Tittel 6", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatert;Adresse;Tittel 1;Tittel 2;Tittel 3;Tittel 4;Tittel 5;Tittel 6;Normal (DIV)", // Alerts and Messages ProcessingXHTML : "Lager XHTML. Vennligst vent...", @@ -221,16 +230,16 @@ DlgLnkType : "Lenketype", DlgLnkTypeURL : "URL", -DlgLnkTypeAnchor : "Lenke til bokmerke i teksten", -DlgLnkTypeEMail : "E-Post", +DlgLnkTypeAnchor : "Lenke til anker i teksten", +DlgLnkTypeEMail : "E-post", DlgLnkProto : "Protokoll", DlgLnkProtoOther : "", DlgLnkURL : "URL", DlgLnkAnchorSel : "Velg ett anker", DlgLnkAnchorByName : "Anker etter navn", DlgLnkAnchorById : "Element etter ID", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) -DlgLnkEMail : "E-Post Addresse", +DlgLnkNoAnchors : "(Ingen anker i dokumentet)", +DlgLnkEMail : "E-postadresse", DlgLnkEMailSubject : "Meldingsemne", DlgLnkEMailBody : "Melding", DlgLnkUpload : "Last opp", @@ -287,7 +296,7 @@ DlgTableAlignCenter : "Midtjuster", DlgTableAlignRight : "H©Ìyre", DlgTableWidth : "Bredde", -DlgTableWidthPx : "pixler", +DlgTableWidthPx : "piksler", DlgTableWidthPc : "prosent", DlgTableHeight : "H©Ìyde", DlgTableCellSpace : "Celle marg", @@ -296,9 +305,9 @@ DlgTableSummary : "Sammendrag", // Table Cell Dialog -DlgCellTitle : "Celle egenskaper", +DlgCellTitle : "Celleegenskaper", DlgCellWidth : "Bredde", -DlgCellWidthPx : "pixeler", +DlgCellWidthPx : "piksler", DlgCellWidthPc : "prosent", DlgCellHeight : "H©Ìyde", DlgCellWordWrap : "Tekstbrytning", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Rammefarge", DlgCellBtnSelect : "Velg...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "Finn", DlgFindFindBtn : "Finn", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Fjern skrifttyper", DlgPasteRemoveStyles : "Fjern stildefinisjoner", -DlgPasteCleanBox : "T©Ìm boksen", // Color Picker ColorAutomatic : "Automatisk", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Lisens", DlgAboutVersion : "versjon", DlgAboutInfo : "For further information go to" //MISSING -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/nl.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/nl.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/nl.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Link invoegen/wijzigen", RemoveLink : "Link verwijderen", Anchor : "Interne link", +AnchorDelete : "Anker verwijderen", InsertImageLbl : "Afbeelding", InsertImage : "Afbeelding invoegen/wijzigen", InsertFlashLbl : "Flash", @@ -52,7 +53,7 @@ InsertTableLbl : "Tabel", InsertTable : "Tabel invoegen/wijzigen", InsertLineLbl : "Lijn", -InsertLine : "Invoegen horizontale lijn", +InsertLine : "Horizontale lijn invoegen", InsertSpecialCharLbl: "Speciale tekens", InsertSpecialChar : "Speciaal teken invoegen", InsertSmileyLbl : "Smiley", @@ -70,6 +71,7 @@ BlockJustify : "Uitvullen", DecreaseIndent : "Inspringen verkleinen", IncreaseIndent : "Inspringen vergroten", +Blockquote : "Citaatblok", Undo : "Ongedaan maken", Redo : "Opnieuw uitvoeren", NumberedListLbl : "Genummerde lijst", @@ -103,20 +105,27 @@ ImageButton : "Afbeeldingsknop", FitWindow : "De editor maximaliseren", +ShowBlocks : "Toon blokken", // Context Menu EditLink : "Link wijzigen", CellCM : "Cel", RowCM : "Rij", ColumnCM : "Kolom", -InsertRow : "Rij invoegen", +InsertRowAfter : "Voeg rij in achter", +InsertRowBefore : "Voeg rij in voor", DeleteRows : "Rijen verwijderen", -InsertColumn : "Kolom invoegen", +InsertColumnAfter : "Voeg kolom in achter", +InsertColumnBefore : "Voeg kolom in voor", DeleteColumns : "Kolommen verwijderen", -InsertCell : "Cel", +InsertCellAfter : "Voeg cel in achter", +InsertCellBefore : "Voeg cel in voor", DeleteCells : "Cellen verwijderen", MergeCells : "Cellen samenvoegen", -SplitCell : "Cellen splitsen", +MergeRight : "Voeg samen naar rechts", +MergeDown : "Voeg samen naar beneden", +HorizontalSplitCell : "Splits cellen horizontaal", +VerticalSplitCell : "Splits cellen verticaal", TableDelete : "Tabel verwijderen", CellProperties : "Eigenschappen cel", TableProperties : "Eigenschappen tabel", @@ -134,7 +143,7 @@ TextareaProp : "Eigenschappen tekstvak", FormProp : "Eigenschappen formulier", -FontFormats : "Normaal;Met opmaak;Adres;Kop 1;Kop 2;Kop 3;Kop 4;Kop 5;Kop 6;Normaal (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normaal;Met opmaak;Adres;Kop 1;Kop 2;Kop 3;Kop 4;Kop 5;Kop 6;Normaal (DIV)", // Alerts and Messages ProcessingXHTML : "Bezig met verwerken XHTML. Even geduld aub...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Kies een interne link", DlgLnkAnchorByName : "Op naam interne link", DlgLnkAnchorById : "Op kenmerk interne link", -DlgLnkNoAnchors : "(Geen interne links in document gevonden)", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Geen interne links in document gevonden)", DlgLnkEMail : "E-mailadres", DlgLnkEMailSubject : "Onderwerp bericht", DlgLnkEMailBody : "Inhoud bericht", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Randkleur", DlgCellBtnSelect : "Selecteren...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Zoeken en vervangen", + // Find Dialog DlgFindTitle : "Zoeken", DlgFindFindBtn : "Zoeken", @@ -343,11 +355,10 @@ PasteAsText : "Plakken als platte tekst", PasteFromWord : "Plakken als Word-gegevens", -DlgPasteMsg2 : "Plak de tekst in het volgende vak gebruik makend van je toetstenbord (Ctrl+V) en klik op OK.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteMsg2 : "Plak de tekst in het volgende vak gebruik makend van je toetstenbord (Ctrl+V) en klik op OK.", +DlgPasteSec : "Door de beveiligingsinstellingen van uw browser is het niet mogelijk om direct vanuit het klembord in de editor te plakken. Middels opnieuw plakken in dit venster kunt u de tekst alsnog plakken in de editor.", DlgPasteIgnoreFont : "Negeer \"Font Face\"-definities", DlgPasteRemoveStyles : "Verwijder \"Style\"-definities", -DlgPasteCleanBox : "Vak opschonen", // Color Picker ColorAutomatic : "Automatisch", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Licentie", DlgAboutVersion : "Versie", DlgAboutInfo : "Voor meer informatie ga naar " -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/no.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/no.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/no.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -39,12 +39,13 @@ PasteText : "Lim inn som ren tekst", PasteWord : "Lim inn fra Word", Print : "Skriv ut", -SelectAll : "Velg alle", +SelectAll : "Merk alt", RemoveFormat : "Fjern format", InsertLinkLbl : "Lenke", InsertLink : "Sett inn/Rediger lenke", RemoveLink : "Fjern lenke", Anchor : "Sett inn/Rediger anker", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Bilde", InsertImage : "Sett inn/Rediger bilde", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Blokkjuster", DecreaseIndent : "Senk niv«©", IncreaseIndent : "©¬k niv«©", +Blockquote : "Blockquote", //MISSING Undo : "Angre", Redo : "Gj©Ìr om", NumberedListLbl : "Numrert liste", @@ -103,20 +105,27 @@ ImageButton : "Bildeknapp", FitWindow : "Maksimer st©Ìrrelsen p«© redigeringsverkt©Ìyet", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "Rediger lenke", CellCM : "Celle", RowCM : "Rader", ColumnCM : "Kolonne", -InsertRow : "Sett inn rad", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Slett rader", -InsertColumn : "Sett inn kolonne", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "Slett kolonner", -InsertCell : "Sett inn celle", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "Slett celler", MergeCells : "Sl«© sammen celler", -SplitCell : "Splitt celler", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Slett tabell", CellProperties : "Celleegenskaper", TableProperties : "Tabellegenskaper", @@ -134,7 +143,7 @@ TextareaProp : "Tekstfeltegenskaper", FormProp : "Skjemaegenskaper", -FontFormats : "Normal;Formatert;Adresse;Tittel 1;Tittel 2;Tittel 3;Tittel 4;Tittel 5;Tittel 6", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatert;Adresse;Tittel 1;Tittel 2;Tittel 3;Tittel 4;Tittel 5;Tittel 6;Normal (DIV)", // Alerts and Messages ProcessingXHTML : "Lager XHTML. Vennligst vent...", @@ -221,16 +230,16 @@ DlgLnkType : "Lenketype", DlgLnkTypeURL : "URL", -DlgLnkTypeAnchor : "Lenke til bokmerke i teksten", -DlgLnkTypeEMail : "E-Post", +DlgLnkTypeAnchor : "Lenke til anker i teksten", +DlgLnkTypeEMail : "E-post", DlgLnkProto : "Protokoll", DlgLnkProtoOther : "", DlgLnkURL : "URL", DlgLnkAnchorSel : "Velg ett anker", DlgLnkAnchorByName : "Anker etter navn", DlgLnkAnchorById : "Element etter ID", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) -DlgLnkEMail : "E-Post Addresse", +DlgLnkNoAnchors : "(Ingen anker i dokumentet)", +DlgLnkEMail : "E-postadresse", DlgLnkEMailSubject : "Meldingsemne", DlgLnkEMailBody : "Melding", DlgLnkUpload : "Last opp", @@ -287,7 +296,7 @@ DlgTableAlignCenter : "Midtjuster", DlgTableAlignRight : "H©Ìyre", DlgTableWidth : "Bredde", -DlgTableWidthPx : "pixler", +DlgTableWidthPx : "piksler", DlgTableWidthPc : "prosent", DlgTableHeight : "H©Ìyde", DlgTableCellSpace : "Celle marg", @@ -296,9 +305,9 @@ DlgTableSummary : "Sammendrag", // Table Cell Dialog -DlgCellTitle : "Celle egenskaper", +DlgCellTitle : "Celleegenskaper", DlgCellWidth : "Bredde", -DlgCellWidthPx : "pixeler", +DlgCellWidthPx : "piksler", DlgCellWidthPc : "prosent", DlgCellHeight : "H©Ìyde", DlgCellWordWrap : "Tekstbrytning", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Rammefarge", DlgCellBtnSelect : "Velg...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "Finn", DlgFindFindBtn : "Finn", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Fjern skrifttyper", DlgPasteRemoveStyles : "Fjern stildefinisjoner", -DlgPasteCleanBox : "T©Ìm boksen", // Color Picker ColorAutomatic : "Automatisk", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Lisens", DlgAboutVersion : "versjon", DlgAboutInfo : "For further information go to" //MISSING -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/pl.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/pl.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/pl.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Wstaw/edytuj hiper©È«¨cze", RemoveLink : "Usu«Í hiper©È«¨cze", Anchor : "Wstaw/edytuj kotwic«¸", +AnchorDelete : "Usu«Í kotwic«¸", InsertImageLbl : "Obrazek", InsertImage : "Wstaw/edytuj obrazek", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Wyr«Ñwnaj do lewej i prawej", DecreaseIndent : "Zmniejsz wci«¸cie", IncreaseIndent : "Zwi«¸ksz wci«¸cie", +Blockquote : "Cytat", Undo : "Cofnij", Redo : "Pon«Ñw", NumberedListLbl : "Lista numerowana", @@ -93,30 +95,37 @@ PageBreak : "Wstaw odst«¸p", Form : "Formularz", -Checkbox : "Checkbox", -RadioButton : "Pole wyboru", +Checkbox : "Pole wyboru (checkbox)", +RadioButton : "Pole wyboru (radio)", TextField : "Pole tekstowe", Textarea : "Obszar tekstowy", HiddenField : "Pole ukryte", Button : "Przycisk", SelectionField : "Lista wyboru", -ImageButton : "Przycisk obrazek", +ImageButton : "Przycisk-obrazek", FitWindow : "Maksymalizuj rozmiar edytora", +ShowBlocks : "Poka«÷ bloki", // Context Menu EditLink : "Edytuj hiper©È«¨cze", CellCM : "Kom«Ñrka", RowCM : "Wiersz", ColumnCM : "Kolumna", -InsertRow : "Wstaw wiersz", +InsertRowAfter : "Wstaw wiersz poni«÷ej", +InsertRowBefore : "Wstaw wiersz powy«÷ej", DeleteRows : "Usu«Í wiersze", -InsertColumn : "Wstaw kolumn«¸", +InsertColumnAfter : "Wstaw kolumn«¸ z prawej", +InsertColumnBefore : "Wstaw kolumn«¸ z lewej", DeleteColumns : "Usu«Í kolumny", -InsertCell : "Wstaw kom«Ñrk«¸", +InsertCellAfter : "Wstaw kom«Ñrk«¸ z prawej", +InsertCellBefore : "Wstaw kom«Ñrk«¸ z lewej", DeleteCells : "Usu«Í kom«Ñrki", MergeCells : "Po©È«¨cz kom«Ñrki", -SplitCell : "Podziel kom«Ñrk«¸", +MergeRight : "Po©È«¨cz z kom«Ñrk«¨ z prawej", +MergeDown : "Po©È«¨cz z kom«Ñrk«¨ poni«÷ej", +HorizontalSplitCell : "Podziel kom«Ñrk«¸ poziomo", +VerticalSplitCell : "Podziel kom«Ñrk«¸ pionowo", TableDelete : "Usu«Í tabel«¸", CellProperties : "W©Èa«Üciwo«Üci kom«Ñrki", TableProperties : "W©Èa«Üciwo«Üci tabeli", @@ -125,16 +134,16 @@ AnchorProp : "W©Èa«Üciwo«Üci kotwicy", ButtonProp : "W©Èa«Üciwo«Üci przycisku", -CheckboxProp : "Checkbox - w©Èa«Üciwo«Üci", +CheckboxProp : "W©Èa«Üciwo«Üci pola wyboru (checkbox)", HiddenFieldProp : "W©Èa«Üciwo«Üci pola ukrytego", -RadioButtonProp : "W©Èa«Üciwo«Üci pola wyboru", +RadioButtonProp : "W©Èa«Üciwo«Üci pola wyboru (radio)", ImageButtonProp : "W©Èa«Üciwo«Üci przycisku obrazka", TextFieldProp : "W©Èa«Üciwo«Üci pola tekstowego", SelectionFieldProp : "W©Èa«Üciwo«Üci listy wyboru", TextareaProp : "W©Èa«Üciwo«Üci obszaru tekstowego", FormProp : "W©Èa«Üciwo«Üci formularza", -FontFormats : "Normalny;Tekst sformatowany;Adres;Nag©È«Ñwek 1;Nag©È«Ñwek 2;Nag©È«Ñwek 3;Nag©È«Ñwek 4;Nag©È«Ñwek 5;Nag©È«Ñwek 6", //REVIEW : Check _getfontformat.html +FontFormats : "Normalny;Tekst sformatowany;Adres;Nag©È«Ñwek 1;Nag©È«Ñwek 2;Nag©È«Ñwek 3;Nag©È«Ñwek 4;Nag©È«Ñwek 5;Nag©È«Ñwek 6", // Alerts and Messages ProcessingXHTML : "Przetwarzanie XHTML. Prosz«¸ czeka««...", @@ -146,8 +155,8 @@ NotImplemented : "Komenda niezaimplementowana", UnknownToolbarSet : "Pasek narz«¸dzi \"%1\" nie istnieje", NoActiveX : "Ustawienia zabezpiecze«Í twojej przegl«¨darki mog«¨ ograniczy«« niekt«Ñre funkcje edytora. Musisz w©È«¨czy«« opcj«¸ \"Uruchamianie formant«Ñw Activex i dodatk«Ñw plugin\". W przeciwnym wypadku mog«¨ pojawia«« si«¸ b©È«¸dy.", -BrowseServerBlocked : "Okno menad«÷era plik«Ñw nie mo«÷e zosta«« otwarte. Upewnij si«¸, «÷e wszystkie blokady popup s«¨ wy©È«¨czone.", -DialogBlocked : "Nie mo«÷na otworzy«« okna dialogowego. Upewnij si«¸, «÷e wszystkie blokady popup s«¨ wy©È«¨czone.", +BrowseServerBlocked : "Nie mo«÷na otworzy«« okno menad«÷era plik«Ñw. Upewnij si«¸, «÷e wszystkie blokady wyskakuj«¨cych okienek s«¨ wy©È«¨czone.", +DialogBlocked : "Nie mo«÷na otworzy«« okna dialogowego. Upewnij si«¸, «÷e wszystkie blokady wyskakuj«¨cych okienek s«¨ wy©È«¨czone.", // Dialogs DlgBtnOK : "OK", @@ -160,7 +169,7 @@ DlgAlertUrl : "Prosz«¸ poda«« URL", // General Dialogs Labels -DlgGenNotSet : "", +DlgGenNotSet : "", DlgGenId : "Id", DlgGenLangDir : "Kierunek tekstu", DlgGenLangDirLtr : "Od lewej do prawej (LTR)", @@ -169,17 +178,17 @@ DlgGenAccessKey : "Klawisz dost«¸pu", DlgGenName : "Nazwa", DlgGenTabIndex : "Indeks tabeli", -DlgGenLongDescr : "Long Description URL", -DlgGenClass : "Stylesheet Classes", -DlgGenTitle : "Advisory Title", -DlgGenContType : "Advisory Content Type", -DlgGenLinkCharset : "Linked Resource Charset", +DlgGenLongDescr : "D©Èugi opis hiper©È«¨cza", +DlgGenClass : "Nazwa klasy CSS", +DlgGenTitle : "Opis obiektu docelowego", +DlgGenContType : "Typ MIME obiektu docelowego", +DlgGenLinkCharset : "Kodowanie znak«Ñw obiektu docelowego", DlgGenStyle : "Styl", // Image Dialog DlgImgTitle : "W©Èa«Üciwo«Üci obrazka", DlgImgInfoTab : "Informacje o obrazku", -DlgImgBtnUpload : "Sy«Ülij", +DlgImgBtnUpload : "Wy«Ülij", DlgImgURL : "Adres URL", DlgImgUpload : "Wy«Ülij", DlgImgAlt : "Tekst zast«¸pczy", @@ -202,7 +211,7 @@ DlgImgAlignTop : "Do g«Ñry", DlgImgPreview : "Podgl«¨d", DlgImgAlertUrl : "Podaj adres obrazka.", -DlgImgLinkTab : "Link", +DlgImgLinkTab : "Hiper©È«¨cze", // Flash Dialog DlgFlashTitle : "W©Èa«Üciwo«Üci elementu Flash", @@ -229,11 +238,11 @@ DlgLnkAnchorSel : "Wybierz etykiet«¸", DlgLnkAnchorByName : "Wg etykiety", DlgLnkAnchorById : "Wg identyfikatora elementu", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(W dokumencie nie zdefiniowano «÷adnych etykiet)", DlgLnkEMail : "Adres e-mail", DlgLnkEMailSubject : "Temat", DlgLnkEMailBody : "Tre«Ü««", -DlgLnkUpload : "Upload", +DlgLnkUpload : "Wy«Ülij", DlgLnkBtnUpload : "Wy«Ülij", DlgLnkTarget : "Cel", @@ -262,7 +271,7 @@ DlnLnkMsgNoUrl : "Podaj adres URL", DlnLnkMsgNoEMail : "Podaj adres e-mail", DlnLnkMsgNoAnchor : "Wybierz etykiet«¸", -DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces", //MISSING +DlnLnkMsgInvPopName : "Nazwa wyskakuj«¨cego okienka musi zaczyna«« si«¸ od znaku alfanumerycznego i nie mo«÷e zawiera«« spacji", // Color Dialog DlgColorTitle : "Wybierz kolor", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Kolor ramki", DlgCellBtnSelect : "Wybierz...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Znajd«õ i zamie«Í", + // Find Dialog DlgFindTitle : "Znajd«õ", DlgFindFindBtn : "Znajd«õ", @@ -344,10 +356,9 @@ PasteFromWord : "Wklej z Worda", DlgPasteMsg2 : "Prosz«¸ wklei«« w poni«÷szym polu u«÷ywaj«¨c klawiaturowego skr«Ñtu (Ctrl+V) i klikn«¨«« OK.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "Zabezpieczenia przegl«¨darki uniemo«÷liwiaj«¨ wklejenie danych bezpo«Ürednio do edytora. Prosz«¸ dane wklei«« ponownie w tym okienku.", DlgPasteIgnoreFont : "Ignoruj definicje 'Font Face'", DlgPasteRemoveStyles : "Usu«Í definicje Styl«Ñw", -DlgPasteCleanBox : "Wyczy«Ü««", // Color Picker ColorAutomatic : "Automatycznie", @@ -368,7 +379,7 @@ DlgSpellBtnIgnoreAll : "Ignoruj wszystkie", DlgSpellBtnReplace : "Zmie«Í", DlgSpellBtnReplaceAll : "Zmie«Í wszystkie", -DlgSpellBtnUndo : "Undo", +DlgSpellBtnUndo : "Cofnij", DlgSpellNoSuggestions : "- Brak sugestii -", DlgSpellProgress : "Trwa sprawdzanie ...", DlgSpellNoMispell : "Sprawdzanie zako«Íczone: nie znaleziono b©È«¸d«Ñw", @@ -381,14 +392,14 @@ // Button Dialog DlgButtonText : "Tekst (Warto«Ü««)", DlgButtonType : "Typ", -DlgButtonTypeBtn : "Button", //MISSING -DlgButtonTypeSbm : "Submit", //MISSING -DlgButtonTypeRst : "Reset", //MISSING +DlgButtonTypeBtn : "Przycisk", +DlgButtonTypeSbm : "Wy«Ülij", +DlgButtonTypeRst : "Wyzeruj", // Checkbox and Radio Button Dialogs DlgCheckboxName : "Nazwa", DlgCheckboxValue : "Warto«Ü««", -DlgCheckboxSelected : "Zaznaczony", +DlgCheckboxSelected : "Zaznaczone", // Form Dialog DlgFormName : "Nazwa", @@ -432,7 +443,7 @@ // Bulleted List Dialog BulletedListProp : "W©Èa«Üciwo«Üci listy punktowanej", NumberedListProp : "W©Èa«Üciwo«Üci listy numerowanej", -DlgLstStart : "Start", //MISSING +DlgLstStart : "Pocz«¨tek", DlgLstType : "Typ", DlgLstTypeCircle : "Ko©Èo", DlgLstTypeDisc : "Dysk", @@ -455,18 +466,18 @@ DlgDocLangDirRTL : "Od prawej do lewej (RTL)", DlgDocLangCode : "Kod j«¸zyka", DlgDocCharSet : "Kodowanie znak«Ñw", -DlgDocCharSetCE : "Central European", //MISSING -DlgDocCharSetCT : "Chinese Traditional (Big5)", //MISSING -DlgDocCharSetCR : "Cyrillic", //MISSING -DlgDocCharSetGR : "Greek", //MISSING -DlgDocCharSetJP : "Japanese", //MISSING -DlgDocCharSetKR : "Korean", //MISSING -DlgDocCharSetTR : "Turkish", //MISSING -DlgDocCharSetUN : "Unicode (UTF-8)", //MISSING -DlgDocCharSetWE : "Western European", //MISSING +DlgDocCharSetCE : "ªÜrodkowoeuropejskie", +DlgDocCharSetCT : "Chi«Ískie tradycyjne (Big5)", +DlgDocCharSetCR : "Cyrylica", +DlgDocCharSetGR : "Greckie", +DlgDocCharSetJP : "Japo«Ískie", +DlgDocCharSetKR : "Korea«Ískie", +DlgDocCharSetTR : "Tureckie", +DlgDocCharSetUN : "Unicode (UTF-8)", +DlgDocCharSetWE : "Zachodnioeuropejskie", DlgDocCharSetOther : "Inne kodowanie znak«Ñw", -DlgDocDocType : "Nag©Èowek typu dokumentu", +DlgDocDocType : "Nag©È«Ñwek typu dokumentu", DlgDocDocTypeOther : "Inny typ dokumentu", DlgDocIncXHTML : "Do©È«¨cz deklaracj«¸ XHTML", DlgDocBgColor : "Kolor t©Èa", @@ -484,7 +495,7 @@ DlgDocMeIndex : "S©Èowa kluczowe (oddzielone przecinkami)", DlgDocMeDescr : "Opis dokumentu", DlgDocMeAuthor : "Autor", -DlgDocMeCopy : "Copyright", +DlgDocMeCopy : "Prawa autorskie", DlgDocPreview : "Podgl«¨d", // Templates Dialog @@ -493,7 +504,7 @@ DlgTemplatesSelMsg : "Wybierz szablon do otwarcia w edytorze
      (obecna zawarto«Ü«« okna edytora zostanie utracona):", DlgTemplatesLoading : "©¨adowanie listy szablon«Ñw. Prosz«¸ czeka««...", DlgTemplatesNoTpl : "(Brak zdefiniowanych szablon«Ñw)", -DlgTemplatesReplace : "Replace actual contents", //MISSING +DlgTemplatesReplace : "Zast«¨p aktualn«¨ zawarto«Ü««", // About Dialog DlgAboutAboutTab : "O ...", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Licencja", DlgAboutVersion : "wersja", DlgAboutInfo : "Wi«¸cej informacji uzyskasz pod adresem" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/pt-br.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/pt-br.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/pt-br.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Inserir/Editar Hiperlink", RemoveLink : "Remover Hiperlink", Anchor : "Inserir/Editar ª¤ncora", +AnchorDelete : "Remover ª¤ncora", InsertImageLbl : "Figura", InsertImage : "Inserir/Editar Figura", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Justificado", DecreaseIndent : "Diminuir Recuo", IncreaseIndent : "Aumentar Recuo", +Blockquote : "Recuo", Undo : "Desfazer", Redo : "Refazer", NumberedListLbl : "Numera«®«ªo", @@ -103,20 +105,27 @@ ImageButton : "Bot«ªo de Imagem", FitWindow : "Maximizar o tamanho do editor", +ShowBlocks : "Mostrar blocos", // Context Menu EditLink : "Editar Hiperlink", CellCM : "C«±lula", RowCM : "Linha", ColumnCM : "Coluna", -InsertRow : "Inserir Linha", +InsertRowAfter : "Inserir linha abaixo", +InsertRowBefore : "Inserir linha acima", DeleteRows : "Remover Linhas", -InsertColumn : "Inserir Coluna", +InsertColumnAfter : "Inserir coluna «¢ direita", +InsertColumnBefore : "Inserir coluna «¢ esquerda", DeleteColumns : "Remover Colunas", -InsertCell : "Inserir C«±lulas", +InsertCellAfter : "Inserir c«±lula «¢ direita", +InsertCellBefore : "Inserir c«±lula «¢ esquerda", DeleteCells : "Remover C«±lulas", MergeCells : "Mesclar C«±lulas", -SplitCell : "Dividir C«±lular", +MergeRight : "Mesclar com c«±lula «¢ direita", +MergeDown : "Mesclar com c«±lula abaixo", +HorizontalSplitCell : "Dividir c«±lula horizontalmente", +VerticalSplitCell : "Dividir c«±lula verticalmente", TableDelete : "Apagar Tabela", CellProperties : "Formatar C«±lula", TableProperties : "Formatar Tabela", @@ -134,7 +143,7 @@ TextareaProp : "Formatar ª¡rea de Texto", FormProp : "Formatar Formul«¡rio", -FontFormats : "Normal;Formatado;Endere«®o;T«¿tulo 1;T«¿tulo 2;T«¿tulo 3;T«¿tulo 4;T«¿tulo 5;T«¿tulo 6", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatado;Endere«®o;T«¿tulo 1;T«¿tulo 2;T«¿tulo 3;T«¿tulo 4;T«¿tulo 5;T«¿tulo 6", // Alerts and Messages ProcessingXHTML : "Processando XHTML. Por favor, aguarde...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Selecione uma «¤ncora", DlgLnkAnchorByName : "Pelo Nome da «¤ncora", DlgLnkAnchorById : "Pelo Id do Elemento", -DlgLnkNoAnchors : "(N«ªo h«¡ «¤ncoras dispon«¿veis neste documento)", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(N«ªo h«¡ «¤ncoras dispon«¿veis neste documento)", DlgLnkEMail : "Endere«®o E-Mail", DlgLnkEMailSubject : "Assunto da Mensagem", DlgLnkEMailBody : "Corpo da Mensagem", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Cor da Borda", DlgCellBtnSelect : "Selecionar...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Localizar e Substituir", + // Find Dialog DlgFindTitle : "Localizar...", DlgFindFindBtn : "Localizar", @@ -344,10 +356,9 @@ PasteFromWord : "Colar do Word", DlgPasteMsg2 : "Transfira o link usado no box usando o teclado com (Ctrl+V) e OK.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "As configura«®«Øes de seguran«®a do seu navegador n«ªo permitem que o editor acesse os dados da «¡rea de transfer«´ncia diretamente. Por favor cole o conte«âdo novamente nesta janela.", DlgPasteIgnoreFont : "Ignorar defini«®«Øes de fonte", DlgPasteRemoveStyles : "Remove defini«®«Øes de estilo", -DlgPasteCleanBox : "Limpar Box", // Color Picker ColorAutomatic : "Autom«¡tico", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Licen«®a", DlgAboutVersion : "vers«ªo", DlgAboutInfo : "Para maiores informa«®«Øes visite" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/pt.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/pt.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/pt.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Inserir/Editar Hiperliga«®«ªo", RemoveLink : "Eliminar Hiperliga«®«ªo", Anchor : " Inserir/Editar ª¤ncora", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Imagem", InsertImage : "Inserir/Editar Imagem", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Justificado", DecreaseIndent : "Diminuir Avan«®o", IncreaseIndent : "Aumentar Avan«®o", +Blockquote : "Blockquote", //MISSING Undo : "Anular", Redo : "Repetir", NumberedListLbl : "Numera«®«ªo", @@ -103,20 +105,27 @@ ImageButton : "Bot«ªo de Imagem", FitWindow : "Maximizar o tamanho do editor", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "Editar Hiperliga«®«ªo", CellCM : "C«±lula", RowCM : "Linha", ColumnCM : "Coluna", -InsertRow : "Inserir Linha", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Eliminar Linhas", -InsertColumn : "Inserir Coluna", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "Eliminar Coluna", -InsertCell : "Inserir C«±lula", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "Eliminar C«±lula", MergeCells : "Unir C«±lulas", -SplitCell : "Dividir C«±lula", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Eliminar Tabela", CellProperties : "Propriedades da C«±lula", TableProperties : "Propriedades da Tabela", @@ -134,7 +143,7 @@ TextareaProp : "Propriedades da ª¡rea de Texto", FormProp : "Propriedades do Formul«¡rio", -FontFormats : "Normal;Formatado;Endere«®o;T«¿tulo 1;T«¿tulo 2;T«¿tulo 3;T«¿tulo 4;T«¿tulo 5;T«¿tulo 6", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatado;Endere«®o;T«¿tulo 1;T«¿tulo 2;T«¿tulo 3;T«¿tulo 4;T«¿tulo 5;T«¿tulo 6", // Alerts and Messages ProcessingXHTML : "A Processar XHTML. Por favor, espere...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Seleccionar una refer«´ncia", DlgLnkAnchorByName : "Por Nome de Refer«´ncia", DlgLnkAnchorById : "Por ID de elemento", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(N«ªo h«¡ refer«´ncias dispon«¿veis no documento)", DlgLnkEMail : "Endere«®o de E-Mail", DlgLnkEMailSubject : "T«¿tulo de Mensagem", DlgLnkEMailBody : "Corpo da Mensagem", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Cor do Limite", DlgCellBtnSelect : "Seleccione...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "Procurar", DlgFindFindBtn : "Procurar", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Ignorar da defini«®«Øes do Tipo de Letra ", DlgPasteRemoveStyles : "Remover as defini«®«Øes de Estilos", -DlgPasteCleanBox : "Caixa de Limpeza", // Color Picker ColorAutomatic : "Autom«¡tico", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Licen«®a", DlgAboutVersion : "vers«ªo", DlgAboutInfo : "Para mais informa«®«Øes por favor dirija-se a" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ro.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ro.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ro.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Insereaz«¥/Editeaz«¥ link (leg«¥tur«¥ web)", RemoveLink : "ªÂnl«¥tur«¥ link (leg«¥tur«¥ web)", Anchor : "Insereaz«¥/Editeaz«¥ ancor«¥", +AnchorDelete : "ªßterge ancor«¥", InsertImageLbl : "Imagine", InsertImage : "Insereaz«¥/Editeaz«¥ imagine", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Aliniere «Ân bloc (Block Justify)", DecreaseIndent : "Scade indentarea", IncreaseIndent : "Cre«ßte indentarea", +Blockquote : "Citat", Undo : "Starea anterioar«¥ (undo)", Redo : "Starea ulterioar«¥ (redo)", NumberedListLbl : "List«¥ numerotat«¥", @@ -103,20 +105,27 @@ ImageButton : "Buton imagine (ImageButton)", FitWindow : "Maximizeaz«¥ m«¥rimea editorului", +ShowBlocks : "Arat«¥ blocurile", // Context Menu EditLink : "Editeaz«¥ Link", CellCM : "Celul«¥", RowCM : "Linie", ColumnCM : "Coloan«¥", -InsertRow : "Insereaz«¥ linie", +InsertRowAfter : "Insereaz«¥ linie dup«¥", +InsertRowBefore : "Insereaz«¥ linie «Ânainte", DeleteRows : "ªßterge linii", -InsertColumn : "Insereaz«¥ coloan«¥", +InsertColumnAfter : "Insereaz«¥ coloan«¥ dup«¥", +InsertColumnBefore : "Insereaz«¥ coloan«¥ «Ânainte", DeleteColumns : "ªßterge celule", -InsertCell : "Insereaz«¥ celul«¥", +InsertCellAfter : "Insereaz«¥ celul«¥ dup«¥", +InsertCellBefore : "Insereaz«¥ celul«¥ «Ânainte", DeleteCells : "ªßterge celule", MergeCells : "Une«ßte celule", -SplitCell : "ªÂmparte celul«¥", +MergeRight : "Une«ßte la dreapta", +MergeDown : "Une«ßte jos", +HorizontalSplitCell : "ªÂmparte celula pe orizontal«¥", +VerticalSplitCell : "ªÂmparte celula pe vertical«¥", TableDelete : "ªßterge tabel", CellProperties : "Propriet«¥«áile celulei", TableProperties : "Propriet«¥«áile tabelului", @@ -134,7 +143,7 @@ TextareaProp : "Propriet«¥«ái suprafa«á«¥ text (Textarea)", FormProp : "Propriet«¥«ái formular (Form)", -FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", //REVIEW : Check _getfontformat.html //MISSING +FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", //MISSING // Alerts and Messages ProcessingXHTML : "Proces«¥m XHTML. V«¥ rug«¥m a«ßtepta«ái...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Selecta«ái o ancor«¥", DlgLnkAnchorByName : "dup«¥ numele ancorei", DlgLnkAnchorById : "dup«¥ Id-ul elementului", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Nicio ancor«¥ disponibil«¥ «Ân document)", DlgLnkEMail : "Adres«¥ de e-mail", DlgLnkEMailSubject : "Subiectul mesajului", DlgLnkEMailBody : "Con«áinutul mesajului", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Culoarea marginii", DlgCellBtnSelect : "Selecta«ái...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "G«¥se«ßte «ßi «Ânlocuie«ßte", + // Find Dialog DlgFindTitle : "G«¥se«ßte", DlgFindFindBtn : "G«¥se«ßte", @@ -344,10 +356,9 @@ PasteFromWord : "Adaug«¥ din Word", DlgPasteMsg2 : "V«¥ rug«¥m ad«¥uga«ái «Ân c«¥su«áa urm«¥toare folosind tastatura (Ctrl+V) «ßi ap«¥sa«ái OK.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "Din cauza set«¥rilor de securitate ale programului dvs. cu care naviga«ái pe internet (browser), editorul nu poate accesa direct datele din clipboard. Va trebui s«¥ ad«¥uga«ái din nou datele «Ân aceast«¥ fereastr«¥.", DlgPasteIgnoreFont : "Ignor«¥ defini«áiile Font Face", DlgPasteRemoveStyles : "ªßterge defini«áiile stilurilor", -DlgPasteCleanBox : "ªßterge c«¥su«áa", // Color Picker ColorAutomatic : "Automatic", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Licen«á«¥", DlgAboutVersion : "versiune", DlgAboutInfo : "Pentru informa«áii am«¥nun«áite, vizita«ái" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ru.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ru.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/ru.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "§£§ã§ä§Ñ§Ó§Ú§ä§î/§²§Ö§Õ§Ñ§Ü§ä§Ú§â§à§Ó§Ñ§ä§î §ã§ã§í§Ý§Ü§å", RemoveLink : "§µ§Ò§â§Ñ§ä§î §ã§ã§í§Ý§Ü§å", Anchor : "§£§ã§ä§Ñ§Ó§Ú§ä§î/§²§Ö§Õ§Ñ§Ü§ä§Ú§â§à§Ó§Ñ§ä§î §ñ§Ü§à§â§î", +AnchorDelete : "§µ§Ò§â§Ñ§ä§î §ñ§Ü§à§â§î", InsertImageLbl : "§ª§Ù§à§Ò§â§Ñ§Ø§Ö§ß§Ú§Ö", InsertImage : "§£§ã§ä§Ñ§Ó§Ú§ä§î/§²§Ö§Õ§Ñ§Ü§ä§Ú§â§à§Ó§Ñ§ä§î §Ú§Ù§à§Ò§â§Ñ§Ø§Ö§ß§Ú§Ö", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "§±§à §ê§Ú§â§Ú§ß§Ö", DecreaseIndent : "§µ§Þ§Ö§ß§î§ê§Ú§ä§î §à§ä§ã§ä§å§á", IncreaseIndent : "§µ§Ó§Ö§Ý§Ú§é§Ú§ä§î §à§ä§ã§ä§å§á", +Blockquote : "§¸§Ú§ä§Ñ§ä§Ñ", Undo : "§°§ä§Þ§Ö§ß§Ú§ä§î", Redo : "§±§à§Ó§ä§à§â§Ú§ä§î", NumberedListLbl : "§¯§å§Þ§Ö§â§à§Ó§Ñ§ß§ß§í§Û §ã§á§Ú§ã§à§Ü", @@ -103,20 +105,27 @@ ImageButton : "§¬§ß§à§á§Ü§Ñ §ã §Ú§Ù§à§Ò§â§Ñ§Ø§Ö§ß§Ú§Ö§Þ", FitWindow : "§²§Ñ§Ù§Ó§Ö§â§ß§å§ä§î §à§Ü§ß§à §â§Ö§Õ§Ñ§Ü§ä§à§â§Ñ", +ShowBlocks : "§±§à§Ü§Ñ§Ù§Ñ§ä§î §Ò§Ý§à§Ü§Ú", // Context Menu EditLink : "§£§ã§ä§Ñ§Ó§Ú§ä§î §ã§ã§í§Ý§Ü§å", CellCM : "§Á§é§Ö§Û§Ü§Ñ", RowCM : "§³§ä§â§à§Ü§Ñ", ColumnCM : "§¬§à§Ý§à§ß§Ü§Ñ", -InsertRow : "§£§ã§ä§Ñ§Ó§Ú§ä§î §ã§ä§â§à§Ü§å", +InsertRowAfter : "§£§ã§ä§Ñ§Ó§Ú§ä§î §ã§ä§â§à§Ü§å §á§à§ã§Ý§Ö", +InsertRowBefore : "§£§ã§ä§Ñ§Ó§Ú§ä§î §ã§ä§â§à§Ü§å §Õ§à", DeleteRows : "§µ§Õ§Ñ§Ý§Ú§ä§î §ã§ä§â§à§Ü§Ú", -InsertColumn : "§£§ã§ä§Ñ§Ó§Ú§ä§î §Ü§à§Ý§à§ß§Ü§å", +InsertColumnAfter : "§£§ã§ä§Ñ§Ó§Ú§ä§î §Ü§à§Ý§à§ß§Ü§å §á§à§ã§Ý§Ö", +InsertColumnBefore : "§£§ã§ä§Ñ§Ó§Ú§ä§î §Ü§à§Ý§à§ß§Ü§å §Õ§à", DeleteColumns : "§µ§Õ§Ñ§Ý§Ú§ä§î §Ü§à§Ý§à§ß§Ü§Ú", -InsertCell : "§£§ã§ä§Ñ§Ó§Ú§ä§î §ñ§é§Ö§Û§Ü§å", +InsertCellAfter : "§£§ã§ä§Ñ§Ó§Ú§ä§î §ñ§é§Ö§Û§Ü§å §á§à§ã§Ý§Ö", +InsertCellBefore : "§£§ã§ä§Ñ§Ó§Ú§ä§î §ñ§é§Ö§Û§Ü§å §Õ§à", DeleteCells : "§µ§Õ§Ñ§Ý§Ú§ä§î §ñ§é§Ö§Û§Ü§Ú", MergeCells : "§³§à§Ö§Õ§Ú§ß§Ú§ä§î §ñ§é§Ö§Û§Ü§Ú", -SplitCell : "§²§Ñ§Ù§Ò§Ú§ä§î §ñ§é§Ö§Û§Ü§å", +MergeRight : "§³§à§Ö§Õ§Ú§ß§Ú§ä§î §Ó§á§â§Ñ§Ó§à", +MergeDown : "§³§à§Ö§Õ§Ú§ß§Ú§ä§î §Ó§ß§Ú§Ù", +HorizontalSplitCell : "§²§Ñ§Ù§Ò§Ú§ä§î §ñ§é§Ö§Û§Ü§å §Ô§à§â§Ú§Ù§à§ß§ä§Ñ§Ý§î§ß§à", +VerticalSplitCell : "§²§Ñ§Ù§Ò§Ú§ä§î §ñ§é§Ö§Û§Ü§å §Ó§Ö§â§ä§Ú§Ü§Ñ§Ý§î§ß§à", TableDelete : "§µ§Õ§Ñ§Ý§Ú§ä§î §ä§Ñ§Ò§Ý§Ú§è§å", CellProperties : "§³§Ó§à§Û§ã§ä§Ó§Ñ §ñ§é§Ö§Û§Ü§Ú", TableProperties : "§³§Ó§à§Û§ã§ä§Ó§Ñ §ä§Ñ§Ò§Ý§Ú§è§í", @@ -134,10 +143,10 @@ TextareaProp : "§³§Ó§à§Û§ã§ä§Ó§Ñ §ä§Ö§Ü§ã§ä§à§Ó§à§Û §à§Ò§Ý§Ñ§ã§ä§Ú", FormProp : "§³§Ó§à§Û§ã§ä§Ó§Ñ §æ§à§â§Þ§í", -FontFormats : "§¯§à§â§Þ§Ñ§Ý§î§ß§í§Û;§¶§à§â§Þ§Ñ§ä§Ú§â§à§Ó§Ñ§ß§ß§í§Û;§¡§Õ§â§Ö§ã;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 1;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 2;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 3;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 4;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 5;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 6;§¯§à§â§Þ§Ñ§Ý§î§ß§í§Û (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "§¯§à§â§Þ§Ñ§Ý§î§ß§í§Û;§¶§à§â§Þ§Ñ§ä§Ú§â§à§Ó§Ñ§ß§ß§í§Û;§¡§Õ§â§Ö§ã;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 1;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 2;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 3;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 4;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 5;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 6;§¯§à§â§Þ§Ñ§Ý§î§ß§í§Û (DIV)", // Alerts and Messages -ProcessingXHTML : "§°§Ò§â§Ñ§Ò§à§ä§Ü§Ñ XHTML. §±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ §á§à§Õ§à§Ø§Õ§Ú§ä§Ö...", +ProcessingXHTML : "§°§Ò§â§Ñ§Ò§à§ä§Ü§Ñ XHTML. §±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ, §á§à§Õ§à§Ø§Õ§Ú§ä§Ö...", Done : "§³§Õ§Ö§Ý§Ñ§ß§à", PasteWordConfirm : "§´§Ö§Ü§ã§ä, §Ü§à§ä§à§â§í§Û §Ó§í §ç§à§ä§Ú§ä§Ö §Ó§ã§ä§Ñ§Ó§Ú§ä§î, §á§à§ç§à§Ø §ß§Ñ §Ü§à§á§Ú§â§å§Ö§Þ§í§Û §Ú§Ù Word. §£§í §ç§à§ä§Ú§ä§Ö §à§é§Ú§ã§ä§Ú§ä§î §Ö§Ô§à §á§Ö§â§Ö§Õ §Ó§ã§ä§Ñ§Ó§Ü§à§Û?", NotCompatiblePaste : "§¿§ä§Ñ §Ü§à§Þ§Ñ§ß§Õ§Ñ §Õ§à§ã§ä§å§á§ß§Ñ §Õ§Ý§ñ Internet Explorer §Ó§Ö§â§ã§Ú§Ú 5.5 §Ú§Ý§Ú §Ó§í§ê§Ö. §£§í §ç§à§ä§Ú§ä§Ö §Ó§ã§ä§Ñ§Ó§Ú§ä§î §Ò§Ö§Ù §à§é§Ú§ã§ä§Ü§Ú?", @@ -147,7 +156,7 @@ UnknownToolbarSet : "§±§Ñ§ß§Ö§Ý§î §Ú§ß§ã§ä§â§å§Þ§Ö§ß§ä§à§Ó \"%1\" §ß§Ö §ã§å§ë§Ö§ã§ä§Ó§å§Ö§ä", NoActiveX : "§¯§Ñ§ã§ä§â§à§Û§Ü§Ú §Ò§Ö§Ù§à§á§Ñ§ã§ß§à§ã§ä§Ú §Ó§Ñ§ê§Ö§Ô§à §Ò§â§Ñ§å§Ù§Ö§â§Ñ §Þ§à§Ô§å§ä §à§Ô§â§Ñ§ß§Ú§é§Ú§Ó§Ñ§ä§î §ß§Ö§Ü§à§ä§à§â§í§Ö §ã§Ó§à§Û§ã§ä§Ó§Ñ §â§Ö§Õ§Ñ§Ü§ä§à§â§Ñ. §£§í §Õ§à§Ý§Ø§ß§í §Ó§Ü§Ý§ð§é§Ú§ä§î §à§á§è§Ú§ð \"§©§Ñ§á§å§ã§Ü§Ñ§ä§î §ï§Ý§Ö§Þ§Ö§ß§ä§í §å§á§â§Ñ§Ó§Ý§Ö§ß§Ú§ñ ActiveX §Ú §á§Ý§å§Ô§Ú§ß§í\". §£§í §Þ§à§Ø§Ö§ä§Ö §Ó§Ú§Õ§Ö§ä§î §à§ê§Ú§Ò§Ü§Ú §Ú §Ù§Ñ§Þ§Ö§é§Ñ§ä§î §à§ä§ã§å§ä§ã§ä§Ó§Ú§Ö §Ó§à§Ù§Þ§à§Ø§ß§à§ã§ä§Ö§Û.", BrowseServerBlocked : "§²§Ö§ã§å§â§ã§í §Ò§â§Ñ§å§Ù§Ö§â§Ñ §ß§Ö §Þ§à§Ô§å§ä §Ò§í§ä§î §à§ä§Ü§â§í§ä§í. §±§â§à§Ó§Ö§â§î§ä§Ö §é§ä§à §Ò§Ý§à§Ü§Ú§â§à§Ó§Ü§Ú §Ó§ã§á§Ý§í§Ó§Ñ§ð§ë§Ú§ç §à§Ü§à§ß §Ó§í§Ü§Ý§ð§é§Ö§ß§í.", -DialogBlocked : "§¯§Ö §Ó§à§Ù§Þ§à§Ø§ß§à §à§ä§Ü§â§í§ä§î §à§Ü§ß§à §Õ§Ú§Ñ§Ý§à§Ô§Ñ. §±§â§à§Ó§Ö§â§î§ä§Ö §é§ä§à §Ò§Ý§à§Ü§Ú§â§à§Ó§Ü§Ú §Ó§ã§á§Ý§í§Ó§Ñ§ð§ë§Ú§ç §à§Ü§à§ß §Ó§í§Ü§Ý§ð§é§Ö§ß§í.", +DialogBlocked : "§¯§Ö§Ó§à§Ù§Þ§à§Ø§ß§à §à§ä§Ü§â§í§ä§î §à§Ü§ß§à §Õ§Ú§Ñ§Ý§à§Ô§Ñ. §±§â§à§Ó§Ö§â§î§ä§Ö §é§ä§à §Ò§Ý§à§Ü§Ú§â§à§Ó§Ü§Ú §Ó§ã§á§Ý§í§Ó§Ñ§ð§ë§Ú§ç §à§Ü§à§ß §Ó§í§Ü§Ý§ð§é§Ö§ß§í.", // Dialogs DlgBtnOK : "§°§¬", @@ -157,7 +166,7 @@ DlgAdvancedTag : "§²§Ñ§ã§ê§Ú§â§Ö§ß§ß§í§Û", DlgOpOther : "<§¥§â§å§Ô§à§Ö>", DlgInfoTab : "§ª§ß§æ§à§â§Þ§Ñ§è§Ú§ñ", -DlgAlertUrl : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ §Ó§ã§ä§Ñ§Ó§î§ä§Ö URL", +DlgAlertUrl : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ, §Ó§ã§ä§Ñ§Ó§î§ä§Ö URL", // General Dialogs Labels DlgGenNotSet : "<§ß§Ö §à§á§â§Ö§Õ§Ö§Ý§Ö§ß§à>", @@ -201,7 +210,7 @@ DlgImgAlignTextTop : "§´§Ö§Ü§ã§ä §ß§Ñ§Ó§Ö§â§ç§å", DlgImgAlignTop : "§±§à §Ó§Ö§â§ç§å", DlgImgPreview : "§±§â§Ö§Õ§Ó§Ñ§â§Ú§ä§Ö§Ý§î§ß§í§Û §á§â§à§ã§Þ§à§ä§â", -DlgImgAlertUrl : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ §Ó§Ó§Ö§Õ§Ú§ä§Ö URL §Ú§Ù§à§Ò§â§Ñ§Ø§Ö§ß§Ú§ñ", +DlgImgAlertUrl : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ, §Ó§Ó§Ö§Õ§Ú§ä§Ö URL §Ú§Ù§à§Ò§â§Ñ§Ø§Ö§ß§Ú§ñ", DlgImgLinkTab : "§³§ã§í§Ý§Ü§Ñ", // Flash Dialog @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "§£§í§Ò§Ö§â§Ú§ä§Ö §ñ§Ü§à§â§î", DlgLnkAnchorByName : "§±§à §Ú§Þ§Ö§ß§Ú §ñ§Ü§à§â§ñ", DlgLnkAnchorById : "§±§à §Ú§Õ§Ö§ß§ä§Ú§æ§Ú§Ü§Ñ§ä§à§â§å §ï§Ý§Ö§Þ§Ö§ß§ä§Ñ", -DlgLnkNoAnchors : "<§¯§Ö§ä §ñ§Ü§à§â§Ö§Û §Õ§à§ã§ä§å§á§ß§í§ç §Ó §ï§ä§à§Þ §Õ§à§Ü§å§Þ§Ö§ß§ä§Ö>", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(§¯§Ö§ä §ñ§Ü§à§â§Ö§Û §Õ§à§ã§ä§å§á§ß§í§ç §Ó §ï§ä§à§Þ §Õ§à§Ü§å§Þ§Ö§ß§ä§Ö)", DlgLnkEMail : "§¡§Õ§â§Ö§ã §ï§Ý. §á§à§é§ä§í", DlgLnkEMailSubject : "§©§Ñ§Ô§à§Ý§à§Ó§à§Ü §ã§à§à§Ò§ë§Ö§ß§Ú§ñ", DlgLnkEMailBody : "§´§Ö§Ý§à §ã§à§à§Ò§ë§Ö§ß§Ú§ñ", @@ -259,9 +268,9 @@ DlgLnkPopLeft : "§±§à§Ù§Ú§è§Ú§ñ §ã§Ý§Ö§Ó§Ñ", DlgLnkPopTop : "§±§à§Ù§Ú§è§Ú§ñ §ã§Ó§Ö§â§ç§å", -DlnLnkMsgNoUrl : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ §Ó§Ó§Ö§Õ§Ú§ä§Ö URL §ã§ã§í§Ý§Ü§Ú", -DlnLnkMsgNoEMail : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ §Ó§Ó§Ö§Õ§Ú§ä§Ö §Ñ§Õ§â§Ö§ã §ï§Ý. §á§à§é§ä§í", -DlnLnkMsgNoAnchor : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ §Ó§í§Ò§Ö§â§Ö§ä§Ö §ñ§Ü§à§â§î", +DlnLnkMsgNoUrl : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ, §Ó§Ó§Ö§Õ§Ú§ä§Ö URL §ã§ã§í§Ý§Ü§Ú", +DlnLnkMsgNoEMail : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ, §Ó§Ó§Ö§Õ§Ú§ä§Ö §Ñ§Õ§â§Ö§ã §ï§Ý. §á§à§é§ä§í", +DlnLnkMsgNoAnchor : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ, §Ó§í§Ò§Ö§â§Ö§ä§Ö §ñ§Ü§à§â§î", DlnLnkMsgInvPopName : "§¯§Ñ§Ù§Ó§Ñ§ß§Ú§Ö §Ó§ã§á§í§Ó§Ñ§ð§ë§Ö§Ô§à §à§Ü§ß§Ñ §Õ§à§Ý§Ø§ß§à §ß§Ñ§é§Ú§ß§Ñ§ä§î§ã§ñ §Ò§å§Ü§Ó§í §Ú §ß§Ö §Þ§à§Ø§Ö§ä §ã§à§Õ§Ö§â§Ø§Ñ§ä§î §á§â§à§Ò§Ö§Ý§à§Ó", // Color Dialog @@ -322,6 +331,9 @@ DlgCellBorderColor : "§¸§Ó§Ö§ä §Ò§à§â§Õ§ð§â§Ñ", DlgCellBtnSelect : "§£§í§Ò§Ö§â§Ú§ä§Ö...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "§¯§Ñ§Û§ä§Ú §Ú §Ù§Ñ§Þ§Ö§ß§Ú§ä§î", + // Find Dialog DlgFindTitle : "§¯§Ñ§Û§ä§Ú", DlgFindFindBtn : "§¯§Ñ§Û§ä§Ú", @@ -337,17 +349,16 @@ DlgReplaceWordChk : "§³§à§Ó§á§Ñ§Õ§Ö§ß§Ú§Ö §è§Ö§Ý§í§ç §ã§Ý§à§Ó", // Paste Operations / Dialog -PasteErrorCut : "§¯§Ñ§ã§ä§â§à§Û§Ü§Ú §Ò§Ö§Ù§à§á§Ñ§ã§ß§à§ã§ä§Ú §Ó§Ñ§ê§Ö§Ô§à §Ò§â§Ñ§å§Ù§Ö§â§Ñ §ß§Ö §á§à§Ù§Ó§à§Ý§ñ§ð§ä §â§Ö§Õ§Ñ§Ü§ä§à§â§å §Ñ§Ó§ä§à§Þ§Ñ§ä§Ú§é§Ö§ã§Ü§Ú §Ó§í§á§à§Ý§ß§ñ§ä§î §à§á§Ö§â§Ñ§è§Ú§Ú §Ó§í§â§Ö§Ù§Ñ§ß§Ú§ñ. §±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ §Ú§ã§á§à§Ý§î§Ù§å§Û§ä§Ö §Ü§Ý§Ñ§Ó§Ú§Ñ§ä§å§â§å §Õ§Ý§ñ §ï§ä§à§Ô§à (Ctrl+X).", -PasteErrorCopy : "§¯§Ñ§ã§ä§â§à§Û§Ü§Ú §Ò§Ö§Ù§à§á§Ñ§ã§ß§à§ã§ä§Ú §Ó§Ñ§ê§Ö§Ô§à §Ò§â§Ñ§å§Ù§Ö§â§Ñ §ß§Ö §á§à§Ù§Ó§à§Ý§ñ§ð§ä §â§Ö§Õ§Ñ§Ü§ä§à§â§å §Ñ§Ó§ä§à§Þ§Ñ§ä§Ú§é§Ö§ã§Ü§Ú §Ó§í§á§à§Ý§ß§ñ§ä§î §à§á§Ö§â§Ñ§è§Ú§Ú §Ü§à§á§Ú§â§à§Ó§Ñ§ß§Ú§ñ. §±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ §Ú§ã§á§à§Ý§î§Ù§å§Û§ä§Ö §Ü§Ý§Ñ§Ó§Ú§Ñ§ä§å§â§å §Õ§Ý§ñ §ï§ä§à§Ô§à (Ctrl+C).", +PasteErrorCut : "§¯§Ñ§ã§ä§â§à§Û§Ü§Ú §Ò§Ö§Ù§à§á§Ñ§ã§ß§à§ã§ä§Ú §Ó§Ñ§ê§Ö§Ô§à §Ò§â§Ñ§å§Ù§Ö§â§Ñ §ß§Ö §á§à§Ù§Ó§à§Ý§ñ§ð§ä §â§Ö§Õ§Ñ§Ü§ä§à§â§å §Ñ§Ó§ä§à§Þ§Ñ§ä§Ú§é§Ö§ã§Ü§Ú §Ó§í§á§à§Ý§ß§ñ§ä§î §à§á§Ö§â§Ñ§è§Ú§Ú §Ó§í§â§Ö§Ù§Ñ§ß§Ú§ñ. §±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ, §Ú§ã§á§à§Ý§î§Ù§å§Û§ä§Ö §Ü§Ý§Ñ§Ó§Ú§Ñ§ä§å§â§å §Õ§Ý§ñ §ï§ä§à§Ô§à (Ctrl+X).", +PasteErrorCopy : "§¯§Ñ§ã§ä§â§à§Û§Ü§Ú §Ò§Ö§Ù§à§á§Ñ§ã§ß§à§ã§ä§Ú §Ó§Ñ§ê§Ö§Ô§à §Ò§â§Ñ§å§Ù§Ö§â§Ñ §ß§Ö §á§à§Ù§Ó§à§Ý§ñ§ð§ä §â§Ö§Õ§Ñ§Ü§ä§à§â§å §Ñ§Ó§ä§à§Þ§Ñ§ä§Ú§é§Ö§ã§Ü§Ú §Ó§í§á§à§Ý§ß§ñ§ä§î §à§á§Ö§â§Ñ§è§Ú§Ú §Ü§à§á§Ú§â§à§Ó§Ñ§ß§Ú§ñ. §±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ, §Ú§ã§á§à§Ý§î§Ù§å§Û§ä§Ö §Ü§Ý§Ñ§Ó§Ú§Ñ§ä§å§â§å §Õ§Ý§ñ §ï§ä§à§Ô§à (Ctrl+C).", PasteAsText : "§£§ã§ä§Ñ§Ó§Ú§ä§î §ä§à§Ý§î§Ü§à §ä§Ö§Ü§ã§ä", PasteFromWord : "§£§ã§ä§Ñ§Ó§Ú§ä§î §Ú§Ù Word", -DlgPasteMsg2 : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ §Ó§ã§ä§Ñ§Ó§î§ä§Ö §ä§Ö§Ü§ã§ä §Ó §á§â§ñ§Þ§à§å§Ô§à§Ý§î§ß§Ú§Ü §Ú§ã§á§à§Ý§î§Ù§å§ñ §ã§à§é§Ö§ä§Ñ§ß§Ú§Ö §Ü§Ý§Ñ§Ó§Ú§ê (Ctrl+V) §Ú §ß§Ñ§Ø§Þ§Ú§ä§Ö OK.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteMsg2 : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ, §Ó§ã§ä§Ñ§Ó§î§ä§Ö §ä§Ö§Ü§ã§ä §Ó §á§â§ñ§Þ§à§å§Ô§à§Ý§î§ß§Ú§Ü, §Ú§ã§á§à§Ý§î§Ù§å§ñ §ã§à§é§Ö§ä§Ñ§ß§Ú§Ö §Ü§Ý§Ñ§Ó§Ú§ê (Ctrl+V), §Ú §ß§Ñ§Ø§Þ§Ú§ä§Ö OK.", +DlgPasteSec : "§±§à §á§â§Ú§é§Ú§ß§Ö §ß§Ñ§ã§ä§â§à§Ö§Ü §Ò§Ö§Ù§à§á§Ñ§ã§ß§à§ã§ä§Ú §Ò§â§Ñ§å§Ù§Ö§â§Ñ, §â§Ö§Õ§Ñ§Ü§ä§à§â §ß§Ö §Ú§Þ§Ö§Ö§ä §Õ§à§ã§ä§å§á§Ñ §Ü §Õ§Ñ§ß§ß§í§Þ §Ò§å§æ§Ö§â§Ñ §à§Ò§Þ§Ö§ß§Ñ §ß§Ñ§á§â§ñ§Þ§å§ð. §£§Ñ§Þ §ß§Ö§à§Ò§ç§à§Õ§Ú§Þ§à §Ó§ã§ä§Ñ§Ó§Ú§ä§î §ä§Ö§Ü§ã§ä §ã§ß§à§Ó§Ñ §Ó §ï§ä§à §à§Ü§ß§à.", DlgPasteIgnoreFont : "§ª§Ô§ß§à§â§Ú§â§à§Ó§Ñ§ä§î §à§á§â§Ö§Õ§Ö§Ý§Ö§ß§Ú§ñ §Ô§Ñ§â§ß§Ú§ä§å§â§í", DlgPasteRemoveStyles : "§µ§Ò§â§Ñ§ä§î §à§á§â§Ö§Õ§Ö§Ý§Ö§ß§Ú§ñ §ã§ä§Ú§Ý§Ö§Û", -DlgPasteCleanBox : "§°§é§Ú§ã§ä§Ú§ä§î", // Color Picker ColorAutomatic : "§¡§Ó§ä§à§Þ§Ñ§ä§Ú§é§Ö§ã§Ü§Ú§Û", @@ -359,7 +370,7 @@ // Anchor Dialog DlgAnchorTitle : "§³§Ó§à§Û§ã§ä§Ó§Ñ §ñ§Ü§à§â§ñ", DlgAnchorName : "§ª§Þ§ñ §ñ§Ü§à§â§ñ", -DlgAnchorErrorName : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ §Ó§Ó§Ö§Õ§Ú§ä§Ö §Ú§Þ§ñ §ñ§Ü§à§â§ñ", +DlgAnchorErrorName : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ, §Ó§Ó§Ö§Õ§Ú§ä§Ö §Ú§Þ§ñ §ñ§Ü§à§â§ñ", // Speller Pages Dialog DlgSpellNotInDic : "§¯§Ö§ä §Ó §ã§Ý§à§Ó§Ñ§â§Ö", @@ -451,8 +462,8 @@ DlgDocPageTitle : "§©§Ñ§Ô§à§Ý§à§Ó§à§Ü §ã§ä§â§Ñ§ß§Ú§è§í", DlgDocLangDir : "§¯§Ñ§á§â§Ñ§Ó§Ý§Ö§ß§Ú§Ö §ä§Ö§Ü§ã§ä§Ñ", -DlgDocLangDirLTR : "§³§Ý§Ö§Ó§Ñ §ß§Ñ §á§â§Ñ§Ó§à (LTR)", -DlgDocLangDirRTL : "§³§á§â§Ñ§Ó§Ñ §ß§Ñ §Ý§Ö§Ó§à (RTL)", +DlgDocLangDirLTR : "§³§Ý§Ö§Ó§Ñ §ß§Ñ§á§â§Ñ§Ó§à (LTR)", +DlgDocLangDirRTL : "§³§á§â§Ñ§Ó§Ñ §ß§Ñ§Ý§Ö§Ó§à (RTL)", DlgDocLangCode : "§¬§à§Õ §ñ§Ù§í§Ü§Ñ", DlgDocCharSet : "§¬§à§Õ§Ú§â§à§Ó§Ü§Ñ §ß§Ñ§Ò§à§â§Ñ §ã§Ú§Þ§Ó§à§Ý§à§Ó", DlgDocCharSetCE : "§¸§Ö§ß§ä§â§Ñ§Ý§î§ß§à-§Ö§Ó§â§à§á§Ö§Û§ã§Ü§Ñ§ñ", @@ -490,8 +501,8 @@ // Templates Dialog Templates : "§º§Ñ§Ò§Ý§à§ß§í", DlgTemplatesTitle : "§º§Ñ§Ò§Ý§à§ß§í §ã§à§Õ§Ö§â§Ø§Ú§Þ§à§Ô§à", -DlgTemplatesSelMsg : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ §Ó§í§Ò§Ö§â§Ö§ä§Ö §ê§Ñ§Ò§Ý§à§ß §Õ§Ý§ñ §à§ä§Ü§â§í§ä§Ú§ñ §Ó §â§Ö§Õ§Ñ§Ü§ä§à§â§Ö
      (§ä§Ö§Ü§å§ë§Ö§Ö §ã§à§Õ§Ö§â§Ø§Ú§Þ§à§Ö §Ò§å§Õ§Ö§ä §á§à§ä§Ö§â§ñ§ß§à):", -DlgTemplatesLoading : "§©§Ñ§Ô§â§å§Ù§Ü§Ñ §ã§á§Ú§ã§Ü§Ñ §ê§Ñ§Ò§Ý§à§ß§à§Ó. §±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ §á§à§Õ§à§Ø§Õ§Ú§ä§Ö...", +DlgTemplatesSelMsg : "§±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ, §Ó§í§Ò§Ö§â§Ö§ä§Ö §ê§Ñ§Ò§Ý§à§ß §Õ§Ý§ñ §à§ä§Ü§â§í§ä§Ú§ñ §Ó §â§Ö§Õ§Ñ§Ü§ä§à§â§Ö
      (§ä§Ö§Ü§å§ë§Ö§Ö §ã§à§Õ§Ö§â§Ø§Ú§Þ§à§Ö §Ò§å§Õ§Ö§ä §á§à§ä§Ö§â§ñ§ß§à):", +DlgTemplatesLoading : "§©§Ñ§Ô§â§å§Ù§Ü§Ñ §ã§á§Ú§ã§Ü§Ñ §ê§Ñ§Ò§Ý§à§ß§à§Ó. §±§à§Ø§Ñ§Ý§å§Û§ã§ä§Ñ, §á§à§Õ§à§Ø§Õ§Ú§ä§Ö...", DlgTemplatesNoTpl : "(§¯§Ú §à§Õ§ß§à§Ô§à §ê§Ñ§Ò§Ý§à§ß§Ñ §ß§Ö §à§á§â§Ö§Õ§Ö§Ý§Ö§ß§à)", DlgTemplatesReplace : "§©§Ñ§Þ§Ö§ß§Ú§ä§î §ä§Ö§Ü§å§ë§Ö§Ö §ã§à§Õ§Ö§â§Ø§Ñ§ß§Ú§Ö", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "§­§Ú§è§Ö§ß§Ù§Ú§ñ", DlgAboutVersion : "§£§Ö§â§ã§Ú§ñ", DlgAboutInfo : "§¥§Ý§ñ §Ò§à§Ý§î§ê§Ö§Û §Ú§ß§æ§à§â§Þ§Ñ§è§Ú§Ú, §á§à§ã§Ö§ä§Ú§ä§Ö" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sk.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sk.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sk.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Vlo«öi«à/zmeni«à odkaz", RemoveLink : "Odstr«¡ni«à odkaz", Anchor : "Vlo«öi«à/zmeni«à kotvu", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Obr«¡zok", InsertImage : "Vlo«öi«à/zmeni«à obr«¡zok", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Zarovna«à do bloku", DecreaseIndent : "Zmen«Þi«à odsadenie", IncreaseIndent : "Zv«£«­«Þi«à odsadenie", +Blockquote : "Blockquote", //MISSING Undo : "Sp«£«à", Redo : "Znovu", NumberedListLbl : "ª­«¿slovanie", @@ -103,20 +105,27 @@ ImageButton : "Obr«¡zkov«± tla«­idlo", FitWindow : "Maximalizova«à ve«Ëkos«à okna editora", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "Zmeni«à odkaz", CellCM : "Bunka", RowCM : "Riadok", ColumnCM : "St«Êpec", -InsertRow : "Vlo«öi«à riadok", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Vymaza«à riadok", -InsertColumn : "Vlo«öi«à st«Êpec", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "Zmaza«à st«Êpec", -InsertCell : "Vlo«öi«à bunku", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "Vymaza«à bunky", MergeCells : "Zl«â«­i«à bunky", -SplitCell : "Rozdeli«à bunku", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Vymaza«à tabu«Ëku", CellProperties : "Vlastnosti bunky", TableProperties : "Vlastnosti tabu«Ëky", @@ -134,7 +143,7 @@ TextareaProp : "Vlastnosti textovej oblasti", FormProp : "Vlastnosti formul«¡ra", -FontFormats : "Norm«¡lny;Form«¡tovan«ò;Adresa;Nadpis 1;Nadpis 2;Nadpis 3;Nadpis 4;Nadpis 5;Nadpis 6;Odsek (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Norm«¡lny;Form«¡tovan«ò;Adresa;Nadpis 1;Nadpis 2;Nadpis 3;Nadpis 4;Nadpis 5;Nadpis 6;Odsek (DIV)", // Alerts and Messages ProcessingXHTML : "Prebieha spracovanie XHTML. ª­akajte pros«¿m...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Vybra«à kotvu", DlgLnkAnchorByName : "Pod«Ëa mena kotvy", DlgLnkAnchorById : "Pod«Ëa Id objektu", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(V str«¡nke nie je definovan«¡ «öiadna kotva)", DlgLnkEMail : "E-Mailov«¡ adresa", DlgLnkEMailSubject : "Predmet spr«¡vy", DlgLnkEMailBody : "Telo spr«¡vy", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Farba ohrani«­enia", DlgCellBtnSelect : "V«òber...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "H«Ëada«à", DlgFindFindBtn : "H«Ëada«à", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Ignorova«à nastavenia typu p«¿sma", DlgPasteRemoveStyles : "Odstr«¡ni«à form«¡tovanie", -DlgPasteCleanBox : "Vy«­isti«à schr«¡nku", // Color Picker ColorAutomatic : "Automaticky", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Licencia", DlgAboutVersion : "verzia", DlgAboutInfo : "Viac inform«¡ci«¿ z«¿skate na" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sl.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sl.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sl.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Vstavi/uredi povezavo", RemoveLink : "Odstrani povezavo", Anchor : "Vstavi/uredi zaznamek", +AnchorDelete : "Odstrani zaznamek", InsertImageLbl : "Slika", InsertImage : "Vstavi/uredi sliko", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Obojestranska poravnava", DecreaseIndent : "Zmanj«Þaj zamik", IncreaseIndent : "Pove«­aj zamik", +Blockquote : "Citat", Undo : "Razveljavi", Redo : "Ponovi", NumberedListLbl : "O«Þtevil«­en seznam", @@ -102,21 +104,28 @@ SelectionField : "Spustni seznam", ImageButton : "Gumb s sliko", -FitWindow : "Maximize the editor size", //MISSING +FitWindow : "Raz«Þiri velikost urejevalnika «­ez cel zaslon", +ShowBlocks : "Prika«öi ograde", // Context Menu EditLink : "Uredi povezavo", -CellCM : "Cell", //MISSING -RowCM : "Row", //MISSING -ColumnCM : "Column", //MISSING -InsertRow : "Vstavi vrstico", +CellCM : "Celica", +RowCM : "Vrstica", +ColumnCM : "Stolpec", +InsertRowAfter : "Vstavi vrstico za", +InsertRowBefore : "Vstavi vrstico pred", DeleteRows : "Izbri«Þi vrstice", -InsertColumn : "Vstavi stolpec", +InsertColumnAfter : "Vstavi stolpec za", +InsertColumnBefore : "Vstavi stolpec pred", DeleteColumns : "Izbri«Þi stolpce", -InsertCell : "Vstavi celico", +InsertCellAfter : "Vstavi celico za", +InsertCellBefore : "Vstavi celico pred", DeleteCells : "Izbri«Þi celice", MergeCells : "Zdru«öi celice", -SplitCell : "Razdeli celico", +MergeRight : "Zdru«öi desno", +MergeDown : "Dru«öi navzdol", +HorizontalSplitCell : "Razdeli celico vodoravno", +VerticalSplitCell : "Razdeli celico navpi«­no", TableDelete : "Izbri«Þi tabelo", CellProperties : "Lastnosti celice", TableProperties : "Lastnosti tabele", @@ -134,7 +143,7 @@ TextareaProp : "Lastnosti vnosnega obmo«­ja", FormProp : "Lastnosti obrazca", -FontFormats : "Navaden;Oblikovan;Napis;Naslov 1;Naslov 2;Naslov 3;Naslov 4;Naslov 5;Naslov 6", //REVIEW : Check _getfontformat.html +FontFormats : "Navaden;Oblikovan;Napis;Naslov 1;Naslov 2;Naslov 3;Naslov 4;Naslov 5;Naslov 6", // Alerts and Messages ProcessingXHTML : "Obdelujem XHTML. Prosim po«­akajte...", @@ -145,9 +154,9 @@ UnknownCommand : "Neznano ime ukaza \"%1\"", NotImplemented : "Ukaz ni izdelan", UnknownToolbarSet : "Skupina orodnih vrstic \"%1\" ne obstoja", -NoActiveX : "Your browser's security settings could limit some features of the editor. You must enable the option \"Run ActiveX controls and plug-ins\". You may experience errors and notice missing features.", //MISSING -BrowseServerBlocked : "The resources browser could not be opened. Make sure that all popup blockers are disabled.", //MISSING -DialogBlocked : "It was not possible to open the dialog window. Make sure all popup blockers are disabled.", //MISSING +NoActiveX : "Varnostne nastavitve va«Þega brskalnika lahko omejijo delovanje nekaterih zmo«önosti urejevalnika. ª­e ne «öelite zaznavati napak in sporo«­il o manjkajo«­ih zmo«önostih, omogo«­ite mo«önost \"Za«öeni ActiveX kontrolnike in vti«­nike\".", +BrowseServerBlocked : "Brskalnik virov se ne more odpreti. Prepri«­ajte se, da je prepre«­evanje pojavnih oken onemogo«­eno.", +DialogBlocked : "Pogovorno okno se ni moglo odpreti. Prepri«­ajte se, da je prepre«­evanje pojavnih oken onemogo«­eno.", // Dialogs DlgBtnOK : "V redu", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Izberi zaznamek", DlgLnkAnchorByName : "Po imenu zaznamka", DlgLnkAnchorById : "Po ID-ju elementa", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(V tem dokumentu ni zaznamkov)", DlgLnkEMail : "Elektronski naslov", DlgLnkEMailSubject : "Predmet sporo«­ila", DlgLnkEMailBody : "Vsebina sporo«­ila", @@ -262,7 +271,7 @@ DlnLnkMsgNoUrl : "Vnesite URL povezave", DlnLnkMsgNoEMail : "Vnesite elektronski naslov", DlnLnkMsgNoAnchor : "Izberite zaznamek", -DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces", //MISSING +DlnLnkMsgInvPopName : "Ime pojavnega okna se mora za«­eti s «­rko ali «Þtevilko in ne sme vsebovati presledkov", // Color Dialog DlgColorTitle : "Izberite barvo", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Barva obrobe", DlgCellBtnSelect : "Izberi...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Najdi in zamenjaj", + // Find Dialog DlgFindTitle : "Najdi", DlgFindFindBtn : "Najdi", @@ -344,10 +356,9 @@ PasteFromWord : "Prilepi iz Worda", DlgPasteMsg2 : "Prosim prilepite v sle«­i okvir s pomo«­jo tipkovnice (Ctrl+V) in pritisnite V redu.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "Zaradi varnostnih nastavitev va«Þega brskalnika urejevalnik ne more neposredno dostopati do odlo«öi«Þ«­a. Vsebino odlo«öi«Þ«­a ponovno prilepite v to okno.", DlgPasteIgnoreFont : "Prezri obliko pisave", DlgPasteRemoveStyles : "Odstrani nastavitve stila", -DlgPasteCleanBox : "Po«­isti okvir", // Color Picker ColorAutomatic : "Samodejno", @@ -381,9 +392,9 @@ // Button Dialog DlgButtonText : "Besedilo (Vrednost)", DlgButtonType : "Tip", -DlgButtonTypeBtn : "Button", //MISSING -DlgButtonTypeSbm : "Submit", //MISSING -DlgButtonTypeRst : "Reset", //MISSING +DlgButtonTypeBtn : "Gumb", +DlgButtonTypeSbm : "Potrdi", +DlgButtonTypeRst : "Ponastavi", // Checkbox and Radio Button Dialogs DlgCheckboxName : "Ime", @@ -432,7 +443,7 @@ // Bulleted List Dialog BulletedListProp : "Lastnosti ozna«­enega seznama", NumberedListProp : "Lastnosti o«Þtevil«­enega seznama", -DlgLstStart : "Start", //MISSING +DlgLstStart : "Za«­etek", DlgLstType : "Tip", DlgLstTypeCircle : "Pikica", DlgLstTypeDisc : "Kroglica", @@ -455,15 +466,15 @@ DlgDocLangDirRTL : "Od desne proti levi (RTL)", DlgDocLangCode : "Oznaka jezika", DlgDocCharSet : "Kodna tabela", -DlgDocCharSetCE : "Central European", //MISSING -DlgDocCharSetCT : "Chinese Traditional (Big5)", //MISSING -DlgDocCharSetCR : "Cyrillic", //MISSING -DlgDocCharSetGR : "Greek", //MISSING -DlgDocCharSetJP : "Japanese", //MISSING -DlgDocCharSetKR : "Korean", //MISSING -DlgDocCharSetTR : "Turkish", //MISSING -DlgDocCharSetUN : "Unicode (UTF-8)", //MISSING -DlgDocCharSetWE : "Western European", //MISSING +DlgDocCharSetCE : "Srednjeevropsko", +DlgDocCharSetCT : "Tradicionalno Kitajsko (Big5)", +DlgDocCharSetCR : "Cirilica", +DlgDocCharSetGR : "Gr«Þko", +DlgDocCharSetJP : "Japonsko", +DlgDocCharSetKR : "Korejsko", +DlgDocCharSetTR : "Tur«Þko", +DlgDocCharSetUN : "Unicode (UTF-8)", +DlgDocCharSetWE : "Zahodnoevropsko", DlgDocCharSetOther : "Druga kodna tabela", DlgDocDocType : "Glava tipa dokumenta", @@ -493,12 +504,12 @@ DlgTemplatesSelMsg : "Izberite predlogo, ki jo «öelite odpreti v urejevalniku
      (trenutna vsebina bo izgubljena):", DlgTemplatesLoading : "Nalagam seznam predlog. Prosim po«­akajte...", DlgTemplatesNoTpl : "(Ni pripravljenih predlog)", -DlgTemplatesReplace : "Replace actual contents", //MISSING +DlgTemplatesReplace : "Zamenjaj trenutno vsebino", // About Dialog DlgAboutAboutTab : "Vizitka", DlgAboutBrowserInfoTab : "Informacije o brskalniku", -DlgAboutLicenseTab : "License", //MISSING +DlgAboutLicenseTab : "Dovoljenja", DlgAboutVersion : "razli«­ica", DlgAboutInfo : "Za ve«­ informacij obi«Þ«­ite" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sr-latn.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sr-latn.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sr-latn.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Unesi/izmeni link", RemoveLink : "Ukloni link", Anchor : "Unesi/izmeni sidro", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Slika", InsertImage : "Unesi/izmeni sliku", InsertFlashLbl : "Fle«Þ", @@ -70,6 +71,7 @@ BlockJustify : "Obostrano ravnanje", DecreaseIndent : "Smanji levu marginu", IncreaseIndent : "Uve««aj levu marginu", +Blockquote : "Blockquote", //MISSING Undo : "Poni?ti akciju", Redo : "Ponovi akciju", NumberedListLbl : "Nabrojiva lista", @@ -103,20 +105,27 @@ ImageButton : "Dugme sa slikom", FitWindow : "Maximize the editor size", //MISSING +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "Izmeni link", CellCM : "Cell", //MISSING RowCM : "Row", //MISSING ColumnCM : "Column", //MISSING -InsertRow : "Unesi red", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Obri«Þi redove", -InsertColumn : "Unesi kolonu", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "Obri«Þi kolone", -InsertCell : "Unesi ««elije", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "Obri«Þi ««elije", MergeCells : "Spoj celije", -SplitCell : "Razdvoji celije", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Delete Table", //MISSING CellProperties : "Osobine celije", TableProperties : "Osobine tabele", @@ -134,7 +143,7 @@ TextareaProp : "Osobine zone teksta", FormProp : "Osobine forme", -FontFormats : "Normal;Formatirano;Adresa;Naslov 1;Naslov 2;Naslov 3;Naslov 4;Naslov 5;Naslov 6", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatirano;Adresa;Naslov 1;Naslov 2;Naslov 3;Naslov 4;Naslov 5;Naslov 6", // Alerts and Messages ProcessingXHTML : "Obradujem XHTML. Malo strpljenja...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Odaberi sidro", DlgLnkAnchorByName : "Po nazivu sidra", DlgLnkAnchorById : "Po Id-ju elementa", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Nema dostupnih sidra)", DlgLnkEMail : "E-Mail adresa", DlgLnkEMailSubject : "Naslov", DlgLnkEMailBody : "Sadr«öaj poruke", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Boja okvira", DlgCellBtnSelect : "Odaberi...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "Prona©Âi", DlgFindFindBtn : "Prona©Âi", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Ignori«Þi definicije fontova", DlgPasteRemoveStyles : "Ukloni definicije stilova", -DlgPasteCleanBox : "Obri«Þi sve", // Color Picker ColorAutomatic : "Automatski", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "License", //MISSING DlgAboutVersion : "verzija", DlgAboutInfo : "Za vi«Þe informacija posetite" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sr.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sr.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sr.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "§µ§ß§Ö§ã§Ú/§Ú§Ù§Þ§Ö§ß§Ú §Ý§Ú§ß§Ü", RemoveLink : "§µ§Ü§Ý§à§ß§Ú §Ý§Ú§ß§Ü", Anchor : "§µ§ß§Ö§ã§Ú/§Ú§Ù§Þ§Ö§ß§Ú §ã§Ú§Õ§â§à", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "§³§Ý§Ú§Ü§Ñ", InsertImage : "§µ§ß§Ö§ã§Ú/§Ú§Ù§Þ§Ö§ß§Ú §ã§Ý§Ú§Ü§å", InsertFlashLbl : "§¶§Ý§Ö§ê §Ö§Ý§Ö§Þ§Ö§ß§ä", @@ -70,6 +71,7 @@ BlockJustify : "§°§Ò§à§ã§ä§â§Ñ§ß§à §â§Ñ§Ó§ß§Ñ§ú§Ö", DecreaseIndent : "§³§Þ§Ñ§ú§Ú §Ý§Ö§Ó§å §Þ§Ñ§â§Ô§Ú§ß§å", IncreaseIndent : "§µ§Ó§Ö§û§Ñ§ø §Ý§Ö§Ó§å §Þ§Ñ§â§Ô§Ú§ß§å", +Blockquote : "Blockquote", //MISSING Undo : "§±§à§ß§Ú§ê§ä§Ú §Ñ§Ü§è§Ú§ø§å", Redo : "§±§à§ß§à§Ó§Ú §Ñ§Ü§è§Ú§ø§å", NumberedListLbl : "§¯§Ñ§Ò§â§à§ø§Ú§Ó§å §Ý§Ú§ã§ä§å", @@ -103,20 +105,27 @@ ImageButton : "§¥§å§Ô§Þ§Ö §ã§Ñ §ã§Ý§Ú§Ü§à§Þ", FitWindow : "Maximize the editor size", //MISSING +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "§±§â§à§Þ§Ö§ß§Ú §Ý§Ú§ß§Ü", CellCM : "Cell", //MISSING RowCM : "Row", //MISSING ColumnCM : "Column", //MISSING -InsertRow : "§µ§ß§Ö§ã§Ú §â§Ö§Õ", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "§°§Ò§â§Ú§ê§Ú §â§Ö§Õ§à§Ó§Ö", -InsertColumn : "§µ§ß§Ö§ã§Ú §Ü§à§Ý§à§ß§å", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "§°§Ò§â§Ú§ê§Ú §Ü§à§Ý§à§ß§Ö", -InsertCell : "§µ§ß§Ö§ã§Ú §û§Ö§Ý§Ú§ø§Ö", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "§°§Ò§â§Ú§ê§Ú §û§Ö§Ý§Ú§ø§Ö", MergeCells : "§³§á§à§ø §û§Ö§Ý§Ú§ø§Ö", -SplitCell : "§²§Ñ§Ù§Õ§Ó§à§ø§Ú §û§Ö§Ý§Ú§ø§Ö", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Delete Table", //MISSING CellProperties : "§°§ã§à§Ò§Ú§ß§Ö §û§Ö§Ý§Ú§ø§Ö", TableProperties : "§°§ã§à§Ò§Ú§ß§Ö §ä§Ñ§Ò§Ö§Ý§Ö", @@ -134,7 +143,7 @@ TextareaProp : "§°§ã§à§Ò§Ú§ß§Ö §Ù§à§ß§Ö §ä§Ö§Ü§ã§ä§Ñ", FormProp : "§°§ã§à§Ò§Ú§ß§Ö §æ§à§â§Þ§Ö", -FontFormats : "Normal;Formatirano;Adresa;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatirano;Adresa;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6", // Alerts and Messages ProcessingXHTML : "§°§Ò§â§Ñ§ò§å§ø§Ö§Þ XHTML. Ma§Ýo §ã§ä§â§á§ù§Ö§ú§Ñ...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "§°§Õ§Ñ§Ò§Ö§â§Ú §ã§Ú§Õ§â§à", DlgLnkAnchorByName : "§±§à §ß§Ñ§Ù§Ú§Ó§å §ã§Ú§Õ§â§Ñ", DlgLnkAnchorById : "§±o §ª§Õ-j§å §Ö§Ý§Ö§Þ§Ö§ß§ä§Ñ", -DlgLnkNoAnchors : "<§¯§Ö§Þ§Ñ §Õ§à§ã§ä§å§á§ß§Ú§ç §ã§Ú§Õ§â§Ñ>", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(§¯§Ö§Þ§Ñ §Õ§à§ã§ä§å§á§ß§Ú§ç §ã§Ú§Õ§â§Ñ)", DlgLnkEMail : "§¡§Õ§â§Ö§ã§Ñ §Ö§Ý§Ö§Ü§ä§â§à§ß§ã§Ü§Ö §á§à§ê§ä§Ö", DlgLnkEMailSubject : "§¯§Ñ§ã§Ý§à§Ó", DlgLnkEMailBody : "§³§Ñ§Õ§â§Ø§Ñ§ø §á§à§â§å§Ü§Ö", @@ -322,6 +331,9 @@ DlgCellBorderColor : "§¢§à§ø§Ñ §à§Ü§Ó§Ú§â§Ñ", DlgCellBtnSelect : "O§Õ§Ñ§Ò§Ö§â§Ú...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "§±§â§à§ß§Ñ§ò§Ú", DlgFindFindBtn : "§±§â§à§ß§Ñ§ò§Ú", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "§ª§Ô§ß§à§â§Ú§ê§Ú Font Face §Õ§Ö§æ§Ú§ß§Ú§è§Ú§ø§Ö", DlgPasteRemoveStyles : "§µ§Ü§Ý§à§ß§Ú §Õ§Ö§æ§Ú§ß§Ú§è§Ú§ø§Ö §ã§ä§Ú§Ý§à§Ó§Ñ", -DlgPasteCleanBox : "§°§Ò§â§Ú§ê§Ú §ã§Ó§Ö", // Color Picker ColorAutomatic : "§¡§å§ä§à§Þ§Ñ§ä§ã§Ü§Ú", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "License", //MISSING DlgAboutVersion : "§Ó§Ö§â§Ù§Ú§ø§Ñ", DlgAboutInfo : "§©§Ñ §Ó§Ú§ê§Ö §Ú§ß§æ§à§â§Þ§Ñ§è§Ú§ø§Ñ §á§à§ã§Ö§ä§Ú§ä§Ö" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sv.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sv.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/sv.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Infoga/Redigera l«£nk", RemoveLink : "Radera l«£nk", Anchor : "Infoga/Redigera ankarl«£nk", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Bild", InsertImage : "Infoga/Redigera bild", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Justera till marginaler", DecreaseIndent : "Minska indrag", IncreaseIndent : "ªÓka indrag", +Blockquote : "Blockquote", //MISSING Undo : "ª©ngra", Redo : "G«Ór om", NumberedListLbl : "Numrerad lista", @@ -102,21 +104,28 @@ SelectionField : "Flervalslista", ImageButton : "Bildknapp", -FitWindow : "Maximize the editor size", //MISSING +FitWindow : "Anpassa till f«Ónstrets storlek", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "Redigera l«£nk", -CellCM : "Cell", //MISSING -RowCM : "Row", //MISSING -ColumnCM : "Column", //MISSING -InsertRow : "Infoga rad", +CellCM : "Cell", +RowCM : "Rad", +ColumnCM : "Kolumn", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Radera rad", -InsertColumn : "Infoga kolumn", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "Radera kolumn", -InsertCell : "Infoga cell", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "Radera celler", MergeCells : "Sammanfoga celler", -SplitCell : "Separera celler", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Radera tabell", CellProperties : "Cellegenskaper", TableProperties : "Tabellegenskaper", @@ -134,7 +143,7 @@ TextareaProp : "Egenskaper f«Ór textruta", FormProp : "Egenskaper f«Ór formul«£r", -FontFormats : "Normal;Formaterad;Adress;Rubrik 1;Rubrik 2;Rubrik 3;Rubrik 4;Rubrik 5;Rubrik 6", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formaterad;Adress;Rubrik 1;Rubrik 2;Rubrik 3;Rubrik 4;Rubrik 5;Rubrik 6;Normal (DIV)", // Alerts and Messages ProcessingXHTML : "Bearbetar XHTML. Var god v«£nta...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "V«£lj ett ankare", DlgLnkAnchorByName : "efter ankarnamn", DlgLnkAnchorById : "efter objektid", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Inga ankare kunde hittas)", DlgLnkEMail : "E-postadress", DlgLnkEMailSubject : "ª£mne", DlgLnkEMailBody : "Inneh«©ll", @@ -262,7 +271,7 @@ DlnLnkMsgNoUrl : "Var god ange l«£nkens URL", DlnLnkMsgNoEMail : "Var god ange E-postadress", DlnLnkMsgNoAnchor : "Var god ange ett ankare", -DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces", //MISSING +DlnLnkMsgInvPopName : "Popup-rutans namn m«©ste b«Órja med en alfabetisk bokstav och f«©r inte inneh«©lla mellanslag", // Color Dialog DlgColorTitle : "V«£lj f«£rg", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Kantf«£rg", DlgCellBtnSelect : "V«£lj...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "S«Ók", DlgFindFindBtn : "S«Ók", @@ -344,10 +356,9 @@ PasteFromWord : "Klistra in fr«©n Word", DlgPasteMsg2 : "Var god och klistra in Er text i rutan nedan genom att anv«£nda (Ctrl+V) klicka sen p«© OK.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "P«© grund av din webl«£sares s«£kerhetsinst«£llningar kan verktyget inte f«© «©tkomst till urklippsdatan. Var god och anv«£nd detta f«Ónster ist«£llet.", DlgPasteIgnoreFont : "Ignorera typsnittsdefinitioner", DlgPasteRemoveStyles : "Radera Stildefinitioner", -DlgPasteCleanBox : "T«Óm rutans inneh«©ll", // Color Picker ColorAutomatic : "Automatisk", @@ -381,9 +392,9 @@ // Button Dialog DlgButtonText : "Text (V«£rde)", DlgButtonType : "Typ", -DlgButtonTypeBtn : "Button", //MISSING -DlgButtonTypeSbm : "Submit", //MISSING -DlgButtonTypeRst : "Reset", //MISSING +DlgButtonTypeBtn : "Knapp", +DlgButtonTypeSbm : "Skicka", +DlgButtonTypeRst : "ª©terst«£ll", // Checkbox and Radio Button Dialogs DlgCheckboxName : "Namn", @@ -455,15 +466,15 @@ DlgDocLangDirRTL : "H«Óger till V«£nster", DlgDocLangCode : "Spr«©kkod", DlgDocCharSet : "Teckenupps«£ttningar", -DlgDocCharSetCE : "Central European", //MISSING -DlgDocCharSetCT : "Chinese Traditional (Big5)", //MISSING -DlgDocCharSetCR : "Cyrillic", //MISSING -DlgDocCharSetGR : "Greek", //MISSING -DlgDocCharSetJP : "Japanese", //MISSING -DlgDocCharSetKR : "Korean", //MISSING -DlgDocCharSetTR : "Turkish", //MISSING -DlgDocCharSetUN : "Unicode (UTF-8)", //MISSING -DlgDocCharSetWE : "Western European", //MISSING +DlgDocCharSetCE : "Central Europa", +DlgDocCharSetCT : "Traditionell Kinesisk (Big5)", +DlgDocCharSetCR : "Kyrillisk", +DlgDocCharSetGR : "Grekiska", +DlgDocCharSetJP : "Japanska", +DlgDocCharSetKR : "Koreanska", +DlgDocCharSetTR : "Turkiska", +DlgDocCharSetUN : "Unicode (UTF-8)", +DlgDocCharSetWE : "V«£st Europa", DlgDocCharSetOther : "ªÓvriga teckenupps«£ttningar", DlgDocDocType : "Sidhuvud", @@ -493,12 +504,12 @@ DlgTemplatesSelMsg : "Var god v«£lj en mall att anv«£nda med editorn
      (allt nuvarande inneh«©ll raderas):", DlgTemplatesLoading : "Laddar mallar. Var god v«£nta...", DlgTemplatesNoTpl : "(Ingen mall «£r vald)", -DlgTemplatesReplace : "Replace actual contents", //MISSING +DlgTemplatesReplace : "Ers«£tt aktuellt inneh«©ll", // About Dialog DlgAboutAboutTab : "Om", DlgAboutBrowserInfoTab : "Webl«£sare", -DlgAboutLicenseTab : "License", //MISSING +DlgAboutLicenseTab : "Licens", DlgAboutVersion : "version", DlgAboutInfo : "F«Ór mer information se" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/th.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/th.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/th.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "????/????? ?????", RemoveLink : "?? ?????", Anchor : "????/????? Anchor", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "??????", InsertImage : "????/????? ??????", InsertFlashLbl : "???? Flash", @@ -70,6 +71,7 @@ BlockJustify : "?????????????????", DecreaseIndent : "?????????????", IncreaseIndent : "????????????????", +Blockquote : "Blockquote", //MISSING Undo : "????????????", Redo : "???????????", NumberedListLbl : "????????????????????", @@ -103,20 +105,27 @@ ImageButton : "?????????????", FitWindow : "?????????????????????", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "????? ?????", CellCM : "?????????", RowCM : "???", ColumnCM : "???????", -InsertRow : "???????", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "?????", -InsertColumn : "?????????", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "???????", -InsertCell : "????????", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "??????", MergeCells : "????????", -SplitCell : "???????", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "???????", CellProperties : "????????????????", TableProperties : "?????????????????", @@ -134,7 +143,7 @@ TextareaProp : "???????????? ??????????", FormProp : "???????????? ????????", -FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Paragraph (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Paragraph (DIV)", // Alerts and Messages ProcessingXHTML : "?????????????????????????????? XHTML ??????????????...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "????????????????????????? (Anchor)", DlgLnkAnchorByName : "????", DlgLnkAnchorById : "????", -DlgLnkNoAnchors : "(??????????????????????????????????????)", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(??????????????????????????????????????)", DlgLnkEMail : "?????? (E-Mail)", DlgLnkEMailSubject : "?????????", DlgLnkEMailBody : "???????", @@ -322,6 +331,9 @@ DlgCellBorderColor : "?????????", DlgCellBtnSelect : "?????..", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "?????", DlgFindFindBtn : "?????", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "??????? Font Face definitions", DlgPasteRemoveStyles : "?? Styles definitions", -DlgPasteCleanBox : "???????????? Box", // Color Picker ColorAutomatic : "???????????", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "?????????", DlgAboutVersion : "????", DlgAboutInfo : "For further information go to" //MISSING -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/tr.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/tr.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/tr.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "K«Ópr«ä Ekle/D«äzenle", RemoveLink : "K«Ópr«ä Kald©År", Anchor : "ª®apa Ekle/D«äzenle", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "Resim", InsertImage : "Resim Ekle/D«äzenle", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "ªÄki Kenara Yaslanm©Å«ß", DecreaseIndent : "Sekme Azalt", IncreaseIndent : "Sekme Artt©År", +Blockquote : "Blockquote", //MISSING Undo : "Geri Al", Redo : "Tekrarla", NumberedListLbl : "Numaral©Å Liste", @@ -103,20 +105,27 @@ ImageButton : "Resimli D«ä«»me", FitWindow : "D«äzenleyici boyutunu b«äy«ät", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "K«Ópr«ä D«äzenle", CellCM : "H«äcre", RowCM : "Sat©År", ColumnCM : "S«ätun", -InsertRow : "Sat©År Ekle", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Sat©År Sil", -InsertColumn : "S«ätun Ekle", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "S«ätun Sil", -InsertCell : "H«äcre Ekle", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "H«äcre Sil", MergeCells : "H«äcreleri Birle«ßtir", -SplitCell : "H«äcre B«Ól", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "Tabloyu Sil", CellProperties : "H«äcre ªÓzellikleri", TableProperties : "Tablo ªÓzellikleri", @@ -134,7 +143,7 @@ TextareaProp : "ª®ok Sat©Årl©Å Metin ªÓzellikleri", FormProp : "Form ªÓzellikleri", -FontFormats : "Normal;Bi«®imli;Adres;Ba«ßl©Åk 1;Ba«ßl©Åk 2;Ba«ßl©Åk 3;Ba«ßl©Åk 4;Ba«ßl©Åk 5;Ba«ßl©Åk 6;Paragraf (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Bi«®imli;Adres;Ba«ßl©Åk 1;Ba«ßl©Åk 2;Ba«ßl©Åk 3;Ba«ßl©Åk 4;Ba«ßl©Åk 5;Ba«ßl©Åk 6;Paragraf (DIV)", // Alerts and Messages ProcessingXHTML : "XHTML i«ßleniyor. L«ätfen bekleyin...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "ª®apa Se«®", DlgLnkAnchorByName : "ª®apa Ad©Å ile", DlgLnkAnchorById : "Eleman Kimlik Numaras©Å ile", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Bu belgede hi«® «®apa yok)", DlgLnkEMail : "E-Posta Adresi", DlgLnkEMailSubject : "ªÄleti Konusu", DlgLnkEMailBody : "ªÄleti G«Óvdesi", @@ -322,6 +331,9 @@ DlgCellBorderColor : "Kenar Rengi", DlgCellBtnSelect : "Se«®...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "Bul", DlgFindFindBtn : "Bul", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Yaz©Å Tipi tan©Åmlar©Ån©Å yoksay", DlgPasteRemoveStyles : "Bi«®em Tan©Åmlar©Ån©Å «®©Åkar", -DlgPasteCleanBox : "Temizlik Kutusu", // Color Picker ColorAutomatic : "Otomatik", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Lisans", DlgAboutVersion : "s«är«äm", DlgAboutInfo : "Daha fazla bilgi i«®in:" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/uk.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/uk.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/uk.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "§£§ã§ä§Ñ§Ó§Ú§ä§Ú/§²§Ö§Õ§Ñ§Ô§å§Ó§Ñ§ä§Ú §á§à§ã§Ú§Ý§Ñ§ß§ß§ñ", RemoveLink : "§©§ß§Ú§ë§Ú§ä§Ú §á§à§ã§Ú§Ý§Ñ§ß§ß§ñ", Anchor : "§£§ã§ä§Ñ§Ó§Ú§ä§Ú/§²§Ö§Õ§Ñ§Ô§å§Ó§Ñ§ä§Ú §ñ§Ü§ö§â", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "§©§à§Ò§â§Ñ§Ø§Ö§ß§ß§ñ", InsertImage : "§£§ã§ä§Ñ§Ó§Ú§ä§Ú/§²§Ö§Õ§Ñ§Ô§å§Ó§Ñ§ä§Ú §Ù§à§Ò§â§Ñ§Ø§Ö§ß§ß§ñ", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "§±§à §ê§Ú§â§Ú§ß§ö", DecreaseIndent : "§©§Þ§Ö§ß§ê§Ú§ä§Ú §Ó§ö§Õ§ã§ä§å§á", IncreaseIndent : "§©§Ò§ö§Ý§î§ê§Ú§ä§Ú §Ó§ö§Õ§ã§ä§å§á", +Blockquote : "Blockquote", //MISSING Undo : "§±§à§Ó§Ö§â§ß§å§ä§Ú", Redo : "§±§à§Ó§ä§à§â§Ú§ä§Ú", NumberedListLbl : "§¯§å§Þ§Ö§â§à§Ó§Ñ§ß§Ú§Û §ã§á§Ú§ã§à§Ü", @@ -103,20 +105,27 @@ ImageButton : "§¬§ß§à§á§Ü§Ñ §ö§Ù §Ù§à§Ò§â§Ñ§Ø§Ö§ß§ß§ñ§Þ", FitWindow : "§²§à§Ù§Ó§Ö§â§ß§å§ä§Ú §Ó§ö§Ü§ß§à §â§Ö§Õ§Ñ§Ü§ä§à§â§Ñ", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "§£§ã§ä§Ñ§Ó§Ú§ä§Ú §á§à§ã§Ú§Ý§Ñ§ß§ß§ñ", CellCM : "§°§ã§Ö§â§Ö§Õ§à§Ü", RowCM : "§²§ñ§Õ§à§Ü", ColumnCM : "§¬§à§Ý§à§ß§Ü§Ñ", -InsertRow : "§£§ã§ä§Ñ§Ó§Ú§ä§Ú §ã§ä§â§à§Ü§å", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "§£§Ú§Õ§Ñ§Ý§Ú§ä§Ú §ã§ä§â§à§Ü§Ú", -InsertColumn : "§£§ã§ä§Ñ§Ó§Ú§ä§Ú §Ü§à§Ý§à§ß§Ü§å", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "§£§Ú§Õ§Ñ§Ý§Ú§ä§Ú §Ü§à§Ý§à§ß§Ü§Ú", -InsertCell : "§£§ã§ä§Ñ§Ó§Ú§ä§Ú §Ü§à§Þ§ö§â§Ü§å", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "§£§Ú§Õ§Ñ§Ý§Ú§ä§Ú §Ü§à§Þ§ö§â§Ü§Ú", MergeCells : "§°§Ò'§ô§Õ§ß§Ñ§ä§Ú §Ü§à§Þ§ö§â§Ü§Ú", -SplitCell : "§²§à§Ù'§ô§Õ§ß§Ñ§ä§Ú §Ü§à§Þ§ö§â§Ü§å", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "§£§Ú§Õ§Ñ§Ý§Ú§ä§Ú §ä§Ñ§Ò§Ý§Ú§è§ð", CellProperties : "§£§Ý§Ñ§ã§ä§Ú§Ó§à§ã§ä§ö §Ü§à§Þ§ö§â§Ü§Ú", TableProperties : "§£§Ý§Ñ§ã§ä§Ú§Ó§à§ã§ä§ö §ä§Ñ§Ò§Ý§Ú§è§ö", @@ -134,7 +143,7 @@ TextareaProp : "§£§Ý§Ñ§ã§ä§Ú§Ó§à§ã§ä§ö §ä§Ö§Ü§ã§ä§à§Ó§à§÷ §à§Ò§Ý§Ñ§ã§ä§ö", FormProp : "§£§Ý§Ñ§ã§ä§Ú§Ó§à§ã§ä§ö §æ§à§â§Þ§Ú", -FontFormats : "§¯§à§â§Þ§Ñ§Ý§î§ß§Ú§Û;§¶§à§â§Þ§Ñ§ä§à§Ó§Ñ§ß§Ú§Û;§¡§Õ§â§Ö§ã§Ñ;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 1;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 2;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 3;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 4;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 5;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 6", //REVIEW : Check _getfontformat.html +FontFormats : "§¯§à§â§Þ§Ñ§Ý§î§ß§Ú§Û;§¶§à§â§Þ§Ñ§ä§à§Ó§Ñ§ß§Ú§Û;§¡§Õ§â§Ö§ã§Ñ;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 1;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 2;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 3;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 4;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 5;§©§Ñ§Ô§à§Ý§à§Ó§à§Ü 6;§¯§à§â§Þ§Ñ§Ý§î§ß§Ú§Û (DIV)", // Alerts and Messages ProcessingXHTML : "§°§Ò§â§à§Ò§Ü§Ñ XHTML. §©§Ñ§é§Ö§Ü§Ñ§Û§ä§Ö, §Ò§å§Õ§î §Ý§Ñ§ã§Ü§Ñ...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "§°§Ò§Ö§â§ö§ä§î §ñ§Ü§ö§â", DlgLnkAnchorByName : "§©§Ñ §ö§Þ'§ñ§Þ §ñ§Ü§à§â§ñ", DlgLnkAnchorById : "§©§Ñ §ö§Õ§Ö§ß§ä§Ú§æ§ö§Ü§Ñ§ä§à§â§à§Þ §Ö§Ý§Ö§Þ§Ö§ß§ä§Ñ", -DlgLnkNoAnchors : "<§¯§Ö§Þ§Ñ§ô §ñ§Ü§à§â§ö§Ó §Õ§à§ã§ä§å§á§ß§Ú§ç §Ó §è§î§à§Þ§å §Õ§à§Ü§å§Þ§Ö§ß§ä§ö>", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(§¯§Ö§Þ§Ñ§ô §ñ§Ü§à§â§ö§Ó §Õ§à§ã§ä§å§á§ß§Ú§ç §Ó §è§î§à§Þ§å §Õ§à§Ü§å§Þ§Ö§ß§ä§ö)", DlgLnkEMail : "§¡§Õ§â§Ö§ã§Ñ §Ö§Ý. §á§à§ê§ä§Ú", DlgLnkEMailSubject : "§´§Ö§Þ§Ñ §Ý§Ú§ã§ä§Ñ", DlgLnkEMailBody : "§´§ö§Ý§à §á§à§Ó§ö§Õ§à§Þ§Ý§Ö§ß§ß§ñ", @@ -322,6 +331,9 @@ DlgCellBorderColor : "§¬§à§Ý§ö§â §Ò§à§â§Õ§ð§â§Ñ", DlgCellBtnSelect : "§°§Ò§Ö§â§ö§ä§î...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "§±§à§ê§å§Ü", DlgFindFindBtn : "§±§à§ê§å§Ü", @@ -344,10 +356,9 @@ PasteFromWord : "§£§ã§ä§Ñ§Ó§Ú§ä§Ú §Ù Word", DlgPasteMsg2 : "§¢§å§Õ§î-§Ý§Ñ§ã§Ü§Ñ, §Ó§ã§ä§Ñ§Ó§ä§Ö §Ù §Ò§å§æ§Ö§â§Ñ §à§Ò§Þ§ö§ß§å §Ó §è§ð §à§Ò§Ý§Ñ§ã§ä§î, §Ü§à§â§Ú§ã§ä§å§ð§é§Ú§ã§î §Ü§à§Þ§Ò§ö§ß§Ñ§è§ö§ô§ð §Ü§Ý§Ñ§Ó§ö§ê (Ctrl+V) §ä§Ñ §ß§Ñ§ä§Ú§ã§ß§ö§ä§î OK.", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "§²§Ö§Õ§Ñ§Ü§ä§à§â §ß§Ö §Þ§à§Ø§Ö §à§ä§â§Ú§Þ§Ñ§ä§Ú §á§â§ñ§Þ§Ú§Û §Õ§à§ã§ä§å§á §Õ§à §Ò§å§æ§Ö§â§å §à§Ò§Þ§ö§ß§å §å §Ù§Ó'§ñ§Ù§Ü§å §Ù §ß§Ñ§Ý§Ñ§ê§ä§å§Ó§Ñ§ß§ß§ñ§Þ§Ú §Ó§Ñ§ê§à§Ô§à §Ò§â§Ñ§å§Ù§Ö§â§Ñ. §£§Ñ§Þ §á§à§ä§â§ö§Ò§ß§à §Ó§ã§ä§Ñ§Ó§Ú§ä§Ú §ö§ß§æ§à§â§Þ§Ñ§è§ö§ð §á§à§Ó§ä§à§â§ß§à §Ó §è§Ö §Ó§ö§Ü§ß§à.", DlgPasteIgnoreFont : "§Æ§Ô§ß§à§â§å§Ó§Ñ§ä§Ú §ß§Ñ§Ý§Ñ§ê§ä§å§Ó§Ñ§ß§ß§ñ §ê§â§Ú§æ§ä§ö§Ó", DlgPasteRemoveStyles : "§£§Ú§Õ§Ñ§Ý§Ú§ä§Ú §ß§Ñ§Ý§Ñ§ê§ä§å§Ó§Ñ§ß§ß§ñ §ã§ä§Ú§Ý§ö§Ó", -DlgPasteCleanBox : "§°§é§Ú§ã§ä§Ú§ä§Ú §à§Ò§Ý§Ñ§ã§ä§î", // Color Picker ColorAutomatic : "§¡§Ó§ä§à§Þ§Ñ§ä§Ú§é§ß§Ú§Û", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "§­§ö§è§Ö§ß§Ù§ö§ñ", DlgAboutVersion : "§£§Ö§â§ã§ö§ñ", DlgAboutInfo : "§¥§à§Õ§Ñ§ä§Ü§à§Ó§å §ö§ß§æ§à§â§Þ§Ñ§è§ö§ð §Õ§Ú§Ó§ö§ä§î§ã§ñ §ß§Ñ " -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/vi.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/vi.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/vi.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "Ch«²n/S?a Li«´n k?t", RemoveLink : "Xo«¡ Li«´n k?t", Anchor : "Ch«²n/S?a Neo", +AnchorDelete : "Remove Anchor", //MISSING InsertImageLbl : "H«Ành ?nh", InsertImage : "Ch«²n/S?a H«Ành ?nh", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "Canh ©Â?u", DecreaseIndent : "D?ch ra ngo«¢i", IncreaseIndent : "D?ch v«¢o trong", +Blockquote : "Blockquote", //MISSING Undo : "Kh«Ôi ph?c thao t«¡c", Redo : "L«¢m l?i thao t«¡c", NumberedListLbl : "Danh s«¡ch c«Ñ th? t?", @@ -103,20 +105,27 @@ ImageButton : "N«ât h«Ành ?nh", FitWindow : "M? r?ng t?i ©Âa k«¿ch th??c tr«Ành bi«´n t?p", +ShowBlocks : "Show Blocks", //MISSING // Context Menu EditLink : "S?a Li«´n k?t", CellCM : "ªÔ", RowCM : "H«¢ng", ColumnCM : "C?t", -InsertRow : "Ch«²n H«¢ng", +InsertRowAfter : "Insert Row After", //MISSING +InsertRowBefore : "Insert Row Before", //MISSING DeleteRows : "Xo«¡ H«¢ng", -InsertColumn : "Ch«²n C?t", +InsertColumnAfter : "Insert Column After", //MISSING +InsertColumnBefore : "Insert Column Before", //MISSING DeleteColumns : "Xo«¡ C?t", -InsertCell : "Ch«²n ªÔ", +InsertCellAfter : "Insert Cell After", //MISSING +InsertCellBefore : "Insert Cell Before", //MISSING DeleteCells : "Xo«¡ ªÔ", MergeCells : "Tr?n ªÔ", -SplitCell : "Chia ªÔ", +MergeRight : "Merge Right", //MISSING +MergeDown : "Merge Down", //MISSING +HorizontalSplitCell : "Split Cell Horizontally", //MISSING +VerticalSplitCell : "Split Cell Vertically", //MISSING TableDelete : "X«Ña B?ng", CellProperties : "Thu?c t«¿nh ªÔ", TableProperties : "Thu?c t«¿nh B?ng", @@ -134,7 +143,7 @@ TextareaProp : "Thu?c t«¿nh V«ãng v«¥n b?n", FormProp : "Thu?c t«¿nh Bi?u m?u", -FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)", // Alerts and Messages ProcessingXHTML : "©¢ang x? l«ò XHTML. Vui l«Òng ©Â?i trong gi«¤y l«¡t...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "Ch?n m?t Neo", DlgLnkAnchorByName : "Theo T«´n Neo", DlgLnkAnchorById : "Theo ©¢?nh danh Element", -DlgLnkNoAnchors : "", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(Kh«Ông c«Ñ Neo n«¢o trong t«¢i li?u)", DlgLnkEMail : "Th? ©Âi?n t?", DlgLnkEMailSubject : "Ti«´u ©Â? Th«Ông ©Âi?p", DlgLnkEMailBody : "N?i dung Th«Ông ©Âi?p", @@ -322,6 +331,9 @@ DlgCellBorderColor : "M«¢u vi?n", DlgCellBtnSelect : "Ch?n...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "Find and Replace", //MISSING + // Find Dialog DlgFindTitle : "T«Àm ki?m", DlgFindFindBtn : "T«Àm ki?m", @@ -347,7 +359,6 @@ DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING DlgPasteIgnoreFont : "Ch?p nh?n c«¡c ©Â?nh d?ng ph«Ông", DlgPasteRemoveStyles : "G? b? c«¡c ©Â?nh d?ng Styles", -DlgPasteCleanBox : "X«Ña n?i dung", // Color Picker ColorAutomatic : "T? ©Â?ng", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "Gi?y ph«±p", DlgAboutVersion : "phi«´n b?n", DlgAboutInfo : "©¢? bi?t th«´m th«Ông tin, h«ªy truy c?p" -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/zh-cn.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/zh-cn.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/zh-cn.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "ÙçÆþ/??Ķ?ÀÜ", RemoveLink : "¼è¾ÃĶ?ÀÜ", Anchor : "ÙçÆþ/???ÅÀ?ÀÜ", +AnchorDelete : "À¶½ü?ÅÀ?ÀÜ", InsertImageLbl : "?¾Ý", InsertImage : "ÙçÆþ/???¾Ý", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "°¨Ã¼??", DecreaseIndent : "³¢¾¯??ÎÌ", IncreaseIndent : "?²Ã??ÎÌ", +Blockquote : "°úÍÑʸ»ú", Undo : "ű¾Ã", Redo : "½ÅÐö", NumberedListLbl : "?¹æÎóɽ", @@ -103,20 +105,27 @@ ImageButton : "?Áü°è", FitWindow : "Á´Ö¢??", +ShowBlocks : "?¼¨¶è?", // Context Menu EditLink : "??Ķ?ÀÜ", CellCM : "?¸µ³Ê", RowCM : "¹Ô", ColumnCM : "Îó", -InsertRow : "ÙçÆþ¹Ô", +InsertRowAfter : "²¼ÙçÆþ¹Ô", +InsertRowBefore : "¾åÙçÆþ¹Ô", DeleteRows : "?½ü¹Ô", -InsertColumn : "ÙçÆþÎó", +InsertColumnAfter : "±¦ÙçÆþÎó", +InsertColumnBefore : "º¸ÙçÆþÎó", DeleteColumns : "?½üÎó", -InsertCell : "ÙçÆþ?¸µ³Ê", +InsertCellAfter : "±¦ÙçÆþ?¸µ³Ê", +InsertCellBefore : "º¸ÙçÆþ?¸µ³Ê", DeleteCells : "?½ü?¸µ³Ê", MergeCells : "¹çÖõ?¸µ³Ê", -SplitCell : "پʬ?¸µ³Ê", +MergeRight : "±¦¹çÖõ?¸µ³Ê", +MergeDown : "²¼¹çÖõ?¸µ³Ê", +HorizontalSplitCell : "?پʬ?¸µ³Ê", +VerticalSplitCell : "åÔپʬ?¸µ³Ê", TableDelete : "?½üɽ³Ê", CellProperties : "?¸µ³Ê°À­", TableProperties : "ɽ³Ê°À­", @@ -134,7 +143,7 @@ TextareaProp : "¿¹ÔʸËÜ°À­", FormProp : "ɽ?°À­", -FontFormats : "ÉáÄÌ;Öá?Çӳʼ°;ÃÏÔ®;?? 1;?? 2;?? 3;?? 4;?? 5;?? 6;ÃÊÍî(DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "ÉáÄÌ;Öá?Çӳʼ°;ÃÏÔ®;?? 1;?? 2;?? 3;?? 4;?? 5;?? 6;ÃÊÍî(DIV)", // Alerts and Messages ProcessingXHTML : "Àµºß?Íý XHTML¡¤?ãÄÅù...", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "??°ìФ?ÅÀ", DlgLnkAnchorByName : "°Ä?ÅÀ̾¾Î", DlgLnkAnchorById : "°Ä?ÅÀ ID", -DlgLnkNoAnchors : "<º¡Ê¸ÛãË×Í­²ÄÍÑŪ?ÅÀ>", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(º¡Ê¸ÛãË×Í­²ÄÍÑŪ?ÅÀ)", DlgLnkEMail : "ÃÏÔ®", DlgLnkEMailSubject : "¼ç?", DlgLnkEMailBody : "ÆâÍÆ", @@ -322,6 +331,9 @@ DlgCellBorderColor : "?ÛÚ?¿§", DlgCellBtnSelect : "??...", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "?Ù²ÏÂÂØ?", + // Find Dialog DlgFindTitle : "?Ù²", DlgFindFindBtn : "?Ù²", @@ -344,10 +356,9 @@ PasteFromWord : "к MS Word Ç´?", DlgPasteMsg2 : "?»ÈÍÑ??²÷¾¹?(Ctrl+V)ÇÄÆâÍÆÇ´?Åþ²¼ÌÌŪÊýÛÚΤ¡¤ºÆ°Ä ÏìÄê¡£", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "°ø?°ßŪ??´ïŪ°ÂÁ´?ÃÖ¸¶°ø¡¤ËÜ??´ïÉÔǽľÀÜ??°ßŪÑò?ÈÄÆâÍÆ¡¤°ß¼ûÍ׺ßËÜãÙ¸ý½Å¿·Ç´?°ì¼¡¡£", DlgPasteIgnoreFont : "¹úά Font ??", DlgPasteRemoveStyles : "À¶Íý CSS ?¼°", -DlgPasteCleanBox : "À¶¶õ¾åÌÌÆâÍÆ", // Color Picker ColorAutomatic : "¼«?", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "?²Ä?", DlgAboutVersion : "ÈÇËÜ", DlgAboutInfo : "Í×?ÆÀ¹¹Â¿¿®Â©??? " -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/zh.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/zh.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/lang/zh.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -45,6 +45,7 @@ InsertLink : "ÙçÆþ/ÊÔ½´Ä¶Ï¢·ë", RemoveLink : "°Ü½üĶϢ·ë", Anchor : "ÙçÆþ/ÊÔ½´ÉÅóÚ", +AnchorDelete : "°Ü½üÉÅóÚ", InsertImageLbl : "±ÆÁü", InsertImage : "ÙçÆþ/ÊÔ½´±ÆÁü", InsertFlashLbl : "Flash", @@ -70,6 +71,7 @@ BlockJustify : "º¸±¦Õôóî", DecreaseIndent : "¸º¾¯½ÌÇÓ", IncreaseIndent : "?²Ã½ÌÇÓ", +Blockquote : "?°úÍÑ", Undo : "Éü¸¶", Redo : "½ÅÊ£", NumberedListLbl : "ÊÔéËÀ¶ÓÅ", @@ -103,20 +105,27 @@ ImageButton : "±ÆÁü°Äîæ", FitWindow : "ÊÔ½´´ïºÇÂç²½", +ShowBlocks : "ðý¼¨Ò¿²ô", // Context Menu EditLink : "ÊÔ½´Ä¶Ï¢·ë", CellCM : "ÌÙ¸³Ê", RowCM : "Îó", ColumnCM : "Íó", -InsertRow : "ÙçÆþÎó", +InsertRowAfter : "¸þ²¼ÙçÆþÎó", +InsertRowBefore : "¸þ¾åÙçÆþÎó", DeleteRows : "Ñè½üÎó", -InsertColumn : "ÙçÆþÍó", +InsertColumnAfter : "¸þ±¦ÙçÆþÍó", +InsertColumnBefore : "¸þº¸ÙçÆþÍó", DeleteColumns : "Ñè½üÍó", -InsertCell : "ÙçÆþÌÙ¸³Ê", +InsertCellAfter : "¸þ±¦ÙçÆþÌÙ¸³Ê", +InsertCellBefore : "¸þº¸ÙçÆþÌÙ¸³Ê", DeleteCells : "Ñè½üÌÙ¸³Ê", MergeCells : "¹çÊ»ÌÙ¸³Ê", -SplitCell : "ʬ³äÌÙ¸³Ê", +MergeRight : "¸þ±¦¹çÊ»ÌÙ¸³Ê", +MergeDown : "¸þ²¼¹çÊ»ÌÙ¸³Ê", +HorizontalSplitCell : "?¸þʬ³äÌÙ¸³Ê", +VerticalSplitCell : "åÔ¸þʬ³äÌÙ¸³Ê", TableDelete : "Ñè½üɽ³Ê", CellProperties : "ÌÙ¸³ÊÖ¤À­", TableProperties : "ɽ³ÊÖ¤À­", @@ -134,7 +143,7 @@ TextareaProp : "ʸ»úÒ¿°èÖ¤À­", FormProp : "ɽÓÅÖ¤À­", -FontFormats : "ËÜʸ;Öá³Ê¼°²½;°ÌÔ®;ɸÂê 1;ɸÂê 2;ɸÂê 3;ɸÂê 4;ɸÂê 5;ɸÂê 6;ËÜʸ (DIV)", //REVIEW : Check _getfontformat.html +FontFormats : "°ìÈÌ;Öá³Ê¼°²½;°ÌÔ®;ɸÂê 1;ɸÂê 2;ɸÂê 3;ɸÂê 4;ɸÂê 5;ɸÂê 6;°ìÈÌ (DIV)", // Alerts and Messages ProcessingXHTML : "ÑÝÍý XHTML Ã桤ÀÁãĸõ¡Ä", @@ -229,7 +238,7 @@ DlgLnkAnchorSel : "ÀÁÁªÚ¤ÉÅóÚ", DlgLnkAnchorByName : "°ÍÉÅóÚ̾ãÊ", DlgLnkAnchorById : "°Í¸µ·ï ID", -DlgLnkNoAnchors : "<ËÜʸ·ï¾°Ìµ²ÄÍÑÇ·ÉÅóÚ>", //REVIEW : Change < and > with ( and ) +DlgLnkNoAnchors : "(ËÜʸ·ï¾°Ìµ²ÄÍÑÇ·ÉÅóÚ)", DlgLnkEMail : "ÅÅ»Ò͹·ï", DlgLnkEMailSubject : "͹·ï¼ç»Ý", DlgLnkEMailBody : "͹·ï?ÍÆ", @@ -322,6 +331,9 @@ DlgCellBorderColor : "î´ÛÚðú¿§", DlgCellBtnSelect : "ÀÁÁªÚ¤¡Ä", +// Find and Replace Dialog +DlgFindAndReplaceTitle : "¿ÒÙ²çмèÂå", + // Find Dialog DlgFindTitle : "¿ÒÙ²", DlgFindFindBtn : "¿ÒÙ²", @@ -344,10 +356,9 @@ PasteFromWord : "¼« Word Ž¾å", DlgPasteMsg2 : "ÀÁ»ÈÍѲ÷¾¹¸° (Ctrl+V) ŽÅþ²¼ÊýÒ¿°èÃæÊ°IJ¼ ³ÎÄê", -DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.", //MISSING +DlgPasteSec : "°ø°ÙßÈëµ´ïŪ°ÂÁ´À­ÀßÄꡤËÜÊÔ½´´ï̵ˡľÀܸ¼è½ûŪÑòŽÊí»ñÎÁ¡¤ÀÁ½û¼«¹ÔºßËÜ»ëãٿʹÔŽ¾åÆ°ºî¡£", DlgPasteIgnoreFont : "°Ü½ü»ú·¿ÀßÄê", DlgPasteRemoveStyles : "°Ü½üÜë¼°ÀßÄê", -DlgPasteCleanBox : "À¶½üʸ»úÒ¿°è", // Color Picker ColorAutomatic : "¼«Æ°", @@ -501,4 +512,4 @@ DlgAboutLicenseTab : "µö²Äëú", DlgAboutVersion : "ÈÇËÜ", DlgAboutInfo : "ÁÛ³ÍÆÀ¹¹Â¿»ñ¿ÖÀÁ»ê " -}; \ No newline at end of file +}; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/autogrow/fckplugin.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/autogrow/fckplugin.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/autogrow/fckplugin.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ?/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -63,6 +63,13 @@ return ; window.frameElement.height = iMainFrameSize ; + + // Gecko browsers use an onresize handler to update the innermost + // IFRAME's height. If the document is modified before the onresize + // is triggered, the plugin will miscalculate the new height. Thus, + // forcibly trigger onresize. #1336 + if ( typeof window.onresize == 'function' ) + window.onresize() ; } } @@ -89,4 +96,4 @@ FCKAutoGrow_Check() ; } -FCK.Events.AttachEvent( 'OnStatusChange', FCKAutoGrow_CheckEditorStatus ) ; \ No newline at end of file +FCK.Events.AttachEvent( 'OnStatusChange', FCKAutoGrow_CheckEditorStatus ) ; Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/bbcode/_sample/sample.config.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/bbcode/_sample/sample.config.js (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/bbcode/_sample/sample.config.js 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,26 @@ +?/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * Sample custom configuration settings used by the BBCode plugin. It simply + * loads the plugin. All the rest is done by the plugin itself. + */ + +// Add the BBCode plugin. +FCKConfig.Plugins.Add( 'bbcode' ) ; Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/bbcode/_sample/sample.html =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/bbcode/_sample/sample.html (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/bbcode/_sample/sample.html 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,67 @@ + + + + + FCKeditor - BBCode Sample + + + + + + +

      + FCKeditor - BBCode Sample

      +

      + This is a sample of custom Data Processor implementation for (very) basic BBCode + syntax. Only [b], [i], [u] and + [url] may be used. It may be extended, but this is out of this + sample purpose. +

      +

      + Note that the input and output of the editor is not HTML, but BBCode +

      +
      +
      + +
      + +
      + + Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/bbcode/fckplugin.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/bbcode/fckplugin.js (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/bbcode/fckplugin.js 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,123 @@ +?/* + * FCKeditor - The text editor for Internet - http://www.fckeditor.net + * Copyright (C) 2003-2008 Frederico Caldeira Knabben + * + * == BEGIN LICENSE == + * + * Licensed under the terms of any of the following licenses at your + * choice: + * + * - GNU General Public License Version 2 or later (the "GPL") + * http://www.gnu.org/licenses/gpl.html + * + * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") + * http://www.gnu.org/licenses/lgpl.html + * + * - Mozilla Public License Version 1.1 or later (the "MPL") + * http://www.mozilla.org/MPL/MPL-1.1.html + * + * == END LICENSE == + * + * This is a sample implementation for a custom Data Processor for basic BBCode. + */ + +FCK.DataProcessor = +{ + /* + * Returns a string representing the HTML format of "data". The returned + * value will be loaded in the editor. + * The HTML must be from to , eventually including + * the DOCTYPE. + * @param {String} data The data to be converted in the + * DataProcessor specific format. + */ + ConvertToHtml : function( data ) + { + // Convert < and > to their HTML entities. + data = data.replace( //g, '>' ) ; + + // Convert line breaks to
      . + data = data.replace( /(?:\r\n|\n|\r)/g, '
      ' ) ; + + // [url] + data = data.replace( /\[url\](.+?)\[\/url]/gi, '$1' ) ; + data = data.replace( /\[url\=([^\]]+)](.+?)\[\/url]/gi, '$2' ) ; + + // [b] + data = data.replace( /\[b\](.+?)\[\/b]/gi, '$1' ) ; + + // [i] + data = data.replace( /\[i\](.+?)\[\/i]/gi, '$1' ) ; + + // [u] + data = data.replace( /\[u\](.+?)\[\/u]/gi, '$1' ) ; + + return '' + data + '' ; + }, + + /* + * Converts a DOM (sub-)tree to a string in the data format. + * @param {Object} rootNode The node that contains the DOM tree to be + * converted to the data format. + * @param {Boolean} excludeRoot Indicates that the root node must not + * be included in the conversion, only its children. + * @param {Boolean} format Indicates that the data must be formatted + * for human reading. Not all Data Processors may provide it. + */ + ConvertToDataFormat : function( rootNode, excludeRoot, ignoreIfEmptyParagraph, format ) + { + var data = rootNode.innerHTML ; + + // Convert
      to line breaks. + data = data.replace( /]).*?>/gi, '\r\n') ; + + // [url] + data = data.replace( /(.+?)<\/a>/gi, '[url=$2]$3[/url]') ; + + // [b] + data = data.replace( /<(?:b|strong)>/gi, '[b]') ; + data = data.replace( /<\/(?:b|strong)>/gi, '[/b]') ; + + // [i] + data = data.replace( /<(?:i|em)>/gi, '[i]') ; + data = data.replace( /<\/(?:i|em)>/gi, '[/i]') ; + + // [u] + data = data.replace( //gi, '[u]') ; + data = data.replace( /<\/u>/gi, '[/u]') ; + + // Remove remaining tags. + data = data.replace( /<[^>]+>/g, '') ; + + return data ; + }, + + /* + * Makes any necessary changes to a piece of HTML for insertion in the + * editor selection position. + * @param {String} html The HTML to be fixed. + */ + FixHtml : function( html ) + { + return html ; + } +} ; + +// This Data Processor doesn't support

      , so let's use
      . +FCKConfig.EnterMode = 'br' ; + +// To avoid pasting invalid markup (which is discarded in any case), let's +// force pasting to plain text. +FCKConfig.ForcePasteAsPlainText = true ; + +// Rename the "Source" buttom to "BBCode". +FCKToolbarItems.RegisterItem( 'Source', new FCKToolbarButton( 'Source', 'BBCode', null, FCK_TOOLBARITEM_ICONTEXT, true, true, 1 ) ) ; + +// Let's enforce the toolbar to the limits of this Data Processor. A custom +// toolbar set may be defined in the configuration file with more or less entries. +FCKConfig.ToolbarSets["Default"] = [ + ['Source'], + ['Bold','Italic','Underline','-','Link'], + ['About'] +] ; Added: pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/dragresizetable/fckplugin.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/dragresizetable/fckplugin.js (rev 0) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/dragresizetable/fckplugin.js 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,527 @@ +?var FCKDragTableHandler = +{ + "_DragState" : 0, + "_LeftCell" : null, + "_RightCell" : null, + "_MouseMoveMode" : 0, // 0 - find candidate cells for resizing, 1 - drag to resize + "_ResizeBar" : null, + "_OriginalX" : null, + "_MinimumX" : null, + "_MaximumX" : null, + "_LastX" : null, + "_TableMap" : null, + "_doc" : document, + "_IsInsideNode" : function( w, domNode, pos ) + { + var myCoords = FCKTools.GetWindowPosition( w, domNode ) ; + var xMin = myCoords.x ; + var yMin = myCoords.y ; + var xMax = parseInt( xMin, 10 ) + parseInt( domNode.offsetWidth, 10 ) ; + var yMax = parseInt( yMin, 10 ) + parseInt( domNode.offsetHeight, 10 ) ; + if ( pos.x >= xMin && pos.x <= xMax && pos.y >= yMin && pos.y <= yMax ) + return true; + return false; + }, + "_GetBorderCells" : function( w, tableNode, tableMap, mouse ) + { + // Enumerate all the cells in the table. + var cells = [] ; + for ( var i = 0 ; i < tableNode.rows.length ; i++ ) + { + var r = tableNode.rows[i] ; + for ( var j = 0 ; j < r.cells.length ; j++ ) + cells.push( r.cells[j] ) ; + } + + if ( cells.length < 1 ) + return null ; + + // Get the cells whose right or left border is nearest to the mouse cursor's x coordinate. + var minRxDist = null ; + var lxDist = null ; + var minYDist = null ; + var rbCell = null ; + var lbCell = null ; + for ( var i = 0 ; i < cells.length ; i++ ) + { + var pos = FCKTools.GetWindowPosition( w, cells[i] ) ; + var rightX = pos.x + parseInt( cells[i].clientWidth, 10 ) ; + var rxDist = mouse.x - rightX ; + var yDist = mouse.y - ( pos.y + ( cells[i].clientHeight / 2 ) ) ; + if ( minRxDist == null || + ( Math.abs( rxDist ) <= Math.abs( minRxDist ) && + ( minYDist == null || Math.abs( yDist ) <= Math.abs( minYDist ) ) ) ) + { + minRxDist = rxDist ; + minYDist = yDist ; + rbCell = cells[i] ; + } + } + /* + var rowNode = FCKTools.GetElementAscensor( rbCell, "tr" ) ; + var cellIndex = rbCell.cellIndex + 1 ; + if ( cellIndex >= rowNode.cells.length ) + return null ; + lbCell = rowNode.cells.item( cellIndex ) ; + */ + var rowIdx = rbCell.parentNode.rowIndex ; + var colIdx = FCKTableHandler._GetCellIndexSpan( tableMap, rowIdx, rbCell ) ; + var colSpan = isNaN( rbCell.colSpan ) ? 1 : rbCell.colSpan ; + lbCell = tableMap[rowIdx][colIdx + colSpan] ; + + if ( ! lbCell ) + return null ; + + // Abort if too far from the border. + lxDist = mouse.x - FCKTools.GetWindowPosition( w, lbCell ).x ; + if ( lxDist < 0 && minRxDist < 0 && minRxDist < -2 ) + return null ; + if ( lxDist > 0 && minRxDist > 0 && lxDist > 3 ) + return null ; + + return { "leftCell" : rbCell, "rightCell" : lbCell } ; + }, + "_GetResizeBarPosition" : function() + { + var row = FCKTools.GetElementAscensor( this._RightCell, "tr" ) ; + return FCKTableHandler._GetCellIndexSpan( this._TableMap, row.rowIndex, this._RightCell ) ; + }, + "_ResizeBarMouseDownListener" : function( evt ) + { + if ( ! evt ) + evt = window.event ; + if ( FCKDragTableHandler._LeftCell ) + FCKDragTableHandler._MouseMoveMode = 1 ; + if ( FCKBrowserInfo.IsIE ) + FCKDragTableHandler._ResizeBar.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 50 ; + else + FCKDragTableHandler._ResizeBar.style.opacity = 0.5 ; + FCKDragTableHandler._OriginalX = evt.clientX ; + + // Calculate maximum and minimum x-coordinate delta. + var borderIndex = FCKDragTableHandler._GetResizeBarPosition() ; + var offset = FCKDragTableHandler._GetIframeOffset(); + var table = FCKTools.GetElementAscensor( FCKDragTableHandler._LeftCell, "table" ); + var minX = null ; + var maxX = null ; + for ( var r = 0 ; r < FCKDragTableHandler._TableMap.length ; r++ ) + { + var leftCell = FCKDragTableHandler._TableMap[r][borderIndex - 1] ; + var rightCell = FCKDragTableHandler._TableMap[r][borderIndex] ; + var leftPosition = FCKTools.GetWindowPosition( FCK.EditorWindow, leftCell ) ; + var rightPosition = FCKTools.GetWindowPosition( FCK.EditorWindow, rightCell ) ; + var leftPadding = FCKDragTableHandler._GetCellPadding( table, leftCell ) ; + var rightPadding = FCKDragTableHandler._GetCellPadding( table, rightCell ) ; + if ( minX == null || leftPosition.x + leftPadding > minX ) + minX = leftPosition.x + leftPadding ; + if ( maxX == null || rightPosition.x + rightCell.clientWidth - rightPadding < maxX ) + maxX = rightPosition.x + rightCell.clientWidth - rightPadding ; + } + + FCKDragTableHandler._MinimumX = minX + offset.x ; + FCKDragTableHandler._MaximumX = maxX + offset.x ; + FCKDragTableHandler._LastX = null ; + }, + "_ResizeBarMouseUpListener" : function( evt ) + { + if ( ! evt ) + evt = window.event ; + FCKDragTableHandler._MouseMoveMode = 0 ; + FCKDragTableHandler._HideResizeBar() ; + + if ( FCKDragTableHandler._LastX == null ) + return ; + + // Calculate the delta value. + var deltaX = FCKDragTableHandler._LastX - FCKDragTableHandler._OriginalX ; + + // Then, build an array of current column width values. + // This algorithm can be very slow if the cells have insane colSpan values. (e.g. colSpan=1000). + var table = FCKTools.GetElementAscensor( FCKDragTableHandler._LeftCell, "table" ) ; + var colArray = [] ; + var tableMap = FCKDragTableHandler._TableMap ; + for ( var i = 0 ; i < tableMap.length ; i++ ) + { + for ( var j = 0 ; j < tableMap[i].length ; j++ ) + { + var cell = tableMap[i][j] ; + var width = FCKDragTableHandler._GetCellWidth( table, cell ) ; + var colSpan = isNaN( cell.colSpan) ? 1 : cell.colSpan ; + if ( colArray.length <= j ) + colArray.push( { width : width / colSpan, colSpan : colSpan } ) ; + else + { + var guessItem = colArray[j] ; + if ( guessItem.colSpan > colSpan ) + { + guessItem.width = width / colSpan ; + guessItem.colSpan = colSpan ; + } + } + } + } + + // Find out the equivalent column index of the two cells selected for resizing. + colIndex = FCKDragTableHandler._GetResizeBarPosition() ; + + // Note that colIndex must be at least 1 here, so it's safe to subtract 1 from it. + colIndex-- ; + + // Modify the widths in the colArray according to the mouse coordinate delta value. + colArray[colIndex].width += deltaX ; + colArray[colIndex + 1].width -= deltaX ; + + // Clear all cell widths, delete all elements from the table. + for ( var r = 0 ; r < table.rows.length ; r++ ) + { + var row = table.rows.item( r ) ; + for ( var c = 0 ; c < row.cells.length ; c++ ) + { + var cell = row.cells.item( c ) ; + cell.width = "" ; + cell.style.width = "" ; + } + } + var colElements = table.getElementsByTagName( "col" ) ; + for ( var i = colElements.length - 1 ; i >= 0 ; i-- ) + colElements[i].parentNode.removeChild( colElements[i] ) ; + + // Set new cell widths. + var processedCells = [] ; + for ( var i = 0 ; i < tableMap.length ; i++ ) + { + for ( var j = 0 ; j < tableMap[i].length ; j++ ) + { + var cell = tableMap[i][j] ; + if ( cell._Processed ) + continue ; + if ( tableMap[i][j-1] != cell ) + cell.width = colArray[j].width ; + else + cell.width = parseInt( cell.width, 10 ) + parseInt( colArray[j].width, 10 ) ; + if ( tableMap[i][j+1] != cell ) + { + processedCells.push( cell ) ; + cell._Processed = true ; + } + } + } + for ( var i = 0 ; i < processedCells.length ; i++ ) + { + if ( FCKBrowserInfo.IsIE ) + processedCells[i].removeAttribute( '_Processed' ) ; + else + delete processedCells[i]._Processed ; + } + + FCKDragTableHandler._LastX = null ; + }, + "_ResizeBarMouseMoveListener" : function( evt ) + { + if ( ! evt ) + evt = window.event ; + if ( FCKDragTableHandler._MouseMoveMode == 0 ) + return FCKDragTableHandler._MouseFindHandler( FCK, evt ) ; + else + return FCKDragTableHandler._MouseDragHandler( FCK, evt ) ; + }, + // Calculate the padding of a table cell. + // It returns the value of paddingLeft + paddingRight of a table cell. + // This function is used, in part, to calculate the width parameter that should be used for setting cell widths. + // The equation in question is clientWidth = paddingLeft + paddingRight + width. + // So that width = clientWidth - paddingLeft - paddingRight. + // The return value of this function must be pixel accurate acorss all supported browsers, so be careful if you need to modify it. + "_GetCellPadding" : function( table, cell ) + { + var attrGuess = parseInt( table.cellPadding, 10 ) * 2 ; + var cssGuess = null ; + if ( typeof( window.getComputedStyle ) == "function" ) + { + var styleObj = window.getComputedStyle( cell, null ) ; + cssGuess = parseInt( styleObj.getPropertyValue( "padding-left" ), 10 ) + + parseInt( styleObj.getPropertyValue( "padding-right" ), 10 ) ; + } + else + cssGuess = parseInt( cell.currentStyle.paddingLeft, 10 ) + parseInt (cell.currentStyle.paddingRight, 10 ) ; + + var cssRuntime = cell.style.padding ; + if ( isFinite( cssRuntime ) ) + cssGuess = parseInt( cssRuntime, 10 ) * 2 ; + else + { + cssRuntime = cell.style.paddingLeft ; + if ( isFinite( cssRuntime ) ) + cssGuess = parseInt( cssRuntime, 10 ) ; + cssRuntime = cell.style.paddingRight ; + if ( isFinite( cssRuntime ) ) + cssGuess += parseInt( cssRuntime, 10 ) ; + } + + attrGuess = parseInt( attrGuess, 10 ) ; + cssGuess = parseInt( cssGuess, 10 ) ; + if ( isNaN( attrGuess ) ) + attrGuess = 0 ; + if ( isNaN( cssGuess ) ) + cssGuess = 0 ; + return Math.max( attrGuess, cssGuess ) ; + }, + // Calculate the real width of the table cell. + // The real width of the table cell is the pixel width that you can set to the width attribute of the table cell and after + // that, the table cell should be of exactly the same width as before. + // The real width of a table cell can be calculated as: + // width = clientWidth - paddingLeft - paddingRight. + "_GetCellWidth" : function( table, cell ) + { + var clientWidth = cell.clientWidth ; + if ( isNaN( clientWidth ) ) + clientWidth = 0 ; + return clientWidth - this._GetCellPadding( table, cell ) ; + }, + "MouseMoveListener" : function( FCK, evt ) + { + if ( FCKDragTableHandler._MouseMoveMode == 0 ) + return FCKDragTableHandler._MouseFindHandler( FCK, evt ) ; + else + return FCKDragTableHandler._MouseDragHandler( FCK, evt ) ; + }, + "_MouseFindHandler" : function( FCK, evt ) + { + if ( FCK.MouseDownFlag ) + return ; + var node = evt.srcElement || evt.target ; + try + { + if ( ! node || node.nodeType != 1 ) + { + this._HideResizeBar() ; + return ; + } + } + catch ( e ) + { + this._HideResizeBar() ; + return ; + } + + // Since this function might be called from the editing area iframe or the outer fckeditor iframe, + // the mouse point coordinates from evt.clientX/Y can have different reference points. + // We need to resolve the mouse pointer position relative to the editing area iframe. + var mouseX = evt.clientX ; + var mouseY = evt.clientY ; + if ( FCKTools.GetElementDocument( node ) == document ) + { + var offset = this._GetIframeOffset() ; + mouseX -= offset.x ; + mouseY -= offset.y ; + } + + + if ( this._ResizeBar && this._LeftCell ) + { + var leftPos = FCKTools.GetWindowPosition( FCK.EditorWindow, this._LeftCell ) ; + var rightPos = FCKTools.GetWindowPosition( FCK.EditorWindow, this._RightCell ) ; + var rxDist = mouseX - ( leftPos.x + this._LeftCell.clientWidth ) ; + var lxDist = mouseX - rightPos.x ; + var inRangeFlag = false ; + if ( lxDist >= 0 && rxDist <= 0 ) + inRangeFlag = true ; + else if ( rxDist > 0 && lxDist <= 3 ) + inRangeFlag = true ; + else if ( lxDist < 0 && rxDist >= -2 ) + inRangeFlag = true ; + if ( inRangeFlag ) + { + this._ShowResizeBar( FCK.EditorWindow, + FCKTools.GetElementAscensor( this._LeftCell, "table" ), + { "x" : mouseX, "y" : mouseY } ) ; + return ; + } + } + + var tagName = node.tagName.toLowerCase() ; + if ( tagName != "table" && tagName != "td" && tagName != "th" ) + { + if ( this._LeftCell ) + this._LeftCell = this._RightCell = this._TableMap = null ; + this._HideResizeBar() ; + return ; + } + node = FCKTools.GetElementAscensor( node, "table" ) ; + var tableMap = FCKTableHandler._CreateTableMap( node ) ; + var cellTuple = this._GetBorderCells( FCK.EditorWindow, node, tableMap, { "x" : mouseX, "y" : mouseY } ) ; + + if ( cellTuple == null ) + { + if ( this._LeftCell ) + this._LeftCell = this._RightCell = this._TableMap = null ; + this._HideResizeBar() ; + } + else + { + this._LeftCell = cellTuple["leftCell"] ; + this._RightCell = cellTuple["rightCell"] ; + this._TableMap = tableMap ; + this._ShowResizeBar( FCK.EditorWindow, + FCKTools.GetElementAscensor( this._LeftCell, "table" ), + { "x" : mouseX, "y" : mouseY } ) ; + } + }, + "_MouseDragHandler" : function( FCK, evt ) + { + var mouse = { "x" : evt.clientX, "y" : evt.clientY } ; + + // Convert mouse coordinates in reference to the outer iframe. + var node = evt.srcElement || evt.target ; + if ( FCKTools.GetElementDocument( node ) == FCK.EditorDocument ) + { + var offset = this._GetIframeOffset() ; + mouse.x += offset.x ; + mouse.y += offset.y ; + } + + // Calculate the mouse position delta and see if we've gone out of range. + if ( mouse.x >= this._MaximumX - 5 ) + mouse.x = this._MaximumX - 5 ; + if ( mouse.x <= this._MinimumX + 5 ) + mouse.x = this._MinimumX + 5 ; + + var docX = mouse.x + FCKTools.GetScrollPosition( window ).X ; + this._ResizeBar.style.left = ( docX - this._ResizeBar.offsetWidth / 2 ) + "px" ; + this._LastX = mouse.x ; + }, + "_ShowResizeBar" : function( w, table, mouse ) + { + if ( this._ResizeBar == null ) + { + this._ResizeBar = this._doc.createElement( "div" ) ; + var paddingBar = this._ResizeBar ; + var paddingStyles = { 'position' : 'absolute', 'cursor' : 'e-resize' } ; + if ( FCKBrowserInfo.IsIE ) + paddingStyles.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=10,enabled=true)" ; + else + paddingStyles.opacity = 0.10 ; + FCKDomTools.SetElementStyles( paddingBar, paddingStyles ) ; + this._avoidStyles( paddingBar ); + paddingBar.setAttribute('_fcktemp', true); + this._doc.body.appendChild( paddingBar ) ; + FCKTools.AddEventListener( paddingBar, "mousemove", this._ResizeBarMouseMoveListener ) ; + FCKTools.AddEventListener( paddingBar, "mousedown", this._ResizeBarMouseDownListener ) ; + FCKTools.AddEventListener( document, "mouseup", this._ResizeBarMouseUpListener ) ; + FCKTools.AddEventListener( FCK.EditorDocument, "mouseup", this._ResizeBarMouseUpListener ) ; + + // IE doesn't let the tranparent part of the padding block to receive mouse events unless there's something inside. + // So we need to create a spacer image to fill the block up. + var filler = this._doc.createElement( "img" ) ; + filler.setAttribute('_fcktemp', true); + filler.border = 0 ; + filler.src = FCKConfig.BasePath + "images/spacer.gif" ; + filler.style.position = "absolute" ; + paddingBar.appendChild( filler ) ; + + // Disable drag and drop, and selection for the filler image. + var disabledListener = function( evt ) + { + if ( ! evt ) + evt = window.event ; + if ( evt.preventDefault ) + evt.preventDefault() ; + else + evt.returnValue = false ; + } + FCKTools.AddEventListener( filler, "dragstart", disabledListener ) ; + FCKTools.AddEventListener( filler, "selectstart", disabledListener ) ; + } + + var paddingBar = this._ResizeBar ; + var offset = this._GetIframeOffset() ; + var tablePos = this._GetTablePosition( w, table ) ; + var barHeight = table.offsetHeight ; + var barTop = offset.y + tablePos.y ; + // Do not let the resize bar intrude into the toolbar area. + if ( tablePos.y < 0 ) + { + barHeight += tablePos.y ; + barTop -= tablePos.y ; + } + var bw = parseInt( table.border, 10 ) ; + if ( isNaN( bw ) ) + bw = 0 ; + var cs = parseInt( table.cellSpacing, 10 ) ; + if ( isNaN( cs ) ) + cs = 0 ; + var barWidth = Math.max( bw+100, cs+100 ) ; + var paddingStyles = + { + 'top' : barTop + 'px', + 'height' : barHeight + 'px', + 'width' : barWidth + 'px', + 'left' : ( offset.x + mouse.x + FCKTools.GetScrollPosition( w ).X - barWidth / 2 ) + 'px' + } ; + if ( FCKBrowserInfo.IsIE ) + paddingBar.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 10 ; + else + paddingStyles.opacity = 0.1 ; + + FCKDomTools.SetElementStyles( paddingBar, paddingStyles ) ; + var filler = paddingBar.getElementsByTagName( "img" )[0] ; + + FCKDomTools.SetElementStyles( filler, + { + width : paddingBar.offsetWidth + 'px', + height : barHeight + 'px' + } ) ; + + barWidth = Math.max( bw, cs, 3 ) ; + var visibleBar = null ; + if ( paddingBar.getElementsByTagName( "div" ).length < 1 ) + { + visibleBar = this._doc.createElement( "div" ) ; + this._avoidStyles( visibleBar ); + visibleBar.setAttribute('_fcktemp', true); + paddingBar.appendChild( visibleBar ) ; + } + else + visibleBar = paddingBar.getElementsByTagName( "div" )[0] ; + + FCKDomTools.SetElementStyles( visibleBar, + { + position : 'absolute', + backgroundColor : 'blue', + width : barWidth + 'px', + height : barHeight + 'px', + left : '50px', + top : '0px' + } ) ; + }, + "_HideResizeBar" : function() + { + if ( this._ResizeBar ) + // IE bug: display : none does not hide the resize bar for some reason. + // so set the position to somewhere invisible. + FCKDomTools.SetElementStyles( this._ResizeBar, + { + top : '-100000px', + left : '-100000px' + } ) ; + }, + "_GetIframeOffset" : function () + { + return FCKTools.GetDocumentPosition( window, FCK.EditingArea.IFrame ) ; + }, + "_GetTablePosition" : function ( w, table ) + { + return FCKTools.GetWindowPosition( w, table ) ; + }, + "_avoidStyles" : function( element ) + { + FCKDomTools.SetElementStyles( element, + { + padding : '0', + backgroundImage : 'none', + border : '0' + } ) ; + } + +}; + +FCK.Events.AttachEvent( "OnMouseMove", FCKDragTableHandler.MouseMoveListener ) ; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/placeholder/fck_placeholder.html =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/placeholder/fck_placeholder.html 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/editor/plugins/placeholder/fck_placeholder.html 2008-05-15 06:08:06 UTC (rev 930) @@ -1,7 +1,7 @@ + + + + #CreateHtml()# + + + @@ -62,9 +76,9 @@ // display the html editor or a plain textarea? if( isCompatible() ) - showHTMLEditor(); + return getHtmlEditor(); else - showTextArea(); + return getTextArea(); @@ -86,70 +100,48 @@ if( not this.checkBrowser ) return true; - // check for Internet Explorer ( >= 5.5 ) - if( find( "msie", sAgent ) and not find( "mac", sAgent ) and not find( "opera", sAgent ) ) - { - // try to extract IE version - stResult = reFind( "msie ([5-9]\.[0-9])", sAgent, 1, true ); - if( arrayLen( stResult.pos ) eq 2 ) - { - // get IE Version - sBrowserVersion = mid( sAgent, stResult.pos[2], stResult.len[2] ); - return ( sBrowserVersion GTE 5.5 ); - } - } - // check for Gecko ( >= 20030210+ ) - else if( find( "gecko/", sAgent ) ) - { - // try to extract Gecko version date - stResult = reFind( "gecko/(200[3-9][0-1][0-9][0-3][0-9])", sAgent, 1, true ); - if( arrayLen( stResult.pos ) eq 2 ) - { - // get Gecko build (i18n date) - sBrowserVersion = mid( sAgent, stResult.pos[2], stResult.len[2] ); - return ( sBrowserVersion GTE 20030210 ); - } - } - - return false; + return FCKeditor_IsCompatibleBrowser(); + + + - // append unit "px" for numeric width and/or height values - if( isNumeric( this.width ) ) - this.width = this.width & "px"; - if( isNumeric( this.height ) ) - this.height = this.height & "px"; - + if( Find( "%", this.width ) gt 0) + sWidthCSS = this.width; + else + sWidthCSS = this.width & "px"; - -

      - -
      - + if( Find( "%", this.width ) gt 0) + sHeightCSS = this.height; + else + sHeightCSS = this.height & "px"; + result = "" & chr(13) & chr(10); + + + + - var sURL = ""; - // try to fix the basePath, if ending slash is missing if( len( this.basePath) and right( this.basePath, 1 ) is not "/" ) this.basePath = this.basePath & "/"; @@ -162,14 +154,12 @@ sURL = sURL & "&Toolbar=" & this.toolbarSet; - -
      - - - -
      -
      - + + result = result & "" & chr(13) & chr(10); + result = result & "" & chr(13) & chr(10); + result = result & "" & chr(13) & chr(10); + +
      + + + + + + - var sParams = ""; - var key = ""; - var fieldValue = ""; - var fieldLabel = ""; - var lConfigKeys = ""; - var iPos = ""; - /** * CFML doesn't store casesensitive names for structure keys, but the configuration names must be casesensitive for js. * So we need to find out the correct case for the configuration keys. * We "fix" this by comparing the caseless configuration keys to a list of all available configuration options in the correct case. * changed 20041206 hk ¡÷ lwd.de (improvements are welcome!) */ - lConfigKeys = lConfigKeys & "CustomConfigurationsPath,EditorAreaCSS,DocType,BaseHref,FullPage,Debug,SkinPath,PluginsPath,AutoDetectLanguage,DefaultLanguage,ContentLangDirection,EnableXHTML,EnableSourceXHTML,ProcessHTMLEntities,IncludeLatinEntities,IncludeGreekEntities"; - lConfigKeys = lConfigKeys & ",FillEmptyBlocks,FormatSource,FormatOutput,FormatIndentator,GeckoUseSPAN,StartupFocus,ForcePasteAsPlainText,ForceSimpleAmpersand,TabSpaces,ShowBorders,UseBROnCarriageReturn"; - lConfigKeys = lConfigKeys & ",ToolbarStartExpanded,ToolbarCanCollapse,ToolbarSets,ContextMenu,FontColors,FontNames,FontSizes,FontFormats,StylesXmlPath,SpellChecker,IeSpellDownloadUrl,MaxUndoLevels"; - lConfigKeys = lConfigKeys & ",LinkBrowser,LinkBrowserURL,LinkBrowserWindowWidth,LinkBrowserWindowHeight"; - lConfigKeys = lConfigKeys & ",LinkUpload,LinkUploadURL,LinkUploadWindowWidth,LinkUploadWindowHeight,LinkUploadAllowedExtensions,LinkUploadDeniedExtensions"; - lConfigKeys = lConfigKeys & ",ImageBrowser,ImageBrowserURL,ImageBrowserWindowWidth,ImageBrowserWindowHeight,SmileyPath,SmileyImages,SmileyColumns,SmileyWindowWidth,SmileyWindowHeight"; + lConfigKeys = lConfigKeys & "CustomConfigurationsPath,EditorAreaCSS,ToolbarComboPreviewCSS,DocType"; + lConfigKeys = lConfigKeys & ",BaseHref,FullPage,Debug,AllowQueryStringDebug,SkinPath"; + lConfigKeys = lConfigKeys & ",PreloadImages,PluginsPath,AutoDetectLanguage,DefaultLanguage,ContentLangDirection"; + lConfigKeys = lConfigKeys & ",ProcessHTMLEntities,IncludeLatinEntities,IncludeGreekEntities,ProcessNumericEntities,AdditionalNumericEntities"; + lConfigKeys = lConfigKeys & ",FillEmptyBlocks,FormatSource,FormatOutput,FormatIndentator"; + lConfigKeys = lConfigKeys & ",StartupFocus,ForcePasteAsPlainText,AutoDetectPasteFromWord,ForceSimpleAmpersand"; + lConfigKeys = lConfigKeys & ",TabSpaces,ShowBorders,SourcePopup,ToolbarStartExpanded,ToolbarCanCollapse"; + lConfigKeys = lConfigKeys & ",IgnoreEmptyParagraphValue,PreserveSessionOnFileBrowser,FloatingPanelsZIndex,TemplateReplaceAll,TemplateReplaceCheckbox"; + lConfigKeys = lConfigKeys & ",ToolbarLocation,ToolbarSets,EnterMode,ShiftEnterMode,Keystrokes"; + lConfigKeys = lConfigKeys & ",ContextMenu,BrowserContextMenuOnCtrl,FontColors,FontNames,FontSizes"; + lConfigKeys = lConfigKeys & ",FontFormats,StylesXmlPath,TemplatesXmlPath,SpellChecker,IeSpellDownloadUrl"; + lConfigKeys = lConfigKeys & ",SpellerPagesServerScript,FirefoxSpellChecker,MaxUndoLevels,DisableObjectResizing,DisableFFTableHandles"; + lConfigKeys = lConfigKeys & ",LinkDlgHideTarget,LinkDlgHideAdvanced,ImageDlgHideLink,ImageDlgHideAdvanced,FlashDlgHideAdvanced"; + lConfigKeys = lConfigKeys & ",ProtectedTags,BodyId,BodyClass,DefaultLinkTarget,CleanWordKeepsStructure"; + lConfigKeys = lConfigKeys & ",LinkBrowser,LinkBrowserURL,LinkBrowserWindowWidth,LinkBrowserWindowHeight,ImageBrowser"; + lConfigKeys = lConfigKeys & ",ImageBrowserURL,ImageBrowserWindowWidth,ImageBrowserWindowHeight,FlashBrowser,FlashBrowserURL"; + lConfigKeys = lConfigKeys & ",FlashBrowserWindowWidth,FlashBrowserWindowHeight,LinkUpload,LinkUploadURL,LinkUploadWindowWidth"; + lConfigKeys = lConfigKeys & ",LinkUploadWindowHeight,LinkUploadAllowedExtensions,LinkUploadDeniedExtensions,ImageUpload,ImageUploadURL"; + lConfigKeys = lConfigKeys & ",ImageUploadAllowedExtensions,ImageUploadDeniedExtensions,FlashUpload,FlashUploadURL,FlashUploadAllowedExtensions"; + lConfigKeys = lConfigKeys & ",FlashUploadDeniedExtensions,SmileyPath,SmileyImages,SmileyColumns,SmileyWindowWidth,SmileyWindowHeight"; for( key in this.config ) { @@ -226,4 +229,4 @@ - \ No newline at end of file + Modified: pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.cfm =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.cfm 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.cfm 2008-05-15 06:08:06 UTC (rev 930) @@ -1,7 +1,7 @@ -
      -
      - \ No newline at end of file + Modified: pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.js =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.js 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.js 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ /* * FCKeditor - The text editor for Internet - http://www.fckeditor.net - * Copyright (C) 2003-2007 Frederico Caldeira Knabben + * Copyright (C) 2003-2008 Frederico Caldeira Knabben * * == BEGIN LICENSE == * @@ -34,11 +34,9 @@ this.Height = height || '200' ; this.ToolbarSet = toolbarSet || 'Default' ; this.Value = value || '' ; - this.BasePath = '/fckeditor/' ; + this.BasePath = FCKeditor.BasePath ; this.CheckBrowser = true ; this.DisplayErrors = true ; - this.EnableSafari = false ; // This is a temporary property, while Safari support is under development. - this.EnableOpera = false ; // This is a temporary property, while Opera support is under development. this.Config = new Object() ; @@ -46,9 +44,24 @@ this.OnError = null ; // function( source, errorNumber, errorDescription ) } -FCKeditor.prototype.Version = '2.4.2' ; -FCKeditor.prototype.VersionBuild = '14978' ; +/** + * This is the default BasePath used by all editor instances. + */ +FCKeditor.BasePath = '/fckeditor/' ; +/** + * The minimum height used when replacing textareas. + */ +FCKeditor.MinHeight = 200 ; + +/** + * The minimum width used when replacing textareas. + */ +FCKeditor.MinWidth = 750 ; + +FCKeditor.prototype.Version = '2.6' ; +FCKeditor.prototype.VersionBuild = '18638' ; + FCKeditor.prototype.Create = function() { document.write( this.CreateHtml() ) ; @@ -63,7 +76,7 @@ return '' ; } - var sHtml = '
      ' ; + var sHtml = '' ; if ( !this.CheckBrowser || this._IsCompatibleBrowser() ) { @@ -78,8 +91,6 @@ sHtml += ' -
      '); /if; return(@#out); /define_tag; define_tag('isCompatibleBrowser'); - local('result' = true); - (client_browser >> 'Apple' || client_browser >> 'Opera' || client_browser >> 'KHTML') ? #result = false; + local('result' = false); + if (client_browser->Find("MSIE") && !client_browser->Find("mac") && !client_browser->Find("Opera")); + #result = client_browser->Substring(client_browser->Find("MSIE")+5,3)>=5.5; + /if; + if (client_browser->Find("Gecko/")); + #result = client_browser->Substring(client_browser->Find("Gecko/")+6,8)>=20030210; + /if; + if (client_browser->Find("Opera/")); + #result = client_browser->Substring(client_browser->Find("Opera/")+6,4)>=9.5; + /if; + if (client_browser->Find("AppleWebKit/")); + #result = client_browser->Substring(client_browser->Find("AppleWebKit/")+12,3)>=522; + /if; return(#result); /define_tag; Modified: pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.php =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.php 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.php 2008-05-15 06:08:06 UTC (rev 930) @@ -1,7 +1,7 @@ = 5.5) ; + } + else if ( strpos($sAgent, 'Gecko/') !== false ) + { + $iVersion = (int)substr($sAgent, strpos($sAgent, 'Gecko/') + 6, 8) ; + return ($iVersion >= 20030210) ; + } + else if ( strpos($sAgent, 'Opera/') !== false ) + { + $fVersion = (float)substr($sAgent, strpos($sAgent, 'Opera/') + 6, 4) ; + return ($fVersion >= 9.5) ; + } + else if ( preg_match( "|AppleWebKit/(\d+)|i", $sAgent, $matches ) ) + { + $iVersion = $matches[1] ; + return ( $matches[1] >= 522 ) ; + } + else + return false ; +} + +if ( !function_exists('version_compare') || version_compare( phpversion(), '5', '<' ) ) include_once( 'fckeditor_php4.php' ) ; else include_once( 'fckeditor_php5.php' ) ; - -?> \ No newline at end of file Modified: pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.pl =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.pl 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.pl 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ ##### # FCKeditor - The text editor for Internet - http://www.fckeditor.net -# Copyright (C) 2003-2007 Frederico Caldeira Knabben +# Copyright (C) 2003-2008 Frederico Caldeira Knabben # # == BEGIN LICENSE == # @@ -63,7 +63,7 @@ { $HtmlValue = &specialchar_cnv($Value); - $Html = '
      ' ; + $Html = '' ; if(&IsCompatible()) { $Link = $BasePath . "editor/fckeditor.html?InstanceName=$InstanceName"; if($ToolbarSet ne '') { @@ -93,7 +93,6 @@ } $Html .= ""; } - $Html .= '
      '; return($Html); } @@ -107,6 +106,11 @@ } elsif($sAgent =~ /Gecko\//i) { $iVersion = substr($sAgent,index($sAgent,'Gecko/') + 6,8); return($iVersion >= 20030210) ; + } elsif($sAgent =~ /Opera\//i) { + $iVersion = substr($sAgent,index($sAgent,'Opera/') + 6,4); + return($iVersion >= 9.5) ; + } elsif($sAgent =~ /AppleWebKit\/(\d+)/i) { + return($1 >= 522) ; } else { return(0); # 2.0 PR fix } Modified: pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.py =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.py 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor.py 2008-05-15 06:08:06 UTC (rev 930) @@ -1,6 +1,6 @@ """ FCKeditor - The text editor for Internet - http://www.fckeditor.net -Copyright (C) 2003-2007 Frederico Caldeira Knabben +Copyright (C) 2003-2008 Frederico Caldeira Knabben == BEGIN LICENSE == @@ -23,6 +23,7 @@ import cgi import os +import re import string def escape(text, replace=string.replace): @@ -56,7 +57,7 @@ def CreateHtml(self): HtmlValue = escape(self.Value) - Html = "
      " + Html = "" if (self.IsCompatible()): File = "fckeditor.html" @@ -104,7 +105,6 @@ HeightCSS, HtmlValue ) - Html += "
      " return Html def IsCompatible(self): @@ -124,6 +124,18 @@ if (iVersion >= 20030210): return True return False + elif (sAgent.find("Opera/") >= 0): + i = sAgent.find("Opera/") + iVersion = float(sAgent[i+6:i+6+4]) + if (iVersion >= 9.5): + return True + return False + elif (sAgent.find("AppleWebKit/") >= 0): + p = re.compile('AppleWebKit\/(\d+)', re.IGNORECASE) + m = p.search(sAgent) + if (m.group(1) >= 522): + return True + return False else: return False @@ -146,4 +158,3 @@ else: sParams += "%s=%s" % (k, v) return sParams - Modified: pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor_php4.php =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor_php4.php 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor_php4.php 2008-05-15 06:08:06 UTC (rev 930) @@ -1,7 +1,7 @@ Config['EnterMode'] = 'br'; + * + * @var array + */ var $Config ; - // PHP 4 Contructor + /** + * Main Constructor. + * Refer to the _samples/php directory for examples. + * + * @param string $instanceName + */ function FCKeditor( $instanceName ) { $this->InstanceName = $instanceName ; @@ -48,17 +93,31 @@ $this->Config = array() ; } + /** + * Display FCKeditor. + * + */ function Create() { echo $this->CreateHtml() ; } + /** + * Return the HTML code required to run FCKeditor. + * + * @return string + */ function CreateHtml() { $HtmlValue = htmlspecialchars( $this->Value ) ; - $Html = '
      ' ; + $Html = '' ; + if ( !isset( $_GET ) ) { + global $HTTP_GET_VARS ; + $_GET = $HTTP_GET_VARS ; + } + if ( $this->IsCompatible() ) { if ( isset( $_GET['fcksource'] ) && $_GET['fcksource'] == "true" ) @@ -95,34 +154,25 @@ $Html .= "" ; } - $Html .= '
      ' ; - return $Html ; } + /** + * Returns true if browser is compatible with FCKeditor. + * + * @return boolean + */ function IsCompatible() { - global $HTTP_USER_AGENT ; - - if ( isset( $HTTP_USER_AGENT ) ) - $sAgent = $HTTP_USER_AGENT ; - else - $sAgent = $_SERVER['HTTP_USER_AGENT'] ; - - if ( strpos($sAgent, 'MSIE') !== false && strpos($sAgent, 'mac') === false && strpos($sAgent, 'Opera') === false ) - { - $iVersion = (float)substr($sAgent, strpos($sAgent, 'MSIE') + 5, 3) ; - return ($iVersion >= 5.5) ; - } - else if ( strpos($sAgent, 'Gecko/') !== false ) - { - $iVersion = (int)substr($sAgent, strpos($sAgent, 'Gecko/') + 6, 8) ; - return ($iVersion >= 20030210) ; - } - else - return false ; + return FCKeditor_IsCompatibleBrowser() ; } + /** + * Get settings from Config array as a single string. + * + * @access protected + * @return string + */ function GetConfigFieldString() { $sParams = '' ; @@ -146,6 +196,14 @@ return $sParams ; } + /** + * Encode characters that may break the configuration string + * generated by GetConfigFieldString(). + * + * @access protected + * @param string $valueToEncode + * @return string + */ function EncodeConfig( $valueToEncode ) { $chars = array( @@ -156,5 +214,3 @@ return strtr( $valueToEncode, $chars ) ; } } - -?> \ No newline at end of file Modified: pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor_php5.php =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor_php5.php 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/fckeditor_php5.php 2008-05-15 06:08:06 UTC (rev 930) @@ -1,7 +1,7 @@ Config['EnterMode'] = 'br'; + * + * @var array + */ + public $Config ; - // PHP 5 Constructor (by Marcus Bointon ) - function __construct( $instanceName ) + /** + * Main Constructor. + * Refer to the _samples/php directory for examples. + * + * @param string $instanceName + */ + public function __construct( $instanceName ) { $this->InstanceName = $instanceName ; $this->BasePath = '/fckeditor/' ; @@ -48,16 +93,25 @@ $this->Config = array() ; } - function Create() + /** + * Display FCKeditor. + * + */ + public function Create() { echo $this->CreateHtml() ; } - function CreateHtml() + /** + * Return the HTML code required to run FCKeditor. + * + * @return string + */ + public function CreateHtml() { $HtmlValue = htmlspecialchars( $this->Value ) ; - $Html = '
      ' ; + $Html = '' ; if ( $this->IsCompatible() ) { @@ -95,35 +149,26 @@ $Html .= "" ; } - $Html .= '
      ' ; - return $Html ; } - function IsCompatible() + /** + * Returns true if browser is compatible with FCKeditor. + * + * @return boolean + */ + public function IsCompatible() { - global $HTTP_USER_AGENT ; - - if ( isset( $HTTP_USER_AGENT ) ) - $sAgent = $HTTP_USER_AGENT ; - else - $sAgent = $_SERVER['HTTP_USER_AGENT'] ; - - if ( strpos($sAgent, 'MSIE') !== false && strpos($sAgent, 'mac') === false && strpos($sAgent, 'Opera') === false ) - { - $iVersion = (float)substr($sAgent, strpos($sAgent, 'MSIE') + 5, 3) ; - return ($iVersion >= 5.5) ; - } - else if ( strpos($sAgent, 'Gecko/') !== false ) - { - $iVersion = (int)substr($sAgent, strpos($sAgent, 'Gecko/') + 6, 8) ; - return ($iVersion >= 20030210) ; - } - else - return false ; + return FCKeditor_IsCompatibleBrowser() ; } - function GetConfigFieldString() + /** + * Get settings from Config array as a single string. + * + * @access protected + * @return string + */ + public function GetConfigFieldString() { $sParams = '' ; $bFirst = true ; @@ -146,7 +191,15 @@ return $sParams ; } - function EncodeConfig( $valueToEncode ) + /** + * Encode characters that may break the configuration string + * generated by GetConfigFieldString(). + * + * @access protected + * @param string $valueToEncode + * @return string + */ + public function EncodeConfig( $valueToEncode ) { $chars = array( '&' => '%26', @@ -156,5 +209,3 @@ return strtr( $valueToEncode, $chars ) ; } } - -?> \ No newline at end of file Modified: pal-wcm/trunk/src/main/webapp/fckeditor/fckpackager.xml =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/fckpackager.xml 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/fckpackager.xml 2008-05-15 06:08:06 UTC (rev 930) @@ -1,7 +1,7 @@ + + + + + + + + + + + + + + + + + + + - - - - - \ No newline at end of file + Modified: pal-wcm/trunk/src/main/webapp/fckeditor/fcktemplates.xml =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/fcktemplates.xml 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/fcktemplates.xml 2008-05-15 06:08:06 UTC (rev 930) @@ -1,7 +1,7 @@ + +function FCKeditor_IsCompatibleBrowser() +{ + sAgent = lCase( cgi.HTTP_USER_AGENT ); + isCompatibleBrowser = false; + + // check for Internet Explorer ( >= 5.5 ) + if( find( "msie", sAgent ) and not find( "mac", sAgent ) and not find( "opera", sAgent ) ) + { + // try to extract IE version + stResult = reFind( "msie ([5-9]\.[0-9])", sAgent, 1, true ); + if( arrayLen( stResult.pos ) eq 2 ) + { + // get IE Version + sBrowserVersion = mid( sAgent, stResult.pos[2], stResult.len[2] ); + if( sBrowserVersion GTE 5.5 ) + isCompatibleBrowser = true; + } + } + // check for Gecko ( >= 20030210+ ) + else if( find( "gecko/", sAgent ) ) + { + // try to extract Gecko version date + stResult = reFind( "gecko/(200[3-9][0-1][0-9][0-3][0-9])", sAgent, 1, true ); + if( arrayLen( stResult.pos ) eq 2 ) + { + // get Gecko build (i18n date) + sBrowserVersion = mid( sAgent, stResult.pos[2], stResult.len[2] ); + if( sBrowserVersion GTE 20030210 ) + isCompatibleBrowser = true; + } + } + else if( find( "opera/", sAgent ) ) + { + // try to extract Opera version + stResult = reFind( "opera/([0-9]+\.[0-9]+)", sAgent, 1, true ); + if( arrayLen( stResult.pos ) eq 2 ) + { + if ( mid( sAgent, stResult.pos[2], stResult.len[2] ) gte 9.5) + isCompatibleBrowser = true; + } + } + else if( find( "applewebkit", sAgent ) ) + { + // try to extract Gecko version date + stResult = reFind( "applewebkit/([0-9]+)", sAgent, 1, true ); + if( arrayLen( stResult.pos ) eq 2 ) + { + if( mid( sAgent, stResult.pos[2], stResult.len[2] ) gte 522 ) + isCompatibleBrowser = true; + } + } + return isCompatibleBrowser; +} + Modified: pal-wcm/trunk/src/main/webapp/fckeditor/license.txt =================================================================== --- pal-wcm/trunk/src/main/webapp/fckeditor/license.txt 2008-05-15 05:34:30 UTC (rev 929) +++ pal-wcm/trunk/src/main/webapp/fckeditor/license.txt 2008-05-15 06:08:06 UTC (rev 930) @@ -1,5 +1,5 @@ FCKeditor - The text editor for Internet - http://www.fckeditor.net -Copyright (C) 2003-2007 Frederico Caldeira Knabben +Copyright (C) 2003-2008 Frederico Caldeira Knabben Licensed under the terms of any of the following licenses at your choice: @@ -1244,4 +1244,3 @@ the notices in the Source Code files of the Original Code. You should use the text of this Exhibit A rather than the text found in the Original Code Source Code for Your Modifications.] - Added: pal-wcm/trunk/src/main/webapp/index.jsp =================================================================== --- pal-wcm/trunk/src/main/webapp/index.jsp (rev 0) +++ pal-wcm/trunk/src/main/webapp/index.jsp 2008-05-15 06:08:06 UTC (rev 930) @@ -0,0 +1,69 @@ +<%@ page language="java" import="jp.sf.pal.wcm.*, java.util.*, java.io.File, java.io.FileReader, java.io.BufferedReader, javax.servlet.ServletContext" %> + + + + + PAL-WCM + + + + + +
      +<% +ServletContext servletContext = getServletContext(); +String contents = ""; +String fragID = "test123"; +String outputFileName = "/content_jp.html"; +String outputFilePath = servletContext.getRealPath("/WEB-INF/data/" + fragID + outputFileName); +File contentsFile = new File(outputFilePath); +try{ + if(contentsFile.exists()){ + String line = ""; + FileReader fr = new FileReader(outputFilePath); + BufferedReader reader = new BufferedReader(fr); + while ((line = reader.readLine()) != null){ + contents += line; + } + fr.close(); + } +} catch (Exception e){ + e.printStackTrace(); +} +FCKeditor oFCKeditor ; +oFCKeditor = new FCKeditor( request, "EditorDefault" ) ; +oFCKeditor.setBasePath( "/FCKeditor/" ) ; +oFCKeditor.setValue( contents ); +out.println( oFCKeditor.create() ) ; +%> +
      + + +
      + + From svnnotify ¡÷ sourceforge.jp Thu May 15 15:25:40 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 15:25:40 +0900 Subject: [pal-cvs 3194] [931] passed an exception to log. Message-ID: <1210832740.073639.24313.nullmailer@users.sourceforge.jp> Revision: 931 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=931 Author: shinsuke Date: 2008-05-15 15:25:39 +0900 (Thu, 15 May 2008) Log Message: ----------- passed an exception to log. Modified Paths: -------------- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/JetspeedRequestContextComponent.java -------------- next part -------------- Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/JetspeedRequestContextComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/JetspeedRequestContextComponent.java 2008-05-15 06:08:06 UTC (rev 930) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/JetspeedRequestContextComponent.java 2008-05-15 06:25:39 UTC (rev 931) @@ -32,45 +32,52 @@ /** * JetspeedRequestContextComponent - * + * * @author
      David Sean Taylor - * @version $Id: JetspeedRequestContextComponent.java 619702 2008-02-08 00:21:55Z taylor $ + * @version $Id: JetspeedRequestContextComponent.java 619702 2008-02-08 + * 00:21:55Z taylor $ */ public class JetspeedRequestContextComponent implements RequestContextComponent { + private String contextClassName = null; + private Class contextClass = null; + /** The user info manager. */ private UserInfoManager userInfoMgr; + private ThreadLocal tlRequestContext = new ThreadLocal(); + private Map requestContextObjects; - - private final static Log log = LogFactory.getLog(JetspeedRequestContextComponent.class); + private final static Log log = LogFactory + .getLog(JetspeedRequestContextComponent.class); + public JetspeedRequestContextComponent(String contextClassName) { this.contextClassName = contextClassName; this.requestContextObjects = new HashMap(); } - public JetspeedRequestContextComponent(String contextClassName, - UserInfoManager userInfoMgr) + public JetspeedRequestContextComponent(String contextClassName, + UserInfoManager userInfoMgr) { this.contextClassName = contextClassName; this.userInfoMgr = userInfoMgr; - this.requestContextObjects = new HashMap(); + this.requestContextObjects = new HashMap(); } - public JetspeedRequestContextComponent(String contextClassName, - UserInfoManager userInfoMgr, - Map requestContextObjects) + public JetspeedRequestContextComponent(String contextClassName, + UserInfoManager userInfoMgr, Map requestContextObjects) { this.contextClassName = contextClassName; this.userInfoMgr = userInfoMgr; - this.requestContextObjects = requestContextObjects; + this.requestContextObjects = requestContextObjects; } - - public RequestContext create(HttpServletRequest req, HttpServletResponse resp, ServletConfig config) + + public RequestContext create(HttpServletRequest req, + HttpServletResponse resp, ServletConfig config) { RequestContext context = null; @@ -81,23 +88,20 @@ contextClass = Class.forName(contextClassName); } - Constructor constructor = - contextClass.getConstructor( - new Class[] { - HttpServletRequest.class, - HttpServletResponse.class, - ServletConfig.class, - UserInfoManager.class, - Map.class}); - context = (RequestContext) constructor.newInstance(new Object[] { req, resp, config, userInfoMgr, requestContextObjects}); - + Constructor constructor = contextClass.getConstructor(new Class[] + { HttpServletRequest.class, HttpServletResponse.class, + ServletConfig.class, UserInfoManager.class, Map.class}); + context = (RequestContext) constructor.newInstance(new Object[] + { req, resp, config, userInfoMgr, requestContextObjects}); + } catch (Exception e) { - String msg = "JetspeedRequestContextComponent: Failed to create a Class object for RequestContext: " + e.toString(); - log.error(msg); + String msg = "JetspeedRequestContextComponent: Failed to create a Class object for RequestContext: " + + e.toString(); + log.error(msg, e); } - tlRequestContext.set(context); + tlRequestContext.set(context); return context; } @@ -107,37 +111,41 @@ } /** - * The servlet request can always get you back to the Request Context if you need it - * This static accessor provides this capability - * + * The servlet request can always get you back to the Request Context if you + * need it. This static accessor provides this capability + * * @param request * @return RequestContext */ public RequestContext getRequestContext(HttpServletRequest request) { - RequestContext rc = (RequestContext) request.getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); - if(rc != null) + RequestContext rc = (RequestContext) request + .getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); + if (rc != null) { return rc; } else { - log.error("Cannot call getRequestContext(HttpServletRequest request) before it has been created and set for this thread."); - throw new IllegalStateException("Cannot call getRequestContext(HttpServletRequest request) before it has been created and set for this thread."); + log + .error("Cannot call getRequestContext(HttpServletRequest request) before it has been created and set for this thread."); + throw new IllegalStateException( + "Cannot call getRequestContext(HttpServletRequest request) before it has been created and set for this thread."); } } - + public RequestContext getRequestContext() { RequestContext rc = null; if (CurrentWorkerContext.getParallelRenderingMode()) { - rc = (RequestContext) CurrentWorkerContext.getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); + rc = (RequestContext) CurrentWorkerContext + .getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); } else { - rc = (RequestContext) tlRequestContext.get(); + rc = (RequestContext) tlRequestContext.get(); } return rc; } From svnnotify ¡÷ sourceforge.jp Thu May 15 15:31:50 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 15:31:50 +0900 Subject: [pal-cvs 3195] [932] added eclipse setting. Message-ID: <1210833110.781814.28727.nullmailer@users.sourceforge.jp> Revision: 932 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=932 Author: shinsuke Date: 2008-05-15 15:31:50 +0900 (Thu, 15 May 2008) Log Message: ----------- added eclipse setting. Added Paths: ----------- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.core.prefs pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.ui.prefs -------------- next part -------------- Added: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.core.prefs =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.core.prefs (rev 0) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.core.prefs 2008-05-15 06:31:50 UTC (rev 932) @@ -0,0 +1,266 @@ +#Thu May 15 15:29:00 JST 2008 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.4 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.source=1.4 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.blank_lines_before_field=1 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=1 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 +org.eclipse.jdt.core.formatter.blank_lines_before_method=1 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=next_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=next_line +org.eclipse.jdt.core.formatter.brace_position_for_block=next_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=next_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=next_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=next_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=next_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false +org.eclipse.jdt.core.formatter.comment.format_block_comments=true +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true +org.eclipse.jdt.core.formatter.comment.format_line_comments=true +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert +org.eclipse.jdt.core.formatter.comment.line_length=80 +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=false +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=true +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.formatter.lineSplit=80 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true +org.eclipse.jdt.core.formatter.tabulation.char=space +org.eclipse.jdt.core.formatter.tabulation.size=4 +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true Added: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.ui.prefs =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.ui.prefs (rev 0) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.ui.prefs 2008-05-15 06:31:50 UTC (rev 932) @@ -0,0 +1,4 @@ +#Thu May 15 15:09:12 JST 2008 +eclipse.preferences.version=1 +formatter_profile=_Jetspeed +formatter_settings_version=11 From svnnotify ¡÷ sourceforge.jp Thu May 15 15:36:40 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 15:36:40 +0900 Subject: [pal-cvs 3196] [933] added memo. Message-ID: <1210833400.102146.32298.nullmailer@users.sourceforge.jp> Revision: 933 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=933 Author: shinsuke Date: 2008-05-15 15:36:40 +0900 (Thu, 15 May 2008) Log Message: ----------- added memo. Added Paths: ----------- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/sync.txt -------------- next part -------------- Added: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/sync.txt =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/sync.txt (rev 0) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/sync.txt 2008-05-15 06:36:40 UTC (rev 933) @@ -0,0 +1 @@ +This source code is synced up with 648465. Property changes on: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/sync.txt ___________________________________________________________________ Name: svn:eol-style + native From svnnotify ¡÷ sourceforge.jp Thu May 15 15:50:25 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 15:50:25 +0900 Subject: [pal-cvs 3197] [934] modified psml path. Message-ID: <1210834225.450122.10635.nullmailer@users.sourceforge.jp> Revision: 934 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=934 Author: shinsuke Date: 2008-05-15 15:50:25 +0900 (Thu, 15 May 2008) Log Message: ----------- modified psml path. Modified Paths: -------------- pal-portal/branches/pal-portal-1.x/build.properties -------------- next part -------------- Modified: pal-portal/branches/pal-portal-1.x/build.properties =================================================================== --- pal-portal/branches/pal-portal-1.x/build.properties 2008-05-15 06:36:40 UTC (rev 933) +++ pal-portal/branches/pal-portal-1.x/build.properties 2008-05-15 06:50:25 UTC (rev 934) @@ -18,8 +18,8 @@ portal.site.password=site portal.dir=${portal.home}/jetspeed-2 portal.resource.dir=${portal.home}/resources -portal.psml.dir=${portal.resource.dir}/psml -portal.psml.name=default +portal.psml.dir=${portal.dir}/src/webapp/WEB-INF/ +portal.psml.name=pages installer.dir=${basedir}/installer installer.resources.dir=${installer.dir}/resources From svnnotify ¡÷ sourceforge.jp Thu May 15 22:48:57 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 22:48:57 +0900 Subject: [pal-cvs 3198] [935] backport of 644679. Message-ID: <1210859337.883888.7509.nullmailer@users.sourceforge.jp> Revision: 935 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=935 Author: shinsuke Date: 2008-05-15 22:48:57 +0900 (Thu, 15 May 2008) Log Message: ----------- backport of 644679. Modified Paths: -------------- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/webapp/WEB-INF/web.xml Removed Paths: ------------- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/webapp/WEB-INF/portlet.tld -------------- next part -------------- Deleted: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/webapp/WEB-INF/portlet.tld =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/webapp/WEB-INF/portlet.tld 2008-05-15 06:50:25 UTC (rev 934) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/webapp/WEB-INF/portlet.tld 2008-05-15 13:48:57 UTC (rev 935) @@ -1,103 +0,0 @@ - - - - - 1.0 - 1.1 - Tags for portlets - - defineObjects - org.apache.pluto.tags.DefineObjectsTag - org.apache.pluto.tags.DefineObjectsTag$TEI - empty - - - param - org.apache.pluto.tags.ParamTag - empty - - name - true - true - - - value - true - true - - - - actionURL - org.apache.pluto.tags.ActionURLTag - org.apache.pluto.tags.BasicURLTag$TEI - JSP - - windowState - false - true - - - portletMode - false - true - - - secure - false - true - - - var - false - true - - - - renderURL - org.apache.pluto.tags.RenderURLTag - org.apache.pluto.tags.BasicURLTag$TEI - JSP - - windowState - false - true - - - portletMode - false - true - - - secure - false - true - - - var - false - true - - - - namespace - org.apache.pluto.tags.NamespaceTag - empty - - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/webapp/WEB-INF/web.xml =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/webapp/WEB-INF/web.xml 2008-05-15 06:50:25 UTC (rev 934) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/webapp/WEB-INF/web.xml 2008-05-15 13:48:57 UTC (rev 935) @@ -15,34 +15,8 @@ See the License for the specific language governing permissions and limitations under the License. --> - + - Jetspeed 2 Core Portlets - Jetspeed 2 Core Portlets - - - JetspeedContainer - Jetspeed Container - MVC Servlet for Jetspeed Portlet Applications - org.apache.jetspeed.container.JetspeedContainerServlet - - contextName - jetspeed-layouts - - - - - - JetspeedContainer - - /container/* - - - - - portlet.tld - /WEB-INF/portlet.tld - - + Jetspeed 2 Layout Portlets Application + Jetspeed 2 Layout Portlets Applications From svnnotify ¡÷ sourceforge.jp Thu May 15 22:51:07 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 22:51:07 +0900 Subject: [pal-cvs 3199] [936] backport of 643129. Message-ID: <1210859467.412287.9004.nullmailer@users.sourceforge.jp> Revision: 936 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=936 Author: shinsuke Date: 2008-05-15 22:51:07 +0900 (Thu, 15 May 2008) Log Message: ----------- backport of 643129. Modified Paths: -------------- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/DatabasePageManagerCache.java -------------- next part -------------- Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/DatabasePageManagerCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/DatabasePageManagerCache.java 2008-05-15 13:48:57 UTC (rev 935) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/DatabasePageManagerCache.java 2008-05-15 13:51:07 UTC (rev 936) @@ -37,43 +37,53 @@ */ public class DatabasePageManagerCache implements ObjectCache { + private static HashMap cacheByOID; + private static LinkedList cacheLRUList; + private static HashMap cacheByPath; + private static int cacheSize; + private static int cacheExpiresSeconds; + private static boolean constraintsEnabled; + private static boolean permissionsEnabled; + private static PageManager pageManager; /** * cacheInit - * + * * Initialize cache using page manager configuration. - * - * @param pageManager configured page manager + * + * @param pageManager + * configured page manager */ public synchronized static void cacheInit(DatabasePageManager dbPageManager) { - if (pageManager == null) + if (pageManager != null) { - cacheByOID = new HashMap(); - cacheLRUList = new LinkedList(); - cacheByPath = new HashMap(); - cacheSize = dbPageManager.getCacheSize(); - cacheExpiresSeconds = dbPageManager.getCacheExpiresSeconds(); - constraintsEnabled = dbPageManager.getConstraintsEnabled(); - permissionsEnabled = dbPageManager.getPermissionsEnabled(); - pageManager = dbPageManager; + cacheClear(); } + cacheByOID = new HashMap(); + cacheLRUList = new LinkedList(); + cacheByPath = new HashMap(); + cacheSize = dbPageManager.getCacheSize(); + cacheExpiresSeconds = dbPageManager.getCacheExpiresSeconds(); + constraintsEnabled = dbPageManager.getConstraintsEnabled(); + permissionsEnabled = dbPageManager.getPermissionsEnabled(); + pageManager = dbPageManager; } /** * setPageManagerProxy - * - * @param proxy proxied page manager interface used to - * inject into Folder instances to provide - * transaction/interception + * + * @param proxy + * proxied page manager interface used to inject into Folder + * instances to provide transaction/interception */ public synchronized static void setPageManagerProxy(PageManager proxy) { @@ -88,10 +98,11 @@ /** * cacheLookup - * + * * Lookup node instances by unique path. - * - * @param path node unique path + * + * @param path + * node unique path * @return cached node */ public synchronized static NodeImpl cacheLookup(String path) @@ -99,23 +110,25 @@ if (path != null) { // return valid object cached by path - return (NodeImpl)cacheValidateEntry((Entry)cacheByPath.get(path)); + return (NodeImpl) cacheValidateEntry((Entry) cacheByPath.get(path)); } return null; } /** * cacheAdd - * - * Add object to cache and cache node instances by unique path; - * infuse nodes loaded by OJB with page manager configuration. - * - * @param oid object/node indentity - * @param obj object/node to cache + * + * Add object to cache and cache node instances by unique path; infuse nodes + * loaded by OJB with page manager configuration. + * + * @param oid + * object/node indentity + * @param obj + * object/node to cache */ public synchronized static void cacheAdd(Identity oid, Object obj) { - Entry entry = (Entry)cacheByOID.get(oid); + Entry entry = (Entry) cacheByOID.get(oid); if (entry != null) { // update cache LRU order @@ -132,29 +145,29 @@ cacheLRUList.addFirst(entry); // infuse node with page manager configuration // or the page manager itself and add to the - // paths cache + // paths cache if (obj instanceof NodeImpl) { - NodeImpl node = (NodeImpl)obj; + NodeImpl node = (NodeImpl) obj; node.setConstraintsEnabled(constraintsEnabled); node.setPermissionsEnabled(permissionsEnabled); cacheByPath.put(node.getPath(), entry); if (obj instanceof FolderImpl) { - ((FolderImpl)obj).setPageManager(pageManager); + ((FolderImpl) obj).setPageManager(pageManager); } } // trim cache as required to maintain cache size while (cacheLRUList.size() > cacheSize) { - cacheRemoveEntry((Entry)cacheLRUList.getLast(), true); + cacheRemoveEntry((Entry) cacheLRUList.getLast(), true); } } } /** * cacheClear - * + * * Clear object and node caches. */ public synchronized static void cacheClear() @@ -163,7 +176,7 @@ Iterator removeIter = cacheLRUList.iterator(); while (removeIter.hasNext()) { - cacheRemoveEntry((Entry)removeIter.next(), false); + cacheRemoveEntry((Entry) removeIter.next(), false); } // clear cache cacheByOID.clear(); @@ -173,10 +186,11 @@ /** * cacheLookup - * + * * Lookup objects by identity. - * - * @param oid object identity + * + * @param oid + * object identity * @return cached object */ public synchronized static Object cacheLookup(Identity oid) @@ -184,44 +198,46 @@ if (oid != null) { // return valid object cached by oid - return cacheValidateEntry((Entry)cacheByOID.get(oid)); + return cacheValidateEntry((Entry) cacheByOID.get(oid)); } return null; } /** * cacheRemove - * + * * Remove identified object from object and node caches. - * - * @param oid object identity + * + * @param oid + * object identity */ public synchronized static void cacheRemove(Identity oid) { // remove from cache by oid - cacheRemoveEntry((Entry)cacheByOID.get(oid), true); + cacheRemoveEntry((Entry) cacheByOID.get(oid), true); } /** * cacheRemove - * + * * Remove identified object from object and node caches. - * - * @param path object path + * + * @param path + * object path */ public synchronized static void cacheRemove(String path) { // remove from cache by path - cacheRemoveEntry((Entry)cacheByPath.get(path), true); + cacheRemoveEntry((Entry) cacheByPath.get(path), true); } - + /** * cacheValidateEntry - * - * Validate specified entry from cache, returning cached - * object if valid. - * - * @param entry cache entry to validate + * + * Validate specified entry from cache, returning cached object if valid. + * + * @param entry + * cache entry to validate * @return validated object from cache */ private synchronized static Object cacheValidateEntry(Entry entry) @@ -245,16 +261,19 @@ } return null; } - + /** * cacheRemoveEntry - * + * * Remove specified entry from cache. - * - * @param entry cache entry to remove - * @param remove enable removal from cache + * + * @param entry + * cache entry to remove + * @param remove + * enable removal from cache */ - private synchronized static void cacheRemoveEntry(Entry entry, boolean remove) + private synchronized static void cacheRemoveEntry(Entry entry, + boolean remove) { if (entry != null) { @@ -279,20 +298,20 @@ cacheByOID.remove(entry.getOID()); if (removeObj instanceof NodeImpl) { - cacheByPath.remove(((NodeImpl)removeObj).getPath()); + cacheByPath.remove(((NodeImpl) removeObj).getPath()); } } // reset internal FolderImpl caches if (removeObj instanceof FolderImpl) { - ((FolderImpl)removeObj).resetAll(false); + ((FolderImpl) removeObj).resetAll(false); } } } /** * resetCachedSecurityConstraints - * + * * Reset cached security constraints in all cached node objects. */ public synchronized static void resetCachedSecurityConstraints() @@ -301,23 +320,26 @@ Iterator resetIter = cacheLRUList.iterator(); while (resetIter.hasNext()) { - Object obj = ((Entry)resetIter.next()).getObject(); + Object obj = ((Entry) resetIter.next()).getObject(); if (obj instanceof NodeImpl) { - ((NodeImpl)obj).resetCachedSecurityConstraints(); + ((NodeImpl) obj).resetCachedSecurityConstraints(); } } } /** * Entry - * + * * Cache entry class adding entry timestamp to track expiration */ private static class Entry { + public long timestamp; + public Object object; + public Identity oid; public Entry(Object object, Identity oid) @@ -341,7 +363,7 @@ } return false; } - + public void touch() { if (DatabasePageManagerCache.cacheExpiresSeconds > 0) @@ -363,25 +385,32 @@ /** * DatabasePageManagerCache - * + * * Construct a cache instance using OJB compliant signatures. - * - * @param broker broker that is to own cache - * @param props attribute properties passed to cache + * + * @param broker + * broker that is to own cache + * @param props + * attribute properties passed to cache */ public DatabasePageManagerCache(PersistenceBroker broker, Properties props) { } - /* (non-Javadoc) - * @see org.apache.ojb.broker.cache.ObjectCache#cache(org.apache.ojb.broker.Identity, java.lang.Object) + /* + * (non-Javadoc) + * + * @see org.apache.ojb.broker.cache.ObjectCache#cache(org.apache.ojb.broker.Identity, + * java.lang.Object) */ public void cache(Identity oid, Object obj) { cacheAdd(oid, obj); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.ojb.broker.cache.ObjectCache#clear() */ public void clear() @@ -389,7 +418,9 @@ cacheClear(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.ojb.broker.cache.ObjectCache#lookup(org.apache.ojb.broker.Identity) */ public Object lookup(Identity oid) @@ -397,7 +428,9 @@ return cacheLookup(oid); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.ojb.broker.cache.ObjectCache#remove(org.apache.ojb.broker.Identity) */ public void remove(Identity oid) @@ -407,15 +440,17 @@ public synchronized static void dump() { - System.out.println("--------------------------1"); + System.out.println("--------------------------1"); Iterator dumpIter = cacheLRUList.iterator(); while (dumpIter.hasNext()) { - Entry entry = (Entry)dumpIter.next(); + Entry entry = (Entry) dumpIter.next(); Object entryObject = entry.getObject(); if (entryObject instanceof NodeImpl) { - System.out.println("entry = " + ((NodeImpl)entryObject).getPath() + ", " + entry.getOID()); + System.out.println("entry = " + + ((NodeImpl) entryObject).getPath() + ", " + + entry.getOID()); } else { @@ -424,18 +459,18 @@ } System.out.println("--------------------------2"); } - + protected static ThreadLocal transactionedOperations = new ThreadLocal(); - + public static List getTransactions() { - List operations = (List)transactionedOperations.get(); + List operations = (List) transactionedOperations.get(); if (operations == null) { operations = new LinkedList(); transactionedOperations.set(operations); } - + return operations; } @@ -445,16 +480,17 @@ */ public static void addTransaction(TransactionedOperation operation) { - List transactions = getTransactions(); + List transactions = getTransactions(); transactions.add(operation); } - + public static void rollbackTransactions() { Iterator transactions = getTransactions().iterator(); while (transactions.hasNext()) { - TransactionedOperation operation = (TransactionedOperation)transactions.next(); + TransactionedOperation operation = (TransactionedOperation) transactions + .next(); cacheRemove(operation.getPath()); } } From svnnotify ¡÷ sourceforge.jp Thu May 15 22:53:50 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 22:53:50 +0900 Subject: [pal-cvs 3200] [937] backport of 643116. Message-ID: <1210859630.628873.10741.nullmailer@users.sourceforge.jp> Revision: 937 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=937 Author: shinsuke Date: 2008-05-15 22:53:50 +0900 (Thu, 15 May 2008) Log Message: ----------- backport of 643116. Modified Paths: -------------- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PersistenceBrokerPreferencesProvider.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesFactoryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/assembly/prefs.xml Added Paths: ----------- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/PreferencesRootWrapper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesProviderWrapper.java -------------- next part -------------- Added: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/PreferencesRootWrapper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/PreferencesRootWrapper.java (rev 0) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/PreferencesRootWrapper.java 2008-05-15 13:53:50 UTC (rev 937) @@ -0,0 +1,240 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jetspeed.util; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.Observable; +import java.util.Observer; +import java.util.prefs.BackingStoreException; +import java.util.prefs.NodeChangeListener; +import java.util.prefs.PreferenceChangeListener; +import java.util.prefs.Preferences; + +/** + * PreferencesRootWrapper is a lightweight wrapper around the Jetspeed + * persistent PreferencesImpl to allow restarting the Jetspeed Portal. + *

      + * As the (Sun) Java Preferences implementation only creates a + * PreferencesFactory instance *once* per JVM (as static final), reloading the + * Jetspeed Portal (using a new classloader) requires a wrapper solution to + * prevent ClassCastExceptions and/or out-of-sync kept proxies and caches. + *

      + *

      + * As a newly created Jetspeed Portal classloader can no longer cast a previous + * Preferences root to its own PreferencesImpl, a "trick" is used by also + * implementing the Observer interface (which is provided by the Java system + * classloader). The Observer interface is used because it is very lightweight + * and allows passing an Object instance through its update method. That update + * method is used to "inject" the newly created Preferences root instance. + *

      + * + * @author Ate Douma + * @version $Id$ + */ +public class PreferencesRootWrapper extends Preferences implements Observer +{ + + private Preferences root; + + public String absolutePath() + { + return root.absolutePath(); + } + + public void addNodeChangeListener(NodeChangeListener ncl) + { + root.addNodeChangeListener(ncl); + } + + public void addPreferenceChangeListener(PreferenceChangeListener pcl) + { + root.addPreferenceChangeListener(pcl); + } + + public String[] childrenNames() throws BackingStoreException + { + return root.childrenNames(); + } + + public void clear() throws BackingStoreException + { + root.clear(); + } + + public boolean equals(Object obj) + { + return root.equals(obj); + } + + public void exportNode(OutputStream os) throws IOException, + BackingStoreException + { + root.exportNode(os); + } + + public void exportSubtree(OutputStream os) throws IOException, + BackingStoreException + { + root.exportSubtree(os); + } + + public void flush() throws BackingStoreException + { + root.flush(); + } + + public String get(String key, String def) + { + return root.get(key, def); + } + + public boolean getBoolean(String key, boolean def) + { + return root.getBoolean(key, def); + } + + public byte[] getByteArray(String key, byte[] def) + { + return root.getByteArray(key, def); + } + + public double getDouble(String key, double def) + { + return root.getDouble(key, def); + } + + public float getFloat(String key, float def) + { + return root.getFloat(key, def); + } + + public int getInt(String key, int def) + { + return root.getInt(key, def); + } + + public long getLong(String key, long def) + { + return root.getLong(key, def); + } + + public int hashCode() + { + return root.hashCode(); + } + + public boolean isUserNode() + { + return root.isUserNode(); + } + + public String[] keys() throws BackingStoreException + { + return root.keys(); + } + + public String name() + { + return root.name(); + } + + public Preferences node(String pathName) + { + return root.node(pathName); + } + + public boolean nodeExists(String pathName) throws BackingStoreException + { + return root.nodeExists(pathName); + } + + public Preferences parent() + { + return root.parent(); + } + + public void put(String key, String value) + { + root.put(key, value); + } + + public void putBoolean(String key, boolean value) + { + root.putBoolean(key, value); + } + + public void putByteArray(String key, byte[] value) + { + root.putByteArray(key, value); + } + + public void putDouble(String key, double value) + { + root.putDouble(key, value); + } + + public void putFloat(String key, float value) + { + root.putFloat(key, value); + } + + public void putInt(String key, int value) + { + root.putInt(key, value); + } + + public void putLong(String key, long value) + { + root.putLong(key, value); + } + + public void remove(String key) + { + root.remove(key); + } + + public void removeNode() throws BackingStoreException + { + root.removeNode(); + } + + public void removeNodeChangeListener(NodeChangeListener ncl) + { + root.removeNodeChangeListener(ncl); + } + + public void removePreferenceChangeListener(PreferenceChangeListener pcl) + { + root.removePreferenceChangeListener(pcl); + } + + public void sync() throws BackingStoreException + { + root.sync(); + } + + public String toString() + { + return root.toString(); + } + + public void update(Observable o, Object arg) + { + root = (Preferences) arg; + } +} Property changes on: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/PreferencesRootWrapper.java ___________________________________________________________________ Name: svn:eol-style + native Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PersistenceBrokerPreferencesProvider.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PersistenceBrokerPreferencesProvider.java 2008-05-15 13:51:07 UTC (rev 936) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PersistenceBrokerPreferencesProvider.java 2008-05-15 13:53:50 UTC (rev 937) @@ -49,62 +49,71 @@ *

      * * @author Scott T. Weaver - * @version $Id: PersistenceBrokerPreferencesProvider.java 605797 2007-12-20 03:39:09Z woonsan $ + * @version $Id$ */ -public class PersistenceBrokerPreferencesProvider extends InitablePersistenceBrokerDaoSupport implements - PreferencesProvider +public class PersistenceBrokerPreferencesProvider extends + InitablePersistenceBrokerDaoSupport implements PreferencesProvider { - + private static class NodeCache implements DistributedCacheObject { + /** The serial uid. */ private static final long serialVersionUID = 1853381807991868844L; + NodeImplProxy node = null; + String key = null;; + Collection children = null;; public NodeCache(NodeImplProxy node) { - // System.out.println(this.getClass().getName() + "-" + "NodeCache (node)" + node.getFullPath()); + // System.out.println(this.getClass().getName() + "-" + "NodeCache + // (node)" + node.getFullPath()); this.node = node; this.key = node.getFullPath() + "-" + node.getNodeType(); } public NodeCache(String fullpath, int type) { - // System.out.println(this.getClass().getName() + "-" + "NodeCache - fullpath=" + fullpath); + // System.out.println(this.getClass().getName() + "-" + "NodeCache - + // fullpath=" + fullpath); this.key = fullpath + "-" + type; } public boolean isChildrenLoaded() { - // System.out.println(this.getClass().getName() + "-" + "isChildrenLoaded"); + // System.out.println(this.getClass().getName() + "-" + + // "isChildrenLoaded"); return children != null; } - - public NodeImplProxy getNode() { - // System.out.println(this.getClass().getName() + "-" + "getNode=" + node.getFullPath()); + // System.out.println(this.getClass().getName() + "-" + "getNode=" + + // node.getFullPath()); return node; } public void setNode(NodeImplProxy node) { - // System.out.println(this.getClass().getName() + "-" + "setFullpath=" + node.getFullPath()); + // System.out.println(this.getClass().getName() + "-" + + // "setFullpath=" + node.getFullPath()); this.node = node; } public Collection getChildren() { - // System.out.println(this.getClass().getName() + "-" + "getCHildren=" ); + // System.out.println(this.getClass().getName() + "-" + + // "getCHildren=" ); return children; } public void setChildren(Collection children) { - // System.out.println(this.getClass().getName() + "-" + "setChildren=" ); + // System.out.println(this.getClass().getName() + "-" + + // "setChildren=" ); this.children = children; } @@ -122,64 +131,63 @@ { return getKey().hashCode(); } - + public String getCacheKey() { return getKey(); } - public String getKey() - { - return key; - } + public String getKey() + { + return key; + } - - public void notifyChange(int action) - { + public void notifyChange(int action) + { - switch (action) - { - case CacheElement.ActionAdded: -// System.out.println("CacheObject Added =" + this.getKey()); - break; - case CacheElement.ActionChanged: -// System.out.println("CacheObject Changed =" + this.getKey()); - if (this.node != null) - this.node.invalidate(); - break; - case CacheElement.ActionRemoved: -// System.out.println("CacheObject Removed =" + this.getKey()); - if (this.node != null) - this.node.invalidate(); - break; - case CacheElement.ActionEvicted: -// System.out.println("CacheObject Evicted =" + this.getKey()); - if (this.node != null) - this.node.invalidate(); - break; - case CacheElement.ActionExpired: -// System.out.println("CacheObject Expired =" + this.getKey()); - if (this.node != null) - this.node.invalidate(); - break; - default: - System.out.println("CacheObject - UNKOWN OPRERATION =" + this.getKey()); - return; - } - return; - } + switch (action) + { + case CacheElement.ActionAdded: + // System.out.println("CacheObject Added =" + this.getKey()); + break; + case CacheElement.ActionChanged: + // System.out.println("CacheObject Changed =" + this.getKey()); + if (this.node != null) this.node.invalidate(); + break; + case CacheElement.ActionRemoved: + // System.out.println("CacheObject Removed =" + this.getKey()); + if (this.node != null) this.node.invalidate(); + break; + case CacheElement.ActionEvicted: + // System.out.println("CacheObject Evicted =" + this.getKey()); + if (this.node != null) this.node.invalidate(); + break; + case CacheElement.ActionExpired: + // System.out.println("CacheObject Expired =" + this.getKey()); + if (this.node != null) this.node.invalidate(); + break; + default: + System.out.println("CacheObject - UNKOWN OPRERATION =" + + this.getKey()); + return; + } + return; + } } private JetspeedCache preferenceCache; + private List preloadedApplications; + private boolean preloadEntities = false; - + /** * @param repositoryPath - * Location of repository mapping file. Must be available within the classpath. + * Location of repository mapping file. Must be available within + * the classpath. * @throws ClassNotFoundException - * if the prefsFactoryImpl argument does not reperesent a Class that exists in the - * current classPath. + * if the prefsFactoryImpl argument does not + * reperesent a Class that exists in the current classPath. */ public PersistenceBrokerPreferencesProvider(String repositoryPath) throws ClassNotFoundException @@ -189,120 +197,138 @@ this.preloadedApplications = new LinkedList(); } - /** * @param repository - * Location of repository mapping file. Must be available within the classpath. + * Location of repository mapping file. Must be available within + * the classpath. * @param prefsFactoryImpl - * java.util.prefs.PreferencesFactory implementation to use. + * java.util.prefs.PreferencesFactory + * implementation to use. * @param enablePropertyManager * Whether or not we chould be suing the property manager. * @throws ClassNotFoundException - * if the prefsFactoryImpl argument does not reperesent a Class that exists in the - * current classPath. + * if the prefsFactoryImpl argument does not + * reperesent a Class that exists in the current classPath. */ - public PersistenceBrokerPreferencesProvider(String repositoryPath, JetspeedCache preferenceCache) - throws ClassNotFoundException + public PersistenceBrokerPreferencesProvider(String repositoryPath, + JetspeedCache preferenceCache) throws ClassNotFoundException { this(repositoryPath); this.preferenceCache = preferenceCache; } - public PersistenceBrokerPreferencesProvider(String repositoryPath, JetspeedCache preferenceCache, List apps, boolean preloadEntities) - throws ClassNotFoundException + public PersistenceBrokerPreferencesProvider(String repositoryPath, + JetspeedCache preferenceCache, List apps, boolean preloadEntities) + throws ClassNotFoundException { this(repositoryPath); this.preferenceCache = preferenceCache; this.preloadedApplications = apps; this.preloadEntities = preloadEntities; } - + + public void destroy() + { + NodeImplProxy.setProvider(null); + preferenceCache = null; + preloadedApplications = null; + } + protected void addToCache(NodeCache content) { - CacheElement cachedElement = preferenceCache.createElement(content.getCacheKey(), content); - cachedElement.setTimeToIdleSeconds(preferenceCache.getTimeToIdleSeconds()); - cachedElement.setTimeToLiveSeconds(preferenceCache.getTimeToLiveSeconds()); - preferenceCache.put(cachedElement); - } - + CacheElement cachedElement = preferenceCache.createElement(content + .getCacheKey(), content); + cachedElement.setTimeToIdleSeconds(preferenceCache + .getTimeToIdleSeconds()); + cachedElement.setTimeToLiveSeconds(preferenceCache + .getTimeToLiveSeconds()); + preferenceCache.put(cachedElement); + } + private NodeCache getNode(String cacheKey) { - CacheElement cachedElement = preferenceCache.get(cacheKey); + CacheElement cachedElement = preferenceCache.get(cacheKey); if (cachedElement != null) - return (NodeCache)cachedElement.getContent(); + return (NodeCache) cachedElement.getContent(); return null; } - - public Node getNode(String fullPath, int nodeType) throws NodeDoesNotExistException + public Node getNode(String fullPath, int nodeType) + throws NodeDoesNotExistException { NodeCache key = new NodeCache(fullPath, nodeType); NodeCache hit = getNode(key.getCacheKey()); - if (hit != null) - { - return hit.getNode(); - } + if (hit != null) { return hit.getNode(); } Criteria c = new Criteria(); c.addEqualTo("fullPath", fullPath); c.addEqualTo("nodeType", new Integer(nodeType)); Query query = QueryFactory.newQuery(NodeImpl.class, c); - Node nodeObj = (Node) getPersistenceBrokerTemplate().getObjectByQuery(query); + Node nodeObj = (Node) getPersistenceBrokerTemplate().getObjectByQuery( + query); if (null != nodeObj) { - NodeImplProxy proxy = new NodeImplProxy(nodeObj); + NodeImplProxy proxy = new NodeImplProxy(nodeObj); addToCache(new NodeCache(proxy)); return proxy; - + } else { - throw new NodeDoesNotExistException("No node of type " + nodeType + "found at path: " + fullPath); + throw new NodeDoesNotExistException("No node of type " + nodeType + + "found at path: " + fullPath); } } + /** - * @see org.apache.jetspeed.prefs.PreferencesProvider#getNode(java.lang.String, int) + * @see org.apache.jetspeed.prefs.PreferencesProvider#getNode(java.lang.String, + * int) */ - public void redoNode(NodeImplProxy proxy, String fullPath, int nodeType) throws NodeDoesNotExistException + public void redoNode(NodeImplProxy proxy, String fullPath, int nodeType) + throws NodeDoesNotExistException { - + Criteria c = new Criteria(); c.addEqualTo("fullPath", fullPath); c.addEqualTo("nodeType", new Integer(nodeType)); Query query = QueryFactory.newQuery(NodeImpl.class, c); - Node nodeObj = (Node) getPersistenceBrokerTemplate().getObjectByQuery(query); + Node nodeObj = (Node) getPersistenceBrokerTemplate().getObjectByQuery( + query); if (null != nodeObj) { - proxy.setNode(nodeObj); - NodeCache cn = new NodeCache(nodeObj.getFullPath(), nodeObj.getNodeType()); - cn.setNode(proxy); + proxy.setNode(nodeObj); + NodeCache cn = new NodeCache(nodeObj.getFullPath(), nodeObj + .getNodeType()); + cn.setNode(proxy); addToCache(cn); } else { - throw new NodeDoesNotExistException("No node of type " + nodeType + "found at path: " + fullPath); + throw new NodeDoesNotExistException("No node of type " + nodeType + + "found at path: " + fullPath); } } /** - * @see org.apache.jetspeed.prefs.PreferencesProvider#nodeExists(java.lang.String, int) + * @see org.apache.jetspeed.prefs.PreferencesProvider#nodeExists(java.lang.String, + * int) */ public boolean nodeExists(String fullPath, int nodeType) { NodeCache key = new NodeCache(fullPath, nodeType); - if (preferenceCache.isKeyInCache(key)) - return true; + if (preferenceCache.isKeyInCache(key)) return true; Criteria c = new Criteria(); c.addEqualTo("fullPath", fullPath); c.addEqualTo("nodeType", new Integer(nodeType)); Query query = QueryFactory.newQuery(NodeImpl.class, c); - Node nodeObj = (Node) getPersistenceBrokerTemplate().getObjectByQuery(query); + Node nodeObj = (Node) getPersistenceBrokerTemplate().getObjectByQuery( + query); if (null != nodeObj) { - NodeImplProxy proxy = new NodeImplProxy(nodeObj); + NodeImplProxy proxy = new NodeImplProxy(nodeObj); addToCache(new NodeCache(proxy)); return true; } @@ -313,14 +339,17 @@ } /** - * @see org.apache.jetspeed.prefs.PreferencesProvider#createNode(org.apache.jetspeed.prefs.om.Node, java.lang.String, int, java.lang.String) + * @see org.apache.jetspeed.prefs.PreferencesProvider#createNode(org.apache.jetspeed.prefs.om.Node, + * java.lang.String, int, java.lang.String) */ - public Node createNode(Node parent, String nodeName, int nodeType, String fullPath) - throws FailedToCreateNodeException, NodeAlreadyExistsException + public Node createNode(Node parent, String nodeName, int nodeType, + String fullPath) throws FailedToCreateNodeException, + NodeAlreadyExistsException { if (nodeExists(fullPath, nodeType)) { - throw new NodeAlreadyExistsException("Node of type " + nodeType + " already exists at path " + fullPath); + throw new NodeAlreadyExistsException("Node of type " + nodeType + + " already exists at path " + fullPath); } else { @@ -330,68 +359,68 @@ parentNodeId = new Long(parent.getNodeId()); } - Node nodeObj = new NodeImpl(parentNodeId, nodeName, nodeType, fullPath); + Node nodeObj = new NodeImpl(parentNodeId, nodeName, nodeType, + fullPath); try { getPersistenceBrokerTemplate().store(nodeObj); - NodeImplProxy proxy = new NodeImplProxy(nodeObj); + NodeImplProxy proxy = new NodeImplProxy(nodeObj); addToCache(new NodeCache(proxy)); return proxy; } catch (Exception e) { - throw new FailedToCreateNodeException("Failed to create node of type " + nodeType + " for the path " - + fullPath + ". " + e.toString(), e); + throw new FailedToCreateNodeException( + "Failed to create node of type " + nodeType + + " for the path " + fullPath + ". " + + e.toString(), e); } } } - + /** * @see org.apache.jetspeed.prefs.PreferencesProvider#getChildren(org.apache.jetspeed.prefs.om.Node) */ public Collection getChildren(Node parentNode) { - NodeCache key = new NodeCache(parentNode.getFullPath(), parentNode.getNodeType()); + NodeCache key = new NodeCache(parentNode.getFullPath(), parentNode + .getNodeType()); NodeCache hit = getNode(key.getCacheKey()); if (hit == null) { - NodeImplProxy proxy = new NodeImplProxy(parentNode); + NodeImplProxy proxy = new NodeImplProxy(parentNode); hit = new NodeCache(proxy); addToCache(hit); } - if (hit.isChildrenLoaded()) - { - return resolveChildren(hit.getChildren()); - } + if (hit.isChildrenLoaded()) { return resolveChildren(hit.getChildren()); } Criteria c = new Criteria(); c.addEqualTo("parentNodeId", new Long(parentNode.getNodeId())); Query query = QueryFactory.newQuery(NodeImpl.class, c); - Collection children = getPersistenceBrokerTemplate().getCollectionByQuery(query); + Collection children = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); hit.setChildren(cacheChildren(children)); // null or not return children; } - private Collection resolveChildren(Collection children) { - if (children == null) - return null; - try - { - Iterator it = children.iterator(); - Vector v = new Vector(); - while (it.hasNext()) - { - String s = (String) it.next(); - NodeCache hit = getNode(s); - if (hit != null) + if (children == null) return null; + try + { + Iterator it = children.iterator(); + Vector v = new Vector(); + while (it.hasNext()) + { + String s = (String) it.next(); + NodeCache hit = getNode(s); + if (hit != null) { - v.add(hit.getNode()); + v.add(hit.getNode()); } else { @@ -407,36 +436,36 @@ } } } - } - return v; - } - catch (Exception e) - { - e.printStackTrace(); - return null; - } + } + return v; + } + catch (Exception e) + { + e.printStackTrace(); + return null; + } } - private Collection cacheChildren(Collection children) { - Iterator it = children.iterator(); - Vector v = new Vector(); - while (it.hasNext()) - { - Node key = (Node)it.next(); - NodeCache nodeKey = new NodeCache(key.getFullPath(),key.getNodeType()); - NodeCache hit = getNode(nodeKey.getCacheKey()); - if (hit == null) - { - NodeImplProxy proxy = new NodeImplProxy(key); - nodeKey.setNode(proxy); - addToCache(nodeKey); - hit= nodeKey; - } - v.add(hit.getCacheKey()); - } - return v; + Iterator it = children.iterator(); + Vector v = new Vector(); + while (it.hasNext()) + { + Node key = (Node) it.next(); + NodeCache nodeKey = new NodeCache(key.getFullPath(), key + .getNodeType()); + NodeCache hit = getNode(nodeKey.getCacheKey()); + if (hit == null) + { + NodeImplProxy proxy = new NodeImplProxy(key); + nodeKey.setNode(proxy); + addToCache(nodeKey); + hit = nodeKey; + } + v.add(hit.getCacheKey()); + } + return v; } /** @@ -444,74 +473,91 @@ */ public void storeNode(Node node) { - NodeImplProxy hit = null; - if (node instanceof NodeImplProxy) - { - hit = (NodeImplProxy)node; - } - else - { - //System.out.println("WARNING!!!!STORE NODE!!!!!!!!!!!! - Illegal Node element passed"); - hit = new NodeImplProxy(node); - } - + NodeImplProxy hit = null; + if (node instanceof NodeImplProxy) + { + hit = (NodeImplProxy) node; + } + else + { + // System.out.println("WARNING!!!!STORE NODE!!!!!!!!!!!! - Illegal + // Node element passed"); + hit = new NodeImplProxy(node); + } + NodeCache key = new NodeCache(hit); - getPersistenceBrokerTemplate().store(hit.getNode()); // avoid racing condition with the db and with cluster notification - // do the db first - preferenceCache.remove(key.getCacheKey()); // not sure we should actually do that, could also just update the node + getPersistenceBrokerTemplate().store(hit.getNode()); // avoid racing + // condition + // with the db + // and with + // cluster + // notification + // do the db first + preferenceCache.remove(key.getCacheKey()); // not sure we should + // actually do that, could + // also just update the node addToCache(key); } /** - * @see org.apache.jetspeed.prefs.PreferencesProvider#removeNode(org.apache.jetspeed.prefs.om.Node, org.apache.jetspeed.prefs.om.Node) + * @see org.apache.jetspeed.prefs.PreferencesProvider#removeNode(org.apache.jetspeed.prefs.om.Node, + * org.apache.jetspeed.prefs.om.Node) */ public void removeNode(Node parentNode, Node node) { - NodeImplProxy hit = null; - NodeImplProxy parentHit = null; + NodeImplProxy hit = null; + NodeImplProxy parentHit = null; - if (node instanceof NodeImplProxy) - { - getPersistenceBrokerTemplate().delete(((NodeImplProxy)node).getNode()); //avoid race conditions - do this first - } - else - getPersistenceBrokerTemplate().delete(node); //avoid race conditions - do this first - - if (node instanceof NodeImplProxy) - { - hit = (NodeImplProxy)node; - } - else - { - //System.out.println("WARNING!!!!REMOVE NODE!!!!!!!!!!!! - Illegal Node element passed"); - hit = new NodeImplProxy(node); - } + if (node instanceof NodeImplProxy) + { + getPersistenceBrokerTemplate().delete( + ((NodeImplProxy) node).getNode()); // avoid race conditions + // - do this first + } + else + getPersistenceBrokerTemplate().delete(node); // avoid race + // conditions - do + // this first + + if (node instanceof NodeImplProxy) + { + hit = (NodeImplProxy) node; + } + else + { + // System.out.println("WARNING!!!!REMOVE NODE!!!!!!!!!!!! - Illegal + // Node element passed"); + hit = new NodeImplProxy(node); + } NodeCache key = new NodeCache(hit); preferenceCache.remove(key.getCacheKey()); - if ( parentNode != null ) + if (parentNode != null) { - if (parentNode instanceof NodeImplProxy) - { - parentHit = (NodeImplProxy)parentNode; - } - else - { - //System.out.println("WARNING!!!!REMOVE NODE!!!!!!!!!!!! - Illegal Node element passed"); - parentHit = new NodeImplProxy(parentNode); - } - NodeCache parentKey = new NodeCache(parentHit); - parentKey = getNode(parentKey.getCacheKey()); - if ( parentKey != null && parentKey.isChildrenLoaded() ) + if (parentNode instanceof NodeImplProxy) { - parentKey.getChildren().remove(key.getCacheKey()); + parentHit = (NodeImplProxy) parentNode; } + else + { + // System.out.println("WARNING!!!!REMOVE NODE!!!!!!!!!!!! - + // Illegal Node element passed"); + parentHit = new NodeImplProxy(parentNode); + } + NodeCache parentKey = new NodeCache(parentHit); + parentKey = getNode(parentKey.getCacheKey()); + if (parentKey != null && parentKey.isChildrenLoaded()) + { + parentKey.getChildren().remove(key.getCacheKey()); + } } } - + /** - * @see org.apache.jetspeed.prefs.PreferencesProvider#lookupPreference(java.lang.String, java.lang.String, java.lang.String) + * @see org.apache.jetspeed.prefs.PreferencesProvider#lookupPreference(java.lang.String, + * java.lang.String, java.lang.String) */ - public Collection lookupPreference(String nodeName, String propertyName, String propertyValue) + public Collection lookupPreference(String nodeName, String propertyName, + String propertyValue) { Criteria c = new Criteria(); if (nodeName != null) @@ -527,28 +573,30 @@ c.addEqualTo("nodeProperties.propertyValue", propertyValue); } Query query = QueryFactory.newQuery(NodeImpl.class, c); - Collection children = getPersistenceBrokerTemplate().getCollectionByQuery(query); + Collection children = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); Collection proxied = new ArrayList(); Iterator iter = children.iterator(); while (iter.hasNext()) { - NodeImpl node = (NodeImpl)iter.next(); - NodeCache key = new NodeCache(node.getFullPath(), node.getNodeType()); + NodeImpl node = (NodeImpl) iter.next(); + NodeCache key = new NodeCache(node.getFullPath(), node + .getNodeType()); NodeCache hit = getNode(key.getCacheKey()); if (hit == null) { NodeImplProxy proxy = new NodeImplProxy(node); addToCache(new NodeCache(proxy)); proxied.add(proxy); - } + } else { proxied.add(hit.getNode()); } } - return proxied; + return proxied; } - + public Property createProperty(Node node, String name, Object value) { return new PropertyImpl(node.getNodeId(), name, value); @@ -560,49 +608,51 @@ Iterator apps = this.preloadedApplications.iterator(); while (apps.hasNext()) { - String appName = (String)apps.next(); + String appName = (String) apps.next(); preloadApplicationPreferences(appName); } - if (preloadEntities) - preloadAllEntities(); + if (preloadEntities) preloadAllEntities(); } - - public void preloadApplicationPreferences(String portletApplicationName) throws NodeDoesNotExistException + + public void preloadApplicationPreferences(String portletApplicationName) + throws NodeDoesNotExistException { - String portletDefPrefPath = "/" + MutablePortletApplication.PREFS_ROOT + "/" + portletApplicationName + "/"; -// + PortletDefinitionComposite.PORTLETS_PREFS_ROOT + "/" + portlet.getName() + "/" -// + MutablePortletApplication.PORTLET_PREFERENCES_ROOT; -// NodeCache key = new NodeCache(portletDefPrefPath, 1); -// NodeCache hit = getNode(key.getCacheKey()); -// if (hit != null) -// { -// return 1; -// //return hit.getNode(); -// } - long start = System.currentTimeMillis(); + String portletDefPrefPath = "/" + MutablePortletApplication.PREFS_ROOT + + "/" + portletApplicationName + "/"; + // + PortletDefinitionComposite.PORTLETS_PREFS_ROOT + "/" + + // portlet.getName() + "/" + // + MutablePortletApplication.PORTLET_PREFERENCES_ROOT; + // NodeCache key = new NodeCache(portletDefPrefPath, 1); + // NodeCache hit = getNode(key.getCacheKey()); + // if (hit != null) + // { + // return 1; + // //return hit.getNode(); + // } + long start = System.currentTimeMillis(); int count = loadNodeAndAllChildren(portletDefPrefPath); long elapsed = System.currentTimeMillis() - start; - System.out.println("++++ PREFS:PA loaded " + count + " pref nodes for app " + portletDefPrefPath + " in " + elapsed + " milliseconds."); + System.out.println("++++ PREFS:PA loaded " + count + + " pref nodes for app " + portletDefPrefPath + " in " + + elapsed + " milliseconds."); } - + protected int loadNodeAndAllChildren(String path) { int count = 0; NodeCache root = null; Criteria c = new Criteria(); c.addLike("fullPath", path + "%"); - //c.addOrderBy("fullPath"); + // c.addOrderBy("fullPath"); Query query = QueryFactory.newQuery(NodeImpl.class, c); - Collection result = getPersistenceBrokerTemplate().getCollectionByQuery(query); + Collection result = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); // TODO: ensure that we always get the first node back first - if (result == null || result.isEmpty()) - { - return count; - } + if (result == null || result.isEmpty()) { return count; } Iterator ri = result.iterator(); if (ri.hasNext()) { - Node n = (Node)ri.next(); + Node n = (Node) ri.next(); NodeImplProxy proxy = new NodeImplProxy(n); root = new NodeCache(proxy); addToCache(root); @@ -610,17 +660,18 @@ } else { - return count; + return count; } Map parents = new HashMap(); parents.put(new Long(root.getNode().getNodeId()), root); while (ri.hasNext()) { // build children and subchildren - Node subNode = (Node)ri.next(); - //System.out.println("*** Preloading: " + subNode.getFullPath()); + Node subNode = (Node) ri.next(); + // System.out.println("*** Preloading: " + subNode.getFullPath()); // add to current node - NodeCache nodeKey = new NodeCache(subNode.getFullPath(), subNode.getNodeType()); + NodeCache nodeKey = new NodeCache(subNode.getFullPath(), subNode + .getNodeType()); NodeCache lookup = getNode(nodeKey.getCacheKey()); if (lookup == null) { @@ -629,7 +680,8 @@ addToCache(nodeKey); lookup = nodeKey; } - NodeCache parent = (NodeCache)parents.get(subNode.getParentNodeId()); + NodeCache parent = (NodeCache) parents.get(subNode + .getParentNodeId()); if (parent != null) { if (parent.getChildren() == null) @@ -639,17 +691,19 @@ } parents.put(new Long(subNode.getNodeId()), lookup); count++; - } + } return count; } - + public void preloadAllEntities() throws NodeDoesNotExistException { - String entitiesRoot = "/" + MutablePortletEntity.PORTLET_ENTITY_ROOT + "/"; - long start = System.currentTimeMillis(); + String entitiesRoot = "/" + MutablePortletEntity.PORTLET_ENTITY_ROOT + + "/"; + long start = System.currentTimeMillis(); int count = loadNodeAndAllChildren(entitiesRoot); long elapsed = System.currentTimeMillis() - start; - System.out.println("++++ PREFS:ENTITIES loaded " + count + " total entity pref nodes in " + elapsed + " milliseconds."); + System.out.println("++++ PREFS:ENTITIES loaded " + count + + " total entity pref nodes in " + elapsed + " milliseconds."); } - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesFactoryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesFactoryImpl.java 2008-05-15 13:51:07 UTC (rev 936) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesFactoryImpl.java 2008-05-15 13:53:50 UTC (rev 937) @@ -16,35 +16,64 @@ */ package org.apache.jetspeed.prefs.impl; +import java.util.Observer; import java.util.prefs.Preferences; import java.util.prefs.PreferencesFactory; import org.apache.jetspeed.prefs.PreferencesException; import org.apache.jetspeed.prefs.PreferencesProvider; +import org.apache.jetspeed.util.PreferencesRootWrapper; /** - *

      {@link java.util.prefs.PreferencesFactory} implementation to - * return {@link PreferencesImpl}.

      - * + *

      + * {@link java.util.prefs.PreferencesFactory} implementation to return + * {@link PreferencesImpl}. + *

      + * * @author David Le Strat + * @author Ate Douma + * @version $Id$ */ public class PreferencesFactoryImpl implements PreferencesFactory { - - protected static PreferencesProvider prefsProvider; + private Preferences userRootWrapper; + + private Preferences systemRootWrapper; + + private PreferencesImpl userRoot; + + private PreferencesImpl systemRoot; + + private PreferencesProvider preferencesProvider; + + /** + * Java Preferences invoked constructor + */ public PreferencesFactoryImpl() { - super(); - System.setProperty("java.util.prefs.PreferencesFactory", getClass().getName()); - } + userRootWrapper = new PreferencesRootWrapper(); + systemRootWrapper = new PreferencesRootWrapper(); + } /** + * Spring invoked constructor with a dummy parameter to distinguish it from + * the default constructor invoked by the Java Preferences + * + * @param dummy + */ + public PreferencesFactoryImpl(int dummy) + { + System.setProperty("java.util.prefs.PreferencesFactory", getClass() + .getName()); + } + + /** * @see java.util.prefs.PreferencesFactory#systemRoot() */ public Preferences systemRoot() { - return PreferencesImpl.systemRoot; + return systemRootWrapper; } /** @@ -52,9 +81,9 @@ */ public Preferences userRoot() { - return PreferencesImpl.userRoot; + return userRootWrapper; } - + /** *

      * Initializes the factory. @@ -63,37 +92,52 @@ * @throws Exception */ public void init() throws Exception - { + { try - { - PreferencesImpl.setPreferencesProvider(prefsProvider); - PreferencesImpl.systemRoot = new PreferencesImpl(null, "", PreferencesImpl.SYSTEM_NODE_TYPE); - PreferencesImpl.userRoot = new PreferencesImpl(null, "", PreferencesImpl.USER_NODE_TYPE); + { + // Wrap the PreferencesProvider to provide a single instance to be + // stored in the Preferences nodes + // which can be disposed at once for all + PreferencesProviderWrapper ppw = new PreferencesProviderWrapper( + preferencesProvider); + preferencesProvider = null; + userRoot = new PreferencesImpl(null, ppw, "", + PreferencesImpl.USER_NODE_TYPE); + systemRoot = new PreferencesImpl(null, ppw, "", + PreferencesImpl.SYSTEM_NODE_TYPE); + // set/update the Java Preferences userRoot and systeRoot + // PreferencesRootWrapper instances + ((Observer) Preferences.userRoot()).update(null, userRoot); + ((Observer) Preferences.systemRoot()).update(null, systemRoot); } - catch(Throwable e) + catch (Throwable e) { - e.printStackTrace(); - throw new PreferencesException("Failed to initialize prefs api. "+e.toString()); + throw new PreferencesException("Failed to initialize prefs api. " + + e.getMessage(), e); } } - - /** - * @return The {@link PreferencesProvider} - */ - public PreferencesProvider getPrefsProvider() + + public void dispose() { - return prefsProvider; + ((Observer) Preferences.userRoot()).update(null, null); + ((Observer) Preferences.systemRoot()).update(null, null); + userRoot.disposeNode(); + systemRoot.disposeNode(); + userRoot.ppw.dispose(); + userRoot = null; + systemRoot = null; } - + /** *

      * Set the preferences provider. *

      * - * @param prefsProvider The {@link PreferencesProvider} + * @param preferencesProvider + * The {@link PreferencesProvider} */ - public void setPrefsProvider(PreferencesProvider prefsProvider) + public void setPrefsProvider(PreferencesProvider preferencesProvider) { - PreferencesFactoryImpl.prefsProvider = prefsProvider; + this.preferencesProvider = preferencesProvider; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesImpl.java 2008-05-15 13:51:07 UTC (rev 936) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesImpl.java 2008-05-15 13:53:50 UTC (rev 937) @@ -29,7 +29,6 @@ import org.apache.jetspeed.prefs.FailedToCreateNodeException; import org.apache.jetspeed.prefs.NodeAlreadyExistsException; import org.apache.jetspeed.prefs.NodeDoesNotExistException; -import org.apache.jetspeed.prefs.PreferencesProvider; import org.apache.jetspeed.prefs.om.Node; import org.apache.jetspeed.prefs.om.Property; import org.apache.jetspeed.prefs.om.impl.PropertyImpl; @@ -41,6 +40,8 @@ *

      * * @author David Le Strat + * @author Ate Douma + * @version $Id$ */ public class PreferencesImpl extends AbstractPreferences { @@ -57,12 +58,13 @@ /** Logger. */ private static final Log log = LogFactory.getLog(PreferencesImpl.class); - protected static PreferencesProvider prefsProvider; + protected PreferencesProviderWrapper ppw; - static PreferencesImpl systemRoot; + void disposeNode() + { + node = null; + } - static PreferencesImpl userRoot; - /** *

      * Constructs a root node in the underlying datastore if they have not yet @@ -72,31 +74,39 @@ * Logs a warning if the underlying datastore is unavailable. *

      * - * @param parent The parent object. - * @param nodeName The node name. - * @param nodeType The node type. + * @param parent + * The parent object. + * @param nodeName + * The node name. + * @param nodeType + * The node type. */ - public PreferencesImpl(PreferencesImpl parent, String nodeName, int nodeType) throws IllegalStateException + PreferencesImpl(PreferencesImpl parent, PreferencesProviderWrapper ppw, + String nodeName, int nodeType) throws IllegalStateException { super(parent, nodeName); try { + this.ppw = ppw; if (parent != null) { - this.node = prefsProvider.createNode(parent.getNode(), nodeName, nodeType, this.absolutePath()); + this.node = ppw.provider().createNode(parent.getNode(), + nodeName, nodeType, this.absolutePath()); } else { - this.node = prefsProvider.createNode(null, nodeName, nodeType, this.absolutePath()); + this.node = ppw.provider().createNode(null, nodeName, nodeType, + this.absolutePath()); } newNode = true; } catch (FailedToCreateNodeException e) { - IllegalStateException ise = new IllegalStateException("Failed to create new Preferences of type " - + nodeType + " for path " + this.absolutePath()); + IllegalStateException ise = new IllegalStateException( + "Failed to create new Preferences of type " + nodeType + + " for path " + this.absolutePath()); ise.initCause(e); throw ise; } @@ -104,7 +114,7 @@ { try { - node = prefsProvider.getNode(this.absolutePath(), nodeType); + node = ppw.provider().getNode(this.absolutePath(), nodeType); newNode = false; } catch (NodeDoesNotExistException e1) @@ -128,7 +138,7 @@ */ public String[] childrenNamesSpi() throws BackingStoreException { - Collection nodes = prefsProvider.getChildren(getNode()); + Collection nodes = ppw.provider().getChildren(getNode()); if (null != nodes) { @@ -153,7 +163,7 @@ */ public AbstractPreferences childSpi(String name) { - return new PreferencesImpl(this, name, node.getNodeType()); + return new PreferencesImpl(this, ppw, name, node.getNodeType()); } /** @@ -161,7 +171,7 @@ */ public void flushSpi() throws BackingStoreException { - prefsProvider.storeNode(this.node); + ppw.provider().storeNode(this.node); } /** @@ -171,14 +181,19 @@ { String value = null; // Collection properties = node.getNodeProperties(); - // BEGIN + // TODO review below + // BEGIN Node targetNode = null; - try { - targetNode = prefsProvider.getNode(node.getFullPath(), node - .getNodeType()); - } catch (NodeDoesNotExistException e) { + try + { + targetNode = ppw.provider().getNode(node.getFullPath(), + node.getNodeType()); } - if (targetNode == null) { + catch (NodeDoesNotExistException e) + { + } + if (targetNode == null) + { targetNode = node; } Collection properties = targetNode.getNodeProperties(); @@ -187,7 +202,8 @@ for (Iterator i = properties.iterator(); i.hasNext();) { Property curProp = (Property) i.next(); - if ((null != curProp) && (null != curProp.getPropertyName()) && (curProp.getPropertyName().equals(key))) + if ((null != curProp) && (null != curProp.getPropertyName()) + && (curProp.getPropertyName().equals(key))) { value = curProp.getPropertyValue(); } @@ -216,7 +232,8 @@ } } - return (String[]) propertyNames.toArray(new String[propertyNames.size()]); + return (String[]) propertyNames + .toArray(new String[propertyNames.size()]); } /** @@ -228,7 +245,8 @@ Collection properties = node.getNodeProperties(); if (null == properties) { - log.error("Could not retrieve node property: [key: " + key + ", value:" + value + "]"); + log.error("Could not retrieve node property: [key: " + key + + ", value:" + value + "]"); return; } @@ -237,14 +255,18 @@ for (Iterator i = properties.iterator(); i.hasNext();) { Property curProp = (Property) i.next(); - if ((null != curProp) && (null != curProp.getPropertyName()) && curProp.getPropertyName().equals(key)) + if ((null != curProp) && (null != curProp.getPropertyName()) + && curProp.getPropertyName().equals(key)) { propFound = true; curProp.setPropertyValue(value); - curProp.setModifiedDate(new Timestamp(System.currentTimeMillis())); + curProp.setModifiedDate(new Timestamp(System + .currentTimeMillis())); if (log.isDebugEnabled()) { - log.debug("Update existing property: " + curProp.toString()); + log + .debug("Update existing property: " + + curProp.toString()); } // Property found, we break. break; @@ -255,7 +277,7 @@ properties.add(new PropertyImpl(node.getNodeId(), key, value)); } - prefsProvider.storeNode(node); + ppw.provider().storeNode(node); } /** @@ -269,7 +291,7 @@ { parentNode = ((PreferencesImpl) parent).getNode(); } - prefsProvider.removeNode(parentNode, node); + ppw.provider().removeNode(parentNode, node); } /** @@ -289,7 +311,7 @@ } } // Update node. - prefsProvider.storeNode(node); + ppw.provider().storeNode(node); } /** @@ -312,20 +334,4 @@ { return node; } - - /** - * - *

      - * setPreferencesProvider - *

      - * Sets the org.apache.jetspeed.prefs.PreferencesProvider - * that will support backing store operations for all - * PreferencesImpls - * - * @param prefsProvider - */ - public static void setPreferencesProvider(PreferencesProvider prefsProvider) - { - PreferencesImpl.prefsProvider = prefsProvider; - } } Added: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesProviderWrapper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesProviderWrapper.java (rev 0) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesProviderWrapper.java 2008-05-15 13:53:50 UTC (rev 937) @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.jetspeed.prefs.impl; + +import org.apache.jetspeed.prefs.PreferencesProvider; + +/** + * @author Ate Douma + * @version $Id$ + */ +public class PreferencesProviderWrapper +{ + + PreferencesProvider provider; + + PreferencesProviderWrapper(PreferencesProvider provider) + { + this.provider = provider; + } + + PreferencesProvider provider() + { + return provider; + } + + void dispose() + { + provider = null; + } +} Property changes on: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesProviderWrapper.java ___________________________________________________________________ Name: svn:eol-style + native Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/assembly/prefs.xml =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/assembly/prefs.xml 2008-05-15 13:51:07 UTC (rev 936) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/assembly/prefs.xml 2008-05-15 13:53:50 UTC (rev 937) @@ -19,7 +19,7 @@ - + JETSPEED-INF/ojb/prefs_repository.xml @@ -36,7 +36,7 @@ false - + org.apache.jetspeed.prefs.PreferencesProvider @@ -55,7 +55,9 @@ - + + + 1 From svnnotify ¡÷ sourceforge.jp Thu May 15 22:57:46 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Thu, 15 May 2008 22:57:46 +0900 Subject: [pal-cvs 3201] [938] put a proper portal name and version. Message-ID: <1210859866.236553.13401.nullmailer@users.sourceforge.jp> Revision: 938 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=938 Author: shinsuke Date: 2008-05-15 22:57:46 +0900 (Thu, 15 May 2008) Log Message: ----------- put a proper portal name and version. Modified Paths: -------------- pal-portal/branches/pal-portal-1.x/build.properties pal-portal/branches/pal-portal-1.x/portal/build.xml pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/decorations/layout/default/footer.vm pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/decorations/layout/nextgen/footer.vm Added Paths: ----------- pal-portal/branches/pal-portal-1.x/portal/files/src/ pal-portal/branches/pal-portal-1.x/portal/files/src/webapp/ pal-portal/branches/pal-portal-1.x/portal/files/src/webapp/WEB-INF/ pal-portal/branches/pal-portal-1.x/portal/files/src/webapp/WEB-INF/conf/ pal-portal/branches/pal-portal-1.x/portal/files/src/webapp/WEB-INF/conf/override.properties Removed Paths: ------------- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/conf/override.properties -------------- next part -------------- Modified: pal-portal/branches/pal-portal-1.x/build.properties =================================================================== --- pal-portal/branches/pal-portal-1.x/build.properties 2008-05-15 13:53:50 UTC (rev 937) +++ pal-portal/branches/pal-portal-1.x/build.properties 2008-05-15 13:57:46 UTC (rev 938) @@ -6,6 +6,7 @@ container.version.major=1 container.version.minor=0.5-dev container.info.file=commons/src/java/org/apache/jetspeed/container/resources/ContainerInfo.properties +override.prop.file=src/webapp/WEB-INF/conf/override.properties portlets.home=${basedir}/portlets portlets.build.dir=${portlets.home}/build portlets.resource.dir=${portlets.home}/resources Modified: pal-portal/branches/pal-portal-1.x/portal/build.xml =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/build.xml 2008-05-15 13:53:50 UTC (rev 937) +++ pal-portal/branches/pal-portal-1.x/portal/build.xml 2008-05-15 13:57:46 UTC (rev 938) @@ -146,6 +146,22 @@ token="@@CONTAINER_VERSION_MINOR@@" value="${container.version.minor}" /> + + + + Copied: pal-portal/branches/pal-portal-1.x/portal/files/src/webapp/WEB-INF/conf/override.properties (from rev 922, pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/conf/override.properties) =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/files/src/webapp/WEB-INF/conf/override.properties (rev 0) +++ pal-portal/branches/pal-portal-1.x/portal/files/src/webapp/WEB-INF/conf/override.properties 2008-05-15 13:57:46 UTC (rev 938) @@ -0,0 +1,4 @@ +portal.name = @@CONTAINER_NAME@@ +portal.version = @@CONTAINER_VERSION_MAJOR@@.@@CONTAINER_VERSION_MINOR@@ + +email.sender=palportal ¡÷ pal.sourceforge.jp Deleted: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/conf/override.properties =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/conf/override.properties 2008-05-15 13:53:50 UTC (rev 937) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/conf/override.properties 2008-05-15 13:57:46 UTC (rev 938) @@ -1 +0,0 @@ -email.sender=palportal ¡÷ pal.sourceforge.jp Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/decorations/layout/default/footer.vm =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/decorations/layout/default/footer.vm 2008-05-15 13:53:50 UTC (rev 937) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/decorations/layout/default/footer.vm 2008-05-15 13:57:46 UTC (rev 938) @@ -77,7 +77,7 @@ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/decorations/layout/nextgen/footer.vm =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/decorations/layout/nextgen/footer.vm 2008-05-15 13:53:50 UTC (rev 937) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/decorations/layout/nextgen/footer.vm 2008-05-15 13:57:46 UTC (rev 938) @@ -16,7 +16,7 @@ From svnnotify ¡÷ sourceforge.jp Fri May 16 10:52:50 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Fri, 16 May 2008 10:52:50 +0900 Subject: [pal-cvs 3202] [939] updated eclipse setting. Message-ID: <1210902770.169148.6629.nullmailer@users.sourceforge.jp> Revision: 939 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=939 Author: shinsuke Date: 2008-05-16 10:52:50 +0900 (Fri, 16 May 2008) Log Message: ----------- updated eclipse setting. Modified Paths: -------------- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.core.prefs pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.ui.prefs -------------- next part -------------- Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.core.prefs =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.core.prefs 2008-05-15 13:57:46 UTC (rev 938) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.core.prefs 2008-05-16 01:52:50 UTC (rev 939) @@ -1,4 +1,4 @@ -#Thu May 15 15:29:00 JST 2008 +#Fri May 16 09:54:06 JST 2008 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.4 @@ -133,7 +133,7 @@ org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert -org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.ui.prefs =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.ui.prefs 2008-05-15 13:57:46 UTC (rev 938) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/.settings/org.eclipse.jdt.ui.prefs 2008-05-16 01:52:50 UTC (rev 939) @@ -1,4 +1,52 @@ -#Thu May 15 15:09:12 JST 2008 +#Fri May 16 10:30:59 JST 2008 eclipse.preferences.version=1 +editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true formatter_profile=_Jetspeed formatter_settings_version=11 +sp_cleanup.add_default_serial_version_id=true +sp_cleanup.add_generated_serial_version_id=false +sp_cleanup.add_missing_annotations=true +sp_cleanup.add_missing_deprecated_annotations=true +sp_cleanup.add_missing_nls_tags=false +sp_cleanup.add_missing_override_annotations=true +sp_cleanup.add_serial_version_id=false +sp_cleanup.always_use_blocks=true +sp_cleanup.always_use_parentheses_in_expressions=false +sp_cleanup.always_use_this_for_non_static_field_access=false +sp_cleanup.always_use_this_for_non_static_method_access=false +sp_cleanup.convert_to_enhanced_for_loop=false +sp_cleanup.format_source_code=true +sp_cleanup.make_local_variable_final=false +sp_cleanup.make_parameters_final=false +sp_cleanup.make_private_fields_final=true +sp_cleanup.make_variable_declarations_final=true +sp_cleanup.never_use_blocks=false +sp_cleanup.never_use_parentheses_in_expressions=true +sp_cleanup.on_save_use_additional_actions=false +sp_cleanup.organize_imports=true +sp_cleanup.qualify_static_field_accesses_with_declaring_class=false +sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +sp_cleanup.qualify_static_member_accesses_with_declaring_class=false +sp_cleanup.qualify_static_method_accesses_with_declaring_class=false +sp_cleanup.remove_private_constructors=true +sp_cleanup.remove_trailing_whitespaces=false +sp_cleanup.remove_trailing_whitespaces_all=true +sp_cleanup.remove_trailing_whitespaces_ignore_empty=false +sp_cleanup.remove_unnecessary_casts=true +sp_cleanup.remove_unnecessary_nls_tags=false +sp_cleanup.remove_unused_imports=false +sp_cleanup.remove_unused_local_variables=false +sp_cleanup.remove_unused_private_fields=true +sp_cleanup.remove_unused_private_members=false +sp_cleanup.remove_unused_private_methods=true +sp_cleanup.remove_unused_private_types=true +sp_cleanup.sort_members=false +sp_cleanup.sort_members_all=false +sp_cleanup.use_blocks=false +sp_cleanup.use_blocks_only_for_return_and_throw=false +sp_cleanup.use_parentheses_in_expressions=false +sp_cleanup.use_this_for_non_static_field_access=false +sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true +sp_cleanup.use_this_for_non_static_method_access=false +sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true From svnnotify ¡÷ sourceforge.jp Fri May 16 10:54:54 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Fri, 16 May 2008 10:54:54 +0900 Subject: [pal-cvs 3203] [940] code format and organize imports. Message-ID: <1210902894.820583.8518.nullmailer@users.sourceforge.jp> Revision: 940 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=940 Author: shinsuke Date: 2008-05-16 10:54:54 +0900 (Fri, 16 May 2008) Log Message: ----------- code format and organize imports. Modified Paths: -------------- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/AntInstallerCheckConnection.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/ArchetypeDescriptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/ExecuteJavaSQL.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/ExecuteSQL.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StartDatabase.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StartDerby.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StopDatabase.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StopDerby.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/app-servers/security/jboss/src/java/org/apache/jetspeed/appservers/security/jboss/JetspeedSecurityService.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/app-servers/security/jboss/src/java/org/apache/jetspeed/appservers/security/jboss/JetspeedSecurityServiceMBean.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/app-servers/security/jboss/src/java/org/apache/jetspeed/appservers/security/jboss/LoginModule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/Jetspeed.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/aggregator/CurrentWorkerContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerConstants.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerInfo.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerRequest.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerResponse.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/InternalPortletConfig.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/InternalPortletContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/JetspeedContainerServlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/JetspeedPortletConfig.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/JetspeedPortletContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortalAccessor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletConfigFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletContextFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletDispatcherIncludeAware.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletRequestContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/session/PortletApplicationSessionMonitorImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/dispatcher/JetspeedRequestDispatcher.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlet/PortletObjectProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlet/PortletResourceURLFactoryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlet/ServletContextProviderImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/ColumnLayout.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/EmptyLayoutLocationException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/FragmentNotInLayoutException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/InvalidLayoutLocationException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutCoordinate.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutError.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutEvent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutEventListener.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/PageManagerLayoutEventListener.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/FolderPermission.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/FragmentPermission.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/JSSubject.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PagePermission.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PortalResourcePermission.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PortalResourcePermissionCollection.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PortletPermission.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/services/JetspeedPortletServices.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/services/PortletServices.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/AbstractFileSystemHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/ArgUtil.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/BaseObjectProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/ChecksumHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/DirectoryHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/FIFOQueue.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/HashCodeBuilder.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JarHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JetspeedLocale.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JetspeedLongObjectID.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JetspeedObjectID.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/Path.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/PortalObjectID.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/test/org/apache/jetspeed/util/TestPathUtil.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/CapabilityImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/CapabilityMapImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/ClientImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/JetspeedCapabilities.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/MediaTypeImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/MimeTypeImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/test/org/apache/jetspeed/capabilities/TestCapability.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/general/SimpleHashMapCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheDistributedElementImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheDistributedImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheElementImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheEventListener.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheEventListenerFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhDecorationContentCacheElementImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhDecorationContentCacheImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhPortletContentCacheElementImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhPortletContentCacheImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhPortletWindowCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/JetspeedCacheKeyGenerator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/JetspeedContentCacheKey.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/SpringComponentManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/factorybeans/PlutoFactoryFactoryBean.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/factorybeans/ServletConfigFactoryBean.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/interceptors/AbstractCacheInterceptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/interceptors/CachingInterceptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/interceptors/RemoveFromCacheInterceptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/test/AbstractSpringTestCase.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/util/system/ClassLoaderSystemResourceUtilImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/util/system/FSSystemResourceUtilImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/util/system/SystemResourceUtil.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/mocks/BaseMockServletContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/mocks/ResourceLocatingRequestDispatcher.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/mocks/ResourceLocatingServletContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/AbstractTestHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/BuildPropertiesHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/DatasourceHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/OJBHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/TestHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/TestContentCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/TestDecorationContentCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/TestPortletWindowCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/general/InvocationCountingCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/general/TestCachingInterceptors.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/BaseMockComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/MockComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/MockDependentComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/SimpleComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/testhelpers/TestDatasourceHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/testhelpers/TestOJBHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedContextRewriter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedDeploy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedDeployFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriter2_3.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriter2_4.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriterFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/java/org/apache/jetspeed/cache/file/FileCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/java/org/apache/jetspeed/cache/file/FileCacheEntryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/test/org/apache/jetspeed/cache/file/FileCopy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/test/org/apache/jetspeed/cache/file/TestFileCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/header-resource/src/java/org/apache/jetspeed/headerresource/impl/HeaderResourceFactoryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/header-resource/src/java/org/apache/jetspeed/headerresource/impl/HeaderResourceImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/id-generator/src/java/org/apache/jetspeed/idgenerator/JetspeedIdGenerator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/id-generator/src/test/org/apache/jetspeed/idgenerator/TestIdGenerator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/AbstractScheduler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/BaseJobEntry.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/JobEntry.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/JobQueue.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/MemoryBasedScheduler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/ScheduledJob.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/Scheduler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/WorkerThread.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/util/OverwriteProperties.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/locator/JetspeedLocatorDescriptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/locator/JetspeedTemplateDescriptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/locator/JetspeedTemplateLocator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/JetspeedProfileLocator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/ProfileFallbackIterator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/ProfileLocatorControl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/ProfileLocatorPropertyImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/test/org/apache/jetspeed/locator/TestTemplateLocator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuDefinitionElement.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuDefinitionMetadata.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuExcludeDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuIncludeDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuOptionsDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuSeparatorDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionElement.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionElementList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuExcludeDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuIncludeDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuMetadataLocalizedFieldImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuOptionsDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuSeparatorDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMetadataLocalizedFieldImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderOrder.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderOrderList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderSecurityConstraintImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderSecurityConstraintsImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderSecurityConstraintsRef.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/FolderImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/FolderMetaDataImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuElementImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuExcludeDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuIncludeDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuMetadataImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuOptionsDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuSeparatorDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/ContentFragmentImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/ContentPageImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/PageMetadataImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/SecurityConstraintImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/BaseElementImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/BaseSecurityConstraintsRef.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FilteredFragmentList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceValue.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceValueList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPropertyMap.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentSecurityConstraintImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentSecurityConstraintsImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentSecurityConstraintsRef.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkMetadataLocalizedFieldImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkSecurityConstraintImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkSecurityConstraintsImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkSecurityConstraintsRef.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionElement.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionElementList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuExcludeDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuIncludeDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuMetadataLocalizedFieldImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuOptionsDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuSeparatorDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMetadataLocalizedFieldImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsDefList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsRef.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsRefList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityGlobalSecurityConstraintsRef.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecuritySecurityConstraintImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintDefList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintsDefImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintsImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintsRefList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/AbstractBaseElement.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/DefaultsImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/DocumentImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FilteredFragmentList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FragmentImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FragmentList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FragmentPreferenceImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/LinkImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/PageImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/PageSecurityImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/PropertyImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/ReferenceImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/SecurityConstraintsDefImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/SecurityConstraintsImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/AbstractPageManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/DelegatingPageManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/PageImporter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/PageManagerSecurityUtils.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/PageManagerUtils.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/impl/DocumentImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/impl/NodeImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/impl/NodeSetImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/AbstractNode.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/CastorFileSystemDocumentHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/DocumentHandlerFactoryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/FileSystemFolderHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/NodeOrderCompartaor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/NodeSetImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/DatabasePageManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/DatabasePageManagerUtils.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/TransactionedOperation.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/psml/CastorXmlPageManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/MethodReplayDecisionMaker.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/MethodReplayInterceptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/PageManagerInterceptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/TransactionalMethodReplayDecisionMaker.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/ojb/ACLFieldConversion.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/om/page/TestPageObjectModel.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/DirectoryXMLTransform.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/PageManagerTestShared.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestCastorXmlPageManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestCreateUserHomePagesFromRoles.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestDatabasePageManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestMappings.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecureCastorXmlPageManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecureDatabasePageManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecurePermissionsCastorXmlPageManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecurePermissionsDatabasePageManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestTransactions.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/document/psml/TestCastorFileSystemDocumentHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/AbstractAuthFilter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/CookieAuthFilter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/CookieTransferFilter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/RequestHeaderAuthFilter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/RequestParameterAuthFilter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/servlet/UserManagerServlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/JetspeedPortalContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/PortalContextFactoryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/AdminUtil.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/PortalAdministrationImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/PortalAuthenticationConfigurationImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/PortalConfigurationImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/AggregatorValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/FileServerValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/HeaderAggregatorValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/PortletValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/AsyncPageAggregatorImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/BaseAggregatorImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/CommonjWorkerMonitorImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/ContentDispatcherImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/HeaderAggregatorImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/HttpBufferedResponse.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PageAggregatorImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletAggregatorFragmentImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletAggregatorImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletContentImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletHeaderRequestImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletHeaderResponseImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletRendererImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletTrackingManagerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/RenderingJobImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/WorkerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/WorkerMonitorImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXFilter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXRequestImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXResponseImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXServiceImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AjaxRequestServiceImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/capabilities/impl/CapabilityCustomizerValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/capabilities/impl/CapabilityValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/cluster/NodeInformationImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/cluster/NodeManagerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/ContainerValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/DesktopPortletContainerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/JetspeedPortletContainerWrapper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/PageHistoryValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/PortletContainerWrapper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/DefaultPortletRequestResponseUnwrapper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/JetspeedPortletInvoker.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/LocalPortletInvoker.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/LocalPortletInvokerFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/LocalServletRequest.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/PortletInvokerFactoryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/ServletPortletInvoker.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/ServletPortletInvokerFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapperFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapperFactoryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapperImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/services/log/ContainerLoggerAdaptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/services/log/PlutoLogService.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionMonitorImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionsManagerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/AbstractNavigationalState.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/HybridNavigationalState.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/JetspeedNavigationalStateCodec.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/JetspeedNavigationalStateComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/NavigationalStateCodec.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PathNavigationalState.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowBaseNavigationalState.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowExtendedNavigationalState.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowRequestNavigationalState.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowRequestNavigationalStates.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowSessionNavigationalStates.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/SessionFullExtendedNavigationalState.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/SessionFullNavigationalState.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/SessionNavigationalState.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/AbstractPortalURL.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/BasePortalURLImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/CleanPathInfoEncodedNavStateFromPortalURLValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/DesktopEncodingPortalURL.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/GlassFishPathInfoEncodingPortalURL.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/JetspeedPortletURL.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/PathInfoEncodingPortalURL.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/PortalURLValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/PortletURLFactoryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/QueryStringEncodingPortalURL.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/window/impl/PortletWindowAccessorImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/AbstractDecoratorActionsFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/BaseDecoration.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/CustomDecoratorActionsFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecorationFactoryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecorationValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecoratorAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecoratorActionTemplate.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecoratorActionsFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DefaultDecoratorActionsFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/LayoutDecorationImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/LayoutInfoImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PageActionAccess.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PageTheme.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PortletDecorationImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PrintSoloDecoratorActionsFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/caches/HashMapPathResolverCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/caches/NoCachePathResolverCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/caches/SessionPathResolverCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/validators/ClasspathResourceValidator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/validators/WebApplicationResourceValidator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/DeployDecoratorEventListener.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/DeployPortletAppEventListener.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/DeploymentEventImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/FileNotDeployableException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/JarExpander.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/JettyDeployPortletAppEventListener.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/StandardDeploymentManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/StandardDeploymentObject.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/Entry.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/SimpleRegistry.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/SimpleRegistryException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/impl/InMemoryRegistryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/DesktopEncoderRedirectValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/DesktopValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/JetspeedDesktopContextImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/JetspeedDesktopImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/JetspeedEngine.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/JetspeedServlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/core/PortalContextImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/core/PortalContextProviderImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/core/PortletActionProviderImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/HttpSessionWrapper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/NamespaceEncodedSession.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletObjectAccess.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletRequestFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletRequestFactoryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletRequestImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletResponseFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletResponseFactoryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletResponseImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/StaticResourceCachingFilter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/XXSUrlAttackFilter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/AddPortletAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BaseGetResourceAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BasePortletAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BaseSiteUpdateAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BaseUserAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/ChangePortletAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/Constants.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/ExportJetspeedSchema.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/ExportObject.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetFolderAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetFolderListAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetFoldersListAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetLinkAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetMenuAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetMenusAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPageAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPagesAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPortletActionsAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPortletsAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetThemesAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetUserInformationAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetUserListAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/LayoutValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/MovePortletAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/MultipleAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/NestedFragmentContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletActionSecurityConstraintsBehavior.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletActionSecurityPathBehavior.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletActionSecurityPathMergeBehavior.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletInfo.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletPlacementContextImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/RemovePortletAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/RolesSecurityBehavior.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/SecurityConstraintsAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/SecurityPermissionAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/UpdateFolderAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/UpdateLinkAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/UpdatePageAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/localization/impl/LocalizationValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/localization/impl/SimplifiedLocalizationValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginErrorServlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginProxyServlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginRedirectorServlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginServlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LogoutServlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/filter/PortalFilter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/filter/PortalRequestWrapper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/impl/LoginJSPViewValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/manager/ManagerServlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/messaging/PortletMessagingImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/JetspeedPipeline.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/AbstractValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/ActionValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/AggregateValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/CapabilityValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/CleanupValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/ContainerValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/ContentValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LayoutValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LocalizationValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LoginValidationValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LoginViewValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/PageProfilerValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/PasswordCredentialValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/SecurityValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/UserProfilerValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/ActionValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/CleanupValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/DebugValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/PropertyLoaderValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/VerySimpleLayoutValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/profiler/impl/CreatePageValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/profiler/impl/CreateUserTemplatePagesValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/profiler/impl/ProfilerValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/JetspeedRequestContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/JetspeedRequestContextComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/PortalRequest.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/PortalRequestFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/PortalRequestFactoryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/resource/BufferedHttpServletResponse.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/resource/ResourceValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/AbstractSecurityValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/Jetspeed1CredentialPasswordEncoder.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/LoginValidationValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/PasswordCredentialValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/SecurityAccessControllerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/SecurityValveImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/ntlm/NtlmHttpServletRequestFilter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/ntlm/NtlmHttpServletRequestWrapper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/ntlm/NtlmSecurityValve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/DynamicInformationProviderImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/InformationProviderServiceImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/PortletURLProviderImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/ResourceURLProviderImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/StaticInformationProviderImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/title/DynamicTitleService.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/title/DynamicTitleServiceImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/PortletApplicationException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/PortletApplicationManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/VersionedPortletApplicationManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/JetspeedServiceRule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/JetspeedServicesRuleSet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/LocalizedFieldRule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/MetadataRuleSet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/PortletRule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/SecurityConstraintRefRule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/UserAttributeRefRule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/UserAttributeRefRuleSet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/GlassFishManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/JBossManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/TomcatManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/WeblogicManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/registration/RegistrationTool.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/AbstractUserInfoManagerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/MultiSourceUserInfoManagerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/UserInfoManagerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/UserManagerUserAttributeSourceImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/CloneUtil.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/DirectoryUtils.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/MimeType.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/MultiFileChecksumHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/ExtendedPortletMetadata.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/MetaDataException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationDescriptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationRule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationRuleSet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationWar.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletPreferenceRule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletPreferenceRuleSet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletRule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/WebApplicationDescriptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/HtmlUtilTool.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedPowerToolFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedPowerToolImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedVelocityPowerTool.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedVelocityViewServlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/RemoteContentTool.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/AbstractPortalContainerTestCase.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/AbstractRequestContextTestCase.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/HashMapWindowCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/PortalTestConstants.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/PortletFactoryMock.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/administration/TestPortalAdministrationImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/MockRenderJob.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/TestAggregator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/TestRenderer.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/TestWorkerMonitor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/cluster/TestCluster.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/container/TestPortletContainer.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/container/state/TestNavigationalState.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/decoration/OnConsecutiveInvokes.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/decoration/StringReaderInputStream.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/decoration/TestDecorations.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/deployment/TestSimpleDeployment.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/engine/AbstractEngineTest.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/engine/TestSpringEngine.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/FragmentUtil.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/LocalFragmentImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/MockPortletRegistryFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/TestConstraintsAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/TestLayout.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/TestPortletPlacement.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/pipeline/TestPipeline.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/test/JetspeedTest.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/test/JetspeedTestSuite.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/testhelpers/SpringEngineHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/TestWebXML.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/pamanager/TestJetspeedPortletDescriptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/pamanager/TestPortletDescriptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/pamanager/TestPortletDescriptorSecurityRoles.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/userinfo/MockUserInfoManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/userinfo/TestUserInfoManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/window/TestWindows.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuExcludeDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuIncludeDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuOptionsDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuSeparatorDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/proxy/FolderProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/page/proxy/LinkProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/page/proxy/PageProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/page/document/proxy/NodeProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/page/document/proxy/NodeSetImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuElementImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuOptionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuSeparatorImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/PortalSiteImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/PortalSiteRequestContextImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/PortalSiteSessionContextImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/DefaultMenuDefinition.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/DefaultMenuOptionsDefinition.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardBackMenuDefinition.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardBreadcrumbsMenuDefinition.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardNavigationsMenuDefinition.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardPagesMenuDefinition.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteView.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteViewMenuDefinitionLocator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteViewProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteViewSearchPath.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/test/org/apache/jetspeed/portalsite/TestPortalSite.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portlet-factory/src/java/org/apache/jetspeed/factory/JetspeedPortletFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portlet-factory/src/java/org/apache/jetspeed/factory/JetspeedPortletInstance.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portlet-factory/src/java/org/apache/jetspeed/factory/JetspeedPortletProxyInstance.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/NodeImplProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PersistenceBrokerPreferencesProvider.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/om/impl/NodeImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/om/impl/PropertyImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/util/test/AbstractPrefsSupportedTestCase.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestNodePreferences.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestPreferences.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestPreferencesNoPropManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestPreferencesProvider.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/impl/JetspeedProfilerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/AbstractProfilingRule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/CountryCriterionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/DomainCriterionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/GroupCriterionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/GroupRoleUserCriterionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/HardCodedResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/HostnameCriterionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/LanguageCriterionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/MediatypeCriterionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/NavigationCriterionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/PathResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/PathSessionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/PrincipalRuleImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/ProfileResolversImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RequestSessionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RoleComboCriterionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RoleCriterionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RoleFallbackProfilingRule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RuleCriterionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/SessionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/StandardProfilingRule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/StandardResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/UserAgentCriterionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/UserAttributeResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/UserCriterionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/test/org/apache/jetspeed/profiler/TestProfiler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/dao/InitablePersistenceBrokerDaoSupport.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/BoundDBCPDatasourceComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/DBCPDatasourceComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/DatasourceComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/SchemaAwareDataSourceProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/JNDIComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/JetspeedTestJNDIComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/SpringJNDIStarter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/TyrexJNDIComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionManagerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionRepositoryEntry.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/DatabasePlatformConfigurator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/util/DatasourceEnabledSpringTestCase.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/util/DatasourceTestCase.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/test/org/apache/jetspeed/components/TestRDBMS.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletentity/PersistenceBrokerPortletEntityAccess.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletentity/PortletEntityImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/MutablePortletApplicationProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PersistenceBrokerPortletRegistry.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PortletApplicationProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PortletDefinitionCompositeProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PortletRegistryHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/RegistryApplicationCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/RegistryCacheObjectWrapper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/RegistryPortletCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/util/RegistrySupportedTestCase.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DescriptionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DescriptionSetImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DisplayNameImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DisplayNameSetImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DublinCoreImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/GenericMetadataImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/JetspeedServiceReferenceImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/LanguageImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/LanguageSetImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/LocalizedFieldImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ParameterDescriptionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ParameterImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ParameterSetImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletAppDescriptionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletDescriptionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletDisplayNameImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletEntityDescriptionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletInitParameterImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletParameterSetImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PreferenceDescriptionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/SecurityRoleRefDescriptionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/SecurityRoleRefImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/SecurityRoleRefSetImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ServletInitParameterImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ServletParameterSetImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/UserAttributeImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/UserAttributeRefImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/WebAppDescriptionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/WebAppDisplayNameImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/ContentTypeImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/ContentTypeSetImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/CustomPortletModeImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/CustomWindowStateImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/FragmentPortletDefinition.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletApplicationDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletApplicationLocalizedFieldImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletApplicationMetadataImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionListImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionLocalizedFieldImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionMetadataImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/preference/impl/FragmentPortletPreferenceSet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/preference/impl/PrefsPreference.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/preference/impl/PrefsPreferenceSetImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/servlet/impl/SecurityRoleImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/servlet/impl/SecurityRoleSetImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/servlet/impl/WebApplicationDefinitionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/window/impl/PortletWindowImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/window/impl/PortletWindowListImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/CSVtoCollectionFieldConversion.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/CSVtoPortletModeFieldConversion.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/CollectionDebugger.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/FieldConversionLog.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/LocaleFieldConversion.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/ObjectIDtoLongFieldConversion.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/ObjectIDtoStringFieldConversion.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletentity/ContentFragmentTestImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletentity/TestPortletEntityDAO.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/AbstractRegistryTest.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/TestPortletRegistryDAO.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/TestRegistryCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectAll.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectPart1a.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectPart1b.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectPart2a.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/request/MockRequestContextComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/AbstractRewriter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/BasicRewriter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/JetspeedClasspathRewriterController.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/JetspeedRewriterController.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/MutableAttributes.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/ParserAdaptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/Rewriter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RewriterController.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RewriterException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RulesetRewriter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RulesetRewriterImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/TicketParamRewriter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/WebContentRewriter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/SwingAttributes.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/SwingParserAdaptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/CallbackElementRemover.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/NeckoHTMLParserAdapter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/NekoParserAdaptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/URLRewriterFilter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/XMLAttributesWrapper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Attribute.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Identified.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Rule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Ruleset.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Tag.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/AttributeImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/IdentifiedImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/RuleImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/RulesetImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/TagImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/xml/SaxParserAdaptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/util/Streams.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/test/org/apache/jetspeed/rewriter/TestNekoRewriter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/test/org/apache/jetspeed/rewriter/TestRewriterController.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/test/org/apache/jetspeed/rewriter/UnitTestRewriter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/AbstractObjectHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/BaseParsedObject.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/HandlerFactoryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/URLToDocHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/pam/PortletApplicationHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/pam/PortletDefinitionHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/lucene/SearchEngineImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/lucene/SearchResultsImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/test/org/apache/jetspeed/search/TestSearch.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/PolicyWrapper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/SecurityHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/SecurityPolicies.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/activeauthentication/ActiveAuthenticationIdentityProviderImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/activeauthentication/IdentityTokenImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AggregationHierarchyResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AuthenticationProviderImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AuthenticationProviderProxyImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AuthorizationProviderImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/BaseHierarchyResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/BasePrincipalImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/DefaultLoginModule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GeneralizationHierarchyResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GroupImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GroupManagerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GroupPrincipalImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/JaasPolicyCoordinator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/LoginModuleProxyImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/PassiveCallbackHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/PermissionManagerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/PrincipalsSet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RdbmsPolicy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RoleImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RoleManagerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RolePrincipalImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/SecurityProviderImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserManagerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserPrincipalImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserSubjectPrincipalImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/ext/JBossLoginModule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalCredentialImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalGroupPrincipalImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalPermissionImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalPrincipalImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalRolePrincipalImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalUserPrincipalImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/AbstractInternalPasswordCredentialInterceptorImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/AlgorithmUpgradePBEPasswordService.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/CredentialPasswordValidatorsProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultCredentialHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultCredentialPasswordValidator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultGroupSecurityHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultPasswordCredentialImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultPasswordCredentialProvider.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultRoleSecurityHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultSecurityMappingHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultUserSecurityHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/EncodePasswordOnFirstLoadInterceptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/InternalPasswordCredentialInterceptorsProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapCredentialHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapGroupSecurityHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapRoleSecurityHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapSecurityMappingHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapUserSecurityHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LengthCredentialPasswordValidator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/MaxPasswordAuthenticationFailuresInterceptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/MessageDigestCredentialPasswordEncoder.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/PBEPasswordService.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/PasswordExpirationInterceptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/PasswordHistoryInterceptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/RegexCredentialPasswordValidator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ReservedWordsCredentialPasswordValidator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/SecurityAccessImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/SimpleCredentialPasswordValidator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ValidatePasswordOnLoadInterceptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/AbstractLdapDao.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/InitLdapSchema.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapBindingConfig.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapContextProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapGroupDaoImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapMemberShipDaoImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapMembershipDao.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapPrincipalDao.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapPrincipalDaoImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapReadOnlyPrincipalDao.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapRoleDaoImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserCredentialDao.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserCredentialDaoImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserPrincipalDao.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserPrincipalDaoImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/util/GullibleSSLSocketFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/util/PBEPasswordTool.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/util/test/AbstractSecurityTestcase.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestAggregationHierarchy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestAuthenticationProviderProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestGeneralizationHierarchy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestGroupManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestLoginModule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestPermissionManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestRdbmsPolicy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestRdbmsPolicyFolder.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestRoleManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestSecurityHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestUserManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestCredentialHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestCredentialPasswordEncoder.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestGroupSecurityHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestPasswordCredentialProvider.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestPasswordExpirationAndMaxAuthenticationFailuresInterceptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestPasswordHistoryInterceptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestRoleSecurityHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestSecurityMappingHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestUserSecurityHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/AbstractLdapTest.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/LdapDataHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapCredentialHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapGroupSecurityHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapRoleSecurityHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapSecurityMappingHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapUserCredentialDao.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapUserSecurityDao.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapUserSecurityHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/util/TestPBEPasswordTool.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedDDLApplication.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedDDLUtil.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerApplication.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerBase.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerSecondaryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSApplication.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSApplications.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSCapabilities.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSCapability.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClient.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClientCapabilities.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClientMimeTypes.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClients.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntities.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntity.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntityPreference.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntityPreferences.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSGroup.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSGroups.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSMediaType.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSMediaTypes.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSMimeTypes.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSNVPElement.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSNVPElements.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSNameValuePairs.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPWAttributes.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPermission.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPermissions.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPortlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPortlets.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPrincipalRule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPrincipalRules.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSProcessOrder.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSProfilingRule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSProfilingRules.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSRoles.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSRuleCriterion.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSRuleCriterions.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSecondaryData.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSeedData.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSimpleIDName.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSnapshot.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUser.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserAttributes.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserGroups.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserRoles.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserUsers.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUsers.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/PersistenceBrokerSSOProvider.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOContextImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOCookieImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOPrincipalImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOSiteImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/test/org/apache/jetspeed/sso/TestBasicSSO.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/test/org/apache/jetspeed/sso/TestSSOComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/audit/impl/ActivityBean.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/audit/impl/AuditActivityImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/AggregateStatisticsImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/BatchedStatistics.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/PortalStatisticsImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/StatisticsQueryCriteriaImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/UserStatsImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/test/org/apache/jetspeed/audit/TestAuditActivity.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/test/org/apache/jetspeed/statistics/TestStatistics.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/IFrameGenericPortlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/IFramePortlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/SSOIFramePortlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/SSOTicketPortlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/SSOWebContentPortlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/WebContentPortlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/sso/SSOProxyPortlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/webcontent/WebContentHistoryList.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/webcontent/WebContentHistoryPage.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/webcontent/WebContentResource.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/webapp-logging/src/java/org/apache/jetspeed/webapp/logging/IsolatedLog4JLogger.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/webapp-logging/src/java/org/apache/jetspeed/webapp/logging/Log4JConfigurator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/webapp-logging/src/java/org/apache/jetspeed/webapp/logging/velocity/CommonsLoggingLog4JLogSystem.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/CommonPortletServices.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/JetspeedActions.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/PortalContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/PortalReservedParameters.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/AdministrationEmailException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalAdministration.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalAuthenticationConfiguration.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalConfiguration.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalConfigurationConstants.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/RegistrationException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/Aggregator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/ContentDispatcher.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/ContentDispatcherCtrl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/ContentServerAdapter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/FailedToRenderFragmentException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PageAggregator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletAccessDeniedException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletAggregator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletContent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletRenderer.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletTrackingManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/RenderTrackable.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/RenderingJob.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/UnknownPortletDefinitionException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/UnrenderedContentException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/Worker.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/WorkerMonitor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AJAXRequest.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AJAXResponse.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AJAXService.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AjaxAction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AjaxBuilder.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AjaxRequestService.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/audit/AuditActivity.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/CacheElement.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/ContentCacheElement.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/ContentCacheKey.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/ContentCacheKeyGenerator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/DistributedCacheObject.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/JetspeedCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/JetspeedCacheEventListener.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/JetspeedContentCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/PortletWindowCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/file/FileCacheEntry.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/file/FileCacheEventListener.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/general/GeneralCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/Capabilities.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/CapabilitiesException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/Capability.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/CapabilityMap.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/Client.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/MediaType.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/MimeType.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/UnableToBuildCapabilityMapException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cluster/NodeInformation.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cluster/NodeManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/ComponentManagement.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/ComponentManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/ContainerManagement.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/Filter.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/LockFailedException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStore.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreAware.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreEvent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreEventListener.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreInitializationException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreRuntimeExcpetion.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/RemovalAware.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/Transaction.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/TransactionEvent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/TransactionEventListener.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/UpdateAware.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityAccessComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityNotDeletedException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityNotGeneratedException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityNotStoredException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/FailedToStorePortletDefinitionException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/PortletRegistry.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/RegistryEventListener.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/RegistryException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/invoker/PortletRequestResponseUnwrapper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/session/PortalSessionMonitor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/session/PortalSessionsManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/session/PortletApplicationSessionMonitor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/FailedToCreateNavStateException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/FailedToCreatePortalUrlException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/FailedToCreatedNavStateCodecException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/MutableNavigationalState.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/NavigationalState.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/NavigationalStateComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/url/BasePortalURL.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/url/PortalURL.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/window/FailedToCreateWindowException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/window/FailedToRetrievePortletWindow.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/window/PortletWindowAccessor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/Decoration.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/DecorationFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/LayoutDecoration.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/LayoutInfo.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/PageEditAccess.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/PathResolverCache.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/PortletDecoration.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/ResourceValidator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/Theme.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentEvent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentEventListener.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentObject.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentStatus.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/desktop/JetspeedDesktop.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/desktop/JetspeedDesktopContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/engine/Engine.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/engine/JetspeedEngineConstants.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/exception/JetspeedException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/exception/JetspeedRuntimeException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/factory/PortletFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/factory/PortletInstance.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/headerresource/HeaderResource.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/headerresource/HeaderResourceFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/headerresource/HeaderResourceLib.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/i18n/CurrentLocale.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/i18n/KeyedMessage.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/idgenerator/IdGenerator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/Coordinate.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/JetspeedPowerTool.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/JetspeedPowerToolFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/PortletActionSecurityBehavior.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/PortletPlacementContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/PortletPlacementException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/LocatorDescriptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/TemplateDescriptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/TemplateLocator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/TemplateLocatorException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/login/LoginConstants.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/MockHttpServletRequest.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/portlet/MockPortletRequest.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/portlet/MockPortletSession.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/request/MockRequestContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/BaseSecurityReference.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/ControllerFactoryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/SecurityReference.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/DublinCore.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/GenericMetadata.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/JetspeedServiceReference.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/LocalizedField.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDescription.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDescriptionSet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDisplayName.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDisplayNameSet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableLanguage.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/ParameterComposite.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecuredResource.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecurityConstraint.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecurityConstraints.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecurityRoleRefComposite.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/Support.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/UserAttribute.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/UserAttributeRef.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/ContentTypeComposite.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/ContentTypeSetComposite.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/CustomPortletMode.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/CustomWindowState.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/MutablePortletApplication.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/MutablePortletEntity.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/PortletApplication.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/PortletDefinitionComposite.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/PrincipalAware.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferenceComposite.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferenceSetComposite.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferenceValue.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferencesValidatorFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/servlet/MutableSecurityRole.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/servlet/MutableSecurityRoleSet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/servlet/MutableWebApplication.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/Folder.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/FolderNotFoundException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/InvalidFolderException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuDefinition.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuExcludeDefinition.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuIncludeDefinition.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuOptionsDefinition.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuSeparatorDefinition.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/Reset.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/BaseElement.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/ContentFragment.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/ContentPage.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Document.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Fragment.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Link.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Page.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/PageSecurity.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Reference.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/SecurityConstraintsDef.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/preference/FragmentPreference.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/FolderNotRemovedException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/FolderNotUpdatedException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/LinkNotRemovedException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/LinkNotUpdatedException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageManagerEventListener.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageNotFoundException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageNotRemovedException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageNotUpdatedException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentHandlerFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentNotFoundException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentTypeAlreadyRegisteredException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToDeleteDocumentException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToDeleteFolderException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToUpdateDocumentException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToUpdateFolderException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FolderHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/Node.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/NodeException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/NodeNotFoundException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/NodeSet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/UnsupportedDocumentTypeException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/Pipeline.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/PipelineException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/descriptor/PipelineDescriptorApi.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/descriptor/ValveDescriptorApi.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/valve/Valve.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/valve/ValveContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/Menu.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/MenuElement.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/MenuOption.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/MenuSeparator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/PortalSite.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/PortalSiteRequestContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/PortalSiteSessionContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portlet/PortletHeaderRequest.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portlet/PortletHeaderResponse.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portlet/SupportsHeaderPhase.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/FailedToCreateNodeException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/NodeAlreadyExistsException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/NodeDoesNotExistException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/PreferencesException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/PreferencesProvider.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/om/Node.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/om/Property.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/ProfileLocator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/ProfileLocatorProperty.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/Profiler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/ProfilerException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/PrincipalRule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/ProfileResolvers.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/ProfilingRule.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/RuleCriterion.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/RuleCriterionResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/request/RequestContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/request/RequestContextComponent.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/HandlerFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/ObjectHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/ParsedObject.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/SearchEngine.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/SearchResults.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AlgorithmUpgradePasswordEncodingService.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AuthenticationProvider.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AuthenticationProviderProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AuthorizationProvider.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/BasePrincipal.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/Group.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/GroupManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/GroupPrincipal.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/HierarchyResolver.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidDnException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidNewPasswordException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidPasswordException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidUidException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/LoginModuleProxy.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PasswordAlreadyUsedException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PasswordCredential.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PasswordEncodingService.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PermissionManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/Role.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/RoleManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/RolePrincipal.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/SecurityAccessController.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/SecurityException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/SecurityProvider.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/User.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/UserManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/UserPrincipal.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/UserSubjectPrincipal.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/activeauthentication/ActiveAuthenticationIdentityProvider.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/activeauthentication/IdentityToken.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalCredential.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalGroupPrincipal.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalPermission.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalPrincipal.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalRolePrincipal.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalUserPrincipal.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/AlgorithmUpgradeCredentialPasswordEncoder.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/CredentialHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/CredentialPasswordEncoder.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/CredentialPasswordValidator.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/GroupSecurityHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/InternalPasswordCredentialInterceptor.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/PasswordCredentialProvider.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/RoleSecurityHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/SecurityAccess.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/SecurityMappingHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/UserSecurityHandler.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/serializer/JetspeedSerializer.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/serializer/JetspeedSerializerFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/serializer/SerializerException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOContext.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOCookie.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOPrincipal.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOProvider.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOSite.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/statistics/PortalStatistics.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/statistics/UserStats.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/deploy/DeployFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/pamanager/PortletApplicationManagement.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/ApplicationServerManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/ApplicationServerManagerResult.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/userinfo/UserAttributeRetrievalException.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/userinfo/UserAttributeSource.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/userinfo/UserInfoManager.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/util/FileSystemHelper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/util/Queue.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/ActionLayoutPortlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/LayoutPortlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/MultiColumnPortlet.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/util/ResourceBundleFactory.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/test/org/apache/jetspeed/portlets/layout/TestColumnLayout.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/maven-plugin/src/java/org/apache/jetspeed/dbutil/HSQLServer.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/maven-plugin/src/java/org/apache/jetspeed/dbutil/ScriptUtil.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/jetspeed/portlets/tags/PortletTreeControlTag.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/webapp/admin/TreeControl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/webapp/admin/TreeControlNode.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/webapp/admin/TreeControlTag.java -------------- next part -------------- Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/AntInstallerCheckConnection.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/AntInstallerCheckConnection.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/AntInstallerCheckConnection.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,19 +17,21 @@ package org.apache.jetspeed.anttasks; /** - * @version $Id: AntInstallerCheckConnection.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: AntInstallerCheckConnection.java 516448 2007-03-09 16:25:47Z + * ate $ + * */ import org.apache.tools.ant.BuildException; import org.apache.tools.ant.taskdefs.JDBCTask; public class AntInstallerCheckConnection extends JDBCTask { + public void setDriver(String driver) { super.setDriver(driver); } - + public void execute() throws BuildException { setDriver(getProject().getUserProperty("jdbcDriverClass")); @@ -42,7 +44,7 @@ } catch (Exception e) { - throw new RuntimeException("Connection failed",e); + throw new RuntimeException("Connection failed", e); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/ArchetypeDescriptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/ArchetypeDescriptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/ArchetypeDescriptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -35,27 +35,38 @@ * ArchetypeDescriptor * * This Ant task is used to generate a Maven2 Archetype Descriptor file. - * + * * @author Randy Watler * @version $Id: $ */ public class ArchetypeDescriptor extends Task { + private String header; + private String artifactId; + private Boolean allowPartial = new Boolean(true); + private File baseDir; + private File destFile; + private Reference sourcesRefId; + private Reference resourcesRefId; + private Reference testSourcesRefId; + private Reference testResourcesRefId; + private Reference siteResourcesRefId; /** * Set archetype descriptor header text - * - * @param header archetype header text + * + * @param header + * archetype header text */ public void addText(String header) { @@ -64,8 +75,9 @@ /** * Set archetype artifact id. - * - * @param artifactId archetype artifact id + * + * @param artifactId + * archetype artifact id */ public void setArtifactid(String artifactId) { @@ -74,8 +86,9 @@ /** * Set archetype partial rules to support execution in existing projects. - * - * @param allowPartial archetype allow partial setting + * + * @param allowPartial + * archetype allow partial setting */ public void setAllowpartial(Boolean allowPartial) { @@ -84,8 +97,9 @@ /** * Set archetype base directory for all sources/resources. - * - * @param baseDir archtype source/resource base directory + * + * @param baseDir + * archtype source/resource base directory */ public void setBasedir(File baseDir) { @@ -94,8 +108,9 @@ /** * Set archetype descriptor destination file. - * - * @param destFile archetype descriptor file to generate + * + * @param destFile + * archetype descriptor file to generate */ public void setDestfile(File destFile) { @@ -104,8 +119,9 @@ /** * Set archetype sources refid. - * - * @param sourcesRefId archetype sources + * + * @param sourcesRefId + * archetype sources */ public void setSourcesrefid(Reference sourcesRefId) { @@ -114,8 +130,9 @@ /** * Set archetype resources fileset refid. - * - * @param resourcesRefId archetype resources + * + * @param resourcesRefId + * archetype resources */ public void setResourcesrefid(Reference resourcesRefId) { @@ -124,8 +141,9 @@ /** * Set archetype test sources fileset refid. - * - * @param testSourcesRefId archetype test sources + * + * @param testSourcesRefId + * archetype test sources */ public void setTestsourcesrefid(Reference testSourcesRefId) { @@ -134,8 +152,9 @@ /** * Set archetype test resources fileset refid. - * - * @param testResourcesRefId archetype test resources + * + * @param testResourcesRefId + * archetype test resources */ public void setTestresourcesrefid(Reference testResourcesRefId) { @@ -144,8 +163,9 @@ /** * Set archetype site resources fileset refid. - * - * @param siteResourcesRefId archetype site resources + * + * @param siteResourcesRefId + * archetype site resources */ public void setSiteresourcesrefid(Reference siteResourcesRefId) { @@ -154,23 +174,24 @@ /** * Executes task to generate desciptor file. - * + * * @throws BuildException */ public void execute() throws BuildException { // basic validation - if ((artifactId == null) || (baseDir == null) || (destFile == null)) - { - throw new BuildException("required artifactid, basedir, or destfile attribute missing", getLocation()); - } + if ((artifactId == null) || (baseDir == null) || (destFile == null)) { throw new BuildException( + "required artifactid, basedir, or destfile attribute missing", + getLocation()); } // reference sources/resources List sources = archetypeFiles(sourcesRefId, "sourcesrefid"); List resources = archetypeFiles(resourcesRefId, "resourcesrefid"); List testSources = archetypeFiles(testSourcesRefId, "testsourcesrefid"); - List testResources = archetypeFiles(testResourcesRefId, "testresourcesrefid"); - List siteResources = archetypeFiles(siteResourcesRefId, "siteresourcesrefid"); + List testResources = archetypeFiles(testResourcesRefId, + "testresourcesrefid"); + List siteResources = archetypeFiles(siteResourcesRefId, + "siteresourcesrefid"); // write archetype descriptor file PrintWriter writer = null; @@ -184,7 +205,8 @@ } // write descriptor to destination file - writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(destFile), "UTF-8")); + writer = new PrintWriter(new OutputStreamWriter( + new FileOutputStream(destFile), "UTF-8")); writer.println(""); if (header != null) { @@ -192,7 +214,8 @@ } writer.println(""); writer.println(" " + artifactId + ""); - writer.println(" " + allowPartial + ""); + writer.println(" " + allowPartial + + ""); writeFiles(writer, "sources", "source", sources); writeFiles(writer, "resources", "resource", resources); writeFiles(writer, "testSources", "source", testSources); @@ -202,7 +225,8 @@ } catch (IOException ioe) { - throw new BuildException("unable to write decriptor", ioe, getLocation()); + throw new BuildException("unable to write decriptor", ioe, + getLocation()); } finally { @@ -213,31 +237,37 @@ } // log task success - int archetypeSourcesCount = sources.size() + resources.size() + testSources.size() + testResources.size() + siteResources.size(); - log("generated " + destFile + " including " + archetypeSourcesCount + " source/resource files"); + int archetypeSourcesCount = sources.size() + resources.size() + + testSources.size() + testResources.size() + + siteResources.size(); + log("generated " + destFile + " including " + archetypeSourcesCount + + " source/resource files"); } /** * Utility to read fileset refid attributes. - * - * @param refId attribute refid - * @param name attribute name + * + * @param refId + * attribute refid + * @param name + * attribute name * @return list of String file paths * @throws BuildException */ - private List archetypeFiles(Reference refId, String name) throws BuildException + private List archetypeFiles(Reference refId, String name) + throws BuildException { List archetypeFiles = new ArrayList(); if (refId != null) { // access fileset from refid - if (!(refId.getReferencedObject(getProject()) instanceof AbstractFileSet)) - { - throw new BuildException(name + " attribute must reference a fileset", getLocation()); - } - AbstractFileSet fileSet = (AbstractFileSet)refId.getReferencedObject(getProject()); - DirectoryScanner directoryScanner = fileSet.getDirectoryScanner(getProject()); - String [] files = directoryScanner.getIncludedFiles(); + if (!(refId.getReferencedObject(getProject()) instanceof AbstractFileSet)) { throw new BuildException( + name + " attribute must reference a fileset", getLocation()); } + AbstractFileSet fileSet = (AbstractFileSet) refId + .getReferencedObject(getProject()); + DirectoryScanner directoryScanner = fileSet + .getDirectoryScanner(getProject()); + String[] files = directoryScanner.getIncludedFiles(); if ((files != null) && (files.length > 0)) { String basePath = canonicalPath(baseDir); @@ -248,12 +278,14 @@ String archetypePath = files[i]; if (basePath != null) { - File file = new File(fileSet.getDir(getProject()), files[i]); + File file = new File(fileSet.getDir(getProject()), + files[i]); String filePath = canonicalPath(file); if ((filePath != null) && filePath.startsWith(basePath)) { // path relative to baseDir - archetypePath = filePath.substring(basePath.length()); + archetypePath = filePath.substring(basePath + .length()); if (archetypePath.startsWith("/")) { archetypePath = archetypePath.substring(1); @@ -270,8 +302,9 @@ /** * Utility to get canonical file path - * - * @param file file to convert to canonical path + * + * @param file + * file to convert to canonical path * @return canonical path */ private String canonicalPath(File file) @@ -289,14 +322,19 @@ /** * Utility to write archetype descriptor file lists. - * - * @param writer descriptor writer - * @param collectionElementName collection element name - * @param elementName file element name - * @param files list of String file paths + * + * @param writer + * descriptor writer + * @param collectionElementName + * collection element name + * @param elementName + * file element name + * @param files + * list of String file paths * @throws IOException */ - private void writeFiles(PrintWriter writer, String collectionElementName, String elementName, List files) throws IOException + private void writeFiles(PrintWriter writer, String collectionElementName, + String elementName, List files) throws IOException { // write file list to descriptor if (!files.isEmpty()) @@ -305,7 +343,8 @@ Iterator fileIter = files.iterator(); while (fileIter.hasNext()) { - writer.println(" <" + elementName + ">" + (String)fileIter.next() + ""); + writer.println(" <" + elementName + ">" + + (String) fileIter.next() + ""); } writer.println(" "); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/ExecuteJavaSQL.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/ExecuteJavaSQL.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/ExecuteJavaSQL.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * */ @@ -32,120 +32,114 @@ public class ExecuteJavaSQL { - /** - * @param args - */ - public static void main(String[] args) - { - final class TEMPSQL extends SQLExec { - public TEMPSQL() - { - setProject(new Project()); - getProject().init(); - super.setTaskType("sql"); - super.setTaskName("sql"); - super.target = new Target(); - } - } + /** + * @param args + */ + public static void main(String[] args) + { + final class TEMPSQL extends SQLExec + { - boolean autocommit = true; - String driver = null; - String url = null; - String userid = null; - String password = null; - String source = null; - String onError = null; - - - - if (args == null) - throw new IllegalArgumentException("ExecuteSQL needs to know what to do - no arguments provided!!! "); + public TEMPSQL() + { + setProject(new Project()); + getProject().init(); + super.setTaskType("sql"); + super.setTaskName("sql"); + super.target = new Target(); + } + } - + boolean autocommit = true; + String driver = null; + String url = null; + String userid = null; + String password = null; + String source = null; + String onError = null; + + if (args == null) + throw new IllegalArgumentException( + "ExecuteSQL needs to know what to do - no arguments provided!!! "); + // Parse all the command-line arguments for (int n = 0; n < args.length; n++) { - String argument = args[n].toLowerCase().trim(); - - if (argument.startsWith("driver=")) - { - driver = args[n].substring("driver=".length()); - } - else - if (argument.startsWith("url=")) - { - url = args[n].substring("url=".length()); - } - else - if (argument.startsWith("userid=")) - { - userid = args[n].substring("userid=".length()); - } - else - if (argument.startsWith("password=")) - { - password = args[n].substring("password=".length()); - } - else - if (argument.startsWith("src=")) - { - source = args[n].substring("src=".length()); - } - else - if (argument.startsWith("autocommit=")) - { - String s = args[n].substring("src=".length()); - try - { - autocommit = Boolean.valueOf(s).booleanValue(); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - else - if (argument.startsWith("onerror=")) - { - onError = args[n].substring("onerror=".length()); - } - else - { - throw new IllegalArgumentException("Unknown argument: " - + args[n]); - } + String argument = args[n].toLowerCase().trim(); + + if (argument.startsWith("driver=")) + { + driver = args[n].substring("driver=".length()); + } + else if (argument.startsWith("url=")) + { + url = args[n].substring("url=".length()); + } + else if (argument.startsWith("userid=")) + { + userid = args[n].substring("userid=".length()); + } + else if (argument.startsWith("password=")) + { + password = args[n].substring("password=".length()); + } + else if (argument.startsWith("src=")) + { + source = args[n].substring("src=".length()); + } + else if (argument.startsWith("autocommit=")) + { + String s = args[n].substring("src=".length()); + try + { + autocommit = Boolean.valueOf(s).booleanValue(); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + else if (argument.startsWith("onerror=")) + { + onError = args[n].substring("onerror=".length()); + } + else + { + throw new IllegalArgumentException("Unknown argument: " + + args[n]); + } } - TEMPSQL sql = new TEMPSQL(); - - sql.setAutocommit(autocommit); - sql.setDriver(driver); - sql.setUrl(url); - sql.setUserid(userid); - sql.setPassword(password); - File sqlFile = null; - try - { - sqlFile = new File(source); - } - catch (Exception e) - { - throw new IllegalArgumentException("File parameter " + source + " invalid : " + e.getLocalizedMessage()); - } - sql.setSrc(sqlFile); - try - { - SQLExec.OnError errorHandling = new SQLExec.OnError(); - errorHandling.setValue(onError); - sql.setOnerror(errorHandling); - } - catch (Exception e) - { - throw new IllegalArgumentException("Error handling parameter " + onError + " invalid : " + e.getLocalizedMessage()); - } - + TEMPSQL sql = new TEMPSQL(); - - sql.execute(); + sql.setAutocommit(autocommit); + sql.setDriver(driver); + sql.setUrl(url); + sql.setUserid(userid); + sql.setPassword(password); + File sqlFile = null; + try + { + sqlFile = new File(source); + } + catch (Exception e) + { + throw new IllegalArgumentException("File parameter " + source + + " invalid : " + e.getLocalizedMessage()); + } + sql.setSrc(sqlFile); + try + { + SQLExec.OnError errorHandling = new SQLExec.OnError(); + errorHandling.setValue(onError); + sql.setOnerror(errorHandling); + } + catch (Exception e) + { + throw new IllegalArgumentException("Error handling parameter " + + onError + " invalid : " + e.getLocalizedMessage()); + } - } + sql.execute(); + + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/ExecuteSQL.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/ExecuteSQL.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/ExecuteSQL.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,99 +16,101 @@ */ package org.apache.jetspeed.anttasks; - import java.sql.Connection; import java.sql.SQLException; +import java.util.Properties; + import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.SQLExec; -import java.util.Properties; -import org.apache.tools.ant.Project;; +; + public class ExecuteSQL extends SQLExec -{ +{ - - public void execute() throws BuildException - { - - - try - { - System.out.println("Executing SQL statement"); - super.execute(); - } - catch (Exception e) - { - throw new BuildException(e, getLocation()); - } - finally - { - if (StartDerby.getConnection(getProject()) != null) - { - try - { - if (!(StartDerby.getConnection(getProject()).isClosed())) - StartDerby.getConnection(getProject()).close(); - } - catch (Exception e1) - { - // just a safetyguard - } - StartDerby.setConnection(getProject(),null); - } - } - } - + public void execute() throws BuildException + { - /** + try + { + System.out.println("Executing SQL statement"); + super.execute(); + } + catch (Exception e) + { + throw new BuildException(e, getLocation()); + } + finally + { + if (StartDerby.getConnection(getProject()) != null) + { + try + { + if (!(StartDerby.getConnection(getProject()).isClosed())) + StartDerby.getConnection(getProject()).close(); + } + catch (Exception e1) + { + // just a safetyguard + } + StartDerby.setConnection(getProject(), null); + } + } + } + + /** * Creates a new Connection as using the driver, url, userid and password * specified. - * + * * The calling method is responsible for closing the connection. - * + * * @return Connection the newly created connection. - * @throws BuildException if the UserId/Password/Url is not set or there - * is no suitable driver or the driver fails to load. + * @throws BuildException + * if the UserId/Password/Url is not set or there is no suitable + * driver or the driver fails to load. */ - protected Connection getConnection() throws BuildException - { - if (StartDerby.getDriver(getProject()) == null) - throw new BuildException("Derby driver not established!", getLocation()); - // reuse excisting connection: - if (StartDerby.getConnection(getProject())!= null) - { - System.out.println("Connection already established"); - return StartDerby.getConnection(getProject()); - } - // do almost the same as in the orignial JDBC tasks: - - if (getUrl() == null) { - throw new BuildException("Url attribute must be set!", getLocation()); + protected Connection getConnection() throws BuildException + { + if (StartDerby.getDriver(getProject()) == null) + throw new BuildException("Derby driver not established!", + getLocation()); + // reuse excisting connection: + if (StartDerby.getConnection(getProject()) != null) + { + System.out.println("Connection already established"); + return StartDerby.getConnection(getProject()); } - try { + // do almost the same as in the orignial JDBC tasks: + if (getUrl() == null) { throw new BuildException( + "Url attribute must be set!", getLocation()); } + try + { + log("connecting to " + getUrl(), Project.MSG_VERBOSE); Properties info = new Properties(); - if (getUserId() != null) - info.put("user", getUserId()); - if (getPassword() != null) - info.put("password", getPassword()); - - Connection conn = StartDerby.getDriver(getProject()).connect(getUrl(), info); - if (conn == null) { + if (getUserId() != null) info.put("user", getUserId()); + if (getPassword() != null) info.put("password", getPassword()); + + Connection conn = StartDerby.getDriver(getProject()).connect( + getUrl(), info); + if (conn == null) + { // Driver doesn't understand the URL throw new SQLException("No suitable Driver for " + getUrl()); } conn.setAutoCommit(isAutocommit()); - System.out.println("Connection to " + getUrl() + " established"); - StartDerby.setConnection(getProject(),conn); + System.out.println("Connection to " + getUrl() + " established"); + StartDerby.setConnection(getProject(), conn); return conn; - } catch (SQLException e) { + } + catch (SQLException e) + { throw new BuildException(e, getLocation()); } } - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StartDatabase.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StartDatabase.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StartDatabase.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,57 +16,57 @@ */ package org.apache.jetspeed.anttasks; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.taskdefs.JDBCTask; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; + +import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; +import org.apache.tools.ant.taskdefs.JDBCTask; -public class StartDatabase - extends JDBCTask { +public class StartDatabase extends JDBCTask +{ - - - - public void execute() - throws BuildException + public void execute() throws BuildException { - if (StartDerby.getDriver(getProject()) == null) - throw new BuildException("Derby driver not established!", getLocation()); - // reuse excisting connection: - if (StartDerby.getConnection(getProject()) != null) - { - System.out.println("Connection already established"); - return; - } - // do almost the same as in the orignial JDBC tasks: - - if (getUrl() == null) { - throw new BuildException("Url attribute must be set!", getLocation()); - } - try { + if (StartDerby.getDriver(getProject()) == null) + throw new BuildException("Derby driver not established!", + getLocation()); + // reuse excisting connection: + if (StartDerby.getConnection(getProject()) != null) + { + System.out.println("Connection already established"); + return; + } + // do almost the same as in the orignial JDBC tasks: - log("connecting to " + getUrl(), Project.MSG_VERBOSE); - Properties info = new Properties(); - if (getUserId() != null) - info.put("user", getUserId()); - if (getPassword() != null) - info.put("password", getPassword()); - - Connection conn = StartDerby.getDriver(getProject()).connect(getUrl(), info); - if (conn == null) { - // Driver doesn't understand the URL - throw new SQLException("No suitable Driver for " + getUrl()); - } + if (getUrl() == null) { throw new BuildException( + "Url attribute must be set!", getLocation()); } + try + { - conn.setAutoCommit(isAutocommit()); - StartDerby.setConnection(getProject(),conn); - System.out.println("Derby connected to " + getUrl()); - return; - } catch (SQLException e) { - throw new BuildException(e, getLocation()); - } - } - + log("connecting to " + getUrl(), Project.MSG_VERBOSE); + Properties info = new Properties(); + if (getUserId() != null) info.put("user", getUserId()); + if (getPassword() != null) info.put("password", getPassword()); + + Connection conn = StartDerby.getDriver(getProject()).connect( + getUrl(), info); + if (conn == null) + { + // Driver doesn't understand the URL + throw new SQLException("No suitable Driver for " + getUrl()); + } + + conn.setAutoCommit(isAutocommit()); + StartDerby.setConnection(getProject(), conn); + System.out.println("Derby connected to " + getUrl()); + return; + } + catch (SQLException e) + { + throw new BuildException(e, getLocation()); + } + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StartDerby.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StartDerby.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StartDerby.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,112 +16,126 @@ */ package org.apache.jetspeed.anttasks; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Task; +import java.sql.Connection; import java.sql.Driver; -import java.sql.Connection; -import org.apache.tools.ant.Project; import java.util.Hashtable; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Task; -public class StartDerby - extends Task { - -// public static Driver DERBY_DRIVER = null; -// public static Connection DERBY_CONNECTION = null; +public class StartDerby extends Task +{ - public void execute() - throws BuildException { - try { - if (StartDerby.getDriver(getProject()) != null) - { - System.out.println("Derby Driver has ALREADY BEEN ESTABLISHED!"); - return; - } - StartDerby.setDriver(getProject(),(java.sql.Driver)(Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance())); - System.out.println("Derby Driver has been started!"); - } catch (Exception e) { - System.out.println( - "Derby could not start. This is most likely " + - "due to missing Derby JAR files. Please check your classpath" + - "and try again."); - throw new BuildException(e); - } - } - - public static void setDriver(Project project, Driver d) - { - try - { - if (d != null) - { - project.addReference("DRIVER",d); - System.out.println("Driver reference in Project set "); - } - else - { - Hashtable h = project.getReferences(); - h.remove("DRIVER"); - System.out.println("Driver reference in Project removed "); - } - } - catch (Exception e) - { - System.out.println("Could't SET Driver reference in Project : " + e.getLocalizedMessage()); - - } - } - public static Driver getDriver(Project project) - { - try - { - Object o = project.getReference("DRIVER"); - if (o != null) - return (Driver)o; - else return null; - } - catch (Exception e) - { - System.out.println("Could't get Driver reference in Project : " + e.getLocalizedMessage()); - return null; - } - } - - public static void setConnection(Project project, Connection d) - { - try - { - if (d != null) - { - project.addReference("Connection",d); - System.out.println("Connection reference in Project set "); - } - else - { - Hashtable h = project.getReferences(); - h.remove("Connection"); - System.out.println("Connection reference in Project removed "); - } - } - catch (Exception e) - { - System.out.println("Could't SET Connection reference in Project : " + e.getLocalizedMessage()); - - } - } - public static Connection getConnection(Project project) - { - try - { - Object o = project.getReference("Connection"); - if (o != null) - return (Connection)o; - else return null; - } - catch (Exception e) - { - System.out.println("Could't get Connection reference in Project : " + e.getLocalizedMessage()); - return null; - } - } + // public static Driver DERBY_DRIVER = null; + // public static Connection DERBY_CONNECTION = null; + + public void execute() throws BuildException + { + try + { + if (StartDerby.getDriver(getProject()) != null) + { + System.out + .println("Derby Driver has ALREADY BEEN ESTABLISHED!"); + return; + } + StartDerby.setDriver(getProject(), (java.sql.Driver) (Class + .forName("org.apache.derby.jdbc.EmbeddedDriver") + .newInstance())); + System.out.println("Derby Driver has been started!"); + } + catch (Exception e) + { + System.out + .println("Derby could not start. This is most likely " + + "due to missing Derby JAR files. Please check your classpath" + + "and try again."); + throw new BuildException(e); + } + } + + public static void setDriver(Project project, Driver d) + { + try + { + if (d != null) + { + project.addReference("DRIVER", d); + System.out.println("Driver reference in Project set "); + } + else + { + Hashtable h = project.getReferences(); + h.remove("DRIVER"); + System.out.println("Driver reference in Project removed "); + } + } + catch (Exception e) + { + System.out.println("Could't SET Driver reference in Project : " + + e.getLocalizedMessage()); + + } + } + + public static Driver getDriver(Project project) + { + try + { + Object o = project.getReference("DRIVER"); + if (o != null) + return (Driver) o; + else + return null; + } + catch (Exception e) + { + System.out.println("Could't get Driver reference in Project : " + + e.getLocalizedMessage()); + return null; + } + } + + public static void setConnection(Project project, Connection d) + { + try + { + if (d != null) + { + project.addReference("Connection", d); + System.out.println("Connection reference in Project set "); + } + else + { + Hashtable h = project.getReferences(); + h.remove("Connection"); + System.out.println("Connection reference in Project removed "); + } + } + catch (Exception e) + { + System.out.println("Could't SET Connection reference in Project : " + + e.getLocalizedMessage()); + + } + } + + public static Connection getConnection(Project project) + { + try + { + Object o = project.getReference("Connection"); + if (o != null) + return (Connection) o; + else + return null; + } + catch (Exception e) + { + System.out.println("Could't get Connection reference in Project : " + + e.getLocalizedMessage()); + return null; + } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StopDatabase.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StopDatabase.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StopDatabase.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,47 +16,49 @@ */ package org.apache.jetspeed.anttasks; +import java.sql.SQLException; + import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; -import java.sql.SQLException; +public class StopDatabase extends Task +{ -public class StopDatabase - extends Task { + private String url; - private String url; + public String getUrl() + { + return url; + } - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public void execute() - throws BuildException { - if (StartDerby.getDriver(getProject()) == null) - { - System.out.println("Derby Driver has NOT BEEN ESTABLISHED!"); - return ; // already closed; - } - if (StartDerby.getConnection(getProject()) != null) - { - try - { - StartDerby.getConnection(getProject()).close(); - System.out.println("Derby Connection successfully closed!"); - } - catch (SQLException e) - { - throw new BuildException(e, getLocation()); - } - StartDerby.setConnection(getProject(),null); - - } - else - System.out.println("Derby Connection has already been closed!"); - } - + public void setUrl(String url) + { + this.url = url; + } + + public void execute() throws BuildException + { + if (StartDerby.getDriver(getProject()) == null) + { + System.out.println("Derby Driver has NOT BEEN ESTABLISHED!"); + return; // already closed; + } + if (StartDerby.getConnection(getProject()) != null) + { + try + { + StartDerby.getConnection(getProject()).close(); + System.out.println("Derby Connection successfully closed!"); + } + catch (SQLException e) + { + throw new BuildException(e, getLocation()); + } + StartDerby.setConnection(getProject(), null); + + } + else + System.out.println("Derby Connection has already been closed!"); + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StopDerby.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StopDerby.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/ant-tasks/src/java/org/apache/jetspeed/anttasks/StopDerby.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,55 +16,54 @@ */ package org.apache.jetspeed.anttasks; -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Task; import java.sql.SQLException; import java.util.Properties; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Task; -public class StopDerby - extends Task { - +public class StopDerby extends Task +{ - public void execute() - throws BuildException + public void execute() throws BuildException { - if (StartDerby.getDriver(getProject()) == null) - { - System.out.println("Derby Driver has NOT BEEN ESTABLISHED!"); - return ; // already closed; - } - if (StartDerby.getConnection(getProject()) != null) - { - try - { - StartDerby.getConnection(getProject()).close(); - System.out.println("Derby Connection successfully closed!"); - } - catch (SQLException e) - { - throw new BuildException(e, getLocation()); - } - StartDerby.setConnection(getProject(),null); - - } - else - System.out.println("Derby Connection has already been closed!"); - -// getConnection("jdbc:derby:;shutdown=true"); + if (StartDerby.getDriver(getProject()) == null) + { + System.out.println("Derby Driver has NOT BEEN ESTABLISHED!"); + return; // already closed; + } + if (StartDerby.getConnection(getProject()) != null) + { + try + { + StartDerby.getConnection(getProject()).close(); + System.out.println("Derby Connection successfully closed!"); + } + catch (SQLException e) + { + throw new BuildException(e, getLocation()); + } + StartDerby.setConnection(getProject(), null); + + } + else + System.out.println("Derby Connection has already been closed!"); + + // getConnection("jdbc:derby:;shutdown=true"); Properties info = new Properties(); - info.put("shutdown",Boolean.TRUE); + info.put("shutdown", Boolean.TRUE); System.out.println("Derby Driver sutting down!"); try { - StartDerby.getDriver(getProject()).connect("jdbc:derby:",info); - } catch (Exception e) - { - System.out.println("Derby has been shutdown!"); + StartDerby.getDriver(getProject()).connect("jdbc:derby:", info); } + catch (Exception e) + { + System.out.println("Derby has been shutdown!"); + } - StartDerby.setDriver(getProject(),null); + StartDerby.setDriver(getProject(), null); System.out.println("Derby Driver has been shutdown!"); - } - + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/app-servers/security/jboss/src/java/org/apache/jetspeed/appservers/security/jboss/JetspeedSecurityService.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/app-servers/security/jboss/src/java/org/apache/jetspeed/appservers/security/jboss/JetspeedSecurityService.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/app-servers/security/jboss/src/java/org/apache/jetspeed/appservers/security/jboss/JetspeedSecurityService.java 2008-05-16 01:54:54 UTC (rev 940) @@ -41,8 +41,9 @@ private GenericApplicationContext ctx; /** - * Create a new security service. The service's implementation is based on a Spring application that is assembled from the configuration files in + * Create a new security service. The service's implementation is based on a + * Spring application that is + * assembled from the configuration files in * META-INF/jboss-secsvc. */ public JetspeedSecurityService() @@ -57,25 +58,29 @@ ConnectionPoolDescriptor cpd = new ConnectionPoolDescriptor(); cpd.setConnectionFactory(ConnectionFactoryManagedImpl.class); jcd.setConnectionPoolDescriptor(cpd); - ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); + ConnectionRepository cr = MetadataManager.getInstance() + .connectionRepository(); cr.addDescriptor(jcd); } // Instatiating application ctx = new GenericApplicationContext(); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx); - xmlReader.loadBeanDefinitions(new ClassPathResource("META-INF/jboss-secsvc/jboss-security-service.xml")); + xmlReader.loadBeanDefinitions(new ClassPathResource( + "META-INF/jboss-secsvc/jboss-security-service.xml")); ctx.refresh(); } private JdbcConnectionDescriptor findJcd() { // Try to find JCD - ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); + ConnectionRepository cr = MetadataManager.getInstance() + .connectionRepository(); return cr.getDescriptor(new PBKey(JCD_ALIAS)); } /** - * Set the JNDI name of the DataSource to be used to access the database. + * Set the JNDI name of the DataSource to be used to access + * the database. * * @param jndiName */ @@ -86,28 +91,28 @@ { Context initialContext = new InitialContext(); DataSource ds = (DataSource) initialContext.lookup(jndiName); - (new JdbcMetadataUtils()).fillJCDFromDataSource(jcd, ds, null, null); + (new JdbcMetadataUtils()) + .fillJCDFromDataSource(jcd, ds, null, null); } catch (NamingException e) { - throw (IllegalArgumentException) (new IllegalArgumentException("Data source \"" + jndiName - + "\" not found in JNDI: " + e.getMessage())).initCause(e); + throw (IllegalArgumentException) (new IllegalArgumentException( + "Data source \"" + jndiName + "\" not found in JNDI: " + + e.getMessage())).initCause(e); } jcd.setDatasourceName(jndiName); } /** - * Get the JNDI name of the DataSource used to access the database. + * Get the JNDI name of the DataSource used to access the + * database. * * @return jndiName */ public String getDataSourceJndiName() { JdbcConnectionDescriptor jcd = findJcd(); - if (jcd == null) - { - return null; - } + if (jcd == null) { return null; } return jcd.getDatasourceName(); } @@ -116,7 +121,8 @@ */ public UserManager getUserManager() { - UserManager um = (UserManager) ctx.getBean("org.apache.jetspeed.security.UserManager"); + UserManager um = (UserManager) ctx + .getBean("org.apache.jetspeed.security.UserManager"); return um; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/app-servers/security/jboss/src/java/org/apache/jetspeed/appservers/security/jboss/JetspeedSecurityServiceMBean.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/app-servers/security/jboss/src/java/org/apache/jetspeed/appservers/security/jboss/JetspeedSecurityServiceMBean.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/app-servers/security/jboss/src/java/org/apache/jetspeed/appservers/security/jboss/JetspeedSecurityServiceMBean.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,14 +22,16 @@ { /** - * Set the JNDI name of the DataSource to be used to access the database. + * Set the JNDI name of the DataSource to be used to access + * the database. * * @param jndiName */ void setDataSourceJndiName(String jndiName); /** - * Get the JNDI name of the DataSource used to access the database. + * Get the JNDI name of the DataSource used to access the + * database. * * @return jndiName */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/app-servers/security/jboss/src/java/org/apache/jetspeed/appservers/security/jboss/LoginModule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/app-servers/security/jboss/src/java/org/apache/jetspeed/appservers/security/jboss/LoginModule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/app-servers/security/jboss/src/java/org/apache/jetspeed/appservers/security/jboss/LoginModule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,7 +33,8 @@ import org.apache.jetspeed.security.impl.ext.JBossLoginModule; /** - * A login module that uses the JetspeedSecurityService MBean for authentication and role assignment. + * A login module that uses the JetspeedSecurityService MBean for authentication + * and role assignment. */ public class LoginModule implements javax.security.auth.spi.LoginModule { @@ -43,12 +44,15 @@ private JBossLoginModule delegee = null; /** - * Helper for delaying the creation of the JBossLoginModule. We cannot access the security service MBean before - * initialize has been called, but need the user manager in the constructor of JBossLoginModule. The - * constructor that takes the user manager as argument is protected (and right so), so we need this helper. + * Helper for delaying the creation of the JBossLoginModule. We cannot + * access the security service MBean before initialize has + * been called, but need the user manager in the constructor of + * JBossLoginModule. The constructor that takes the user manager as argument + * is protected (and right so), so we need this helper. */ private class LoginModuleDelegee extends JBossLoginModule { + public LoginModuleDelegee(UserManager userManager) { super(userManager); @@ -56,12 +60,14 @@ } /** - * Create a new login module. The module looks up the JetspeedSecurityService MBean and uses it to actually perform + * Create a new login module. The module looks up the + * JetspeedSecurityService MBean and uses it to actually perform * authentication and role lookup. *

      - * Note that the MBean must be available when this login module is instantiated. Therefore, if the MBean (the SAR) - * is deployed after JBoss has been started, this login module must be created lazily by using the JBoss login - * module proxy in login-config.xml. + * Note that the MBean must be available when this login module is + * instantiated. Therefore, if the MBean (the SAR) is deployed after JBoss + * has been started, this login module must be created lazily by using the + * JBoss login module proxy in login-config.xml. * *

            *  <application-policy name = "sample">
      @@ -89,32 +95,39 @@
           {
               try
               {
      -            MBeanServer server = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0);
      +            MBeanServer server = (MBeanServer) MBeanServerFactory
      +                    .findMBeanServer(null).get(0);
                   ObjectName serviceName = new ObjectName(securityService);
      -            return (UserManager) server.invoke(serviceName, "getUserManager", null, null);
      +            return (UserManager) server.invoke(serviceName, "getUserManager",
      +                    null, null);
               }
               catch (MalformedObjectNameException e)
               {
      -            throw (IllegalStateException) ((new IllegalStateException(e.getMessage())).initCause(e));
      +            throw (IllegalStateException) ((new IllegalStateException(e
      +                    .getMessage())).initCause(e));
               }
               catch (InstanceNotFoundException e)
               {
      -            throw (IllegalStateException) ((new IllegalStateException(e.getMessage())).initCause(e));
      +            throw (IllegalStateException) ((new IllegalStateException(e
      +                    .getMessage())).initCause(e));
               }
               catch (ReflectionException e)
               {
      -            throw (IllegalStateException) ((new IllegalStateException(e.getMessage())).initCause(e));
      +            throw (IllegalStateException) ((new IllegalStateException(e
      +                    .getMessage())).initCause(e));
               }
               catch (MBeanException e)
               {
      -            throw (IllegalStateException) ((new IllegalStateException(e.getMessage())).initCause(e));
      +            throw (IllegalStateException) ((new IllegalStateException(e
      +                    .getMessage())).initCause(e));
               }
           }
       
           /**
            * @see javax.security.auth.spi.LoginModule#initialize()
            */
      -    public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options)
      +    public void initialize(Subject subject, CallbackHandler callbackHandler,
      +            Map sharedState, Map options)
           {
               securityService = (String) options.get("securityService");
               delegee = new LoginModuleDelegee(getUserManager());
      @@ -122,7 +135,7 @@
       
           }
       
      -    /** 
      +    /**
            * @see javax.security.auth.spi.LoginModule#abort()
            */
           public boolean abort() throws LoginException
      @@ -130,7 +143,7 @@
               return delegee.abort();
           }
       
      -    /** 
      +    /**
            * @see javax.security.auth.spi.LoginModule#commit()
            */
           public boolean commit() throws LoginException
      @@ -138,7 +151,7 @@
               return delegee.commit();
           }
       
      -    /** 
      +    /**
            * @see javax.security.auth.spi.LoginModule#login()
            */
           public boolean login() throws LoginException
      @@ -146,7 +159,7 @@
               return delegee.login();
           }
       
      -    /** 
      +    /**
            * @see javax.security.auth.spi.LoginModule#logout()
            */
           public boolean logout() throws LoginException
      
      Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/Jetspeed.java
      ===================================================================
      --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/Jetspeed.java	2008-05-16 01:52:50 UTC (rev 939)
      +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/Jetspeed.java	2008-05-16 01:54:54 UTC (rev 940)
      @@ -25,26 +25,25 @@
       import org.apache.jetspeed.request.RequestContext;
       
       /**
      - * Jetspeed environment
      - * 
      - * Provides an easy way to access the current running environment - * of jetspeed. - * + * Jetspeed environment
      Provides an easy way to access the current running + * environment of jetspeed. + * * @author David Sean Taylor * @version $Id: Jetspeed.java 552657 2007-07-03 03:57:47Z taylor $ */ public class Jetspeed { + private static Engine engine = null; + /** - * Shuts down the currently running instance of the portal - * Engine. + * Shuts down the currently running instance of the portal Engine. + * * @throws JetspeedException */ public static void shutdown() throws JetspeedException { - if (engine != null) - engine.shutdown(); + if (engine != null) engine.shutdown(); } public static Engine getEngine() @@ -54,29 +53,25 @@ public static PortalContext getContext() { - if (engine == null) - { - throw new NullPointerException("The engine is null, have you called createEngine() yet?"); - } + if (engine == null) { throw new NullPointerException( + "The engine is null, have you called createEngine() yet?"); } return engine.getContext(); } /** - * Given a application relative path, returns the real path relative to the application root - * + * Given a application relative path, returns the real path relative to the + * application root + * */ public static String getRealPath(String path) { - if (engine == null) - { - return null; - } + if (engine == null) { return null; } return engine.getRealPath(path); } /** - * Delegtes to the current Engine to retreive the RequestContext - * appropriate for the current thread. + * Delegtes to the current Engine to retreive the RequestContext appropriate + * for the current thread. * * @see org.apache.jetspeed.engine.Engine#getCurrentRequestContext() * @@ -84,12 +79,12 @@ */ public static RequestContext getCurrentRequestContext() { - if (engine != null) - return engine.getCurrentRequestContext(); + if (engine != null) return engine.getCurrentRequestContext(); return null; } - // TODO We need to get this from the Engine and the engine should get it from the configuration. + // TODO We need to get this from the Engine and the engine should get it + // from the configuration. public static Locale getDefaultLocale() { @@ -98,8 +93,7 @@ public static ComponentManager getComponentManager() { - if (engine == null) - return null; + if (engine == null) return null; return engine.getComponentManager(); } @@ -107,13 +101,14 @@ { Jetspeed.engine = engine; } - + public static PortalConfiguration getConfiguration() { - ComponentManager manager = getComponentManager(); + ComponentManager manager = getComponentManager(); if (manager != null) - return (PortalConfiguration)manager.getComponent("PortalConfiguration"); - return null; + return (PortalConfiguration) manager + .getComponent("PortalConfiguration"); + return null; } - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/aggregator/CurrentWorkerContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/aggregator/CurrentWorkerContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/aggregator/CurrentWorkerContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,36 +27,44 @@ */ public final class CurrentWorkerContext { - private static ThreadLocal currentWorkerContext = - new ThreadLocal() { - protected synchronized Object initialValue() { - return new Hashtable(); - } - }; - - private static ThreadLocal parallelRenderingMode = - new ThreadLocal() { - protected synchronized Object initialValue() { - return new boolean [] { false }; - } - }; - + + private static ThreadLocal currentWorkerContext = new ThreadLocal() + { + + protected synchronized Object initialValue() + { + return new Hashtable(); + } + }; + + private static ThreadLocal parallelRenderingMode = new ThreadLocal() + { + + protected synchronized Object initialValue() + { + return new boolean[] + {false}; + } + }; + private CurrentWorkerContext() { } /** - * Returns an Enumeration containing the names of the attributes available to this Thread. - * This method returns an empty Enumeration if the thread has no attributes available to it. + * Returns an Enumeration containing the names of the attributes available + * to this Thread. This method returns an empty Enumeration if the thread + * has no attributes available to it. */ public static Enumeration getAttributeNames() { return ((Hashtable) currentWorkerContext.get()).keys(); } - /** + /** * @return an attribute in the current Thread - * @param attrName Locale for this Thread + * @param attrName + * Locale for this Thread */ public static Object getAttribute(String name) { @@ -64,24 +72,30 @@ } /** - * Stores an attribute in this Thread. - *
      - * @param name - a String specifying the name of the attribute - * @param o - the Object to be stored + * Stores an attribute in this Thread.
      + * + * @param name - + * a String specifying the name of the attribute + * @param o - + * the Object to be stored */ public static void setAttribute(String name, Object o) { - if (o != null) { + if (o != null) + { ((Hashtable) currentWorkerContext.get()).put(name, o); - } else { + } + else + { removeAttribute(name); } } /** - * Removes an attribute from this Thread. - *
      - * @param name - a String specifying the name of the attribute + * Removes an attribute from this Thread.
      + * + * @param name - + * a String specifying the name of the attribute */ public static void removeAttribute(String name) { @@ -95,14 +109,14 @@ { ((Hashtable) currentWorkerContext.get()).clear(); } - + public static void setParallelRenderingMode(boolean parallelMode) { - ((boolean []) parallelRenderingMode.get())[0] = parallelMode; + ((boolean[]) parallelRenderingMode.get())[0] = parallelMode; } public static boolean getParallelRenderingMode() { - return ((boolean []) parallelRenderingMode.get())[0]; + return ((boolean[]) parallelRenderingMode.get())[0]; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerConstants.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerConstants.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerConstants.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,15 +24,26 @@ */ public class ContainerConstants { + public final static String PORTLET_ACTION = "javax.portlet.action"; + public final static String PORTLET_REQUEST = "javax.portlet.request"; + public final static String PORTLET_RESPONSE = "javax.portlet.response"; + public final static String PORTLET_CONFIG = "javax.portlet.config"; + public final static String PORTAL_CONTEXT = "org.apache.jetspeed.context"; + public final static String METHOD_ID = "org.apache.jetspeed.method"; + public final static String PORTLET = "org.apache.jetspeed.portlet"; + public final static String PORTLET_NAME = "org.apache.jetspeed.portlet.name"; + public final static Integer METHOD_RENDER = new Integer(1); + public final static Integer METHOD_ACTION = new Integer(3); + public final static Integer METHOD_NOOP = new Integer(5); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerInfo.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerInfo.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerInfo.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,16 +20,18 @@ /** * Container Information - * + * * @author Shinsuke Sugaya */ public final class ContainerInfo { + public static final ResourceBundle CONTAINER_INFO; static { - CONTAINER_INFO = ResourceBundle.getBundle("org.apache.jetspeed.container.resources.ContainerInfo"); + CONTAINER_INFO = ResourceBundle + .getBundle("org.apache.jetspeed.container.resources.ContainerInfo"); } public static final String getPortletContainerName() @@ -49,19 +51,22 @@ public static final int getMajorSpecificationVersion() { - return Integer.parseInt(CONTAINER_INFO.getString("javax.portlet.version.major")); + return Integer.parseInt(CONTAINER_INFO + .getString("javax.portlet.version.major")); } public static final int getMinorSpecificationVersion() { - return Integer.parseInt(CONTAINER_INFO.getString("javax.portlet.version.minor")); + return Integer.parseInt(CONTAINER_INFO + .getString("javax.portlet.version.minor")); } public static final String getServerInfo() { StringBuffer sb = new StringBuffer(getPortletContainerName()).append( - CONTAINER_INFO.getString("jetspeed.container.separator")).append(getPortletContainerMajorVersion()) - .append(".").append(getPortletContainerMinorVersion()); + CONTAINER_INFO.getString("jetspeed.container.separator")) + .append(getPortletContainerMajorVersion()).append(".").append( + getPortletContainerMinorVersion()); return sb.toString(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerRequest.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerRequest.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerRequest.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,26 +16,28 @@ */ package org.apache.jetspeed.container; +import javax.portlet.PortletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; -import javax.portlet.PortletRequest; import org.apache.pluto.om.portlet.PortletDefinition; /** - * The container request wrappers the servlet request and is used - * within the container to communicate to the invoked servlet. - * + * The container request wrappers the servlet request and is used within the + * container to communicate to the invoked servlet. + * * @author David Sean Taylor * @version $Id: ContainerRequest.java 516448 2007-03-09 16:25:47Z ate $ */ public class ContainerRequest extends HttpServletRequestWrapper { + protected PortletDefinition portletDef; + protected PortletRequest portletRequest; - public ContainerRequest(HttpServletRequest httpRequest, - PortletDefinition portletDef) + public ContainerRequest(HttpServletRequest httpRequest, + PortletDefinition portletDef) { super(httpRequest); this.portletDef = portletDef; @@ -57,4 +59,3 @@ } } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerResponse.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerResponse.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/ContainerResponse.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,28 +16,31 @@ */ package org.apache.jetspeed.container; +import javax.portlet.ActionResponse; +import javax.portlet.RenderResponse; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; -import javax.portlet.RenderResponse; -import javax.portlet.ActionResponse; import org.apache.pluto.om.portlet.PortletDefinition; /** - * The container response wrappers the servlet response and is used - * within the container to communicate to the invoked servlet. - * + * The container response wrappers the servlet response and is used within the + * container to communicate to the invoked servlet. + * * @author David Sean Taylor * @version $Id: ContainerResponse.java 516448 2007-03-09 16:25:47Z ate $ */ public class ContainerResponse extends HttpServletResponseWrapper { + RenderResponse renderResponse; + ActionResponse actionResponse; + PortletDefinition portletDef; public ContainerResponse(HttpServletResponse response, - PortletDefinition portletDef) + PortletDefinition portletDef) { super(response); this.portletDef = portletDef; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/InternalPortletConfig.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/InternalPortletConfig.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/InternalPortletConfig.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,12 +21,14 @@ /** * This interface defines the internal methods used on the Portlet Config. * - * + * * @author David Sean Taylor * @version $Id: InternalPortletConfig.java 516448 2007-03-09 16:25:47Z ate $ */ public interface InternalPortletConfig { - PortletDefinition getPortletDefinition(); - void setPortletDefinition(PortletDefinition pd); + + PortletDefinition getPortletDefinition(); + + void setPortletDefinition(PortletDefinition pd); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/InternalPortletContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/InternalPortletContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/InternalPortletContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,18 +20,17 @@ import org.apache.pluto.om.portlet.PortletApplicationDefinition; - - /** * This interface defines the internal methods used on the Portlet Context. * - * + * * @author David Sean Taylor * @version $Id: InternalPortletContext.java 516448 2007-03-09 16:25:47Z ate $ */ public interface InternalPortletContext { + public ServletContext getServletContext(); - - public PortletApplicationDefinition getApplication(); + + public PortletApplicationDefinition getApplication(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/JetspeedContainerServlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/JetspeedContainerServlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/JetspeedContainerServlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -39,82 +39,103 @@ import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; +import org.apache.jetspeed.aggregator.CurrentWorkerContext; import org.apache.jetspeed.container.session.PortalSessionsManager; import org.apache.jetspeed.request.RequestContext; import org.apache.jetspeed.services.JetspeedPortletServices; import org.apache.jetspeed.services.PortletServices; import org.apache.jetspeed.tools.pamanager.PortletApplicationManagement; import org.apache.jetspeed.util.DirectoryHelper; -import org.apache.jetspeed.aggregator.CurrentWorkerContext; /** * Jetspeed Container entry point. - * + * * @author David Sean Taylor - * @version $Id: JetspeedContainerServlet.java 593180 2007-11-08 15:00:35Z weaver $ + * @version $Id: JetspeedContainerServlet.java 593180 2007-11-08 15:00:35Z + * weaver $ */ -public class JetspeedContainerServlet extends HttpServlet +public class JetspeedContainerServlet extends HttpServlet { - private String contextName; + + private String contextName; + private boolean started = false; - private Timer startTimer = null; + + private Timer startTimer = null; + private PortalSessionsManager psm; + private String contextPath; // ------------------------------------------------------------------- // I N I T I A L I Z A T I O N // ------------------------------------------------------------------- private static final String JCS = "JetspeedContainerServlet: "; - private static final String INIT_START_MSG = JCS + "starting initialization of Portlet Application at: "; - private static final String TRY_START_MSG = JCS + "attemping to start Portlet Application at: "; - private static final String STARTED_MSG = JCS + "started Portlet Application at: "; - private static final String INIT_FAILED_MSG = JCS + "initialization failed for Portlet Application at: "; - private static final String INIT_DONE_MSG = JCS + "initialization done for Portlet Application at: "; - private static final String STOP_MSG = JCS + "shutting down portlet application at: "; - private static final String STOP_FAILED_MSG = JCS + "shutting down error for portlet application at: "; - - public synchronized final void init(ServletConfig config) throws ServletException + + private static final String INIT_START_MSG = JCS + + "starting initialization of Portlet Application at: "; + + private static final String TRY_START_MSG = JCS + + "attemping to start Portlet Application at: "; + + private static final String STARTED_MSG = JCS + + "started Portlet Application at: "; + + private static final String INIT_FAILED_MSG = JCS + + "initialization failed for Portlet Application at: "; + + private static final String INIT_DONE_MSG = JCS + + "initialization done for Portlet Application at: "; + + private static final String STOP_MSG = JCS + + "shutting down portlet application at: "; + + private static final String STOP_FAILED_MSG = JCS + + "shutting down error for portlet application at: "; + + public synchronized final void init(ServletConfig config) + throws ServletException { synchronized (this.getClass()) - { + { super.init(config); - + ServletContext context = getServletContext(); started = false; - startTimer = null; - contextName = config.getInitParameter("contextName"); + startTimer = null; + contextName = config.getInitParameter("contextName"); contextPath = config.getInitParameter("contextPath"); if (null == contextName || contextName.length() == 0) { contextName = null; // just to make sure for the destroy method - - throw new ServletException(JCS + "Portlet Application contextName not supplied in Init Parameters."); + + throw new ServletException( + JCS + + "Portlet Application contextName not supplied in Init Parameters."); } - + if (null == contextPath || contextPath.length() == 0) { - contextPath = "/"+contextName; + contextPath = "/" + contextName; } - else if(!contextPath.startsWith("/")) - { - throw new ServletException(JCS + "Portlet Application contextPath must start with a \"/\"."); - } - - + else if (!contextPath.startsWith("/")) { throw new ServletException( + JCS + + "Portlet Application contextPath must start with a \"/\"."); } + String paDir = context.getRealPath("/"); - if ( paDir == null ) - { - throw new ServletException(JCS + " Initialization of PortletApplication at "+contextName+" without access to its real path not supported"); - } + if (paDir == null) { throw new ServletException(JCS + + " Initialization of PortletApplication at " + contextName + + " without access to its real path not supported"); } - context.log(INIT_START_MSG + contextName); - System.out.println(INIT_START_MSG + contextName); + context.log(INIT_START_MSG + contextName); + System.out.println(INIT_START_MSG + contextName); try - { - startPortletApplication(context, paDir, Thread.currentThread().getContextClassLoader()); + { + startPortletApplication(context, paDir, Thread.currentThread() + .getContextClassLoader()); } catch (Exception e) { @@ -129,47 +150,57 @@ } } - private void startPortletApplication(final ServletContext context, final String paDir, final ClassLoader paClassLoader) - throws ServletException + private void startPortletApplication(final ServletContext context, + final String paDir, final ClassLoader paClassLoader) + throws ServletException { -/* TODO: Ate Douma, 2005-03-25 - Under fusion, this call always results in a javax.naming.NameNotFoundException: "Name jdbc is not bound in this Context" - but when started from a separate (timer) Thread, even with only a delay of 1ms, it works again. - I don't have any clue what is the cause of this or how to solve it, thus for now I disabled starting directly - - if (attemptStart(context, contextName, paDir, paClassLoader)) - { - started = true; - return; - } -*/ - final String START_DELAYED_MSG = JCS + "Could not yet start portlet application at: "+contextName+". Starting back ground thread to start when the portal comes online."; + /* + * TODO: Ate Douma, 2005-03-25 Under fusion, this call always results in + * a javax.naming.NameNotFoundException: "Name jdbc is not bound in this + * Context" but when started from a separate (timer) Thread, even with + * only a delay of 1ms, it works again. I don't have any clue what is + * the cause of this or how to solve it, thus for now I disabled + * starting directly + * + * if (attemptStart(context, contextName, paDir, paClassLoader)) { + * started = true; return; } + */ + final String START_DELAYED_MSG = JCS + + "Could not yet start portlet application at: " + + contextName + + ". Starting back ground thread to start when the portal comes online."; context.log(START_DELAYED_MSG); startTimer = new Timer(true); - startTimer.schedule( - new TimerTask() { - public void run() { - synchronized(contextName) - { - if (startTimer != null) + startTimer.schedule(new TimerTask() + { + + public void run() + { + synchronized (contextName) + { + if (startTimer != null) + { + if (attemptStart(context, contextName, contextPath, + paDir, paClassLoader)) { - if (attemptStart(context, contextName, contextPath, paDir, paClassLoader)) { startTimer.cancel(); startTimer = null; - } else { + } + else + { context.log(START_DELAYED_MSG); - } } - } } - }, -// 10000, Setting delay to 1ms, see TODO comment above - 1, - 10000); + } + } + }, + // 10000, Setting delay to 1ms, see TODO comment above + 1, 10000); } - private boolean attemptStart(ServletContext context, String contextName, String contextPath, String paDir, ClassLoader paClassLoader) + private boolean attemptStart(ServletContext context, String contextName, + String contextPath, String paDir, ClassLoader paClassLoader) { try { @@ -177,15 +208,18 @@ PortletServices services = JetspeedPortletServices.getSingleton(); if (services != null) { - PortletApplicationManagement pam = - (PortletApplicationManagement)services.getService("PAM"); + PortletApplicationManagement pam = (PortletApplicationManagement) services + .getService("PAM"); if (pam != null && pam.isStarted()) { - DirectoryHelper paDirHelper = new DirectoryHelper(new File(paDir)); - pam.startPortletApplication(contextName, contextPath, paDirHelper, paClassLoader); + DirectoryHelper paDirHelper = new DirectoryHelper(new File( + paDir)); + pam.startPortletApplication(contextName, contextPath, + paDirHelper, paClassLoader); started = true; - psm = (PortalSessionsManager)services.getService(PortalSessionsManager.SERVICE_NAME); + psm = (PortalSessionsManager) services + .getService(PortalSessionsManager.SERVICE_NAME); context.log(STARTED_MSG + contextPath); return true; @@ -198,82 +232,100 @@ return true; // don't try again } return false; - } - + } + // ------------------------------------------------------------------- - // R E Q U E S T P R O C E S S I N G + // R E Q U E S T P R O C E S S I N G // ------------------------------------------------------------------- /** * The primary method invoked when the Jetspeed servlet is executed. - * - * @param request Servlet request. - * @param ressponse Servlet response. - * @exception IOException a servlet exception. - * @exception ServletException a servlet exception. + * + * @param request + * Servlet request. + * @param ressponse + * Servlet response. + * @exception IOException + * a servlet exception. + * @exception ServletException + * a servlet exception. */ - public final void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException + public final void doGet(HttpServletRequest request, + HttpServletResponse response) throws IOException, ServletException { String portletName = null; Integer method = ContainerConstants.METHOD_NOOP; Portlet portlet = null; boolean destroyPortlet = false; boolean isParallelMode = false; - + try { isParallelMode = CurrentWorkerContext.getParallelRenderingMode(); if (isParallelMode) { - method = (Integer) CurrentWorkerContext.getAttribute(ContainerConstants.METHOD_ID); + method = (Integer) CurrentWorkerContext + .getAttribute(ContainerConstants.METHOD_ID); } else { - method = (Integer) request.getAttribute(ContainerConstants.METHOD_ID); + method = (Integer) request + .getAttribute(ContainerConstants.METHOD_ID); } - if (method == ContainerConstants.METHOD_NOOP) - { - return; - } + if (method == ContainerConstants.METHOD_NOOP) { return; } if (isParallelMode) { - portlet = (Portlet) CurrentWorkerContext.getAttribute(ContainerConstants.PORTLET); - portletName = (String) CurrentWorkerContext.getAttribute(ContainerConstants.PORTLET_NAME); + portlet = (Portlet) CurrentWorkerContext + .getAttribute(ContainerConstants.PORTLET); + portletName = (String) CurrentWorkerContext + .getAttribute(ContainerConstants.PORTLET_NAME); } else { - portlet = (Portlet)request.getAttribute(ContainerConstants.PORTLET); - portletName = (String)request.getAttribute(ContainerConstants.PORTLET_NAME); + portlet = (Portlet) request + .getAttribute(ContainerConstants.PORTLET); + portletName = (String) request + .getAttribute(ContainerConstants.PORTLET_NAME); request.removeAttribute(ContainerConstants.PORTLET); } if (method == ContainerConstants.METHOD_ACTION) { - ActionRequest actionRequest = (ActionRequest) request.getAttribute(ContainerConstants.PORTLET_REQUEST); - ActionResponse actionResponse = (ActionResponse) request.getAttribute(ContainerConstants.PORTLET_RESPONSE); - // inject the current request into the actionRequest handler (o.a.j.engine.servlet.ServletRequestImpl) - ((HttpServletRequestWrapper)((HttpServletRequestWrapper)actionRequest).getRequest()).setRequest(request); + ActionRequest actionRequest = (ActionRequest) request + .getAttribute(ContainerConstants.PORTLET_REQUEST); + ActionResponse actionResponse = (ActionResponse) request + .getAttribute(ContainerConstants.PORTLET_RESPONSE); + // inject the current request into the actionRequest handler + // (o.a.j.engine.servlet.ServletRequestImpl) + ((HttpServletRequestWrapper) ((HttpServletRequestWrapper) actionRequest) + .getRequest()).setRequest(request); portlet.processAction(actionRequest, actionResponse); } else if (method == ContainerConstants.METHOD_RENDER) { RenderRequest renderRequest = null; - RenderResponse renderResponse = null; + RenderResponse renderResponse = null; if (isParallelMode) { - renderRequest = (RenderRequest) CurrentWorkerContext.getAttribute(ContainerConstants.PORTLET_REQUEST); - renderResponse = (RenderResponse) CurrentWorkerContext.getAttribute(ContainerConstants.PORTLET_RESPONSE); + renderRequest = (RenderRequest) CurrentWorkerContext + .getAttribute(ContainerConstants.PORTLET_REQUEST); + renderResponse = (RenderResponse) CurrentWorkerContext + .getAttribute(ContainerConstants.PORTLET_RESPONSE); } else { - renderRequest = (RenderRequest) request.getAttribute(ContainerConstants.PORTLET_REQUEST); - renderResponse = (RenderResponse) request.getAttribute(ContainerConstants.PORTLET_RESPONSE); - } - // inject the current request into the renderRequest handler (o.a.j.engine.servlet.ServletRequestImpl) - ((HttpServletRequestWrapper)((HttpServletRequestWrapper)renderRequest).getRequest()).setRequest(request); + renderRequest = (RenderRequest) request + .getAttribute(ContainerConstants.PORTLET_REQUEST); + renderResponse = (RenderResponse) request + .getAttribute(ContainerConstants.PORTLET_RESPONSE); + } + // inject the current request into the renderRequest handler + // (o.a.j.engine.servlet.ServletRequestImpl) + ((HttpServletRequestWrapper) ((HttpServletRequestWrapper) renderRequest) + .getRequest()).setRequest(request); portlet.render(renderRequest, renderResponse); } @@ -282,16 +334,17 @@ } catch (Throwable t) { - if ( t instanceof UnavailableException ) + if (t instanceof UnavailableException) { // destroy the portlet in the finally clause destroyPortlet = true; } - + if (method != ContainerConstants.METHOD_ACTION) { ServletContext context = getServletContext(); - context.log(JCS + "Error rendering portlet \"" + portletName + "\": " + t.toString(), t); + context.log(JCS + "Error rendering portlet \"" + portletName + + "\": " + t.toString(), t); try { String errorTemplate = getInitParameter("portal.error.page"); @@ -301,16 +354,19 @@ } if (null != context.getResource(errorTemplate)) { - RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(errorTemplate); + RequestDispatcher dispatcher = getServletContext() + .getRequestDispatcher(errorTemplate); request.setAttribute("e", t); StringWriter stackTrace = new StringWriter(); t.printStackTrace(new PrintWriter(stackTrace)); - request.setAttribute("stacktrace", stackTrace.toString()); + request.setAttribute("stacktrace", stackTrace + .toString()); dispatcher.include(request, response); } else { - displayPortletNotAvailableMessage(t, response, portletName); + displayPortletNotAvailableMessage(t, response, + portletName); } } catch (Throwable e) @@ -324,17 +380,17 @@ } else { - if ( t instanceof RuntimeException ) + if (t instanceof RuntimeException) { - throw (RuntimeException)t; + throw (RuntimeException) t; } - else if (t instanceof IOException ) + else if (t instanceof IOException) { - throw (IOException)t; + throw (IOException) t; } else if (t instanceof ServletException) { - throw (ServletException)t; + throw (ServletException) t; } else { @@ -344,7 +400,7 @@ } finally { - if ( destroyPortlet ) + if (destroyPortlet) { // portlet throwed UnavailableException: take it out of service try @@ -353,21 +409,26 @@ } catch (Exception e) { - // never mind, it won't be used anymore. + // never mind, it won't be used anymore. } } if (psm != null) { - RequestContext rc = (RequestContext)request.getAttribute(RequestContext.REQUEST_PORTALENV); - psm.checkMonitorSession(contextName,rc.getRequest().getSession(),request.getSession(false)); + RequestContext rc = (RequestContext) request + .getAttribute(RequestContext.REQUEST_PORTALENV); + psm.checkMonitorSession(contextName, rc.getRequest() + .getSession(), request.getSession(false)); } } } - private void displayPortletNotAvailableMessage(Throwable t, HttpServletResponse response, String portletName) - throws IOException + private void displayPortletNotAvailableMessage(Throwable t, + HttpServletResponse response, String portletName) + throws IOException { - getServletContext().log(JCS + "Error rendering JetspeedContainerServlet error page: " + t.toString(), t); + getServletContext().log( + JCS + "Error rendering JetspeedContainerServlet error page: " + + t.toString(), t); PrintWriter directError; try { @@ -376,67 +437,76 @@ catch (IllegalStateException e) { // Happens if get writer is already been called. - directError = new PrintWriter(new OutputStreamWriter(response.getOutputStream())); + directError = new PrintWriter(new OutputStreamWriter(response + .getOutputStream())); } - directError.write("Portlet is Not Available: " + portletName + "
      Reason: " + t.getMessage()); - //t.printStackTrace(directError); - directError.close(); + directError.write("Portlet is Not Available: " + portletName + + "
      Reason: " + t.getMessage()); + // t.printStackTrace(directError); + directError.close(); } - + /** * In this application doGet and doPost are the same thing. - * - * @param req Servlet request. - * @param res Servlet response. - * @exception IOException a servlet exception. - * @exception ServletException a servlet exception. + * + * @param req + * Servlet request. + * @param res + * Servlet response. + * @exception IOException + * a servlet exception. + * @exception ServletException + * a servlet exception. */ - public final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException + public final void doPost(HttpServletRequest req, HttpServletResponse res) + throws IOException, ServletException { doGet(req, res); } // ------------------------------------------------------------------- - // S E R V L E T S H U T D O W N + // S E R V L E T S H U T D O W N // ------------------------------------------------------------------- public final void destroy() { - if ( contextName != null ) - { - synchronized (contextName) + if (contextName != null) { - if ( startTimer != null ) - { - startTimer.cancel(); - startTimer = null; - } - else if ( started ) - { - started = false; - PortletServices services = JetspeedPortletServices.getSingleton(); - if (services != null) + synchronized (contextName) { - PortletApplicationManagement pam = - (PortletApplicationManagement)services.getService("PAM"); + if (startTimer != null) + { + startTimer.cancel(); + startTimer = null; + } + else if (started) + { + started = false; + PortletServices services = JetspeedPortletServices + .getSingleton(); + if (services != null) + { + PortletApplicationManagement pam = (PortletApplicationManagement) services + .getService("PAM"); - if (pam != null) - { - getServletContext().log(STOP_MSG + contextName); - try - { - pam.stopPortletApplication(contextName); + if (pam != null) + { + getServletContext().log(STOP_MSG + contextName); + try + { + pam.stopPortletApplication(contextName); + } + catch (Exception e) + { + getServletContext().log( + STOP_FAILED_MSG + contextName, e); + } + } } - catch (Exception e) - { - getServletContext().log(STOP_FAILED_MSG + contextName, e); - } + contextName = null; + psm = null; } } - contextName = null; - psm = null; - } } - } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/JetspeedPortletConfig.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/JetspeedPortletConfig.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/JetspeedPortletConfig.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,19 +32,24 @@ /** * Implements the Portlet API Portlet Config class - * + * * @author David Sean Taylor * @author Scott T. Weaver * @version $Id: JetspeedPortletConfig.java 516448 2007-03-09 16:25:47Z ate $ */ -public class JetspeedPortletConfig implements PortletConfig, InternalPortletConfig +public class JetspeedPortletConfig implements PortletConfig, + InternalPortletConfig { - // private static final Log log = LogFactory.getLog(JetspeedPortletConfig.class); - + + // private static final Log log = + // LogFactory.getLog(JetspeedPortletConfig.class); + private PortletContext portletContext; + private PortletDefinition portletDefinition; - public JetspeedPortletConfig(PortletContext portletContext, PortletDefinition portletEntity) + public JetspeedPortletConfig(PortletContext portletContext, + PortletDefinition portletEntity) { this.portletContext = portletContext; this.portletDefinition = portletEntity; @@ -63,31 +68,31 @@ public ResourceBundle getResourceBundle(Locale locale) { LanguageSet languageSet = portletDefinition.getLanguageSet(); - + Language lang = languageSet.get(locale); - + if (lang == null) { Locale defaultLocale = languageSet.getDefaultLocale(); lang = languageSet.get(defaultLocale); } - + return lang.getResourceBundle(); } public String getInitParameter(java.lang.String name) { - if ( name == null ) - { - throw new IllegalArgumentException("Required parameter name is null"); - } - //if (log.isDebugEnabled()) log.debug("Getting init parameter for: " + name); + if (name == null) { throw new IllegalArgumentException( + "Required parameter name is null"); } + // if (log.isDebugEnabled()) log.debug("Getting init parameter for: " + + // name); ParameterSet parameters = portletDefinition.getInitParameterSet(); Parameter param = parameters.get(name); if (param != null) { - // if (log.isDebugEnabled()) log.debug("Param: [[name," + name + "], [value, " + param.getValue() + "]]"); + // if (log.isDebugEnabled()) log.debug("Param: [[name," + name + "], + // [value, " + param.getValue() + "]]"); return param.getValue(); } @@ -98,7 +103,10 @@ { return new java.util.Enumeration() { - private ParameterSet parameters = portletDefinition.getInitParameterSet(); + + private ParameterSet parameters = portletDefinition + .getInitParameterSet(); + private Iterator iterator = parameters.iterator(); public boolean hasMoreElements() @@ -119,10 +127,10 @@ public void setPortletDefinition(PortletDefinition pd) { - this.portletDefinition = pd; + this.portletDefinition = pd; } - - // internal portlet config implementation + + // internal portlet config implementation public PortletDefinition getPortletDefinition() { return portletDefinition; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/JetspeedPortletContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/JetspeedPortletContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/JetspeedPortletContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,11 +21,10 @@ import java.util.Enumeration; import java.util.Iterator; -import javax.servlet.ServletContext; -import javax.servlet.RequestDispatcher; - import javax.portlet.PortletContext; import javax.portlet.PortletRequestDispatcher; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; import org.apache.jetspeed.dispatcher.JetspeedRequestDispatcher; import org.apache.jetspeed.om.common.JetspeedServiceReference; @@ -36,26 +35,30 @@ /** * Implements the Portlet API Portlet Context class - * + * * TODO: on LOCAL apps, we need to merge in web.xml props. See PLT 10.3 - * + * * @author David Sean Taylor * @version $Id: JetspeedPortletContext.java 516448 2007-03-09 16:25:47Z ate $ */ -public class JetspeedPortletContext implements PortletContext, InternalPortletContext +public class JetspeedPortletContext implements PortletContext, + InternalPortletContext { + /** * The path to the Local Portlet Apps directory */ public static final String LOCAL_PA_ROOT = "/WEB-INF/apps"; private ServletContext servletContext; + private MutablePortletApplication application; - public JetspeedPortletContext(ServletContext servletContext, PortletApplicationDefinition application) + public JetspeedPortletContext(ServletContext servletContext, + PortletApplicationDefinition application) { this.servletContext = servletContext; - this.application = (MutablePortletApplication)application; + this.application = (MutablePortletApplication) application; } public int getMajorVersion() @@ -75,11 +78,12 @@ return servletContext.getResourcePaths(path); } - public javax.portlet.PortletRequestDispatcher getRequestDispatcher(String path) + public javax.portlet.PortletRequestDispatcher getRequestDispatcher( + String path) { String localizedPath = localizePath(path, this.application); RequestDispatcher rd = null; - + try { rd = servletContext.getRequestDispatcher(localizedPath); @@ -90,10 +94,7 @@ } // TODO: factory - if ( rd != null ) - { - return new JetspeedRequestDispatcher(rd); - } + if (rd != null) { return new JetspeedRequestDispatcher(rd); } return null; } @@ -102,7 +103,7 @@ // TODO: localize name RequestDispatcher rd = null; - + try { rd = servletContext.getNamedDispatcher(name); @@ -111,13 +112,10 @@ { // Portlet API says: return null } - + // TODO: factory - if ( rd != null ) - { - return new JetspeedRequestDispatcher(rd); - } + if (rd != null) { return new JetspeedRequestDispatcher(rd); } return null; } @@ -128,43 +126,37 @@ public InputStream getResourceAsStream(String path) { - return servletContext.getResourceAsStream(localizePath(path, this.application)); + return servletContext.getResourceAsStream(localizePath(path, + this.application)); } public java.lang.Object getAttribute(java.lang.String name) { - if ( name == null ) - { - throw new IllegalArgumentException("Required parameter name is null"); - } - + if (name == null) { throw new IllegalArgumentException( + "Required parameter name is null"); } + if (name.startsWith("cps:")) { String serviceName = name.substring("cps:".length()); - + // validate service Collection validServices = application.getJetspeedServices(); - if (null == validServices) - { - return null; - } + if (null == validServices) { return null; } boolean found = false; Iterator iterator = validServices.iterator(); while (iterator.hasNext()) { - JetspeedServiceReference validService = (JetspeedServiceReference)iterator.next(); + JetspeedServiceReference validService = (JetspeedServiceReference) iterator + .next(); if (validService.getName().equals(serviceName)) { found = true; break; } } - - if (!found) - { - return null; - } - + + if (!found) { return null; } + // return the service PortletServices services = JetspeedPortletServices.getSingleton(); return services.getService(serviceName); @@ -189,7 +181,8 @@ return servletContext.getRealPath(localizePath(path, this.application)); } - public java.net.URL getResource(String path) throws java.net.MalformedURLException + public java.net.URL getResource(String path) + throws java.net.MalformedURLException { return servletContext.getResource(localizePath(path, this.application)); } @@ -201,10 +194,8 @@ public java.lang.String getInitParameter(java.lang.String name) { - if ( name == null ) - { - throw new IllegalArgumentException("Required parameter name is null"); - } + if (name == null) { throw new IllegalArgumentException( + "Required parameter name is null"); } return servletContext.getInitParameter(name); } @@ -215,20 +206,16 @@ public void removeAttribute(java.lang.String name) { - if (name == null) - { - throw new IllegalArgumentException("Attribute name == null"); - } + if (name == null) { throw new IllegalArgumentException( + "Attribute name == null"); } servletContext.removeAttribute(name); } public void setAttribute(java.lang.String name, java.lang.Object object) { - if (name == null) - { - throw new IllegalArgumentException("Attribute name == null"); - } + if (name == null) { throw new IllegalArgumentException( + "Attribute name == null"); } servletContext.setAttribute(name, object); } @@ -259,27 +246,18 @@ private String localizePath(String path, MutablePortletApplication app) { - if (path == null) - { - return "/"; - } + if (path == null) { return "/"; } return path; // TODO: local PA with own/extra resource paths support -/* - if (app.getApplicationType() == MutablePortletApplication.WEBAPP) - { - return path; - } - - StringBuffer pathBuffer = new StringBuffer(LOCAL_PA_ROOT); - pathBuffer.append(app.getWebApplicationDefinition().getContextRoot()); - if (!path.startsWith("/")) - { - pathBuffer.append("/"); - } - pathBuffer.append(path); - String result = pathBuffer.toString(); - return result; -*/ + /* + * if (app.getApplicationType() == MutablePortletApplication.WEBAPP) { + * return path; } + * + * StringBuffer pathBuffer = new StringBuffer(LOCAL_PA_ROOT); + * pathBuffer.append(app.getWebApplicationDefinition().getContextRoot()); + * if (!path.startsWith("/")) { pathBuffer.append("/"); } + * pathBuffer.append(path); String result = pathBuffer.toString(); + * return result; + */ } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortalAccessor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortalAccessor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortalAccessor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,9 +16,9 @@ */ package org.apache.jetspeed.container; +import javax.portlet.PortletConfig; +import javax.portlet.PortletContext; import javax.servlet.ServletContext; -import javax.portlet.PortletContext; -import javax.portlet.PortletConfig; import org.apache.pluto.om.portlet.PortletApplicationDefinition; import org.apache.pluto.om.portlet.PortletDefinition; @@ -26,24 +26,26 @@ /** * Portal Accessor - bridge used by container to communicate with Portal * insulating the communications protocol between container and portlet - * + * * @author David Sean Taylor * @version $Id: PortalAccessor.java 516448 2007-03-09 16:25:47Z ate $ */ public class PortalAccessor { - public static PortletConfig createPortletConfig(PortletContext portletContext, - PortletDefinition portletDefinition) + public static PortletConfig createPortletConfig( + PortletContext portletContext, PortletDefinition portletDefinition) { - return PortletConfigFactory.createPortletConfig(portletContext, portletDefinition); + return PortletConfigFactory.createPortletConfig(portletContext, + portletDefinition); } - public static PortletContext createPortletContext(ServletContext servletContext, - PortletApplicationDefinition application) + public static PortletContext createPortletContext( + ServletContext servletContext, + PortletApplicationDefinition application) { - return PortletContextFactory.createPortletContext(servletContext, application); + return PortletContextFactory.createPortletContext(servletContext, + application); } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletConfigFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletConfigFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletConfigFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,13 +23,15 @@ /** * Portlet Config Factory - * + * * @author David Sean Taylor * @version $Id: PortletConfigFactory.java 516448 2007-03-09 16:25:47Z ate $ */ public class PortletConfigFactory { - public static PortletConfig createPortletConfig(PortletContext portletContext,PortletDefinition portletDefinition) + + public static PortletConfig createPortletConfig( + PortletContext portletContext, PortletDefinition portletDefinition) { return new JetspeedPortletConfig(portletContext, portletDefinition); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletContextFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletContextFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletContextFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,23 +16,25 @@ */ package org.apache.jetspeed.container; +import javax.portlet.PortletContext; import javax.servlet.ServletContext; -import javax.portlet.PortletContext; import org.apache.pluto.om.portlet.PortletApplicationDefinition; /** * Portlet Config Factory - * + * * @author David Sean Taylor * @version $Id: PortletContextFactory.java 516448 2007-03-09 16:25:47Z ate $ */ public class PortletContextFactory { - public static PortletContext createPortletContext(ServletContext servletContext, - PortletApplicationDefinition application) + + public static PortletContext createPortletContext( + ServletContext servletContext, + PortletApplicationDefinition application) { return new JetspeedPortletContext(servletContext, application); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletDispatcherIncludeAware.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletDispatcherIncludeAware.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletDispatcherIncludeAware.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,13 +17,15 @@ package org.apache.jetspeed.container; /** - * Interface to communicate to HttpServleRequest and HttpServletResponse implementations if they - * are currently dispatched from PortletDispatcher so that they can enforce the JSR-168 PLT.16.3.3 restrictions. - * + * Interface to communicate to HttpServleRequest and HttpServletResponse + * implementations if they are currently dispatched from PortletDispatcher so + * that they can enforce the JSR-168 PLT.16.3.3 restrictions. + * * @author Ate Douma * @version $Id$ */ public interface PortletDispatcherIncludeAware { + public void setPortletDispatcherIncluded(boolean included); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletRequestContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletRequestContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/PortletRequestContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.container; import javax.portlet.Portlet; @@ -24,29 +24,35 @@ public class PortletRequestContext { + private static ThreadLocal context = new ThreadLocal(); - + private PortletDefinition pd; + private Portlet portlet; + private PortletRequest request; + private PortletResponse response; - + public static PortletRequestContext getContext() { - return (PortletRequestContext)context.get(); + return (PortletRequestContext) context.get(); } - - public static void createContext(PortletDefinition pd, Portlet portlet, PortletRequest request, PortletResponse response) + + public static void createContext(PortletDefinition pd, Portlet portlet, + PortletRequest request, PortletResponse response) { context.set(new PortletRequestContext(pd, portlet, request, response)); } - + public static void clearContext() - { + { context.set(null); } - private PortletRequestContext(PortletDefinition pd, Portlet portlet, PortletRequest request, PortletResponse response) + private PortletRequestContext(PortletDefinition pd, Portlet portlet, + PortletRequest request, PortletResponse response) { this.pd = pd; this.portlet = portlet; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/session/PortletApplicationSessionMonitorImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/session/PortletApplicationSessionMonitorImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/container/session/PortletApplicationSessionMonitorImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,75 +20,90 @@ import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionEvent; -import org.apache.jetspeed.container.session.PortalSessionsManager; -import org.apache.jetspeed.container.session.PortletApplicationSessionMonitor; import org.apache.jetspeed.services.JetspeedPortletServices; import org.apache.jetspeed.services.PortletServices; /** * PortletApplicationSessionMonitorImpl - * + * * @author Ate Douma * @version $Id: $ */ -public class PortletApplicationSessionMonitorImpl implements PortletApplicationSessionMonitor +public class PortletApplicationSessionMonitorImpl implements + PortletApplicationSessionMonitor { + private static final long serialVersionUID = -6729032046828426324L; - - private String contextPath; + + private String contextPath; + private String portalSessionId; + private long portalSessionKey; + private transient HttpSession session; + private boolean forceInvalidate; - public PortletApplicationSessionMonitorImpl(String contextPath, String portalSessionId, long portalSessionKey) + public PortletApplicationSessionMonitorImpl(String contextPath, + String portalSessionId, long portalSessionKey) { this(contextPath, portalSessionId, portalSessionKey, true); } - - public PortletApplicationSessionMonitorImpl(String contextPath, String portalSessionId, long portalSessionKey, boolean forceInvalidate) + + public PortletApplicationSessionMonitorImpl(String contextPath, + String portalSessionId, long portalSessionKey, + boolean forceInvalidate) { this.contextPath = contextPath; this.portalSessionId = portalSessionId; this.portalSessionKey = portalSessionKey; this.forceInvalidate = forceInvalidate; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.session.PortletApplicationSessionMonitor#getPortalSessionKey() */ public long getPortalSessionKey() { return portalSessionKey; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.session.PortletApplicationSessionMonitor#getPortalSessionId() */ public String getPortalSessionId() { return portalSessionId; } - + public HttpSession getSession() { return session; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.session.PortletApplicationSessionMonitor#getContextPath() */ public String getContextPath() { return contextPath; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.session.PortletApplicationSessionMonitor#invalidateSession() */ public void invalidateSession() { - if ( session != null ) + if (session != null) { HttpSession thisSession = session; session = null; @@ -103,10 +118,12 @@ // ignore } } - } + } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpSessionBindingListener#valueBound(javax.servlet.http.HttpSessionBindingEvent) */ public void valueBound(HttpSessionBindingEvent event) @@ -114,15 +131,17 @@ this.session = event.getSession(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpSessionBindingListener#valueUnbound(javax.servlet.http.HttpSessionBindingEvent) */ public void valueUnbound(HttpSessionBindingEvent event) { - if ( session != null ) + if (session != null) { - PortalSessionsManager manager = getManager(); - if ( manager != null ) + PortalSessionsManager manager = getManager(); + if (manager != null) { manager.sessionDestroyed(this); } @@ -130,39 +149,41 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpSessionActivationListener#sessionDidActivate(javax.servlet.http.HttpSessionEvent) */ public void sessionDidActivate(HttpSessionEvent event) { this.session = event.getSession(); - PortalSessionsManager manager = getManager(); - if ( manager != null ) + PortalSessionsManager manager = getManager(); + if (manager != null) { manager.sessionDidActivate(this); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpSessionActivationListener#sessionWillPassivate(javax.servlet.http.HttpSessionEvent) */ public void sessionWillPassivate(HttpSessionEvent event) { - PortalSessionsManager manager = getManager(); - if ( manager != null ) + PortalSessionsManager manager = getManager(); + if (manager != null) { manager.sessionWillPassivate(this); } session = null; } - + private PortalSessionsManager getManager() { PortletServices services = JetspeedPortletServices.getSingleton(); - if (services != null) - { - return (PortalSessionsManager)services.getService(PortalSessionsManager.SERVICE_NAME); - } + if (services != null) { return (PortalSessionsManager) services + .getService(PortalSessionsManager.SERVICE_NAME); } return null; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/dispatcher/JetspeedRequestDispatcher.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/dispatcher/JetspeedRequestDispatcher.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/dispatcher/JetspeedRequestDispatcher.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,14 +18,14 @@ import java.io.IOException; +import javax.portlet.PortletException; +import javax.portlet.PortletRequestDispatcher; +import javax.portlet.RenderRequest; +import javax.portlet.RenderResponse; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.portlet.PortletRequestDispatcher; -import javax.portlet.RenderResponse; -import javax.portlet.RenderRequest; -import javax.portlet.PortletException; import org.apache.jetspeed.container.PortletDispatcherIncludeAware; import org.apache.pluto.core.impl.RenderRequestImpl; @@ -33,68 +33,74 @@ /** * Implements the Portlet API Request Dispatcher to dispatch to portlets - * + * * @author David Sean Taylor * @version $Id: JetspeedRequestDispatcher.java 516448 2007-03-09 16:25:47Z ate $ */ public class JetspeedRequestDispatcher implements PortletRequestDispatcher { + private RequestDispatcher requestDispatcher; public JetspeedRequestDispatcher(RequestDispatcher requestDispatcher) { - if(requestDispatcher == null) - { - throw new IllegalArgumentException("RequestDispatcher cannot be null for JetspeedRequestDispatcher."); - } + if (requestDispatcher == null) { throw new IllegalArgumentException( + "RequestDispatcher cannot be null for JetspeedRequestDispatcher."); } this.requestDispatcher = requestDispatcher; } // portlet-only implementation - public void include(RenderRequest request, RenderResponse response) throws PortletException, java.io.IOException + public void include(RenderRequest request, RenderResponse response) + throws PortletException, java.io.IOException { HttpServletRequest servletRequest = null; HttpServletResponse servletResponse = null; try { - servletRequest = (HttpServletRequest) ((RenderRequestImpl) request).getRequest(); - servletResponse = (HttpServletResponse) ((RenderResponseImpl) response).getResponse(); - - if ( servletRequest instanceof PortletDispatcherIncludeAware ) + servletRequest = (HttpServletRequest) ((RenderRequestImpl) request) + .getRequest(); + servletResponse = (HttpServletResponse) ((RenderResponseImpl) response) + .getResponse(); + + if (servletRequest instanceof PortletDispatcherIncludeAware) { - ((PortletDispatcherIncludeAware)servletRequest).setPortletDispatcherIncluded(true); + ((PortletDispatcherIncludeAware) servletRequest) + .setPortletDispatcherIncluded(true); } - if ( servletResponse instanceof PortletDispatcherIncludeAware ) + if (servletResponse instanceof PortletDispatcherIncludeAware) { - ((PortletDispatcherIncludeAware)servletResponse).setPortletDispatcherIncluded(true); + ((PortletDispatcherIncludeAware) servletResponse) + .setPortletDispatcherIncluded(true); } - + this.requestDispatcher.include(servletRequest, servletResponse); } catch (RuntimeException re) { - // PLT.16.3.4 cxlii: + // PLT.16.3.4 cxlii: // RuntimeExceptions must be propagated back throw re; } catch (IOException ioe) { - // PLT.16.3.4 cxlii: + // PLT.16.3.4 cxlii: // IOExceptions must be propagated back throw ioe; } catch (Exception e) { - // PLT.16.3.4 cxliii: - // All other exceptions, including ServletExceptions must be wrapped in a PortletException - // with the root cause set to the original exception before propagated back + // PLT.16.3.4 cxliii: + // All other exceptions, including ServletExceptions must be wrapped + // in a PortletException + // with the root cause set to the original exception before + // propagated back Throwable rootCause = null; - if ( e instanceof ServletException) + if (e instanceof ServletException) { - rootCause = ((ServletException)e).getRootCause(); + rootCause = ((ServletException) e).getRootCause(); } else { @@ -104,15 +110,19 @@ } finally { - if ( servletRequest != null && servletRequest instanceof PortletDispatcherIncludeAware ) + if (servletRequest != null + && servletRequest instanceof PortletDispatcherIncludeAware) { - ((PortletDispatcherIncludeAware)servletRequest).setPortletDispatcherIncluded(false); + ((PortletDispatcherIncludeAware) servletRequest) + .setPortletDispatcherIncluded(false); } - if ( servletResponse != null && servletResponse instanceof PortletDispatcherIncludeAware ) + if (servletResponse != null + && servletResponse instanceof PortletDispatcherIncludeAware) { - ((PortletDispatcherIncludeAware)servletResponse).setPortletDispatcherIncluded(false); + ((PortletDispatcherIncludeAware) servletResponse) + .setPortletDispatcherIncluded(false); } - + } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlet/PortletObjectProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlet/PortletObjectProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlet/PortletObjectProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,41 +16,37 @@ */ package org.apache.jetspeed.portlet; +import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; +import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; -import java.lang.reflect.Modifier; -import java.io.IOException; - +import javax.portlet.ActionRequest; +import javax.portlet.ActionResponse; +import javax.portlet.GenericPortlet; import javax.portlet.Portlet; -import javax.portlet.GenericPortlet; import javax.portlet.PortletException; import javax.portlet.PortletMode; -import javax.portlet.WindowState; -import javax.portlet.ActionRequest; -import javax.portlet.ActionResponse; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; - -import org.apache.pluto.om.portlet.PortletDefinition; -import org.apache.pluto.om.portlet.ContentTypeSet; - -import org.apache.jetspeed.JetspeedActions; -import org.apache.jetspeed.portlet.SupportsHeaderPhase; -import org.apache.jetspeed.util.BaseObjectProxy; -import org.apache.jetspeed.container.JetspeedPortletConfig; - +import javax.portlet.UnavailableException; +import javax.portlet.WindowState; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; -import javax.portlet.UnavailableException; + import org.apache.jetspeed.Jetspeed; +import org.apache.jetspeed.JetspeedActions; import org.apache.jetspeed.components.portletregistry.PortletRegistry; +import org.apache.jetspeed.container.JetspeedPortletConfig; +import org.apache.jetspeed.factory.PortletFactory; +import org.apache.jetspeed.factory.PortletInstance; +import org.apache.jetspeed.om.common.portlet.MutablePortletApplication; import org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite; -import org.apache.jetspeed.om.common.portlet.MutablePortletApplication; +import org.apache.jetspeed.util.BaseObjectProxy; +import org.apache.pluto.om.portlet.ContentTypeSet; +import org.apache.pluto.om.portlet.PortletDefinition; import org.apache.pluto.om.servlet.WebApplicationDefinition; -import org.apache.jetspeed.factory.PortletFactory; -import org.apache.jetspeed.factory.PortletInstance; /** * PortletObjectProxy @@ -60,81 +56,107 @@ */ public class PortletObjectProxy extends BaseObjectProxy { - - private static ThreadLocal tlPortletObjectProxied = - new ThreadLocal() { - protected synchronized Object initialValue() { - return new boolean [] { false }; - } - }; - + + private static ThreadLocal tlPortletObjectProxied = new ThreadLocal() + { + + protected synchronized Object initialValue() + { + return new boolean[] + {false}; + } + }; + public static void setPortletObjectProxied(boolean portletObjectProxied) { - ((boolean []) tlPortletObjectProxied.get())[0] = portletObjectProxied; + ((boolean[]) tlPortletObjectProxied.get())[0] = portletObjectProxied; } - + public static boolean isPortletObjectProxied() { - return ((boolean []) tlPortletObjectProxied.get())[0]; + return ((boolean[]) tlPortletObjectProxied.get())[0]; } - + private static Method renderMethod; + private static Method processActionMethod; - - static + + static { - try + try { - renderMethod = Portlet.class.getMethod("render", new Class [] { RenderRequest.class, RenderResponse.class }); - processActionMethod = Portlet.class.getMethod("processAction", new Class [] { ActionRequest.class, ActionResponse.class }); - } - catch (NoSuchMethodException e) + renderMethod = Portlet.class.getMethod("render", new Class[] + {RenderRequest.class, RenderResponse.class}); + processActionMethod = Portlet.class.getMethod("processAction", + new Class[] + {ActionRequest.class, ActionResponse.class}); + } + catch (NoSuchMethodException e) { - throw new NoSuchMethodError(e.getMessage()); - } + throw new NoSuchMethodError(e.getMessage()); + } } - + private Object portletObject; + private PortletInstance customConfigModePortletInstance; + private boolean genericPortletInvocable; + private Method portletDoEditMethod; + private ContentTypeSet portletContentTypeSet; + private boolean autoSwitchEditDefaultsModeToEditMode; + private boolean autoSwitchConfigMode; + private String customConfigModePortletUniqueName; - - public static Object createProxy(Object proxiedObject, boolean autoSwitchEditDefaultsModeToEditMode, boolean autoSwitchConfigMode, String customConfigModePortletUniqueName) + + public static Object createProxy(Object proxiedObject, + boolean autoSwitchEditDefaultsModeToEditMode, + boolean autoSwitchConfigMode, + String customConfigModePortletUniqueName) { Class proxiedClass = proxiedObject.getClass(); ClassLoader classLoader = proxiedClass.getClassLoader(); - Class [] proxyInterfaces = null; - + Class[] proxyInterfaces = null; + if (proxiedObject instanceof SupportsHeaderPhase) { - proxyInterfaces = new Class [] { Portlet.class, SupportsHeaderPhase.class }; + proxyInterfaces = new Class[] + {Portlet.class, SupportsHeaderPhase.class}; } else { - proxyInterfaces = new Class [] { Portlet.class }; + proxyInterfaces = new Class[] + {Portlet.class}; } - - InvocationHandler handler = new PortletObjectProxy(proxiedObject, autoSwitchEditDefaultsModeToEditMode, autoSwitchConfigMode, customConfigModePortletUniqueName); + + InvocationHandler handler = new PortletObjectProxy(proxiedObject, + autoSwitchEditDefaultsModeToEditMode, autoSwitchConfigMode, + customConfigModePortletUniqueName); return Proxy.newProxyInstance(classLoader, proxyInterfaces, handler); } - private PortletObjectProxy(Object portletObject, boolean autoSwitchEditDefaultsModeToEditMode, boolean autoSwitchConfigMode, String customConfigModePortletUniqueName) + private PortletObjectProxy(Object portletObject, + boolean autoSwitchEditDefaultsModeToEditMode, + boolean autoSwitchConfigMode, + String customConfigModePortletUniqueName) { this.portletObject = portletObject; this.autoSwitchEditDefaultsModeToEditMode = autoSwitchEditDefaultsModeToEditMode; this.autoSwitchConfigMode = autoSwitchConfigMode; this.customConfigModePortletUniqueName = customConfigModePortletUniqueName; - + if (portletObject instanceof GenericPortlet) { try { - this.portletDoEditMethod = this.portletObject.getClass().getMethod("doEdit", new Class [] { RenderRequest.class, RenderResponse.class }); - + this.portletDoEditMethod = this.portletObject.getClass() + .getMethod("doEdit", new Class[] + {RenderRequest.class, RenderResponse.class}); + if (Modifier.isPublic(this.portletDoEditMethod.getModifiers())) { this.genericPortletInvocable = true; @@ -146,12 +168,13 @@ } } - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { Object result = null; boolean handledHere = false; Class declaringClass = method.getDeclaringClass(); - + if (declaringClass == Portlet.class) { if (renderMethod.equals(method)) @@ -161,7 +184,8 @@ } else if (processActionMethod.equals(method)) { - proxyProcessAction((ActionRequest) args[0], (ActionResponse) args[1]); + proxyProcessAction((ActionRequest) args[0], + (ActionResponse) args[1]); } else { @@ -176,23 +200,26 @@ { result = super.invoke(proxy, method, args); } - + return result; } - protected void proxyRender(RenderRequest request, RenderResponse response) throws PortletException, IOException, Exception + protected void proxyRender(RenderRequest request, RenderResponse response) + throws PortletException, IOException, Exception { PortletMode mode = request.getPortletMode(); - + boolean autoSwitchConfigMode = false; boolean autoSwitchToEditMode = false; - - if (this.autoSwitchConfigMode && JetspeedActions.CONFIG_MODE.equals(mode)) + + if (this.autoSwitchConfigMode + && JetspeedActions.CONFIG_MODE.equals(mode)) { autoSwitchConfigMode = true; } - - if (this.autoSwitchEditDefaultsModeToEditMode && this.genericPortletInvocable) + + if (this.autoSwitchEditDefaultsModeToEditMode + && this.genericPortletInvocable) { if (JetspeedActions.EDIT_DEFAULTS_MODE.equals(mode)) { @@ -202,7 +229,7 @@ } } } - + if (autoSwitchConfigMode) { try @@ -211,7 +238,7 @@ { refreshCustomConfigModePortletInstance(); } - + this.customConfigModePortletInstance.render(request, response); } catch (UnavailableException e) @@ -223,16 +250,19 @@ else if (autoSwitchToEditMode) { GenericPortlet genericPortlet = (GenericPortlet) this.portletObject; - + // Override GenericPortlet#render.... WindowState state = request.getWindowState(); - + if (!WindowState.MINIMIZED.equals(state)) { - String title = genericPortlet.getPortletConfig().getResourceBundle(request.getLocale()).getString("javax.portlet.title"); + String title = genericPortlet.getPortletConfig() + .getResourceBundle(request.getLocale()).getString( + "javax.portlet.title"); response.setTitle(title); - - this.portletDoEditMethod.invoke(genericPortlet, new Object [] { request, response }); + + this.portletDoEditMethod.invoke(genericPortlet, new Object[] + {request, response}); } } else @@ -241,17 +271,20 @@ } } - protected void proxyProcessAction(ActionRequest request, ActionResponse response) throws PortletException, IOException, Exception + protected void proxyProcessAction(ActionRequest request, + ActionResponse response) throws PortletException, IOException, + Exception { PortletMode mode = request.getPortletMode(); - + boolean autoSwitchConfigMode = false; - - if (this.autoSwitchConfigMode && JetspeedActions.CONFIG_MODE.equals(mode)) + + if (this.autoSwitchConfigMode + && JetspeedActions.CONFIG_MODE.equals(mode)) { autoSwitchConfigMode = true; } - + if (autoSwitchConfigMode) { try @@ -260,13 +293,15 @@ { refreshCustomConfigModePortletInstance(); } - - this.customConfigModePortletInstance.processAction(request, response); + + this.customConfigModePortletInstance.processAction(request, + response); } catch (UnavailableException e) { refreshCustomConfigModePortletInstance(); - this.customConfigModePortletInstance.processAction(request, response); + this.customConfigModePortletInstance.processAction(request, + response); } } else @@ -274,14 +309,15 @@ ((Portlet) this.portletObject).processAction(request, response); } } - + private boolean isSupportingEditDefaultsMode(GenericPortlet portlet) { if (this.portletContentTypeSet == null) { try { - JetspeedPortletConfig config = (JetspeedPortletConfig) portlet.getPortletConfig(); + JetspeedPortletConfig config = (JetspeedPortletConfig) portlet + .getPortletConfig(); PortletDefinition portletDef = config.getPortletDefinition(); this.portletContentTypeSet = portletDef.getContentTypeSet(); } @@ -289,31 +325,38 @@ { } } - - if (this.portletContentTypeSet != null) - { - return this.portletContentTypeSet.supportsPortletMode(JetspeedActions.EDIT_DEFAULTS_MODE); - } - + + if (this.portletContentTypeSet != null) { return this.portletContentTypeSet + .supportsPortletMode(JetspeedActions.EDIT_DEFAULTS_MODE); } + return false; } - + private void refreshCustomConfigModePortletInstance() { try { - PortletRegistry registry = (PortletRegistry) Jetspeed.getComponentManager().getComponent("portletRegistry"); - PortletFactory portletFactory = (PortletFactory) Jetspeed.getComponentManager().getComponent("portletFactory"); - ServletContext portalAppContext = ((ServletConfig) Jetspeed.getComponentManager().getComponent("ServletConfig")).getServletContext(); - - PortletDefinitionComposite portletDef = (PortletDefinitionComposite) registry.getPortletDefinitionByUniqueName(this.customConfigModePortletUniqueName); - MutablePortletApplication portletApp = (MutablePortletApplication) portletDef.getPortletApplicationDefinition(); - WebApplicationDefinition webAppDef = portletApp.getWebApplicationDefinition(); + PortletRegistry registry = (PortletRegistry) Jetspeed + .getComponentManager().getComponent("portletRegistry"); + PortletFactory portletFactory = (PortletFactory) Jetspeed + .getComponentManager().getComponent("portletFactory"); + ServletContext portalAppContext = ((ServletConfig) Jetspeed + .getComponentManager().getComponent("ServletConfig")) + .getServletContext(); + + PortletDefinitionComposite portletDef = (PortletDefinitionComposite) registry + .getPortletDefinitionByUniqueName(this.customConfigModePortletUniqueName); + MutablePortletApplication portletApp = (MutablePortletApplication) portletDef + .getPortletApplicationDefinition(); + WebApplicationDefinition webAppDef = portletApp + .getWebApplicationDefinition(); String portletAppName = webAppDef.getContextRoot(); - ServletContext portletAppContext = portalAppContext.getContext(portletAppName); - + ServletContext portletAppContext = portalAppContext + .getContext(portletAppName); + setPortletObjectProxied(true); - this.customConfigModePortletInstance = portletFactory.getPortletInstance(portletAppContext, portletDef); + this.customConfigModePortletInstance = portletFactory + .getPortletInstance(portletAppContext, portletDef); } catch (Exception e) { @@ -323,5 +366,5 @@ setPortletObjectProxied(false); } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlet/PortletResourceURLFactoryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlet/PortletResourceURLFactoryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlet/PortletResourceURLFactoryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,10 +31,12 @@ * Jetspeed specific implementation of PortletResourceURLFactory. * * @author Ate Douma - * @version $Id: PortletResourceURLFactoryImpl.java 544026 2007-06-04 01:02:24Z ate $ + * @version $Id: PortletResourceURLFactoryImpl.java 544026 2007-06-04 01:02:24Z + * ate $ */ public class PortletResourceURLFactoryImpl implements PortletResourceURLFactory { + /* * (non-Javadoc) * @@ -42,7 +44,8 @@ * javax.portlet.RenderRequest, javax.portlet.RenderResponse, * java.util.Map) */ - public String createResourceURL(PortletConfig config, RenderRequest request, RenderResponse response, Map parameters) + public String createResourceURL(PortletConfig config, + RenderRequest request, RenderResponse response, Map parameters) throws PortletException { PortletURL url = response.createRenderURL(); @@ -50,7 +53,10 @@ { url.setParameters(parameters); } - url.setParameter(PortalReservedParameters.PORTLET_RESOURCE_URL_REQUEST_PARAMETER, ""); + url + .setParameter( + PortalReservedParameters.PORTLET_RESOURCE_URL_REQUEST_PARAMETER, + ""); return url.toString(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlet/ServletContextProviderImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlet/ServletContextProviderImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlet/ServletContextProviderImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,25 +29,32 @@ import org.apache.portals.bridges.common.ServletContextProvider; /** - * ServletContextProviderImpl supplies access to the - * Servlet context of a Jetspeed Portlet. + * ServletContextProviderImpl supplies access to the Servlet context of a + * Jetspeed Portlet. + * * @author Ate Douma * @version $Id: ServletContextProviderImpl.java 516448 2007-03-09 16:25:47Z ate $ */ -public class ServletContextProviderImpl implements ServletContextProvider +public class ServletContextProviderImpl implements ServletContextProvider { - public ServletContext getServletContext(GenericPortlet portlet) + + public ServletContext getServletContext(GenericPortlet portlet) { - return ((JetspeedPortletContext)portlet.getPortletContext()).getServletContext(); + return ((JetspeedPortletContext) portlet.getPortletContext()) + .getServletContext(); } - public HttpServletRequest getHttpServletRequest(GenericPortlet portlet, PortletRequest request) + public HttpServletRequest getHttpServletRequest(GenericPortlet portlet, + PortletRequest request) { - return (HttpServletRequest) ((HttpServletRequestWrapper) request).getRequest(); + return (HttpServletRequest) ((HttpServletRequestWrapper) request) + .getRequest(); } - public HttpServletResponse getHttpServletResponse(GenericPortlet portlet, PortletResponse response) + public HttpServletResponse getHttpServletResponse(GenericPortlet portlet, + PortletResponse response) { - return (HttpServletResponse) ((HttpServletResponseWrapper) response).getResponse(); + return (HttpServletResponse) ((HttpServletResponseWrapper) response) + .getResponse(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/ColumnLayout.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/ColumnLayout.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/ColumnLayout.java 2008-05-16 01:54:54 UTC (rev 940) @@ -44,21 +44,23 @@ * *

      Characteristics:

      *
        - *
      • Columns and rows always start at 0.
      • - *
      • Unless otherwise noted, assume all Collections returned are immutable.
      • - *
      • Unless otherwise noted, assume that no public method will ever return null.
      • + *
      • Columns and rows always start at 0.
      • + *
      • Unless otherwise noted, assume all Collections returned are immutable.
      • + *
      • Unless otherwise noted, assume that no public method will ever return + * null.
      • *
      - * * + * *

      Layout Events

      *

      - * When any move*() method is invoked and a portlet is actually moved (see indvidual - * methods for what causes these circumstances), an initial LayoutEvent is dispatched. - * This may cause a cascade of LayoutEvents to be fired in turn if the movement of the - * target fragment cause other fragments to be repositioned. In this case a LayoutEvent - * is dispatched for each portlet moved, which in turn may our may not cause another - * LayoutEvent to be fired. + * When any move*() method is invoked and a portlet is actually moved (see + * indvidual methods for what causes these circumstances), an initial + * LayoutEvent is dispatched. This may cause a cascade of LayoutEvents to be + * fired in turn if the movement of the target fragment cause other fragments to + * be repositioned. In this case a LayoutEvent is dispatched for each portlet + * moved, which in turn may our may not cause another LayoutEvent to be fired. *

      + * * @see org.apache.jetspeed.portlets.layout.LayoutEvent * @see org.apache.jetspeed.portlets.layout.LayoutEventListener * @see org.apache.jetspeed.portlets.layout.LayoutCoordinate @@ -69,28 +71,32 @@ */ public class ColumnLayout implements Serializable { + /** Percentage widths gutter width */ private final static double PERCENTAGE_WIDTH_GUTTER = 0.01; /** Percentage widths format */ - private final static DecimalFormat PERCENTAGE_WIDTH_FORMAT = new DecimalFormat("0.00'%'", new DecimalFormatSymbols( - Locale.ENGLISH)); + private final static DecimalFormat PERCENTAGE_WIDTH_FORMAT = new DecimalFormat( + "0.00'%'", new DecimalFormatSymbols(Locale.ENGLISH)); /** Constrains the columns for this layout */ private final int numberOfColumns; - + /** SortedMap of Columns (which are also sorted maps */ private final SortedMap columns; - + /** Width settings for eacah column */ private final String[] columnWidths; - + /** Efficent way to always be aware of the next available row in a column */ private final int[] nextRowNumber; - - /** maps Fragments (key) to it's current LayoutCoordinate (value) in this layout */ + + /** + * maps Fragments (key) to it's current LayoutCoordinate (value) in this + * layout + */ private final Map coordinates; - + /** All of the LayoutEventListeners registered to this layout */ private final List eventListeners; @@ -109,7 +115,8 @@ * are used. * @see org.apache.jetspeed.om.page.Fragment#getType() */ - public ColumnLayout(int numberOfColumns, String layoutType, String[] columnWidths) + public ColumnLayout(int numberOfColumns, String layoutType, + String[] columnWidths) { this.numberOfColumns = numberOfColumns; this.columnWidths = columnWidths; @@ -130,12 +137,12 @@ nextRowNumber[i] = 0; } } - + /** * Same as ColumnLayout(int numberOfColumns, String layoutType) but also - * supplies a Collection of fragmetns to initially populate the layout - * with. Adding these fragments WILL NOT cause - * a LayoutEvent to be dispatched. + * supplies a Collection of fragmetns to initially populate the layout with. + * Adding these fragments WILL NOT cause a LayoutEvent to + * be dispatched. * * @see ColumnLayout(int numberOfColumns, String layoutType) * @param numberOfColumns @@ -146,13 +153,16 @@ * property settings based on the type of layout in use. This * effectively allows for the interchange of multiple layout * formats without one format effecting the settings of another. - * @param fragments Initial set of fragments to add to this layout. + * @param fragments + * Initial set of fragments to add to this layout. * @param columnWidths * widths for each column that accumulate to 100% if percentages * are used. * @throws LayoutEventException */ - public ColumnLayout(int numberOfColumns, String layoutType, Collection fragments, String[] columnWidths) throws LayoutEventException + public ColumnLayout(int numberOfColumns, String layoutType, + Collection fragments, String[] columnWidths) + throws LayoutEventException { this(numberOfColumns, layoutType, columnWidths); Iterator fragmentsItr = fragments.iterator(); @@ -161,7 +171,8 @@ while (fragmentsItr.hasNext()) { Fragment fragment = (Fragment) fragmentsItr.next(); - doAdd(getColumn(fragment), getRow(getColumn(fragment), fragment), fragment); + doAdd(getColumn(fragment), + getRow(getColumn(fragment), fragment), fragment); } } catch (InvalidLayoutLocationException e) @@ -169,7 +180,8 @@ // This should NEVER happen as getColumn() should // automatically constrain any fragments who's column // setting would cause this exception. - throw new LayoutError("A malformed fragment could not be adjusted.", e); + throw new LayoutError( + "A malformed fragment could not be adjusted.", e); } } @@ -191,7 +203,7 @@ * * @param fragment * Fragment to add to this layout. - * @throws LayoutEventException + * @throws LayoutEventException * @see org.apache.jetspeed.om.page.Fragment * */ @@ -199,26 +211,30 @@ { try { - doAdd(getColumn(fragment), getRow(getColumn(fragment), fragment), fragment); + doAdd(getColumn(fragment), getRow(getColumn(fragment), fragment), + fragment); LayoutCoordinate coordinate = getCoordinate(fragment); - processEvent(new LayoutEvent(LayoutEvent.ADDED, fragment, coordinate, coordinate)); + processEvent(new LayoutEvent(LayoutEvent.ADDED, fragment, + coordinate, coordinate)); } catch (InvalidLayoutLocationException e) { // This should NEVER happen as getColumn() should // automatically constrain any fragments who's column // setting would cause this exception. - throw new LayoutError("A malformed fragment could not be adjusted.", e); + throw new LayoutError( + "A malformed fragment could not be adjusted.", e); } catch (FragmentNotInLayoutException e) - { - throw new LayoutError("Failed to add coordinate to this ColumnLayout.", e); + { + throw new LayoutError( + "Failed to add coordinate to this ColumnLayout.", e); } } - + /** - * Adds a LayoutEventListener to this layout that will be fired any time - * a LayoutEvent is disaptched. + * Adds a LayoutEventListener to this layout that will be fired any time a + * LayoutEvent is disaptched. * * @param eventListener * @see LayoutEventListener @@ -238,19 +254,21 @@ * @throws InvalidLayoutLocationException * if the column is outisde of the constraints of this layout */ - public Collection getColumn(int columnNumber) throws InvalidLayoutLocationException + public Collection getColumn(int columnNumber) + throws InvalidLayoutLocationException { - return Collections.unmodifiableCollection(getColumnMap(columnNumber).values()); + return Collections.unmodifiableCollection(getColumnMap(columnNumber) + .values()); } /** - * returns the width to be used with the specified column. If - * there is no specific column setting sfor the specified column - * 0 is returned. + * returns the width to be used with the specified column. If there is no + * specific column setting sfor the specified column 0 is returned. * - * @param columnNumber whose width has been requested. - * @return the width to be used with the specified column. Or 0 if no value - * has been specified. + * @param columnNumber + * whose width has been requested. + * @return the width to be used with the specified column. Or 0 if no value + * has been specified. */ public String getColumnWidth(int columnNumber) { @@ -261,17 +279,20 @@ // subtract "gutter" width from last percentage // column to prevent wrapping on rounding errors // of column widths when rendered in the browser - if ((numberOfColumns > 1) && (columnNumber == (numberOfColumns - 1))) + if ((numberOfColumns > 1) + && (columnNumber == (numberOfColumns - 1))) { int percentIndex = columnWidth.lastIndexOf('%'); if (percentIndex > 0) { try { - double width = Double.parseDouble(columnWidth.substring(0,percentIndex).trim()); + double width = Double.parseDouble(columnWidth + .substring(0, percentIndex).trim()); synchronized (PERCENTAGE_WIDTH_FORMAT) { - columnWidth = PERCENTAGE_WIDTH_FORMAT.format(width - PERCENTAGE_WIDTH_GUTTER); + columnWidth = PERCENTAGE_WIDTH_FORMAT.format(width + - PERCENTAGE_WIDTH_GUTTER); } } catch (NumberFormatException nfe) @@ -283,13 +304,14 @@ } return "0"; } - + /** * returns the float to be used with the specified column. * - * @param columnNumber whose width has been requested. - * @return "right" for the last column, "left" if more than one - * column, or "none" otherwise. + * @param columnNumber + * whose width has been requested. + * @return "right" for the last column, "left" if more than one column, or + * "none" otherwise. */ public String getColumnFloat(int columnNumber) { @@ -306,7 +328,7 @@ } return "none"; } - + /** * @return java.util.Collection all of columns (also * Collection objects) in order within this layout. All Collections @@ -318,28 +340,30 @@ Iterator itr = columns.values().iterator(); while (itr.hasNext()) { - columnList.add(Collections.unmodifiableCollection(((Map) itr.next()).values())); + columnList.add(Collections + .unmodifiableCollection(((Map) itr.next()).values())); } return Collections.unmodifiableCollection(columnList); } - + /** * * Returns the index of the last row in the specified column. * - * @param columnNumber column form whom we ant to identify the - * last row. + * @param columnNumber + * column form whom we ant to identify the last row. * @return the index of the last row in the specified column. */ public int getLastRowNumber(int columnNumber) { return nextRowNumber[columnNumber] - 1; } - + /** * Returns an immutable Collection of all the Fragments contained within * this ColumnLayout in no sepcific order. + * * @return Immutable Collection of Fragments. */ public Collection getFragments() @@ -350,15 +374,22 @@ /** * Retrieves the fragment at the specified loaction. * - * @param columnNumber Column coordinate (first column starts at 0) - * @param rowNumber Row coordinate (first row starts at 0) - * @return Fragment at the specified coordinate. Never returns null. - * @throws EmptyLayoutLocationException if there is no fragment currently located at the specified coordinate. - * @throws InvalidLayoutLocationException if the coordinate lies outside the confines of this layout, i.e., the - * columnNumber exceeds the max columns setting for this layout. + * @param columnNumber + * Column coordinate (first column starts at 0) + * @param rowNumber + * Row coordinate (first row starts at 0) + * @return Fragment at the specified coordinate. Never returns + * null. + * @throws EmptyLayoutLocationException + * if there is no fragment currently located at the specified + * coordinate. + * @throws InvalidLayoutLocationException + * if the coordinate lies outside the confines of this layout, + * i.e., the columnNumber exceeds the max columns + * setting for this layout. */ - public Fragment getFragmentAt(int columnNumber, int rowNumber) throws EmptyLayoutLocationException, - InvalidLayoutLocationException + public Fragment getFragmentAt(int columnNumber, int rowNumber) + throws EmptyLayoutLocationException, InvalidLayoutLocationException { SortedMap column = getColumnMap(columnNumber); Integer rowInteger = new Integer(rowNumber); @@ -371,22 +402,28 @@ throw new EmptyLayoutLocationException(columnNumber, rowNumber); } } - + /** * * Retrieves the fragment at the specified loaction. * - * @param coodinate LayoutCoordinate object that will be used to located a fragment in this - * layout. + * @param coodinate + * LayoutCoordinate object that will be used to located a + * fragment in this layout. * @see LayoutCoordinate - * @return Fragment at the specified coordinate. Never returns null. - * @throws EmptyLayoutLocationException if there is no fragment currently located at the specified coordinate. - * @throws InvalidLayoutLocationException if the coordinate lies outside the confines of this layout, i.e., the - * columnNumber exceeds the max columns setting for this layout. + * @return Fragment at the specified coordinate. Never returns + * null. + * @throws EmptyLayoutLocationException + * if there is no fragment currently located at the specified + * coordinate. + * @throws InvalidLayoutLocationException + * if the coordinate lies outside the confines of this layout, + * i.e., the columnNumber exceeds the max columns + * setting for this layout. * @see LayoutCoordinate */ - public Fragment getFragmentAt(LayoutCoordinate coodinate) throws EmptyLayoutLocationException, - InvalidLayoutLocationException + public Fragment getFragmentAt(LayoutCoordinate coodinate) + throws EmptyLayoutLocationException, InvalidLayoutLocationException { return getFragmentAt(coodinate.getX(), coodinate.getY()); } @@ -402,25 +439,28 @@ /** * - * @return The last column in this layout. The Collection is immutable. + * @return The last column in this layout. The Collection is immutable. */ - public Collection getLastColumn() + public Collection getLastColumn() { try { - return Collections.unmodifiableCollection(getColumnMap(numberOfColumns - 1).values()); + return Collections.unmodifiableCollection(getColumnMap( + numberOfColumns - 1).values()); } catch (InvalidLayoutLocationException e) { // This should NEVER happen as getLastColumn() is // always correctly constrained and should always exists. - throw new LayoutError("It appears this layout is corrupt and cannot correctly identify its last column.", e); + throw new LayoutError( + "It appears this layout is corrupt and cannot correctly identify its last column.", + e); } } /** * - * @return The last column in this layout. The Collection is immutable. + * @return The last column in this layout. The Collection is immutable. */ public Collection getFirstColumn() { @@ -432,29 +472,35 @@ { // This should NEVER happen as getLastColumn() is // always correctly constrained and should always exists. - throw new LayoutError("It appears this layout is corrupt and cannot correctly identify its first column.", e); + throw new LayoutError( + "It appears this layout is corrupt and cannot correctly identify its first column.", + e); } } /** * - * Moves a fragment one column to the right. A LayoutEvent is triggered by + * Moves a fragment one column to the right. A LayoutEvent is triggered by * this action. * *

      - * If the fragment currently - * resides in right-most column, no action is taking and no event LayoutEvent - * is fired. + * If the fragment currently resides in right-most column, no action is + * taking and no event LayoutEvent is fired. *

      * - * @param fragment fragment to move. - * @throws FragmentNotInLayoutException if the specified fragment is not currently in the layout. - * @throws LayoutEventException If a triggered LayoutEvent fails. + * @param fragment + * fragment to move. + * @throws FragmentNotInLayoutException + * if the specified fragment is not currently in the layout. + * @throws LayoutEventException + * If a triggered LayoutEvent fails. */ - public void moveRight(Fragment fragment) throws FragmentNotInLayoutException, LayoutEventException + public void moveRight(Fragment fragment) + throws FragmentNotInLayoutException, LayoutEventException { LayoutCoordinate coordinate = getCoordinate(fragment); - LayoutCoordinate newCoordinate = new LayoutCoordinate(coordinate.getX() + 1, coordinate.getY()); + LayoutCoordinate newCoordinate = new LayoutCoordinate( + coordinate.getX() + 1, coordinate.getY()); if (newCoordinate.getX() < numberOfColumns) { @@ -462,11 +508,13 @@ try { doMove(fragment, coordinate, newCoordinate); - processEvent(new LayoutEvent(LayoutEvent.MOVED_RIGHT, fragment, coordinate, newCoordinate)); + processEvent(new LayoutEvent(LayoutEvent.MOVED_RIGHT, fragment, + coordinate, newCoordinate)); // now move the fragment below up one level. try { - Fragment fragmentBelow = getFragmentAt(new LayoutCoordinate(coordinate.getX(), coordinate.getY() + 1)); + Fragment fragmentBelow = getFragmentAt(new LayoutCoordinate( + coordinate.getX(), coordinate.getY() + 1)); moveUp(fragmentBelow); } catch (EmptyLayoutLocationException e) @@ -476,41 +524,49 @@ } catch (InvalidLayoutLocationException e) { - // This should NEVER happen as the location has already been verfied to be valid - throw new LayoutError("It appears this layout is corrupt and cannot correctly identify valid column locations.", e); - } + // This should NEVER happen as the location has already been + // verfied to be valid + throw new LayoutError( + "It appears this layout is corrupt and cannot correctly identify valid column locations.", + e); + } } } /** - * Moves a fragment one column to the left. A LayoutEvent is triggered by + * Moves a fragment one column to the left. A LayoutEvent is triggered by * this action. * *

      - * If the fragment currently - * resides in left-most column, no action is taking and no event LayoutEvent - * is fired. + * If the fragment currently resides in left-most column, no action is + * taking and no event LayoutEvent is fired. *

      * * @param fragment - * @throws FragmentNotInLayoutException if the specified fragment is not currently in the layout. - * @throws LayoutEventException If a triggered LayoutEvent fails. + * @throws FragmentNotInLayoutException + * if the specified fragment is not currently in the layout. + * @throws LayoutEventException + * If a triggered LayoutEvent fails. */ - public void moveLeft(Fragment fragment) throws FragmentNotInLayoutException, LayoutEventException + public void moveLeft(Fragment fragment) + throws FragmentNotInLayoutException, LayoutEventException { LayoutCoordinate coordinate = getCoordinate(fragment); - LayoutCoordinate newCoordinate = new LayoutCoordinate(coordinate.getX() - 1, coordinate.getY()); + LayoutCoordinate newCoordinate = new LayoutCoordinate( + coordinate.getX() - 1, coordinate.getY()); if (newCoordinate.getX() >= 0) { try { doMove(fragment, coordinate, newCoordinate); - processEvent(new LayoutEvent(LayoutEvent.MOVED_LEFT, fragment, coordinate, newCoordinate)); + processEvent(new LayoutEvent(LayoutEvent.MOVED_LEFT, fragment, + coordinate, newCoordinate)); // now move the fragment below up one level. try { - Fragment fragmentBelow = getFragmentAt(new LayoutCoordinate(coordinate.getX(), coordinate.getY() + 1)); + Fragment fragmentBelow = getFragmentAt(new LayoutCoordinate( + coordinate.getX(), coordinate.getY() + 1)); moveUp(fragmentBelow); } catch (EmptyLayoutLocationException e) @@ -520,31 +576,38 @@ } catch (InvalidLayoutLocationException e) { - // This should NEVER happen as the location has already been verfied to be valid - throw new LayoutError("It appears this layout is corrupt and cannot correctly identify valid column locations.", e); + // This should NEVER happen as the location has already been + // verfied to be valid + throw new LayoutError( + "It appears this layout is corrupt and cannot correctly identify valid column locations.", + e); } - + } } /** - * Moves a fragment one row to the up. A LayoutEvent is triggered by - * this action. + * Moves a fragment one row to the up. A LayoutEvent is triggered by this + * action. * *

      - * If the fragment currently - * resides in top-most row, no action is taking and no event LayoutEvent - * is fired. + * If the fragment currently resides in top-most row, no action is taking + * and no event LayoutEvent is fired. *

      + * * @param fragment - * @throws FragmentNotInLayoutException if the specified fragment is not currently in the layout. - * @throws LayoutEventException If a triggered LayoutEvent fails. + * @throws FragmentNotInLayoutException + * if the specified fragment is not currently in the layout. + * @throws LayoutEventException + * If a triggered LayoutEvent fails. */ - public void moveUp(Fragment fragment) throws FragmentNotInLayoutException, LayoutEventException + public void moveUp(Fragment fragment) throws FragmentNotInLayoutException, + LayoutEventException { LayoutCoordinate coordinate = getCoordinate(fragment); - LayoutCoordinate aboveLayoutCoordinate = new LayoutCoordinate(coordinate.getX(), coordinate.getY() - 1); + LayoutCoordinate aboveLayoutCoordinate = new LayoutCoordinate( + coordinate.getX(), coordinate.getY() - 1); LayoutCoordinate newCoordinate = aboveLayoutCoordinate; // never go "above" 0. @@ -555,26 +618,30 @@ try { // now move the fragment above down one level. - /*Fragment fragmentAbove =*/ getFragmentAt(aboveLayoutCoordinate); + /* Fragment fragmentAbove = */getFragmentAt(aboveLayoutCoordinate); doMove(fragment, coordinate, newCoordinate); - processEvent(new LayoutEvent(LayoutEvent.MOVED_UP, fragment, coordinate, newCoordinate)); + processEvent(new LayoutEvent(LayoutEvent.MOVED_UP, + fragment, coordinate, newCoordinate)); } catch (EmptyLayoutLocationException e) { - // Nothing above??? Then scoot all elements below up one level. + // Nothing above??? Then scoot all elements below up one + // level. doMove(fragment, coordinate, newCoordinate); - processEvent(new LayoutEvent(LayoutEvent.MOVED_UP, fragment, coordinate, newCoordinate)); - - // If this the last row, make sure to update the next row pointer accordingly. - if(coordinate.getY() == (nextRowNumber[coordinate.getX()] - 1)) + processEvent(new LayoutEvent(LayoutEvent.MOVED_UP, + fragment, coordinate, newCoordinate)); + + // If this the last row, make sure to update the next row + // pointer accordingly. + if (coordinate.getY() == (nextRowNumber[coordinate.getX()] - 1)) { nextRowNumber[coordinate.getX()] = coordinate.getX(); } - + try { - Fragment fragmentBelow = getFragmentAt(new LayoutCoordinate(coordinate.getX(), - coordinate.getY() + 1)); + Fragment fragmentBelow = getFragmentAt(new LayoutCoordinate( + coordinate.getX(), coordinate.getY() + 1)); moveUp(fragmentBelow); } catch (EmptyLayoutLocationException e1) @@ -585,8 +652,11 @@ } catch (InvalidLayoutLocationException e) { - // This should NEVER happen as the location has already been verfied to be valid - throw new LayoutError("It appears this layout is corrupt and cannot correctly identify valid column locations.", e); + // This should NEVER happen as the location has already been + // verfied to be valid + throw new LayoutError( + "It appears this layout is corrupt and cannot correctly identify valid column locations.", + e); } } } @@ -594,13 +664,17 @@ /** * * @param fragment - * @throws FragmentNotInLayoutException if the specified fragment is not currently in the layout. - * @throws LayoutEventException If a triggered LayoutEvent fails. + * @throws FragmentNotInLayoutException + * if the specified fragment is not currently in the layout. + * @throws LayoutEventException + * If a triggered LayoutEvent fails. */ - public void moveDown(Fragment fragment) throws FragmentNotInLayoutException, LayoutEventException + public void moveDown(Fragment fragment) + throws FragmentNotInLayoutException, LayoutEventException { LayoutCoordinate coordinate = getCoordinate(fragment); - LayoutCoordinate newCoordinate = new LayoutCoordinate(coordinate.getX(), coordinate.getY() + 1); + LayoutCoordinate newCoordinate = new LayoutCoordinate( + coordinate.getX(), coordinate.getY() + 1); // never move past the current bottom row if (newCoordinate.getY() < nextRowNumber[coordinate.getX()]) @@ -609,27 +683,35 @@ { try { - // the best approach to move a fragment down is to actually move + // the best approach to move a fragment down is to actually + // move // its neighbor underneath up - LayoutCoordinate aboveCoord = new LayoutCoordinate(coordinate.getX(), coordinate.getY() + 1); + LayoutCoordinate aboveCoord = new LayoutCoordinate( + coordinate.getX(), coordinate.getY() + 1); Fragment fragmentBelow = getFragmentAt(aboveCoord); doMove(fragmentBelow, aboveCoord, coordinate); - processEvent(new LayoutEvent(LayoutEvent.MOVED_UP, fragmentBelow, aboveCoord, coordinate)); - // Since this logic path is a somewhat special case, the processing of the MOVED_DOWN + processEvent(new LayoutEvent(LayoutEvent.MOVED_UP, + fragmentBelow, aboveCoord, coordinate)); + // Since this logic path is a somewhat special case, the + // processing of the MOVED_DOWN // event happens within the doAdd() method. } catch (EmptyLayoutLocationException e) { doMove(fragment, coordinate, newCoordinate); - processEvent(new LayoutEvent(LayoutEvent.MOVED_DOWN, fragment, coordinate, newCoordinate)); + processEvent(new LayoutEvent(LayoutEvent.MOVED_DOWN, + fragment, coordinate, newCoordinate)); } } catch (InvalidLayoutLocationException e) { - // This should NEVER happen as the location has already been verfied to be valid - throw new LayoutError("It appears this layout is corrupt and cannot correctly identify valid column locations.", e); + // This should NEVER happen as the location has already been + // verfied to be valid + throw new LayoutError( + "It appears this layout is corrupt and cannot correctly identify valid column locations.", + e); } - + } } @@ -641,9 +723,10 @@ * @param oldCoordinate * @param newCoordinate * @throws InvalidLayoutLocationException - * @throws LayoutEventException + * @throws LayoutEventException */ - protected void doMove(Fragment fragment, LayoutCoordinate oldCoordinate, LayoutCoordinate newCoordinate) + protected void doMove(Fragment fragment, LayoutCoordinate oldCoordinate, + LayoutCoordinate newCoordinate) throws InvalidLayoutLocationException, LayoutEventException { SortedMap oldColumn = getColumnMap(oldCoordinate.getX()); @@ -654,15 +737,18 @@ } /** - * * - * @param fragment fragment whose LayoutCoordinate we ant. + * + * @param fragment + * fragment whose LayoutCoordinate we ant. * @return LayoutCoordinate representing the current location of this - * Fragment within this layout. - * @throws FragmentNotInLayoutException if the Fragment is not present in this layout. + * Fragment within this layout. + * @throws FragmentNotInLayoutException + * if the Fragment is not present in this layout. * @see LayoutCoordinate */ - public LayoutCoordinate getCoordinate(Fragment fragment) throws FragmentNotInLayoutException + public LayoutCoordinate getCoordinate(Fragment fragment) + throws FragmentNotInLayoutException { if (coordinates.containsKey(fragment)) { @@ -675,21 +761,25 @@ } /** - * Adds a fragment at the indicated columnNumber - * and rowNumber. + * Adds a fragment at the indicated columnNumber and + * rowNumber. * * @param columnNumber * @param rowNumber * @param fragment - * @throws InvalidLayoutLocationException if the coordinates are outside the bounds of this layout. - * @throws LayoutEventException id a LayoutEvent fails + * @throws InvalidLayoutLocationException + * if the coordinates are outside the bounds of this layout. + * @throws LayoutEventException + * id a LayoutEvent fails */ - protected void doAdd(int columnNumber, int rowNumber, Fragment fragment) throws InvalidLayoutLocationException, LayoutEventException + protected void doAdd(int columnNumber, int rowNumber, Fragment fragment) + throws InvalidLayoutLocationException, LayoutEventException { SortedMap column = getColumnMap(columnNumber); - + Integer rowInteger = new Integer(rowNumber); - LayoutCoordinate targetCoordinate = new LayoutCoordinate(columnNumber, rowNumber); + LayoutCoordinate targetCoordinate = new LayoutCoordinate(columnNumber, + rowNumber); if (column.containsKey(rowInteger)) { // If the row has something in it, push everythin down 1 @@ -697,33 +787,36 @@ column.put(rowInteger, fragment); coordinates.put(fragment, targetCoordinate); doAdd(columnNumber, ++rowNumber, existingFragment); - - LayoutCoordinate oneDownCoordinate = new LayoutCoordinate(targetCoordinate.getX(), targetCoordinate.getY() + 1); - processEvent(new LayoutEvent(LayoutEvent.MOVED_DOWN, existingFragment, targetCoordinate, oneDownCoordinate)); + + LayoutCoordinate oneDownCoordinate = new LayoutCoordinate( + targetCoordinate.getX(), targetCoordinate.getY() + 1); + processEvent(new LayoutEvent(LayoutEvent.MOVED_DOWN, + existingFragment, targetCoordinate, oneDownCoordinate)); } else { column.put(rowInteger, fragment); coordinates.put(fragment, targetCoordinate); rowNumber++; - if(rowNumber > nextRowNumber[columnNumber]) + if (rowNumber > nextRowNumber[columnNumber]) { nextRowNumber[columnNumber] = rowNumber; } } - + } /** - * Retrieves this specified columnNumber as a - * SortedMap. + * Retrieves this specified columnNumber as a SortedMap. * * @param columnNumber * @return - * @throws InvalidLayoutLocationException if the columnNumber resides - * outside the bounds of this layout. + * @throws InvalidLayoutLocationException + * if the columnNumber resides outside the bounds + * of this layout. */ - protected final SortedMap getColumnMap(int columnNumber) throws InvalidLayoutLocationException + protected final SortedMap getColumnMap(int columnNumber) + throws InvalidLayoutLocationException { Integer columnNumberIneteger = new Integer(columnNumber); @@ -739,9 +832,10 @@ } /** - * Gets the row number of this fragment to looking the layoutType - * property row. If this property is undefined, the bottom-most row - * number of currentColumn is returned. + * Gets the row number of this fragment to looking the + * layoutType property row. If this property is + * undefined, the bottom-most row number of currentColumn is + * returned. * * @param currentColumn * @param fragment @@ -762,11 +856,11 @@ } /** - * Gets the row number of this fragment to looking the layoutType - * property column. + * Gets the row number of this fragment to looking the + * layoutType property column. * * If the column is undefined or exceeds the constriants of this - * layout, the value returned is numberOfColumns - 1. If the + * layout, the value returned is numberOfColumns - 1. If the * value is less than 0, 0 is returned. * * @@ -775,7 +869,8 @@ */ protected final int getColumn(Fragment fragment) { - String propertyValue = fragment.getProperty(Fragment.COLUMN_PROPERTY_NAME); + String propertyValue = fragment + .getProperty(Fragment.COLUMN_PROPERTY_NAME); if (propertyValue != null) { int columnNumber = Integer.parseInt(propertyValue); @@ -798,22 +893,26 @@ return (numberOfColumns - 1); } } - + /** - * Dispatches a LayoutEvent to all LayoutEventListeners registered to this layout. + * Dispatches a LayoutEvent to all LayoutEventListeners registered to this + * layout. * * @param event - * @throws LayoutEventException if an error occurs while processing a the LayoutEvent. + * @throws LayoutEventException + * if an error occurs while processing a the LayoutEvent. */ - protected final void processEvent(LayoutEvent event) throws LayoutEventException + protected final void processEvent(LayoutEvent event) + throws LayoutEventException { Iterator itr = eventListeners.iterator(); - while(itr.hasNext()) + while (itr.hasNext()) { - LayoutEventListener eventListener = (LayoutEventListener) itr.next(); + LayoutEventListener eventListener = (LayoutEventListener) itr + .next(); eventListener.handleEvent(event); } - + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/EmptyLayoutLocationException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/EmptyLayoutLocationException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/EmptyLayoutLocationException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,19 +16,20 @@ */ package org.apache.jetspeed.portlets.layout; - /** - * This exception indicates that an attempt to access a layout - * coordinate that does not contain a Fragment. + * This exception indicates that an attempt to access a layout coordinate that + * does not contain a Fragment. * * @author Scott T. Weaver * @see org.apache.jetspeed.portlets.layout.ColumnLayout */ public class EmptyLayoutLocationException extends LayoutException { + public EmptyLayoutLocationException(int column, int row) { - super("No fragment is located in this layout at column:"+column+" row:"+row); + super("No fragment is located in this layout at column:" + column + + " row:" + row); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/FragmentNotInLayoutException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/FragmentNotInLayoutException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/FragmentNotInLayoutException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,20 +18,21 @@ import org.apache.jetspeed.om.page.Fragment; - /** - * This exception indicates that an attmept was made get the coordinates - * within a layout for a fragement that is not within that layout. + * This exception indicates that an attmept was made get the coordinates within + * a layout for a fragement that is not within that layout. * * @author Scott T. Weaver * @see org.apache.jetspeed.portlets.layout.ColumnLayout */ public class FragmentNotInLayoutException extends LayoutException { + public FragmentNotInLayoutException(Fragment fragment) { - super("The fragment "+fragment != null ?fragment.getId():"{null fragment}"+" could not be located in this layout."); - + super("The fragment " + fragment != null ? fragment.getId() + : "{null fragment}" + " could not be located in this layout."); + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/InvalidLayoutLocationException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/InvalidLayoutLocationException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/InvalidLayoutLocationException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,23 +16,24 @@ */ package org.apache.jetspeed.portlets.layout; - /** - * Indicates an attempt to access a local within a layout that is outside - * of the bounds of that layout. + * Indicates an attempt to access a local within a layout that is outside of the + * bounds of that layout. * * @author Scott T. Weaver - * + * */ public class InvalidLayoutLocationException extends LayoutException { + public InvalidLayoutLocationException(LayoutCoordinate coordinate) { - super("Invalid layout coordinate "+coordinate.toString()); - } - + super("Invalid layout coordinate " + coordinate.toString()); + } + public InvalidLayoutLocationException(int column) { - super("Column number "+column+" is not a valid column for this layout."); + super("Column number " + column + + " is not a valid column for this layout."); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutCoordinate.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutCoordinate.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutCoordinate.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,19 +23,21 @@ * Simple class that holds an x,y (column,row) coordinate. * * @author Scott T. Weaver - * + * */ public final class LayoutCoordinate implements Comparable, Serializable { + private final int x; + private final int y; - + public LayoutCoordinate(int x, int y) { this.x = x; this.y = y; } - + /** * @return the x axis (column) value of this coordinate. */ @@ -43,7 +45,7 @@ { return x; } - + /** * @return the y axis (row) value of this coordinate. */ @@ -51,13 +53,14 @@ { return y; } - + /** - * Two LayoutCoordinates are equal if thier respective x and y values are equal. + * Two LayoutCoordinates are equal if thier respective x and y values are + * equal. */ public boolean equals(Object obj) { - if(obj instanceof LayoutCoordinate) + if (obj instanceof LayoutCoordinate) { LayoutCoordinate coordinate = (LayoutCoordinate) obj; return x == coordinate.x && y == coordinate.y; @@ -69,35 +72,34 @@ } public int hashCode() - { + { return toString().hashCode(); } public String toString() - { - return x+","+y; + { + return x + "," + y; } public int compareTo(Object obj) { LayoutCoordinate coordinate = (LayoutCoordinate) obj; - if(!coordinate.equals(this)) + if (!coordinate.equals(this)) { - if(y == coordinate.y) - { - return x > coordinate.x ? 1 : -1; - } - else - { - return y > coordinate.y ? 1 : -1; - } - + if (y == coordinate.y) + { + return x > coordinate.x ? 1 : -1; + } + else + { + return y > coordinate.y ? 1 : -1; + } + } else { return 0; } } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutError.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutError.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutError.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,15 +18,16 @@ /** * - * Should only be thrown when something truely unexpected happens - * when processing a layout. Basically used in the case where something - * that "should never happen" happens. + * Should only be thrown when something truely unexpected happens when + * processing a layout. Basically used in the case where something that "should + * never happen" happens. * * @author Scott T. Weaver - * + * */ public class LayoutError extends Error { + private static final String BUG_MESSAGE = "Congratulations!!! You have found a bug! Please log this issue at http://issues.apache.org/jira."; public LayoutError() @@ -36,7 +37,7 @@ public LayoutError(String message) { - super(BUG_MESSAGE+"\n"+message); + super(BUG_MESSAGE + "\n" + message); } public LayoutError(Throwable cause) @@ -46,7 +47,7 @@ public LayoutError(String message, Throwable cause) { - super(BUG_MESSAGE+"\n"+message, cause); + super(BUG_MESSAGE + "\n" + message, cause); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutEvent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutEvent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutEvent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,14 +20,15 @@ /** * A LayoutEvent is used by ColumnLayout to notify its LayoutAeventListeners - * that there have been a change in the position of a fragment within the layout. + * that there have been a change in the position of a fragment within the + * layout. *

      Constant Values

      *
        - *
      • ADDED == 0
      • - *
      • MOVED_UP == 1
      • - *
      • MOVED_DOWN == 2
      • - *
      • MOVED_LEFT == 3
      • - *
      • MOVED_RIGHT == 4
      • + *
      • ADDED == 0
      • + *
      • MOVED_UP == 1
      • + *
      • MOVED_DOWN == 2
      • + *
      • MOVED_LEFT == 3
      • + *
      • MOVED_RIGHT == 4
      • *
      * * @@ -35,56 +36,70 @@ * @see org.apache.jetspeed.om.page.Fragment * @see org.apache.jetspeed.portlets.layout.LayoutEventListener * @see org.apache.jetspeed.portlets.layout.ColumnLayout - * + * */ public class LayoutEvent -{ - /**Event type value that notifies that a fragment has been added */ - public static final int ADDED =0; - /**Event type value that notifies that a fragment has been moved up */ +{ + + /** Event type value that notifies that a fragment has been added */ + public static final int ADDED = 0; + + /** Event type value that notifies that a fragment has been moved up */ public static final int MOVED_UP = 1; - /**Event type value that notifies that a fragment has been moved down */ + + /** Event type value that notifies that a fragment has been moved down */ public static final int MOVED_DOWN = 2; - /**Event type value that notifies that a fragment has been moved left */ + + /** Event type value that notifies that a fragment has been moved left */ public static final int MOVED_LEFT = 3; - /**Event type value that notifies that a fragment has been moved right */ + + /** Event type value that notifies that a fragment has been moved right */ public static final int MOVED_RIGHT = 4; - + private final int eventType; + private final Fragment fragment; + private final LayoutCoordinate originalCoordinate; - private final LayoutCoordinate newCoordinate; - + + private final LayoutCoordinate newCoordinate; + /** * - * @param eventType The type of event (see the event constants) - * @param fragment Fragment that is the target of this event. - * @param originalCoordinate the previous LayoutCoordinate of this Fragment - * @param newCoordinate the new and current coordinates of this fragment. + * @param eventType + * The type of event (see the event constants) + * @param fragment + * Fragment that is the target of this event. + * @param originalCoordinate + * the previous LayoutCoordinate of this Fragment + * @param newCoordinate + * the new and current coordinates of this fragment. * @see org.apache.jetspeed.om.page.Fragment */ - public LayoutEvent(int eventType, Fragment fragment, LayoutCoordinate originalCoordinate, LayoutCoordinate newCoordinate) + public LayoutEvent(int eventType, Fragment fragment, + LayoutCoordinate originalCoordinate, LayoutCoordinate newCoordinate) { - super(); + super(); this.eventType = eventType; this.fragment = fragment; this.originalCoordinate = originalCoordinate; this.newCoordinate = newCoordinate; } - - - /** + + /** * Returns the event type (see event constants) + * * @return the event type (see event constants) * @see ColumnLayout#layoutType - */ + */ public int getEventType() { return eventType; } - + /** * Returns the fragment that is the target of this event. + * * @return Fragment the fragment that is the target of this event. * @see org.apache.jetspeed.om.page.Fragment */ @@ -92,20 +107,26 @@ { return fragment; } - + /** - * Returns the new/current coordinate of the Fragment targeted by this event. - * @return the new/current coordinate of the Fragment targeted by this event. + * Returns the new/current coordinate of the Fragment targeted by this + * event. + * + * @return the new/current coordinate of the Fragment targeted by this + * event. * @see LayoutCoordinate */ public LayoutCoordinate getNewCoordinate() { return newCoordinate; } - + /** - * Returns the original (prior to the event) coordinate of the Fragment targeted by this event. - * @return the original (prior to the event) coordinate of the Fragment targeted by this event. + * Returns the original (prior to the event) coordinate of the Fragment + * targeted by this event. + * + * @return the original (prior to the event) coordinate of the Fragment + * targeted by this event. * @see LayoutCoordinate */ public LayoutCoordinate getOriginalCoordinate() @@ -113,17 +134,16 @@ return originalCoordinate; } - public boolean equals(Object obj) { - if(obj instanceof LayoutEvent) + if (obj instanceof LayoutEvent) { LayoutEvent event = (LayoutEvent) obj; - return event.fragment.equals(fragment) - && event.eventType == eventType - && event.originalCoordinate.equals(originalCoordinate) - && event.newCoordinate.equals(newCoordinate); - + return event.fragment.equals(fragment) + && event.eventType == eventType + && event.originalCoordinate.equals(originalCoordinate) + && event.newCoordinate.equals(newCoordinate); + } else { @@ -131,12 +151,11 @@ } } - public String toString() - { - return "event_target="+fragment.getId()+",event_type_code="+ eventType + ",orginial_coordinate="+ originalCoordinate+ - ",new_coordinate="+newCoordinate; + { + return "event_target=" + fragment.getId() + ",event_type_code=" + + eventType + ",orginial_coordinate=" + originalCoordinate + + ",new_coordinate=" + newCoordinate; } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutEventListener.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutEventListener.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutEventListener.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,8 +18,7 @@ /** * - * Interface to be implemented by classes that want to handle - * LayoutEvents + * Interface to be implemented by classes that want to handle LayoutEvents * * @author Scott T. Weaver * @see LayoutEvent @@ -27,11 +26,14 @@ */ public interface LayoutEventListener { + /** * Invoked anytime a LayoutEvent is dispatched. * - * @param event LayoutEvent that has been dispatched. - * @throws LayoutEventException if an error occurs will processing the event. + * @param event + * LayoutEvent that has been dispatched. + * @throws LayoutEventException + * if an error occurs will processing the event. */ void handleEvent(LayoutEvent event) throws LayoutEventException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/LayoutException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,7 +16,6 @@ */ package org.apache.jetspeed.portlets.layout; - import org.apache.jetspeed.exception.JetspeedException; import org.apache.jetspeed.i18n.KeyedMessage; @@ -24,7 +23,7 @@ * Base exception for all layout exceptions. * * @author Scott T. Weaver - * + * */ public class LayoutException extends JetspeedException { @@ -41,7 +40,7 @@ public LayoutException(KeyedMessage typedMessage) { - super(typedMessage); + super(typedMessage); } public LayoutException(Throwable nested) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/PageManagerLayoutEventListener.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/PageManagerLayoutEventListener.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/portlets/layout/PageManagerLayoutEventListener.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.portlets.layout; import org.apache.jetspeed.om.page.Fragment; @@ -22,10 +22,13 @@ public class PageManagerLayoutEventListener implements LayoutEventListener { + private final PageManager pageManager; + private final Page page; - - public PageManagerLayoutEventListener(PageManager pageManager, Page page, String layoutType) + + public PageManagerLayoutEventListener(PageManager pageManager, Page page, + String layoutType) { this.pageManager = pageManager; this.page = page; @@ -35,7 +38,7 @@ { try { - if(event.getEventType() == LayoutEvent.ADDED) + if (event.getEventType() == LayoutEvent.ADDED) { page.getRootFragment().getFragments().add(event.getFragment()); pageManager.updatePage(page); @@ -44,8 +47,10 @@ { Fragment fragment = event.getFragment(); LayoutCoordinate coordinate = event.getNewCoordinate(); - fragment.getProperties().put(Fragment.COLUMN_PROPERTY_NAME, String.valueOf(coordinate.getX())); - fragment.getProperties().put(Fragment.ROW_PROPERTY_NAME, String.valueOf(coordinate.getY())); + fragment.getProperties().put(Fragment.COLUMN_PROPERTY_NAME, + String.valueOf(coordinate.getX())); + fragment.getProperties().put(Fragment.ROW_PROPERTY_NAME, + String.valueOf(coordinate.getY())); pageManager.updatePage(page); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/FolderPermission.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/FolderPermission.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/FolderPermission.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,51 +5,63 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security; import java.security.Permission; /** - *

      Folder permission.

      - *

      This code was partially inspired from:

      + *

      + * Folder permission. + *

      + *

      + * This code was partially inspired from: + *

      * + *

      This class represents access to a portal content/folder or document. A + * FolderPermission consists of a pathname and a set of actions valid for that + * pathname.

      Pathname is the pathname of the folder or document granted the + * specified actions. A pathname that ends in "/*" (where "/" is the separator + * character) indicates all the folders and documents contained in that folder. + * A pathname that ends with "/-" indicates (recursively) all documents and + * subfolders contained in that directory. A pathname consisting of the special + * token "<<ALL FILES>>" matches any folder or document. *

      - * This class represents access to a portal content/folder or document. A FolderPermission consists - * of a pathname and a set of actions valid for that pathname. - *

      - * Pathname is the pathname of the folder or document granted the specified - * actions. A pathname that ends in "/*" (where "/" is - * the separator character) indicates all the folders and documents contained in that folder. - * A pathname that ends with "/-" indicates (recursively) all documents - * and subfolders contained in that directory. A pathname consisting of - * the special token "<<ALL FILES>>" matches any folder or document. - *

      - * + * * @author David Sean Taylor - * @author Christophe Lombart + * @author Christophe + * Lombart * @version $Id: FolderPermission.java 516448 2007-03-09 16:25:47Z ate $ */ public class FolderPermission extends PortalResourcePermission { + public static final char RECURSIVE_CHAR = '-'; + public static final char WILD_CHAR = '*'; - public static final String WILD_CHAR_STR = new String(new char[]{WILD_CHAR}); + + public static final String WILD_CHAR_STR = new String(new char[] + {WILD_CHAR}); + public static final char FOLDER_SEPARATOR = '/'; - public static final String FOLDER_SEPARATOR_STR = new String(new char[]{FOLDER_SEPARATOR}); + public static final String FOLDER_SEPARATOR_STR = new String(new char[] + {FOLDER_SEPARATOR}); + // does path indicate a folder? (wildcard or recursive) private boolean folder; @@ -59,10 +71,14 @@ private String cpath; /** - *

      Constructor for FolderPermission.

      - * - * @param name The portlet name. - * @param actions The actions on the portlet. + *

      + * Constructor for FolderPermission. + *

      + * + * @param name + * The portlet name. + * @param actions + * The actions on the portlet. */ public FolderPermission(String name, String actions) { @@ -71,10 +87,14 @@ } /** - *

      Constructor for FolderPermission.

      - * - * @param name The portlet name. - * @param mask The mask of actions on the portlet. + *

      + * Constructor for FolderPermission. + *

      + * + * @param name + * The portlet name. + * @param mask + * The mask of actions on the portlet. */ public FolderPermission(String name, int mask) { @@ -83,7 +103,9 @@ } /** - *

      Parses the path.

      + *

      + * Parses the path. + *

      */ private void parsePath() { @@ -99,62 +121,64 @@ } int len = cpath.length(); - if (len == 0) - { - throw new IllegalArgumentException("invalid folder reference"); - } + if (len == 0) { throw new IllegalArgumentException( + "invalid folder reference"); } char last = cpath.charAt(len - 1); - if (last == RECURSIVE_CHAR && (len == 1 || cpath.charAt(len - 2) == FOLDER_SEPARATOR)) + if (last == RECURSIVE_CHAR + && (len == 1 || cpath.charAt(len - 2) == FOLDER_SEPARATOR)) { folder = true; recursive = true; cpath = cpath.substring(0, --len); } - else if (last == WILD_CHAR && (len == 1 || cpath.charAt(len - 2) == FOLDER_SEPARATOR)) + else if (last == WILD_CHAR + && (len == 1 || cpath.charAt(len - 2) == FOLDER_SEPARATOR)) { folder = true; - //recursive = false; + // recursive = false; cpath = cpath.substring(0, --len); } } /** - * Checks if this FolderPermission object "implies" the specified permission. - *

      - * More specifically, this method returns true if:

      + * Checks if this FolderPermission object "implies" the specified + * permission.

      More specifically, this method returns true if: + *

      *

        - *
      • p is an instanceof FolderPermission,

        - *

      • p's actions are a proper subset of this - * object's actions, and

        - *

      • p's pathname is implied by this object's - * pathname. For example, "/tmp/*" implies "/tmp/foo", since - * "/tmp/*" encompasses the "/tmp" folder and all subfolders or documents in that - * directory, including the one named "foo". + *
      • p is an instanceof FolderPermission, + *

        + *

      • p's actions are a proper subset of this object's actions, + * and + *

        + *

      • p's pathname is implied by this object's pathname. For + * example, "/tmp/*" implies "/tmp/foo", since "/tmp/*" encompasses the + * "/tmp" folder and all subfolders or documents in that directory, + * including the one named "foo". *
      - * - * @param p the permission to check against. - * @return true if the specified permission is implied by this object, - * false if not. + * + * @param p + * the permission to check against. + * @return true if the specified permission is implied by this object, false + * if not. */ public boolean implies(Permission p) { - if (!(p instanceof FolderPermission)) - { - return false; - } + if (!(p instanceof FolderPermission)) { return false; } FolderPermission that = (FolderPermission) p; - return ((this.mask & that.mask) == that.mask) && impliesIgnoreMask(that); + return ((this.mask & that.mask) == that.mask) + && impliesIgnoreMask(that); } /** - * Checks if the Permission's actions are a proper subset of the - * this object's actions. Returns the effective mask iff the - * this FolderPermission's path also implies that FolderPermission's path. - * - * @param that the FolderPermission to check against. + * Checks if the Permission's actions are a proper subset of the this + * object's actions. Returns the effective mask iff the this + * FolderPermission's path also implies that FolderPermission's path. + * + * @param that + * the FolderPermission to check against. * @return the effective mask */ boolean impliesIgnoreMask(FolderPermission that) @@ -167,11 +191,13 @@ // something like /foo/- does not imply /foo if (that.folder) { - return (that.cpath.length() >= this.cpath.length()) && that.cpath.startsWith(this.cpath); + return (that.cpath.length() >= this.cpath.length()) + && that.cpath.startsWith(this.cpath); } else { - return ((that.cpath.length() >= this.cpath.length()) && that.cpath.startsWith(this.cpath)); + return ((that.cpath.length() >= this.cpath.length()) && that.cpath + .startsWith(this.cpath)); } } else @@ -197,7 +223,9 @@ // this.cpath.equals(that.cpath.substring(0, last+1)); // Use regionMatches to avoid creating new string - return (this.cpath.length() == (last + 1)) && this.cpath.regionMatches(0, that.cpath, 0, last + 1); + return (this.cpath.length() == (last + 1)) + && this.cpath.regionMatches(0, that.cpath, 0, + last + 1); } } } @@ -209,31 +237,31 @@ } /** - * Checks two FolderPermission objects for equality. Checks that obj is - * a FolderPermission, and has the same pathname and actions as this object. - *

      - * - * @param obj the object we are testing for equality with this object. + * Checks two FolderPermission objects for equality. Checks that obj + * is a FolderPermission, and has the same pathname and actions as this + * object.

      + * + * @param obj + * the object we are testing for equality with this object. * @return true if obj is a FolderPermission, and has the same pathname and * actions as this FolderPermission object. */ public boolean equals(Object obj) { - if (obj == this) - return true; + if (obj == this) return true; - if (!(obj instanceof FolderPermission)) - return false; + if (!(obj instanceof FolderPermission)) return false; FolderPermission that = (FolderPermission) obj; - return (this.mask == that.mask) && this.cpath.equals(that.cpath) && (this.folder == that.folder) + return (this.mask == that.mask) && this.cpath.equals(that.cpath) + && (this.folder == that.folder) && (this.recursive == that.recursive); } /** * Returns the hash code value for this object. - * + * * @return a hash code value for this object. */ @@ -242,5 +270,4 @@ return this.cpath.hashCode(); } - } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/FragmentPermission.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/FragmentPermission.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/FragmentPermission.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,49 +5,58 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security; import java.security.Permission; /** - *

      Fragment permission.

      - *

      This code was partially inspired from articles from:

      + *

      + * Fragment permission. + *

      + *

      + * This code was partially inspired from articles from: + *

      * - *

      - * This class represents access to a fragment within a - * content document. A FragmentPermission consists - * of a path, fragment name, or a simple fragment name - * pattern and a set of actions valid for that pathname. - *

      - * Here are some examples of valid fragment permissions names: - *

    9. "/folder/page.psml/app::portlet" matches fragments - * within a page for a specified portlet contained in a app
    10. - *
    11. "security::*" matches fragments for portlets from the security app
    12. - *
    13. "<<ALL FRAGMENTS>>" matches any fragment
    14. - *

      - * + *

      This class represents access to a fragment within a content document. A + * FragmentPermission consists of a path, fragment name, or a simple fragment + * name pattern and a set of actions valid for that pathname.

      Here are some + * examples of valid fragment permissions names: + *

    15. "/folder/page.psml/app::portlet" matches fragments within a page for a + * specified portlet contained in a app + *
    16. + *
    17. "security::*" matches fragments for portlets from the security app + *
    18. + *
    19. "<<ALL FRAGMENTS>>" matches any fragment + *
    20. + * * @author Randy Watler */ public class FragmentPermission extends PortalResourcePermission { + /** - *

      Constructor for FragmentPermission.

      - * - * @param name The fragment name. - * @param actions The actions on the fragment. + *

      + * Constructor for FragmentPermission. + *

      + * + * @param name + * The fragment name. + * @param actions + * The actions on the fragment. */ public FragmentPermission(String name, String actions) { @@ -55,10 +64,14 @@ } /** - *

      Constructor for FragmentPermission.

      - * - * @param name The fragment name. - * @param mask The mask of actions on the fragment. + *

      + * Constructor for FragmentPermission. + *

      + * + * @param name + * The fragment name. + * @param mask + * The mask of actions on the fragment. */ public FragmentPermission(String name, int mask) { @@ -69,10 +82,7 @@ { // The permission must be an instance // of the FragmentPermission. - if (!(permission instanceof FragmentPermission)) - { - return false; - } + if (!(permission instanceof FragmentPermission)) { return false; } FragmentPermission fragmentPerm = (FragmentPermission) permission; // Test fragment permission name matches @@ -83,7 +93,8 @@ // match wildcarded portlet names int testNamesSeparator = testName.lastIndexOf("::"); - if (ruleName.endsWith("::" + FolderPermission.WILD_CHAR_STR) && (testNamesSeparator > 0)) + if (ruleName.endsWith("::" + FolderPermission.WILD_CHAR_STR) + && (testNamesSeparator > 0)) { ruleName = ruleName.substring(0, ruleName.length() - 3); testName = testName.substring(0, testNamesSeparator); @@ -91,18 +102,17 @@ // trim path components from test name if rule // is not prefixed with the path - if (!ruleName.startsWith(FolderPermission.FOLDER_SEPARATOR_STR) && - testName.startsWith(FolderPermission.FOLDER_SEPARATOR_STR)) + if (!ruleName.startsWith(FolderPermission.FOLDER_SEPARATOR_STR) + && testName + .startsWith(FolderPermission.FOLDER_SEPARATOR_STR)) { - int testPathIndex = testName.lastIndexOf(FolderPermission.FOLDER_SEPARATOR); + int testPathIndex = testName + .lastIndexOf(FolderPermission.FOLDER_SEPARATOR); testName = testName.substring(testPathIndex + 1); } // remaining name parts must match - if (!ruleName.equals(testName)) - { - return false; - } + if (!ruleName.equals(testName)) { return false; } } // The action bits in FragmentPerm (permission) @@ -116,8 +126,7 @@ */ public boolean equals(Object object) { - if (!(object instanceof FragmentPermission)) - return false; + if (!(object instanceof FragmentPermission)) return false; FragmentPermission p = (FragmentPermission) object; return ((p.mask == mask) && (p.getName().equals(getName()))); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/JSSubject.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/JSSubject.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/JSSubject.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,214 +17,246 @@ package org.apache.jetspeed.security; /** - * Wrapper for the javax.security.auth.Subject class. - * Due to a design oversight in JAAS 1.0, the javax.security.auth.Subject.getSubject method does not return the Subject - * that is associated with the running thread !inside! a java.security.AccessController.doPrivileged code block. - * As a result, the current subject cannot be determined correctly. - * This class uses the ThreadLocal mechanism to carry the thread-specific instance of the subject + * Wrapper for the javax.security.auth.Subject class. Due to a design oversight + * in JAAS 1.0, the javax.security.auth.Subject.getSubject method does not + * return the Subject that is associated with the running thread !inside! a + * java.security.AccessController.doPrivileged code block. As a result, the + * current subject cannot be determined correctly. This class uses the + * ThreadLocal mechanism to carry the thread-specific instance of the subject + * * @author hajo - * + * */ -import javax.security.auth.*; import java.security.AccessControlContext; import java.security.PrivilegedActionException; +import javax.security.auth.Subject; - -public class JSSubject implements java.io.Serializable +public class JSSubject implements java.io.Serializable { private static final long serialVersionUID = -8308522755600156057L; - static ThreadLocal threadLocal = - new ThreadLocal(); - - - - + static ThreadLocal threadLocal = new ThreadLocal(); /** * Get the Subject associated with the provided - * AccessControlContext fromn the current Thread or from the standard SUBJECT mechansim + * AccessControlContext fromn the current Thread or from the + * standard SUBJECT mechansim *

      - * - * @param acc the AccessControlContext from which to retrieve - * the Subject. Only used if current thread doesn't carry subject - * - * @return the Subject associated with the provided - * AccessControlContext, or null - * if no Subject is associated - * with the provided AccessControlContext. - * - * @exception SecurityException if the caller does not have permission - * to get the Subject.

      - * - * @exception NullPointerException if the provided - * AccessControlContext is null. + * + * @param acc + * the AccessControlContext from which to retrieve + * the Subject. Only used if current thread + * doesn't carry subject + * + * @return the Subject associated with the provided + * AccessControlContext, or null if + * no Subject is associated with the provided + * AccessControlContext. + * + * @exception SecurityException + * if the caller does not have permission to get the + * Subject. + *

      + * + * @exception NullPointerException + * if the provided AccessControlContext is + * null. */ - public static Subject getSubject(final AccessControlContext acc) + public static Subject getSubject(final AccessControlContext acc) { - Subject s = null; - try - { - s= (Subject)threadLocal.get(); - } - catch (Exception e) - {} - if (s == null) - return Subject.getSubject(acc); - else - return s; + Subject s = null; + try + { + s = (Subject) threadLocal.get(); + } + catch (Exception e) + { + } + if (s == null) + return Subject.getSubject(acc); + else + return s; } /** - * Perform work as a particular Subject after setting subject reference in current thread - * - * @param subject the Subject that the specified - * action will run as. This parameter - * may be null.

      - * - * @param action the code to be run as the specified - * Subject.

      - * + * Perform work as a particular Subject after setting subject + * reference in current thread + * + * @param subject + * the Subject that the specified + * action will run as. This parameter may be + * null. + *

      + * + * @param action + * the code to be run as the specified Subject. + *

      + * * @return the Object returned by the PrivilegedAction's - * run method. - * - * @exception NullPointerException if the PrivilegedAction - * is null.

      - * - * @exception SecurityException if the caller does not have permission - * to invoke this method. + * run method. + * + * @exception NullPointerException + * if the PrivilegedAction is + * null. + *

      + * + * @exception SecurityException + * if the caller does not have permission to invoke this + * method. */ public static Object doAs(final Subject subject1, - final java.security.PrivilegedAction action) + final java.security.PrivilegedAction action) { - Subject subject = subject1; - if (subject == null) - subject = JSSubject.getSubject(null); - threadLocal.set(subject); - return Subject.doAs(subject,action); + Subject subject = subject1; + if (subject == null) subject = JSSubject.getSubject(null); + threadLocal.set(subject); + return Subject.doAs(subject, action); } /** - * Perform work as a particular Subject after setting subject reference in current thread. - * - * - * @param subject the Subject that the specified - * action will run as. This parameter - * may be null.

      - * - * @param action the code to be run as the specified - * Subject.

      - * + * Perform work as a particular Subject after setting subject + * reference in current thread. + * + * + * @param subject + * the Subject that the specified + * action will run as. This parameter may be + * null. + *

      + * + * @param action + * the code to be run as the specified Subject. + *

      + * * @return the Object returned by the - * PrivilegedExceptionAction's run method. - * - * @exception PrivilegedActionException if the - * PrivilegedExceptionAction.run - * method throws a checked exception.

      - * - * @exception NullPointerException if the specified - * PrivilegedExceptionAction is - * null.

      - * - * @exception SecurityException if the caller does not have permission - * to invoke this method. + * PrivilegedExceptionAction's run method. + * + * @exception PrivilegedActionException + * if the PrivilegedExceptionAction.run method + * throws a checked exception. + *

      + * + * @exception NullPointerException + * if the specified PrivilegedExceptionAction + * is null. + *

      + * + * @exception SecurityException + * if the caller does not have permission to invoke this + * method. */ public static Object doAs(final Subject subject1, - final java.security.PrivilegedExceptionAction action) - throws java.security.PrivilegedActionException - { - Subject subject = subject1; - if (subject == null) - subject = JSSubject.getSubject(null); - threadLocal.set(subject); - if (subject != null) - return Subject.doAs(subject,action); - else - return Subject.doAs(subject,action); - } + final java.security.PrivilegedExceptionAction action) + throws java.security.PrivilegedActionException + { + Subject subject = subject1; + if (subject == null) subject = JSSubject.getSubject(null); + threadLocal.set(subject); + if (subject != null) + return Subject.doAs(subject, action); + else + return Subject.doAs(subject, action); + } + /** - * Perform privileged work as a particular Subject after setting subject reference in current thread. - * - * - * @param subject the Subject that the specified - * action will run as. This parameter - * may be null.

      - * - * @param action the code to be run as the specified - * Subject.

      - * - * @param acc the AccessControlContext to be tied to the - * specified subject and action.

      - * + * Perform privileged work as a particular Subject after + * setting subject reference in current thread. + * + * + * @param subject + * the Subject that the specified + * action will run as. This parameter may be + * null. + *

      + * + * @param action + * the code to be run as the specified Subject. + *

      + * + * @param acc + * the AccessControlContext to be tied to the + * specified subject and action. + *

      + * * @return the Object returned by the PrivilegedAction's - * run method. - * - * @exception NullPointerException if the PrivilegedAction - * is null.

      - * - * @exception SecurityException if the caller does not have permission - * to invoke this method. + * run method. + * + * @exception NullPointerException + * if the PrivilegedAction is + * null. + *

      + * + * @exception SecurityException + * if the caller does not have permission to invoke this + * method. */ public static Object doAsPrivileged(final Subject subject1, - final java.security.PrivilegedAction action, - final java.security.AccessControlContext acc) { - Subject subject = subject1; - if (subject == null) - subject = JSSubject.getSubject(acc); - threadLocal.set(subject); - if (subject != null) - return Subject.doAsPrivileged(subject,action,acc); - else - return Subject.doAsPrivileged(subject,action,acc); - - } + final java.security.PrivilegedAction action, + final java.security.AccessControlContext acc) + { + Subject subject = subject1; + if (subject == null) subject = JSSubject.getSubject(acc); + threadLocal.set(subject); + if (subject != null) + return Subject.doAsPrivileged(subject, action, acc); + else + return Subject.doAsPrivileged(subject, action, acc); + } /** - * Perform privileged work as a particular Subject after setting subject reference in current thread. - * - * - * @param subject the Subject that the specified - * action will run as. This parameter - * may be null.

      - * - * @param action the code to be run as the specified - * Subject.

      - * - * @param acc the AccessControlContext to be tied to the - * specified subject and action.

      - * + * Perform privileged work as a particular Subject after + * setting subject reference in current thread. + * + * + * @param subject + * the Subject that the specified + * action will run as. This parameter may be + * null. + *

      + * + * @param action + * the code to be run as the specified Subject. + *

      + * + * @param acc + * the AccessControlContext to be tied to the + * specified subject and action. + *

      + * * @return the Object returned by the - * PrivilegedExceptionAction's run method. - * - * @exception PrivilegedActionException if the - * PrivilegedExceptionAction.run - * method throws a checked exception.

      - * - * @exception NullPointerException if the specified - * PrivilegedExceptionAction is - * null.

      - * - * @exception SecurityException if the caller does not have permission - * to invoke this method. + * PrivilegedExceptionAction's run method. + * + * @exception PrivilegedActionException + * if the PrivilegedExceptionAction.run method + * throws a checked exception. + *

      + * + * @exception NullPointerException + * if the specified PrivilegedExceptionAction + * is null. + *

      + * + * @exception SecurityException + * if the caller does not have permission to invoke this + * method. */ public static Object doAsPrivileged(final Subject subject, - final java.security.PrivilegedExceptionAction action, - final java.security.AccessControlContext acc) - throws java.security.PrivilegedActionException { - Subject s = subject; - if (s == null) - s = JSSubject.getSubject(acc); - threadLocal.set(s); - if (s != null) - return Subject.doAsPrivileged(s,action,acc); - else - return Subject.doAsPrivileged(s,action,acc); + final java.security.PrivilegedExceptionAction action, + final java.security.AccessControlContext acc) + throws java.security.PrivilegedActionException + { + Subject s = subject; + if (s == null) s = JSSubject.getSubject(acc); + threadLocal.set(s); + if (s != null) + return Subject.doAsPrivileged(s, action, acc); + else + return Subject.doAsPrivileged(s, action, acc); - } + } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PagePermission.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PagePermission.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PagePermission.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,36 +5,45 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security; import java.security.Permission; /** - *

      Folder permission.

      - *

      This code was partially inspired from articles from:

      + *

      + * Folder permission. + *

      + *

      + * This code was partially inspired from articles from: + *

      * - * + * * @author David Sean Taylor */ public class PagePermission extends PortalResourcePermission { + /** - *

      Constructor for PagePermission.

      - * - * @param name The portlet name. - * @param actions The actions on the portlet. + *

      + * Constructor for PagePermission. + *

      + * + * @param name + * The portlet name. + * @param actions + * The actions on the portlet. */ public PagePermission(String name, String actions) { @@ -42,10 +51,14 @@ } /** - *

      Constructor for PagePermission.

      - * - * @param name The portlet name. - * @param mask The mask for actions on the portlet. + *

      + * Constructor for PagePermission. + *

      + * + * @param name + * The portlet name. + * @param mask + * The mask for actions on the portlet. */ public PagePermission(String name, int mask) { @@ -54,18 +67,12 @@ public boolean implies(Permission permission) { - // The permission must be an instance + // The permission must be an instance // of the PortletPermission. - if (!(permission instanceof PagePermission)) - { - return false; - } + if (!(permission instanceof PagePermission)) { return false; } // The page name must be the same. - if (!(permission.getName().equals(getName()))) - { - return false; - } + if (!(permission.getName().equals(getName()))) { return false; } PagePermission pagePerm = (PagePermission) permission; @@ -80,8 +87,7 @@ */ public boolean equals(Object object) { - if (!(object instanceof PagePermission)) - return false; + if (!(object instanceof PagePermission)) return false; PagePermission p = (PagePermission) object; return ((p.mask == mask) && (p.getName().equals(getName()))); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PortalResourcePermission.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PortalResourcePermission.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PortalResourcePermission.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,45 +5,56 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security; -import org.apache.jetspeed.JetspeedActions; - import java.security.Permission; import java.security.PermissionCollection; +import org.apache.jetspeed.JetspeedActions; + /** - *

      Generalized Portlet Resoure permission.

      - *

      This code was partially inspired from articles from:

      + *

      + * Generalized Portlet Resoure permission. + *

      + *

      + * This code was partially inspired from articles from: + *

      * - * + * * @author David Le Strat * @author David Sean Taylor */ public abstract class PortalResourcePermission extends Permission { + /** - *

      Mask used for determining what actions are allowed or requested.

      + *

      + * Mask used for determining what actions are allowed or requested. + *

      */ protected final int mask; /** - *

      Constructor for PortletPermission.

      - * - * @param name The portlet name. - * @param actions The actions on the portlet. + *

      + * Constructor for PortletPermission. + *

      + * + * @param name + * The portlet name. + * @param actions + * The actions on the portlet. */ public PortalResourcePermission(String name, String actions) { @@ -52,10 +63,14 @@ } /** - *

      Constructor for PortletPermission.

      - * - * @param name The portlet name. - * @param mask The mask representing actions on the portlet. + *

      + * Constructor for PortletPermission. + *

      + * + * @param name + * The portlet name. + * @param mask + * The mask representing actions on the portlet. */ public PortalResourcePermission(String name, int mask) { @@ -80,19 +95,27 @@ return JetspeedActions.getContainerActions(mask); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.security.Permission#implies(java.security.Permission) */ public boolean implies(Permission permission) { - throw new IllegalStateException("Permission class did not implement implies"); + throw new IllegalStateException( + "Permission class did not implement implies"); } /** - *

      Parses the actions string.

      - *

      Actions are separated by commas or white space.

      - * - * @param actions The actions + *

      + * Parses the actions string. + *

      + *

      + * Actions are separated by commas or white space. + *

      + * + * @param actions + * The actions */ public static int parseActions(String actions) { @@ -100,8 +123,10 @@ } /** - *

      Overrides Permission.newPermissionCollection().

      - * + *

      + * Overrides Permission.newPermissionCollection(). + *

      + * * @see java.security.Permission#newPermissionCollection() */ public PermissionCollection newPermissionCollection() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PortalResourcePermissionCollection.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PortalResourcePermissionCollection.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PortalResourcePermissionCollection.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,12 +16,11 @@ */ package org.apache.jetspeed.security; -import java.util.Collections; - import java.security.Permission; import java.security.PermissionCollection; -import java.util.Enumeration; import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; import java.util.Iterator; /** @@ -37,7 +36,7 @@ */ public PortalResourcePermissionCollection() { - super(); + super(); } /** @@ -53,12 +52,9 @@ */ public boolean implies(Permission permission) { - for (Iterator i = perms.iterator(); i.hasNext(); ) + for (Iterator i = perms.iterator(); i.hasNext();) { - if (((Permission)i.next()).implies(permission)) - { - return true; - } + if (((Permission) i.next()).implies(permission)) { return true; } } return false; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PortletPermission.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PortletPermission.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/security/PortletPermission.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,23 +19,31 @@ import java.security.Permission; /** - *

      Portlet permission.

      - *

      This code was partially inspired from articles from:

      + *

      + * Portlet permission. + *

      + *

      + * This code was partially inspired from articles from: + *

      * - * + * * @author David Le Strat */ public class PortletPermission extends PortalResourcePermission { /** - *

      Constructor for PortletPermission.

      - * - * @param name The portlet name. - * @param actions The actions on the portlet. + *

      + * Constructor for PortletPermission. + *

      + * + * @param name + * The portlet name. + * @param actions + * The actions on the portlet. */ public PortletPermission(String name, String actions) { @@ -43,10 +51,14 @@ } /** - *

      Constructor for PortletPermission.

      - * - * @param name The portlet name. - * @param mask The mask of actions on the portlet. + *

      + * Constructor for PortletPermission. + *

      + * + * @param name + * The portlet name. + * @param mask + * The mask of actions on the portlet. */ public PortletPermission(String name, int mask) { @@ -55,12 +67,9 @@ public boolean implies(Permission permission) { - // The permission must be an instance + // The permission must be an instance // of the PortletPermission. - if (!(permission instanceof PortletPermission)) - { - return false; - } + if (!(permission instanceof PortletPermission)) { return false; } String name = getName(); if (name != null) @@ -68,10 +77,7 @@ int index = name.indexOf('*'); if (index > -1) { - if (!(permission.getName().startsWith(name.substring(0, index)))) - { - return false; - } + if (!(permission.getName().startsWith(name.substring(0, index)))) { return false; } } else if (!(permission.getName().equals(name))) { @@ -82,7 +88,7 @@ PortletPermission portletPerm = (PortletPermission) permission; - // The action bits in portletPerm (permission) + // The action bits in portletPerm (permission) // must be set in the current mask permission. return (mask & portletPerm.mask) == portletPerm.mask; @@ -93,8 +99,7 @@ */ public boolean equals(Object object) { - if (!(object instanceof PortletPermission)) - return false; + if (!(object instanceof PortletPermission)) return false; PortletPermission p = (PortletPermission) object; return ((p.mask == mask) && (p.getName().equals(getName()))); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/services/JetspeedPortletServices.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/services/JetspeedPortletServices.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/services/JetspeedPortletServices.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,47 +19,54 @@ import java.util.HashMap; import java.util.Map; - /** * JetspeedPortletServices - * + * * @author David Sean Taylor * @version $Id: JetspeedPortletServices.java 516448 2007-03-09 16:25:47Z ate $ */ public class JetspeedPortletServices implements PortletServices { + private Map services; + private static PortletServices singleton = null; - + /** - * Necessary evil until we get a PA component framework + * Necessary evil until we get a PA component framework + * * @return */ public static PortletServices getSingleton() { return singleton; } - + public JetspeedPortletServices() { this(new HashMap()); } - + public JetspeedPortletServices(Map services) { singleton = this; this.services = services; } - - /* (non-Javadoc) - * @see org.apache.jetspeed.components.PortletServices#addPortletService(java.lang.String, java.lang.Object) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.components.PortletServices#addPortletService(java.lang.String, + * java.lang.Object) */ public void addPortletService(String serviceName, Object service) { services.put(serviceName, service); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.components.PortletServices#getService(java.lang.String) */ public Object getService(String serviceName) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/services/PortletServices.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/services/PortletServices.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/services/PortletServices.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,16 +16,16 @@ */ package org.apache.jetspeed.services; - /** * PortletServices - * + * * @author David Sean Taylor * @version $Id: PortletServices.java 516448 2007-03-09 16:25:47Z ate $ */ public interface PortletServices { + void addPortletService(String serviceName, Object service); - + Object getService(String serviceName); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/AbstractFileSystemHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/AbstractFileSystemHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/AbstractFileSystemHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,25 +22,22 @@ import java.io.IOException; import java.io.InputStream; - /** * implements common directory and jar operations - * + * * @author David Sean Taylor * @version $Id: AbstractFileSystemHelper.java 516448 2007-03-09 16:25:47Z ate $ */ public abstract class AbstractFileSystemHelper { + public abstract File getRootDirectory(); - + public long getChecksum(String path) { File child = new File(getRootDirectory(), path); - if (child == null || !child.exists()) - { - return 0; - } - + if (child == null || !child.exists()) { return 0; } + long checksum = 0; InputStream is = null; try @@ -51,17 +48,18 @@ catch (FileNotFoundException e) { } - finally + finally { - if (is != null) - { - try - { - is.close(); - } - catch (IOException io) - {} - } + if (is != null) + { + try + { + is.close(); + } + catch (IOException io) + { + } + } } return checksum; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/ArgUtil.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/ArgUtil.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/ArgUtil.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,21 +25,28 @@ * * @author Scott T. Weaver * @version $Id: ArgUtil.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public final class ArgUtil { + private static final String MSG_1 = "Argument \""; + private static final String MSG_2 = "\" cannot be null for method "; /** * - * @throws java.lang.IllegalArgumentException If ANY of the arguments are null - * @param args array of arguments to validate as not nul - * @param argNames array of arguments names, idexes should match with args. - * @param methodName Name of method we are validating arguments for. + * @throws java.lang.IllegalArgumentException + * If ANY of the arguments are null + * @param args + * array of arguments to validate as not nul + * @param argNames + * array of arguments names, idexes should match with args. + * @param methodName + * Name of method we are validating arguments for. */ - public static void notNull(Object[] args, String[] argNames, String methodName) + public static void notNull(Object[] args, String[] argNames, + String methodName) { for (int i = 0; i < args.length; i++) { @@ -62,38 +69,45 @@ } } } - + /** * *

      * notNull *

      - * + * * @param nonNullObject * @param thisObject * @throws IllegalArgumentException */ - public static final void assertNotNull(Class nonNullClass, Object nonNullObject, Object thisObject) throws IllegalArgumentException + public static final void assertNotNull(Class nonNullClass, + Object nonNullObject, Object thisObject) + throws IllegalArgumentException { - if(nonNullObject == null) - { - throw new IllegalArgumentException(thisObject.getClass().getName()+" requires a non-null "+nonNullClass.getName()+" as an argument."); - } + if (nonNullObject == null) { throw new IllegalArgumentException( + thisObject.getClass().getName() + " requires a non-null " + + nonNullClass.getName() + " as an argument."); } } - - public static final void assertNotNull(Class nonNullClass, Object nonNullObject, Object thisObject, String methodName) throws IllegalArgumentException + + public static final void assertNotNull(Class nonNullClass, + Object nonNullObject, Object thisObject, String methodName) + throws IllegalArgumentException { - if(nonNullObject == null) - { - throw new IllegalArgumentException(thisObject.getClass().getName()+"."+methodName+" requires a non-null "+nonNullClass.getName()+" as an argument."); - } + if (nonNullObject == null) { throw new IllegalArgumentException( + thisObject.getClass().getName() + "." + methodName + + " requires a non-null " + nonNullClass.getName() + + " as an argument."); } } - - public static final void assertPropertyNotNull(Object nonNullObject, Object thisObject, String methodName, String property) throws IllegalArgumentException + + public static final void assertPropertyNotNull(Object nonNullObject, + Object thisObject, String methodName, String property) + throws IllegalArgumentException { - if(nonNullObject == null) - { - throw new IllegalStateException(thisObject.getClass().getName()+"."+methodName+" cannot be invoked until the property "+property+" has been set."); - } + if (nonNullObject == null) { throw new IllegalStateException(thisObject + .getClass().getName() + + "." + + methodName + + " cannot be invoked until the property " + + property + " has been set."); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/BaseObjectProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/BaseObjectProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/BaseObjectProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,72 +25,79 @@ * @author Woonsan Ko * @version $Id: BaseObjectProxy.java 516448 2007-03-09 16:25:47Z ate $ */ -public class BaseObjectProxy implements InvocationHandler +public class BaseObjectProxy implements InvocationHandler { protected static Method hashCodeMethod; + protected static Method equalsMethod; + protected static Method toStringMethod; - - static + + static { - try + try { - hashCodeMethod = Object.class.getMethod("hashCode", null); - equalsMethod = Object.class.getMethod("equals", new Class [] { Object.class }); - toStringMethod = Object.class.getMethod("toString", null); - } - catch (NoSuchMethodException e) + hashCodeMethod = Object.class.getMethod("hashCode", null); + equalsMethod = Object.class.getMethod("equals", new Class[] + {Object.class}); + toStringMethod = Object.class.getMethod("toString", null); + } + catch (NoSuchMethodException e) { - throw new NoSuchMethodError(e.getMessage()); - } + throw new NoSuchMethodError(e.getMessage()); + } } - - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable + + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { Object result = null; - Class declaringClass = method.getDeclaringClass(); + Class declaringClass = method.getDeclaringClass(); - if (declaringClass == Object.class) + if (declaringClass == Object.class) { - if (hashCodeMethod.equals(method)) + if (hashCodeMethod.equals(method)) { result = proxyHashCode(proxy); - } - else if (equalsMethod.equals(method)) + } + else if (equalsMethod.equals(method)) { result = proxyEquals(proxy, args[0]); - } - else if (toStringMethod.equals(method)) + } + else if (toStringMethod.equals(method)) { result = proxyToString(proxy); - } - else + } + else { - throw new InternalError("unexpected Object method dispatched: " + method); - } - } + throw new InternalError("unexpected Object method dispatched: " + + method); + } + } else { - throw new InternalError("unexpected Object method dispatched: " + method); + throw new InternalError("unexpected Object method dispatched: " + + method); } - + return result; } - - protected Integer proxyHashCode(Object proxy) + + protected Integer proxyHashCode(Object proxy) { - return new Integer(System.identityHashCode(proxy)); + return new Integer(System.identityHashCode(proxy)); } - protected Boolean proxyEquals(Object proxy, Object other) + protected Boolean proxyEquals(Object proxy, Object other) { - return (proxy == other ? Boolean.TRUE : Boolean.FALSE); + return (proxy == other ? Boolean.TRUE : Boolean.FALSE); } - protected String proxyToString(Object proxy) + protected String proxyToString(Object proxy) { - return proxy.getClass().getName() + '@' + Integer.toHexString(proxy.hashCode()); + return proxy.getClass().getName() + '@' + + Integer.toHexString(proxy.hashCode()); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/ChecksumHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/ChecksumHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/ChecksumHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,34 +16,34 @@ */ package org.apache.jetspeed.util; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; import java.util.zip.Adler32; import java.util.zip.CheckedInputStream; - /** * implements checksum related utilities - * + * * @author David Sean Taylor * @version $Id: ChecksumHelper.java 516448 2007-03-09 16:25:47Z ate $ */ public final class ChecksumHelper { + public static long getChecksum(InputStream is) { - CheckedInputStream cis = null; + CheckedInputStream cis = null; long checksum = 0; - try + try { cis = new CheckedInputStream(is, new Adler32()); byte[] tempBuf = new byte[128]; - while (cis.read(tempBuf) >= 0) + while (cis.read(tempBuf) >= 0) { } checksum = cis.getChecksum().getValue(); - } - catch (IOException e) + } + catch (IOException e) { checksum = 0; } @@ -56,11 +56,10 @@ cis.close(); } catch (IOException ioe) - { + { } } } return checksum; } } - \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/DirectoryHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/DirectoryHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/DirectoryHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,6 +19,7 @@ import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; @@ -27,117 +28,117 @@ * @author Scott T. Weaver * @version $Id: DirectoryHelper.java 516448 2007-03-09 16:25:47Z ate $ */ -public class DirectoryHelper - extends - AbstractFileSystemHelper - implements +public class DirectoryHelper extends AbstractFileSystemHelper implements FileSystemHelper { protected File directory; + /** * */ public DirectoryHelper(File directory) { super(); - if(!directory.exists()) + if (!directory.exists()) { directory.mkdirs(); } - - if(!directory.isDirectory()) - { - throw new IllegalArgumentException("DirectoryHelper(File) requires directory not a file."); - } + + if (!directory.isDirectory()) { throw new IllegalArgumentException( + "DirectoryHelper(File) requires directory not a file."); } this.directory = directory; - - } /** *

      * copyFrom *

      - * + * * @see org.apache.jetspeed.util.FileSystemHelper#copyFrom(java.io.File) * @param directory * @throws IOException */ - public void copyFrom( File srcDirectory ) throws IOException + public void copyFrom(File srcDirectory) throws IOException { - copyFrom(srcDirectory, new FileFilter() { + copyFrom(srcDirectory, new FileFilter() + { + public boolean accept(File pathname) { - return true; + return true; } - }); + }); } - + /** *

      * copyFrom *

      - * - * @see org.apache.jetspeed.util.FileSystemHelper#copyFrom(java.io.File, java.io.FileFilter) + * + * @see org.apache.jetspeed.util.FileSystemHelper#copyFrom(java.io.File, + * java.io.FileFilter) * @param directory * @param fileFilter * @throws IOException */ - public void copyFrom( File srcDirectory, FileFilter fileFilter ) throws IOException + public void copyFrom(File srcDirectory, FileFilter fileFilter) + throws IOException { - if(!srcDirectory.isDirectory()) - { - throw new IllegalArgumentException("DirectoryHelper.copyFrom(File) requires directory not a file."); - } - copyFiles(srcDirectory, directory, fileFilter); + if (!srcDirectory.isDirectory()) { throw new IllegalArgumentException( + "DirectoryHelper.copyFrom(File) requires directory not a file."); } + copyFiles(srcDirectory, directory, fileFilter); } + /** * *

      * copyFiles *

      - * - * @param srcDir Source directory to copy from. - * @param dstDir Destination directory to copy to. + * + * @param srcDir + * Source directory to copy from. + * @param dstDir + * Destination directory to copy to. * @throws IOException * @throws FileNotFoundException - + * */ - protected void copyFiles(File srcDir, File dstDir, FileFilter fileFilter) throws IOException + protected void copyFiles(File srcDir, File dstDir, FileFilter fileFilter) + throws IOException { FileChannel srcChannel = null; FileChannel dstChannel = null; try { - File[] children = srcDir.listFiles(fileFilter); - for(int i=0; i * remove *

      - * + * * @see org.apache.jetspeed.util.FileSystemHelper#remove() * */ @@ -174,46 +175,43 @@ { return doRemove(directory); } - + /** * *

      * doRemove *

      - * + * * @param file - * @return true if the removal war successful, otherwise returns - * false. + * @return true if the removal war successful, otherwise + * returns false. */ protected boolean doRemove(File file) { if (file.isDirectory()) - { - String[] children = file.list(); - for (int i = 0; i < children.length; i++) - { - boolean success = doRemove(new File(file, children[i])); - if (!success) - { - return false; - } - } - } + { + String[] children = file.list(); + for (int i = 0; i < children.length; i++) + { + boolean success = doRemove(new File(file, children[i])); + if (!success) { return false; } + } + } - // The directory is now empty so delete it OR it is a plain file - return file.delete(); + // The directory is now empty so delete it OR it is a plain file + return file.delete(); } /** *

      * getRootDirectory *

      - * + * * @see org.apache.jetspeed.util.FileSystemHelper#getRootDirectory() * @return */ public File getRootDirectory() - { + { return directory; } @@ -221,7 +219,7 @@ *

      * close *

      - * + * * @see org.apache.jetspeed.util.FileSystemHelper#close() * */ @@ -230,17 +228,18 @@ // TODO Auto-generated method stub } + /** *

      * getSourcePath *

      - * + * * @see org.apache.jetspeed.util.FileSystemHelper#getSourcePath() * @return */ public String getSourcePath() - { + { return getRootDirectory().getAbsolutePath(); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/FIFOQueue.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/FIFOQueue.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/FIFOQueue.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,47 +18,42 @@ package org.apache.jetspeed.util; /** - * Simple FIFO implementation of Queue interface extending Vector - * as storage backend. - * + * Simple FIFO implementation of Queue interface extending Vector as storage + * backend. + * * @author Rapha\u00ebl Luta * @version $Id: FIFOQueue.java 516448 2007-03-09 16:25:47Z ate $ */ public class FIFOQueue extends java.util.Vector implements Queue { - /** - * Adds a new object into the queue - */ - public synchronized void push(Object obj) - { - this.add(obj); - } - /** - * Gets the first object in the queue and remove it from the queue - */ - public synchronized Object pop() - { + /** + * Adds a new object into the queue + */ + public synchronized void push(Object obj) + { + this.add(obj); + } - if (this.size() == 0) - { - return null; - } + /** + * Gets the first object in the queue and remove it from the queue + */ + public synchronized Object pop() + { - return this.remove(0); - } + if (this.size() == 0) { return null; } - /** - * Gets the first object in the queue without removing it from the queue - */ - public synchronized Object peek() - { + return this.remove(0); + } - if (this.size() == 0) - { - return null; - } + /** + * Gets the first object in the queue without removing it from the queue + */ + public synchronized Object peek() + { - return this.get(0); - } + if (this.size() == 0) { return null; } + + return this.get(0); + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/HashCodeBuilder.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/HashCodeBuilder.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/HashCodeBuilder.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,19 +18,21 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; + /** * HashCode generation routines. *

      - * This class enables a good hashcode to be built for any class. It follows - * the rules laid out in the book Effective Java, by Joshua Bloch. Writing a - * good hashCode is actually quite difficult. This class aims to simplify the + * This class enables a good hashcode to be built for any class. It follows the + * rules laid out in the book Effective Java, by Joshua Bloch. Writing a good + * hashCode is actually quite difficult. This class aims to simplify the * process. *

      - * All relevant fields from the object should be included in the hashCode. Derived - * fields may be excluded. In general, any field used in the equals method must be - * used in the hashCode method. + * All relevant fields from the object should be included in the hashCode. + * Derived fields may be excluded. In general, any field used in the equals + * method must be used in the hashCode method. *

      * To use this class write code as follows: + * *

        * public class Person {
        *   String name;
      @@ -49,18 +51,21 @@
        *   }
        * }
        * 
      + * *

      - * Alternatively, there is a method that uses reflection to determine - * the fields to test. Because these fields are usually private, the method, - * reflectionHashCode, uses Field.setAccessible to - * change the visibility of the fields. This will fail under a security manager, - * unless the appropriate permissions are set. It is also slower than testing - * explicitly. + * Alternatively, there is a method that uses reflection to determine the fields + * to test. Because these fields are usually private, the method, + * reflectionHashCode, uses Field.setAccessible + * to change the visibility of the fields. This will fail under a security + * manager, unless the appropriate permissions are set. It is also slower than + * testing explicitly. *

      * A typical invocation for this method would look like: + * *

      - * public boolean hashCode(Object o) {
      - *   return HashCodeBuilder.reflectionHashCode(this);
      + * public boolean hashCode(Object o)
      + * {
      + *     return HashCodeBuilder.reflectionHashCode(this);
        * }
        * 
      * @@ -74,15 +79,15 @@ * Constant to use in building the hashCode */ private final int iConstant; + /** * Running total of the hashCode */ private int iTotal = 0; /** - * Constructor for HashCodeBuilder. - * This constructor uses two hard coded choices for the constants needed - * to build a hashCode. + * Constructor for HashCodeBuilder. This constructor uses two hard coded + * choices for the constants needed to build a hashCode. */ public HashCodeBuilder() { @@ -92,56 +97,52 @@ } /** - * Constructor for HashCodeBuilder. - * Two randomly chosen, non-zero, odd numbers must be passed in. Ideally - * these should be different for each class, however this is not vital. - * Prime numbers are preferred, especially for the multiplier. + * Constructor for HashCodeBuilder. Two randomly chosen, non-zero, odd + * numbers must be passed in. Ideally these should be different for each + * class, however this is not vital. Prime numbers are preferred, especially + * for the multiplier. * - * @param initialNonZeroOddNumber a non-zero, odd number used as the initial value - * @param multiplierNonZeroOddNumber a non-zero, odd number used as the multiplier - * @throws IllegalArgumentException if the number is zero or even + * @param initialNonZeroOddNumber + * a non-zero, odd number used as the initial value + * @param multiplierNonZeroOddNumber + * a non-zero, odd number used as the multiplier + * @throws IllegalArgumentException + * if the number is zero or even */ - public HashCodeBuilder(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber) + public HashCodeBuilder(int initialNonZeroOddNumber, + int multiplierNonZeroOddNumber) { super(); - if (initialNonZeroOddNumber == 0) - { - throw new IllegalArgumentException("HashCodeBuilder requires a non zero initial value"); - } - if (initialNonZeroOddNumber % 2 == 0) - { - throw new IllegalArgumentException("HashCodeBuilder requires an odd initial value"); - } - if (multiplierNonZeroOddNumber == 0) - { - throw new IllegalArgumentException("HashCodeBuilder requires a non zero multiplier"); - } - if (multiplierNonZeroOddNumber % 2 == 0) - { - throw new IllegalArgumentException("HashCodeBuilder requires an odd multiplier"); - } + if (initialNonZeroOddNumber == 0) { throw new IllegalArgumentException( + "HashCodeBuilder requires a non zero initial value"); } + if (initialNonZeroOddNumber % 2 == 0) { throw new IllegalArgumentException( + "HashCodeBuilder requires an odd initial value"); } + if (multiplierNonZeroOddNumber == 0) { throw new IllegalArgumentException( + "HashCodeBuilder requires a non zero multiplier"); } + if (multiplierNonZeroOddNumber % 2 == 0) { throw new IllegalArgumentException( + "HashCodeBuilder requires an odd multiplier"); } iConstant = multiplierNonZeroOddNumber; iTotal = initialNonZeroOddNumber; } - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- /** - * This method uses reflection to build a valid hash code. + * This method uses reflection to build a valid hash code. *

      * It uses Field.setAccessible to gain access to private fields. This means - * that it will throw a security exception if run under a security manger, if - * the permissions are not set up. - * It is also not as efficient as testing explicitly. - * Transient members will be not be used, as they are likely derived - * fields, and not part of the value of the object. - * Static fields will not be tested. - * This constructor uses two hard coded choices for the constants needed - * to build a hash code. + * that it will throw a security exception if run under a security manger, + * if the permissions are not set up. It is also not as efficient as testing + * explicitly. Transient members will be not be used, as they are likely + * derived fields, and not part of the value of the object. Static fields + * will not be tested. This constructor uses two hard coded choices for the + * constants needed to build a hash code. * - * @param object the object to create a hash code for + * @param object + * the object to create a hash code for * @return int hash code - * @throws IllegalArgumentException if the object is null + * @throws IllegalArgumentException + * if the object is null */ public static int reflectionHashCode(Object object) { @@ -149,23 +150,24 @@ } /** - * This method uses reflection to build a valid hash code. + * This method uses reflection to build a valid hash code. *

      * It uses Field.setAccessible to gain access to private fields. This means - * that it will throw a security exception if run under a security manger, if - * the permissions are not set up. - * It is also not as efficient as testing explicitly. - * If the TestTransients parameter is set to true, transient members will be - * tested, otherwise they are ignored, as they are likely derived fields, and - * not part of the value of the object. - * Static fields will not be tested. - * This constructor uses two hard coded choices for the constants needed - * to build a hash code. + * that it will throw a security exception if run under a security manger, + * if the permissions are not set up. It is also not as efficient as testing + * explicitly. If the TestTransients parameter is set to true, transient + * members will be tested, otherwise they are ignored, as they are likely + * derived fields, and not part of the value of the object. Static fields + * will not be tested. This constructor uses two hard coded choices for the + * constants needed to build a hash code. * - * @param object the object to create a hash code for - * @param testTransients whether to include transient fields + * @param object + * the object to create a hash code for + * @param testTransients + * whether to include transient fields * @return int hash code - * @throws IllegalArgumentException if the object is null + * @throws IllegalArgumentException + * if the object is null */ public static int reflectionHashCode(Object object, boolean testTransients) { @@ -173,43 +175,48 @@ } /** - * This method uses reflection to build a valid hash code. + * This method uses reflection to build a valid hash code. *

      * It uses Field.setAccessible to gain access to private fields. This means - * that it will throw a security exception if run under a security manger, if - * the permissions are not set up. - * It is also not as efficient as testing explicitly. - * Transient members will be not be used, as they are likely derived - * fields, and not part of the value of the object. - * Static fields will not be tested. + * that it will throw a security exception if run under a security manger, + * if the permissions are not set up. It is also not as efficient as testing + * explicitly. Transient members will be not be used, as they are likely + * derived fields, and not part of the value of the object. Static fields + * will not be tested. *

      * Two randomly chosen, non-zero, odd numbers must be passed in. Ideally * these should be different for each class, however this is not vital. * Prime numbers are preferred, especially for the multiplier. * - * @param initialNonZeroOddNumber a non-zero, odd number used as the initial value - * @param multiplierNonZeroOddNumber a non-zero, odd number used as the multiplier - * @param object the object to create a hash code for + * @param initialNonZeroOddNumber + * a non-zero, odd number used as the initial value + * @param multiplierNonZeroOddNumber + * a non-zero, odd number used as the multiplier + * @param object + * the object to create a hash code for * @return int hash code - * @throws IllegalArgumentException if the object is null - * @throws IllegalArgumentException if the number is zero or even + * @throws IllegalArgumentException + * if the object is null + * @throws IllegalArgumentException + * if the number is zero or even */ - public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object) + public static int reflectionHashCode(int initialNonZeroOddNumber, + int multiplierNonZeroOddNumber, Object object) { - return reflectionHashCode(initialNonZeroOddNumber, multiplierNonZeroOddNumber, object, false); + return reflectionHashCode(initialNonZeroOddNumber, + multiplierNonZeroOddNumber, object, false); } /** - * This method uses reflection to build a valid hash code. + * This method uses reflection to build a valid hash code. *

      * It uses Field.setAccessible to gain access to private fields. This means - * that it will throw a security exception if run under a security manger, if - * the permissions are not set up. - * It is also not as efficient as testing explicitly. - * If the TestTransients parameter is set to true, transient members will be - * tested, otherwise they are ignored, as they are likely derived fields, and - * not part of the value of the object. - * Static fields will not be tested. + * that it will throw a security exception if run under a security manger, + * if the permissions are not set up. It is also not as efficient as testing + * explicitly. If the TestTransients parameter is set to true, transient + * members will be tested, otherwise they are ignored, as they are likely + * derived fields, and not part of the value of the object. Static fields + * will not be tested. *

      * Two randomly chosen, non-zero, odd numbers must be passed in. Ideally * these should be different for each class, however this is not vital. @@ -217,24 +224,25 @@ * * @param initialNonZeroOddNumber * @param multiplierNonZeroOddNumber - * @param object the object to create a hash code for - * @param testTransients whether to include transient fields + * @param object + * the object to create a hash code for + * @param testTransients + * whether to include transient fields * @return int hash code - * @throws IllegalArgumentException if the object is null - * @throws IllegalArgumentException if the number is zero or even + * @throws IllegalArgumentException + * if the object is null + * @throws IllegalArgumentException + * if the number is zero or even */ - public static int reflectionHashCode( - int initialNonZeroOddNumber, - int multiplierNonZeroOddNumber, - Object object, - boolean testTransients) + public static int reflectionHashCode(int initialNonZeroOddNumber, + int multiplierNonZeroOddNumber, Object object, + boolean testTransients) { - if (object == null) - { - throw new IllegalArgumentException("The object to build a hash code for must not be null"); - } - HashCodeBuilder hashCodeBuilder = new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber); + if (object == null) { throw new IllegalArgumentException( + "The object to build a hash code for must not be null"); } + HashCodeBuilder hashCodeBuilder = new HashCodeBuilder( + initialNonZeroOddNumber, multiplierNonZeroOddNumber); Field[] fields = object.getClass().getDeclaredFields(); Field.setAccessible(fields, true); for (int i = 0; i < fields.length; ++i) @@ -250,9 +258,12 @@ } catch (IllegalAccessException e) { - //this can't happen. Would get a Security exception instead - //throw a runtime exception in case the impossible happens. - throw new InternalError("Unexpected IllegalAccessException"); + // this can't happen. Would get a Security exception + // instead + // throw a runtime exception in case the impossible + // happens. + throw new InternalError( + "Unexpected IllegalAccessException"); } } } @@ -260,12 +271,13 @@ return hashCodeBuilder.toHashCode(); } - //------------------------------------------------------------------------- + // ------------------------------------------------------------------------- /** * Append a hashCode for an Object. - * - * @param object the object to add to the hashCode + * + * @param object + * the object to add to the hashCode * @return this */ public HashCodeBuilder append(Object object) @@ -279,13 +291,13 @@ { if (object.getClass().isArray() == false) { - //the simple case, not an array, just the element + // the simple case, not an array, just the element iTotal = iTotal * iConstant + object.hashCode(); } else { - //'Switch' on type of array, to dispatch to the correct handler + // 'Switch' on type of array, to dispatch to the correct handler // This handles multi dimensional arrays if (object instanceof long[]) { @@ -331,8 +343,9 @@ /** * Append a hashCode for a long. - * - * @param value the long to add to the hashCode + * + * @param value + * the long to add to the hashCode * @return this */ public HashCodeBuilder append(long value) @@ -343,8 +356,9 @@ /** * Append a hashCode for an int. - * - * @param value the int to add to the hashCode + * + * @param value + * the int to add to the hashCode * @return this */ public HashCodeBuilder append(int value) @@ -355,8 +369,9 @@ /** * Append a hashCode for a short. - * - * @param value the short to add to the hashCode + * + * @param value + * the short to add to the hashCode * @return this */ public HashCodeBuilder append(short value) @@ -367,8 +382,9 @@ /** * Append a hashCode for a char. - * - * @param value the char to add to the hashCode + * + * @param value + * the char to add to the hashCode * @return this */ public HashCodeBuilder append(char value) @@ -379,8 +395,9 @@ /** * Append a hashCode for a byte. - * - * @param value the byte to add to the hashCode + * + * @param value + * the byte to add to the hashCode * @return this */ public HashCodeBuilder append(byte value) @@ -391,8 +408,9 @@ /** * Append a hashCode for a double. - * - * @param value the double to add to the hashCode + * + * @param value + * the double to add to the hashCode * @return this */ public HashCodeBuilder append(double value) @@ -402,8 +420,9 @@ /** * Append a hashCode for a float. - * - * @param value the float to add to the hashCode + * + * @param value + * the float to add to the hashCode * @return this */ public HashCodeBuilder append(float value) @@ -414,8 +433,9 @@ /** * Append a hashCode for a long. - * - * @param value the long to add to the hashCode + * + * @param value + * the long to add to the hashCode * @return this */ public HashCodeBuilder append(boolean value) @@ -426,8 +446,9 @@ /** * Append a hashCode for an Object array. - * - * @param array the array to add to the hashCode + * + * @param array + * the array to add to the hashCode * @return this */ public HashCodeBuilder append(Object[] array) @@ -448,8 +469,9 @@ /** * Append a hashCode for a long array. - * - * @param array the array to add to the hashCode + * + * @param array + * the array to add to the hashCode * @return this */ public HashCodeBuilder append(long[] array) @@ -470,8 +492,9 @@ /** * Append a hashCode for an int array. - * - * @param array the array to add to the hashCode + * + * @param array + * the array to add to the hashCode * @return this */ public HashCodeBuilder append(int[] array) @@ -492,8 +515,9 @@ /** * Append a hashCode for a short array. - * - * @param array the array to add to the hashCode + * + * @param array + * the array to add to the hashCode * @return this */ public HashCodeBuilder append(short[] array) @@ -514,8 +538,9 @@ /** * Append a hashCode for a char array. - * - * @param array the array to add to the hashCode + * + * @param array + * the array to add to the hashCode * @return this */ public HashCodeBuilder append(char[] array) @@ -536,8 +561,9 @@ /** * Append a hashCode for a byte array. - * - * @param array the array to add to the hashCode + * + * @param array + * the array to add to the hashCode * @return this */ public HashCodeBuilder append(byte[] array) @@ -558,8 +584,9 @@ /** * Append a hashCode for a double array. - * - * @param array the array to add to the hashCode + * + * @param array + * the array to add to the hashCode * @return this */ public HashCodeBuilder append(double[] array) @@ -580,8 +607,9 @@ /** * Append a hashCode for a float array. - * - * @param array the array to add to the hashCode + * + * @param array + * the array to add to the hashCode * @return this */ public HashCodeBuilder append(float[] array) @@ -602,8 +630,9 @@ /** * Append a hashCode for a boolean array. - * - * @param array the array to add to the hashCode + * + * @param array + * the array to add to the hashCode * @return this */ public HashCodeBuilder append(boolean[] array) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JarHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JarHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JarHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,18 +33,20 @@ * Creates a a temp directory to which a JarFile is expanded and can be * manipulated. All operations are performed by an internal instance of * {@link DirectoryHelper}. - * + * */ -public class JarHelper - extends - AbstractFileSystemHelper - implements +public class JarHelper extends AbstractFileSystemHelper implements FileSystemHelper { + protected JarFile jarFile; + protected DirectoryHelper dirHelper; + protected File file; + private boolean deleteOnClose; + protected File jarRoot; /** @@ -52,7 +54,7 @@ * @param jarFile * @throws IOException */ - public JarHelper( File file, boolean deleteOnClose ) throws IOException + public JarHelper(File file, boolean deleteOnClose) throws IOException { this.jarFile = new JarFile(file); this.deleteOnClose = deleteOnClose; @@ -100,8 +102,8 @@ * @throws IOException * @throws FileNotFoundException */ - protected void copyEntryToFile( JarFile jarFile, File jarRoot, JarEntry jarEntry ) throws IOException, - FileNotFoundException + protected void copyEntryToFile(JarFile jarFile, File jarRoot, + JarEntry jarEntry) throws IOException, FileNotFoundException { String name = jarEntry.getName(); File file = new File(jarRoot, name); @@ -146,15 +148,17 @@ *

      * copyFrom *

      - * + * * @param directory * @param fileFilter * @throws IOException */ - public void copyFrom( File directory, FileFilter fileFilter ) throws IOException + public void copyFrom(File directory, FileFilter fileFilter) + throws IOException { dirHelper.copyFrom(directory, fileFilter); } + /** *

      * copyFrom @@ -164,7 +168,7 @@ * @param directory * @throws IOException */ - public void copyFrom( File directory ) throws IOException + public void copyFrom(File directory) throws IOException { dirHelper.copyFrom(directory); } @@ -203,7 +207,7 @@ * @throws IOException * * @see org.apache.jetspeed.util.FileSystemHelper#close() - * + * */ public void close() throws IOException { @@ -213,7 +217,7 @@ // remove all temporary files dirHelper.remove(); } - + dirHelper.close(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JetspeedLocale.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JetspeedLocale.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JetspeedLocale.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,15 +22,16 @@ /** * Class to set and get Locale settings for Jetspeed. - * + * * @author Roger Ruttimann * @author Shinsuke Sugaya * @version $Id: JetspeedLocale.java 516448 2007-03-09 16:25:47Z ate $ */ public class JetspeedLocale { + private static final String DELIM = ","; - + /** * According to PLT.21.8.1, the default locale should be English. */ @@ -39,7 +40,6 @@ return Locale.ENGLISH; } - /** * Converts Locale to String. * @@ -48,10 +48,7 @@ */ public static String convertLocaleToString(Locale locale) { - if (locale == null) - { - return null; - } + if (locale == null) { return null; } String country = locale.getCountry(); String language = locale.getLanguage(); String variant = locale.getVariant(); @@ -84,10 +81,7 @@ */ public static Locale convertStringToLocale(String localeString) { - if (localeString == null) - { - return null; - } + if (localeString == null) { return null; } StringTokenizer tokenizer = new StringTokenizer(localeString, DELIM); String language = tokenizer.nextToken().trim(); @@ -122,5 +116,4 @@ } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JetspeedLongObjectID.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JetspeedLongObjectID.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JetspeedLongObjectID.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,14 +20,15 @@ /** * JetspeedLongObjectID - * + * * @author Ate Douma * @version $Id$ */ public class JetspeedLongObjectID implements PortalObjectID, Serializable { + private Long oid; - + public JetspeedLongObjectID(long oid) { this.oid = new Long(oid); @@ -36,7 +37,7 @@ public JetspeedLongObjectID(Long oid) { this.oid = oid; - if ( oid == null ) + if (oid == null) { // really cannot have a null here throw new NullPointerException(); @@ -47,26 +48,24 @@ { return oid.longValue(); } - + public Long getLong() { return oid; } - + public boolean equals(Object object) { if (object instanceof PortalObjectID) { - return ((PortalObjectID)object).getOID() == oid.longValue(); + return ((PortalObjectID) object).getOID() == oid.longValue(); } else if (object instanceof Long) { - return ((Long)object).longValue() == oid.longValue(); + return ((Long) object).longValue() == oid.longValue(); } - else if (object instanceof Integer) - { - return ((Integer)object).longValue() == oid.longValue(); - } + else if (object instanceof Integer) { return ((Integer) object) + .longValue() == oid.longValue(); } return false; } @@ -74,7 +73,7 @@ { return oid.hashCode(); } - + public String toString() { return oid.toString(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JetspeedObjectID.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JetspeedObjectID.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/JetspeedObjectID.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,22 +23,22 @@ /** * - * JetspeedObjectID - ** Wraps around the internal Object IDs. By holding both - ** the string and the integer version of an Object ID this class - ** helps speed up the internal processing. + * JetspeedObjectID * Wraps around the internal Object IDs. By holding both * + * the string and the integer version of an Object ID this class * helps speed + * up the internal processing. * * @version $Id: JetspeedObjectID.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class JetspeedObjectID implements ObjectID, Serializable { + private String stringOID = null; public JetspeedObjectID(String stringOID) { this.stringOID = stringOID; - if ( stringOID == null ) + if (stringOID == null) { // really cannot have a null here throw new NullPointerException(); @@ -49,12 +49,10 @@ { if (object instanceof JetspeedObjectID) { - return ((JetspeedObjectID)object).stringOID.equals(stringOID); + return ((JetspeedObjectID) object).stringOID.equals(stringOID); } - else if (object instanceof String) - { - return ((String)object).equals(stringOID); - } + else if (object instanceof String) { return ((String) object) + .equals(stringOID); } return false; } @@ -78,8 +76,10 @@ * @param instanceName * @return */ - public static JetspeedObjectID createPortletEntityId(PortletDefinition portletDefinition, String instanceName) + public static JetspeedObjectID createPortletEntityId( + PortletDefinition portletDefinition, String instanceName) { - return createFromString(portletDefinition.getName() + ":" + portletDefinition.getId().toString() + ":" + instanceName); + return createFromString(portletDefinition.getName() + ":" + + portletDefinition.getId().toString() + ":" + instanceName); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/Path.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/Path.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/Path.java 2008-05-16 01:54:54 UTC (rev 940) @@ -62,16 +62,18 @@ */ public class Path implements Serializable, Cloneable { + /** The serial version uid. */ private static final long serialVersionUID = 6890966283704092945L; public static final String PATH_SEPERATOR = "/"; - + private static final String[] EMPTY_SEGMENTS = new String[0]; - + private static HashMap childrenMap = new HashMap(); - + private final String path; + private final String[] segments; private final String fileName; @@ -81,7 +83,7 @@ private final String fileExtension; private final String queryString; - + private final int hashCode; public Path() @@ -94,12 +96,12 @@ hashCode = 0; path = ""; } - + private Path(Path parent, String childSegment, boolean pathOnly) { this(parent, splitPath(childSegment), pathOnly); } - + private Path(Path parent, String[] children, boolean pathOnly) { int code = 0; @@ -121,7 +123,7 @@ fileExtension = null; queryString = null; } - + int size = parent.segments.length; if (pathOnly && parent.fileName != null) { @@ -129,8 +131,8 @@ } int index = 0; - - segments = new String[size+children.length]; + + segments = new String[size + children.length]; for (index = 0; index < size; index++) { segments[index] = parent.segments[index]; @@ -149,31 +151,31 @@ hashCode = code; path = buildPath(); } - + private Path(Path parent) { this.fileName = parent.fileName; this.baseName = parent.baseName; this.fileExtension = parent.fileExtension; this.queryString = parent.queryString; - segments = new String[parent.segments.length-1]; + segments = new String[parent.segments.length - 1]; int code = 0; - for (int i = 0; i < parent.segments.length-2; i++) + for (int i = 0; i < parent.segments.length - 2; i++) { segments[i] = parent.segments[i]; code += segments.hashCode(); } if (fileName != null) { - segments[segments.length-1] = fileName; + segments[segments.length - 1] = fileName; } else if (parent.segments.length > 1) { - segments[segments.length-1] = parent.segments[parent.segments.length-2]; + segments[segments.length - 1] = parent.segments[parent.segments.length - 2]; } - if ( segments.length > 0) + if (segments.length > 0) { - code += segments[segments.length-1].hashCode(); + code += segments[segments.length - 1].hashCode(); } if (queryString != null) { @@ -182,20 +184,20 @@ hashCode = code; path = buildPath(); } - + private Path(String[] segments, int offset, int count) { this.segments = new String[count]; int code = 0; for (int i = 0; i < count; i++) { - this.segments[i] = segments[offset+i]; - code+=segments[offset+i].hashCode(); + this.segments[i] = segments[offset + i]; + code += segments[offset + i].hashCode(); } hashCode = code; if (count > 0) { - fileName = this.segments[count-1]; + fileName = this.segments[count - 1]; int extIndex = fileName.lastIndexOf('.'); if (extIndex > -1) { @@ -217,10 +219,10 @@ queryString = null; path = buildPath(); } - + public Path(String path) { - + String tmp = path.replace('\\', '/'); if (!tmp.startsWith("/")) @@ -229,10 +231,11 @@ } this.path = tmp; - + if (path.equals("/")) { - segments = new String[]{""}; + segments = new String[] + {""}; fileName = null; baseName = null; fileExtension = null; @@ -244,16 +247,16 @@ int queryStart = path.indexOf('?'); int len = queryStart > -1 ? queryStart : path.length(); segments = split(path, 0, len, '/'); - int code = 0; + int code = 0; for (int i = 0; i < segments.length; i++) { code += segments[i].hashCode(); } String tmpFileName = null; - - if (queryStart > 1 && path.length() > queryStart+1) + + if (queryStart > 1 && path.length() > queryStart + 1) { - queryString = path.substring(queryStart+1); + queryString = path.substring(queryStart + 1); code += queryString.hashCode(); } else @@ -264,7 +267,7 @@ int extIndex = -1; if (segments.length > 0) { - tmpFileName = segments[segments.length-1]; + tmpFileName = segments[segments.length - 1]; extIndex = tmpFileName.lastIndexOf('.'); } if (extIndex > -1) @@ -294,7 +297,8 @@ if (path.equals("/")) { - children = new String[]{""}; + children = new String[] + {""}; } else { @@ -304,7 +308,7 @@ } return children; } - + /** * Returns the segement of the path at the specified index i. * @@ -341,12 +345,13 @@ public Path getSubPath(int beginAtSegment) { - return new Path(segments, beginAtSegment, segments.length-beginAtSegment); + return new Path(segments, beginAtSegment, segments.length + - beginAtSegment); } public Path getSubPath(int beginAtSegment, int endSegment) { - return new Path(segments, beginAtSegment, endSegment-beginAtSegment); + return new Path(segments, beginAtSegment, endSegment - beginAtSegment); } public String getBaseName() @@ -373,7 +378,7 @@ { return segments.length; } - + public String toString() { return path; @@ -384,23 +389,23 @@ int len = 0; for (int i = 0; i < segments.length; i++) { - len+=segments[i].length()+1; + len += segments[i].length() + 1; } - if (queryString!=null) + if (queryString != null) { - len+=queryString.length()+1; + len += queryString.length() + 1; } char[] buffer = new char[len]; int index = 0; - for (int i = 0; i < segments.length; i++ ) + for (int i = 0; i < segments.length; i++) { buffer[index++] = '/'; len = segments[i].length(); segments[i].getChars(0, len, buffer, index); - index+= len; + index += len; } if (queryString != null) - { + { buffer[index++] = '?'; len = queryString.length(); queryString.getChars(0, len, buffer, index); @@ -412,12 +417,11 @@ { if (obj instanceof Path) { - Path other = (Path)obj; - if ( (other.queryString != null && other.queryString.equals(queryString)) || - (other.queryString == null && queryString == null) ) - { - return Arrays.equals(other.segments,segments); - } + Path other = (Path) obj; + if ((other.queryString != null && other.queryString + .equals(queryString)) + || (other.queryString == null && queryString == null)) { return Arrays + .equals(other.segments, segments); } } return false; } @@ -436,10 +440,7 @@ */ public Path removeLastPathSegment() { - if ((fileName != null && segments.length == 1) || segments.length == 0) - { - return this; - } + if ((fileName != null && segments.length == 1) || segments.length == 0) { return this; } return new Path(this); } @@ -448,7 +449,7 @@ synchronized (childrenMap) { Path child = null; - HashMap children = (HashMap)childrenMap.get(path); + HashMap children = (HashMap) childrenMap.get(path); if (children == null) { children = new HashMap(); @@ -456,9 +457,9 @@ } else { - child = (Path)children.get(childPath); + child = (Path) children.get(childPath); } - if ( child == null ) + if (child == null) { if (segments.length == 0) { @@ -478,8 +479,9 @@ { return getChild(childPath.path); } - - private static String[] split(String str, int start, int length, char separator) + + private static String[] split(String str, int start, int length, + char separator) { String[] result; char[] buffer = str.toCharArray(); @@ -487,7 +489,7 @@ boolean token = false; for (int i = start; i < length; i++) { - if (buffer[i]==separator) + if (buffer[i] == separator) { token = false; } @@ -506,12 +508,12 @@ tokens = 0; for (int i = start; i < length; i++) { - if (buffer[i]==separator) + if (buffer[i] == separator) { if (token) { - result[tokens++] = new String(buffer,begin,end); - token = false; + result[tokens++] = new String(buffer, begin, end); + token = false; } } else if (!token) @@ -527,7 +529,7 @@ } if (token) { - result[tokens] = new String(buffer,begin, end); + result[tokens] = new String(buffer, begin, end); } } return result; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/PortalObjectID.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/PortalObjectID.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/PortalObjectID.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,11 +20,12 @@ /** * PortalObjectID - * + * * @author David Sean Taylor * @version $Id: PortalObjectID.java 516448 2007-03-09 16:25:47Z ate $ */ public interface PortalObjectID extends ObjectID { - long getOID(); + + long getOID(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/test/org/apache/jetspeed/util/TestPathUtil.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/test/org/apache/jetspeed/util/TestPathUtil.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/test/org/apache/jetspeed/util/TestPathUtil.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,63 +20,77 @@ public class TestPathUtil extends TestCase { + public void testPath() { Path path = new Path("/root/sub1/sub2/file.html?foo=bar&name=bob"); - + Path path2 = new Path("/root/sub1/sub2/file.html?foo=bar&name=bob"); - + assertEquals(path, path2); - + assertEquals(".html", path.getFileExtension()); assertEquals("foo=bar&name=bob", path.getQueryString()); assertEquals("file.html", path.getFileName()); assertEquals("file", path.getBaseName()); - + assertEquals(4, path.length()); - + assertEquals("root", path.getSegment(0)); assertEquals("sub1", path.getSegment(1)); assertEquals("sub2", path.getSegment(2)); - assertEquals("file.html", path.getSegment(3)); -// assertEquals("/root/sub1/sub2/file.html", path.pathOnly()); - + assertEquals("file.html", path.getSegment(3)); + // assertEquals("/root/sub1/sub2/file.html", path.pathOnly()); + assertEquals("/sub1/sub2/file.html", path.getSubPath(1).toString()); - + path = new Path("file.html"); assertEquals(".html", path.getFileExtension()); assertEquals("file.html", path.getFileName()); assertEquals("file", path.getBaseName()); - + assertNull(path.getQueryString()); - + assertEquals(1, path.length()); - assertEquals("file.html", path.getSegment(0)); - + assertEquals("file.html", path.getSegment(0)); + path = new Path("file"); - + assertNull(path.getBaseName()); - + Path pathNoFile = new Path("/root/sub1/sub2?abc"); assertEquals("root", pathNoFile.getSegment(0)); assertEquals("sub1", pathNoFile.getSegment(1)); assertEquals("sub2", pathNoFile.getSegment(2)); - + assertEquals("/sub1/sub2", pathNoFile.getSubPath(1).toString()); - - assertEquals("/root/sub1/sub2/abc", pathNoFile.getChild("abc").toString()); - assertEquals("/root/sub1/sub2/abc/def", pathNoFile.getChild(new Path("abc/def")).toString()); - assertEquals("/root/sub1?abc", pathNoFile.removeLastPathSegment().toString()); - assertEquals("/root?abc", pathNoFile.removeLastPathSegment().removeLastPathSegment().toString()); - assertEquals("?abc", pathNoFile.removeLastPathSegment().removeLastPathSegment().removeLastPathSegment().toString()); - assertEquals("?abc", pathNoFile.removeLastPathSegment().removeLastPathSegment().removeLastPathSegment().removeLastPathSegment().toString()); + assertEquals("/root/sub1/sub2/abc", pathNoFile.getChild("abc") + .toString()); + assertEquals("/root/sub1/sub2/abc/def", pathNoFile.getChild( + new Path("abc/def")).toString()); + assertEquals("/root/sub1?abc", pathNoFile.removeLastPathSegment() + .toString()); + assertEquals("/root?abc", pathNoFile.removeLastPathSegment() + .removeLastPathSegment().toString()); + assertEquals("?abc", pathNoFile.removeLastPathSegment() + .removeLastPathSegment().removeLastPathSegment().toString()); + assertEquals("?abc", pathNoFile.removeLastPathSegment() + .removeLastPathSegment().removeLastPathSegment() + .removeLastPathSegment().toString()); + Path pathFile = new Path("/root/sub1/sub2/test.html?123"); assertEquals("/root/sub1/sub2/abc", pathFile.getChild("abc").toString()); - assertEquals("/root/sub1/sub2/abc/def/test123.html", pathFile.getChild(new Path("abc/def/test123.html")).toString()); - assertEquals("/root/sub1/test.html?123", pathFile.removeLastPathSegment().toString()); - assertEquals("/root/test.html?123", pathFile.removeLastPathSegment().removeLastPathSegment().toString()); - assertEquals("/test.html?123", pathFile.removeLastPathSegment().removeLastPathSegment().removeLastPathSegment().toString()); - assertEquals("/test.html?123", pathFile.removeLastPathSegment().removeLastPathSegment().removeLastPathSegment().removeLastPathSegment().toString()); + assertEquals("/root/sub1/sub2/abc/def/test123.html", pathFile.getChild( + new Path("abc/def/test123.html")).toString()); + assertEquals("/root/sub1/test.html?123", pathFile + .removeLastPathSegment().toString()); + assertEquals("/root/test.html?123", pathFile.removeLastPathSegment() + .removeLastPathSegment().toString()); + assertEquals("/test.html?123", pathFile.removeLastPathSegment() + .removeLastPathSegment().removeLastPathSegment().toString()); + assertEquals("/test.html?123", pathFile.removeLastPathSegment() + .removeLastPathSegment().removeLastPathSegment() + .removeLastPathSegment().toString()); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/CapabilityImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/CapabilityImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/CapabilityImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,17 +21,21 @@ /** * Capability implementation class. - * + * * @author Roger Ruttimann * @version $Id: CapabilityImpl.java 517719 2007-03-13 15:05:48Z ate $ */ public class CapabilityImpl implements Capability { + private int capabilityId; + private String name; - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.registry.Capability#setCapabilityId(int) */ public void setCapabilityId(int id) @@ -39,7 +43,9 @@ this.capabilityId = id; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.registry.Capability#getCapabilityId() */ public int getCapabilityId() @@ -47,7 +53,9 @@ return this.capabilityId; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.registry.Capability#setName(java.lang.String) */ public void setName(String name) @@ -55,53 +63,48 @@ this.name = name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.registry.Capability#getName() */ public String getName() { return this.name; } - - + /** - * Implements the hashCode calculation so two different objects with the content return the same hashcode.... + * Implements the hashCode calculation so two different objects with the + * content return the same hashcode.... */ public int hashCode() { - return name.hashCode(); + return name.hashCode(); } /** - * Implements the equals operation so that 2 elements are equal if - * all their member values are equal. - * - * - * @param object to compare this one with + * Implements the equals operation so that 2 elements are equal if all their + * member values are equal. + * + * + * @param object + * to compare this one with * @return true if both objects represent the same (logical) content */ public boolean equals(Object object) { - if (!(object instanceof Capability)) - { - return false; - } - if (this == object) - return true; -// Don't check the ID - id is only set through OJB so this would not recognize equality correctly - /* if (this.capabilityId != ((Capability)object).getCapabilityId()) - return false; - */ - String oName = ((Capability)object).getName(); - if ( - (oName == null) && (name == null) - || - (oName == name) - || - ((oName != null) && (oName.equals(name))) - ) - return true; - return false; + if (!(object instanceof Capability)) { return false; } + if (this == object) return true; + // Don't check the ID - id is only set through OJB so this would not + // recognize equality correctly + /* + * if (this.capabilityId != ((Capability)object).getCapabilityId()) + * return false; + */ + String oName = ((Capability) object).getName(); + if ((oName == null) && (name == null) || (oName == name) + || ((oName != null) && (oName.equals(name)))) return true; + return false; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/CapabilityMapImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/CapabilityMapImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/CapabilityMapImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,125 +16,133 @@ */ package org.apache.jetspeed.capabilities.impl; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.jetspeed.capabilities.Capability; import org.apache.jetspeed.capabilities.CapabilityMap; import org.apache.jetspeed.capabilities.Client; -import org.apache.jetspeed.capabilities.Capability; import org.apache.jetspeed.capabilities.MediaType; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - import org.apache.jetspeed.capabilities.MimeType; /** * Implementation for capabilityMap interface - * + * * @author Roger Ruttimann * @version $Id: CapabilityMapImpl.java 553014 2007-07-03 23:10:53Z ate $ */ class CapabilityMapImpl implements CapabilityMap { - private static final Log log = - LogFactory.getLog(JetspeedCapabilities.class); - + + private static final Log log = LogFactory + .getLog(JetspeedCapabilities.class); + // Members private String useragent; // User agent for request + private Map mimeTypeMap = new HashMap(); // supported Mimetypes for Agent + private Map capabilityMap = new HashMap(); + // supported Capabilities for Agent - private Map mediaTypeMap = new HashMap(); // supported MediaTypes for Agent + private Map mediaTypeMap = new HashMap(); // supported MediaTypes for + + // Agent + private Client client; // client for Agent + private MediaType preferredMediaType; // Preferred MediaType for client. /** - Sets the client for the CapabilityMap - */ + * Sets the client for the CapabilityMap + */ public void setClient(Client client) { this.client = client; } /** - Returns the Client for the CapabilityMap - */ + * Returns the Client for the CapabilityMap + */ public Client getClient() { return this.client; } /** - Add capability to the CapabilityMap - */ + * Add capability to the CapabilityMap + */ public void addCapability(Capability capability) - { - if (capability != null) // avoid null due to duplicates in database - this.capabilityMap.put(capability.getName(), capability); + { + if (capability != null) // avoid null due to duplicates in database + this.capabilityMap.put(capability.getName(), capability); } /** - Add Mimetype to the MimetypeMap - */ + * Add Mimetype to the MimetypeMap + */ public void addMimetype(MimeType mimetype) { - if (mimetype != null) // avoid null due to duplicates in database - this.mimeTypeMap.put(mimetype.getName(), mimetype); + if (mimetype != null) // avoid null due to duplicates in database + this.mimeTypeMap.put(mimetype.getName(), mimetype); } /** - Add MediaType to the MediaTypeMap - */ + * Add MediaType to the MediaTypeMap + */ public void addMediaType(MediaType mediatype) { - if (mediatype != null) // avoid null due to duplicates in database - this.mediaTypeMap.put(mediatype.getName(), mediatype); + if (mediatype != null) // avoid null due to duplicates in database + this.mediaTypeMap.put(mediatype.getName(), mediatype); } /** - Returns the preferred MIME type for the current user-agent - */ + * Returns the preferred MIME type for the current user-agent + */ public MimeType getPreferredType() { - // Return the value that matches the preferredMimeType defined in the Client + // Return the value that matches the preferredMimeType defined in the + // Client int prefMimeTypeId = this.client.getPreferredMimeTypeId(); - MimeType mt = null; + MimeType mt = null; Iterator e = this.mimeTypeMap.values().iterator(); while (e.hasNext()) - { + { mt = (MimeType) e.next(); - - if (mt.getMimetypeId() == prefMimeTypeId) - return mt; + + if (mt.getMimetypeId() == prefMimeTypeId) return mt; } - log.error("Could not find preferred Mime Type for " + prefMimeTypeId); + log.error("Could not find preferred Mime Type for " + prefMimeTypeId); // Should never reach this point. A preferred value needs to be set return null; // TODO: NEVER RETURN NULL } /** - * Sets the preferred MediaType for this CapabilityMap - * @param MediaTypeEntry - */ + * Sets the preferred MediaType for this CapabilityMap + * + * @param MediaTypeEntry + */ public void setPreferredMediaType(MediaType type) { this.preferredMediaType = type; } /** - Returns the preferred media type for the current user-agent - */ + * Returns the preferred media type for the current user-agent + */ public MediaType getPreferredMediaType() { return this.preferredMediaType; } /** - * Returns an ordered list of supported media-types, from most preferred - * to least preferred + * Returns an ordered list of supported media-types, from most preferred to + * least preferred */ public Iterator listMediaTypes() { @@ -142,8 +150,8 @@ } /** - Returns the user-agent string - */ + * Returns the user-agent string + */ public String getAgent() { return this.useragent; @@ -165,73 +173,61 @@ Iterator capabilities = capabilityMap.values().iterator(); while (capabilities.hasNext()) { - if (((Capability) capabilities.next()).getCapabilityId() - == capability) - { - return true; - } + if (((Capability) capabilities.next()).getCapabilityId() == capability) { return true; } } return false; } /** - * Checks to see if the current agent has the specified capability + * Checks to see if the current agent has the specified capability */ public boolean hasCapability(String capability) { Iterator capabilities = capabilityMap.values().iterator(); while (capabilities.hasNext()) { - if (((Capability) capabilities.next()).getName().equals(capability)) - { - return true; - } + if (((Capability) capabilities.next()).getName().equals(capability)) { return true; } } return false; } /** - Get the mime types that this CapabilityMap supports. - */ + * Get the mime types that this CapabilityMap supports. + */ public Iterator getMimeTypes() { return mimeTypeMap.values().iterator(); } /** - Return true if this CapabilityMap supports the given MimeType - */ + * Return true if this CapabilityMap supports the given MimeType + */ public boolean supportsMimeType(MimeType mimeType) { Iterator mimetypes = mimeTypeMap.values().iterator(); while (mimetypes.hasNext()) { - if (((MimeType) mimetypes.next()).getName().equals(mimeType.getName())) - { - return true; - } + if (((MimeType) mimetypes.next()).getName().equals( + mimeType.getName())) { return true; } } return false; } /** * Return true if this CapabilityMap supports the given media type - * - * @param media the name of a media type registered in the - * MediaType registry - * + * + * @param media + * the name of a media type registered in the MediaType registry + * * @return true is the capabilities of this agent at least match those - * required by the media type + * required by the media type */ public boolean supportsMediaType(String media) { Iterator mediatypes = mediaTypeMap.values().iterator(); while (mediatypes.hasNext()) { - if (((MediaType) mediatypes.next()).getName() == media) - { - return true; - } + if (((MediaType) mediatypes.next()).getName() == media) { return true; } } return false; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/ClientImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/ClientImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/ClientImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,15 +17,15 @@ package org.apache.jetspeed.capabilities.impl; -import org.apache.commons.collections.CollectionUtils; -import org.apache.jetspeed.capabilities.Client; - import java.util.ArrayList; import java.util.Collection; +import org.apache.commons.collections.CollectionUtils; +import org.apache.jetspeed.capabilities.Client; + /** * Simple implementation of the ClientRegistry interface. - * + * * @author Stephan Hesmer * @author Rapha\u00ebl Luta * @author Roger Ruttimann @@ -33,16 +33,25 @@ */ public class ClientImpl implements Client, java.io.Serializable { + private String userAgentPattern = ""; + private String manufacturer = ""; + private String model = ""; + private String version = ""; + private String name; + private Collection mimetypes; + private Collection capabilities; + private int preferredMimeTypeId; private int clientId; + private int evalOrder = 0; public ClientImpl() @@ -50,116 +59,78 @@ } /** - * Implements the equals operation so that 2 elements are equal if - * all their member values are equal. + * Implements the equals operation so that 2 elements are equal if all their + * member values are equal. */ public boolean equals(Object object) { - if (object == this) - return true; + if (object == this) return true; - if (object == null) - { - return false; - } - + if (object == null) { return false; } + ClientImpl obj = (ClientImpl) object; if (name != null) { - if (!name.equals(obj.name)) - { - return false; - } - } else + if (!name.equals(obj.name)) { return false; } + } + else { - if (obj.name != null) - { - return false; - } + if (obj.name != null) { return false; } } - + if (userAgentPattern != null) { - if (!userAgentPattern.equals(obj.userAgentPattern)) - { - return false; - } - } else + if (!userAgentPattern.equals(obj.userAgentPattern)) { return false; } + } + else { - if (obj.userAgentPattern != null) - { - return false; - } + if (obj.userAgentPattern != null) { return false; } } if (manufacturer != null) { - if (!manufacturer.equals(obj.manufacturer)) - { - return false; - } - } else + if (!manufacturer.equals(obj.manufacturer)) { return false; } + } + else { - if (obj.manufacturer != null) - { - return false; - } + if (obj.manufacturer != null) { return false; } } if (model != null) { - if (!model.equals(obj.model)) - { - return false; - } - } else + if (!model.equals(obj.model)) { return false; } + } + else { - if (obj.model != null) - { - return false; - } + if (obj.model != null) { return false; } } if (version != null) { - if (!version.equals(obj.version)) - { - return false; - } - } else + if (!version.equals(obj.version)) { return false; } + } + else { - if (obj.version != null) - { - return false; - } + if (obj.version != null) { return false; } } if (mimetypes != null) { - if (!CollectionUtils.isEqualCollection(mimetypes, obj.mimetypes)) - { - return false; - } + if (!CollectionUtils.isEqualCollection(mimetypes, obj.mimetypes)) { return false; } } else { - if (obj.mimetypes != null) - { - return false; - } + if (obj.mimetypes != null) { return false; } } - if (capabilities != null) + if (capabilities != null) { - if (!(CollectionUtils.isEqualCollection(capabilities,obj.capabilities ))) - return false; - } + if (!(CollectionUtils.isEqualCollection(capabilities, + obj.capabilities))) return false; + } else { - if (obj.capabilities != null) - { - return false; - } + if (obj.capabilities != null) { return false; } } return true; } @@ -206,7 +177,7 @@ public Collection getMimetypes() { - if(this.mimetypes == null) + if (this.mimetypes == null) { this.mimetypes = new ArrayList(); } @@ -220,7 +191,7 @@ public Collection getCapabilities() { - if(capabilities == null) + if (capabilities == null) { capabilities = new ArrayList(); } @@ -234,6 +205,7 @@ /** * Set Client ID -- Assigns the Client ID + * * @param id */ public void setClientId(int id) @@ -243,12 +215,14 @@ /** * Get Client ID + * * @return Client ID */ public int getClientId() { return this.clientId; } + /** * @return */ @@ -275,7 +249,9 @@ /** * Set preferred Mimetype ID for Client - * @param mimeTypeId MimeTypeId + * + * @param mimeTypeId + * MimeTypeId */ public void setPreferredMimeTypeId(int mimeTypeId) { @@ -289,8 +265,10 @@ { return evalOrder; } + /** - * @param evalOrder The evalOrder to set. + * @param evalOrder + * The evalOrder to set. */ public void setEvalOrder(int evalOrder) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/JetspeedCapabilities.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/JetspeedCapabilities.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/JetspeedCapabilities.java 2008-05-16 01:54:54 UTC (rev 940) @@ -42,16 +42,18 @@ /** * Jetspeed Capabilities - * + * * @author David Sean Taylor * @author Roger Ruttimann * @version $Id: JetspeedCapabilities.java 517124 2007-03-12 08:10:25Z ate $ */ -public class JetspeedCapabilities extends InitablePersistenceBrokerDaoSupport implements Capabilities ,BeanFactoryAware +public class JetspeedCapabilities extends InitablePersistenceBrokerDaoSupport + implements Capabilities, BeanFactoryAware { - private static final Log log = - LogFactory.getLog(JetspeedCapabilities.class); + private static final Log log = LogFactory + .getLog(JetspeedCapabilities.class); + public static final String DEFAULT_AGENT = "Mozilla/4.0"; public static final String AGENT_XML = "agentxml/1.0"; @@ -67,45 +69,55 @@ private BeanFactory beanFactory; /** named bean references */ - private String clientBeanName; - private String capabilityBeanName; - private String mimeTypeBeanName; - private String mediaTypeBeanName; + private String clientBeanName; - private Class clientClass; - private Class capabilityClass; - private Class mimeTypeClass; - private Class mediaTypeClass; - - - public JetspeedCapabilities(String repositoryPath, String clientBeanName, String mediaTypeBeanName, String mimeTypeBeanName, String capabilityBeanName) + private String capabilityBeanName; + + private String mimeTypeBeanName; + + private String mediaTypeBeanName; + + private Class clientClass; + + private Class capabilityClass; + + private Class mimeTypeClass; + + private Class mediaTypeClass; + + public JetspeedCapabilities(String repositoryPath, String clientBeanName, + String mediaTypeBeanName, String mimeTypeBeanName, + String capabilityBeanName) { super(repositoryPath); - this.clientBeanName = clientBeanName; - this.capabilityBeanName = capabilityBeanName; - this.mimeTypeBeanName = mimeTypeBeanName; - this.mediaTypeBeanName = mediaTypeBeanName; - } - + this.clientBeanName = clientBeanName; + this.capabilityBeanName = capabilityBeanName; + this.mimeTypeBeanName = mimeTypeBeanName; + this.mediaTypeBeanName = mediaTypeBeanName; + } + /** * Create a JetspeedProfiler with properties. Expected properties are: * - * defaultRule = the default profiling rule - * anonymousUser = the name of the anonymous user - * persistenceStoreName = The name of the persistence persistenceStore component to connect to - * services.profiler.locator.impl = the pluggable Profile Locator impl - * services.profiler.principalRule.impl = the pluggable Principal Rule impl - * services.profiler.profilingRule.impl = the pluggable Profiling Rule impl - * - * @param persistenceStore The persistence persistenceStore - * @param properties Properties for this component described above + * defaultRule = the default profiling rule anonymousUser = the name of the + * anonymous user persistenceStoreName = The name of the persistence + * persistenceStore component to connect to services.profiler.locator.impl = + * the pluggable Profile Locator impl services.profiler.principalRule.impl = + * the pluggable Principal Rule impl services.profiler.profilingRule.impl = + * the pluggable Profiling Rule impl + * + * @param persistenceStore + * The persistence persistenceStore + * @param properties + * Properties for this component described above * @deprecated As of release 2.1, property-based class references replaced * by container managed bean factory */ public JetspeedCapabilities(String repositoryPath, Properties properties) - { + { super(repositoryPath); } + /* * Method called automatically by Spring container upon initialization * @@ -117,50 +129,51 @@ this.beanFactory = beanFactory; } + private Class getClientClass() throws ClassNotFoundException + { + if (clientClass == null) + { + clientClass = createClient(null).getClass(); + } + return clientClass; + } - private Class getClientClass() throws ClassNotFoundException - { - if (clientClass == null) - { - clientClass = createClient(null).getClass(); - } - return clientClass; - } - - private Class getMimeTypeClass() throws ClassNotFoundException - { - if (mimeTypeClass == null) - { - mimeTypeClass = this.createMimeType(null).getClass(); - } - return mimeTypeClass; - } - private Class getCapabilityClass()throws ClassNotFoundException - { - if (capabilityClass == null) - { - capabilityClass = this.createCapability(null).getClass(); - } - return capabilityClass; - } + private Class getMimeTypeClass() throws ClassNotFoundException + { + if (mimeTypeClass == null) + { + mimeTypeClass = this.createMimeType(null).getClass(); + } + return mimeTypeClass; + } - private Class getMediaTypeClass()throws ClassNotFoundException - { - if (mediaTypeClass == null) - { - mediaTypeClass = this.createMediaType(null).getClass(); - } - return mediaTypeClass; - } - + private Class getCapabilityClass() throws ClassNotFoundException + { + if (capabilityClass == null) + { + capabilityClass = this.createCapability(null).getClass(); + } + return capabilityClass; + } + private Class getMediaTypeClass() throws ClassNotFoundException + { + if (mediaTypeClass == null) + { + mediaTypeClass = this.createMediaType(null).getClass(); + } + return mediaTypeClass; + } + /** - * @param userAgent Agent from the request + * @param userAgent + * Agent from the request * @throws UnableToBuildCapabilityMapException * @see org.apache.jetspeed.services.capability.CapabilityService#getCapabilityMap(java.lang.String) */ - public CapabilityMap getCapabilityMap(String userAgent) throws UnableToBuildCapabilityMapException - { + public CapabilityMap getCapabilityMap(String userAgent) + throws UnableToBuildCapabilityMapException + { CapabilityMap map = null; boolean bClientFound = false; String defaultAgent = null; @@ -188,19 +201,19 @@ { if (userAgent.equals(DEFAULT_AGENT)) { - log.error( - "CapabilityMap: Default agent not found in Client Registry !"); + log + .error("CapabilityMap: Default agent not found in Client Registry !"); - // Stop searching -- event the default userAgent can't be found + // Stop searching -- event the default userAgent can't be + // found bClientFound = true; - } else + } + else { // Retry with the default Agent if (log.isDebugEnabled()) { - log.debug( - "CapabilityMap: useragent " - + userAgent + log.debug("CapabilityMap: useragent " + userAgent + "unknown, falling back to default"); } @@ -208,7 +221,8 @@ defaultAgent = userAgent; userAgent = DEFAULT_AGENT; } - } else + } + else { // Found Client entry start populating the capability map. map = new CapabilityMapImpl(); @@ -223,8 +237,8 @@ map.addCapability((Capability) capabilities.next()); } - Collection mediatypes = - getMediaTypesForMimeTypes(entry.getMimetypes().iterator()); + Collection mediatypes = getMediaTypesForMimeTypes(entry + .getMimetypes().iterator()); // Add Mimetypes to map Iterator mimetypes = entry.getMimetypes().iterator(); @@ -239,13 +253,14 @@ map.addMediaType((MediaType) media.next()); } - //Set preferred Mimetype + // Set preferred Mimetype MediaType mtEntry = getMediaType(entry.getName()); if (mtEntry == null) { - mtEntry = getMediaTypeForMimeType(map.getPreferredType().getName()); + mtEntry = getMediaTypeForMimeType(map.getPreferredType() + .getName()); } - + map.setPreferredMediaType(mtEntry); // Add map to cache @@ -256,24 +271,27 @@ } } - - if(map != null) + + if (map != null) { - return map; + return map; } else { - throw new UnableToBuildCapabilityMapException("We were unable to build a capability map for the agent, "+userAgent+ - ". This might be an indiciation that the capability database has not been correctly initialized."); + throw new UnableToBuildCapabilityMapException( + "We were unable to build a capability map for the agent, " + + userAgent + + ". This might be an indiciation that the capability database has not been correctly initialized."); } } /** * Returns the client which matches the given useragent string. - * - * @param useragent the useragent to match + * + * @param useragent + * the useragent to match * @return the found client or null if the user-agent does not match any - * defined client + * defined client * @see org.apache.jetspeed.capabilities.CapabilityService#findClient(java.lang.String) */ @@ -284,8 +302,7 @@ if (log.isDebugEnabled()) { - log.debug( - "ClientRegistry: Looking for client with useragent :" + log.debug("ClientRegistry: Looking for client with useragent :" + userAgent); } @@ -298,37 +315,33 @@ { // Java 1.4 has regular expressions build in String exp = client.getUserAgentPattern(); - //RE r = new RE(client.getUserAgentPattern()); - //r.setMatchFlags(RE.MATCH_CASEINDEPENDENT); - //if (r.match(userAgent)) + // RE r = new RE(client.getUserAgentPattern()); + // r.setMatchFlags(RE.MATCH_CASEINDEPENDENT); + // if (r.match(userAgent)) if (userAgent.matches(exp)) { if (log.isDebugEnabled()) { - log.debug( - "Client: " - + userAgent - + " matches " + log.debug("Client: " + userAgent + " matches " + client.getUserAgentPattern()); } return client; - } else + } + else { if (log.isDebugEnabled()) { - log.debug( - "Client: " - + userAgent + log.debug("Client: " + userAgent + " does not match " + client.getUserAgentPattern()); } } - } catch (java.util.regex.PatternSyntaxException e) + } + catch (java.util.regex.PatternSyntaxException e) { - String message = - "CapabilityServiceImpl: UserAgentPattern not valid : " + String message = "CapabilityServiceImpl: UserAgentPattern not valid : " + client.getUserAgentPattern() + " : " + e.getMessage(); @@ -340,38 +353,39 @@ return clientEntry; } - /* + /* * @see org.apache.jetspeed.capabilities.CapabilityService#getClients() */ public Iterator getClients() { if (null == clients) { - try - { - QueryByCriteria query = QueryFactory.newQuery(getClientClass(), new Criteria()); - query.addOrderByAscending("evalOrder"); - this.clients = getPersistenceBrokerTemplate().getCollectionByQuery(query); - } - catch (Exception e) - { - String message = - "CapabilityServiceImpl: getClients query used invalid class "; - log.error(message, e); - return null; - } + try + { + QueryByCriteria query = QueryFactory.newQuery(getClientClass(), + new Criteria()); + query.addOrderByAscending("evalOrder"); + this.clients = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); + } + catch (Exception e) + { + String message = "CapabilityServiceImpl: getClients query used invalid class "; + log.error(message, e); + return null; + } } return this.clients.iterator(); } - /* + /* * @see org.apache.jetspeed.capabilities.CapabilityService#getMediaTypesForMimeTypes(java.util.Iterator) */ public Collection getMediaTypesForMimeTypes(Iterator mimetypes) { - //Find the MediaType by matching the Mimetype - + // Find the MediaType by matching the Mimetype + Criteria filter = new Criteria(); Vector temp = new Vector(); @@ -383,26 +397,26 @@ // Add mimetype to query // Note: mimetypes is a member of MediaTypeImpl // criteria.addEqualTo("mimetypes.name", mt.getName()); - //stuff.add(new Integer(mt.getMimetypeId())); + // stuff.add(new Integer(mt.getMimetypeId())); temp.add(mt.getName()); } - + Collection co = null; if (temp.size() > 0) { - try - { - filter.addIn("mimetypes.name", temp); - QueryByCriteria query = QueryFactory.newQuery(getMediaTypeClass(), filter); - co = getPersistenceBrokerTemplate().getCollectionByQuery(query); - } - catch (Exception e) - { - String message = - "CapabilityServiceImpl: getMediaTypesForMimeTypes -> getMediaTypeClass query used invalid class "; - log.error(message, e); - - } + try + { + filter.addIn("mimetypes.name", temp); + QueryByCriteria query = QueryFactory.newQuery( + getMediaTypeClass(), filter); + co = getPersistenceBrokerTemplate().getCollectionByQuery(query); + } + catch (Exception e) + { + String message = "CapabilityServiceImpl: getMediaTypesForMimeTypes -> getMediaTypeClass query used invalid class "; + log.error(message, e); + + } } if (co == null || co.isEmpty()) { @@ -414,7 +428,7 @@ return co; } - /* + /* * @see org.apache.jetspeed.capabilities.CapabilityService#deleteCapabilityMapCache() */ public void deleteCapabilityMapCache() @@ -423,57 +437,65 @@ clients = null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.capabilities.CapabilityService#getMediaType(java.lang.String) */ public MediaType getMediaType(String mediaType) - { - try - { - Criteria filter = new Criteria(); - filter.addEqualTo("name", mediaType); - QueryByCriteria query = QueryFactory.newQuery(getMediaTypeClass(), filter); - return (MediaType) getPersistenceBrokerTemplate().getObjectByQuery(query); - } - catch (Exception e) - { - String message = - "CapabilityServiceImpl: getMediaType query used invalid class "; - log.error(message, e); - return null; - } + { + try + { + Criteria filter = new Criteria(); + filter.addEqualTo("name", mediaType); + QueryByCriteria query = QueryFactory.newQuery(getMediaTypeClass(), + filter); + return (MediaType) getPersistenceBrokerTemplate().getObjectByQuery( + query); + } + catch (Exception e) + { + String message = "CapabilityServiceImpl: getMediaType query used invalid class "; + log.error(message, e); + return null; + } } /** * getMediaTypeForMimeType - * @param mimeType to use for lookup - * @return MediaTypeEntry that matches the lookup in the MEDIATYPE_TO_MIMETYPE table + * + * @param mimeType + * to use for lookup + * @return MediaTypeEntry that matches the lookup in the + * MEDIATYPE_TO_MIMETYPE table */ public MediaType getMediaTypeForMimeType(String mimeTypeName) - { - //Find the MediaType by matching the Mimetype - Collection mediaTypeCollection = null; - try - { - Criteria filter = new Criteria(); - filter.addEqualTo("mimetypes.name", mimeTypeName); - - QueryByCriteria query = QueryFactory.newQuery(getMediaTypeClass(), filter); - mediaTypeCollection = getPersistenceBrokerTemplate().getCollectionByQuery(query); - } - catch (Exception e) - { - String message = - "CapabilityServiceImpl: getMediaTypeForMimeType query used invalid class "; - log.error(message, e); - return null; - } - + { + // Find the MediaType by matching the Mimetype + Collection mediaTypeCollection = null; + try + { + Criteria filter = new Criteria(); + filter.addEqualTo("mimetypes.name", mimeTypeName); + + QueryByCriteria query = QueryFactory.newQuery(getMediaTypeClass(), + filter); + mediaTypeCollection = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); + } + catch (Exception e) + { + String message = "CapabilityServiceImpl: getMediaTypeForMimeType query used invalid class "; + log.error(message, e); + return null; + } + Iterator mtIterator = mediaTypeCollection.iterator(); if (mtIterator.hasNext()) { return (MediaType) mtIterator.next(); - } else + } + else { return null; } @@ -481,318 +503,347 @@ /** * Obtain an iterator of all existing capabilities. - * @return Returns an iterator for all existing Capabilities of type Capability + * + * @return Returns an iterator for all existing Capabilities of type + * Capability */ public Iterator getCapabilities() { - QueryByCriteria query = null; - try - { - query = QueryFactory.newQuery(getCapabilityClass(), new Criteria()); - } - catch (Exception e) - { - String message = - "CapabilityServiceImpl: getCapabilities query used invalid class "; - log.error(message, e); - return null; - } + QueryByCriteria query = null; + try + { + query = QueryFactory.newQuery(getCapabilityClass(), new Criteria()); + } + catch (Exception e) + { + String message = "CapabilityServiceImpl: getCapabilities query used invalid class "; + log.error(message, e); + return null; + } query.addOrderByAscending("name"); - return getPersistenceBrokerTemplate().getCollectionByQuery(query).iterator(); + return getPersistenceBrokerTemplate().getCollectionByQuery(query) + .iterator(); } - + /** * Obtain an iterator of all existing mime types. - * @return Returns an iterator for all existing Mime Types of type MimeType + * + * @return Returns an iterator for all existing Mime Types of type + * MimeType */ public Iterator getMimeTypes() { - try - { - QueryByCriteria query = QueryFactory.newQuery(getMimeTypeClass(), new Criteria()); - query.addOrderByAscending("name"); - return getPersistenceBrokerTemplate().getCollectionByQuery(query).iterator(); - } - catch (Exception e) - { - String message = - "CapabilityServiceImpl: getMimeTypes query used invalid class "; - log.error(message, e); - return null; - } + try + { + QueryByCriteria query = QueryFactory.newQuery(getMimeTypeClass(), + new Criteria()); + query.addOrderByAscending("name"); + return getPersistenceBrokerTemplate().getCollectionByQuery(query) + .iterator(); + } + catch (Exception e) + { + String message = "CapabilityServiceImpl: getMimeTypes query used invalid class "; + log.error(message, e); + return null; + } } - + /** * Obtain an iterator of all existing media types. - * @return Returns an iterator for all existing media types of type MediaType + * + * @return Returns an iterator for all existing media types of type + * MediaType */ public Iterator getMediaTypes() { - try - { - QueryByCriteria query = QueryFactory.newQuery(getMediaTypeClass(), new Criteria()); - query.addOrderByAscending("name"); - return getPersistenceBrokerTemplate().getCollectionByQuery(query).iterator(); - } - catch (Exception e) - { - String message = - "CapabilityServiceImpl: getMediaTypes query used invalid class "; - log.error(message, e); - return null; - } + try + { + QueryByCriteria query = QueryFactory.newQuery(getMediaTypeClass(), + new Criteria()); + query.addOrderByAscending("name"); + return getPersistenceBrokerTemplate().getCollectionByQuery(query) + .iterator(); + } + catch (Exception e) + { + String message = "CapabilityServiceImpl: getMediaTypes query used invalid class "; + log.error(message, e); + return null; + } } - /* + + /* * @see org.apache.jetspeed.capabilities.Capabilities#getMimeTypeBeanName() */ - public String getMimeTypeBeanName() { - return mimeTypeBeanName; - } + public String getMimeTypeBeanName() + { + return mimeTypeBeanName; + } - /* + /* * @see org.apache.jetspeed.capabilities.Capabilities#setMimeTypeBeanName(String) */ - public void setMimeTypeBeanName(String mimeTypeBeanName) { - this.mimeTypeBeanName = mimeTypeBeanName; - } + public void setMimeTypeBeanName(String mimeTypeBeanName) + { + this.mimeTypeBeanName = mimeTypeBeanName; + } - /* + /* * @see org.apache.jetspeed.capabilities.Capabilities#getClientBeanName() */ - public String getClientBeanName() { - return clientBeanName; - } + public String getClientBeanName() + { + return clientBeanName; + } - /* + /* * @see org.apache.jetspeed.capabilities.Capabilities#setClientBeanName(String) */ - public void setClientBeanName(String clientBeanName) { - this.clientBeanName = clientBeanName; - } + public void setClientBeanName(String clientBeanName) + { + this.clientBeanName = clientBeanName; + } - /* + /* * @see org.apache.jetspeed.capabilities.Capabilities#getMediaTypeBeanName() */ - public String getMediaTypeBeanName() { - return mediaTypeBeanName; - } + public String getMediaTypeBeanName() + { + return mediaTypeBeanName; + } - /* + /* * @see org.apache.jetspeed.capabilities.Capabilities#setMediaTypeBeanName(String) */ - public void setMediaTypeBeanName(String mediaTypeBeanName) { - this.mediaTypeBeanName = mediaTypeBeanName; - } + public void setMediaTypeBeanName(String mediaTypeBeanName) + { + this.mediaTypeBeanName = mediaTypeBeanName; + } - /* + /* * @see org.apache.jetspeed.capabilities.Capabilities#getCapabilityBeanName() */ - public String getCapabilityBeanName() { - return capabilityBeanName; - } + public String getCapabilityBeanName() + { + return capabilityBeanName; + } - /* + /* * @see org.apache.jetspeed.capabilities.Capabilities#setCapabilityBeanName(String) */ - public void setCapabilityBeanName(String capabilityBeanName) { - this.capabilityBeanName = capabilityBeanName; - } - - /* + public void setCapabilityBeanName(String capabilityBeanName) + { + this.capabilityBeanName = capabilityBeanName; + } + + /* * @see org.apache.jetspeed.capabilities.Capabilities#createMimeType(String) */ - public MimeType createMimeType(String mimeType) - throws ClassNotFoundException - { - MimeType mimeTypeobj = null; - if (mimeType != null) - { - //try to find it in space - mimeTypeobj = this.getMimeType(mimeType); - if (mimeTypeobj != null) - return mimeTypeobj; - } + public MimeType createMimeType(String mimeType) + throws ClassNotFoundException + { + MimeType mimeTypeobj = null; + if (mimeType != null) + { + // try to find it in space + mimeTypeobj = this.getMimeType(mimeType); + if (mimeTypeobj != null) return mimeTypeobj; + } try { - mimeTypeobj = (MimeType) beanFactory.getBean( - this.mimeTypeBeanName, MimeType.class); - mimeTypeobj.setName(mimeType); + mimeTypeobj = (MimeType) beanFactory.getBean(this.mimeTypeBeanName, + MimeType.class); + mimeTypeobj.setName(mimeType); return mimeTypeobj; - } catch (Exception e) + } + catch (Exception e) { - log.error("Failed to create capability instance for " + this.mimeTypeBeanName - + " error : " + e.getLocalizedMessage()); - throw new ClassNotFoundException("Spring failed to create the " + this.mimeTypeBeanName - + " mimeType bean.", e); + log.error("Failed to create capability instance for " + + this.mimeTypeBeanName + " error : " + + e.getLocalizedMessage()); + throw new ClassNotFoundException("Spring failed to create the " + + this.mimeTypeBeanName + " mimeType bean.", e); } - } - + } - /* + /* * @see org.apache.jetspeed.capabilities.Capabilities#createCapability(String) */ - public Capability createCapability(String capabilityName) throws ClassNotFoundException - { - Capability capability = null; - if (capabilityName != null) - { - //try to find it in space - capability = this.getCapability(capabilityName); - if (capability != null) - return capability; - } + public Capability createCapability(String capabilityName) + throws ClassNotFoundException + { + Capability capability = null; + if (capabilityName != null) + { + // try to find it in space + capability = this.getCapability(capabilityName); + if (capability != null) return capability; + } try { - capability = (Capability) beanFactory.getBean( + capability = (Capability) beanFactory.getBean( this.capabilityBeanName, Capability.class); - capability.setName(capabilityName); + capability.setName(capabilityName); return capability; - } catch (Exception e) + } + catch (Exception e) { - log.error("Failed to create capability instance for " + this.capabilityBeanName - + " error : " + e.getLocalizedMessage()); + log.error("Failed to create capability instance for " + + this.capabilityBeanName + " error : " + + e.getLocalizedMessage()); throw new ClassNotFoundException("Spring failed to create the " + " capability bean.", e); } - } + } - /* + /* * @see org.apache.jetspeed.capabilities.Capabilities#createMediaType(String) */ - public MediaType createMediaType(String mediaTypeName) throws ClassNotFoundException - { - MediaType mediaType = null; - if (mediaTypeName != null) - { - //try to find it in space - mediaType = this.getMediaType(mediaTypeName); - if (mediaType != null) - return mediaType; - } + public MediaType createMediaType(String mediaTypeName) + throws ClassNotFoundException + { + MediaType mediaType = null; + if (mediaTypeName != null) + { + // try to find it in space + mediaType = this.getMediaType(mediaTypeName); + if (mediaType != null) return mediaType; + } try { - mediaType = (MediaType) beanFactory.getBean( - this.mediaTypeBeanName, MediaType.class); - mediaType.setName(mediaTypeName); + mediaType = (MediaType) beanFactory.getBean(this.mediaTypeBeanName, + MediaType.class); + mediaType.setName(mediaTypeName); return mediaType; - } catch (Exception e) + } + catch (Exception e) { - log.error("Failed to create mediaType instance for " + this.mediaTypeBeanName - + " error : " + e.getLocalizedMessage()); + log.error("Failed to create mediaType instance for " + + this.mediaTypeBeanName + " error : " + + e.getLocalizedMessage()); throw new ClassNotFoundException("Spring failed to create the " + " mediaType bean.", e); } - } + } - - /* + /* * @see org.apache.jetspeed.capabilities.Capabilities#createClient(String) */ - public Client createClient(String clientName) throws ClassNotFoundException - { - Client client = null; - if (clientName != null) - { - //try to find it in space - client = this.getClient(clientName); - if (client != null) - return client; - } + public Client createClient(String clientName) throws ClassNotFoundException + { + Client client = null; + if (clientName != null) + { + // try to find it in space + client = this.getClient(clientName); + if (client != null) return client; + } try { - client = (Client) beanFactory.getBean( - this.clientBeanName, Client.class); - client.setName(clientName); + client = (Client) beanFactory.getBean(this.clientBeanName, + Client.class); + client.setName(clientName); return client; - } catch (Exception e) + } + catch (Exception e) { - log.error("Failed to create client instance for " + this.clientBeanName - + " error : " + e.getLocalizedMessage()); + log.error("Failed to create client instance for " + + this.clientBeanName + " error : " + + e.getLocalizedMessage()); throw new ClassNotFoundException("Spring failed to create the " + " client bean.", e); } - } - /* (non-Javadoc) + } + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.capabilities.MimeTypeservice#getCapability(java.lang.String) */ public MimeType getMimeType(String mimeType) { - try - { - Criteria filter = new Criteria(); - filter.addEqualTo("name", mimeType); - QueryByCriteria query = QueryFactory.newQuery(getMimeTypeClass(), filter); - return (MimeType) getPersistenceBrokerTemplate().getObjectByQuery(query); - } - catch (Exception e) - { - String message = - "MimeTypeserviceImpl: getCapability - query for getCapabilityClass failed "; - log.error(message, e); - return null; - - } + try + { + Criteria filter = new Criteria(); + filter.addEqualTo("name", mimeType); + QueryByCriteria query = QueryFactory.newQuery(getMimeTypeClass(), + filter); + return (MimeType) getPersistenceBrokerTemplate().getObjectByQuery( + query); + } + catch (Exception e) + { + String message = "MimeTypeserviceImpl: getCapability - query for getCapabilityClass failed "; + log.error(message, e); + return null; + } + } - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.capabilities.MimeTypeservice#getClientjava.lang.String) */ public Client getClient(String clientName) - { - try - { - Criteria filter = new Criteria(); - filter.addEqualTo("name", clientName); - QueryByCriteria query = QueryFactory.newQuery(getClientClass(), filter); - return (Client) getPersistenceBrokerTemplate().getObjectByQuery(query); - } - catch (Exception e) - { - String message = - "MimeTypeserviceImpl: getClient - query for getClientClass failed "; - log.error(message, e); - return null; - - } - } - + { + try + { + Criteria filter = new Criteria(); + filter.addEqualTo("name", clientName); + QueryByCriteria query = QueryFactory.newQuery(getClientClass(), + filter); + return (Client) getPersistenceBrokerTemplate().getObjectByQuery( + query); + } + catch (Exception e) + { + String message = "MimeTypeserviceImpl: getClient - query for getClientClass failed "; + log.error(message, e); + return null; - /* (non-Javadoc) + } + } + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.capabilities.MimeTypeservice#getCapability(java.lang.String) */ public Capability getCapability(String capability) - { - try - { - - Criteria filter = new Criteria(); - filter.addEqualTo("name", capability); - QueryByCriteria query = QueryFactory.newQuery(getCapabilityClass(), filter); - return (Capability) getPersistenceBrokerTemplate().getObjectByQuery(query); - } - catch (Exception e) - { - String message = - "MimeTypeserviceImpl: getCapability - query for getCapabilityClass failed "; - log.error(message, e); - return null; - - } + { + try + { + + Criteria filter = new Criteria(); + filter.addEqualTo("name", capability); + QueryByCriteria query = QueryFactory.newQuery(getCapabilityClass(), + filter); + return (Capability) getPersistenceBrokerTemplate() + .getObjectByQuery(query); + } + catch (Exception e) + { + String message = "MimeTypeserviceImpl: getCapability - query for getCapabilityClass failed "; + log.error(message, e); + return null; + + } } - - /* + /* * (non-Javadoc) * * @see org.apache.jetspeed.capabilities.Capabilities#storeMediaType(MediaType) */ - public void storeMediaType(MediaType mediaType) throws CapabilitiesException + public void storeMediaType(MediaType mediaType) + throws CapabilitiesException { - //TODO: change exception to better indicate cause - getPersistenceBrokerTemplate().store(mediaType); + // TODO: change exception to better indicate cause + getPersistenceBrokerTemplate().store(mediaType); } /* @@ -803,21 +854,21 @@ public void deleteMediaType(MediaType mediaType) throws CapabilitiesException { - //TODO: change exception to better indicate cause + // TODO: change exception to better indicate cause getPersistenceBrokerTemplate().delete(mediaType); } - - /* + /* * (non-Javadoc) * * @see org.apache.jetspeed.capabilities.Capabilities#storeCapability(MediaType) */ - public void storeCapability(Capability capability) throws CapabilitiesException + public void storeCapability(Capability capability) + throws CapabilitiesException { - //TODO: change exception to better indicate cause - getPersistenceBrokerTemplate().store(capability); + // TODO: change exception to better indicate cause + getPersistenceBrokerTemplate().store(capability); } /* @@ -828,11 +879,11 @@ public void deleteCapability(Capability capability) throws CapabilitiesException { - //TODO: change exception to better indicate cause + // TODO: change exception to better indicate cause getPersistenceBrokerTemplate().delete(capability); } - /* + /* * (non-Javadoc) * * @see org.apache.jetspeed.capabilities.Capabilities#storeMimeType(MimeType) @@ -840,8 +891,8 @@ public void storeMimeType(MimeType mimeType) throws CapabilitiesException { - //TODO: change exception to better indicate cause - getPersistenceBrokerTemplate().store(mimeType); + // TODO: change exception to better indicate cause + getPersistenceBrokerTemplate().store(mimeType); } /* @@ -849,17 +900,13 @@ * * @see org.apache.jetspeed.capabilities.Capabilities#deleteMimeType(MimeType) */ - public void deleteMimeType(MimeType mimeType) - throws CapabilitiesException + public void deleteMimeType(MimeType mimeType) throws CapabilitiesException { - //TODO: change exception to better indicate cause + // TODO: change exception to better indicate cause getPersistenceBrokerTemplate().delete(mimeType); } - - - - /* + /* * (non-Javadoc) * * @see org.apache.jetspeed.capabilities.Capabilities#storeClient(MediaType) @@ -867,8 +914,8 @@ public void storeClient(Client client) throws CapabilitiesException { - //TODO: change exception to better indicate cause - getPersistenceBrokerTemplate().store(client); + // TODO: change exception to better indicate cause + getPersistenceBrokerTemplate().store(client); } /* @@ -876,11 +923,10 @@ * * @see org.apache.jetspeed.capabilities.Capabilities#deleteClient(Client) */ - public void deleteClient(Client client) - throws CapabilitiesException + public void deleteClient(Client client) throws CapabilitiesException { - //TODO: change exception to better indicate cause + // TODO: change exception to better indicate cause getPersistenceBrokerTemplate().delete(client); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/MediaTypeImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/MediaTypeImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/MediaTypeImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,147 +25,108 @@ import org.apache.jetspeed.capabilities.MimeType; /** - * Default bean like implementation of MediaTypeEntry interface - * suitable for serializing with Castor - * + * Default bean like implementation of MediaTypeEntry interface suitable for + * serializing with Castor + * * @author Rapha\u00ebl Luta * @version $Id: MediaTypeImpl.java 516448 2007-03-09 16:25:47Z ate $ */ -public class MediaTypeImpl - implements MediaType +public class MediaTypeImpl implements MediaType { + protected String characterSet; + private Collection capabilities; + private Collection mimetypes; + private int mediatypeId; + private String title; + private String description; - - private String name; // MediaTypeEntry name + private String name; // MediaTypeEntry name + public MediaTypeImpl() - {} + { + } - public MediaTypeImpl(long id, - String name, - int _hidden, - String mimeType, - String title, - String description, - String image, - String role) + public MediaTypeImpl(long id, String name, int _hidden, String mimeType, + String title, String description, String image, String role) { - this.mimetypes.add(mimeType); + this.mimetypes.add(mimeType); } /** - * Implements the equals operation so that 2 elements are equal if - * all their member values are equal. + * Implements the equals operation so that 2 elements are equal if all their + * member values are equal. */ public boolean equals(Object object) { - if (this == object) - return true; - if (object==null) - return false; - - MediaTypeImpl obj = (MediaTypeImpl)object; + if (this == object) return true; + if (object == null) return false; + MediaTypeImpl obj = (MediaTypeImpl) object; - if (this.name!=null) + if (this.name != null) { - if (!name.equals(obj.name)) - { - return false; - } + if (!name.equals(obj.name)) { return false; } } else { - if (obj.name!=null) - { - return false; - } + if (obj.name != null) { return false; } } - if (this.description!=null) + if (this.description != null) { - if (!description.equals(obj.description)) - { - return false; - } + if (!description.equals(obj.description)) { return false; } } else { - if (obj.description!=null) - { - return false; - } + if (obj.description != null) { return false; } } - if (characterSet!=null) + if (characterSet != null) { - if (!characterSet.equals(obj.characterSet)) - { - return false; - } + if (!characterSet.equals(obj.characterSet)) { return false; } } else { - if (obj.characterSet!=null) - { - return false; - } + if (obj.characterSet != null) { return false; } } - - if (this.title!=null) + if (this.title != null) { - if (!title.equals(obj.title)) - { - return false; - } + if (!title.equals(obj.title)) { return false; } } else { - if (obj.title!=null) - { - return false; - } + if (obj.title != null) { return false; } } - if (mimetypes != null) { - if (!CollectionUtils.isEqualCollection(mimetypes, obj.mimetypes)) - { - return false; - } + if (!CollectionUtils.isEqualCollection(mimetypes, obj.mimetypes)) { return false; } } else { - if (obj.mimetypes != null) - { - return false; - } + if (obj.mimetypes != null) { return false; } } - if (capabilities != null) + if (capabilities != null) { - if (!(CollectionUtils.isEqualCollection(capabilities,obj.capabilities ))) - return false; - } + if (!(CollectionUtils.isEqualCollection(capabilities, + obj.capabilities))) return false; + } else { - if (obj.capabilities != null) - { - return false; - } + if (obj.capabilities != null) { return false; } } return true; -} - - + } + /** @return the character set associated with this MediaType */ public String getCharacterSet() { @@ -173,12 +134,11 @@ } /** Sets the character set associated with this MediaType */ - public void setCharacterSet( String charSet) + public void setCharacterSet(String charSet) { this.characterSet = charSet; } - public Collection getCapabilities() { return this.capabilities; @@ -188,13 +148,12 @@ { this.capabilities = capabilities; } - - + public Collection getMimetypes() { return this.mimetypes; } - + public void setMimetypes(Collection mimetypes) { this.mimetypes = mimetypes; @@ -202,22 +161,19 @@ public void addMimetype(MimeType mimeType) { - if (mimetypes == null) - mimetypes = new ArrayList(); + if (mimetypes == null) mimetypes = new ArrayList(); if (!mimetypes.contains(mimeType.getName())) { mimetypes.add(mimeType); } } - public void addCapability(Capability capability) { - if (capabilities == null) - capabilities = new ArrayList(); + if (capabilities == null) capabilities = new ArrayList(); if (!capabilities.contains(capability.getName())) { - capabilities.add(capability); + capabilities.add(capability); } } @@ -225,9 +181,10 @@ { mimetypes.remove(name); } - + /** * Set MediaType ID -- Assigns ID + * * @param id */ public void setMediatypeId(int id) @@ -237,46 +194,46 @@ /** * Get MediaType ID -- Return ID + * * @return MediaTypeID */ public int getMediatypeId() { return this.mediatypeId; } - + /** - * Set name ob MediaTypeEntry - */ - public void setName(String name) - { - this.name = name; - } - - /** - * Get name ob MediaTypeEntry - */ - - public String getName() - { - return this.name; - } - - public String getTitle() - { - return this.title; - } + * Set name ob MediaTypeEntry + */ + public void setName(String name) + { + this.name = name; + } - public void setTitle(String title) - { - this.title = title; - } - - public String getDescription() - { - return this.description; - } + /** + * Get name ob MediaTypeEntry + */ + public String getName() + { + return this.name; + } + public String getTitle() + { + return this.title; + } + + public void setTitle(String title) + { + this.title = title; + } + + public String getDescription() + { + return this.description; + } + public void setDescription(String desc) { this.description = desc; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/MimeTypeImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/MimeTypeImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/java/org/apache/jetspeed/capabilities/impl/MimeTypeImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,17 +21,21 @@ /** * Mimetype implementation class. - * + * * @author Roger Ruttimann * @version $Id: MimeTypeImpl.java 517719 2007-03-13 15:05:48Z ate $ */ public class MimeTypeImpl implements MimeType { + private int mimeTypeId; + private String name; - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.registry.MimeType#setMimetypeId(int) */ public void setMimetypeId(int id) @@ -39,7 +43,9 @@ this.mimeTypeId = id; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.registry.MimeType#getMimetypeId() */ public int getMimetypeId() @@ -47,7 +53,9 @@ return this.mimeTypeId; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.registry.MimeType#setName(java.lang.String) */ public void setName(String name) @@ -55,7 +63,9 @@ this.name = name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.registry.MimeType#getName() */ public String getName() @@ -64,42 +74,36 @@ } /** - * Implements the hashCode calculation so two different objects with the content return the same hashcode.... + * Implements the hashCode calculation so two different objects with the + * content return the same hashcode.... */ public int hashCode() { - return name.hashCode(); + return name.hashCode(); } + /** - * Implements the equals operation so that 2 elements are equal if - * all their member values are equal. - * - * - * @param object to compare this one with + * Implements the equals operation so that 2 elements are equal if all their + * member values are equal. + * + * + * @param object + * to compare this one with * @return true if both objects represent the same (logical) content */ public boolean equals(Object object) { - if (!(object instanceof MimeType)) - { - return false; - } - if (this == object) - return true; -// Don't check the ID - id is only set through OJB so this would not recognize equality correctly -/* if (mimeTypeId != ((MimeType)object).getMimetypeId()) - return false; -*/ - String oName = ((MimeType)object).getName(); - if ( - (oName == null) && (name == null) - || - (oName == name) - || - ((oName != null) && (oName.equals(name))) - ) - return true; - return false; + if (!(object instanceof MimeType)) { return false; } + if (this == object) return true; + // Don't check the ID - id is only set through OJB so this would not + // recognize equality correctly + /* + * if (mimeTypeId != ((MimeType)object).getMimetypeId()) return false; + */ + String oName = ((MimeType) object).getName(); + if ((oName == null) && (name == null) || (oName == name) + || ((oName != null) && (oName.equals(name)))) return true; + return false; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/test/org/apache/jetspeed/capabilities/TestCapability.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/test/org/apache/jetspeed/capabilities/TestCapability.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/capability/src/test/org/apache/jetspeed/capabilities/TestCapability.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,7 +27,6 @@ import org.apache.jetspeed.components.util.DatasourceEnabledSpringTestCase; - /** * Test Capability Service * @@ -36,6 +35,7 @@ */ public class TestCapability extends DatasourceEnabledSpringTestCase { + private Capabilities capabilities = null; /** @@ -47,7 +47,7 @@ public static void main(String args[]) { junit.awtui.TestRunner.main(new String[] - { TestCapability.class.getName() }); + {TestCapability.class.getName()}); } protected void setUp() throws Exception @@ -137,7 +137,8 @@ System.out.println("Find pattern: " + userAgent); cm = capabilities.getCapabilityMap(userAgent); assertNotNull("getCapabilityMap is null", cm); - assertTrue("IE for Mac " + cm.getClient().getName(), cm.getClient().getName().equals("ie5mac")); + assertTrue("IE for Mac " + cm.getClient().getName(), cm.getClient() + .getName().equals("ie5mac")); capabilityMapReport(cm); userAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)"; @@ -152,8 +153,8 @@ cm = capabilities.getCapabilityMap(userAgent); assertNotNull("getCapabilityMap is null", cm); assertTrue("Ericsson", cm.getClient().getName().equals("sonyericsson")); - capabilityMapReport(cm); - + capabilityMapReport(cm); + } private void capabilityMapReport(CapabilityMap cm) @@ -189,336 +190,333 @@ private HashMap getCapabilities(int howMany) { - Capability capability = null; - Iterator _it = capabilities.getCapabilities(); - HashMap _hash = new HashMap(); - int count = 0; - while (_it.hasNext()) - { - capability = (Capability)_it.next(); - _hash.put(capability.getName(), capability); - count++; - if (howMany > 0) - if (count >= howMany) - return _hash; - } - return _hash; + Capability capability = null; + Iterator _it = capabilities.getCapabilities(); + HashMap _hash = new HashMap(); + int count = 0; + while (_it.hasNext()) + { + capability = (Capability) _it.next(); + _hash.put(capability.getName(), capability); + count++; + if (howMany > 0) if (count >= howMany) return _hash; + } + return _hash; } - + private HashMap getMimeTypes(int howMany) { - MimeType mimeType = null; - Iterator _it = capabilities.getMimeTypes(); - HashMap _hash = new HashMap(); - int count = 0; - while (_it.hasNext()) - { - mimeType = (MimeType)_it.next(); - _hash.put(mimeType.getName(), mimeType); - count++; - if (howMany > 0) - if (count >= howMany) - return _hash; - } - return _hash; + MimeType mimeType = null; + Iterator _it = capabilities.getMimeTypes(); + HashMap _hash = new HashMap(); + int count = 0; + while (_it.hasNext()) + { + mimeType = (MimeType) _it.next(); + _hash.put(mimeType.getName(), mimeType); + count++; + if (howMany > 0) if (count >= howMany) return _hash; + } + return _hash; } - + public void testNewMimeType() throws Exception { - MimeType mimeType = null; - Iterator _it = null; - HashMap _hash = getMimeTypes(0); - int count = _hash.size(); + MimeType mimeType = null; + Iterator _it = null; + HashMap _hash = getMimeTypes(0); + int count = _hash.size(); assertTrue("MimeTypes do not exist", (count > 0)); - _it = _hash.keySet().iterator(); - - int pos = count/2; - - for (int i = 0; i < pos; i++) - _it.next(); - - String existingKey = (String)_it.next(); - MimeType existingObject = (MimeType)_hash.get(existingKey); - assertNotNull("Couldn't identify existing mime object to run test",existingObject); + _it = _hash.keySet().iterator(); - - // "create" existing one + int pos = count / 2; + + for (int i = 0; i < pos; i++) + _it.next(); + + String existingKey = (String) _it.next(); + MimeType existingObject = (MimeType) _hash.get(existingKey); + assertNotNull("Couldn't identify existing mime object to run test", + existingObject); + + // "create" existing one mimeType = capabilities.createMimeType(existingKey); assertNotNull("creating 'existing' mimetype returns null", mimeType); - assertTrue("creating 'existing' mimetype didn't return existing object", (mimeType.equals(existingObject))); - + assertTrue( + "creating 'existing' mimetype didn't return existing object", + (mimeType.equals(existingObject))); + // create a new one: mimeType = capabilities.createMimeType("TEST MIME TYPE"); assertNotNull("creating new mimetype returns null", mimeType); - + // ensure it doesn't exist in the capabilities Set existing = _hash.entrySet(); - assertTrue("creating new mimetype already in existing list", (!(existing.contains(mimeType)))); - - existingObject = capabilities.getMimeType("TEST MIME TYPE"); - assertNull("creating new mimetype already in existing capabilities",existingObject); - + assertTrue("creating new mimetype already in existing list", + (!(existing.contains(mimeType)))); + + existingObject = capabilities.getMimeType("TEST MIME TYPE"); + assertNull("creating new mimetype already in existing capabilities", + existingObject); + capabilities.storeMimeType(mimeType); - existingObject = capabilities.getMimeType("TEST MIME TYPE"); - assertNotNull("creating and saving new mimetype didn't store object",existingObject); - - + existingObject = capabilities.getMimeType("TEST MIME TYPE"); + assertNotNull("creating and saving new mimetype didn't store object", + existingObject); + capabilities.deleteMimeType(mimeType); - existingObject = capabilities.getMimeType("TEST MIME TYPE"); - assertNull("creating new mimetype delete from storage didn't work",existingObject); - + existingObject = capabilities.getMimeType("TEST MIME TYPE"); + assertNull("creating new mimetype delete from storage didn't work", + existingObject); + } - - - - public void testNewCapability() throws Exception { - Capability capability = null; - Iterator _it = null; - HashMap _hash = getCapabilities(0); - int count = _hash.size(); + Capability capability = null; + Iterator _it = null; + HashMap _hash = getCapabilities(0); + int count = _hash.size(); assertTrue("Capabilitys do not exist", (count > 0)); - _it = _hash.keySet().iterator(); - - int pos = count/2; - - for (int i = 0; i < pos; i++) - _it.next(); - - String existingKey = (String)_it.next(); - Capability existingObject = (Capability)_hash.get(existingKey); - assertNotNull("Couldn't identify existing mime object to run test",existingObject); + _it = _hash.keySet().iterator(); - - // "create" existing one + int pos = count / 2; + + for (int i = 0; i < pos; i++) + _it.next(); + + String existingKey = (String) _it.next(); + Capability existingObject = (Capability) _hash.get(existingKey); + assertNotNull("Couldn't identify existing mime object to run test", + existingObject); + + // "create" existing one capability = capabilities.createCapability(existingKey); assertNotNull("creating 'existing' capability returns null", capability); - assertTrue("creating 'existing' capability didn't return existing object", (capability.equals(existingObject))); - + assertTrue( + "creating 'existing' capability didn't return existing object", + (capability.equals(existingObject))); + // create a new one: capability = capabilities.createCapability("TEST CAPABILITY TYPE"); assertNotNull("creating new capability returns null", capability); - + // ensure it doesn't exist in the capabilities Set existing = _hash.entrySet(); - assertTrue("creating new capability already in existing list", (!(existing.contains(capability)))); - - existingObject = capabilities.getCapability("TEST CAPABILITY TYPE"); - assertNull("creating new capability already in existing capabilities",existingObject); - + assertTrue("creating new capability already in existing list", + (!(existing.contains(capability)))); + + existingObject = capabilities.getCapability("TEST CAPABILITY TYPE"); + assertNull("creating new capability already in existing capabilities", + existingObject); + capabilities.storeCapability(capability); - existingObject = capabilities.getCapability("TEST CAPABILITY TYPE"); - assertNotNull("creating and saving new capability didn't store object",existingObject); - - + existingObject = capabilities.getCapability("TEST CAPABILITY TYPE"); + assertNotNull("creating and saving new capability didn't store object", + existingObject); + capabilities.deleteCapability(capability); - existingObject = capabilities.getCapability("TEST CAPABILITY TYPE"); - assertNull("creating new capability delete from storage didn't work",existingObject); - + existingObject = capabilities.getCapability("TEST CAPABILITY TYPE"); + assertNull("creating new capability delete from storage didn't work", + existingObject); + } - - public void testNewMediaType() throws Exception { - MediaType mediaType = null; - Iterator _it = capabilities.getMediaTypes(); - HashMap _hash = new HashMap(); - int count = 0; - while (_it.hasNext()) - { - mediaType = (MediaType)_it.next(); - _hash.put(mediaType.getName(), mediaType); - count++; - } + MediaType mediaType = null; + Iterator _it = capabilities.getMediaTypes(); + HashMap _hash = new HashMap(); + int count = 0; + while (_it.hasNext()) + { + mediaType = (MediaType) _it.next(); + _hash.put(mediaType.getName(), mediaType); + count++; + } assertTrue("Mediatypes do not exist", (count > 0)); - _it = _hash.keySet().iterator(); - - int pos = count/2; - - for (int i = 0; i < pos; i++) - _it.next(); - - String existingKey = (String)_it.next(); - MediaType existingObject = (MediaType)_hash.get(existingKey); - assertNotNull("Couldn't identify existing object to run test",existingObject); + _it = _hash.keySet().iterator(); - - // "create" existing one - mediaType = capabilities.createMediaType(existingKey); + int pos = count / 2; + + for (int i = 0; i < pos; i++) + _it.next(); + + String existingKey = (String) _it.next(); + MediaType existingObject = (MediaType) _hash.get(existingKey); + assertNotNull("Couldn't identify existing object to run test", + existingObject); + + // "create" existing one + mediaType = capabilities.createMediaType(existingKey); assertNotNull("creating 'existing' mediatype returns null", mediaType); - assertTrue("creating 'existing' mediatype didn't return existing object", (mediaType.equals(existingObject))); + assertTrue( + "creating 'existing' mediatype didn't return existing object", + (mediaType.equals(existingObject))); - // setting fields String name = "TEST MEDIA TYPE"; String utf = "UTF-8"; String title = "TEST MEDIA TYPE - Title"; String description = "TEST MEDIA TYPE - Description"; - + int numCapabilities = 2; int numMimeTypes = 3; - - HashMap someCapabilities = getCapabilities(numCapabilities); - HashMap someMimeTypes = getMimeTypes(numMimeTypes); - - - + + HashMap someCapabilities = getCapabilities(numCapabilities); + HashMap someMimeTypes = getMimeTypes(numMimeTypes); + // create a new one: mediaType = capabilities.createMediaType(name); assertNotNull("creating new mediatype returns null", mediaType); - + // ensure it doesn't exist in the capabilities Set existing = _hash.entrySet(); - assertTrue("creating new mediaType already in existing list", (!(existing.contains(mediaType)))); - - existingObject = capabilities.getMediaType(name); - assertNull("creating new mediaType already in existing capabilities",existingObject); - - -// set object fields + assertTrue("creating new mediaType already in existing list", + (!(existing.contains(mediaType)))); + + existingObject = capabilities.getMediaType(name); + assertNull("creating new mediaType already in existing capabilities", + existingObject); + + // set object fields mediaType.setCharacterSet(utf); mediaType.setTitle(title); mediaType.setDescription(description); - + _it = someMimeTypes.values().iterator(); int added = 0; while (_it.hasNext()) { - mediaType.addMimetype((MimeType)_it.next()); - added++; + mediaType.addMimetype((MimeType) _it.next()); + added++; } - assertTrue("number of Mimetypes added (" + added + ") not the same as expected ("+numMimeTypes+")",(added==numMimeTypes)); - + assertTrue("number of Mimetypes added (" + added + + ") not the same as expected (" + numMimeTypes + ")", + (added == numMimeTypes)); + // setting links: - - + ArrayList set = new ArrayList(someCapabilities.values()); mediaType.setCapabilities(set); - assertTrue("number of Capabilities added (" + set.size() + ") not the same as expected ("+numCapabilities+")",(set.size()==numCapabilities)); - + assertTrue("number of Capabilities added (" + set.size() + + ") not the same as expected (" + numCapabilities + ")", (set + .size() == numCapabilities)); + capabilities.storeMediaType(mediaType); - existingObject = capabilities.getMediaType(name); - assertNotNull("creating and saving new mediaType didn't store object",existingObject); - + existingObject = capabilities.getMediaType(name); + assertNotNull("creating and saving new mediaType didn't store object", + existingObject); + capabilities.deleteMediaType(mediaType); - existingObject = capabilities.getMediaType(name); - assertNull("creating new mediaType delete from storage didn't work",existingObject); - - - - - + existingObject = capabilities.getMediaType(name); + assertNull("creating new mediaType delete from storage didn't work", + existingObject); + } - - public void testNewClient() throws Exception { - Client client = null; - Iterator _it = capabilities.getClients(); - HashMap _hash = new HashMap(); - int count = 0; - while (_it.hasNext()) - { - client = (Client)_it.next(); - _hash.put(client.getName(), client); - count++; - } + Client client = null; + Iterator _it = capabilities.getClients(); + HashMap _hash = new HashMap(); + int count = 0; + while (_it.hasNext()) + { + client = (Client) _it.next(); + _hash.put(client.getName(), client); + count++; + } assertTrue("Clients do not exist", (count > 0)); - _it = _hash.keySet().iterator(); - - int pos = count/2; - - for (int i = 0; i < pos; i++) - _it.next(); - - String existingKey = (String)_it.next(); - Client existingObject = (Client)_hash.get(existingKey); - assertNotNull("Couldn't identify existing object to run test",existingObject); + _it = _hash.keySet().iterator(); - - // "create" existing one - client = capabilities.createClient(existingKey); + int pos = count / 2; + + for (int i = 0; i < pos; i++) + _it.next(); + + String existingKey = (String) _it.next(); + Client existingObject = (Client) _hash.get(existingKey); + assertNotNull("Couldn't identify existing object to run test", + existingObject); + + // "create" existing one + client = capabilities.createClient(existingKey); assertNotNull("creating 'existing' client returns null", client); - assertTrue("creating 'existing' client didn't return existing object", (client.equals(existingObject))); + assertTrue("creating 'existing' client didn't return existing object", + (client.equals(existingObject))); - // setting fields - - String name = "TEST CLIENT"; + + String name = "TEST CLIENT"; int numCapabilities = 3; int numMimeTypes = 4; - - HashMap someCapabilities = getCapabilities(numCapabilities); - HashMap someMimeTypes = getMimeTypes(numMimeTypes); + HashMap someCapabilities = getCapabilities(numCapabilities); + HashMap someMimeTypes = getMimeTypes(numMimeTypes); + // create a new one: client = capabilities.createClient(name); assertNotNull("creating new client returns null", client); - + // ensure it doesn't exist in the capabilities Set existing = _hash.entrySet(); - assertTrue("creating new client already in existing list", (!(existing.contains(client)))); - - existingObject = capabilities.getClient(name); - assertNull("creating new client already in existing capabilities",existingObject); - + assertTrue("creating new client already in existing list", (!(existing + .contains(client)))); + + existingObject = capabilities.getClient(name); + assertNull("creating new client already in existing capabilities", + existingObject); + String userAgentPattern = "TEST.*|TESTBROWSER.*"; String manufacturer = "Test Manufacturer"; String model = "XYZ"; - -// set object fields + + // set object fields client.setUserAgentPattern(userAgentPattern); client.setManufacturer(manufacturer); client.setModel(model); ArrayList set = new ArrayList(someCapabilities.values()); client.setCapabilities(set); - assertTrue("number of Capabilities added (" + set.size() + ") not the same as expected ("+numCapabilities+")",(set.size()==numCapabilities)); - + assertTrue("number of Capabilities added (" + set.size() + + ") not the same as expected (" + numCapabilities + ")", (set + .size() == numCapabilities)); + set = new ArrayList(someMimeTypes.values()); client.setCapabilities(set); - assertTrue("number of MimeTypes added (" + set.size() + ") not the same as expected ("+numCapabilities+")",(set.size()==numMimeTypes)); + assertTrue("number of MimeTypes added (" + set.size() + + ") not the same as expected (" + numCapabilities + ")", (set + .size() == numMimeTypes)); - // setting links: - - - + capabilities.storeClient(client); - existingObject = capabilities.getClient(name); - assertNotNull("creating and saving new client didn't store object",existingObject); - + existingObject = capabilities.getClient(name); + assertNotNull("creating and saving new client didn't store object", + existingObject); + capabilities.deleteClient(client); - existingObject = capabilities.getClient(name); - assertNull("creating new client delete from storage didn't work",existingObject); - - - - - + existingObject = capabilities.getClient(name); + assertNull("creating new client delete from storage didn't work", + existingObject); + } - - public void testCapabilityRepeat() throws Exception { - capabilities.deleteCapabilityMapCache(); + capabilities.deleteCapabilityMapCache(); testCapability(); } - protected String[] getConfigurations() { return new String[] - { "capabilities.xml", "transaction.xml" }; + {"capabilities.xml", "transaction.xml"}; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/general/SimpleHashMapCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/general/SimpleHashMapCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/general/SimpleHashMapCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,15 +23,16 @@ * SimpleHashMapCache *

      *

      - * + * *

      + * * @author Scott T. Weaver * @version $Id: SimpleHashMapCache.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class SimpleHashMapCache implements GeneralCache { - + protected HashMap cache; /** @@ -40,35 +41,36 @@ public SimpleHashMapCache() { super(); - cache = new HashMap(); + cache = new HashMap(); } /** *

      * get *

      - * + * * @see org.apache.jetspeed.cache.general.GeneralCache#get(java.lang.String) * @param key * @return */ - public Object get( String key ) + public Object get(String key) { - return cache.get(key); + return cache.get(key); } /** *

      * put *

      - * - * @see org.apache.jetspeed.cache.general.GeneralCache#put(java.lang.String, java.lang.Object) + * + * @see org.apache.jetspeed.cache.general.GeneralCache#put(java.lang.String, + * java.lang.Object) * @param key * @param value */ - public void put( String key, Object value ) + public void put(String key, Object value) { - cache.put(key, value); + cache.put(key, value); } @@ -76,12 +78,12 @@ *

      * contains *

      - * + * * @see org.apache.jetspeed.cache.general.GeneralCache#contains(java.lang.String) * @param key * @return */ - public boolean contains( String key ) + public boolean contains(String key) { return cache.containsKey(key); } @@ -90,13 +92,13 @@ *

      * remove *

      - * + * * @see org.apache.jetspeed.cache.general.GeneralCache#remove(java.lang.String) * @param key */ - public Object remove( String key ) + public Object remove(String key) { - return cache.remove(key); + return cache.remove(key); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheDistributedElementImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheDistributedElementImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheDistributedElementImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,24 +22,24 @@ import org.apache.jetspeed.cache.DistributedCacheObject; +public class EhCacheDistributedElementImpl extends EhCacheElementImpl +{ -public class EhCacheDistributedElementImpl extends EhCacheElementImpl -{ - public EhCacheDistributedElementImpl(Element element) + public EhCacheDistributedElementImpl(Element element) { super(element); } - public EhCacheDistributedElementImpl(Serializable key, DistributedCacheObject value) + public EhCacheDistributedElementImpl(Serializable key, + DistributedCacheObject value) { - super(key, value); - + super(key, value); + } - + public void notifyChange(int action) { - ((DistributedCacheObject)getContent()).notifyChange(action); + ((DistributedCacheObject) getContent()).notifyChange(action); } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheDistributedImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheDistributedImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheDistributedImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,203 +33,206 @@ import org.apache.jetspeed.cache.JetspeedCache; import org.apache.jetspeed.request.RequestContext; -public class EhCacheDistributedImpl extends EhCacheImpl implements JetspeedCache, CacheEventListener +public class EhCacheDistributedImpl extends EhCacheImpl implements + JetspeedCache, CacheEventListener { + private Map refList = Collections.synchronizedMap(new HashMap()); - private Map refList = Collections.synchronizedMap(new HashMap()); + public EhCacheDistributedImpl(Ehcache ehcache) + { + super(ehcache); + RegisteredEventListeners listeners = ehcache + .getCacheEventNotificationService(); + listeners.registerListener(this); + } - public EhCacheDistributedImpl(Ehcache ehcache) - { - super(ehcache); - RegisteredEventListeners listeners = ehcache - .getCacheEventNotificationService(); - listeners.registerListener(this); + public CacheElement get(Object key) + { + return get((Serializable) key); + } - } + public CacheElement get(Serializable key) + { + Element element = ehcache.get(key); + if (element == null) return null; + return new EhCacheDistributedElementImpl(element); + } - public CacheElement get(Object key) - { - return get((Serializable)key); - } + public boolean isKeyInCache(Object key) + { + if ((key == null) || (!(key instanceof Serializable))) return false; + return ehcache.isKeyInCache(key); + } + public boolean isKeyInCache(Serializable key) + { + return ehcache.isKeyInCache(key); + } - public CacheElement get(Serializable key) - { - Element element = ehcache.get(key); - if (element == null) - return null; - return new EhCacheDistributedElementImpl(element); - } + public void put(CacheElement element) + { + EhCacheDistributedElementImpl impl = (EhCacheDistributedElementImpl) element; + ehcache.put(impl.getImplElement()); + refList.put(impl.getKey(), impl); + notifyListeners(true, CacheElement.ActionAdded, impl.getKey(), impl + .getContent()); + } + public CacheElement createElement(Object key, Object content) + { + return new EhCacheDistributedElementImpl((Serializable) key, + (DistributedCacheObject) content); + } - public boolean isKeyInCache(Object key) - { - if ((key == null) || (!(key instanceof Serializable))) - return false; - return ehcache.isKeyInCache(key); - } + public CacheElement createElement(Serializable key, + DistributedCacheObject content) + { + return new EhCacheDistributedElementImpl(key, content); + } - public boolean isKeyInCache(Serializable key) - { - return ehcache.isKeyInCache(key); - } + public boolean remove(Object key) + { + return remove((Serializable) key); + } - public void put(CacheElement element) - { - EhCacheDistributedElementImpl impl = (EhCacheDistributedElementImpl) element; - ehcache.put(impl.getImplElement()); - refList.put(impl.getKey(), impl); - notifyListeners(true, CacheElement.ActionAdded,impl.getKey(),impl.getContent()); - } + public boolean remove(Serializable key) + { + Element element = ehcache.get(key); + refList.remove(key); + if (element == null) return false; + boolean isRemoved = ehcache.remove(key); + if (isRemoved) + notifyListeners(true, CacheElement.ActionRemoved, key, null); + return isRemoved; + } - public CacheElement createElement(Object key, Object content) - { - return new EhCacheDistributedElementImpl((Serializable)key, (DistributedCacheObject)content); - } + public boolean removeQuiet(Object key) + { + Element element = ehcache.get(key); + refList.remove(key); + if (element == null) return false; + return ehcache.removeQuiet(key); - public CacheElement createElement(Serializable key, DistributedCacheObject content) - { - return new EhCacheDistributedElementImpl(key, content); - } + } + public void evictContentForUser(RequestContext context) + { + return; + } - public boolean remove(Object key) - { - return remove ((Serializable) key); - } + public String createCacheKey(String primary, String secondary) + { + return primary; + } - public boolean remove(Serializable key) - { - Element element = ehcache.get(key); - refList.remove(key); - if (element == null) - return false; - boolean isRemoved = ehcache.remove(key); - if (isRemoved) - notifyListeners(true, CacheElement.ActionRemoved,key,null); - return isRemoved; - } + public Object clone() throws CloneNotSupportedException + { + return null; + } - public boolean removeQuiet(Object key) - { - Element element = ehcache.get(key); - refList.remove(key); - if (element == null) - return false; - return ehcache.removeQuiet(key); + public void dispose() + { + if (refList != null) + { + Map temp = refList; + refList = null; + temp.clear(); + } + else + return; + if (this.ehcache != null) + { + ehcache = null; + } + } - } + public void notifyElement(Ehcache cache, boolean local, Element arg1, + int action) + { + if (cache != this.ehcache) + { + System.out.println("Cache=" + cache.getName() + " is not my cache=" + + this.ehcache.getName()); + return; + } + try + { + EhCacheDistributedElementImpl e = (EhCacheDistributedElementImpl) refList + .get(arg1.getKey()); + if (e != null) + { + if (action < 0) + refList.remove(arg1.getKey()); + else if (action == CacheElement.ActionAdded) + refList.put(arg1.getKey(), arg1); + e.notifyChange(action); + notifyListeners(local, action, arg1.getKey(), arg1 + .getObjectValue()); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } - public void evictContentForUser(RequestContext context) - { - return; - } + public void notifyElementEvicted(Ehcache cache, Element arg1) + { + notifyElement(cache, false, arg1, CacheElement.ActionEvicted); + } - public String createCacheKey(String primary, String secondary) - { - return primary; - } - - public Object clone() throws CloneNotSupportedException - { - return null; - } - - public void dispose() + public void notifyElementExpired(Ehcache cache, Element arg1) { - if (refList != null) - { - Map temp = refList; - refList = null; - temp.clear(); - } - else - return; - if (this.ehcache != null) - { - ehcache = null; - } + notifyElement(cache, false, arg1, CacheElement.ActionExpired); } - - public void notifyElement( Ehcache cache, boolean local,Element arg1, int action) - { - if (cache != this.ehcache) - { - System.out.println ("Cache=" + cache.getName() + " is not my cache=" + this.ehcache.getName()); - return; - } - try - { - EhCacheDistributedElementImpl e = (EhCacheDistributedElementImpl) refList - .get(arg1.getKey()); - if (e != null) - { - if (action < 0) - refList.remove(arg1.getKey()); - else if (action == CacheElement.ActionAdded) - refList.put(arg1.getKey(), arg1); - e.notifyChange(action); - notifyListeners(local, action,arg1.getKey(),arg1.getObjectValue()); - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - public void notifyElementEvicted(Ehcache cache, Element arg1) - { - notifyElement(cache, false, arg1,CacheElement.ActionEvicted); - } + public void notifyElementPut(Ehcache cache, Element arg1) + throws CacheException + { - public void notifyElementExpired(Ehcache cache, Element arg1) - { - notifyElement(cache, false, arg1,CacheElement.ActionExpired); - } + notifyElement(cache, false, arg1, CacheElement.ActionAdded); + } - public void notifyElementPut(Ehcache cache, Element arg1) - throws CacheException - { - - notifyElement(cache, false, arg1, CacheElement.ActionAdded); - } + public void notifyElementRemoved(Ehcache cache, Element arg1) + throws CacheException + { + notifyElement(cache, false, arg1, CacheElement.ActionRemoved); + } - public void notifyElementRemoved(Ehcache cache, Element arg1) - throws CacheException - { - notifyElement(cache, false, arg1,CacheElement.ActionRemoved); - } + public void notifyElementUpdated(Ehcache cache, Element arg1) + throws CacheException + { + notifyElement(cache, false, arg1, CacheElement.ActionChanged); + } - public void notifyElementUpdated(Ehcache cache, Element arg1) - throws CacheException - { - notifyElement(cache, false,arg1,CacheElement.ActionChanged); - } - public void notifyRemoveAll(Ehcache cache) - { - if (cache != this.ehcache) - { - System.out.println ("Cache=" + cache.getName() + " is not my cache=" + this.ehcache.getName()); - return; - } - try - { - Iterator it = refList.entrySet().iterator(); - while (it.hasNext()) - { - EhCacheDistributedElementImpl e = (EhCacheDistributedElementImpl)it.next(); - notifyListeners(false, CacheElement.ActionRemoved,e.getKey(),e); - e.notifyChange(CacheElement.ActionRemoved); - } - refList.clear(); - } catch (Exception e) - { - e.printStackTrace(); - } + public void notifyRemoveAll(Ehcache cache) + { + if (cache != this.ehcache) + { + System.out.println("Cache=" + cache.getName() + " is not my cache=" + + this.ehcache.getName()); + return; + } + try + { + Iterator it = refList.entrySet().iterator(); + while (it.hasNext()) + { + EhCacheDistributedElementImpl e = (EhCacheDistributedElementImpl) it + .next(); + notifyListeners(false, CacheElement.ActionRemoved, e.getKey(), + e); + e.notifyChange(CacheElement.ActionRemoved); + } + refList.clear(); + } + catch (Exception e) + { + e.printStackTrace(); + } - - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheElementImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheElementImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheElementImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,66 +24,66 @@ public class EhCacheElementImpl implements CacheElement { - Element element; - - public EhCacheElementImpl(Element element) + + Element element; + + public EhCacheElementImpl(Element element) { this.element = element; } - public EhCacheElementImpl(Serializable key, Serializable value) + public EhCacheElementImpl(Serializable key, Serializable value) { - this.element = new Element(key,value); + this.element = new Element(key, value); } public EhCacheElementImpl(Serializable key, Object value) { - this.element = new Element(key,value); + this.element = new Element(key, value); } - public Object getKey() - { - return element.getObjectKey(); - } - - - public Object getContent() - { - return element.getObjectValue(); - } + public Object getKey() + { + return element.getObjectKey(); + } - public int getTimeToIdleSeconds() - { - return element.getTimeToIdle(); - } + public Object getContent() + { + return element.getObjectValue(); + } - public int getTimeToLiveSeconds() - { - return element.getTimeToLive(); - } + public int getTimeToIdleSeconds() + { + return element.getTimeToIdle(); + } - public boolean isEternal() - { - return element.isEternal(); - } + public int getTimeToLiveSeconds() + { + return element.getTimeToLive(); + } - public Element getImplElement() - { - return element; - } + public boolean isEternal() + { + return element.isEternal(); + } - public void setEternal(boolean eternal) - { - element.setEternal(eternal); - } + public Element getImplElement() + { + return element; + } - public void setTimeToIdleSeconds(int timeToIdle) - { - element.setTimeToIdle(timeToIdle); - } + public void setEternal(boolean eternal) + { + element.setEternal(eternal); + } - public void setTimeToLiveSeconds(int timeToLive) - { - element.setTimeToLive(timeToLive); - } + public void setTimeToIdleSeconds(int timeToIdle) + { + element.setTimeToIdle(timeToIdle); + } + + public void setTimeToLiveSeconds(int timeToLive) + { + element.setTimeToLive(timeToLive); + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheEventListener.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheEventListener.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheEventListener.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,53 +24,57 @@ public class EhCacheEventListener implements CacheEventListener { - public Object clone() throws CloneNotSupportedException - { - return null; - } + public Object clone() throws CloneNotSupportedException + { + return null; + } + public void dispose() + { + // TODO Auto-generated method stub - public void dispose() - { - // TODO Auto-generated method stub + } - } + public void notifyElementEvicted(Ehcache cache, Element arg1) + { + // System.out.println("notifyElementEvicted cache=" + cache.getName() + + // " - element = " + arg1.getObjectKey().toString()); - public void notifyElementEvicted(Ehcache cache, Element arg1) - { -// System.out.println("notifyElementEvicted cache=" + cache.getName() + " - element = " + arg1.getObjectKey().toString()); + } - } + public void notifyElementExpired(Ehcache cache, Element arg1) + { + // System.out.println("notifyElementExpired cache=" + cache.getName() + + // " - element = " + arg1.getObjectKey().toString()); - public void notifyElementExpired(Ehcache cache, Element arg1) - { -// System.out.println("notifyElementExpired cache=" + cache.getName() + " - element = " + arg1.getObjectKey().toString()); + } - } + public void notifyElementPut(Ehcache cache, Element arg1) + throws CacheException + { + // System.out.println("notifyElementPut cache=" + cache.getName() + " - + // element = " + arg1.getObjectKey().toString()); - public void notifyElementPut(Ehcache cache, Element arg1) - throws CacheException - { -// System.out.println("notifyElementPut cache=" + cache.getName() + " - element = " + arg1.getObjectKey().toString()); + } - } + public void notifyElementRemoved(Ehcache cache, Element arg1) + throws CacheException + { + // System.out.println("notifyElementRemoved cache=" + cache.getName() + + // " - element = " + arg1.getObjectKey().toString()); - public void notifyElementRemoved(Ehcache cache, Element arg1) - throws CacheException - { -// System.out.println("notifyElementRemoved cache=" + cache.getName() + " - element = " + arg1.getObjectKey().toString()); + } - } + public void notifyElementUpdated(Ehcache cache, Element arg1) + throws CacheException + { + // System.out.println("notifyElementUpdated cache=" + cache.getName() + + // " - element = " + arg1.getObjectKey().toString()); + } - public void notifyElementUpdated(Ehcache cache, Element arg1) - throws CacheException - { -// System.out.println("notifyElementUpdated cache=" + cache.getName() + " - element = " + arg1.getObjectKey().toString()); - } + public void notifyRemoveAll(Ehcache cache) + { + // System.out.println("notifyRemoveAll cache=" + cache.getName() ); + } - public void notifyRemoveAll(Ehcache cache) - { -// System.out.println("notifyRemoveAll cache=" + cache.getName() ); - } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheEventListenerFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheEventListenerFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheEventListenerFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,14 +24,14 @@ public class EhCacheEventListenerFactory extends CacheEventListenerFactory { - public EhCacheEventListenerFactory() - { - // TODO Auto-generated constructor stub - } + public EhCacheEventListenerFactory() + { + // TODO Auto-generated constructor stub + } - public CacheEventListener createCacheEventListener(Properties arg0) - { - return new EhCacheEventListener(); - } + public CacheEventListener createCacheEventListener(Properties arg0) + { + return new EhCacheEventListener(); + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhCacheImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,31 +31,33 @@ public class EhCacheImpl implements JetspeedCache { + protected Ehcache ehcache; + protected List localListeners = new ArrayList(); + protected List remoteListeners = new ArrayList(); - + public EhCacheImpl(Ehcache ehcache) { this.ehcache = ehcache; - } + } public CacheElement get(Object key) { Element element = ehcache.get(key); - if (element == null) - return null; + if (element == null) return null; return new EhCacheElementImpl(element); } public int getTimeToIdleSeconds() { - return (int)ehcache.getTimeToIdleSeconds(); + return (int) ehcache.getTimeToIdleSeconds(); } public int getTimeToLiveSeconds() { - return (int)ehcache.getTimeToLiveSeconds(); + return (int) ehcache.getTimeToLiveSeconds(); } public boolean isKeyInCache(Object key) @@ -63,76 +65,79 @@ return ehcache.isKeyInCache(key); } - public void put(CacheElement element) { - EhCacheElementImpl impl = (EhCacheElementImpl)element; + EhCacheElementImpl impl = (EhCacheElementImpl) element; ehcache.put(impl.getImplElement()); - notifyListeners(true, CacheElement.ActionAdded,impl.getKey(),impl.getContent()); + notifyListeners(true, CacheElement.ActionAdded, impl.getKey(), impl + .getContent()); } - + public CacheElement createElement(Object key, Object content) { - if (!((key instanceof Serializable) || !(content instanceof Serializable))) - throw new IllegalArgumentException("The cache key and the object to cache must be serializable."); //return null; - return new EhCacheElementImpl((Serializable)key, (Serializable)content); + if (!((key instanceof Serializable) || !(content instanceof Serializable))) + throw new IllegalArgumentException( + "The cache key and the object to cache must be serializable."); // return + // null; + return new EhCacheElementImpl((Serializable) key, + (Serializable) content); } public boolean remove(Object key) { Element element = ehcache.get(key); - if (element == null) - return false; + if (element == null) return false; boolean isRemoved = ehcache.remove(key); if (isRemoved) - notifyListeners(true, CacheElement.ActionRemoved,key,null); + notifyListeners(true, CacheElement.ActionRemoved, key, null); return isRemoved; } - + public boolean removeQuiet(Object key) { Element element = ehcache.get(key); - if (element == null) - return false; + if (element == null) return false; return ehcache.removeQuiet(key); - } + } public void clear() { ehcache.removeAll(); - notifyListeners(true, CacheElement.ActionRemoved,null,null); + notifyListeners(true, CacheElement.ActionRemoved, null, null); } - + public void evictContentForUser(String username) { - return; + return; } public void evictContentForSession(String session) { return; } - - public void addEventListener(JetspeedCacheEventListener listener, boolean local) + + public void addEventListener(JetspeedCacheEventListener listener, + boolean local) { - if (local) - localListeners.add(listener); - else - remoteListeners.add(listener); - + if (local) + localListeners.add(listener); + else + remoteListeners.add(listener); + } - - public void removeEventListener(JetspeedCacheEventListener listener, boolean local) + + public void removeEventListener(JetspeedCacheEventListener listener, + boolean local) { if (local) - localListeners.remove(listener); + localListeners.remove(listener); else - remoteListeners.remove(listener); - + remoteListeners.remove(listener); + } - + // ------------------------------------------------------ - + public Object clone() throws CloneNotSupportedException { return super.clone(); @@ -142,39 +147,41 @@ { } - protected void notifyListeners(boolean local, int action, Object key, Object value) + protected void notifyListeners(boolean local, int action, Object key, + Object value) { - List listeners = (local?localListeners:remoteListeners); + List listeners = (local ? localListeners : remoteListeners); for (int ix = 0; ix < listeners.size(); ix++) { - try - { - JetspeedCacheEventListener listener = (JetspeedCacheEventListener)listeners.get(ix); - switch (action) - { - case CacheElement.ActionAdded: - listener.notifyElementAdded(this,local, key,value); - break; - case CacheElement.ActionChanged: - listener.notifyElementChanged(this,local, key,value); - break; - case CacheElement.ActionRemoved: - listener.notifyElementRemoved(this,local, key,value); - break; - case CacheElement.ActionEvicted: - listener.notifyElementEvicted(this,local, key,value); - break; - case CacheElement.ActionExpired: - listener.notifyElementExpired(this,local, key,value); - break; - } - } - catch (Exception e) - { - e.printStackTrace(); - - } - } + try + { + JetspeedCacheEventListener listener = (JetspeedCacheEventListener) listeners + .get(ix); + switch (action) + { + case CacheElement.ActionAdded: + listener.notifyElementAdded(this, local, key, value); + break; + case CacheElement.ActionChanged: + listener.notifyElementChanged(this, local, key, value); + break; + case CacheElement.ActionRemoved: + listener.notifyElementRemoved(this, local, key, value); + break; + case CacheElement.ActionEvicted: + listener.notifyElementEvicted(this, local, key, value); + break; + case CacheElement.ActionExpired: + listener.notifyElementExpired(this, local, key, value); + break; + } + } + catch (Exception e) + { + e.printStackTrace(); + + } + } } public ContentCacheKey createCacheKey(RequestContext rc, String windowId) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhDecorationContentCacheElementImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhDecorationContentCacheElementImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhDecorationContentCacheElementImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,12 +30,15 @@ */ public class EhDecorationContentCacheElementImpl implements ContentCacheElement { + Element element; + ContentCacheKey cckey; - + public static final String KEY_SEPARATOR = "/"; - - public EhDecorationContentCacheElementImpl(Element element, ContentCacheKey cckey) + + public EhDecorationContentCacheElementImpl(Element element, + ContentCacheKey cckey) { this.element = element; this.cckey = cckey; @@ -45,7 +48,7 @@ { return element.getObjectKey(); } - + public Object getContent() { return element.getObjectValue(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhDecorationContentCacheImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhDecorationContentCacheImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhDecorationContentCacheImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -44,62 +44,72 @@ * @author David Sean Taylor * @version $Id: $ */ -public class EhDecorationContentCacheImpl extends EhCacheImpl implements JetspeedContentCache, JetspeedCacheEventListener +public class EhDecorationContentCacheImpl extends EhCacheImpl implements + JetspeedContentCache, JetspeedCacheEventListener { - JetspeedCache preferenceCache = null; - ContentCacheKeyGenerator keyGenerator = null; + JetspeedCache preferenceCache = null; - public EhDecorationContentCacheImpl(Ehcache ehcache, JetspeedCache preferenceCache, ContentCacheKeyGenerator keyGenerator) + ContentCacheKeyGenerator keyGenerator = null; + + public EhDecorationContentCacheImpl(Ehcache ehcache, + JetspeedCache preferenceCache, ContentCacheKeyGenerator keyGenerator) { this(ehcache); this.preferenceCache = preferenceCache; this.keyGenerator = keyGenerator; - preferenceCache.addEventListener(this,false); //only listen to remote events + preferenceCache.addEventListener(this, false); // only listen to remote + // events } - - public EhDecorationContentCacheImpl(Ehcache ehcache, JetspeedCache preferenceCache) + + public EhDecorationContentCacheImpl(Ehcache ehcache, + JetspeedCache preferenceCache) { this(ehcache); this.preferenceCache = preferenceCache; - preferenceCache.addEventListener(this,false); //only listen to remote events + preferenceCache.addEventListener(this, false); // only listen to remote + // events } - + public EhDecorationContentCacheImpl(Ehcache ehcache) { super(ehcache); } - public EhDecorationContentCacheImpl(Cache ehcache, ContentCacheKeyGenerator keyGenerator) + public EhDecorationContentCacheImpl(Cache ehcache, + ContentCacheKeyGenerator keyGenerator) { this(ehcache); this.keyGenerator = keyGenerator; } - - public void notifyElementAdded(JetspeedCache cache, boolean local, Object key, Object element) - { - } + public void notifyElementAdded(JetspeedCache cache, boolean local, + Object key, Object element) + { + } - public void notifyElementChanged(JetspeedCache cache, boolean local, Object key, Object element) - { - } + public void notifyElementChanged(JetspeedCache cache, boolean local, + Object key, Object element) + { + } - public void notifyElementEvicted(JetspeedCache cache, boolean local, Object key, Object element) - { - } + public void notifyElementEvicted(JetspeedCache cache, boolean local, + Object key, Object element) + { + } - public void notifyElementExpired(JetspeedCache cache, boolean local, Object key, Object element) - { - notifyElementRemoved(cache,local,key,element); - } + public void notifyElementExpired(JetspeedCache cache, boolean local, + Object key, Object element) + { + notifyElementRemoved(cache, local, key, element); + } + public static final String KEY_THEME_KEY = EhDecorationContentCacheElementImpl.KEY_SEPARATOR + + "theme" + EhDecorationContentCacheElementImpl.KEY_SEPARATOR; - public static final String KEY_THEME_KEY = - EhDecorationContentCacheElementImpl.KEY_SEPARATOR + "theme" + EhDecorationContentCacheElementImpl.KEY_SEPARATOR ; - public static final int KEY_THEME_KEY_LENGTH = KEY_THEME_KEY.length(); - - public void notifyElementRemoved(JetspeedCache cache, boolean local, + public static final int KEY_THEME_KEY_LENGTH = KEY_THEME_KEY.length(); + + public void notifyElementRemoved(JetspeedCache cache, boolean local, Object key, Object element) { if (local) return; // not interested in local changes @@ -122,7 +132,7 @@ case 0: break; case 1: - te = temp; + te = temp; break; case 2: user = temp; @@ -133,20 +143,21 @@ } if (te != null) { - removeUserEntry(user, "theme", te); + removeUserEntry(user, "theme", te); } } void removeUserEntry(String username, String pipeline, String windowId) - { - ContentCacheKey key = keyGenerator.createUserCacheKey(username, pipeline, windowId); + { + ContentCacheKey key = keyGenerator.createUserCacheKey(username, + pipeline, windowId); if (ehcache.remove(key.getKey())) { Element userElement = ehcache.get(username); - + if (userElement != null) { - Map map = (Map)userElement.getObjectValue(); + Map map = (Map) userElement.getObjectValue(); if (map != null) { map.remove(windowId); @@ -154,37 +165,36 @@ } } } - + public CacheElement get(Object key) { - ContentCacheKey cckey = (ContentCacheKey)key; + ContentCacheKey cckey = (ContentCacheKey) key; Element element = ehcache.get(cckey.getKey()); - if (element == null) - return null; + if (element == null) return null; return new EhDecorationContentCacheElementImpl(element, cckey); } public int getTimeToIdleSeconds() { - return (int)ehcache.getTimeToIdleSeconds(); + return (int) ehcache.getTimeToIdleSeconds(); } public int getTimeToLiveSeconds() { - return (int)ehcache.getTimeToLiveSeconds(); + return (int) ehcache.getTimeToLiveSeconds(); } public boolean isKeyInCache(Object key) { - ContentCacheKey cckey = (ContentCacheKey)key; + ContentCacheKey cckey = (ContentCacheKey) key; return ehcache.isKeyInCache(cckey.getKey()); } public void put(CacheElement element) { - ContentCacheElement ccElement = (ContentCacheElement)element; - EhDecorationContentCacheElementImpl impl = (EhDecorationContentCacheElementImpl)element; - Element ehl = impl.getImplElement(); + ContentCacheElement ccElement = (ContentCacheElement) element; + EhDecorationContentCacheElementImpl impl = (EhDecorationContentCacheElementImpl) element; + Element ehl = impl.getImplElement(); String userKey = ccElement.getContentCacheKey().getSessionId(); if (userKey == null) { @@ -205,19 +215,19 @@ Map map = Collections.synchronizedMap(new HashMap()); map.put(windowId, ccElement.getContentCacheKey()); userElement = new Element(userKey, map); - ehcache.put(userElement); + ehcache.put(userElement); } else { - Map map = (Map)userElement.getObjectValue(); + Map map = (Map) userElement.getObjectValue(); map.put(windowId, ccElement.getContentCacheKey()); - } + } } - + public CacheElement createElement(Object key, Object content) { - ContentCacheKey cckey = (ContentCacheKey)key; - Element cachedElement = new Element(cckey.getKey(), content); + ContentCacheKey cckey = (ContentCacheKey) key; + Element cachedElement = new Element(cckey.getKey(), content); return new EhDecorationContentCacheElementImpl(cachedElement, cckey); } @@ -225,23 +235,22 @@ { CacheElement element = this.get(key); boolean removed = false; - if (element == null) - return false; - - ContentCacheElement ccElement = (ContentCacheElement)element; - EhDecorationContentCacheElementImpl impl = (EhDecorationContentCacheElementImpl)element; - Element ehl = impl.getImplElement(); + if (element == null) return false; + + ContentCacheElement ccElement = (ContentCacheElement) element; + EhDecorationContentCacheElementImpl impl = (EhDecorationContentCacheElementImpl) element; + Element ehl = impl.getImplElement(); String userKey = ccElement.getContentCacheKey().getSessionId(); if (userKey == null) { userKey = ccElement.getContentCacheKey().getUsername(); - } - String windowId = ccElement.getContentCacheKey().getWindowId(); + } + String windowId = ccElement.getContentCacheKey().getWindowId(); removed = ehcache.remove(ccElement.getContentCacheKey().getKey()); Element userElement = ehcache.get(userKey); if (userElement != null) { - Map map = (Map)userElement.getObjectValue(); + Map map = (Map) userElement.getObjectValue(); if (map != null) { map.remove(windowId); @@ -249,19 +258,19 @@ } return removed; } - + public void evictContentForUser(String username) { Element userElement = saveGet(username); if (userElement != null) { - Map map = (Map)userElement.getObjectValue(); + Map map = (Map) userElement.getObjectValue(); if (map != null) { Iterator entities = map.values().iterator(); while (entities.hasNext()) { - ContentCacheKey ccKey = (ContentCacheKey)entities.next(); + ContentCacheKey ccKey = (ContentCacheKey) entities.next(); ehcache.remove(ccKey.getKey()); } } @@ -274,30 +283,31 @@ Element userElement = saveGet(session); if (userElement != null) { - Map map = (Map)userElement.getObjectValue(); + Map map = (Map) userElement.getObjectValue(); if (map != null) { Iterator entities = map.values().iterator(); while (entities.hasNext()) { - ContentCacheKey ccKey = (ContentCacheKey)entities.next(); + ContentCacheKey ccKey = (ContentCacheKey) entities.next(); ehcache.remove(ccKey.getKey()); } } ehcache.remove(session); } } - + public void clear() { ehcache.removeAll(); } - - public ContentCacheKey createCacheKey(RequestContext context, String windowId) + + public ContentCacheKey createCacheKey(RequestContext context, + String windowId) { - return this.keyGenerator.createCacheKey(context, windowId); + return this.keyGenerator.createCacheKey(context, windowId); } - + protected Element saveGet(Object key) { try @@ -310,23 +320,23 @@ return null; } } - + public String createSessionKey(RequestContext context) { boolean isAjaxRequest = (context == null); String mode = isAjaxRequest ? "-d-" : "-p-"; String user = context.getRequest().getRemoteUser(); - if (user == null) - user = "guest"; - return user + mode + context.getPage().getId(); + if (user == null) user = "guest"; + return user + mode + context.getPage().getId(); } - + public void invalidate(RequestContext context) { ContentPage page = context.getPage(); - ContentCacheKey themeContentCacheKey = createCacheKey(context, page.getId()); + ContentCacheKey themeContentCacheKey = createCacheKey(context, page + .getId()); CacheElement themeCacheElem = get(themeContentCacheKey); - + if (themeCacheElem != null) { Theme theme = (Theme) themeCacheElem.getContent(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhPortletContentCacheElementImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhPortletContentCacheElementImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhPortletContentCacheElementImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,12 +30,15 @@ */ public class EhPortletContentCacheElementImpl implements ContentCacheElement { + Element element; + ContentCacheKey cckey; - + public static final String KEY_SEPARATOR = "/"; - - public EhPortletContentCacheElementImpl(Element element, ContentCacheKey cckey) + + public EhPortletContentCacheElementImpl(Element element, + ContentCacheKey cckey) { this.element = element; this.cckey = cckey; @@ -45,7 +48,7 @@ { return element.getObjectKey(); } - + public Object getContent() { return element.getObjectValue(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhPortletContentCacheImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhPortletContentCacheImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhPortletContentCacheImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -42,62 +42,72 @@ * @author David Sean Taylor * @version $Id: $ */ -public class EhPortletContentCacheImpl extends EhCacheImpl implements JetspeedContentCache, JetspeedCacheEventListener +public class EhPortletContentCacheImpl extends EhCacheImpl implements + JetspeedContentCache, JetspeedCacheEventListener { - JetspeedCache preferenceCache = null; - ContentCacheKeyGenerator keyGenerator = null; + JetspeedCache preferenceCache = null; - public EhPortletContentCacheImpl(Ehcache ehcache, JetspeedCache preferenceCache, ContentCacheKeyGenerator keyGenerator) + ContentCacheKeyGenerator keyGenerator = null; + + public EhPortletContentCacheImpl(Ehcache ehcache, + JetspeedCache preferenceCache, ContentCacheKeyGenerator keyGenerator) { this(ehcache); this.preferenceCache = preferenceCache; this.keyGenerator = keyGenerator; - preferenceCache.addEventListener(this,false); //only listen to remote events + preferenceCache.addEventListener(this, false); // only listen to remote + // events } - - public EhPortletContentCacheImpl(Ehcache ehcache, JetspeedCache preferenceCache) + + public EhPortletContentCacheImpl(Ehcache ehcache, + JetspeedCache preferenceCache) { this(ehcache); this.preferenceCache = preferenceCache; - preferenceCache.addEventListener(this,false); //only listen to remote events + preferenceCache.addEventListener(this, false); // only listen to remote + // events } - + public EhPortletContentCacheImpl(Ehcache ehcache) { super(ehcache); } - public EhPortletContentCacheImpl(Ehcache ehcache, ContentCacheKeyGenerator keyGenerator) + public EhPortletContentCacheImpl(Ehcache ehcache, + ContentCacheKeyGenerator keyGenerator) { this(ehcache); this.keyGenerator = keyGenerator; } - - public void notifyElementAdded(JetspeedCache cache, boolean local, Object key, Object element) - { - } + public void notifyElementAdded(JetspeedCache cache, boolean local, + Object key, Object element) + { + } - public void notifyElementChanged(JetspeedCache cache, boolean local, Object key, Object element) - { - } + public void notifyElementChanged(JetspeedCache cache, boolean local, + Object key, Object element) + { + } - public void notifyElementEvicted(JetspeedCache cache, boolean local, Object key, Object element) - { - } + public void notifyElementEvicted(JetspeedCache cache, boolean local, + Object key, Object element) + { + } - public void notifyElementExpired(JetspeedCache cache, boolean local, Object key, Object element) - { - notifyElementRemoved(cache,local,key,element); - } + public void notifyElementExpired(JetspeedCache cache, boolean local, + Object key, Object element) + { + notifyElementRemoved(cache, local, key, element); + } + public static final String KEY_ENTITY_KEY = EhPortletContentCacheElementImpl.KEY_SEPARATOR + + "portlet_entity" + EhPortletContentCacheElementImpl.KEY_SEPARATOR; - public static final String KEY_ENTITY_KEY = - EhPortletContentCacheElementImpl.KEY_SEPARATOR + "portlet_entity" + EhPortletContentCacheElementImpl.KEY_SEPARATOR ; - public static final int KEY_ENTITY_KEY_LENGTH = KEY_ENTITY_KEY.length(); - - public void notifyElementRemoved(JetspeedCache cache, boolean local, + public static final int KEY_ENTITY_KEY_LENGTH = KEY_ENTITY_KEY.length(); + + public void notifyElementRemoved(JetspeedCache cache, boolean local, Object key, Object element) { if (local) return; // not interested in local changes @@ -120,7 +130,7 @@ case 0: break; case 1: - pe = temp; + pe = temp; break; case 2: user = temp; @@ -131,21 +141,22 @@ } if ((pe != null) && (user != null)) { - removeUserEntry(user, "portal", pe); + removeUserEntry(user, "portal", pe); removeUserEntry(user, "desktop", pe); } } void removeUserEntry(String username, String pipeline, String windowId) - { - ContentCacheKey key = keyGenerator.createUserCacheKey(username, pipeline, windowId); + { + ContentCacheKey key = keyGenerator.createUserCacheKey(username, + pipeline, windowId); if (ehcache.remove(key.getKey())) { Element userElement = ehcache.get(username); - + if (userElement != null) { - Map map = (Map)userElement.getObjectValue(); + Map map = (Map) userElement.getObjectValue(); if (map != null) { map.remove(windowId); @@ -153,37 +164,36 @@ } } } - + public CacheElement get(Object key) { - ContentCacheKey cckey = (ContentCacheKey)key; + ContentCacheKey cckey = (ContentCacheKey) key; Element element = ehcache.get(cckey.getKey()); - if (element == null) - return null; + if (element == null) return null; return new EhPortletContentCacheElementImpl(element, cckey); } public int getTimeToIdleSeconds() { - return (int)ehcache.getTimeToIdleSeconds(); + return (int) ehcache.getTimeToIdleSeconds(); } public int getTimeToLiveSeconds() { - return (int)ehcache.getTimeToLiveSeconds(); + return (int) ehcache.getTimeToLiveSeconds(); } public boolean isKeyInCache(Object key) { - ContentCacheKey cckey = (ContentCacheKey)key; + ContentCacheKey cckey = (ContentCacheKey) key; return ehcache.isKeyInCache(cckey.getKey()); } public void put(CacheElement element) { - ContentCacheElement ccElement = (ContentCacheElement)element; - EhPortletContentCacheElementImpl impl = (EhPortletContentCacheElementImpl)element; - Element ehl = impl.getImplElement(); + ContentCacheElement ccElement = (ContentCacheElement) element; + EhPortletContentCacheElementImpl impl = (EhPortletContentCacheElementImpl) element; + Element ehl = impl.getImplElement(); String userKey = ccElement.getContentCacheKey().getSessionId(); if (userKey == null) { @@ -204,19 +214,19 @@ Map map = Collections.synchronizedMap(new HashMap()); map.put(windowId, ccElement.getContentCacheKey()); userElement = new Element(userKey, map); - ehcache.put(userElement); + ehcache.put(userElement); } else { - Map map = (Map)userElement.getObjectValue(); + Map map = (Map) userElement.getObjectValue(); map.put(windowId, ccElement.getContentCacheKey()); - } + } } - + public CacheElement createElement(Object key, Object content) { - ContentCacheKey cckey = (ContentCacheKey)key; - Element cachedElement = new Element(cckey.getKey(), content); + ContentCacheKey cckey = (ContentCacheKey) key; + Element cachedElement = new Element(cckey.getKey(), content); return new EhPortletContentCacheElementImpl(cachedElement, cckey); } @@ -224,23 +234,22 @@ { CacheElement element = this.get(key); boolean removed = false; - if (element == null) - return false; - - ContentCacheElement ccElement = (ContentCacheElement)element; - EhPortletContentCacheElementImpl impl = (EhPortletContentCacheElementImpl)element; - Element ehl = impl.getImplElement(); + if (element == null) return false; + + ContentCacheElement ccElement = (ContentCacheElement) element; + EhPortletContentCacheElementImpl impl = (EhPortletContentCacheElementImpl) element; + Element ehl = impl.getImplElement(); String userKey = ccElement.getContentCacheKey().getSessionId(); if (userKey == null) { userKey = ccElement.getContentCacheKey().getUsername(); - } - String windowId = ccElement.getContentCacheKey().getWindowId(); + } + String windowId = ccElement.getContentCacheKey().getWindowId(); removed = ehcache.remove(ccElement.getContentCacheKey().getKey()); Element userElement = ehcache.get(userKey); if (userElement != null) { - Map map = (Map)userElement.getObjectValue(); + Map map = (Map) userElement.getObjectValue(); if (map != null) { map.remove(windowId); @@ -248,19 +257,19 @@ } return removed; } - + public void evictContentForUser(String username) { Element userElement = saveGet(username); if (userElement != null) { - Map map = (Map)userElement.getObjectValue(); + Map map = (Map) userElement.getObjectValue(); if (map != null) { Iterator entities = map.values().iterator(); while (entities.hasNext()) { - ContentCacheKey ccKey = (ContentCacheKey)entities.next(); + ContentCacheKey ccKey = (ContentCacheKey) entities.next(); ehcache.remove(ccKey.getKey()); } } @@ -273,30 +282,31 @@ Element userElement = saveGet(session); if (userElement != null) { - Map map = (Map)userElement.getObjectValue(); + Map map = (Map) userElement.getObjectValue(); if (map != null) { Iterator entities = map.values().iterator(); while (entities.hasNext()) { - ContentCacheKey ccKey = (ContentCacheKey)entities.next(); + ContentCacheKey ccKey = (ContentCacheKey) entities.next(); ehcache.remove(ccKey.getKey()); } } ehcache.remove(session); } } - + public void clear() { ehcache.removeAll(); } - - public ContentCacheKey createCacheKey(RequestContext context, String windowId) + + public ContentCacheKey createCacheKey(RequestContext context, + String windowId) { - return this.keyGenerator.createCacheKey(context, windowId); + return this.keyGenerator.createCacheKey(context, windowId); } - + protected Element saveGet(Object key) { try @@ -309,21 +319,21 @@ return null; } } - + public String createSessionKey(RequestContext context) { boolean isAjaxRequest = (context == null); String mode = isAjaxRequest ? "-d-" : "-p-"; String user = context.getRequest().getRemoteUser(); - if (user == null) - user = "guest"; - return user + mode + context.getPage().getId(); + if (user == null) user = "guest"; + return user + mode + context.getPage().getId(); } - + public void invalidate(RequestContext context) { String themeCacheKey = createSessionKey(context); - Theme theme = (Theme)context.getRequest().getSession().getAttribute(themeCacheKey); + Theme theme = (Theme) context.getRequest().getSession().getAttribute( + themeCacheKey); if (theme != null) { theme.setInvalidated(true); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhPortletWindowCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhPortletWindowCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/EhPortletWindowCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.cache.impl; import java.util.HashMap; @@ -34,107 +34,123 @@ * EhPortletWindowCache *

      *

      - * Implementation of {@link PortletWindowCache} that is backed - * Ehcache. + * Implementation of {@link PortletWindowCache} that is backed Ehcache. *

      + * * @author Scott T. Weaver - * + * */ -public class EhPortletWindowCache extends EhCacheImpl implements PortletWindowCache { +public class EhPortletWindowCache extends EhCacheImpl implements + PortletWindowCache +{ - /** Allows us to track {@link PortletWindow}s in cache by {@link PortletEntity#getId()}*/ + /** + * Allows us to track {@link PortletWindow}s in cache by + * {@link PortletEntity#getId()} + */ private Map portletEntityIdToEntityid; - - - public EhPortletWindowCache(Ehcache ehcache) - { - super(ehcache); - portletEntityIdToEntityid = new HashMap(); - } - - /* (non-Javadoc) - * @see org.apache.jetspeed.cache.impl.PortletWindowCache#getPortletWindow(java.lang.String) - */ - public PortletWindow getPortletWindow(String windowId) - { - assert windowId != null; - CacheElement cacheElement = get(windowId); - if(cacheElement != null) - { - return (PortletWindow) cacheElement.getContent(); - } - else - { - return null; - } - } - - /* (non-Javadoc) - * @see org.apache.jetspeed.cache.impl.PortletWindowCache#getPortletWindowByEntityId(java.lang.String) - */ - public PortletWindow getPortletWindowByEntityId(String portletEntityId) - { - assert portletEntityId != null; - if(portletEntityIdToEntityid.containsKey(portletEntityId)) - { - return (PortletWindow) getPortletWindow((String) portletEntityIdToEntityid.get(portletEntityId)); - } - else - { - return null; - } - } - - /* (non-Javadoc) - * @see org.apache.jetspeed.cache.impl.PortletWindowCache#putPortletWindow(org.apache.pluto.om.window.PortletWindow) - */ - public void putPortletWindow(PortletWindow window) - { - assert window != null; - String windowId = window.getId().toString(); - portletEntityIdToEntityid.put(window.getPortletEntity().getId().toString(), windowId); - put(createElement(windowId, window)); - } - - /* (non-Javadoc) - * @see org.apache.jetspeed.cache.impl.PortletWindowCache#removePortletWindow(java.lang.String) - */ - public void removePortletWindow(String portletWindowId) - { - assert portletWindowId != null; - PortletWindow window = getPortletWindow(portletWindowId); - if(window != null) - { - portletEntityIdToEntityid.remove(window.getPortletEntity().getId().toString()); - removeQuiet(portletWindowId); - } - } - - public void removePortletWindowByPortletEntityId(String portletEntityId) - { - assert portletEntityId != null; - PortletWindow portletWindow = getPortletWindowByEntityId(portletEntityId); - if(portletWindow != null) - { - portletEntityIdToEntityid.remove(portletEntityId); + + public EhPortletWindowCache(Ehcache ehcache) + { + super(ehcache); + portletEntityIdToEntityid = new HashMap(); + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.cache.impl.PortletWindowCache#getPortletWindow(java.lang.String) + */ + public PortletWindow getPortletWindow(String windowId) + { + assert windowId != null; + CacheElement cacheElement = get(windowId); + if (cacheElement != null) + { + return (PortletWindow) cacheElement.getContent(); + } + else + { + return null; + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.cache.impl.PortletWindowCache#getPortletWindowByEntityId(java.lang.String) + */ + public PortletWindow getPortletWindowByEntityId(String portletEntityId) + { + assert portletEntityId != null; + if (portletEntityIdToEntityid.containsKey(portletEntityId)) + { + return (PortletWindow) getPortletWindow((String) portletEntityIdToEntityid + .get(portletEntityId)); + } + else + { + return null; + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.cache.impl.PortletWindowCache#putPortletWindow(org.apache.pluto.om.window.PortletWindow) + */ + public void putPortletWindow(PortletWindow window) + { + assert window != null; + String windowId = window.getId().toString(); + portletEntityIdToEntityid.put(window.getPortletEntity().getId() + .toString(), windowId); + put(createElement(windowId, window)); + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.cache.impl.PortletWindowCache#removePortletWindow(java.lang.String) + */ + public void removePortletWindow(String portletWindowId) + { + assert portletWindowId != null; + PortletWindow window = getPortletWindow(portletWindowId); + if (window != null) + { + portletEntityIdToEntityid.remove(window.getPortletEntity().getId() + .toString()); + removeQuiet(portletWindowId); + } + } + + public void removePortletWindowByPortletEntityId(String portletEntityId) + { + assert portletEntityId != null; + PortletWindow portletWindow = getPortletWindowByEntityId(portletEntityId); + if (portletWindow != null) + { + portletEntityIdToEntityid.remove(portletEntityId); removeQuiet(portletWindow.getId().toString()); - } - } - - public Set getAllPortletWindows() - { - Iterator keys = ehcache.getKeys().iterator(); - Set windows = new HashSet(); - while(keys.hasNext()) - { - String key = (String) keys.next(); - PortletWindow window = getPortletWindow(key); - if(window != null) - { - windows.add(window); - } - } - return windows; - } + } + } + public Set getAllPortletWindows() + { + Iterator keys = ehcache.getKeys().iterator(); + Set windows = new HashSet(); + while (keys.hasNext()) + { + String key = (String) keys.next(); + PortletWindow window = getPortletWindow(key); + if (window != null) + { + windows.add(window); + } + } + return windows; + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/JetspeedCacheKeyGenerator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/JetspeedCacheKeyGenerator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/JetspeedCacheKeyGenerator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,42 +31,48 @@ */ public class JetspeedCacheKeyGenerator implements ContentCacheKeyGenerator { + private List segments; + private boolean cacheBySessionId = true; - + public JetspeedCacheKeyGenerator(List segments) { this.segments = segments; - this.cacheBySessionId = (segments.contains("sessionid")); + this.cacheBySessionId = (segments.contains("sessionid")); } - - public ContentCacheKey createCacheKey(RequestContext context, String windowId) + + public ContentCacheKey createCacheKey(RequestContext context, + String windowId) { - ContentCacheKey key = new JetspeedContentCacheKey(segments, context, windowId); + ContentCacheKey key = new JetspeedContentCacheKey(segments, context, + windowId); return key; } - public ContentCacheKey createUserCacheKey(String username, String pipeline, String windowId) + public ContentCacheKey createUserCacheKey(String username, String pipeline, + String windowId) { ContentCacheKey key = new JetspeedContentCacheKey(); key.createFromUser(username, pipeline, windowId); return key; } - public ContentCacheKey createSessionCacheKey(String sessionId, String pipeline, String windowId) + public ContentCacheKey createSessionCacheKey(String sessionId, + String pipeline, String windowId) { ContentCacheKey key = new JetspeedContentCacheKey(); key.createFromSession(sessionId, pipeline, windowId); return key; } - + public boolean isCacheBySessionId() { return cacheBySessionId; } - + public boolean isCacheByUsername() { - return !cacheBySessionId; + return !cacheBySessionId; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/JetspeedContentCacheKey.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/JetspeedContentCacheKey.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/cache/impl/JetspeedContentCacheKey.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,8 +26,8 @@ import org.apache.jetspeed.request.RequestContext; /** - * The content cache key holds an immutable cache key definition. - * Cache key definitions are based on the following required properties: + * The content cache key holds an immutable cache key definition. Cache key + * definitions are based on the following required properties: *
        *
      • username
      • *
      • windowid
      • @@ -47,40 +47,57 @@ */ public class JetspeedContentCacheKey implements ContentCacheKey, Serializable { + private String username = null; + private String pipeline = null; + private String windowId = null; + private String sessionId = null; + private String requestParameter = null; + private String sessionAttribute = null; + private String key = ""; - - public JetspeedContentCacheKey(List segments, RequestContext context, String windowId) + + public JetspeedContentCacheKey(List segments, RequestContext context, + String windowId) { boolean first = true; Iterator si = segments.iterator(); while (si.hasNext()) { - String segment = (String)si.next(); + String segment = (String) si.next(); if (segment.equals("username")) { this.username = context.getUserPrincipal().getName(); - key = (first) ? this.username : key + EhPortletContentCacheElementImpl.KEY_SEPARATOR + this.username; + key = (first) ? this.username : key + + EhPortletContentCacheElementImpl.KEY_SEPARATOR + + this.username; } else if (segment.equals("windowid")) { this.windowId = windowId; - key = (first) ? this.windowId : key + EhPortletContentCacheElementImpl.KEY_SEPARATOR + this.windowId; + key = (first) ? this.windowId : key + + EhPortletContentCacheElementImpl.KEY_SEPARATOR + + this.windowId; } else if (segment.equals("sessionid")) { this.sessionId = context.getRequest().getSession().getId(); - key = (first) ? this.sessionId : key + EhPortletContentCacheElementImpl.KEY_SEPARATOR + this.sessionId; + key = (first) ? this.sessionId : key + + EhPortletContentCacheElementImpl.KEY_SEPARATOR + + this.sessionId; } else if (segment.equals("pipeline")) { - String encoder = context.getRequestParameter(JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER); - if (encoder != null && encoder.equals(JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER_VALUE)) + String encoder = context + .getRequestParameter(JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER); + if (encoder != null + && encoder + .equals(JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER_VALUE)) { this.pipeline = "desktop"; } @@ -88,7 +105,9 @@ { this.pipeline = "portal"; } - key = (first) ? this.pipeline : key + EhPortletContentCacheElementImpl.KEY_SEPARATOR + this.pipeline; + key = (first) ? this.pipeline : key + + EhPortletContentCacheElementImpl.KEY_SEPARATOR + + this.pipeline; } else if (segment.startsWith("request")) { @@ -96,10 +115,14 @@ if (pos > -1) { String parameterName = segment.substring(pos); - this.requestParameter = context.getRequestParameter(parameterName); + this.requestParameter = context + .getRequestParameter(parameterName); if (this.requestParameter != null) { - key = (first) ? this.requestParameter : key + EhPortletContentCacheElementImpl.KEY_SEPARATOR + this.requestParameter; + key = (first) ? this.requestParameter + : key + + EhPortletContentCacheElementImpl.KEY_SEPARATOR + + this.requestParameter; } } } @@ -109,46 +132,51 @@ if (pos > -1) { String attributeName = segment.substring(pos); - this.sessionAttribute = (String)context.getSessionAttribute(attributeName); + this.sessionAttribute = (String) context + .getSessionAttribute(attributeName); if (this.sessionAttribute != null) { - key = (first) ? this.sessionAttribute : key + EhPortletContentCacheElementImpl.KEY_SEPARATOR + this.sessionAttribute; + key = (first) ? this.sessionAttribute + : key + + EhPortletContentCacheElementImpl.KEY_SEPARATOR + + this.sessionAttribute; } - } - } + } + } first = false; } - //System.out.println("*** CACHE KEY IS [" + key + "]"); + // System.out.println("*** CACHE KEY IS [" + key + "]"); } - + public JetspeedContentCacheKey() - { + { } - + public void createFromUser(String username, String pipeline, String windowId) { this.setUsername(username); this.setPipeline(pipeline); this.setWindowId(windowId); - this.key = this.getUsername() + - EhPortletContentCacheElementImpl.KEY_SEPARATOR + - this.getPipeline() + - EhPortletContentCacheElementImpl.KEY_SEPARATOR + - this.getWindowId(); + this.key = this.getUsername() + + EhPortletContentCacheElementImpl.KEY_SEPARATOR + + this.getPipeline() + + EhPortletContentCacheElementImpl.KEY_SEPARATOR + + this.getWindowId(); } - public void createFromSession(String sessionId, String pipeline, String windowId) + public void createFromSession(String sessionId, String pipeline, + String windowId) { this.setSessionId(sessionId); this.setPipeline(pipeline); this.setWindowId(windowId); - this.key = this.getSessionId() + - EhPortletContentCacheElementImpl.KEY_SEPARATOR + - this.getPipeline() + - EhPortletContentCacheElementImpl.KEY_SEPARATOR + - this.getWindowId(); + this.key = this.getSessionId() + + EhPortletContentCacheElementImpl.KEY_SEPARATOR + + this.getPipeline() + + EhPortletContentCacheElementImpl.KEY_SEPARATOR + + this.getWindowId(); } - + public String getKey() { return this.key; @@ -184,37 +212,31 @@ return this.windowId; } - public void setPipeline(String pipeline) { this.pipeline = pipeline; } - public void setRequestParameter(String requestParameter) { this.requestParameter = requestParameter; } - public void setSessionAttribute(String sessionAttribute) { this.sessionAttribute = sessionAttribute; } - public void setSessionId(String sessionId) { this.sessionId = sessionId; } - public void setUsername(String username) { this.username = username; } - public void setWindowId(String windowId) { this.windowId = windowId; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/SpringComponentManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/SpringComponentManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/SpringComponentManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -49,6 +49,7 @@ */ public class SpringComponentManager implements ComponentManager { + protected ConfigurableApplicationContext appContext; private ConfigurableApplicationContext bootCtx; @@ -59,17 +60,20 @@ private boolean started = false; - public SpringComponentManager(String[] bootConfigs, String[] appConfigs, ServletContext servletContext, - String appRoot) + public SpringComponentManager(String[] bootConfigs, String[] appConfigs, + ServletContext servletContext, String appRoot) { File appRootDir = new File(appRoot); - System.setProperty(JetspeedEngineConstants.APPLICATION_ROOT_KEY, appRootDir.getAbsolutePath()); + System.setProperty(JetspeedEngineConstants.APPLICATION_ROOT_KEY, + appRootDir.getAbsolutePath()); if (bootConfigs != null && bootConfigs.length > 0) { bootCtx = new XmlWebApplicationContext(); - ((XmlWebApplicationContext) bootCtx).setServletContext(servletContext); - ((XmlWebApplicationContext) bootCtx).setConfigLocations(bootConfigs); + ((XmlWebApplicationContext) bootCtx) + .setServletContext(servletContext); + ((XmlWebApplicationContext) bootCtx) + .setConfigLocations(bootConfigs); } else { @@ -78,30 +82,34 @@ appContext = new XmlWebApplicationContext(); ((XmlWebApplicationContext) appContext).setParent(bootCtx); - ((XmlWebApplicationContext) appContext).setServletContext(servletContext); + ((XmlWebApplicationContext) appContext) + .setServletContext(servletContext); ((XmlWebApplicationContext) appContext).setConfigLocations(appConfigs); factories = new ArrayList(); factories.add(appContext); - servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appContext); + servletContext.setAttribute( + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, + appContext); } - public SpringComponentManager(String[] bootConfigs, String[] appConfigs, ServletContext servletContext, - String appRoot, Map preconfiguredBeans) + public SpringComponentManager(String[] bootConfigs, String[] appConfigs, + ServletContext servletContext, String appRoot, + Map preconfiguredBeans) { this(bootConfigs, appConfigs, servletContext, appRoot); this.preconfiguredBeans = preconfiguredBeans; } - - public SpringComponentManager(String[] bootConfigs, String[] appConfigs, String appRoot) - { + public SpringComponentManager(String[] bootConfigs, String[] appConfigs, + String appRoot) + { PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); Properties p = new Properties(); - //p.setProperty(APPLICATION_ROOT_KEY,appRootDir.getAbsolutePath()); + // p.setProperty(APPLICATION_ROOT_KEY,appRootDir.getAbsolutePath()); ppc.setProperties(p); - + if (bootConfigs != null && bootConfigs.length > 0) { bootCtx = new FileSystemXmlApplicationContext(bootConfigs, false); @@ -113,14 +121,15 @@ bootCtx = new GenericApplicationContext(); } - appContext = new FileSystemXmlApplicationContext(appConfigs, false, bootCtx); + appContext = new FileSystemXmlApplicationContext(appConfigs, false, + bootCtx); appContext.addBeanFactoryPostProcessor(ppc); appContext.refresh(); factories = new ArrayList(); factories.add(appContext); - + } - + /** *

        * getComponent @@ -241,7 +250,8 @@ while (itr.hasNext()) { Map.Entry entry = (Map.Entry) itr.next(); - bootCtx.getBeanFactory().registerSingleton(entry.getKey().toString(), entry.getValue()); + bootCtx.getBeanFactory().registerSingleton( + entry.getKey().toString(), entry.getValue()); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/factorybeans/PlutoFactoryFactoryBean.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/factorybeans/PlutoFactoryFactoryBean.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/factorybeans/PlutoFactoryFactoryBean.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,25 +30,29 @@ * PlutoFactoryFactoryBean *

        *

        - * + * *

        + * * @author Scott T. Weaver * @version $Id: PlutoFactoryFactoryBean.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class PlutoFactoryFactoryBean extends AbstractFactoryBean { - + private String className; + private Map props; + private ServletConfig servletConfig; + private Object bean; - + /** *

        * createInstance *

        - * + * * @see org.springframework.beans.factory.config.AbstractFactoryBean#createInstance() * @return * @throws java.lang.Exception @@ -56,45 +60,43 @@ protected Object createInstance() throws Exception { Factory factory; - if(bean == null && className != null) + if (bean == null && className != null) { - factory = (Factory)Thread.currentThread() - .getContextClassLoader().loadClass(className).newInstance(); + factory = (Factory) Thread.currentThread().getContextClassLoader() + .loadClass(className).newInstance(); } - else if(bean != null) + else if (bean != null) { - factory = (Factory)bean; + factory = (Factory) bean; } else { - throw new BeanCreationException("PlutoFactoryFactoryBean requires either a 'className' or a 'bean' reference to be set."); + throw new BeanCreationException( + "PlutoFactoryFactoryBean requires either a 'className' or a 'bean' reference to be set."); } - - if(props == null) + + if (props == null) { props = new HashMap(); } - + factory.init(servletConfig, props); - return factory; + return factory; } /** *

        * getObjectType *

        - * + * * @see org.springframework.beans.factory.FactoryBean#getObjectType() * @return */ public Class getObjectType() { - return Factory.class; + return Factory.class; } - - - /** * @return Returns the props. */ @@ -102,13 +104,16 @@ { return props; } + /** - * @param props The props to set. + * @param props + * The props to set. */ - public void setProps( Map props ) + public void setProps(Map props) { this.props = props; } + /** * @return Returns the servletConfig. */ @@ -116,13 +121,16 @@ { return servletConfig; } + /** - * @param servletConfig The servletConfig to set. + * @param servletConfig + * The servletConfig to set. */ - public void setServletConfig( ServletConfig servletConfig ) + public void setServletConfig(ServletConfig servletConfig) { this.servletConfig = servletConfig; } + /** * @return Returns the className. */ @@ -130,10 +138,12 @@ { return className; } + /** - * @param className The className to set. + * @param className + * The className to set. */ - public void setClassName( String className ) + public void setClassName(String className) { this.className = className; } @@ -142,11 +152,10 @@ { return bean; } - public void setBean(Object bean) { this.bean = bean; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/factorybeans/ServletConfigFactoryBean.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/factorybeans/ServletConfigFactoryBean.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/factorybeans/ServletConfigFactoryBean.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,37 +25,38 @@ * PreSetInstanceFactoryBean *

        *

        - * + * *

        + * * @author Scott T. Weaver * @version $Id: ServletConfigFactoryBean.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class ServletConfigFactoryBean extends AbstractFactoryBean { private static ServletConfig servletConfig; - /** *

        * createInstance *

        - * + * * @see org.springframework.beans.factory.config.AbstractFactoryBean#createInstance() * @return * @throws Exception */ protected final Object createInstance() throws Exception - { + { verifyState(); - return servletConfig; + return servletConfig; } /** *

        * getObjectType *

        + * * @see org.springframework.beans.factory.FactoryBean#getObjectType() * @return */ @@ -63,18 +64,16 @@ { return ServletConfig.class; } - + public final static void setServletConfig(ServletConfig servletConfig) { ServletConfigFactoryBean.servletConfig = servletConfig; } - + protected final void verifyState() throws IllegalStateException { - if(servletConfig == null) - { - throw new IllegalStateException("You invoke the ServletConfigFactoryBean.setServletConfig() "+ - "method prior to attempting to get the ServletConfig."); - } + if (servletConfig == null) { throw new IllegalStateException( + "You invoke the ServletConfigFactoryBean.setServletConfig() " + + "method prior to attempting to get the ServletConfig."); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/interceptors/AbstractCacheInterceptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/interceptors/AbstractCacheInterceptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/interceptors/AbstractCacheInterceptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,96 +29,97 @@ * AbstractCacheInterceptor *

        *

        - * + * *

        + * * @author Scott T. Weaver * @version $Id: AbstractCacheInterceptor.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public abstract class AbstractCacheInterceptor implements Interceptor, MethodInterceptor, Advice +public abstract class AbstractCacheInterceptor implements Interceptor, + MethodInterceptor, Advice { protected GeneralCache cache; + protected String uniquePrefix; - + /** - * + * */ - public AbstractCacheInterceptor( GeneralCache cache, String uniquePrefix ) + public AbstractCacheInterceptor(GeneralCache cache, String uniquePrefix) { super(); this.cache = cache; this.uniquePrefix = uniquePrefix; } - + /** * * @param cache */ - public AbstractCacheInterceptor( GeneralCache cache ) + public AbstractCacheInterceptor(GeneralCache cache) { this(cache, null); } - /** * *

        * buildKey *

        - * + * * @param clazz * @param method * @param arg0 * @return */ - public static final String buildKey( String uniquePrefix, String arg0 ) + public static final String buildKey(String uniquePrefix, String arg0) { - return uniquePrefix + ":" + arg0 ; + return uniquePrefix + ":" + arg0; } - /** * *

        * invoke *

        - * + * * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation) * @param mi * @return * @throws Throwable */ - public Object invoke( MethodInvocation mi ) throws Throwable + public Object invoke(MethodInvocation mi) throws Throwable { Object[] args = mi.getArguments(); Method method = mi.getMethod(); - if (args == null) - { - throw new IllegalArgumentException(method.getDeclaringClass() + "." + method.getName() - + "() receives no arguments. " - + "CacheInterceptor can only intercept methods that have at least (1) argument."); - } - + if (args == null) { throw new IllegalArgumentException( + method.getDeclaringClass() + + "." + + method.getName() + + "() receives no arguments. " + + "CacheInterceptor can only intercept methods that have at least (1) argument."); } + Object arg0 = args[0]; - if(arg0 == null) - { - throw new IllegalArgumentException("CacheInterceptor requires that the first argument passed to a cached be non-null"); - } - + if (arg0 == null) { throw new IllegalArgumentException( + "CacheInterceptor requires that the first argument passed to a cached be non-null"); } + String prefix = null; - if(uniquePrefix != null) + if (uniquePrefix != null) { prefix = buildKey(uniquePrefix, arg0.toString()); } else { - prefix = buildKey(mi.getMethod().getDeclaringClass().getName(), arg0.toString()); + prefix = buildKey(mi.getMethod().getDeclaringClass().getName(), + arg0.toString()); } - - return doCacheOperation(mi, prefix); + + return doCacheOperation(mi, prefix); } - - protected abstract Object doCacheOperation( MethodInvocation mi, String uniqueKey ) throws Throwable; + protected abstract Object doCacheOperation(MethodInvocation mi, + String uniqueKey) throws Throwable; + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/interceptors/CachingInterceptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/interceptors/CachingInterceptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/interceptors/CachingInterceptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,25 +24,25 @@ * CacheInterceptor *

        *

        - * AoP Interceptor that can be used for generalized caching. The only requirement is - * that intercepted methods must receive at least one (1) arguments. - *

        - * CacheInterceptor ALWAYS use the first argument in the method to build the unique cache key. + * AoP Interceptor that can be used for generalized caching. The only + * requirement is that intercepted methods must receive at least one (1) + * arguments.
        + *
        + * CacheInterceptor ALWAYS use the first argument in the method to build the + * unique cache key. *

        * * @author Scott T. Weaver * @version $Id: CachingInterceptor.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class CachingInterceptor extends AbstractCacheInterceptor { - - /** * @param cache */ - public CachingInterceptor( GeneralCache cache ) + public CachingInterceptor(GeneralCache cache) { super(cache); } @@ -51,26 +51,27 @@ *

        * doCacheOperation *

        - * + * * @param mi * @param uniqueKey * @return * @throws Throwable */ - protected Object doCacheOperation( MethodInvocation mi, String uniqueKey ) throws Throwable + protected Object doCacheOperation(MethodInvocation mi, String uniqueKey) + throws Throwable { - if(cache.contains(uniqueKey)) + if (cache.contains(uniqueKey)) { return cache.get(uniqueKey); } else { Object value = mi.proceed(); - if(value != null) + if (value != null) { cache.put(uniqueKey, value); } - + return value; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/interceptors/RemoveFromCacheInterceptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/interceptors/RemoveFromCacheInterceptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/interceptors/RemoveFromCacheInterceptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,11 +24,12 @@ * RemoveFromCacheInterceptor *

        *

        - * + * *

        + * * @author Scott T. Weaver * @version $Id: RemoveFromCacheInterceptor.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class RemoveFromCacheInterceptor extends AbstractCacheInterceptor { @@ -36,24 +37,26 @@ /** * @param cache */ - public RemoveFromCacheInterceptor( GeneralCache cache ) + public RemoveFromCacheInterceptor(GeneralCache cache) { super(cache); } - + /** * *

        * doCacheOperation *

        - * - * @see org.apache.jetspeed.components.interceptors.AbstractCacheInterceptor#doCacheOperation(org.aopalliance.intercept.MethodInvocation, java.lang.String) + * + * @see org.apache.jetspeed.components.interceptors.AbstractCacheInterceptor#doCacheOperation(org.aopalliance.intercept.MethodInvocation, + * java.lang.String) * @param mi * @param uniqueKey * @return * @throws Throwable */ - protected Object doCacheOperation( MethodInvocation mi, String uniqueKey ) throws Throwable + protected Object doCacheOperation(MethodInvocation mi, String uniqueKey) + throws Throwable { cache.remove(uniqueKey); return mi.proceed(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/test/AbstractSpringTestCase.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/test/AbstractSpringTestCase.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/test/AbstractSpringTestCase.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,13 +18,13 @@ import java.util.Properties; +import junit.framework.TestCase; + import org.apache.jetspeed.engine.JetspeedEngineConstants; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import junit.framework.TestCase; - /** *

        * AbstractSpringTestCase @@ -35,10 +35,11 @@ * * @author Scott T. Weaver * @version $Id: AbstractSpringTestCase.java 598474 2007-11-27 00:37:16Z ate $ - * + * */ public abstract class AbstractSpringTestCase extends TestCase { + /** * Provides access to the Spring ApplicationContext. */ @@ -48,23 +49,27 @@ * setup Spring context as part of test setup */ protected void setUp() throws Exception - { + { super.setUp(); if (ctx == null) { - String [] bootConfigurations = getBootConfigurations(); + String[] bootConfigurations = getBootConfigurations(); if (bootConfigurations != null) { - ApplicationContext bootContext = new ClassPathXmlApplicationContext(bootConfigurations, true); - ctx = new ClassPathXmlApplicationContext(getConfigurations(), false, bootContext); + ApplicationContext bootContext = new ClassPathXmlApplicationContext( + bootConfigurations, true); + ctx = new ClassPathXmlApplicationContext(getConfigurations(), + false, bootContext); } else { - ctx = new ClassPathXmlApplicationContext(getConfigurations(), false); + ctx = new ClassPathXmlApplicationContext(getConfigurations(), + false); } PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); Properties p = getPostProcessProperties(); - p.setProperty(JetspeedEngineConstants.APPLICATION_ROOT_KEY, "../../src/webapp"); + p.setProperty(JetspeedEngineConstants.APPLICATION_ROOT_KEY, + "../../src/webapp"); ppc.setProperties(p); ctx.addBeanFactoryPostProcessor(ppc); ctx.refresh(); @@ -75,7 +80,7 @@ * close Spring context as part of test teardown */ protected void tearDown() throws Exception - { + { super.tearDown(); if (ctx != null) { @@ -87,7 +92,7 @@ * required specification of spring configurations */ protected abstract String[] getConfigurations(); - + /** * optional specification of boot spring configurations */ @@ -95,7 +100,7 @@ { return null; } - + protected Properties getPostProcessProperties() { return new Properties(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/util/system/ClassLoaderSystemResourceUtilImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/util/system/ClassLoaderSystemResourceUtilImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/util/system/ClassLoaderSystemResourceUtilImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,29 +26,30 @@ *

        * * @author Scott T. Weaver - * @version $Id: ClassLoaderSystemResourceUtilImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: ClassLoaderSystemResourceUtilImpl.java 516448 2007-03-09 + * 16:25:47Z ate $ + * */ public class ClassLoaderSystemResourceUtilImpl implements SystemResourceUtil { - - private ClassLoader cl; - - /** - * - * @param cl ClassLoader that will be used to locate a resource - */ - public ClassLoaderSystemResourceUtilImpl(ClassLoader cl) - { - this.cl = cl; - } + private ClassLoader cl; /** + * + * @param cl + * ClassLoader that will be used to locate a resource + */ + public ClassLoaderSystemResourceUtilImpl(ClassLoader cl) + { + this.cl = cl; + } + + /** * For this implementation, always returns "/" */ public String getSystemRoot() - { + { return "/"; } @@ -56,13 +57,13 @@ * @see org.apache.jetspeed.components.util.system.SystemResourceUtil#getURL(java.lang.String) */ public URL getURL(String relativePath) throws MalformedURLException - { + { return cl.getResource(convertFSSeperatorToSlash(relativePath)); } - + private String convertFSSeperatorToSlash(String path) { - return path.replace(File.separatorChar, '/'); + return path.replace(File.separatorChar, '/'); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/util/system/FSSystemResourceUtilImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/util/system/FSSystemResourceUtilImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/util/system/FSSystemResourceUtilImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,21 +26,22 @@ * FSSystemResourceUtilImpl *

        *

        - * Locates resources relative to the root file system path + * Locates resources relative to the root file system path *

        * * @author Scott T. Weaver * @version $Id: FSSystemResourceUtilImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class FSSystemResourceUtilImpl implements SystemResourceUtil { + private String systemRoot; /** * - * @param systemRoot The root from which all resource - * URLs will be constructed. + * @param systemRoot + * The root from which all resource URLs will be constructed. */ public FSSystemResourceUtilImpl(String systemRoot) throws IOException { @@ -48,11 +49,11 @@ // Append trailing seperator if (endsWithSeperator(absPath)) { - this.systemRoot = absPath; + this.systemRoot = absPath; } else { - this.systemRoot = absPath + File.separator; + this.systemRoot = absPath + File.separator; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/util/system/SystemResourceUtil.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/util/system/SystemResourceUtil.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/components/util/system/SystemResourceUtil.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,30 +25,32 @@ * SystemResourceUtil *

        *

        - * This is a simple component that allows location of system resources - * based on implementation. Sources could be anyone or combination of: - * the file system, classloaders, VFS source (see the Virtual File System - * project: http://jakarta.apache.org/commons/sandbox/vfs/) + * This is a simple component that allows location of system resources based on + * implementation. Sources could be anyone or combination of: the file system, + * classloaders, VFS source (see the Virtual File System project: + * http://jakarta.apache.org/commons/sandbox/vfs/) *

        * * @author Scott T. Weaver * @version $Id: SystemResourceUtil.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface SystemResourceUtil { - /** - * - * @return The root from were this system is running - */ - String getSystemRoot(); - - /** - * Creates a fully qualified path to the relativePath - * as a {@link java.net.URL} - * @param relativePath - * @return - */ - URL getURL(String relativePath) throws MalformedURLException; + /** + * + * @return The root from were this system is running + */ + String getSystemRoot(); + + /** + * Creates a fully qualified path to the relativePath as a + * {@link java.net.URL} + * + * @param relativePath + * @return + */ + URL getURL(String relativePath) throws MalformedURLException; + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/mocks/BaseMockServletContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/mocks/BaseMockServletContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/mocks/BaseMockServletContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,160 +23,87 @@ import com.mockrunner.mock.web.MockServletContext; - -public abstract class BaseMockServletContext extends MockServletContext implements ServletContext +public abstract class BaseMockServletContext extends MockServletContext + implements ServletContext { + private final Map attributes = new HashMap(); public BaseMockServletContext() { super(); } + public Object getAttribute(String arg0) { return attributes.get(arg0); } /* - public Enumeration getAttributeNames() - { - unsupported(); - return null; - } - - public ServletContext getContext(String arg0) - { - unsupported(); - return null; - } - - public String getInitParameter(String arg0) - { - unsupported(); - return null; - } - - public Enumeration getInitParameterNames() - { - unsupported(); - return null; - } - - public int getMajorVersion() - { - return 2; - } - - public String getMimeType(String arg0) - { - unsupported(); - return null; - } - - public int getMinorVersion() - { - return 3; - } - - public RequestDispatcher getNamedDispatcher(String arg0) - { - unsupported(); - return null; - } - - public String getRealPath(String arg0) - { - unsupported(); - return null; - } - - public RequestDispatcher getRequestDispatcher(String arg0) - { - unsupported(); - return null; - } - - public URL getResource(String arg0) throws MalformedURLException - { - unsupported(); - return null; - } - - public InputStream getResourceAsStream(String arg0) - { - unsupported(); - return null; - } - - public Set getResourcePaths(String arg0) - { - unsupported(); - return null; - } - - public String getServerInfo() - { - unsupported(); - return null; - } - - public Servlet getServlet(String arg0) throws ServletException - { - unsupported(); - return null; - } - - public String getServletContextName() - { - unsupported(); - return null; - } - - public Enumeration getServletNames() - { - unsupported(); - return null; - } - - public Enumeration getServlets() - { - unsupported(); - return null; - } - - public void log(Exception arg0, String arg1) - { - unsupported(); - - } - - public void log(String arg0, Throwable arg1) - { - unsupported(); - - } - - public void log(String arg0) - { - unsupported(); - - } -*/ + * public Enumeration getAttributeNames() { unsupported(); return null; } + * + * public ServletContext getContext(String arg0) { unsupported(); return + * null; } + * + * public String getInitParameter(String arg0) { unsupported(); return null; } + * + * public Enumeration getInitParameterNames() { unsupported(); return null; } + * + * public int getMajorVersion() { return 2; } + * + * public String getMimeType(String arg0) { unsupported(); return null; } + * + * public int getMinorVersion() { return 3; } + * + * public RequestDispatcher getNamedDispatcher(String arg0) { unsupported(); + * return null; } + * + * public String getRealPath(String arg0) { unsupported(); return null; } + * + * public RequestDispatcher getRequestDispatcher(String arg0) { + * unsupported(); return null; } + * + * public URL getResource(String arg0) throws MalformedURLException { + * unsupported(); return null; } + * + * public InputStream getResourceAsStream(String arg0) { unsupported(); + * return null; } + * + * public Set getResourcePaths(String arg0) { unsupported(); return null; } + * + * public String getServerInfo() { unsupported(); return null; } + * + * public Servlet getServlet(String arg0) throws ServletException { + * unsupported(); return null; } + * + * public String getServletContextName() { unsupported(); return null; } + * + * public Enumeration getServletNames() { unsupported(); return null; } + * + * public Enumeration getServlets() { unsupported(); return null; } + * + * public void log(Exception arg0, String arg1) { unsupported(); } + * + * public void log(String arg0, Throwable arg1) { unsupported(); } + * + * public void log(String arg0) { unsupported(); } + */ public void removeAttribute(String arg0) { attributes.remove(arg0); - + } public void setAttribute(String arg0, Object arg1) { attributes.put(arg0, arg1); - + } - + protected final void unsupported() throws UnsupportedOperationException { - throw new UnsupportedOperationException("The method called has not been implemented."); + throw new UnsupportedOperationException( + "The method called has not been implemented."); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/mocks/ResourceLocatingRequestDispatcher.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/mocks/ResourceLocatingRequestDispatcher.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/mocks/ResourceLocatingRequestDispatcher.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,11 +27,15 @@ public class ResourceLocatingRequestDispatcher extends MockRequestDispatcher { + protected Servlet servlet; + protected String path; + protected String info; - public ResourceLocatingRequestDispatcher(Servlet servlet, String path, String info) + public ResourceLocatingRequestDispatcher(Servlet servlet, String path, + String info) { super(); this.servlet = servlet; @@ -39,7 +43,8 @@ this.info = info; } - public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException + public void include(ServletRequest request, ServletResponse response) + throws ServletException, IOException { super.include(request, response); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/mocks/ResourceLocatingServletContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/mocks/ResourceLocatingServletContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/mocks/ResourceLocatingServletContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -46,29 +46,34 @@ public class ResourceLocatingServletContext extends BaseMockServletContext { - protected final static Log log = LogFactory.getLog(ResourceLocatingServletContext.class); - + + protected final static Log log = LogFactory + .getLog(ResourceLocatingServletContext.class); + private final File rootPath; + private final Map pathOverrides = new HashMap(); + private final List servletInfoList = new ArrayList(); + private final List servletMappingInfoList = new ArrayList(); + private final Map servletInstanceMap = new HashMap(); - + public ResourceLocatingServletContext(File rootPath) { - super(); + super(); this.rootPath = rootPath; } - + public ResourceLocatingServletContext(File rootPath, boolean loadServlet) { super(); this.rootPath = rootPath; - if (loadServlet) - loadServlets(); + if (loadServlet) loadServlets(); } - + public final void addPathOverride(String path, File file) { pathOverrides.put(path, file); @@ -76,21 +81,21 @@ public URL getResource(String path) throws MalformedURLException { - if(pathOverrides.containsKey(path)) - { - return ((File)pathOverrides.get(path)).toURL(); - } - else - { - return new File(rootPath, path).toURL(); - } + if (pathOverrides.containsKey(path)) + { + return ((File) pathOverrides.get(path)).toURL(); + } + else + { + return new File(rootPath, path).toURL(); + } } public String getRealPath(String path) { - if(pathOverrides.containsKey(path)) + if (pathOverrides.containsKey(path)) { - return ((File)pathOverrides.get(path)).getAbsolutePath(); + return ((File) pathOverrides.get(path)).getAbsolutePath(); } else { @@ -114,30 +119,31 @@ public Set getResourcePaths(String path) { - File start = new File(rootPath, path); + File start = new File(rootPath, path); File[] children = start.listFiles(); HashSet pathes = new HashSet(); - for(int i=0; i < children.length; i++) + for (int i = 0; i < children.length; i++) { File child = children[i]; - String relativePath = child.getPath().substring(rootPath.getPath().length()).replace('\\','/'); - - if(child.isDirectory()) - { - pathes.add(relativePath+"/"); + String relativePath = child.getPath().substring( + rootPath.getPath().length()).replace('\\', '/'); + + if (child.isDirectory()) + { + pathes.add(relativePath + "/"); } else { pathes.add(relativePath); } } - + Iterator itr = pathOverrides.keySet().iterator(); - while(itr.hasNext()) + while (itr.hasNext()) { pathes.add(itr.next()); } - + return pathes; } @@ -145,10 +151,8 @@ { Servlet servlet = findServletByPath(arg0); - if (servlet == null) - { - throw new IllegalArgumentException("Failed to find servlet for the path: " + arg0); - } + if (servlet == null) { throw new IllegalArgumentException( + "Failed to find servlet for the path: " + arg0); } return new ResourceLocatingRequestDispatcher(servlet, arg0, null); } @@ -157,47 +161,57 @@ { Servlet servlet = null; - for (Iterator it = this.servletMappingInfoList.iterator(); it.hasNext(); ) + for (Iterator it = this.servletMappingInfoList.iterator(); it.hasNext();) { - ServletMappingInfo servletMappingInfo = (ServletMappingInfo) it.next(); + ServletMappingInfo servletMappingInfo = (ServletMappingInfo) it + .next(); Pattern pattern = servletMappingInfo.getPattern(); if (pattern != null) { PatternMatcher matcher = new Perl5Matcher(); - - if ((matcher.matches(path, pattern)) || (matcher.matches(path + "/", pattern))) + + if ((matcher.matches(path, pattern)) + || (matcher.matches(path + "/", pattern))) { - servlet = (Servlet) this.servletInstanceMap.get(servletMappingInfo.getServletName()); + servlet = (Servlet) this.servletInstanceMap + .get(servletMappingInfo.getServletName()); break; } } } - + return servlet; } - protected void loadServlets() + protected void loadServlets() { this.servletInfoList.clear(); this.servletMappingInfoList.clear(); Digester digester = new Digester(); - + digester.addObjectCreate("web-app/servlet", ServletInfo.class); - digester.addBeanPropertySetter("web-app/servlet/servlet-name", "servletName"); - digester.addBeanPropertySetter("web-app/servlet/servlet-class", "servletClass"); + digester.addBeanPropertySetter("web-app/servlet/servlet-name", + "servletName"); + digester.addBeanPropertySetter("web-app/servlet/servlet-class", + "servletClass"); digester.addCallMethod("web-app/servlet/init-param", "addInitParam", 2); digester.addCallParam("web-app/servlet/init-param/param-name", 0); digester.addCallParam("web-app/servlet/init-param/param-value", 1); - digester.addRule("web-app/servlet", new ServletRule(this.servletInfoList)); - - digester.addObjectCreate("web-app/servlet-mapping", ServletMappingInfo.class); - digester.addBeanPropertySetter("web-app/servlet-mapping/servlet-name", "servletName"); - digester.addBeanPropertySetter("web-app/servlet-mapping/url-pattern", "urlPattern"); - digester.addRule("web-app/servlet-mapping", new ServletMappingRule(this.servletMappingInfoList)); + digester.addRule("web-app/servlet", new ServletRule( + this.servletInfoList)); - File webInfPath = new File(this.rootPath, "WEB-INF"); + digester.addObjectCreate("web-app/servlet-mapping", + ServletMappingInfo.class); + digester.addBeanPropertySetter("web-app/servlet-mapping/servlet-name", + "servletName"); + digester.addBeanPropertySetter("web-app/servlet-mapping/url-pattern", + "urlPattern"); + digester.addRule("web-app/servlet-mapping", new ServletMappingRule( + this.servletMappingInfoList)); + + File webInfPath = new File(this.rootPath, "WEB-INF"); File webDescriptorFile = new File(webInfPath, "web.xml"); log.debug("parsing webDescriptorFile: " + webDescriptorFile); @@ -207,96 +221,111 @@ } catch (Exception e) { - log.error("Failed to parse webDescriptorFile: " + webDescriptorFile, e); + log.error( + "Failed to parse webDescriptorFile: " + webDescriptorFile, + e); } - - for (Iterator it = this.servletInfoList.iterator(); it.hasNext(); ) + + for (Iterator it = this.servletInfoList.iterator(); it.hasNext();) { ServletInfo servletInfo = (ServletInfo) it.next(); - + try { - Servlet servlet = (Servlet) Class.forName(servletInfo.getServletClass()).newInstance(); + Servlet servlet = (Servlet) Class.forName( + servletInfo.getServletClass()).newInstance(); MockServletConfig servletConfig = new MockServletConfig(); servletConfig.setServletContext(this); - + Map initParamMap = servletInfo.getInitParamMap(); - - for (Iterator itParam = initParamMap.keySet().iterator(); itParam.hasNext(); ) + + for (Iterator itParam = initParamMap.keySet().iterator(); itParam + .hasNext();) { String paramName = (String) itParam.next(); String paramValue = (String) initParamMap.get(paramName); servletConfig.setInitParameter(paramName, paramValue); } - + servlet.init(servletConfig); - - this.servletInstanceMap.put(servletInfo.getServletName(), servlet); + + this.servletInstanceMap.put(servletInfo.getServletName(), + servlet); } catch (Exception e) { - log.error("Failed to load and initialize servlet: " + servletInfo); + log.error("Failed to load and initialize servlet: " + + servletInfo); } } } - public static class ServletInfo + public static class ServletInfo { + protected String servletName; + protected String servletClass; + protected Map initParamMap = new HashMap(); - public void setServletName(String servletName) + public void setServletName(String servletName) { this.servletName = servletName; } - - public String getServletName() + + public String getServletName() { return this.servletName; } - public void setServletClass(String servletClass) + public void setServletClass(String servletClass) { this.servletClass = servletClass; } - public String getServletClass() + public String getServletClass() { return this.servletClass; } - public void addInitParam(String paramName, String paramValue) + public void addInitParam(String paramName, String paramValue) { this.initParamMap.put(paramName, paramValue); } - public Map getInitParamMap() { + public Map getInitParamMap() + { return this.initParamMap; } - public String toString() { - return "ServletInfo [" + this.servletName + ", " + this.servletClass + ", " + this.initParamMap + "]"; + public String toString() + { + return "ServletInfo [" + this.servletName + ", " + + this.servletClass + ", " + this.initParamMap + "]"; } } - public static class ServletMappingInfo + public static class ServletMappingInfo { + protected String servletName; + protected String urlPattern; + protected Pattern pattern; - public void setServletName(String servletName) + public void setServletName(String servletName) { this.servletName = servletName; } - public String getServletName() + public String getServletName() { return this.servletName; } - public void setUrlPattern(String urlPattern) + public void setUrlPattern(String urlPattern) { this.urlPattern = urlPattern; this.pattern = null; @@ -312,7 +341,7 @@ } } - public String getUrlPattern() + public String getUrlPattern() { return this.urlPattern; } @@ -322,13 +351,16 @@ return this.pattern; } - public String toString() { - return "ServletMappingInfo [" + this.urlPattern + ", " + this.servletName + "]"; + public String toString() + { + return "ServletMappingInfo [" + this.urlPattern + ", " + + this.servletName + "]"; } } - - public static class ServletRule extends Rule + + public static class ServletRule extends Rule { + private List servletInfoList; public ServletRule(List servletInfoList) @@ -336,7 +368,7 @@ this.servletInfoList = servletInfoList; } - public void end(String namespace, String name) + public void end(String namespace, String name) { try { @@ -352,6 +384,7 @@ public static class ServletMappingRule extends Rule { + private List servletMappingInfoList; public ServletMappingRule(List servletMappingInfoList) @@ -359,11 +392,12 @@ this.servletMappingInfoList = servletMappingInfoList; } - public void end(String namespace, String name) + public void end(String namespace, String name) { - try + try { - ServletMappingInfo servletMappingInfo = (ServletMappingInfo) digester.peek(0); + ServletMappingInfo servletMappingInfo = (ServletMappingInfo) digester + .peek(0); this.servletMappingInfoList.add(servletMappingInfo); } catch (Exception e) @@ -373,5 +407,4 @@ } } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/AbstractTestHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/AbstractTestHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/AbstractTestHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,6 +29,7 @@ public abstract class AbstractTestHelper implements TestHelper { + public static final String APP_CONTEXT = "AppContext"; private final Map context; @@ -38,7 +39,8 @@ { try { - File userBuildFile = new File(System.getProperty("user.home"), "build.properties"); + File userBuildFile = new File(System.getProperty("user.home"), + "build.properties"); Configuration userBuildProps = loadConfiguration(userBuildFile); File mavenBuildFile = new File("../../build.properties"); @@ -55,11 +57,13 @@ catch (ConfigurationException e) { - throw new IllegalStateException("Unable to load ${USER_HOME}/build.properties"); + throw new IllegalStateException( + "Unable to load ${USER_HOME}/build.properties"); } } - private static Configuration loadConfiguration(File propsFile) throws ConfigurationException + private static Configuration loadConfiguration(File propsFile) + throws ConfigurationException { if (propsFile.exists()) { @@ -75,7 +79,7 @@ { this.context = context; } - + public AbstractTestHelper() { context = new HashMap(); @@ -104,7 +108,8 @@ protected final void addBeanFactory(ConfigurableBeanFactory bf) { - ConfigurableBeanFactory currentBf = (ConfigurableBeanFactory) context.get(APP_CONTEXT); + ConfigurableBeanFactory currentBf = (ConfigurableBeanFactory) context + .get(APP_CONTEXT); if (currentBf != null) { bf.setParentBeanFactory(currentBf); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/BuildPropertiesHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/BuildPropertiesHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/BuildPropertiesHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,26 +18,30 @@ /** *

        - * This helper class provides access to the properties configured for the build process. + * This helper class provides access to the properties configured for the build + * process. *

          *
        • build.properties
        • - *
        • project.properties
        • + *
        • project.properties + *
        • *
        *

        + * * @author David Le Strat - * + * */ public class BuildPropertiesHelper extends AbstractTestHelper { + public BuildPropertiesHelper() { } - + public void tearDown() { // Do nothing. } - + public void setUp() { // Do nothing. Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/DatasourceHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/DatasourceHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/DatasourceHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,8 +21,9 @@ import org.apache.commons.dbcp.BasicDataSource; /** - * This helper adds a "datasource" based on the maven build.properties/project.properties database settings passed to - * the test case, (see AbstractTestHelper). + * This helper adds a "datasource" based on the maven + * build.properties/project.properties database settings passed to the test + * case, (see AbstractTestHelper). * * @author Scott T. Weaver */ @@ -50,10 +51,14 @@ public void setUp() throws Exception { datasource = new BasicDataSource(); - datasource.setDriverClassName(getUserProperty(ORG_APACHE_JETSPEED_TEST_DATABASE_DRIVER)); - datasource.setUrl(getUserProperty(ORG_APACHE_JETSPEED_TEST_DATABASE_URL)); - datasource.setUsername(getUserProperty(ORG_APACHE_JETSPEED_TEST_DATABASE_USER)); - datasource.setPassword(getUserProperty(ORG_APACHE_JETSPEED_TEST_DATABASE_PASSWORD)); + datasource + .setDriverClassName(getUserProperty(ORG_APACHE_JETSPEED_TEST_DATABASE_DRIVER)); + datasource + .setUrl(getUserProperty(ORG_APACHE_JETSPEED_TEST_DATABASE_URL)); + datasource + .setUsername(getUserProperty(ORG_APACHE_JETSPEED_TEST_DATABASE_USER)); + datasource + .setPassword(getUserProperty(ORG_APACHE_JETSPEED_TEST_DATABASE_PASSWORD)); getContext().put(DATASOURCE_KEY, datasource); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/OJBHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/OJBHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/OJBHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,9 +21,9 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.support.GenericApplicationContext; -import org.springframework.transaction.interceptor.TransactionProxyFactoryBean; import org.springframework.orm.ojb.PersistenceBrokerTransactionManager; import org.springframework.orm.ojb.support.LocalOjbConfigurer; +import org.springframework.transaction.interceptor.TransactionProxyFactoryBean; public class OJBHelper extends DatasourceHelper { @@ -59,8 +59,9 @@ } /** - * Surrounds the object with TransactionProxyFactoryBean that implements all - * interfaces specified in interfacesToProxyAs + * Surrounds the object with + * TransactionProxyFactoryBean that implements all interfaces + * specified in interfacesToProxyAs * * @param object * object to wrap with a TX Proxy @@ -69,11 +70,13 @@ * @return Tx Wrapped version of the priginal object * @throws Exception */ - public Object getTxProxiedObject(Object object, String[] interfacesToProxyAs) throws Exception + public Object getTxProxiedObject(Object object, String[] interfacesToProxyAs) + throws Exception { Class[] ifaces = new Class[interfacesToProxyAs.length]; - for(int i = 0; i < interfacesToProxyAs.length; i++) { - ifaces[i] = Class.forName(interfacesToProxyAs[i]); + for (int i = 0; i < interfacesToProxyAs.length; i++) + { + ifaces[i] = Class.forName(interfacesToProxyAs[i]); } TransactionProxyFactoryBean txfb = new TransactionProxyFactoryBean(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/TestHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/TestHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/java/org/apache/jetspeed/testhelpers/TestHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,10 +20,11 @@ public interface TestHelper { + public void setUp() throws Exception; - + public void tearDown() throws Exception; - + public Map getContext(); - - } + +} Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/TestContentCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/TestContentCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/TestContentCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,7 +16,6 @@ */ package org.apache.jetspeed.cache; -import java.io.CharArrayWriter; import java.io.PrintWriter; import java.security.Principal; import java.util.LinkedList; @@ -27,7 +26,6 @@ import net.sf.ehcache.CacheManager; import org.apache.jetspeed.aggregator.PortletContent; -import org.apache.jetspeed.aggregator.PortletRenderer; import org.apache.jetspeed.cache.impl.EhPortletContentCacheImpl; import org.apache.jetspeed.cache.impl.JetspeedCacheKeyGenerator; import org.apache.jetspeed.mockobjects.request.MockRequestContext; @@ -41,37 +39,41 @@ * Test Content Cache *

        *

        - * + * *

        + * * @author Scott T. Weaver * @version $Id: TestCachingInterceptors.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class TestContentCache extends TestCase { - + public void testContentCacheByUser() throws Exception { // initialize ehCache CacheManager cacheManager = new CacheManager(); - Cache ehContentCache = new Cache("ehPortletContentCache", 10000, false, false, 28800, 28800); + Cache ehContentCache = new Cache("ehPortletContentCache", 10000, false, + false, 28800, 28800); cacheManager.addCache(ehContentCache); - ehContentCache.setCacheManager(cacheManager); - + ehContentCache.setCacheManager(cacheManager); + // initial Jetspeed caches List segments = new LinkedList(); segments.add("username"); segments.add("pipeline"); segments.add("windowid"); - ContentCacheKeyGenerator generator = new JetspeedCacheKeyGenerator(segments); - JetspeedCache contentCache = new EhPortletContentCacheImpl(ehContentCache, generator); - + ContentCacheKeyGenerator generator = new JetspeedCacheKeyGenerator( + segments); + JetspeedCache contentCache = new EhPortletContentCacheImpl( + ehContentCache, generator); + // create the mock request context - MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setUserPrincipal(new MockPrincipal("david")); MockRequestContext context = new MockRequestContext(request, response); - + // create a simple key String window1 = "555-01"; ContentCacheKey cckey1 = contentCache.createCacheKey(context, window1); @@ -82,17 +84,19 @@ context.getParameterMap().put("encoder", "desktop"); ContentCacheKey cckey2 = contentCache.createCacheKey(context, window2); assertEquals(cckey2.getKey(), "david/desktop/555-02"); - + // create some PortletContent mock objects - PortletContent content1 = new MockPortletContent(cckey1, 100, "ContentOne", "content1content1content1content1"); - PortletContent content2 = new MockPortletContent(cckey2, 200, "ContentTwo", "content2content2content2content2"); - + PortletContent content1 = new MockPortletContent(cckey1, 100, + "ContentOne", "content1content1content1content1"); + PortletContent content2 = new MockPortletContent(cckey2, 200, + "ContentTwo", "content2content2content2content2"); + // put it in the cache CacheElement element1 = contentCache.createElement(cckey1, content1); contentCache.put(element1); CacheElement element2 = contentCache.createElement(cckey2, content2); contentCache.put(element2); - + // assert the gets Object result1 = contentCache.get(cckey1); assertNotNull(result1); @@ -100,18 +104,17 @@ Object result2 = contentCache.get(cckey2); assertNotNull(result2); System.out.println("result 2 = " + result2); - - // assert isKey Apis + + // assert isKey Apis assertTrue(contentCache.isKeyInCache(cckey1)); - - + // test removes contentCache.remove(cckey1); - assertFalse(contentCache.isKeyInCache(cckey1)); + assertFalse(contentCache.isKeyInCache(cckey1)); assertTrue(contentCache.isKeyInCache(cckey2)); - + // test user stuff - request.setUserPrincipal(new MockPrincipal("sean")); + request.setUserPrincipal(new MockPrincipal("sean")); // create a simple key String window3 = "555-03"; ContentCacheKey cckey3 = contentCache.createCacheKey(context, window3); @@ -121,11 +124,13 @@ String window4 = "555-04"; ContentCacheKey cckey4 = contentCache.createCacheKey(context, window4); assertEquals(cckey4.getKey(), "sean/desktop/555-04"); - + // create some PortletContent mock objects - PortletContent content3 = new MockPortletContent(cckey3, 300, "ContentThree", "content3content3content3content3"); - PortletContent content4 = new MockPortletContent(cckey4, 400, "ContentTwo", "content4content4content4content4"); - + PortletContent content3 = new MockPortletContent(cckey3, 300, + "ContentThree", "content3content3content3content3"); + PortletContent content4 = new MockPortletContent(cckey4, 400, + "ContentTwo", "content4content4content4content4"); + // put it in the cache CacheElement element3 = contentCache.createElement(cckey3, content3); contentCache.put(element3); @@ -135,32 +140,35 @@ // assert 3 and 4 assertTrue(contentCache.isKeyInCache(cckey3)); assertTrue(contentCache.isKeyInCache(cckey4)); - + // remove for user contentCache.evictContentForUser("sean"); assertFalse(contentCache.isKeyInCache(cckey3)); assertFalse(contentCache.isKeyInCache(cckey4)); - assertTrue(contentCache.isKeyInCache(cckey2)); + assertTrue(contentCache.isKeyInCache(cckey2)); } public void testContentCacheBySession() throws Exception { // initialize ehCache CacheManager cacheManager = new CacheManager(); - Cache ehContentCache = new Cache("ehPortletContentCache", 10000, false, false, 28800, 28800); + Cache ehContentCache = new Cache("ehPortletContentCache", 10000, false, + false, 28800, 28800); cacheManager.addCache(ehContentCache); - ehContentCache.setCacheManager(cacheManager); - + ehContentCache.setCacheManager(cacheManager); + // initial Jetspeed caches List segments = new LinkedList(); segments.add("sessionid"); segments.add("pipeline"); segments.add("windowid"); - ContentCacheKeyGenerator generator = new JetspeedCacheKeyGenerator(segments); - JetspeedCache contentCache = new EhPortletContentCacheImpl(ehContentCache, generator); - + ContentCacheKeyGenerator generator = new JetspeedCacheKeyGenerator( + segments); + JetspeedCache contentCache = new EhPortletContentCacheImpl( + ehContentCache, generator); + // create the mock request context - MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setUserPrincipal(new MockPrincipal("david")); MockHttpSession session = new MockHttpSession(); @@ -168,7 +176,7 @@ String sessionId = session.getId(); MockRequestContext context = new MockRequestContext(request, response); - + // create a simple key String window1 = "555-01"; ContentCacheKey cckey1 = contentCache.createCacheKey(context, window1); @@ -179,17 +187,19 @@ context.getParameterMap().put("encoder", "desktop"); ContentCacheKey cckey2 = contentCache.createCacheKey(context, window2); assertEquals(cckey2.getKey(), sessionId + "/desktop/555-02"); - + // create some PortletContent mock objects - PortletContent content1 = new MockPortletContent(cckey1, 100, "ContentOne", "content1content1content1content1"); - PortletContent content2 = new MockPortletContent(cckey2, 200, "ContentTwo", "content2content2content2content2"); - + PortletContent content1 = new MockPortletContent(cckey1, 100, + "ContentOne", "content1content1content1content1"); + PortletContent content2 = new MockPortletContent(cckey2, 200, + "ContentTwo", "content2content2content2content2"); + // put it in the cache CacheElement element1 = contentCache.createElement(cckey1, content1); contentCache.put(element1); CacheElement element2 = contentCache.createElement(cckey2, content2); contentCache.put(element2); - + // assert the gets Object result1 = contentCache.get(cckey1); assertNotNull(result1); @@ -197,21 +207,20 @@ Object result2 = contentCache.get(cckey2); assertNotNull(result2); System.out.println("result 2 = " + result2); - - // assert isKey Apis + + // assert isKey Apis assertTrue(contentCache.isKeyInCache(cckey1)); - - + // test removes contentCache.remove(cckey1); - assertFalse(contentCache.isKeyInCache(cckey1)); + assertFalse(contentCache.isKeyInCache(cckey1)); assertTrue(contentCache.isKeyInCache(cckey2)); - + // test user stuff session = new MockHttpSession(); - request.setSession(session); - sessionId = session.getId(); - request.setUserPrincipal(new MockPrincipal("sean")); + request.setSession(session); + sessionId = session.getId(); + request.setUserPrincipal(new MockPrincipal("sean")); // create a simple key String window3 = "555-03"; ContentCacheKey cckey3 = contentCache.createCacheKey(context, window3); @@ -221,11 +230,13 @@ String window4 = "555-04"; ContentCacheKey cckey4 = contentCache.createCacheKey(context, window4); assertEquals(cckey4.getKey(), sessionId + "/desktop/555-04"); - + // create some PortletContent mock objects - PortletContent content3 = new MockPortletContent(cckey3, 300, "ContentThree", "content3content3content3content3"); - PortletContent content4 = new MockPortletContent(cckey4, 400, "ContentTwo", "content4content4content4content4"); - + PortletContent content3 = new MockPortletContent(cckey3, 300, + "ContentThree", "content3content3content3content3"); + PortletContent content4 = new MockPortletContent(cckey4, 400, + "ContentTwo", "content4content4content4content4"); + // put it in the cache CacheElement element3 = contentCache.createElement(cckey3, content3); contentCache.put(element3); @@ -235,38 +246,45 @@ // assert 3 and 4 assertTrue(contentCache.isKeyInCache(cckey3)); assertTrue(contentCache.isKeyInCache(cckey4)); - + // remove for user contentCache.evictContentForSession(sessionId); assertFalse(contentCache.isKeyInCache(cckey3)); assertFalse(contentCache.isKeyInCache(cckey4)); - assertTrue(contentCache.isKeyInCache(cckey2)); + assertTrue(contentCache.isKeyInCache(cckey2)); } - + class MockPrincipal implements Principal { + private String name; + public MockPrincipal(String name) { this.name = name; } - + public String getName() { return name; } } - + class MockPortletContent implements PortletContent { + private boolean complete = false; + private ContentCacheKey cacheKey; + private int expiration = 0; + private String title; + private String content; - - - MockPortletContent(ContentCacheKey cacheKey, int expiration, String title, String content) + + MockPortletContent(ContentCacheKey cacheKey, int expiration, + String title, String content) { this.cacheKey = cacheKey; this.expiration = expiration; @@ -274,7 +292,6 @@ this.content = content; } - public PrintWriter getWriter() { return null; @@ -293,7 +310,7 @@ return content; } - public void writeTo( java.io.Writer out ) throws java.io.IOException + public void writeTo(java.io.Writer out) throws java.io.IOException { } @@ -311,54 +328,55 @@ { this.complete = state; } - + public String getContent() { return toString(); } + /** *

        * complete *

        - * + * * @see org.apache.jetspeed.aggregator.PortletContent#complete() * */ public void complete() { - setComplete(true, true); + setComplete(true, true); } - - // error case, don't notify + + // error case, don't notify public void completeWithError() { setComplete(true, false); } - + public ContentCacheKey getCacheKey() { return cacheKey; } - + public int getExpiration() { return expiration; } - + public void setExpiration(int expiration) { this.expiration = expiration; } - + public String getTitle() { return title; } - + public void setTitle(String title) { this.title = title; } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/TestDecorationContentCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/TestDecorationContentCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/TestDecorationContentCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -38,37 +38,41 @@ * Test Content Cache *

        *

        - * + * *

        + * * @author Scott T. Weaver * @version $Id: TestCachingInterceptors.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class TestDecorationContentCache extends TestCase { - + public void testContentCacheByUser() throws Exception { // initialize ehCache CacheManager cacheManager = new CacheManager(); - Cache ehContentCache = new Cache("ehDecorationContentCache", 10000, false, false, 28800, 28800); + Cache ehContentCache = new Cache("ehDecorationContentCache", 10000, + false, false, 28800, 28800); cacheManager.addCache(ehContentCache); - ehContentCache.setCacheManager(cacheManager); - + ehContentCache.setCacheManager(cacheManager); + // initial Jetspeed caches List segments = new LinkedList(); segments.add("username"); segments.add("pipeline"); segments.add("windowid"); - ContentCacheKeyGenerator generator = new JetspeedCacheKeyGenerator(segments); - JetspeedCache contentCache = new EhDecorationContentCacheImpl(ehContentCache, generator); - + ContentCacheKeyGenerator generator = new JetspeedCacheKeyGenerator( + segments); + JetspeedCache contentCache = new EhDecorationContentCacheImpl( + ehContentCache, generator); + // create the mock request context - MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setUserPrincipal(new MockPrincipal("david")); MockRequestContext context = new MockRequestContext(request, response); - + // create a simple key String window1 = "/default-page.psml"; ContentCacheKey cckey1 = contentCache.createCacheKey(context, window1); @@ -79,17 +83,17 @@ context.getParameterMap().put("encoder", "desktop"); ContentCacheKey cckey2 = contentCache.createCacheKey(context, window2); assertEquals(cckey2.getKey(), "david/desktop//about.psml"); - + // create some PortletContent mock objects MockTheme theme1 = new MockTheme("/default-page.psml"); MockTheme theme2 = new MockTheme("/about.psml"); - + // put it in the cache CacheElement element1 = contentCache.createElement(cckey1, theme1); contentCache.put(element1); CacheElement element2 = contentCache.createElement(cckey2, theme2); contentCache.put(element2); - + // assert the gets Object result1 = contentCache.get(cckey1); assertNotNull(result1); @@ -97,18 +101,17 @@ Object result2 = contentCache.get(cckey2); assertNotNull(result2); System.out.println("result 2 = " + result2); - - // assert isKey Apis + + // assert isKey Apis assertTrue(contentCache.isKeyInCache(cckey1)); - // test removes contentCache.remove(cckey1); - assertFalse(contentCache.isKeyInCache(cckey1)); + assertFalse(contentCache.isKeyInCache(cckey1)); assertTrue(contentCache.isKeyInCache(cckey2)); - + // test user stuff - request.setUserPrincipal(new MockPrincipal("sean")); + request.setUserPrincipal(new MockPrincipal("sean")); // create a simple key String window3 = "/default-page.psml"; ContentCacheKey cckey3 = contentCache.createCacheKey(context, window3); @@ -118,11 +121,11 @@ String window4 = "/about.psml"; ContentCacheKey cckey4 = contentCache.createCacheKey(context, window4); assertEquals(cckey4.getKey(), "sean/desktop//about.psml"); - + // create some MockTheme objects MockTheme theme3 = new MockTheme("/default-page.psml"); MockTheme theme4 = new MockTheme("/about.psml"); - + // put it in the cache CacheElement element3 = contentCache.createElement(cckey3, theme3); contentCache.put(element3); @@ -132,32 +135,35 @@ // assert 3 and 4 assertTrue(contentCache.isKeyInCache(cckey3)); assertTrue(contentCache.isKeyInCache(cckey4)); - + // remove for user contentCache.evictContentForUser("sean"); assertFalse(contentCache.isKeyInCache(cckey3)); assertFalse(contentCache.isKeyInCache(cckey4)); - assertTrue(contentCache.isKeyInCache(cckey2)); + assertTrue(contentCache.isKeyInCache(cckey2)); } - + public void testContentCacheBySession() throws Exception { // initialize ehCache CacheManager cacheManager = new CacheManager(); - Cache ehContentCache = new Cache("ehDecorationContentCache", 10000, false, false, 28800, 28800); + Cache ehContentCache = new Cache("ehDecorationContentCache", 10000, + false, false, 28800, 28800); cacheManager.addCache(ehContentCache); - ehContentCache.setCacheManager(cacheManager); - + ehContentCache.setCacheManager(cacheManager); + // initial Jetspeed caches List segments = new LinkedList(); segments.add("sessionid"); segments.add("pipeline"); segments.add("windowid"); - ContentCacheKeyGenerator generator = new JetspeedCacheKeyGenerator(segments); - JetspeedCache contentCache = new EhDecorationContentCacheImpl(ehContentCache, generator); - + ContentCacheKeyGenerator generator = new JetspeedCacheKeyGenerator( + segments); + JetspeedCache contentCache = new EhDecorationContentCacheImpl( + ehContentCache, generator); + // create the mock request context - MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setUserPrincipal(new MockPrincipal("david")); MockHttpSession session = new MockHttpSession(); @@ -165,7 +171,7 @@ String sessionId = session.getId(); MockRequestContext context = new MockRequestContext(request, response); - + // create a simple key String window1 = "/default-page.psml"; ContentCacheKey cckey1 = contentCache.createCacheKey(context, window1); @@ -176,17 +182,17 @@ context.getParameterMap().put("encoder", "desktop"); ContentCacheKey cckey2 = contentCache.createCacheKey(context, window2); assertEquals(cckey2.getKey(), sessionId + "/desktop//about.psml"); - + // create some MockTheme objects MockTheme theme1 = new MockTheme("/default-page.psml"); MockTheme theme2 = new MockTheme("/about.psml"); - + // put it in the cache CacheElement element1 = contentCache.createElement(cckey1, theme1); contentCache.put(element1); CacheElement element2 = contentCache.createElement(cckey2, theme2); contentCache.put(element2); - + // assert the gets Object result1 = contentCache.get(cckey1); assertNotNull(result1); @@ -194,21 +200,20 @@ Object result2 = contentCache.get(cckey2); assertNotNull(result2); System.out.println("result 2 = " + result2); - - // assert isKey Apis + + // assert isKey Apis assertTrue(contentCache.isKeyInCache(cckey1)); - - + // test removes contentCache.remove(cckey1); - assertFalse(contentCache.isKeyInCache(cckey1)); + assertFalse(contentCache.isKeyInCache(cckey1)); assertTrue(contentCache.isKeyInCache(cckey2)); - + // test user stuff session = new MockHttpSession(); - request.setSession(session); - sessionId = session.getId(); - request.setUserPrincipal(new MockPrincipal("sean")); + request.setSession(session); + sessionId = session.getId(); + request.setUserPrincipal(new MockPrincipal("sean")); // create a simple key String window3 = "/default-page.psml"; ContentCacheKey cckey3 = contentCache.createCacheKey(context, window3); @@ -218,11 +223,11 @@ String window4 = "about.psml"; ContentCacheKey cckey4 = contentCache.createCacheKey(context, window4); assertEquals(cckey4.getKey(), sessionId + "/desktop/about.psml"); - + // create some PortletContent mock objects MockTheme theme3 = new MockTheme("/default-page.psml"); MockTheme theme4 = new MockTheme("/about.psml"); - + // put it in the cache CacheElement element3 = contentCache.createElement(cckey3, theme3); contentCache.put(element3); @@ -232,41 +237,44 @@ // assert 3 and 4 assertTrue(contentCache.isKeyInCache(cckey3)); assertTrue(contentCache.isKeyInCache(cckey4)); - + // remove for user contentCache.evictContentForSession(sessionId); assertFalse(contentCache.isKeyInCache(cckey3)); assertFalse(contentCache.isKeyInCache(cckey4)); - assertTrue(contentCache.isKeyInCache(cckey2)); + assertTrue(contentCache.isKeyInCache(cckey2)); } - + class MockPrincipal implements Principal { + private String name; + public MockPrincipal(String name) { this.name = name; } - + public String getName() { return name; } } - + class MockTheme implements Serializable { + private String pageId; - + public MockTheme(String pageId) { this.pageId = pageId; } - + public String toString() { return this.pageId; } - } - + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/TestPortletWindowCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/TestPortletWindowCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/TestPortletWindowCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,27 +33,30 @@ import org.jmock.cglib.MockObjectTestCase; import org.jmock.core.stub.VoidStub; - - /** * * Tests for {@link EhPortletWindowCache}. * * @author Scott T. Weaver - * + * */ public class TestPortletWindowCache extends MockObjectTestCase { + private static final String WINDOW_ID = "window1"; + private static final String ENTITY_ID = "entity1"; - - + private Mock cacheMock; + private Mock windowMock; + private Mock entityMock; + private Mock oidMock; + private Mock entityOidMock; - + protected void setUp() throws Exception { super.setUp(); @@ -62,7 +65,7 @@ entityMock = mock(PortletEntity.class); oidMock = mock(ObjectID.class); entityOidMock = (Mock) mock(ObjectID.class); - } + } public void testSimplePutAndGet() { @@ -71,152 +74,187 @@ Element element = new Element(WINDOW_ID, window); ObjectID oid = (ObjectID) oidMock.proxy(); ObjectID entityOid = (ObjectID) entityOidMock.proxy(); - entityOidMock.expects(atLeastOnce()).method("toString").will(returnValue(ENTITY_ID)); - oidMock.expects(atLeastOnce()).method("toString").will(returnValue(WINDOW_ID)); - windowMock.expects(once()).method("getId").withNoArguments().will(returnValue(oid)); - windowMock.expects(once()).method("getPortletEntity").withNoArguments().will(returnValue(entityMock.proxy())); - entityMock.expects(once()).method("getId").withNoArguments().will(returnValue(entityOid)); + entityOidMock.expects(atLeastOnce()).method("toString").will( + returnValue(ENTITY_ID)); + oidMock.expects(atLeastOnce()).method("toString").will( + returnValue(WINDOW_ID)); + windowMock.expects(once()).method("getId").withNoArguments().will( + returnValue(oid)); + windowMock.expects(once()).method("getPortletEntity").withNoArguments() + .will(returnValue(entityMock.proxy())); + entityMock.expects(once()).method("getId").withNoArguments().will( + returnValue(entityOid)); cacheMock.expects(once()).method("put").with(eq(element)); - cacheMock.expects(atLeastOnce()).method("get").with(eq(WINDOW_ID)).will(returnValue(element)); - - - Ehcache cache = (Ehcache) cacheMock.proxy(); - PortletWindowCache windowCache = new EhPortletWindowCache(cache); + cacheMock.expects(atLeastOnce()).method("get").with(eq(WINDOW_ID)) + .will(returnValue(element)); + + Ehcache cache = (Ehcache) cacheMock.proxy(); + PortletWindowCache windowCache = new EhPortletWindowCache(cache); windowCache.putPortletWindow(window); - + assertNotNull(windowCache.getPortletWindow(WINDOW_ID)); assertEquals(windowCache.getPortletWindow(WINDOW_ID), window); - + verify(); } - + public void testGetByPortletEntity() { - SerializablePortletWindow window = (SerializablePortletWindow) windowMock.proxy(); + SerializablePortletWindow window = (SerializablePortletWindow) windowMock + .proxy(); Element element = new Element(WINDOW_ID, window); - + ObjectID oid = (ObjectID) oidMock.proxy(); - oidMock.expects(atLeastOnce()).method("toString").will(returnValue(WINDOW_ID)); + oidMock.expects(atLeastOnce()).method("toString").will( + returnValue(WINDOW_ID)); ObjectID entityOid = (ObjectID) entityOidMock.proxy(); - entityOidMock.expects(atLeastOnce()).method("toString").will(returnValue(ENTITY_ID)); + entityOidMock.expects(atLeastOnce()).method("toString").will( + returnValue(ENTITY_ID)); cacheMock.expects(once()).method("put").with(eq(element)); - cacheMock.expects(once()).method("get").with(eq(WINDOW_ID)).will(returnValue(element)); - windowMock.expects(once()).method("getId").withNoArguments().will(returnValue(oid)); - windowMock.expects(once()).method("getPortletEntity").withNoArguments().will(returnValue(entityMock.proxy())); - entityMock.expects(once()).method("getId").withNoArguments().will(returnValue(entityOid)); - - Ehcache cache = (Ehcache) cacheMock.proxy(); - PortletWindowCache windowCache = new EhPortletWindowCache(cache); + cacheMock.expects(once()).method("get").with(eq(WINDOW_ID)).will( + returnValue(element)); + windowMock.expects(once()).method("getId").withNoArguments().will( + returnValue(oid)); + windowMock.expects(once()).method("getPortletEntity").withNoArguments() + .will(returnValue(entityMock.proxy())); + entityMock.expects(once()).method("getId").withNoArguments().will( + returnValue(entityOid)); + + Ehcache cache = (Ehcache) cacheMock.proxy(); + PortletWindowCache windowCache = new EhPortletWindowCache(cache); windowCache.putPortletWindow(window); - - PortletWindow fromCache = windowCache.getPortletWindowByEntityId(ENTITY_ID); + + PortletWindow fromCache = windowCache + .getPortletWindowByEntityId(ENTITY_ID); assertNotNull(fromCache); - - verify(); + + verify(); } - + public void testRemove() { - SerializablePortletWindow window = (SerializablePortletWindow) windowMock.proxy(); + SerializablePortletWindow window = (SerializablePortletWindow) windowMock + .proxy(); Element element = new Element(WINDOW_ID, window); - + ObjectID oid = (ObjectID) oidMock.proxy(); - oidMock.expects(atLeastOnce()).method("toString").will(returnValue(WINDOW_ID)); - - ObjectID entityOid = (ObjectID)entityOidMock.proxy(); - entityOidMock.expects(atLeastOnce()).method("toString").will(returnValue(ENTITY_ID)); - + oidMock.expects(atLeastOnce()).method("toString").will( + returnValue(WINDOW_ID)); + + ObjectID entityOid = (ObjectID) entityOidMock.proxy(); + entityOidMock.expects(atLeastOnce()).method("toString").will( + returnValue(ENTITY_ID)); + cacheMock.expects(once()).method("put").with(eq(element)); - cacheMock.expects(exactly(2)).method("get").with(eq(WINDOW_ID)).will(returnValue(element)); - windowMock.expects(once()).method("getId").withNoArguments().will(returnValue(oid)); - windowMock.expects(exactly(2)).method("getPortletEntity").withNoArguments().will(returnValue(entityMock.proxy())); - entityMock.expects(exactly(2)).method("getId").withNoArguments().will(returnValue(entityOid)); - - - cacheMock.expects(once()).method("removeQuiet").with(eq(WINDOW_ID)).will(returnValue(true)); - - - Ehcache cache = (Ehcache) cacheMock.proxy(); - PortletWindowCache windowCache = new EhPortletWindowCache(cache); + cacheMock.expects(exactly(2)).method("get").with(eq(WINDOW_ID)).will( + returnValue(element)); + windowMock.expects(once()).method("getId").withNoArguments().will( + returnValue(oid)); + windowMock.expects(exactly(2)).method("getPortletEntity") + .withNoArguments().will(returnValue(entityMock.proxy())); + entityMock.expects(exactly(2)).method("getId").withNoArguments().will( + returnValue(entityOid)); + + cacheMock.expects(once()).method("removeQuiet").with(eq(WINDOW_ID)) + .will(returnValue(true)); + + Ehcache cache = (Ehcache) cacheMock.proxy(); + PortletWindowCache windowCache = new EhPortletWindowCache(cache); windowCache.putPortletWindow(window); - + windowCache.removePortletWindow(WINDOW_ID); assertNull(windowCache.getPortletWindowByEntityId(ENTITY_ID)); - - verify(); + + verify(); } - + public void testRemoveByEntityId() { - SerializablePortletWindow window = (SerializablePortletWindow) windowMock.proxy(); + SerializablePortletWindow window = (SerializablePortletWindow) windowMock + .proxy(); Element element = new Element(WINDOW_ID, window); - + ObjectID oid = (ObjectID) oidMock.proxy(); - oidMock.expects(atLeastOnce()).method("toString").will(returnValue(WINDOW_ID)); - + oidMock.expects(atLeastOnce()).method("toString").will( + returnValue(WINDOW_ID)); + ObjectID entityOid = (ObjectID) entityOidMock.proxy(); - entityOidMock.expects(atLeastOnce()).method("toString").will(returnValue(ENTITY_ID)); - + entityOidMock.expects(atLeastOnce()).method("toString").will( + returnValue(ENTITY_ID)); + cacheMock.expects(once()).method("put").with(eq(element)); - cacheMock.expects(exactly(3)).method("get").with(eq(WINDOW_ID)).will(onConsecutiveCalls(returnValue(element), returnValue(element), new VoidStub())); - windowMock.expects(exactly(2)).method("getId").withNoArguments().will(returnValue(oid)); - windowMock.expects(once()).method("getPortletEntity").withNoArguments().will(returnValue(entityMock.proxy())); - entityMock.expects(once()).method("getId").withNoArguments().will(returnValue(entityOid)); - - - cacheMock.expects(atLeastOnce()).method("removeQuiet").with(eq(WINDOW_ID)).will(returnValue(true)); - - - Ehcache cache = (Ehcache) cacheMock.proxy(); - PortletWindowCache windowCache = new EhPortletWindowCache(cache); + cacheMock.expects(exactly(3)).method("get").with(eq(WINDOW_ID)).will( + onConsecutiveCalls(returnValue(element), returnValue(element), + new VoidStub())); + windowMock.expects(exactly(2)).method("getId").withNoArguments().will( + returnValue(oid)); + windowMock.expects(once()).method("getPortletEntity").withNoArguments() + .will(returnValue(entityMock.proxy())); + entityMock.expects(once()).method("getId").withNoArguments().will( + returnValue(entityOid)); + + cacheMock.expects(atLeastOnce()).method("removeQuiet").with( + eq(WINDOW_ID)).will(returnValue(true)); + + Ehcache cache = (Ehcache) cacheMock.proxy(); + PortletWindowCache windowCache = new EhPortletWindowCache(cache); windowCache.putPortletWindow(window); - + windowCache.removePortletWindowByPortletEntityId(ENTITY_ID); assertNull(windowCache.getPortletWindow(WINDOW_ID)); - - verify(); + + verify(); } - + public void testGetAllPortletWindows() - { + { PortletWindow window = (PortletWindow) windowMock.proxy(); - PortletWindow window2 = (PortletWindow) mock(SerializablePortletWindow.class).proxy(); - PortletWindow window3 = (PortletWindow) mock(SerializablePortletWindow.class).proxy(); - - List keys = Arrays.asList(new String[] {WINDOW_ID, "window2", "window3"}); - - cacheMock.expects(once()).method("getKeys").withNoArguments().will(returnValue(keys)); - cacheMock.expects(once()).method("get").with(eq(WINDOW_ID)).will(returnValue(new Element(WINDOW_ID, window))); - cacheMock.expects(once()).method("get").with(eq("window2")).will(returnValue(new Element("window2", window2))); - cacheMock.expects(once()).method("get").with(eq("window3")).will(returnValue(new Element("window3", window3))); - - PortletWindowCache windowCache = new EhPortletWindowCache((Ehcache) cacheMock.proxy()); - + PortletWindow window2 = (PortletWindow) mock( + SerializablePortletWindow.class).proxy(); + PortletWindow window3 = (PortletWindow) mock( + SerializablePortletWindow.class).proxy(); + + List keys = Arrays.asList(new String[] + {WINDOW_ID, "window2", "window3"}); + + cacheMock.expects(once()).method("getKeys").withNoArguments().will( + returnValue(keys)); + cacheMock.expects(once()).method("get").with(eq(WINDOW_ID)).will( + returnValue(new Element(WINDOW_ID, window))); + cacheMock.expects(once()).method("get").with(eq("window2")).will( + returnValue(new Element("window2", window2))); + cacheMock.expects(once()).method("get").with(eq("window3")).will( + returnValue(new Element("window3", window3))); + + PortletWindowCache windowCache = new EhPortletWindowCache( + (Ehcache) cacheMock.proxy()); + Set allPortletWindows = windowCache.getAllPortletWindows(); assertNotNull(allPortletWindows); assertEquals(3, allPortletWindows.size()); } - + public void testUnexpected() { -// PortletWindowCache windowCache = new EhPortletWindowCache((Ehcache) cacheMock.proxy()); -// cacheMock.proxy(); -// windowCache.getPortletWindow(null); -// verify(); + // PortletWindowCache windowCache = new EhPortletWindowCache((Ehcache) + // cacheMock.proxy()); + // cacheMock.proxy(); + // windowCache.getPortletWindow(null); + // verify(); } - + /** - * We need this class to test the cache as the {@link EhCacheImpl} object only - * allows {@link Serializable} objects to be cached. + * We need this class to test the cache as the {@link EhCacheImpl} object + * only allows {@link Serializable} objects to be cached. * * @author Scott T. Weaver - * + * */ - private interface SerializablePortletWindow extends PortletWindow, Serializable + private interface SerializablePortletWindow extends PortletWindow, + Serializable { - + } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/general/InvocationCountingCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/general/InvocationCountingCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/general/InvocationCountingCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /* * Created on Oct 20, 2004 * @@ -27,43 +27,44 @@ * InvocationCountingCache *

        *

        - * + * *

        + * * @author Scott T. Weaver * @version $Id: InvocationCountingCache.java 516881 2007-03-11 10:34:21Z ate $ - * + * */ public class InvocationCountingCache extends SimpleHashMapCache { + int getCount, putCount, removeCount, successGetCount, containsCount; - - public Object get( String key ) + public Object get(String key) { getCount++; - - Object value = super.get(key); - if(value != null) + + Object value = super.get(key); + if (value != null) { successGetCount++; } - + return value; } - - public void put( String key, Object value ) + + public void put(String key, Object value) { putCount++; super.put(key, value); } - - public Object remove( String key ) + + public Object remove(String key) { removeCount++; return super.remove(key); } - - public boolean contains( String key ) + + public boolean contains(String key) { containsCount++; return super.contains(key); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/general/TestCachingInterceptors.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/general/TestCachingInterceptors.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/cache/general/TestCachingInterceptors.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,45 +24,45 @@ * TestCachingInterceptors *

        *

        - * + * *

        + * * @author Scott T. Weaver * @version $Id: TestCachingInterceptors.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class TestCachingInterceptors extends AbstractSpringTestCase { - - - + public void testInterceptors() throws Exception { MockComponent mc = (MockComponent) ctx.getBean("mockComponent"); - InvocationCountingCache cache = (InvocationCountingCache) ctx.getBean("systemCache"); + InvocationCountingCache cache = (InvocationCountingCache) ctx + .getBean("systemCache"); assertNotNull(mc); assertNotNull(cache); - + assertNotNull(mc.getValue("2")); assertEquals(1, cache.containsCount); assertEquals(0, cache.getCount); assertEquals(0, cache.successGetCount); assertEquals(1, cache.putCount); assertEquals(0, cache.removeCount); - + assertNotNull(mc.getValue("2")); assertEquals(2, cache.containsCount); assertEquals(1, cache.getCount); assertEquals(1, cache.successGetCount); assertEquals(1, cache.putCount); assertEquals(0, cache.removeCount); - + mc.setValue("2", "some other value"); assertEquals(2, cache.containsCount); assertEquals(1, cache.getCount); assertEquals(1, cache.successGetCount); assertEquals(1, cache.putCount); assertEquals(1, cache.removeCount); - + assertEquals("some other value", mc.getValue("2")); assertEquals(3, cache.containsCount); assertEquals(1, cache.getCount); @@ -70,10 +70,10 @@ assertEquals(2, cache.putCount); assertEquals(1, cache.removeCount); } - - + protected String[] getConfigurations() { - return new String[] {"org/apache/jetspeed/cache/general/cache-test.xml"}; + return new String[] + {"org/apache/jetspeed/cache/general/cache-test.xml"}; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/BaseMockComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/BaseMockComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/BaseMockComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,15 +18,19 @@ /** * @author Scott T. Weaver - * + * */ public class BaseMockComponent implements MockComponent { + private int fieldValue1; + private String fieldValue2; - + private int id; + private String threadName; + protected static int instanceCount; public BaseMockComponent(int inValue1, String inValue2) @@ -36,7 +40,7 @@ fieldValue1 = inValue1; fieldValue2 = inValue2; this.threadName = Thread.currentThread().getName(); - + } /** @@ -46,13 +50,16 @@ { return fieldValue1; } + /** - * @param value1 The value1 to set. + * @param value1 + * The value1 to set. */ - public void setValue1( int value1 ) + public void setValue1(int value1) { fieldValue1 = value1; } + /** * @return Returns the value2. */ @@ -60,35 +67,43 @@ { return fieldValue2; } + /** - * @param value2 The value2 to set. + * @param value2 + * The value2 to set. */ - public void setValue2( String value2 ) + public void setValue2(String value2) { fieldValue2 = value2; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.components.MockComponent#componentCount() */ public int componentId() - { + { return id; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.components.MockComponent#getThreadName() */ public String getThreadName() - { + { return threadName; } - - public Object getValue( String key ) + + public Object getValue(String key) { - if(key.equals("1")) + if (key.equals("1")) { return new Integer(getValue1()); } - else if(key.equals("2")) + else if (key.equals("2")) { return getValue2(); } @@ -97,17 +112,17 @@ return null; } } - public void setValue( String key, Object value ) + + public void setValue(String key, Object value) { - if(key.equals("1")) + if (key.equals("1")) { setValue1(Integer.parseInt(value.toString())); } - else if(key.equals("2")) + else if (key.equals("2")) { setValue2(value.toString()); } - } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/MockComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/MockComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/MockComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,19 +18,21 @@ /** * @author Scott T. Weaver - * + * */ public interface MockComponent { + /** * @return Returns the value1. */ int getValue1(); /** - * @param value1 The value1 to set. + * @param value1 + * The value1 to set. */ - void setValue1( int value1 ); + void setValue1(int value1); /** * @return Returns the value2. @@ -38,19 +40,20 @@ String getValue2(); /** - * @param value2 The value2 to set. + * @param value2 + * The value2 to set. */ - void setValue2( String value2 ); - + void setValue2(String value2); + /** * * @return number of components of this type that have been instantiated. */ int componentId(); - + String getThreadName(); - + Object getValue(String key); - + void setValue(String key, Object value); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/MockDependentComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/MockDependentComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/MockDependentComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,23 +18,21 @@ /** * @author Scott T. Weaver - * + * */ public class MockDependentComponent -{ - +{ + private MockComponent dependency; public MockDependentComponent(MockComponent dependency) { - this.dependency = dependency; + this.dependency = dependency; } - + public MockComponent getMockComponent() { return dependency; } - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/SimpleComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/SimpleComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/components/SimpleComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,13 +18,14 @@ /** * TestComponentManager - * + * * @version $Id: SimpleComponent.java 516448 2007-03-09 16:25:47Z ate $ */ public class SimpleComponent { + private String simple; - + public SimpleComponent(String simple) { this.simple = simple; @@ -35,4 +36,3 @@ return simple; } } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/testhelpers/TestDatasourceHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/testhelpers/TestDatasourceHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/testhelpers/TestDatasourceHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.testhelpers; import java.sql.Connection; @@ -24,21 +24,22 @@ import junit.framework.TestCase; - public class TestDatasourceHelper extends TestCase { + public void testHelper() throws Exception { Map context = new HashMap(); DatasourceHelper helper = new DatasourceHelper(context); helper.setUp(); - - DataSource ds = (DataSource) context.get(DatasourceHelper.DATASOURCE_KEY); - assertNotNull(ds); + + DataSource ds = (DataSource) context + .get(DatasourceHelper.DATASOURCE_KEY); + assertNotNull(ds); Connection conn = ds.getConnection(); assertNotNull(conn); assertFalse(conn.isClosed()); - conn.close(); + conn.close(); helper.tearDown(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/testhelpers/TestOJBHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/testhelpers/TestOJBHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/cm/src/test/org/apache/jetspeed/testhelpers/TestOJBHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,36 +1,38 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.testhelpers; import java.util.HashMap; import java.util.Map; +import junit.framework.TestCase; + import org.springframework.context.ApplicationContext; -import junit.framework.TestCase; - public class TestOJBHelper extends TestCase { + public void testHelper() throws Exception { Map context = new HashMap(); OJBHelper helper = new OJBHelper(context); helper.setUp(); - ApplicationContext appCtx = (ApplicationContext) context.get(AbstractTestHelper.APP_CONTEXT); + ApplicationContext appCtx = (ApplicationContext) context + .get(AbstractTestHelper.APP_CONTEXT); assertNotNull(appCtx); assertNotNull(appCtx.getBean(OJBHelper.DATASOURCE_BEAN)); helper.tearDown(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedContextRewriter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedContextRewriter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedContextRewriter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,16 +27,18 @@ */ public class JetspeedContextRewriter { + private Document document; + private String portletApplication; + public JetspeedContextRewriter(Document doc, String portletApplication) { this.document = doc; this.portletApplication = portletApplication; } - public void processContextXML() - throws Exception + public void processContextXML() throws Exception { if (document != null) { @@ -52,25 +54,29 @@ else { root = document.getRootElement(); - } - + } + // set Context path String pathAttribute = root.getAttributeValue("path"); - if ((pathAttribute == null) || !pathAttribute.equals("/" + portletApplication)) + if ((pathAttribute == null) + || !pathAttribute.equals("/" + portletApplication)) { root.setAttribute("path", "/" + portletApplication); } - + // set Context docBase String docBaseAttribute = root.getAttributeValue("docBase"); - if ((docBaseAttribute == null) || !docBaseAttribute.equals(portletApplication)) + if ((docBaseAttribute == null) + || !docBaseAttribute.equals(portletApplication)) { root.setAttribute("docBase", portletApplication); } } catch (Exception e) { - throw new Exception("Unable to process context.xml for infusion " + e.toString(), e); + throw new Exception( + "Unable to process context.xml for infusion " + + e.toString(), e); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedDeploy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedDeploy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedDeploy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,11 +16,11 @@ */ package org.apache.jetspeed.tools.deploy; +import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.File; import java.nio.channels.FileChannel; import java.util.Enumeration; import java.util.jar.JarFile; @@ -44,6 +44,7 @@ */ public class JetspeedDeploy implements Deploy { + public static void main(String[] args) throws Exception { if (args.length < 2) @@ -52,43 +53,59 @@ System.exit(1); return; } - + boolean stripLoggers = false; String version = null; - for(int i = 0; i < args.length-2; i++) { + for (int i = 0; i < args.length - 2; i++) + { String option = args[i]; - if(option.equals("-s")) { + if (option.equals("-s")) + { stripLoggers = true; - } else if(option.equals("-v") && i < args.length-3) { - version = args[i+1]; + } + else if (option.equals("-v") && i < args.length - 3) + { + version = args[i + 1]; i++; - } else { + } + else + { // invalid option printUsage(); System.exit(1); return; } } - - new JetspeedDeploy(args[args.length-2], args[args.length-1], stripLoggers, version); + + new JetspeedDeploy(args[args.length - 2], args[args.length - 1], + stripLoggers, version); } - - private static void printUsage() { - System.out.println("Usage: java -jar jetspeed-deploy-tools-.jar [options] INPUT OUTPUT"); + + private static void printUsage() + { + System.out + .println("Usage: java -jar jetspeed-deploy-tools-.jar [options] INPUT OUTPUT"); System.out.println("Options:"); - System.out.println(" -s: stripLoggers - remove commons-logging[version].jar and/or log4j[version].jar from war"); - System.out.println(" (required when targetting application servers like JBoss)"); - System.out.println(" -v VERSION: force servlet specification version to handle web.xml"); - System.out.println(" (default will automatically determine version)"); + System.out + .println(" -s: stripLoggers - remove commons-logging[version].jar and/or log4j[version].jar from war"); + System.out + .println(" (required when targetting application servers like JBoss)"); + System.out + .println(" -v VERSION: force servlet specification version to handle web.xml"); + System.out + .println(" (default will automatically determine version)"); } private final byte[] buffer = new byte[4096]; - public JetspeedDeploy(String inputName, String outputName, boolean stripLoggers) throws Exception { + public JetspeedDeploy(String inputName, String outputName, + boolean stripLoggers) throws Exception + { this(inputName, outputName, stripLoggers, null); } - - public JetspeedDeploy(String inputName, String outputName, boolean stripLoggers, String forcedVersion) throws Exception + + public JetspeedDeploy(String inputName, String outputName, + boolean stripLoggers, String forcedVersion) throws Exception { File tempFile = null; JarFile jin = null; @@ -139,15 +156,19 @@ } else { - if ( stripLoggers && target.endsWith(".jar") && - (target.startsWith("WEB-INF/lib/commons-logging") || target.startsWith("WEB-INF/lib/log4j"))) + if (stripLoggers + && target.endsWith(".jar") + && (target + .startsWith("WEB-INF/lib/commons-logging") || target + .startsWith("WEB-INF/lib/log4j"))) { - System.out.println("Stripping logger "+target); + System.out.println("Stripping logger " + target); continue; } else if ("WEB-INF/tld/portlet.tld".equals(target)) { - System.out.println("Warning: WEB-INF/tld/portlet.tld already provided, won't be replaced."); + System.out + .println("Warning: WEB-INF/tld/portlet.tld already provided, won't be replaced."); taglibFound = true; } addFile(target, source, jout); @@ -159,22 +180,17 @@ } } - if (webXml == null) - { - throw new IllegalArgumentException("WEB-INF/web.xml"); - } - if (portletXml == null) - { - throw new IllegalArgumentException("WEB-INF/portlet.xml"); - } - + if (webXml == null) { throw new IllegalArgumentException( + "WEB-INF/web.xml"); } + if (portletXml == null) { throw new IllegalArgumentException( + "WEB-INF/portlet.xml"); } + JetspeedWebApplicationRewriterFactory webRewriterFactory = new JetspeedWebApplicationRewriterFactory(); - JetspeedWebApplicationRewriter webRewriter = webRewriterFactory.getInstance( - webXml, - portletApplicationName, - forcedVersion); + JetspeedWebApplicationRewriter webRewriter = webRewriterFactory + .getInstance(webXml, portletApplicationName, forcedVersion); webRewriter.processWebXML(); - JetspeedContextRewriter contextRewriter = new JetspeedContextRewriter(contextXml, portletApplicationName); + JetspeedContextRewriter contextRewriter = new JetspeedContextRewriter( + contextXml, portletApplicationName); contextRewriter.processContextXML(); // write the web.xml, portlet.xml, and context.xml files @@ -185,10 +201,12 @@ if (!taglibFound) { System.out.println("Attempting to add portlet.tld to war..."); - InputStream is = this.getClass().getResourceAsStream("/org/apache/jetspeed/tools/deploy/portlet.tld"); + InputStream is = this.getClass().getResourceAsStream( + "/org/apache/jetspeed/tools/deploy/portlet.tld"); if (is == null) { - System.out.println("Failed to find portlet.tld in classpath"); + System.out + .println("Failed to find portlet.tld in classpath"); } else { @@ -287,13 +305,13 @@ SAXBuilder saxBuilder = new SAXBuilder(); saxBuilder.setEntityResolver(new EntityResolver() { - public InputSource resolveEntity(java.lang.String publicId, java.lang.String systemId) throws SAXException, - java.io.IOException + + public InputSource resolveEntity(java.lang.String publicId, + java.lang.String systemId) throws SAXException, + java.io.IOException { - if (systemId.equals("http://java.sun.com/dtd/web-app_2_3.dtd")) - { - return new InputSource(getClass().getResourceAsStream("web-app_2_3.dtd")); - } + if (systemId.equals("http://java.sun.com/dtd/web-app_2_3.dtd")) { return new InputSource( + getClass().getResourceAsStream("web-app_2_3.dtd")); } return null; } }); @@ -301,7 +319,8 @@ return document; } - protected void addFile(String path, InputStream source, JarOutputStream jos) throws IOException + protected void addFile(String path, InputStream source, JarOutputStream jos) + throws IOException { jos.putNextEntry(new ZipEntry(path)); try @@ -318,12 +337,14 @@ } } - protected void addFile(String path, Document source, JarOutputStream jos) throws IOException + protected void addFile(String path, Document source, JarOutputStream jos) + throws IOException { if (source != null) { jos.putNextEntry(new ZipEntry(path)); - XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat()); + XMLOutputter xmlOutputter = new XMLOutputter(Format + .getPrettyFormat()); try { xmlOutputter.output(source, jos); @@ -344,7 +365,7 @@ int index = name.lastIndexOf("-infused.war"); if (index > -1) { - portletApplicationName = name.substring(0, index); + portletApplicationName = name.substring(0, index); } else { @@ -352,7 +373,7 @@ if (index > -1) { portletApplicationName = name.substring(0, index); - } + } } return portletApplicationName; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedDeployFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedDeployFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedDeployFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,6 +24,7 @@ */ public class JetspeedDeployFactory implements DeployFactory { + /** * JetspeedDeployFactory */ @@ -33,13 +34,14 @@ /** * getInstance - * + * * @param inputWarPath * @param outputWarPath * @param stripLoggers * @return JetspeedDeploy instance */ - public Deploy getInstance(String inputWarPath, String outputWarPath, boolean stripLoggers) throws Exception + public Deploy getInstance(String inputWarPath, String outputWarPath, + boolean stripLoggers) throws Exception { return new JetspeedDeploy(inputWarPath, outputWarPath, stripLoggers); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,33 +34,43 @@ * @author Matt Avery * @author David Sean Taylor * @version $Id: WebDescriptorUtilities.java,v 1.2 2004/05/12 22:25:04 taylor - * Exp $ + * Exp $ */ public abstract class JetspeedWebApplicationRewriter { + public static final String JETSPEED_CONTAINER = "JetspeedContainer"; + public static final String JETSPEED_SERVLET_CLASS = "org.apache.jetspeed.container.JetspeedContainerServlet"; + public static final String JETSPEED_SERVLET_DISPLAY_NAME = "Jetspeed Container"; + public static final String JETSPEED_SERVLET_DESCRIPTION = "MVC Servlet for Jetspeed Portlet Applications"; + public static final String NAMESPACE_PREFIX = "js"; + protected static final String WEB_XML_PATH = "WEB-INF/web.xml"; private Document document; + private String portletApplication; + private boolean changed = false; + private boolean portletTaglibAdded = false; - - public JetspeedWebApplicationRewriter(Document doc, String portletApplication) + + public JetspeedWebApplicationRewriter(Document doc, + String portletApplication) { - this.document = doc; - this.portletApplication = portletApplication; + this.document = doc; + this.portletApplication = portletApplication; } public JetspeedWebApplicationRewriter(Document doc) { - this.document = doc; + this.document = doc; } - + /** * *

        @@ -72,26 +82,29 @@ * the JetspeedContainer servlet. This is only done if the descriptor does * not already contain these items. * - * @throws MetaDataException + * @throws Exception * if there is a problem infusing */ - public void processWebXML() - throws Exception + public void processWebXML() throws Exception { try { Element root = document.getRootElement(); - - Object jetspeedServlet = getXPath(getJetspeedServletXPath()).selectSingleNode(document); - Object jetspeedServletMapping = getXPath(getJetspeedServletMappingXPath()).selectSingleNode(document); - Object portletTaglib = getXPath(getPortletTagLibXPath()).selectSingleNode(document); - + + Object jetspeedServlet = getXPath(getJetspeedServletXPath()) + .selectSingleNode(document); + Object jetspeedServletMapping = getXPath( + getJetspeedServletMappingXPath()) + .selectSingleNode(document); + Object portletTaglib = getXPath(getPortletTagLibXPath()) + .selectSingleNode(document); + if (!document.hasRootElement()) { root = new Element("web-app"); document.setRootElement(root); } - + if (jetspeedServlet == null) { insertJetspeedServlet(root); @@ -102,25 +115,29 @@ // double check for register at Init if (jetspeedServlet instanceof Element) { - Parent jetspeedServletElement =((Element)jetspeedServlet).getParent(); - if (null == getXPath("js:init-param/js:param-name[contains(child::text(), \"contextName\")]").selectSingleNode(jetspeedServletElement)) + Parent jetspeedServletElement = ((Element) jetspeedServlet) + .getParent(); + if (null == getXPath( + "js:init-param/js:param-name[contains(child::text(), \"contextName\")]") + .selectSingleNode(jetspeedServletElement)) { - insertContextNameParam((Element)jetspeedServletElement); + insertContextNameParam((Element) jetspeedServletElement); } - if (null == getXPath("js:load-on-startup").selectSingleNode(jetspeedServletElement)) + if (null == getXPath("js:load-on-startup") + .selectSingleNode(jetspeedServletElement)) { insertLoadOnStartup((Element) jetspeedServletElement); } } } - + if (jetspeedServletMapping == null) { insertJetspeedServletMapping(root); changed = true; } - - if(portletTaglib == null) + + if (portletTaglib == null) { insertPortletTagLib(root); changed = true; @@ -129,35 +146,39 @@ } catch (Exception e) { - throw new Exception("Unable to process web.xml for infusion " + e.toString(), e); + throw new Exception("Unable to process web.xml for infusion " + + e.toString(), e); } - + } - + protected void insertContextNameParam(Element jetspeedServletElement) { Namespace namespace = jetspeedServletElement.getNamespace(); - Element param2Name = new Element("param-name", namespace).addContent("contextName"); - Element param2Value = new Element("param-value", namespace).addContent(portletApplication); + Element param2Name = new Element("param-name", namespace) + .addContent("contextName"); + Element param2Value = new Element("param-value", namespace) + .addContent(portletApplication); Element init2Param = new Element("init-param", namespace); init2Param.addContent(param2Name); init2Param.addContent(param2Value); - jetspeedServletElement.addContent(init2Param); - + jetspeedServletElement.addContent(init2Param); + } - + protected void insertLoadOnStartup(Element jetspeedServletElement) { Namespace namespace = jetspeedServletElement.getNamespace(); - Element loadOnStartup = new Element("load-on-startup", namespace).addContent("0"); - jetspeedServletElement.addContent(loadOnStartup); + Element loadOnStartup = new Element("load-on-startup", namespace) + .addContent("0"); + jetspeedServletElement.addContent(loadOnStartup); } - + public boolean isChanged() { return changed; } - + /** * *

        @@ -173,8 +194,8 @@ * element we want to insert. This order should be the order * defined by the web.xml's DTD type definition. */ - protected void insertElementCorrectly( Element root, Element toInsert, String[] elementsBefore ) - throws Exception + protected void insertElementCorrectly(Element root, Element toInsert, + String[] elementsBefore) throws Exception { List allChildren = root.getChildren(); List elementsBeforeList = Arrays.asList(elementsBefore); @@ -191,9 +212,9 @@ } count++; } - + insertAfter = (count == 0) ? 0 : insertAfter + 1; - + try { root.addContent(insertAfter, toInsert); @@ -203,7 +224,7 @@ root.addContent(toInsert); } } - + /** * @return Returns the portletTaglibAdded. */ @@ -211,10 +232,10 @@ { return portletTaglibAdded; } - + /** - * Returns the xpath containing the namespace prefix 'js' mapped to the document - * default namespace. + * Returns the xpath containing the namespace prefix 'js' mapped to the + * document default namespace. * * @param path * @return XPath @@ -224,56 +245,58 @@ { XPath xpath = XPath.newInstance(path); Element root = document.getRootElement(); - if(root != null) + if (root != null) { - if(StringUtils.isNotEmpty(root.getNamespaceURI())) + if (StringUtils.isNotEmpty(root.getNamespaceURI())) { xpath.addNamespace(NAMESPACE_PREFIX, root.getNamespaceURI()); } } return xpath; } - + /** - * Returns the jetspeed servlet xpath. - * The returned path must contain the namespace prefix 'js'. + * Returns the jetspeed servlet xpath. The returned path must contain the + * namespace prefix 'js'. * * @return jetspeed servlet xpath */ protected abstract String getJetspeedServletXPath(); - + /** - * Returns the jetspeed servlet mapping xpath. - * The returned path must contain the namespace prefix 'js'. + * Returns the jetspeed servlet mapping xpath. The returned path must + * contain the namespace prefix 'js'. * * @return jetspeed servlet mapping xpath */ protected abstract String getJetspeedServletMappingXPath(); - + /** - * Returns the portlet taglib xpath. - * The returned path must contain the namespace prefix 'js'. + * Returns the portlet taglib xpath. The returned path must contain the + * namespace prefix 'js'. * * @return portlet taglib xpath */ protected abstract String getPortletTagLibXPath(); - + /** * Inserts the jetspeed servlet into web.xml * * @param root * @throws Exception */ - protected abstract void insertJetspeedServlet(Element root) throws Exception; - + protected abstract void insertJetspeedServlet(Element root) + throws Exception; + /** * Inserts the jetspeed servlet mapping into web.xml * * @param root * @throws Exception */ - protected abstract void insertJetspeedServletMapping(Element root) throws Exception; - + protected abstract void insertJetspeedServletMapping(Element root) + throws Exception; + /** * Inserts the portlet taglib into web.xml * Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriter2_3.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriter2_3.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriter2_3.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,26 +27,34 @@ * @author Matt Avery * @author David Sean Taylor * @version $Id: WebDescriptorUtilities.java,v 1.2 2004/05/12 22:25:04 taylor - * Exp $ + * Exp $ */ class JetspeedWebApplicationRewriter2_3 extends JetspeedWebApplicationRewriter { + public static final String JETSPEED_SERVLET_XPATH = "/js:web-app/js:servlet/js:servlet-name[contains(child::text(), \"JetspeedContainer\")]"; + public static final String JETSPEED_SERVLET_MAPPING_XPATH = "/js:web-app/js:servlet-mapping/js:servlet-name[contains(child::text(), \"JetspeedContainer\")]"; + public static final String PORTLET_TAGLIB_XPATH = "/js:web-app/js:taglib/js:taglib-uri[contains(child::text(), \"http://java.sun.com/portlet\")]"; - - protected static final String[] ELEMENTS_BEFORE_SERVLET = new String[]{"icon", "display-name", "description", - "distributable", "context-param", "filter", "filter-mapping", "listener", "servlet"}; - protected static final String[] ELEMENTS_BEFORE_SERVLET_MAPPING = new String[]{"icon", "display-name", - "description", "distributable", "context-param", "filter", "filter-mapping", "listener", "servlet", + + protected static final String[] ELEMENTS_BEFORE_SERVLET = new String[] + {"icon", "display-name", "description", "distributable", "context-param", + "filter", "filter-mapping", "listener", "servlet"}; + + protected static final String[] ELEMENTS_BEFORE_SERVLET_MAPPING = new String[] + {"icon", "display-name", "description", "distributable", "context-param", + "filter", "filter-mapping", "listener", "servlet", "servlet-mapping"}; - - protected static final String[] ELEMENTS_BEFORE_TAGLIB_MAPPING = new String[]{"icon", "display-name", - "description", "distributable", "context-param", "filter", "filter-mapping", "listener", "servlet", - "servlet-mapping", "session-config", "mime-mapping", "welcome-file-list", "error-page", "taglib"}; - - public JetspeedWebApplicationRewriter2_3(Document doc, String portletApplication) + protected static final String[] ELEMENTS_BEFORE_TAGLIB_MAPPING = new String[] + {"icon", "display-name", "description", "distributable", "context-param", + "filter", "filter-mapping", "listener", "servlet", + "servlet-mapping", "session-config", "mime-mapping", + "welcome-file-list", "error-page", "taglib"}; + + public JetspeedWebApplicationRewriter2_3(Document doc, + String portletApplication) { super(doc, portletApplication); } @@ -55,7 +63,7 @@ { super(doc); } - + /** * Returns the jetspeed servlet xpath. * @@ -65,7 +73,7 @@ { return JETSPEED_SERVLET_XPATH; } - + /** * Returns the jetspeed servlet mapping xpath. * @@ -96,8 +104,10 @@ { Namespace namespace = root.getNamespace(); Element jetspeedServletElement = new Element("servlet", namespace); - Element servletName = new Element("servlet-name", namespace).addContent(JETSPEED_CONTAINER); - Element servletDspName = new Element("display-name", namespace).addContent(JETSPEED_SERVLET_DISPLAY_NAME); + Element servletName = new Element("servlet-name", namespace) + .addContent(JETSPEED_CONTAINER); + Element servletDspName = new Element("display-name", namespace) + .addContent(JETSPEED_SERVLET_DISPLAY_NAME); Element servletDesc = new Element("description", namespace) .addContent(JETSPEED_SERVLET_DESCRIPTION); Element servletClass = new Element("servlet-class", namespace) @@ -108,7 +118,8 @@ jetspeedServletElement.addContent(servletClass); insertContextNameParam(jetspeedServletElement); insertLoadOnStartup(jetspeedServletElement); - insertElementCorrectly(root, jetspeedServletElement, ELEMENTS_BEFORE_SERVLET); + insertElementCorrectly(root, jetspeedServletElement, + ELEMENTS_BEFORE_SERVLET); } /** @@ -120,15 +131,19 @@ protected void insertJetspeedServletMapping(Element root) throws Exception { Namespace namespace = root.getNamespace(); - Element jetspeedServletMappingElement = new Element("servlet-mapping", namespace); - - Element servletMapName = new Element("servlet-name", namespace).addContent(JETSPEED_CONTAINER); - Element servletUrlPattern = new Element("url-pattern", namespace).addContent("/container/*"); + Element jetspeedServletMappingElement = new Element("servlet-mapping", + namespace); + Element servletMapName = new Element("servlet-name", namespace) + .addContent(JETSPEED_CONTAINER); + Element servletUrlPattern = new Element("url-pattern", namespace) + .addContent("/container/*"); + jetspeedServletMappingElement.addContent(servletMapName); jetspeedServletMappingElement.addContent(servletUrlPattern); - insertElementCorrectly(root, jetspeedServletMappingElement, ELEMENTS_BEFORE_SERVLET_MAPPING); + insertElementCorrectly(root, jetspeedServletMappingElement, + ELEMENTS_BEFORE_SERVLET_MAPPING); } /** @@ -140,13 +155,15 @@ protected void insertPortletTagLib(Element root) throws Exception { Namespace namespace = root.getNamespace(); - Element taglib = new Element ("taglib", namespace); - Element taguri = new Element("taglib-uri", namespace).addContent("http://java.sun.com/portlet"); - Element taglocation = new Element("taglib-location", namespace).addContent("/WEB-INF/tld/portlet.tld"); - + Element taglib = new Element("taglib", namespace); + Element taguri = new Element("taglib-uri", namespace) + .addContent("http://java.sun.com/portlet"); + Element taglocation = new Element("taglib-location", namespace) + .addContent("/WEB-INF/tld/portlet.tld"); + taglib.addContent(taguri); taglib.addContent(taglocation); - + insertElementCorrectly(root, taglib, ELEMENTS_BEFORE_TAGLIB_MAPPING); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriter2_4.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriter2_4.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriter2_4.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,28 +24,40 @@ * Utilities for manipulating the web.xml deployment descriptor version 2.4 * * @author Nicolas Dutertry - * @version $Id: JetspeedWebApplicationRewriter2_4.java 517121 2007-03-12 07:45:49Z ate $ + * @version $Id: JetspeedWebApplicationRewriter2_4.java 517121 2007-03-12 + * 07:45:49Z ate $ */ class JetspeedWebApplicationRewriter2_4 extends JetspeedWebApplicationRewriter { + public static final String JETSPEED_SERVLET_XPATH = "/js:web-app/js:servlet/js:servlet-name[contains(child::text(), \"JetspeedContainer\")]"; + public static final String JETSPEED_SERVLET_MAPPING_XPATH = "/js:web-app/js:servlet-mapping/js:servlet-name[contains(child::text(), \"JetspeedContainer\")]"; + public static final String JSP_CONFIG_XPATH = "/js:web-app/js:jsp-config"; + public static final String PORTLET_TAGLIB_XPATH = "/js:web-app/js:jsp-config/js:taglib/js:taglib-uri[contains(child::text(), \"http://java.sun.com/portlet\")]"; - - protected static final String[] ELEMENTS_BEFORE_SERVLET = new String[]{"description", "display-name", "icon", - "distributable", "context-param", "filter", "filter-mapping", "listener", "servlet"}; - protected static final String[] ELEMENTS_BEFORE_SERVLET_MAPPING = new String[]{"description", "display-name", "icon", - "distributable", "context-param", "filter", "filter-mapping", "listener", "servlet", + + protected static final String[] ELEMENTS_BEFORE_SERVLET = new String[] + {"description", "display-name", "icon", "distributable", "context-param", + "filter", "filter-mapping", "listener", "servlet"}; + + protected static final String[] ELEMENTS_BEFORE_SERVLET_MAPPING = new String[] + {"description", "display-name", "icon", "distributable", "context-param", + "filter", "filter-mapping", "listener", "servlet", "servlet-mapping"}; - - protected static final String[] ELEMENTS_BEFORE_JSP_CONFIG = new String[]{"description", "display-name", "icon", - "distributable", "context-param", "filter", "filter-mapping", "listener", "servlet", - "servlet-mapping", "session-config", "mime-mapping", "welcome-file-list", "error-page", "jsp-config"}; - - protected static final String[] ELEMENTS_BEFORE_TAGLIB_MAPPING = new String[]{"taglib"}; - - public JetspeedWebApplicationRewriter2_4(Document doc, String portletApplication) + + protected static final String[] ELEMENTS_BEFORE_JSP_CONFIG = new String[] + {"description", "display-name", "icon", "distributable", "context-param", + "filter", "filter-mapping", "listener", "servlet", + "servlet-mapping", "session-config", "mime-mapping", + "welcome-file-list", "error-page", "jsp-config"}; + + protected static final String[] ELEMENTS_BEFORE_TAGLIB_MAPPING = new String[] + {"taglib"}; + + public JetspeedWebApplicationRewriter2_4(Document doc, + String portletApplication) { super(doc, portletApplication); } @@ -54,7 +66,7 @@ { super(doc); } - + /** * Returns the jetspeed servlet xpath. * @@ -64,7 +76,7 @@ { return JETSPEED_SERVLET_XPATH; } - + /** * Returns the jetspeed servlet mapping xpath. * @@ -95,20 +107,23 @@ { Namespace namespace = root.getNamespace(); Element jetspeedServletElement = new Element("servlet", namespace); - Element servletName = new Element("servlet-name", namespace).addContent(JETSPEED_CONTAINER); - Element servletDspName = new Element("display-name", namespace).addContent(JETSPEED_SERVLET_DISPLAY_NAME); + Element servletName = new Element("servlet-name", namespace) + .addContent(JETSPEED_CONTAINER); + Element servletDspName = new Element("display-name", namespace) + .addContent(JETSPEED_SERVLET_DISPLAY_NAME); Element servletDesc = new Element("description", namespace) .addContent(JETSPEED_SERVLET_DESCRIPTION); Element servletClass = new Element("servlet-class", namespace) .addContent(JETSPEED_SERVLET_CLASS); - // order is important + // order is important jetspeedServletElement.addContent(servletDesc); jetspeedServletElement.addContent(servletDspName); jetspeedServletElement.addContent(servletName); jetspeedServletElement.addContent(servletClass); insertContextNameParam(jetspeedServletElement); insertLoadOnStartup(jetspeedServletElement); - insertElementCorrectly(root, jetspeedServletElement, ELEMENTS_BEFORE_SERVLET); + insertElementCorrectly(root, jetspeedServletElement, + ELEMENTS_BEFORE_SERVLET); } /** @@ -120,15 +135,19 @@ protected void insertJetspeedServletMapping(Element root) throws Exception { Namespace namespace = root.getNamespace(); - Element jetspeedServletMappingElement = new Element("servlet-mapping", namespace); - - Element servletMapName = new Element("servlet-name", namespace).addContent(JETSPEED_CONTAINER); - Element servletUrlPattern = new Element("url-pattern", namespace).addContent("/container/*"); + Element jetspeedServletMappingElement = new Element("servlet-mapping", + namespace); + Element servletMapName = new Element("servlet-name", namespace) + .addContent(JETSPEED_CONTAINER); + Element servletUrlPattern = new Element("url-pattern", namespace) + .addContent("/container/*"); + jetspeedServletMappingElement.addContent(servletMapName); jetspeedServletMappingElement.addContent(servletUrlPattern); - insertElementCorrectly(root, jetspeedServletMappingElement, ELEMENTS_BEFORE_SERVLET_MAPPING); + insertElementCorrectly(root, jetspeedServletMappingElement, + ELEMENTS_BEFORE_SERVLET_MAPPING); } /** @@ -140,19 +159,23 @@ protected void insertPortletTagLib(Element root) throws Exception { Namespace namespace = root.getNamespace(); - Element jspConfig = (Element)getXPath(JSP_CONFIG_XPATH).selectSingleNode(root.getDocument()); - if(jspConfig == null) + Element jspConfig = (Element) getXPath(JSP_CONFIG_XPATH) + .selectSingleNode(root.getDocument()); + if (jspConfig == null) { jspConfig = new Element("jsp-config", namespace); insertElementCorrectly(root, jspConfig, ELEMENTS_BEFORE_JSP_CONFIG); } - Element taglib = new Element ("taglib", namespace); - Element taguri = new Element("taglib-uri", namespace).addContent("http://java.sun.com/portlet"); - Element taglocation = new Element("taglib-location", namespace).addContent("/WEB-INF/tld/portlet.tld"); - + Element taglib = new Element("taglib", namespace); + Element taguri = new Element("taglib-uri", namespace) + .addContent("http://java.sun.com/portlet"); + Element taglocation = new Element("taglib-location", namespace) + .addContent("/WEB-INF/tld/portlet.tld"); + taglib.addContent(taguri); taglib.addContent(taglocation); - - insertElementCorrectly(jspConfig, taglib, ELEMENTS_BEFORE_TAGLIB_MAPPING); + + insertElementCorrectly(jspConfig, taglib, + ELEMENTS_BEFORE_TAGLIB_MAPPING); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriterFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriterFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/deploy-tool/src/java/org/apache/jetspeed/tools/deploy/JetspeedWebApplicationRewriterFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,54 +1,58 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.tools.deploy; import org.jdom.Document; /** * @author Nicolas Dutertry - * @version $Id: JetspeedWebApplicationRewriterFactory.java 516881 2007-03-11 10:34:21Z ate $ + * @version $Id: JetspeedWebApplicationRewriterFactory.java 516881 2007-03-11 + * 10:34:21Z ate $ */ -public class JetspeedWebApplicationRewriterFactory { - - /** +public class JetspeedWebApplicationRewriterFactory +{ + + /** * Returns an instance of JetspeedWebApplicationRewriter. * * @param doc * @return JetspeedWebApplicationRewriter * @throws Exception */ - public JetspeedWebApplicationRewriter getInstance(Document doc) throws Exception + public JetspeedWebApplicationRewriter getInstance(Document doc) + throws Exception { return getInstance(doc, null, null); } - - /** + + /** * Returns an instance of JetspeedWebApplicationRewriter. * * @param doc * @return JetspeedWebApplicationRewriter * @throws Exception */ - public JetspeedWebApplicationRewriter getInstance(Document doc, String portletApplication) throws Exception + public JetspeedWebApplicationRewriter getInstance(Document doc, + String portletApplication) throws Exception { return getInstance(doc, portletApplication, null); } - - /** + + /** * Returns an instance of JetspeedWebApplicationRewriter. * * @param doc @@ -57,35 +61,42 @@ * @return JetspeedWebApplicationRewriter * @throws Exception */ - public JetspeedWebApplicationRewriter getInstance(Document doc, String portletApplication, String forcedVersion) throws Exception + public JetspeedWebApplicationRewriter getInstance(Document doc, + String portletApplication, String forcedVersion) throws Exception { String version = forcedVersion; - if(version == null) + if (version == null) { version = doc.getRootElement().getAttributeValue("version", "2.3"); } - + try { // Check version is a valid number Double.parseDouble(version); } - catch(NumberFormatException e) + catch (NumberFormatException e) { - throw new Exception("Unable to create JetspeedWebApplicationRewriter for version " + version, e); + throw new Exception( + "Unable to create JetspeedWebApplicationRewriter for version " + + version, e); } - - if(version.equals("2.3")) + + if (version.equals("2.3")) { - return new JetspeedWebApplicationRewriter2_3(doc, portletApplication); + return new JetspeedWebApplicationRewriter2_3(doc, + portletApplication); } - else if(version.compareTo("2.4") >= 0) + else if (version.compareTo("2.4") >= 0) { - return new JetspeedWebApplicationRewriter2_4(doc, portletApplication); + return new JetspeedWebApplicationRewriter2_4(doc, + portletApplication); } else { - throw new Exception("Unable to create JetspeedWebApplicationRewriter for version " + version); + throw new Exception( + "Unable to create JetspeedWebApplicationRewriter for version " + + version); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/java/org/apache/jetspeed/cache/file/FileCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/java/org/apache/jetspeed/cache/file/FileCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/java/org/apache/jetspeed/cache/file/FileCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,44 +17,48 @@ package org.apache.jetspeed.cache.file; +import java.io.File; +import java.io.FileNotFoundException; import java.util.Collection; import java.util.Collections; import java.util.Date; -import java.util.Map; import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; import java.util.List; -import java.util.LinkedList; -import java.util.Iterator; -import java.io.File; -import java.io.FileNotFoundException; +import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** - * FileCache keeps a cache of files up-to-date with a most simple eviction policy. - * The eviction policy will keep n items in the cache, and then start evicting - * the items ordered-by least used first. The cache runs a thread to check for - * both evictions and refreshes. - * - * @author David S. Taylor David Sean Taylor - * @version $Id: FileCache.java 516448 2007-03-09 16:25:47Z ate $ + * FileCache keeps a cache of files up-to-date with a most simple eviction + * policy. The eviction policy will keep n items in the cache, and then start + * evicting the items ordered-by least used first. The cache runs a thread to + * check for both evictions and refreshes. + * + * @author David S. Taylor David Sean Taylor + * @version $Id: FileCache.java 516448 2007-03-09 16:25:47Z ate $ */ public class FileCache implements java.util.Comparator { - protected long scanRate = 300; // every 5 minutes + + protected long scanRate = 300; // every 5 minutes + protected int maxSize = 100; // maximum of 100 items + protected List listeners = new LinkedList(); private FileCacheScanner scanner = null; + private Map cache = null; private final static Log log = LogFactory.getLog(FileCache.class); /** * Default constructor. Use default values for scanReate and maxSize - * + * */ public FileCache() { @@ -65,14 +69,15 @@ /** * Set scanRate and maxSize - * - * @param scanRate how often in seconds to refresh and evict from the cache - * @param maxSize the maximum allowed size of the cache before eviction starts + * + * @param scanRate + * how often in seconds to refresh and evict from the cache + * @param maxSize + * the maximum allowed size of the cache before eviction starts */ - public FileCache(long scanRate, - int maxSize) + public FileCache(long scanRate, int maxSize) { - + cache = Collections.synchronizedMap(new HashMap()); this.scanRate = scanRate; @@ -83,18 +88,21 @@ /** * Set all parameters on the cache - * - * @param initialCapacity the initial size of the cache as passed to HashMap - * @param loadFactor how full the hash table is allowed to get before increasing - * @param scanRate how often in seconds to refresh and evict from the cache - * @param maxSize the maximum allowed size of the cache before eviction starts + * + * @param initialCapacity + * the initial size of the cache as passed to HashMap + * @param loadFactor + * how full the hash table is allowed to get before increasing + * @param scanRate + * how often in seconds to refresh and evict from the cache + * @param maxSize + * the maximum allowed size of the cache before eviction starts */ - public FileCache(int initialCapacity, - int loadFactor, - long scanRate, - int maxSize) + public FileCache(int initialCapacity, int loadFactor, long scanRate, + int maxSize) { - cache = Collections.synchronizedMap(new HashMap(initialCapacity, loadFactor)); + cache = Collections.synchronizedMap(new HashMap(initialCapacity, + loadFactor)); this.scanRate = scanRate; this.maxSize = maxSize; @@ -104,17 +112,18 @@ /** * Set the new refresh scan rate on managed files. - * - * @param scanRate the new scan rate in seconds + * + * @param scanRate + * the new scan rate in seconds */ public void setScanRate(long scanRate) { - this.scanRate= scanRate; + this.scanRate = scanRate; } /** - * Get the refresh scan rate - * + * Get the refresh scan rate + * * @return the current refresh scan rate in seconds */ public long getScanRate() @@ -123,9 +132,10 @@ } /** - * Set the new maximum size of the cache - * - * @param maxSize the maximum size of the cache + * Set the new maximum size of the cache + * + * @param maxSize + * the maximum size of the cache */ public void setMaxSize(int maxSize) { @@ -133,8 +143,8 @@ } /** - * Get the maximum size of the cache - * + * Get the maximum size of the cache + * * @return the current maximum size of the cache */ public int getMaxSize() @@ -144,8 +154,9 @@ /** * Gets an entry from the cache given a key - * - * @param key the key to look up the entry by + * + * @param key + * the key to look up the entry by * @return the entry */ public FileCacheEntry get(String key) @@ -155,59 +166,57 @@ /** * Gets an entry from the cache given a key - * - * @param key the key to look up the entry by + * + * @param key + * the key to look up the entry by * @return the entry */ public Object getDocument(String key) { FileCacheEntry entry = (FileCacheEntry) cache.get(key); - if (entry != null) - { - return entry.getDocument(); - } + if (entry != null) { return entry.getDocument(); } return null; } /** * Puts a file entry in the file cache - * - * @param file The file to be put in the cache - * @param document the cached document + * + * @param file + * The file to be put in the cache + * @param document + * the cached document */ - public void put(File file, Object document) - throws java.io.IOException + public void put(File file, Object document) throws java.io.IOException { - if(!file.exists()) - { - throw new FileNotFoundException("File to cache: "+file.getAbsolutePath()+" does not exist."); - } + if (!file.exists()) { throw new FileNotFoundException("File to cache: " + + file.getAbsolutePath() + " does not exist."); } FileCacheEntry entry = new FileCacheEntryImpl(file, document); cache.put(file.getCanonicalPath(), entry); } /** * Puts a file entry in the file cache - * - * @param path the full path name of the file - * @param document the cached document + * + * @param path + * the full path name of the file + * @param document + * the cached document */ public void put(String key, Object document, File rootFile) - throws java.io.IOException + throws java.io.IOException { File file = new File(rootFile, key); - if(!file.exists()) - { - throw new FileNotFoundException("File to cache: "+file.getAbsolutePath()+" does not exist."); - } + if (!file.exists()) { throw new FileNotFoundException("File to cache: " + + file.getAbsolutePath() + " does not exist."); } FileCacheEntry entry = new FileCacheEntryImpl(file, document); cache.put(key, entry); } /** * Removes a file entry from the file cache - * - * @param key the full path name of the file + * + * @param key + * the full path name of the file * @return the entry removed */ public Object remove(String key) @@ -215,11 +224,11 @@ return cache.remove(key); } - /** - * Add a File Cache Event Listener - * - * @param listener the event listener + * Add a File Cache Event Listener + * + * @param listener + * the event listener */ public void addListener(FileCacheEventListener listener) { @@ -228,7 +237,7 @@ /** * Start the file Scanner running at the current scan rate. - * + * */ public void startFileScanner() { @@ -244,8 +253,8 @@ } /** - * Stop the file Scanner - * + * Stop the file Scanner + * */ public void stopFileScanner() { @@ -254,129 +263,127 @@ /** * Evicts entries based on last accessed time stamp - * + * */ - protected void evict() + protected void evict() { synchronized (cache) { - if (this.getMaxSize() >= cache.size()) - { - return; - } - + if (this.getMaxSize() >= cache.size()) { return; } + List list = new LinkedList(cache.values()); Collections.sort(list, this); - + int count = 0; int limit = cache.size() - this.getMaxSize(); - - for (Iterator it = list.iterator(); it.hasNext(); ) + + for (Iterator it = list.iterator(); it.hasNext();) { if (count >= limit) { break; } - + FileCacheEntry entry = (FileCacheEntry) it.next(); String key = null; try { key = entry.getFile().getCanonicalPath(); - } + } catch (java.io.IOException e) { log.error("Exception getting file path: ", e); } // notify that eviction will soon take place - for (Iterator lit = this.listeners.iterator(); lit.hasNext(); ) + for (Iterator lit = this.listeners.iterator(); lit.hasNext();) { - FileCacheEventListener listener = - (FileCacheEventListener) lit.next(); + FileCacheEventListener listener = (FileCacheEventListener) lit + .next(); try { listener.evict(entry); } catch (Exception e1) { - log.warn("Unable to evict cache entry. "+e1.toString(), e1); - } + log.warn("Unable to evict cache entry. " + + e1.toString(), e1); + } } cache.remove(key); - + count++; - } + } } } /** * Evicts all entries - * + * */ - public void evictAll() + public void evictAll() { synchronized (cache) { // evict all cache entries List list = new LinkedList(cache.values()); - for (Iterator it = list.iterator(); it.hasNext(); ) + for (Iterator it = list.iterator(); it.hasNext();) { // evict cache entry FileCacheEntry entry = (FileCacheEntry) it.next(); // notify that eviction will soon take place - for (Iterator lit = this.listeners.iterator(); lit.hasNext(); ) + for (Iterator lit = this.listeners.iterator(); lit.hasNext();) { - FileCacheEventListener listener = - (FileCacheEventListener) lit.next(); + FileCacheEventListener listener = (FileCacheEventListener) lit + .next(); try { listener.evict(entry); } catch (Exception e1) { - log.warn("Unable to evict cache entry. "+e1.toString(), e1); - } + log.warn("Unable to evict cache entry. " + + e1.toString(), e1); + } } // remove from cache by key String key = null; try { key = entry.getFile().getCanonicalPath(); - } + } catch (java.io.IOException e) { log.error("Exception getting file path: ", e); } cache.remove(key); - } + } } } /** * Comparator function for sorting by last accessed during eviction - * + * */ public int compare(Object o1, Object o2) { - FileCacheEntry e1 = (FileCacheEntry)o1; - FileCacheEntry e2 = (FileCacheEntry)o2; + FileCacheEntry e1 = (FileCacheEntry) o1; + FileCacheEntry e2 = (FileCacheEntry) o2; if (e1.getLastAccessed() < e2.getLastAccessed()) { return -1; } - else if (e1.getLastAccessed() == e2.getLastAccessed()) - { - return 0; - } + else if (e1.getLastAccessed() == e2.getLastAccessed()) { return 0; } return 1; } /** - * inner class that runs as a thread to scan the cache for updates or evictions - * + * inner class that runs as a thread to scan the cache for updates or + * evictions + * */ protected class FileCacheScanner extends Thread { + private boolean stopping = false; public void setStopping(boolean flag) @@ -386,41 +393,51 @@ /** * Run the file scanner thread - * + * */ public void run() { boolean done = false; - + try { - while(!done) + while (!done) { try { int count = 0; - Collection values = Collections.synchronizedCollection(FileCache.this.cache.values()); + Collection values = Collections + .synchronizedCollection(FileCache.this.cache + .values()); synchronized (values) { - for (Iterator it = values.iterator(); it.hasNext(); ) + for (Iterator it = values.iterator(); it.hasNext();) { - FileCacheEntry entry = (FileCacheEntry) it.next(); - Date modified = new Date(entry.getFile().lastModified()); - + FileCacheEntry entry = (FileCacheEntry) it + .next(); + Date modified = new Date(entry.getFile() + .lastModified()); + if (modified.after(entry.getLastModified())) - { - for (Iterator lit = FileCache.this.listeners.iterator(); lit.hasNext(); ) + { + for (Iterator lit = FileCache.this.listeners + .iterator(); lit.hasNext();) { - FileCacheEventListener listener = - (FileCacheEventListener) lit.next(); + FileCacheEventListener listener = (FileCacheEventListener) lit + .next(); try { listener.refresh(entry); } catch (Exception e1) { - log.warn("Unable to refresh cached document: "+e1.toString(), e1); - } + log + .warn( + "Unable to refresh cached document: " + + e1 + .toString(), + e1); + } entry.setLastModified(modified); } } @@ -434,11 +451,14 @@ } catch (Exception e) { - log.error("FileCache Scanner: Error in iteration...", e); + log + .error( + "FileCache Scanner: Error in iteration...", + e); } - - sleep(FileCache.this.getScanRate() * 1000); + sleep(FileCache.this.getScanRate() * 1000); + if (this.stopping) { this.stopping = false; @@ -448,15 +468,15 @@ } catch (InterruptedException e) { - log.error("FileCacheScanner: recieved interruption, exiting.", e); + log.error("FileCacheScanner: recieved interruption, exiting.", + e); } } - } // end inner class: FileCacheScanner + } // end inner class: FileCacheScanner - /** * get an iterator over the cache values - * + * * @return iterator over the cache values */ public Iterator getIterator() @@ -465,13 +485,12 @@ } /** - * get the size of the cache - * - * @return the size of the cache - */ + * get the size of the cache + * + * @return the size of the cache + */ public int getSize() { return cache.size(); } } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/java/org/apache/jetspeed/cache/file/FileCacheEntryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/java/org/apache/jetspeed/cache/file/FileCacheEntryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/java/org/apache/jetspeed/cache/file/FileCacheEntryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,17 +22,20 @@ /** * FileCache entry keeps the cached content along with last access information. - * - * @author David S. Taylor David Sean Taylor - * @version $Id: FileCacheEntryImpl.java 516448 2007-03-09 16:25:47Z ate $ + * + * @author David S. Taylor David Sean Taylor + * @version $Id: FileCacheEntryImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class FileCacheEntryImpl implements FileCacheEntry { + protected File file; + protected Object document; protected long lastAccessed; + protected Date lastModified; private FileCacheEntryImpl() @@ -41,9 +44,11 @@ /** * Constructs a FileCacheEntry object - * - * @param document The user specific content being cached - * @param lastModified The document's last modified stamp + * + * @param document + * The user specific content being cached + * @param lastModified + * The document's last modified stamp */ public FileCacheEntryImpl(File file, Object document) { @@ -55,7 +60,7 @@ /** * Get the file descriptor - * + * * @return the file descriptor */ public File getFile() @@ -65,8 +70,9 @@ /** * Set the file descriptor - * - * @param file the new file descriptor + * + * @param file + * the new file descriptor */ public void setFile(File file) { @@ -75,8 +81,9 @@ /** * Set the cache's last accessed stamp - * - * @param lastAccessed the cache's last access stamp + * + * @param lastAccessed + * the cache's last access stamp */ public void setLastAccessed(long lastAccessed) { @@ -85,7 +92,7 @@ /** * Get the cache's lastAccessed stamp - * + * * @return the cache's last accessed stamp */ public long getLastAccessed() @@ -95,8 +102,9 @@ /** * Set the cache's last modified stamp - * - * @param lastModified the cache's last modified stamp + * + * @param lastModified + * the cache's last modified stamp */ public void setLastModified(Date lastModified) { @@ -104,8 +112,9 @@ } /** - * Get the entry's lastModified stamp (which may be stale compared to file's stamp) - * + * Get the entry's lastModified stamp (which may be stale compared to file's + * stamp) + * * @return the last modified stamp */ public Date getLastModified() @@ -115,8 +124,9 @@ /** * Set the Document in the cache - * - * @param document the document being cached + * + * @param document + * the document being cached */ public void setDocument(Object document) { @@ -125,7 +135,7 @@ /** * Get the Document - * + * * @return the document being cached */ public Object getDocument() @@ -134,5 +144,3 @@ } } - - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/test/org/apache/jetspeed/cache/file/FileCopy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/test/org/apache/jetspeed/cache/file/FileCopy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/test/org/apache/jetspeed/cache/file/FileCopy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.jetspeed.cache.file; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; @@ -27,32 +28,34 @@ /* * File Copy Utilities. Some utilities that java.io doesn't give us. - * - * copy() - copies one file source to another file destination. - * copyFromURL)() - copies from a URL source to a file destination. - * - * NOTE: tried to be a good Commons-citizen and use io out of the sandbox - * at the time it was dependent on an older version of commons-lang for a predicate class bs bs - * - * @author David S. Taylor David Sean Taylor + * + * copy() - copies one file source to another file destination. copyFromURL)() - + * copies from a URL source to a file destination. + * + * NOTE: tried to be a good Commons-citizen and use io out of the sandbox at the + * time it was dependent on an older version of commons-lang for a predicate + * class bs bs + * + * @author David S. Taylor David Sean Taylor + * * @version $Id: FileCopy.java 516448 2007-03-09 16:25:47Z ate $ */ -public class FileCopy +public class FileCopy { + public static final int BUFFER_SIZE = 4096; /* - * Copies one file source to another file destination. - * - * @param source The source file. - * @param destination The destination file. + * Copies one file source to another file destination. + * + * @param source The source file. @param destination The destination file. * @throws IOException When an IO error occurs, this exception is thrown. */ public static final void copy(String source, String destination) - throws IOException + throws IOException { - byte[] buffer = new byte[BUFFER_SIZE]; + byte[] buffer = new byte[BUFFER_SIZE]; BufferedInputStream input; BufferedOutputStream output; @@ -66,46 +69,41 @@ } /* - * Copies from a URL source to a file destination. - * - * @param source The source URL. - * @param destination The destination file. + * Copies from a URL source to a file destination. + * + * @param source The source URL. @param destination The destination file. * @throws IOException When an IO error occurs, this exception is thrown. */ public static final void copyFromURL(String source, String destination) - throws IOException + throws IOException { - byte[] buffer = new byte[BUFFER_SIZE]; + byte[] buffer = new byte[BUFFER_SIZE]; URL url = new URL(source); - BufferedInputStream input; - BufferedOutputStream output; - - + BufferedInputStream input; + BufferedOutputStream output; + input = new BufferedInputStream(new DataInputStream(url.openStream())); output = new BufferedOutputStream(new FileOutputStream(destination)); - + copyStream(input, output, buffer); - + input.close(); output.close(); } /* - * Generic copy from a input stream to an output stream. - * - * @param input The source input stream. - * @param output The destination output stream. - * @param buffer The user provided buffer. - * @throws IOException When an IO error occurs, this exception is thrown. + * Generic copy from a input stream to an output stream. + * + * @param input The source input stream. @param output The destination + * output stream. @param buffer The user provided buffer. @throws + * IOException When an IO error occurs, this exception is thrown. */ - public static final void copyStream(InputStream input, - OutputStream output, - byte[] buffer) - throws IOException + public static final void copyStream(InputStream input, OutputStream output, + byte[] buffer) throws IOException { int bytesRead; - while((bytesRead = input.read(buffer)) != -1) + while ((bytesRead = input.read(buffer)) != -1) output.write(buffer, 0, bytesRead); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/test/org/apache/jetspeed/cache/file/TestFileCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/test/org/apache/jetspeed/cache/file/TestFileCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/file-cache/src/test/org/apache/jetspeed/cache/file/TestFileCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,45 +30,45 @@ import org.apache.commons.io.StreamUtils; import org.apache.commons.lang.exception.ExceptionUtils; - /** - * Unit test for FileCache + * Unit test for FileCache * * @author David Sean Taylor * @version $Id: TestFileCache.java 516448 2007-03-09 16:25:47Z ate $ */ public class TestFileCache extends TestCase implements FileCacheEventListener -{ +{ + protected static final String TEST_DIRECTORY = "./testdata"; + protected static final int CACHE_SIZE = 20; + protected static final int SCAN_RATE = 10; + String refreshedEntry = null; - - /** * Creates the test suite. - * - * @return a test suite (TestSuite) that includes all methods - * starting with "test" + * + * @return a test suite (TestSuite) that includes all + * methods starting with "test" */ - public static Test suite() + public static Test suite() { // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestFileCache.class); } - - + private FileCache cache = null; - + protected void setUp() throws Exception { super.setUp(); - + cache = new FileCache(SCAN_RATE, CACHE_SIZE); - } - + } + /** * @see junit.framework.TestCase#tearDown() */ @@ -78,34 +78,36 @@ removeTestFiles(); } - /** + /** * Tests loading the cache + * * @throws Exception */ - public void testLoadCache() throws Exception - { - String templateFile = TEST_DIRECTORY+"/default.psml"; + public void testLoadCache() throws Exception + { + String templateFile = TEST_DIRECTORY + "/default.psml"; try { - File file = new File(templateFile); + File file = new File(templateFile); assertTrue(file.exists()); createTestFiles(templateFile); - // create the Cache wake up after 10 seconds, cache size 20 + // create the Cache wake up after 10 seconds, cache size 20 // FileCache cache = new FileCache(10, 20); // load the Cache File directory = new File(TEST_DIRECTORY); File[] files = directory.listFiles(); - for (int ix=0; ix < files.length; ix++) + for (int ix = 0; ix < files.length; ix++) { - if (files[ix].isDirectory() || files[ix].getName().equals(".cvsignore")) + if (files[ix].isDirectory() + || files[ix].getName().equals(".cvsignore")) { continue; } - String testData = readFile(files[ix]); + String testData = readFile(files[ix]); cache.put(files[ix], testData); } @@ -126,21 +128,22 @@ // Reload files array to get the files back in the correct order // because the cache CAN have reordered them while evicting. - // This can happen if test files where left over from a previous + // This can happen if test files where left over from a previous // test which then will have an older timestamp. // In that case it is NOT garanteed that files[18] below will still // be in the cache! // Note: this is only an issue for the test itself and not for the - // cache as such. + // cache as such. Iterator it = cache.getIterator(); - for ( int ix = 0; it.hasNext(); ix++ ) + for (int ix = 0; it.hasNext(); ix++) { FileCacheEntry entry = (FileCacheEntry) it.next(); files[ix] = entry.getFile(); } - String stuff = (String) cache.getDocument(files[18].getCanonicalPath()); + String stuff = (String) cache.getDocument(files[18] + .getCanonicalPath()); assertNotNull(stuff); files[18].setLastModified(new Date().getTime()); @@ -168,28 +171,27 @@ } private void createTestFiles(String templateFile) - throws java.io.IOException + throws java.io.IOException { - for (int ix=1; ix < 31; ix++) + for (int ix = 1; ix < 31; ix++) { - String testFile = TEST_DIRECTORY+"/testFile-" + ix + ".psml"; + String testFile = TEST_DIRECTORY + "/testFile-" + ix + ".psml"; FileCopy.copy(templateFile, testFile); } } private void removeTestFiles() { - for (int ix=1; ix < 31; ix++) + for (int ix = 1; ix < 31; ix++) { - String testFile = TEST_DIRECTORY+"/testFile-" + ix + ".psml"; + String testFile = TEST_DIRECTORY + "/testFile-" + ix + ".psml"; File file = new File(testFile); - if ( file.exists() ) - file.delete(); + if (file.exists()) file.delete(); } } - private String readFile(File file) - throws java.io.IOException, java.io.FileNotFoundException + private String readFile(File file) throws java.io.IOException, + java.io.FileNotFoundException { BufferedInputStream input; @@ -201,8 +203,9 @@ /** * Refresh event, called when the entry is being refreshed from file system. - * - * @param entry the entry being refreshed. + * + * @param entry + * the entry being refreshed. */ public void refresh(FileCacheEntry entry) { @@ -212,8 +215,9 @@ /** * Evict event, called when the entry is being evicted out of the cache - * - * @param entry the entry being refreshed. + * + * @param entry + * the entry being refreshed. */ public void evict(FileCacheEntry entry) { @@ -222,17 +226,11 @@ private void dumpCache(Iterator it) { - for ( ; it.hasNext(); ) + for (; it.hasNext();) { FileCacheEntry entry = (FileCacheEntry) it.next(); System.out.println(entry.getFile().getName()); } } - -} - - - - - +} Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/header-resource/src/java/org/apache/jetspeed/headerresource/impl/HeaderResourceFactoryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/header-resource/src/java/org/apache/jetspeed/headerresource/impl/HeaderResourceFactoryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/header-resource/src/java/org/apache/jetspeed/headerresource/impl/HeaderResourceFactoryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,28 +30,39 @@ * Default implementation for HeaderResourceFactory * * @author Shinsuke Sugaya - * @version $Id: PortalReservedParameters.java 188569 2005-05-13 13:35:18Z weaver $ + * @version $Id: PortalReservedParameters.java 188569 2005-05-13 13:35:18Z + * weaver $ */ public class HeaderResourceFactoryImpl implements HeaderResourceFactory { - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.headerresource.impl.HeaderResourceFactory#getHeaderResouce(org.apache.jetspeed.request.RequestContext) */ public HeaderResource getHeaderResouce(RequestContext requestContext) { return new HeaderResourceImpl(requestContext); } - public HeaderResource getHeaderResource(RequestContext requestContext, BasePortalURL baseUrlAccess, boolean isDesktop, Map headerConfiguration ) + + public HeaderResource getHeaderResource(RequestContext requestContext, + BasePortalURL baseUrlAccess, boolean isDesktop, + Map headerConfiguration) { - return new HeaderResourceImpl(requestContext, baseUrlAccess, isDesktop, headerConfiguration ); + return new HeaderResourceImpl(requestContext, baseUrlAccess, isDesktop, + headerConfiguration); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.headerresource.impl.HeaderResourceFactory#getHeaderResouce(javax.portlet.PortletRequest) */ public HeaderResource getHeaderResouce(PortletRequest request) { - RequestContext requestContext=(RequestContext)request.getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); + RequestContext requestContext = (RequestContext) request + .getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); return new HeaderResourceImpl(requestContext); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/header-resource/src/java/org/apache/jetspeed/headerresource/impl/HeaderResourceImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/header-resource/src/java/org/apache/jetspeed/headerresource/impl/HeaderResourceImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/header-resource/src/java/org/apache/jetspeed/headerresource/impl/HeaderResourceImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,24 +16,23 @@ */ package org.apache.jetspeed.headerresource.impl; +import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; +import java.util.List; import java.util.Map; -import java.util.List; -import java.util.ArrayList; import java.util.Set; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.apache.jetspeed.PortalReservedParameters; import org.apache.jetspeed.container.url.BasePortalURL; import org.apache.jetspeed.headerresource.HeaderResource; import org.apache.jetspeed.headerresource.HeaderResourceLib; import org.apache.jetspeed.request.RequestContext; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - /** * Default implementation for HeaderResource * @@ -43,54 +42,64 @@ */ public class HeaderResourceImpl implements HeaderResource { - protected final static Log log = LogFactory.getLog( HeaderResourceImpl.class ); - - protected final static String EOL = "\r\n"; // html eol + + protected final static Log log = LogFactory + .getLog(HeaderResourceImpl.class); + + protected final static String EOL = "\r\n"; // html eol + protected final static String UNNAMED_CONTENT_HEADER_NAME = "org.apache.jetspeed.headerresource.unnamed"; - + private RequestContext requestContext; - + // base portal url to override default url server info from servlet private BasePortalURL baseUrlAccess = null; - + private boolean isDesktop; - + private Map headerConfiguration; - // ... mutable output tracking - // - when depending on this feature, one HeaderResourceImpl instance must process all header inclusion + // - when depending on this feature, one HeaderResourceImpl instance must + // process all header inclusion private HashMap namedResourcesAlreadyOutput; - + // ... as needed, these are obtained from request attributes private Map headerDynamicConfiguration; + private Map headerNamedResources; + private Map headerNamedResourcesAddedFragments; + private Map headerResourceRegistry; - + // ... save generated portal urls to avoid duplicate effort private String portalBaseUrl; + private String portalUrl; - + /** * Default Constructor * * @param context */ - public HeaderResourceImpl( RequestContext context ) + public HeaderResourceImpl(RequestContext context) { this.requestContext = context; } - public HeaderResourceImpl( RequestContext context, BasePortalURL baseUrlAccess, boolean isDesktop, Map headerConfiguration ) + + public HeaderResourceImpl(RequestContext context, + BasePortalURL baseUrlAccess, boolean isDesktop, + Map headerConfiguration) { this.requestContext = context; this.baseUrlAccess = baseUrlAccess; - + this.isDesktop = isDesktop; - + this.headerConfiguration = headerConfiguration; } - + /** * Output all content (that has not already been output) * @@ -99,11 +108,11 @@ public String getContent() { StringBuffer header = new StringBuffer(); - getNamedResourceContent( null, false, header ); - getUnnamedContent( header ); + getNamedResourceContent(null, false, header); + getUnnamedContent(header); return header.toString(); } - + /** * Output all content (that has not already been output) * @@ -115,14 +124,15 @@ } /** - * Output all unnamed (getHeaderInfoSet()) content (that has not already been output) + * Output all unnamed (getHeaderInfoSet()) content (that has not already + * been output) * * @return content string for inclusion in html <head> */ public String getUnnamedContent() { StringBuffer header = new StringBuffer(); - getUnnamedContent( header ); + getUnnamedContent(header); return header.toString(); } @@ -134,506 +144,545 @@ public String getNamedContent() { StringBuffer header = new StringBuffer(); - getNamedResourceContent( null, false, header ); + getNamedResourceContent(null, false, header); return header.toString(); } - + /** - * Output the one getHeaderSections() content entry with a key that matches headerName (if it has not already been output) + * Output the one getHeaderSections() content entry with a key that matches + * headerName (if it has not already been output) * * @return content string for inclusion in html <head> */ - public String getNamedContent( String headerName ) + public String getNamedContent(String headerName) { StringBuffer header = new StringBuffer(); - getNamedResourceContent( headerName, false, header ); + getNamedResourceContent(headerName, false, header); return header.toString(); } - + /** - * Output getHeaderSections() content entries with key prefixes that match headerNamePrefix (if it has not already been output) + * Output getHeaderSections() content entries with key prefixes that match + * headerNamePrefix (if it has not already been output) * * @return content string for inclusion in html <head> */ - public String getNamedContentForPrefix( String headerNamePrefix ) + public String getNamedContentForPrefix(String headerNamePrefix) { - if ( headerNamePrefix == null ) - headerNamePrefix = ""; - if ( ! headerNamePrefix.endsWith( "." ) ) + if (headerNamePrefix == null) headerNamePrefix = ""; + if (!headerNamePrefix.endsWith(".")) headerNamePrefix = headerNamePrefix + "."; StringBuffer header = new StringBuffer(); - getNamedResourceContent( headerNamePrefix, true, header ); + getNamedResourceContent(headerNamePrefix, true, header); return header.toString(); } - + /* * Output all getHeaderInfoSet() content (that has not already been output) */ - protected void getUnnamedContent( StringBuffer header ) + protected void getUnnamedContent(StringBuffer header) { HashMap namedResourcesInOutput = getNamedResourcesAlreadyOutput(); - if ( namedResourcesInOutput == null ) + if (namedResourcesInOutput == null) { namedResourcesInOutput = new HashMap(); - setNamedResourcesAlreadyOutput( namedResourcesInOutput ); + setNamedResourcesAlreadyOutput(namedResourcesInOutput); } - if ( ! namedResourcesInOutput.containsKey( UNNAMED_CONTENT_HEADER_NAME ) ) + if (!namedResourcesInOutput.containsKey(UNNAMED_CONTENT_HEADER_NAME)) { - namedResourcesInOutput.put( UNNAMED_CONTENT_HEADER_NAME, Boolean.TRUE ); + namedResourcesInOutput.put(UNNAMED_CONTENT_HEADER_NAME, + Boolean.TRUE); Set headerInfoSet = getHeaderInfoSet(); - for ( Iterator ite = headerInfoSet.iterator(); ite.hasNext(); ) + for (Iterator ite = headerInfoSet.iterator(); ite.hasNext();) { - header.append( ((HeaderInfo) ite.next()).toString() ); - header.append( EOL ); + header.append(((HeaderInfo) ite.next()).toString()); + header.append(EOL); } } } - + /* - * Output getHeaderSections() content (that has not already been output) with regard to optional match arguments + * Output getHeaderSections() content (that has not already been output) + * with regard to optional match arguments */ - protected void getNamedResourceContent( String headerNameMatch, boolean headerNameMatchPrefixOnly, StringBuffer header ) + protected void getNamedResourceContent(String headerNameMatch, + boolean headerNameMatchPrefixOnly, StringBuffer header) { - List headerOrderList = getHeaderSectionOrderList( false ); - if ( headerOrderList != null && headerOrderList.size() > 0 ) + List headerOrderList = getHeaderSectionOrderList(false); + if (headerOrderList != null && headerOrderList.size() > 0) { HashMap namedResourcesInOutput = getNamedResourcesAlreadyOutput(); - if ( namedResourcesInOutput == null ) + if (namedResourcesInOutput == null) { namedResourcesInOutput = new HashMap(); - setNamedResourcesAlreadyOutput( namedResourcesInOutput ); + setNamedResourcesAlreadyOutput(namedResourcesInOutput); } Map namedResources = getHeaderSections(); Map dynamicConfig = getHeaderDynamicConfiguration(); - Map headerTypes = getHeaderSectionTypes( false ); + Map headerTypes = getHeaderSectionTypes(false); Map headerRsrcRegistry = getHeaderResourceRegistry(); HashMap headerReqFlagResults = new HashMap(); boolean inScriptBlock = false; boolean inStyleBlock = false; Iterator headerOrderListIter = headerOrderList.iterator(); - while ( headerOrderListIter.hasNext() ) + while (headerOrderListIter.hasNext()) { - String headerName = (String)headerOrderListIter.next(); - if ( namedResourcesInOutput.containsKey( headerName ) ) + String headerName = (String) headerOrderListIter.next(); + if (namedResourcesInOutput.containsKey(headerName)) { continue; } - if ( headerNameMatch != null ) + if (headerNameMatch != null) { - if ( headerNameMatchPrefixOnly ) + if (headerNameMatchPrefixOnly) { - if ( ! headerName.startsWith( headerNameMatch ) ) + if (!headerName.startsWith(headerNameMatch)) { continue; } } else { - if ( ! headerName.equals( headerNameMatch ) ) + if (!headerName.equals(headerNameMatch)) { continue; } } } boolean includeHeader = true; - Object[] headerTypePair = ( ( headerTypes != null ) ? (Object[])headerTypes.get( headerName ) : (Object[])null ); - String headerReqFlag = ( ( headerTypePair != null ) ? (String)headerTypePair[1] : (String)null ); - if ( headerReqFlag != null && headerReqFlag.length() > 0 ) + Object[] headerTypePair = ((headerTypes != null) ? (Object[]) headerTypes + .get(headerName) + : (Object[]) null); + String headerReqFlag = ((headerTypePair != null) ? (String) headerTypePair[1] + : (String) null); + if (headerReqFlag != null && headerReqFlag.length() > 0) { - Boolean headerReqFlagResult = (Boolean)headerReqFlagResults.get( headerReqFlag ); - if ( headerReqFlagResult == null ) + Boolean headerReqFlagResult = (Boolean) headerReqFlagResults + .get(headerReqFlag); + if (headerReqFlagResult == null) { headerReqFlagResult = Boolean.FALSE; - Object headerReqFlagValObj = dynamicConfig.get( headerReqFlag ); - if ( headerReqFlagValObj != null ) - headerReqFlagResult = new Boolean( headerReqFlagValObj.toString() ); - headerReqFlagResults.put( headerReqFlag, headerReqFlagResult ); + Object headerReqFlagValObj = dynamicConfig + .get(headerReqFlag); + if (headerReqFlagValObj != null) + headerReqFlagResult = new Boolean( + headerReqFlagValObj.toString()); + headerReqFlagResults.put(headerReqFlag, + headerReqFlagResult); } includeHeader = headerReqFlagResult.booleanValue(); } - if ( includeHeader ) + if (includeHeader) { - namedResourcesInOutput.put( headerName, Boolean.TRUE ); - Integer headerTypeIdObj = ( ( headerTypePair != null ) ? (Integer)headerTypePair[0] : (Integer)null ); - int headerTypeId = ( ( headerTypeIdObj != null ) ? headerTypeIdObj.intValue() : HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK ); + namedResourcesInOutput.put(headerName, Boolean.TRUE); + Integer headerTypeIdObj = ((headerTypePair != null) ? (Integer) headerTypePair[0] + : (Integer) null); + int headerTypeId = ((headerTypeIdObj != null) ? headerTypeIdObj + .intValue() + : HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK); boolean requiresScriptBlock = false; boolean requiresStyleBlock = false; boolean preCloseBlock = false; boolean postCloseBlock = false; - - switch ( headerTypeId ) + + switch (headerTypeId) { - case HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK: - { - requiresScriptBlock = true; - break; - } - case HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK_START: - { - preCloseBlock = true; - requiresScriptBlock = true; - break; - } - case HeaderResource.HEADER_TYPE_ID_SCRIPT_TAG: - { - preCloseBlock = true; - break; - } - case HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK_END: - { - postCloseBlock = true; - requiresScriptBlock = true; - break; - } - case HeaderResource.HEADER_TYPE_ID_STYLE_BLOCK: - { - requiresStyleBlock = true; - break; - } - case HeaderResource.HEADER_TYPE_ID_LINK_TAG: - { - preCloseBlock = true; - break; - } - case HeaderResource.HEADER_TYPE_ID_BASE_TAG: - { - preCloseBlock = true; - break; - } - default: - { - log.error( "HeaderResource.getNamedResourceContent() cannot include header section with unknown type; header-section-name=" + headerName + " header-section-type-id=" + headerTypeId ); - includeHeader = false; - break; - } + case HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK: { + requiresScriptBlock = true; + break; } - if ( includeHeader ) + case HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK_START: { + preCloseBlock = true; + requiresScriptBlock = true; + break; + } + case HeaderResource.HEADER_TYPE_ID_SCRIPT_TAG: { + preCloseBlock = true; + break; + } + case HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK_END: { + postCloseBlock = true; + requiresScriptBlock = true; + break; + } + case HeaderResource.HEADER_TYPE_ID_STYLE_BLOCK: { + requiresStyleBlock = true; + break; + } + case HeaderResource.HEADER_TYPE_ID_LINK_TAG: { + preCloseBlock = true; + break; + } + case HeaderResource.HEADER_TYPE_ID_BASE_TAG: { + preCloseBlock = true; + break; + } + default: { + log + .error("HeaderResource.getNamedResourceContent() cannot include header section with unknown type; header-section-name=" + + headerName + + " header-section-type-id=" + + headerTypeId); + includeHeader = false; + break; + } + } + if (includeHeader) { - if ( requiresScriptBlock && inStyleBlock ) + if (requiresScriptBlock && inStyleBlock) { preCloseBlock = true; } - else if ( requiresStyleBlock && inScriptBlock ) + else if (requiresStyleBlock && inScriptBlock) { preCloseBlock = true; } - if ( preCloseBlock ) + if (preCloseBlock) { - if ( inScriptBlock ) + if (inScriptBlock) { - header.append( "" ).append( EOL ); + header.append("").append(EOL); inScriptBlock = false; } - else if ( inStyleBlock ) + else if (inStyleBlock) { - header.append( "" ).append( EOL ); + header.append("").append(EOL); inStyleBlock = false; } } - - String headerText = (String)namedResources.get( headerName ); - if ( headerText == null ) + + String headerText = (String) namedResources + .get(headerName); + if (headerText == null) { - headerText = generateHeaderSection( headerName ); - if ( headerText == null && headerRsrcRegistry != null ) - { - headerText = (String)headerRsrcRegistry.get( headerName ); - log.debug( "header resource registry text for header section=" + headerName + " headerText=" + headerText ); + headerText = generateHeaderSection(headerName); + if (headerText == null + && headerRsrcRegistry != null) + { + headerText = (String) headerRsrcRegistry + .get(headerName); + log + .debug("header resource registry text for header section=" + + headerName + + " headerText=" + + headerText); } } - if ( headerText != null && headerText.length() > 0 ) + if (headerText != null && headerText.length() > 0) { - if ( requiresScriptBlock && ! inScriptBlock ) + if (requiresScriptBlock && !inScriptBlock) { - header.append( "" ).append( EOL ); + header.append("").append(EOL); inScriptBlock = false; } - else if ( inStyleBlock ) + else if (inStyleBlock) { - header.append( "" ).append( EOL ); + header.append("").append(EOL); inStyleBlock = false; } } } - } // if ( includeHeader ) - } // while ( headerOrderListIter.hasNext() ) - if ( inScriptBlock ) + } // if ( includeHeader ) + } // while ( headerOrderListIter.hasNext() ) + if (inScriptBlock) { - header.append( "" ).append( EOL ); + header.append("").append(EOL); inScriptBlock = false; } - else if ( inStyleBlock ) + else if (inStyleBlock) { - header.append( "" ).append( EOL ); + header.append("").append(EOL); inStyleBlock = false; } - } // if ( headerOrderList != null && headerOrderList.size() > 0 ) + } // if ( headerOrderList != null && headerOrderList.size() > 0 ) } - + /* * Intended as derived class hook into late, auto-generated header resources */ - protected String generateHeaderSection( String headerName ) + protected String generateHeaderSection(String headerName) { - if ( headerName != null ) + if (headerName != null) { - if ( headerName.equals( HEADER_SECTION_BASE_TAG ) ) + if (headerName.equals(HEADER_SECTION_BASE_TAG)) { return jetspeedGenerateBasetag(); } - else if ( headerName.startsWith( HEADER_SECTION_NAME_PREFIX_DOJO ) ) + else if (headerName.startsWith(HEADER_SECTION_NAME_PREFIX_DOJO)) { - if ( headerName.equals( HEADER_SECTION_DOJO_PREINIT ) ) + if (headerName.equals(HEADER_SECTION_DOJO_PREINIT)) { return dojoGeneratePreinit(); } - else if ( headerName.equals( HEADER_SECTION_DOJO_INIT ) ) + else if (headerName.equals(HEADER_SECTION_DOJO_INIT)) { return dojoGenerateInit(); } - else if ( headerName.equals( HEADER_SECTION_DOJO_WRITEINCLUDES ) ) + else if (headerName.equals(HEADER_SECTION_DOJO_WRITEINCLUDES)) { return dojoGenerateWriteincludes(); } - else if ( headerName.equals( HEADER_SECTION_DOJO_STYLE_BODYEXPAND ) ) + else if (headerName + .equals(HEADER_SECTION_DOJO_STYLE_BODYEXPAND)) { return dojoGenerateBodyExpandStyle(); } - else if ( headerName.equals( HEADER_SECTION_DOJO_STYLE_BODYEXPAND_NOSCROLL ) ) - { - return dojoGenerateBodyExpandNoScrollStyle(); - } + else if (headerName + .equals(HEADER_SECTION_DOJO_STYLE_BODYEXPAND_NOSCROLL)) { return dojoGenerateBodyExpandNoScrollStyle(); } } } return null; } - + /** - * Add text argument to the getHeaderSections() content entry with a key that matches addToHeaderName argument + * Add text argument to the getHeaderSections() content entry with a key + * that matches addToHeaderName argument * */ - public void addHeaderSectionFragment( String addToHeaderName, String text ) + public void addHeaderSectionFragment(String addToHeaderName, String text) { - addHeaderSectionFragment( null, addToHeaderName, text, false ); + addHeaderSectionFragment(null, addToHeaderName, text, false); } - + /** - * If no previous call using value of headerFragmentName argument has been added to any getHeaderSections() content entry, - * add text argument to the getHeaderSections() content entry with a key that matches addToHeaderName argument + * If no previous call using value of headerFragmentName argument has been + * added to any getHeaderSections() content entry, add text argument to the + * getHeaderSections() content entry with a key that matches addToHeaderName + * argument * */ - public void addHeaderSectionFragment( String headerFragmentName, String addToHeaderName, String text ) + public void addHeaderSectionFragment(String headerFragmentName, + String addToHeaderName, String text) { - addHeaderSectionFragment( headerFragmentName, addToHeaderName, text, false ); + addHeaderSectionFragment(headerFragmentName, addToHeaderName, text, + false); } - - protected void addHeaderSectionFragment( String headerFragmentName, String addToHeaderName, String text, boolean alreadyCheckedFragName ) + + protected void addHeaderSectionFragment(String headerFragmentName, + String addToHeaderName, String text, boolean alreadyCheckedFragName) { - if ( addToHeaderName != null && text != null ) + if (addToHeaderName != null && text != null) { boolean addText = true; - if ( ! alreadyCheckedFragName && headerFragmentName != null && hasHeaderSectionFragment( headerFragmentName, true ) ) + if (!alreadyCheckedFragName && headerFragmentName != null + && hasHeaderSectionFragment(headerFragmentName, true)) { addText = false; } - if ( addText ) + if (addText) { Map headerRsrcRegistry = getHeaderResourceRegistry(); - if ( headerRsrcRegistry != null ) + if (headerRsrcRegistry != null) { - String overrideText = (String)headerRsrcRegistry.get( headerFragmentName ); - if ( overrideText != null ) + String overrideText = (String) headerRsrcRegistry + .get(headerFragmentName); + if (overrideText != null) { text = overrideText; } } Map namedResources = getHeaderSections(); - String nText = (String)namedResources.get( addToHeaderName ); - if ( nText == null ) + String nText = (String) namedResources.get(addToHeaderName); + if (nText == null) { nText = text + EOL; - orderHeaderSection( addToHeaderName ); + orderHeaderSection(addToHeaderName); } else { nText = nText + text + EOL; } - namedResources.put( addToHeaderName, nText ); + namedResources.put(addToHeaderName, nText); } } } - + /** - * Indicate whether value of headerFragmentName argument has been used to add to any getHeaderSections() content entry + * Indicate whether value of headerFragmentName argument has been used to + * add to any getHeaderSections() content entry * - * @return true if headerFragmentName argument has been used to add to any getHeaderSections() content entry + * @return true if headerFragmentName argument has been used to add to any + * getHeaderSections() content entry */ - public boolean hasHeaderSectionFragment( String headerFragmentName ) + public boolean hasHeaderSectionFragment(String headerFragmentName) { - return hasHeaderSectionFragment( headerFragmentName, false ); + return hasHeaderSectionFragment(headerFragmentName, false); } - protected boolean hasHeaderSectionFragment( String headerFragmentName, boolean setToTrue ) + + protected boolean hasHeaderSectionFragment(String headerFragmentName, + boolean setToTrue) { - if ( headerFragmentName != null ) + if (headerFragmentName != null) { Map namedResourcesAddedFragments = getHeaderSectionsAddedFragments(); - if ( namedResourcesAddedFragments.containsKey( headerFragmentName ) ) + if (namedResourcesAddedFragments.containsKey(headerFragmentName)) { return true; } - else if ( setToTrue ) + else if (setToTrue) { - namedResourcesAddedFragments.put( headerFragmentName, Boolean.TRUE ); + namedResourcesAddedFragments.put(headerFragmentName, + Boolean.TRUE); } } return false; } - - protected void orderHeaderSection( String headerName ) + + protected void orderHeaderSection(String headerName) { - if ( headerName != null ) + if (headerName != null) { - Map headerNames = getHeaderSectionNames( true ); - if ( ! headerNames.containsKey( headerName ) ) + Map headerNames = getHeaderSectionNames(true); + if (!headerNames.containsKey(headerName)) { - List headerOrderList = getHeaderSectionOrderList( true ); - - headerOrderList.add( headerName ); - headerNames.put( headerName, Boolean.TRUE ); + List headerOrderList = getHeaderSectionOrderList(true); + + headerOrderList.add(headerName); + headerNames.put(headerName, Boolean.TRUE); } } } - + /** * Indicate whether value of headerName is an included header section * * @return true if headerName argument is an included header section */ - public boolean isHeaderSectionIncluded( String headerName ) + public boolean isHeaderSectionIncluded(String headerName) { - if ( headerName != null ) + if (headerName != null) { - Map headerNames = getHeaderSectionNames( false ); - if ( headerNames != null && headerNames.get( headerName ) != null ) - { - return true; - } + Map headerNames = getHeaderSectionNames(false); + if (headerNames != null && headerNames.get(headerName) != null) { return true; } } return false; } - + /** - * Get the type of the getHeaderSections() content entry with a key that matches headerName argument + * Get the type of the getHeaderSections() content entry with a key that + * matches headerName argument * * @return type of header section */ - public String getHeaderSectionType( String headerName ) + public String getHeaderSectionType(String headerName) { - if ( headerName != null ) + if (headerName != null) { - Map headerTypes = getHeaderSectionTypes( false ); - if ( headerTypes != null ) + Map headerTypes = getHeaderSectionTypes(false); + if (headerTypes != null) { - Object[] headerTypePair = (Object[])headerTypes.get( headerName ); - if ( headerTypePair != null ) + Object[] headerTypePair = (Object[]) headerTypes + .get(headerName); + if (headerTypePair != null) { - Integer headerTypeId = (Integer)headerTypePair[0]; - return HeaderResourceLib.getHeaderType( headerTypeId ); + Integer headerTypeId = (Integer) headerTypePair[0]; + return HeaderResourceLib.getHeaderType(headerTypeId); } } } return null; } - + /** - * Set the type of the getHeaderSections() content entry with a key that matches headerName argument - * to the value of the headerType argument + * Set the type of the getHeaderSections() content entry with a key that + * matches headerName argument to the value of the headerType argument */ - public void setHeaderSectionType( String headerName, String headerType ) + public void setHeaderSectionType(String headerName, String headerType) { - if ( headerName != null ) + if (headerName != null) { - int headerTypeId = HeaderResourceLib.getHeaderTypeId( headerType ); - if ( headerTypeId < 0 ) + int headerTypeId = HeaderResourceLib.getHeaderTypeId(headerType); + if (headerTypeId < 0) { - log.error( "HeaderResourceImpl.setHeaderSectionType() ignoring specification of unknown header section type; header-section-name=" + headerName + " header-section-type=" + headerType ); + log + .error("HeaderResourceImpl.setHeaderSectionType() ignoring specification of unknown header section type; header-section-name=" + + headerName + + " header-section-type=" + + headerType); } else { - Map headerTypes = getHeaderSectionTypes( true ); - Object[] headerTypePair = (Object[])headerTypes.get( headerName ); - if ( headerTypePair == null ) + Map headerTypes = getHeaderSectionTypes(true); + Object[] headerTypePair = (Object[]) headerTypes + .get(headerName); + if (headerTypePair == null) { - if ( headerType != null ) + if (headerType != null) { - headerTypePair = new Object[] { new Integer( headerTypeId ), null }; - headerTypes.put( headerName, headerTypePair ); + headerTypePair = new Object[] + {new Integer(headerTypeId), null}; + headerTypes.put(headerName, headerTypePair); } } else { - headerTypePair[0] = new Integer( headerTypeId ); + headerTypePair[0] = new Integer(headerTypeId); } } } } - + /** - * Get the requiredflag of the getHeaderSections() content entry with a key that matches headerName argument + * Get the requiredflag of the getHeaderSections() content entry with a key + * that matches headerName argument * * @return requiredflag for header section */ - public String getHeaderSectionRequiredFlag( String headerName ) + public String getHeaderSectionRequiredFlag(String headerName) { - if ( headerName != null ) + if (headerName != null) { - Map headerTypes = getHeaderSectionTypes( false ); - if ( headerTypes != null ) + Map headerTypes = getHeaderSectionTypes(false); + if (headerTypes != null) { - Object[] headerTypePair = (Object[])headerTypes.get( headerName ); - if ( headerTypePair != null ) - { - return (String)headerTypePair[1]; - } + Object[] headerTypePair = (Object[]) headerTypes + .get(headerName); + if (headerTypePair != null) { return (String) headerTypePair[1]; } } } return null; } - + /** - * Set the requiredflag of the getHeaderSections() content entry with a key that matches headerName argument - * to the value of the headerReqFlag argument + * Set the requiredflag of the getHeaderSections() content entry with a key + * that matches headerName argument to the value of the headerReqFlag + * argument */ - public void setHeaderSectionRequiredFlag( String headerName, String headerReqFlag ) + public void setHeaderSectionRequiredFlag(String headerName, + String headerReqFlag) { - if ( headerName != null ) + if (headerName != null) { - if ( headerReqFlag != null && headerReqFlag.length() == 0 ) + if (headerReqFlag != null && headerReqFlag.length() == 0) headerReqFlag = null; - - Map headerTypes = getHeaderSectionTypes( true ); - Object[] headerTypePair = (Object[])headerTypes.get( headerName ); - if ( headerTypePair == null ) + + Map headerTypes = getHeaderSectionTypes(true); + Object[] headerTypePair = (Object[]) headerTypes.get(headerName); + if (headerTypePair == null) { - if ( headerReqFlag != null ) + if (headerReqFlag != null) { - headerTypePair = new Object[] { null, headerReqFlag }; - headerTypes.put( headerName, headerTypePair ); + headerTypePair = new Object[] + {null, headerReqFlag}; + headerTypes.put(headerName, headerTypePair); } } else @@ -642,107 +691,127 @@ } } } - - protected Map getHeaderSectionTypes( boolean create ) + + protected Map getHeaderSectionTypes(boolean create) { Map dynamicConfig = getHeaderDynamicConfiguration(); - Map headerTypes = (Map)dynamicConfig.get( HEADER_CONFIG_TYPES ); - if ( headerTypes == null && create ) + Map headerTypes = (Map) dynamicConfig.get(HEADER_CONFIG_TYPES); + if (headerTypes == null && create) { headerTypes = new HashMap(); - dynamicConfig.put( HEADER_CONFIG_TYPES, headerTypes ); + dynamicConfig.put(HEADER_CONFIG_TYPES, headerTypes); } return headerTypes; } - protected Map getHeaderSectionNames( boolean create ) + + protected Map getHeaderSectionNames(boolean create) { Map dynamicConfig = getHeaderDynamicConfiguration(); - Map headerNames = (Map)dynamicConfig.get( HEADER_INTERNAL_INCLUDED_NAMES ); - if ( headerNames == null && create ) + Map headerNames = (Map) dynamicConfig + .get(HEADER_INTERNAL_INCLUDED_NAMES); + if (headerNames == null && create) { headerNames = new HashMap(); - dynamicConfig.put( HEADER_INTERNAL_INCLUDED_NAMES, headerNames ); + dynamicConfig.put(HEADER_INTERNAL_INCLUDED_NAMES, headerNames); } return headerNames; } - protected List getHeaderSectionOrderList( boolean create ) + + protected List getHeaderSectionOrderList(boolean create) { Map dynamicConfig = getHeaderDynamicConfiguration(); - List headerOrderList = (List)dynamicConfig.get( HEADER_CONFIG_ORDER ); - if ( headerOrderList == null ) + List headerOrderList = (List) dynamicConfig.get(HEADER_CONFIG_ORDER); + if (headerOrderList == null) { headerOrderList = new ArrayList(); - dynamicConfig.put( HEADER_CONFIG_ORDER, headerOrderList ); + dynamicConfig.put(HEADER_CONFIG_ORDER, headerOrderList); } return headerOrderList; } - + /** * Access modifiable header configuration settings * - * @return Map containing modifiable header configuration settings + * @return Map containing modifiable header configuration settings */ public Map getHeaderDynamicConfiguration() { - if ( this.headerDynamicConfiguration == null ) + if (this.headerDynamicConfiguration == null) { - this.headerDynamicConfiguration = (Map)requestContext.getAttribute( PortalReservedParameters.HEADER_CONFIGURATION_ATTRIBUTE ); - if ( this.headerDynamicConfiguration == null ) + this.headerDynamicConfiguration = (Map) requestContext + .getAttribute(PortalReservedParameters.HEADER_CONFIGURATION_ATTRIBUTE); + if (this.headerDynamicConfiguration == null) { this.headerDynamicConfiguration = new HashMap(); - requestContext.setAttribute( PortalReservedParameters.HEADER_CONFIGURATION_ATTRIBUTE, this.headerDynamicConfiguration ); + requestContext + .setAttribute( + PortalReservedParameters.HEADER_CONFIGURATION_ATTRIBUTE, + this.headerDynamicConfiguration); } } return this.headerDynamicConfiguration; } + protected Map getHeaderSections() { - if ( this.headerNamedResources == null ) + if (this.headerNamedResources == null) { - this.headerNamedResources = (Map)requestContext.getAttribute( PortalReservedParameters.HEADER_NAMED_RESOURCE_ATTRIBUTE ); - if ( this.headerNamedResources == null ) + this.headerNamedResources = (Map) requestContext + .getAttribute(PortalReservedParameters.HEADER_NAMED_RESOURCE_ATTRIBUTE); + if (this.headerNamedResources == null) { this.headerNamedResources = new HashMap(); - requestContext.setAttribute( PortalReservedParameters.HEADER_NAMED_RESOURCE_ATTRIBUTE, this.headerNamedResources ); + requestContext + .setAttribute( + PortalReservedParameters.HEADER_NAMED_RESOURCE_ATTRIBUTE, + this.headerNamedResources); } } return this.headerNamedResources; } + protected Map getHeaderSectionsAddedFragments() { - if ( this.headerNamedResourcesAddedFragments == null ) + if (this.headerNamedResourcesAddedFragments == null) { - this.headerNamedResourcesAddedFragments = (Map)requestContext.getAttribute( PortalReservedParameters.HEADER_NAMED_RESOURCE_ADDED_FRAGMENTS_ATTRIBUTE ); - if ( this.headerNamedResourcesAddedFragments == null ) + this.headerNamedResourcesAddedFragments = (Map) requestContext + .getAttribute(PortalReservedParameters.HEADER_NAMED_RESOURCE_ADDED_FRAGMENTS_ATTRIBUTE); + if (this.headerNamedResourcesAddedFragments == null) { this.headerNamedResourcesAddedFragments = new HashMap(); - requestContext.setAttribute( PortalReservedParameters.HEADER_NAMED_RESOURCE_ADDED_FRAGMENTS_ATTRIBUTE, this.headerNamedResourcesAddedFragments ); + requestContext + .setAttribute( + PortalReservedParameters.HEADER_NAMED_RESOURCE_ADDED_FRAGMENTS_ATTRIBUTE, + this.headerNamedResourcesAddedFragments); } } return this.headerNamedResourcesAddedFragments; } + protected Map getHeaderResourceRegistry() { - if ( this.headerResourceRegistry == null ) + if (this.headerResourceRegistry == null) { - this.headerResourceRegistry = (Map)requestContext.getAttribute( PortalReservedParameters.HEADER_NAMED_RESOURCE_REGISTRY_ATTRIBUTE ); - if ( this.headerResourceRegistry == null ) + this.headerResourceRegistry = (Map) requestContext + .getAttribute(PortalReservedParameters.HEADER_NAMED_RESOURCE_REGISTRY_ATTRIBUTE); + if (this.headerResourceRegistry == null) { this.headerResourceRegistry = new HashMap(); } } return this.headerResourceRegistry; } - + protected RequestContext getRequestContext() { return this.requestContext; - } + } + protected BasePortalURL getBaseUrlAccess() { return this.baseUrlAccess; } - + /** * Is request for /desktop rather than /portal * @@ -752,29 +821,31 @@ { return this.isDesktop; } - + /** * Access complete header configuration settings * - * @return unmodifiable Map containing complete header configuration settings + * @return unmodifiable Map containing complete header configuration + * settings */ public Map getHeaderConfiguration() { return this.headerConfiguration; } - + protected HashMap getNamedResourcesAlreadyOutput() { return this.namedResourcesAlreadyOutput; } - protected void setNamedResourcesAlreadyOutput( HashMap newOne ) + + protected void setNamedResourcesAlreadyOutput(HashMap newOne) { this.namedResourcesAlreadyOutput = newOne; } - - // get portal urls - a copy of each of these methods exists in JetspeedDesktopContextImpl.java - + // get portal urls - a copy of each of these methods exists in + // JetspeedDesktopContextImpl.java + /** * Portal base url ( e.g. http://localhost:8080/jetspeed ) * @@ -782,51 +853,55 @@ */ public String getPortalBaseUrl() { - if ( this.portalBaseUrl == null ) + if (this.portalBaseUrl == null) { - this.portalBaseUrl = HeaderResourceLib.getPortalBaseUrl( this.requestContext, this.baseUrlAccess ); + this.portalBaseUrl = HeaderResourceLib.getPortalBaseUrl( + this.requestContext, this.baseUrlAccess); } return this.portalBaseUrl; } - + /** * Portal base url ( e.g. http://localhost:8080/jetspeed ) * * @return portal base url */ - public String getPortalBaseUrl( boolean encode ) + public String getPortalBaseUrl(boolean encode) { String baseurl = getPortalBaseUrl(); - if ( ! encode ) + if (!encode) { return baseurl; } else { - return requestContext.getResponse().encodeURL( baseurl ); + return requestContext.getResponse().encodeURL(baseurl); } } - + /** - * Portal base url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/javascript/dojo/ ) + * Portal base url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/javascript/dojo/ ) * * @return portal base url with relativePath argument appended */ - public String getPortalResourceUrl( String relativePath ) + public String getPortalResourceUrl(String relativePath) { - return getPortalResourceUrl( relativePath, false ); + return getPortalResourceUrl(relativePath, false); } - + /** - * Portal base url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/javascript/dojo/ ) + * Portal base url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/javascript/dojo/ ) * * @return portal base url with relativePath argument appended */ - public String getPortalResourceUrl( String relativePath, boolean encode ) + public String getPortalResourceUrl(String relativePath, boolean encode) { - return HeaderResourceLib.getPortalResourceUrl( relativePath, getPortalBaseUrl(), encode, this.requestContext ); + return HeaderResourceLib.getPortalResourceUrl(relativePath, + getPortalBaseUrl(), encode, this.requestContext); } - + /** * Portal base servlet url ( e.g. http://localhost:8080/jetspeed/desktop/ ) * @@ -834,226 +909,268 @@ */ public String getPortalUrl() { - if ( this.portalUrl == null ) + if (this.portalUrl == null) { - this.portalUrl = HeaderResourceLib.getPortalUrl( getPortalBaseUrl(), this.requestContext ); + this.portalUrl = HeaderResourceLib.getPortalUrl(getPortalBaseUrl(), + this.requestContext); } return this.portalUrl; } - + /** * Portal base servlet url ( e.g. http://localhost:8080/jetspeed/desktop/ ) * * @return portal base servlet url */ - public String getPortalUrl( boolean encode ) + public String getPortalUrl(boolean encode) { - return getPortalUrl( null, encode ); + return getPortalUrl(null, encode); } - + /** - * Portal base servlet url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/desktop/default-page.psml ) + * Portal base servlet url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/desktop/default-page.psml ) * * @return portal base servlet url with relativePath argument appended */ - public String getPortalUrl( String relativePath ) + public String getPortalUrl(String relativePath) { - return getPortalUrl( relativePath, false ); + return getPortalUrl(relativePath, false); } - + /** - * Portal base servlet url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/desktop/default-page.psml ) + * Portal base servlet url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/desktop/default-page.psml ) * * @return portal base servlet url with relativePath argument appended */ - public String getPortalUrl( String relativePath, boolean encode ) + public String getPortalUrl(String relativePath, boolean encode) { - return HeaderResourceLib.getPortalResourceUrl( relativePath, getPortalUrl(), encode, this.requestContext ); + return HeaderResourceLib.getPortalResourceUrl(relativePath, + getPortalUrl(), encode, this.requestContext); } - - // jetspeed - special convenience methods - + // jetspeed - special convenience methods + protected String jetspeedGenerateBasetag() { StringBuffer basetagOut = new StringBuffer(); - // + // // src='$jetspeedDesktop.getPortalResourceUrl("/javascript/dojo/dojo.js")' - String fullPortalBaseUrl = HeaderResourceLib.getPortalBaseUrl( this.requestContext, this.baseUrlAccess, true ); - String href = HeaderResourceLib.getPortalResourceUrl( "/", fullPortalBaseUrl, false, this.requestContext ); - basetagOut.append( "" ); + String fullPortalBaseUrl = HeaderResourceLib.getPortalBaseUrl( + this.requestContext, this.baseUrlAccess, true); + String href = HeaderResourceLib.getPortalResourceUrl("/", + fullPortalBaseUrl, false, this.requestContext); + basetagOut.append(""); return basetagOut.toString(); } - + // dojo - special convenience methods - + /** - * If no previous call using value of dojoRequire argument has been added to any getHeaderSections() content entry, - * add text argument to the getHeaderSections() content entry for dojo core require statements + * If no previous call using value of dojoRequire argument has been added to + * any getHeaderSections() content entry, add text argument to the + * getHeaderSections() content entry for dojo core require statements * */ - public void dojoAddCoreLibraryRequire( String dojoRequire ) + public void dojoAddCoreLibraryRequire(String dojoRequire) { - dojoAddRequire( dojoRequire, HEADER_SECTION_DOJO_REQUIRES_CORE ); + dojoAddRequire(dojoRequire, HEADER_SECTION_DOJO_REQUIRES_CORE); } - + /** - * Split dojoRequires argument using ';' delimiter and for each resulting dojoRequire value, if no previous call - * using dojoRequire value has been added to any getHeaderSections() content entry, - * add text argument to the getHeaderSections() content entry for dojo core require statements + * Split dojoRequires argument using ';' delimiter and for each resulting + * dojoRequire value, if no previous call using dojoRequire value has been + * added to any getHeaderSections() content entry, add text argument to the + * getHeaderSections() content entry for dojo core require statements * */ - public void dojoAddCoreLibraryRequires( String dojoRequires ) + public void dojoAddCoreLibraryRequires(String dojoRequires) { - dojoAddRequires( dojoRequires, HEADER_SECTION_DOJO_REQUIRES_CORE ); + dojoAddRequires(dojoRequires, HEADER_SECTION_DOJO_REQUIRES_CORE); } - + /** - * If no previous call using value of dojoRequire argument has been added to any getHeaderSections() content entry, - * add text argument to the getHeaderSections() content entry for dojo library module require statements + * If no previous call using value of dojoRequire argument has been added to + * any getHeaderSections() content entry, add text argument to the + * getHeaderSections() content entry for dojo library module require + * statements * */ - public void dojoAddModuleLibraryRequire( String dojoRequire ) + public void dojoAddModuleLibraryRequire(String dojoRequire) { - dojoAddRequire( dojoRequire, HEADER_SECTION_DOJO_REQUIRES_MODULES ); + dojoAddRequire(dojoRequire, HEADER_SECTION_DOJO_REQUIRES_MODULES); } - + /** - * Split dojoRequires argument using ';' delimiter and for each resulting dojoRequire value, if no previous call - * using dojoRequire value has been added to any getHeaderSections() content entry, - * add text argument to the getHeaderSections() content entry for dojo library module require statements + * Split dojoRequires argument using ';' delimiter and for each resulting + * dojoRequire value, if no previous call using dojoRequire value has been + * added to any getHeaderSections() content entry, add text argument to the + * getHeaderSections() content entry for dojo library module require + * statements * */ - public void dojoAddModuleLibraryRequires( String dojoRequires ) + public void dojoAddModuleLibraryRequires(String dojoRequires) { - dojoAddRequires( dojoRequires, HEADER_SECTION_DOJO_REQUIRES_MODULES ); + dojoAddRequires(dojoRequires, HEADER_SECTION_DOJO_REQUIRES_MODULES); } - + /** * Assure that header section name for dojo body expand style is included * */ - public void dojoAddBodyExpandStyle( boolean omitWindowScrollbars ) + public void dojoAddBodyExpandStyle(boolean omitWindowScrollbars) { - if ( isHeaderSectionIncluded( HEADER_SECTION_DOJO_STYLE_BODYEXPAND ) || isHeaderSectionIncluded( HEADER_SECTION_DOJO_STYLE_BODYEXPAND_NOSCROLL ) ) + if (isHeaderSectionIncluded(HEADER_SECTION_DOJO_STYLE_BODYEXPAND) + || isHeaderSectionIncluded(HEADER_SECTION_DOJO_STYLE_BODYEXPAND_NOSCROLL)) { // already included - first inclusion wins } else { - if ( ! omitWindowScrollbars ) + if (!omitWindowScrollbars) { - orderHeaderSection( HEADER_SECTION_DOJO_STYLE_BODYEXPAND ); + orderHeaderSection(HEADER_SECTION_DOJO_STYLE_BODYEXPAND); } else { - orderHeaderSection( HEADER_SECTION_DOJO_STYLE_BODYEXPAND_NOSCROLL ); + orderHeaderSection(HEADER_SECTION_DOJO_STYLE_BODYEXPAND_NOSCROLL); } } } - + /** - * Enable dojo by setting appropriate modifiable header configuration setting + * Enable dojo by setting appropriate modifiable header configuration + * setting * */ public void dojoEnable() { - getHeaderDynamicConfiguration().put( HEADER_CONFIG_DOJO_ENABLE, "true" ); + getHeaderDynamicConfiguration().put(HEADER_CONFIG_DOJO_ENABLE, "true"); } - + protected void dojoDisable() { - getHeaderDynamicConfiguration().put( HEADER_CONFIG_DOJO_ENABLE, "false" ); + getHeaderDynamicConfiguration().put(HEADER_CONFIG_DOJO_ENABLE, "false"); } + protected String dojoGetPath() { - return (String)getHeaderDynamicConfiguration().get( HEADER_CONFIG_DOJO_PATH ); + return (String) getHeaderDynamicConfiguration().get( + HEADER_CONFIG_DOJO_PATH); } - protected void dojoAddRequire( String dojoRequire, String addToHeaderName ) + + protected void dojoAddRequire(String dojoRequire, String addToHeaderName) { - if ( dojoRequire != null && addToHeaderName != null && ! hasHeaderSectionFragment( dojoRequire, true ) ) + if (dojoRequire != null && addToHeaderName != null + && !hasHeaderSectionFragment(dojoRequire, true)) { - String requireStatement = " dojo.require(\"" + dojoRequire + "\");"; - addHeaderSectionFragment( dojoRequire, addToHeaderName, requireStatement, true ); + String requireStatement = " dojo.require(\"" + dojoRequire + + "\");"; + addHeaderSectionFragment(dojoRequire, addToHeaderName, + requireStatement, true); } } - protected void dojoAddRequires( String dojoRequires, String addToHeaderName ) + + protected void dojoAddRequires(String dojoRequires, String addToHeaderName) { - String[] reqStatements = StringUtils.split( dojoRequires, ';' ); - int reqStatementsLen = ( reqStatements == null ) ? 0 : reqStatements.length; - if ( reqStatementsLen > 0 ) - { - for ( int i = 0 ; i < reqStatementsLen ; i++ ) + String[] reqStatements = StringUtils.split(dojoRequires, ';'); + int reqStatementsLen = (reqStatements == null) ? 0 + : reqStatements.length; + if (reqStatementsLen > 0) + { + for (int i = 0; i < reqStatementsLen; i++) { - dojoAddRequire( reqStatements[i], addToHeaderName ); + dojoAddRequire(reqStatements[i], addToHeaderName); } } } + protected String dojoGeneratePreinit() { StringBuffer preinitOut = new StringBuffer(); - //preinitOut.append( " " ).append( "function de_jsessionid_url(url){var tEnds = url.indexOf(';jsessionid=');if (tEnds > 0) url = url.substring(0, tEnds);return url;}" ).append( EOL ); + // preinitOut.append( " " ).append( "function de_jsessionid_url(url){var + // tEnds = url.indexOf(';jsessionid=');if (tEnds > 0) url = + // url.substring(0, tEnds);return url;}" ).append( EOL ); // presence of ;jsessionid in dojo baseScriptUri is bad news - preinitOut.append( " " ).append( "djConfig.baseScriptUri = \"" ).append( getPortalResourceUrl( dojoGetPath(), false ) ).append( "\";" ).append( EOL ); - if (this.requestContext.getRequest().getContextPath().length()==0) + preinitOut.append(" ").append("djConfig.baseScriptUri = \"").append( + getPortalResourceUrl(dojoGetPath(), false)).append("\";") + .append(EOL); + if (this.requestContext.getRequest().getContextPath().length() == 0) { - preinitOut.append( " " ).append( "djConfig.jetspeed.rootContext = \"true\";" ).append( EOL ); + preinitOut.append(" ").append( + "djConfig.jetspeed.rootContext = \"true\";").append(EOL); } - preinitOut.append( " " ).append( "djConfig.jetspeed.servletPath = \"" ).append( this.requestContext.getRequest().getServletPath() ).append( "\";" ); + preinitOut.append(" ").append("djConfig.jetspeed.servletPath = \"") + .append(this.requestContext.getRequest().getServletPath()) + .append("\";"); return preinitOut.toString(); } + protected String dojoGenerateInit() { StringBuffer initOut = new StringBuffer(); - // + // // src='$jetspeedDesktop.getPortalResourceUrl("/javascript/dojo/dojo.js")' - initOut.append( "" ); + initOut.append(""); return initOut.toString(); } + protected String dojoGenerateWriteincludes() { return " dojo.hostenv.writeIncludes();"; } + protected String dojoGenerateBodyExpandStyle() - { // if not defined as getHeaderResourceRegistry(), generate default text + { // if not defined as getHeaderResourceRegistry(), generate default text Map headerRsrcRegistry = getHeaderResourceRegistry(); - String headerText = (String)headerRsrcRegistry.get( HEADER_SECTION_DOJO_STYLE_BODYEXPAND ); - if ( headerText == null ) + String headerText = (String) headerRsrcRegistry + .get(HEADER_SECTION_DOJO_STYLE_BODYEXPAND); + if (headerText == null) { headerText = "html, body { width: 100%; height: 100%; padding: 0 0 0 0; margin: 0 0 0 0; }"; } return headerText; } + protected String dojoGenerateBodyExpandNoScrollStyle() - { // if not defined as getHeaderResourceRegistry(), generate default text + { // if not defined as getHeaderResourceRegistry(), generate default text Map headerRsrcRegistry = getHeaderResourceRegistry(); - String headerText = (String)headerRsrcRegistry.get( HEADER_SECTION_DOJO_STYLE_BODYEXPAND_NOSCROLL ); - if ( headerText == null ) + String headerText = (String) headerRsrcRegistry + .get(HEADER_SECTION_DOJO_STYLE_BODYEXPAND_NOSCROLL); + if (headerText == null) { headerText = "html, body { width: 100%; height: 100%; overflow: hidden; padding: 0 0 0 0; margin: 0 0 0 0; }"; } return headerText; } - - // older content implementation - using HeaderInfo set - + // older content implementation - using HeaderInfo set + /** * Gets HeaderInfo set from the request. * - * @return HeaderInfo set containing content for inclusion in html <head> + * @return HeaderInfo set containing content for inclusion in html + * <head> */ private Set getHeaderInfoSet() { - Set headerInfoSet = (Set) requestContext.getAttribute(PortalReservedParameters.HEADER_RESOURCE_ATTRIBUTE); + Set headerInfoSet = (Set) requestContext + .getAttribute(PortalReservedParameters.HEADER_RESOURCE_ATTRIBUTE); if (headerInfoSet == null) { headerInfoSet = new LinkedHashSet(); - requestContext.setAttribute(PortalReservedParameters.HEADER_RESOURCE_ATTRIBUTE, headerInfoSet); + requestContext.setAttribute( + PortalReservedParameters.HEADER_RESOURCE_ATTRIBUTE, + headerInfoSet); } return headerInfoSet; } - + /* * (non-Javadoc) * @@ -1068,7 +1185,7 @@ headerInfoSet.add(headerInfo); } } - + /* * (non-Javadoc) * @@ -1097,10 +1214,7 @@ for (Iterator ite = headerInfoSet.iterator(); ite.hasNext();) { HeaderInfo hInfo = (HeaderInfo) ite.next(); - if (headerInfo.equals(hInfo)) - { - return true; - } + if (headerInfo.equals(hInfo)) { return true; } } return false; } @@ -1114,7 +1228,7 @@ public void addJavaScript(String path, boolean defer) { HashMap attrs = new HashMap(); - attrs.put("src", requestContext.getResponse().encodeURL( path ) ); + attrs.put("src", requestContext.getResponse().encodeURL(path)); attrs.put("type", "text/javascript"); if (defer) { @@ -1142,11 +1256,11 @@ { HashMap attrs = new HashMap(); attrs.put("rel", "stylesheet"); - attrs.put("href", requestContext.getResponse().encodeURL( path ) ); + attrs.put("href", requestContext.getResponse().encodeURL(path)); attrs.put("type", "text/css"); addHeaderInfo("link", attrs, null); } - + /** * This class represents tag information for HeaderResouce component * @@ -1154,6 +1268,7 @@ */ private class HeaderInfo { + /** * Tag's name */ @@ -1194,16 +1309,16 @@ public String toString() { StringBuffer buf = new StringBuffer(); - + String elmtName = getElementName(); - if ( elmtName != null && elmtName.length() > 0 ) + if (elmtName != null && elmtName.length() > 0) { buf.append("<"); buf.append(getElementName()); buf.append(" "); Map attrMap = getAttributes(); - if ( attrMap != null ) + if (attrMap != null) { Set keySet = attrMap.keySet(); for (Iterator ite = keySet.iterator(); ite.hasNext();) @@ -1228,7 +1343,7 @@ { if (getText() != null) { - buf.append( getText() ); + buf.append(getText()); } } return buf.toString(); @@ -1241,10 +1356,8 @@ HeaderInfo headerInfo = (HeaderInfo) o; if (compareString(headerInfo.getElementName(), getElementName()) && compareString(headerInfo.getText(), getText()) - && compareAttributes(headerInfo.getAttributes(), getAttributes())) - { - return true; - } + && compareAttributes(headerInfo.getAttributes(), + getAttributes())) { return true; } } return false; } @@ -1253,37 +1366,25 @@ { if (str0 == null) { - if (str1 == null) - { - return true; - } + if (str1 == null) { return true; } } - else if ( str1 != null ) + else if (str1 != null) { - if (str0.equals(str1)) - { - return true; - } + if (str0.equals(str1)) { return true; } } return false; } - + private boolean compareAttributes(Map attr0, Map attr1) { if (attr0 == null) { - if (attr1 == null) - { - return true; - } + if (attr1 == null) { return true; } } - else if ( attr1 != null ) + else if (attr1 != null) { - if (attr0.equals(attr1)) - { - return true; - } + if (attr0.equals(attr1)) { return true; } } return false; } @@ -1297,7 +1398,8 @@ } /** - * @param attributes The attributes to set. + * @param attributes + * The attributes to set. */ public void setAttributes(Map attributes) { @@ -1313,7 +1415,8 @@ } /** - * @param elementName The elementName to set. + * @param elementName + * The elementName to set. */ public void setElementName(String elementName) { @@ -1329,7 +1432,8 @@ } /** - * @param text The text to set. + * @param text + * The text to set. */ public void setText(String text) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/id-generator/src/java/org/apache/jetspeed/idgenerator/JetspeedIdGenerator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/id-generator/src/java/org/apache/jetspeed/idgenerator/JetspeedIdGenerator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/id-generator/src/java/org/apache/jetspeed/idgenerator/JetspeedIdGenerator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,79 +16,83 @@ */ package org.apache.jetspeed.idgenerator; - - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Simple implementation of the IdGeneratorService. - * + * * @author Paul Spencer * @author David Sean Taylor * @version $Id: JetspeedIdGenerator.java 516448 2007-03-09 16:25:47Z ate $ */ public class JetspeedIdGenerator implements IdGenerator { + private final static Log log = LogFactory.getLog(JetspeedIdGenerator.class); // default configuration values private final static long DEFAULT_CONFIG_COUNTER_START = 0x10000; + private final static String DEFAULT_CONFIG_PEID_PREFIX = "P-"; + private final static String DEFAULT_CONFIG_PEID_SUFFIX = ""; // configuration parameters private String peidPrefix = null; + private String peidSuffix = null; + protected long idCounter; public JetspeedIdGenerator() { this.idCounter = DEFAULT_CONFIG_COUNTER_START; this.peidPrefix = DEFAULT_CONFIG_PEID_PREFIX; - this.peidSuffix = DEFAULT_CONFIG_PEID_SUFFIX; + this.peidSuffix = DEFAULT_CONFIG_PEID_SUFFIX; } public JetspeedIdGenerator(long counterStart) { this.idCounter = counterStart; this.peidPrefix = DEFAULT_CONFIG_PEID_PREFIX; - this.peidSuffix = DEFAULT_CONFIG_PEID_SUFFIX; + this.peidSuffix = DEFAULT_CONFIG_PEID_SUFFIX; } public JetspeedIdGenerator(long counterStart, String prefix, String suffix) { this.idCounter = counterStart; this.peidPrefix = prefix; - this.peidSuffix = suffix; + this.peidSuffix = suffix; } - - public void start() + + public void start() { - log.info( "Start JetspeedIdGenerator"); - } + log.info("Start JetspeedIdGenerator"); + } - public void stop() + public void stop() { - log.info( "Shutdown for JetspeedIdGenerator called. idCounter = " - + idCounter + " (" + Long.toHexString(idCounter) + ")" ); + log.info("Shutdown for JetspeedIdGenerator called. idCounter = " + + idCounter + " (" + Long.toHexString(idCounter) + ")"); } /** * Generate a Unique PEID + * * @return Unique PEID */ public String getNextPeid() { long newid; - synchronized(JetspeedIdGenerator.class) + synchronized (JetspeedIdGenerator.class) { newid = idCounter++; } - - return peidPrefix + Long.toHexString(System.currentTimeMillis()) + "-" - + Long.toHexString(newid) + peidSuffix; + + return peidPrefix + Long.toHexString(System.currentTimeMillis()) + "-" + + Long.toHexString(newid) + peidSuffix; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/id-generator/src/test/org/apache/jetspeed/idgenerator/TestIdGenerator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/id-generator/src/test/org/apache/jetspeed/idgenerator/TestIdGenerator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/id-generator/src/test/org/apache/jetspeed/idgenerator/TestIdGenerator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,40 +25,41 @@ /** * TestIdGenerator - * + * * @author Paul Spencer * @version $Id: TestIdGenerator.java 516448 2007-03-09 16:25:47Z ate $ */ public class TestIdGenerator extends TestCase { - + private static int ID_TEST_TRIES = 10000; - - + /** * Start the tests. - * - * @param args the arguments. Not used + * + * @param args + * the arguments. Not used */ - public static void main(String args[]) + public static void main(String args[]) { - junit.awtui.TestRunner.main( new String[] { TestIdGenerator.class.getName() } ); + junit.awtui.TestRunner.main(new String[] + {TestIdGenerator.class.getName()}); } - + /** * Creates the test suite. - * - * @return a test suite (TestSuite) that includes all methods - * starting with "test" + * + * @return a test suite (TestSuite) that includes all + * methods starting with "test" */ - public static Test suite() + public static Test suite() { // All methods starting with "test" will be executed in the test suite. - return new TestSuite( TestIdGenerator.class ); + return new TestSuite(TestIdGenerator.class); } - + /** - * Simple test that verify the PEID are unique. This test will generate + * Simple test that verify the PEID are unique. This test will generate * ID_TEST_TRIES PEIDs. It will test for a NULL PEID. * * Granted, passing this test does not guarantee that a duplicate @@ -69,35 +70,36 @@ public void testVerifyUniquePeid() throws Exception { IdGenerator generator = new JetspeedIdGenerator(65536, "P-", ""); - - HashMap generatedIds = new HashMap( ID_TEST_TRIES + 1); - String newId; - - // Add a NULL to verify a NULL is not being generated. + + HashMap generatedIds = new HashMap(ID_TEST_TRIES + 1); + String newId; + + // Add a NULL to verify a NULL is not being generated. generatedIds.put(null, null); - + for (int counter = 1; counter <= ID_TEST_TRIES; counter++) { newId = generator.getNextPeid(); - assertTrue( "PEID already generated. PEID = " + newId, !generatedIds.containsKey(newId)); + assertTrue("PEID already generated. PEID = " + newId, !generatedIds + .containsKey(newId)); generatedIds.put(newId, null); } } /** - * Simple test that verify the PEIDs are increasing. Although this is not a + * Simple test that verify the PEIDs are increasing. Although this is not a * requirement of the IdGenerator, it is recommended - * + * * @throws Exception */ public void testVerifyIncreasingPeid() throws Exception { IdGenerator generator = new JetspeedIdGenerator(65536, "P-", ""); - assertNotNull("idgenerator service is null", generator); - - String newId; - String lastId = null; - + assertNotNull("idgenerator service is null", generator); + + String newId; + String lastId = null; + for (int counter = 1; counter <= ID_TEST_TRIES; counter++) { newId = generator.getNextPeid(); @@ -106,7 +108,8 @@ lastId = newId; continue; } - assertTrue( "PEID is not greater then last generated PEID. PEID = " + newId, (lastId.compareTo(newId)<0)); + assertTrue("PEID is not greater then last generated PEID. PEID = " + + newId, (lastId.compareTo(newId) < 0)); lastId = newId; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/AbstractScheduler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/AbstractScheduler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/AbstractScheduler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,14 +23,16 @@ /** * Service for a cron like scheduler. - * + * * @author Dave Bryson * @version $Id: AbstractScheduler.java 516448 2007-03-09 16:25:47Z ate $ */ public abstract class AbstractScheduler implements Scheduler { - private final static Log log = LogFactory.getLog(MemoryBasedScheduler.class); - + + private final static Log log = LogFactory + .getLog(MemoryBasedScheduler.class); + /** * The queue. */ @@ -58,10 +60,10 @@ public void start() { } - + public void stop() { - if(getThread() != null) + if (getThread() != null) { getThread().interrupt(); } @@ -69,45 +71,49 @@ /** * Get a specific Job from Storage. - * - * @param oid The int id for the job. + * + * @param oid + * The int id for the job. * @return A JobEntry. - * @exception Exception, a generic exception. + * @exception Exception, + * a generic exception. */ - public abstract JobEntry getJob(int oid) - throws Exception; + public abstract JobEntry getJob(int oid) throws Exception; /** - * Add a new job to the queue. Before adding a job, calculate the runtime - * to make sure the entry will be placed at the right order in the queue. - * - * @param je A JobEntry with the job to add. - * @exception Exception, a generic exception. + * Add a new job to the queue. Before adding a job, calculate the runtime to + * make sure the entry will be placed at the right order in the queue. + * + * @param je + * A JobEntry with the job to add. + * @exception Exception, + * a generic exception. */ - public abstract void addJob(JobEntry je) - throws Exception; - + public abstract void addJob(JobEntry je) throws Exception; + /** * Remove a job from the queue. - * - * @param je A JobEntry with the job to remove. - * @exception Exception, a generic exception. + * + * @param je + * A JobEntry with the job to remove. + * @exception Exception, + * a generic exception. */ - public abstract void removeJob(JobEntry je) - throws Exception; + public abstract void removeJob(JobEntry je) throws Exception; /** * Modify a Job. - * - * @param je A JobEntry with the job to modify - * @exception Exception, a generic exception. + * + * @param je + * A JobEntry with the job to modify + * @exception Exception, + * a generic exception. */ - public abstract void updateJob(JobEntry je) - throws Exception; - + public abstract void updateJob(JobEntry je) throws Exception; + /** - * List jobs in the queue. This is used by the scheduler UI. - * + * List jobs in the queue. This is used by the scheduler UI. + * * @return A List of jobs. */ public List listJobs() @@ -116,10 +122,10 @@ } /** - * Return the thread being used to process commands, or null if - * there is no such thread. You can use this to invoke any - * special methods on the thread, for example, to interrupt it. - * + * Return the thread being used to process commands, or null if there is no + * such thread. You can use this to invoke any special methods on the + * thread, for example, to interrupt it. + * * @return A Thread. */ public synchronized Thread getThread() @@ -136,10 +142,10 @@ } /** - * Start (or restart) a thread to process commands, or wake up an - * existing thread if one is already running. This method can be - * invoked if the background thread crashed due to an - * unrecoverable exception in an executed command. + * Start (or restart) a thread to process commands, or wake up an existing + * thread if one is already running. This method can be invoked if the + * background thread crashed due to an unrecoverable exception in an + * executed command. */ public synchronized void restart() { @@ -149,9 +155,11 @@ // for the time when the next task needs to be started, and then // launch a worker thread to execute the task. thread = new Thread(mainLoop, Scheduler.SERVICE_NAME); - // Indicate that this is a system thread. JVM will quit only when there - // are no more active user threads. Settings threads spawned internally - // by CPS as daemons allows commandline applications + // Indicate that this is a system thread. JVM will quit only when + // there + // are no more active user threads. Settings threads spawned + // internally + // by CPS as daemons allows commandline applications // to terminate in an orderly manner. thread.setDaemon(true); thread.start(); @@ -163,18 +171,17 @@ } /** - * Return the next Job to execute, or null if thread is - * interrupted. - * + * Return the next Job to execute, or null if thread is interrupted. + * * @return A JobEntry. - * @exception Exception, a generic exception. + * @exception Exception, + * a generic exception. */ - private synchronized JobEntry nextJob() - throws Exception + private synchronized JobEntry nextJob() throws Exception { try { - while ( !Thread.interrupted() ) + while (!Thread.interrupted()) { // Grab the next job off the queue. JobEntry je = scheduleQueue.getNext(); @@ -189,7 +196,7 @@ long now = System.currentTimeMillis(); long when = je.getNextRuntime(); - if ( when > now ) + if (when > now) { // Wait till next runtime. wait(when - now); @@ -213,13 +220,13 @@ } /** - * Inner class. This is isolated in its own Runnable class just - * so that the main class need not implement Runnable, which would - * allow others to directly invoke run, which is not supported. + * Inner class. This is isolated in its own Runnable class just so that the + * main class need not implement Runnable, which would allow others to + * directly invoke run, which is not supported. */ - protected class MainLoop - implements Runnable + protected class MainLoop implements Runnable { + /** * Method to run the class. */ @@ -227,10 +234,10 @@ { try { - for(;;) + for (;;) { JobEntry je = nextJob(); - if ( je != null ) + if (je != null) { // Start the thread to run the job. Runnable wt = new WorkerThread(je); @@ -243,7 +250,7 @@ } } } - catch(Exception e) + catch (Exception e) { // Log error. log.error("Error running a Scheduled Job: " + e); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/BaseJobEntry.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/BaseJobEntry.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/BaseJobEntry.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,46 +18,53 @@ /** * BaseJobEntry - * + * * @author David Sean Taylor * @version $Id: BaseJobEntry.java 516448 2007-03-09 16:25:47Z ate $ */ public abstract class BaseJobEntry -{ +{ + protected int jobId = 0; + protected int jobSecond = -1; + protected int jobMinute = -1; + protected int jobHour = -1; + protected int weekDay = -1; + protected int dayOfMonth = -1; + protected String task; - protected String email; - + + protected String email; + /** * Get the JobId - * - * @return + * + * @return */ public int getJobId() { return jobId; } - /** * Set the value of JobId - * - * @param v new value + * + * @param v + * new value */ - public void setJobId(int v) + public void setJobId(int v) { - this.jobId = v; + this.jobId = v; } - /** * Get the Second - * + * * @return int */ public int getSecond() @@ -65,21 +72,20 @@ return jobSecond; } - /** * Set the value of Second - * - * @param v new value + * + * @param v + * new value */ - public void setSecond(int v) + public void setSecond(int v) { - this.jobSecond = v; + this.jobSecond = v; } - /** * Get the Minute - * + * * @return int */ public int getMinute() @@ -87,20 +93,20 @@ return jobMinute; } - /** * Set the value of Minute - * - * @param v new value + * + * @param v + * new value */ - public void setMinute(int v) + public void setMinute(int v) { - this.jobMinute = v; - } + this.jobMinute = v; + } /** * Get the Hour - * + * * @return int */ public int getHour() @@ -108,42 +114,41 @@ return jobHour; } - /** * Set the value of Hour - * - * @param v new value + * + * @param v + * new value */ - public void setHour(int v) + public void setHour(int v) { this.jobHour = v; } - /** * Get the WeekDay - * + * * @return int */ public int getWeekDay() { return weekDay; } - + /** * Set the value of WeekDay - * - * @param v new value + * + * @param v + * new value */ - public void setWeekDay(int v) + public void setWeekDay(int v) { - this.weekDay = v; + this.weekDay = v; } - /** * Get the DayOfMonth - * + * * @return int */ public int getDayOfMonth() @@ -151,20 +156,20 @@ return dayOfMonth; } - /** * Set the value of DayOfMonth - * - * @param v new value + * + * @param v + * new value */ - public void setDayOfMonth(int v) + public void setDayOfMonth(int v) { this.dayOfMonth = v; } /** * Get the Task - * + * * @return String */ public String getTask() @@ -172,20 +177,20 @@ return task; } - /** * Set the value of Task - * - * @param v new value + * + * @param v + * new value */ - public void setTask(String v) + public void setTask(String v) { - this.task = v; + this.task = v; } /** * Get the Email - * + * * @return String */ public String getEmail() @@ -193,14 +198,14 @@ return email; } - /** * Set the value of Email - * - * @param v new value + * + * @param v + * new value */ - public void setEmail(String v) + public void setEmail(String v) { - this.email = v; + this.email = v; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/JobEntry.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/JobEntry.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/JobEntry.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,35 +17,35 @@ package org.apache.jetspeed.scheduler; import java.util.Calendar; -import java.lang.Comparable; import java.util.Date; /** - * This is a wrapper for a scheduled job. It is modeled after the - * Unix scheduler cron. - * + * This is a wrapper for a scheduled job. It is modeled after the Unix scheduler + * cron. + * * @author Dave Bryson * @version $Id: JobEntry.java 516448 2007-03-09 16:25:47Z ate $ */ -public class JobEntry - extends BaseJobEntry - implements Comparable +public class JobEntry extends BaseJobEntry implements Comparable { /** indicates if job is currently running */ private boolean jobIsActive = false; - /** Next runtime. **/ + /** Next runtime. * */ private long runtime = 0; - /** schedule types **/ + /** schedule types * */ private static final int SECOND = 0; + private static final int MINUTE = 1; + private static final int WEEK_DAY = 2; + private static final int DAY_OF_MONTH = 3; + private static final int DAILY = 4; - /** * default constructor */ @@ -55,49 +55,47 @@ /** * Constuctor. - * + * * Schedule a job to run on a certain point of time.
        - * - * Example 1: Run the DefaultScheduledJob at 8:00am every 15th of - * the month -
        - * - * JobEntry je = new JobEntry(0,0,8,15,"DefaultScheduledJob");
        - * - * Example 2: Run the DefaultScheduledJob at 8:00am every day - + * + * Example 1: Run the DefaultScheduledJob at 8:00am every 15th of the month - *
        - * + * + * JobEntry je = new JobEntry(0,0,8,15,"DefaultScheduledJob");
        + * + * Example 2: Run the DefaultScheduledJob at 8:00am every day -
        + * * JobEntry je = new JobEntry(0,0,8,-1,"DefaultScheduledJob");
        - * + * * Example 3: Run the DefaultScheduledJob every 2 hours. -
        - * + * * JobEntry je = new JobEntry(0,120,-1,-1,"DefaultScheduledJob");
        - * + * * Example 4: Run the DefaultScheduledJob every 30 seconds. -
        - * + * * JobEntry je = new JobEntry(30,-1,-1,-1,"DefaultScheduledJob");
        - * - * @param sec Value for entry "seconds". - * @param min Value for entry "minutes". - * @param hour Value for entry "hours". - * @param wd Value for entry "week days". - * @param day_mo Value for entry "month days". - * @param task Task to execute. - * @exception Exception, a generic exception. + * + * @param sec + * Value for entry "seconds". + * @param min + * Value for entry "minutes". + * @param hour + * Value for entry "hours". + * @param wd + * Value for entry "week days". + * @param day_mo + * Value for entry "month days". + * @param task + * Task to execute. + * @exception Exception, + * a generic exception. */ - public JobEntry(int sec, - int min, - int hour, - int wd, - int day_mo, - String task) - throws Exception + public JobEntry(int sec, int min, int hour, int wd, int day_mo, String task) + throws Exception { - if ( task == null || task.length() == 0 ) - { - throw new Exception("Error in JobEntry. " + - "Bad Job parameter. Task not set."); - } - + if (task == null || task.length() == 0) { throw new Exception( + "Error in JobEntry. " + "Bad Job parameter. Task not set."); } + setSecond(sec); setMinute(min); setHour(hour); @@ -116,26 +114,24 @@ int result = -1; if (je instanceof JobEntry) { - if (jobId == ((JobEntry)je).getJobId()) + if (jobId == ((JobEntry) je).getJobId()) { return 0; } else { - if (jobId > ((JobEntry)je).getJobId()) - { - return 1; - } + if (jobId > ((JobEntry) je).getJobId()) { return 1; } } - + } return result; } /** * Sets whether the job is running. - * - * @param isActive Whether the job is running. + * + * @param isActive + * Whether the job is running. */ public void setActive(boolean isActive) { @@ -144,18 +140,18 @@ /** * Check to see if job is currently active/running - * - * @return true if job is currently geing run by the - * workerthread, otherwise false + * + * @return true if job is currently geing run by the workerthread, otherwise + * false */ - public boolean isActive() - { + public boolean isActive() + { return jobIsActive; - } + } /** * Get the next runtime for this job as a long. - * + * * @return The next run time as a long. */ public long getNextRuntime() @@ -165,7 +161,7 @@ /** * Get the next runtime for this job as a String. - * + * * @return The next run time as a String. */ public String getNextRunAsString() @@ -175,27 +171,26 @@ /** * Calculate how long before the next runtime.
        - * - * The runtime determines it's position in the job queue. - * Here's the logic:
        - * + * + * The runtime determines it's position in the job queue. Here's the logic:
        + * * 1. Create a date the represents when this job is to run.
        - * - * 2. If this date has expired, them "roll" appropriate date - * fields forward to the next date.
        - * - * 3. Calculate the diff in time between the current time and the - * next run time.
        - * - * @exception Exception, a generic exception. + * + * 2. If this date has expired, them "roll" appropriate date fields forward + * to the next date.
        + * + * 3. Calculate the diff in time between the current time and the next run + * time.
        + * + * @exception Exception, + * a generic exception. */ - public void calcRunTime() - throws Exception + public void calcRunTime() throws Exception { Calendar schedrun = Calendar.getInstance(); Calendar now = Calendar.getInstance(); - - switch( evaluateJobType() ) + + switch (evaluateJobType()) { case SECOND: // SECOND (every so many seconds...) @@ -217,7 +212,7 @@ schedrun.set(Calendar.HOUR_OF_DAY, getHour()); schedrun.set(Calendar.DAY_OF_WEEK, getWeekDay()); - if ( now.before(schedrun) ) + if (now.before(schedrun)) { // Scheduled time has NOT expired. runtime = schedrun.getTime().getTime(); @@ -225,7 +220,7 @@ else { // Scheduled time has expired; roll to the next week. - schedrun.add(Calendar.DAY_OF_WEEK,7); + schedrun.add(Calendar.DAY_OF_WEEK, 7); runtime = schedrun.getTime().getTime(); } break; @@ -237,7 +232,7 @@ schedrun.set(Calendar.HOUR_OF_DAY, getHour()); schedrun.set(Calendar.DAY_OF_MONTH, getDayOfMonth()); - if ( now.before(schedrun) ) + if (now.before(schedrun)) { // Scheduled time has NOT expired. runtime = schedrun.getTime().getTime(); @@ -245,7 +240,7 @@ else { // Scheduled time has expired; roll to the next month. - schedrun.add(Calendar.MONTH,1); + schedrun.add(Calendar.MONTH, 1); runtime = schedrun.getTime().getTime(); } break; @@ -257,14 +252,14 @@ schedrun.set(Calendar.HOUR_OF_DAY, getHour()); // Scheduled time has NOT expired. - if ( now.before(schedrun) ) + if (now.before(schedrun)) { runtime = schedrun.getTime().getTime(); } else { // Scheduled time has expired; roll forward 24 hours. - schedrun.add(Calendar.HOUR_OF_DAY,24); + schedrun.add(Calendar.HOUR_OF_DAY, 24); runtime = schedrun.getTime().getTime(); } break; @@ -276,61 +271,64 @@ /** * What schedule am I on? - * - * I know this is kinda ugly! If you can think of a cleaner way - * to do this, please jump in! - * - * @return A number specifying the type of schedule. See - * calcRunTime(). - * @exception Exception, a generic exception. + * + * I know this is kinda ugly! If you can think of a cleaner way to do this, + * please jump in! + * + * @return A number specifying the type of schedule. See calcRunTime(). + * @exception Exception, + * a generic exception. */ - private int evaluateJobType() - throws Exception + private int evaluateJobType() throws Exception { // First start by checking if it's a day of the month job. - if ( getDayOfMonth() < 0 ) + if (getDayOfMonth() < 0) { // Not a day of the month job... check weekday. - if ( getWeekDay() < 0 ) + if (getWeekDay() < 0) { // Not a weekday job...check if by the hour. - if ( getHour() < 0 ) + if (getHour() < 0) { // Not an hourly job...check if it is by the minute - if ( getMinute() < 0 ) + if (getMinute() < 0) { // Not a by the minute job so must be by the second - if ( getSecond() < 0) - throw new Exception("Error in JobEntry. Bad Job parameter."); + if (getSecond() < 0) + throw new Exception( + "Error in JobEntry. Bad Job parameter."); return SECOND; } else { - // Must be a job run by the minute so we need minutes and + // Must be a job run by the minute so we need minutes + // and // seconds. - if ( getMinute() < 0 || getSecond() < 0 ) - throw new Exception("Error in JobEntry. Bad Job parameter."); + if (getMinute() < 0 || getSecond() < 0) + throw new Exception( + "Error in JobEntry. Bad Job parameter."); return MINUTE; } } else { - // Must be a daily job by hours minutes, and seconds. In + // Must be a daily job by hours minutes, and seconds. In // this case, we need the minute, second, and hour params. - if ( getMinute() < 0 || getHour() < 0 || getSecond() < 0) - throw new Exception("Error in JobEntry. Bad Job parameter."); + if (getMinute() < 0 || getHour() < 0 || getSecond() < 0) + throw new Exception( + "Error in JobEntry. Bad Job parameter."); return DAILY; } } else { - // Must be a weekday job. In this case, we need + // Must be a weekday job. In this case, we need // minute, second, and hour params - if ( getMinute() < 0 || getHour() < 0 || getSecond() < 0 ) + if (getMinute() < 0 || getHour() < 0 || getSecond() < 0) throw new Exception("Error in JobEntry. Bad Job parameter."); return WEEK_DAY; @@ -338,9 +336,9 @@ } else { - // Must be a day of the month job. In this case, we need + // Must be a day of the month job. In this case, we need // minute, second, and hour params - if ( getMinute() < 0 || getHour() < 0 ) + if (getMinute() < 0 || getHour() < 0) throw new Exception("Error in JobEntry. Bad Job parameter."); return DAY_OF_MONTH; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/JobQueue.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/JobQueue.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/JobQueue.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,19 +16,20 @@ */ package org.apache.jetspeed.scheduler; +import java.util.Collections; +import java.util.Comparator; import java.util.List; import java.util.Vector; -import java.util.Collections; -import java.util.Comparator; /** * Queue for the scheduler. - * + * * @author Dave Bryson * @version $Id: JobQueue.java 516448 2007-03-09 16:25:47Z ate $ */ public class JobQueue { + /** * The queue of JobEntry objects. */ @@ -36,11 +37,11 @@ /** * Creates a new instance. - * - * @exception Exception A generic exception. + * + * @exception Exception + * A generic exception. */ - public JobQueue() - throws Exception + public JobQueue() throws Exception { queue = new Vector(10); } @@ -48,14 +49,14 @@ /** * Return the next job off the top of the queue, or null if * there are no jobs in the queue. - * + * * @return The next job in the queue. */ public JobEntry getNext() { - if ( queue.size() > 0 ) + if (queue.size() > 0) { - return (JobEntry)queue.elementAt(0); + return (JobEntry) queue.elementAt(0); } else { @@ -65,39 +66,40 @@ /** * Return a specific job. - * - * @param je The JobEntry we are looking for. + * + * @param je + * The JobEntry we are looking for. * @return A JobEntry. */ public JobEntry getJob(JobEntry je) { int index = -1; - if ( je != null ) + if (je != null) { index = queue.indexOf(je); } - if ( index < 0 ) + if (index < 0) { return null; } else { - return (JobEntry)queue.elementAt(index); + return (JobEntry) queue.elementAt(index); } } /** - * List jobs in the queue. This is used by the scheduler UI. - * + * List jobs in the queue. This is used by the scheduler UI. + * * @return A Vector of JobEntry objects. */ public Vector list() { - if ( queue != null && queue.size() > 0 ) + if (queue != null && queue.size() > 0) { - return (Vector)queue.clone(); + return (Vector) queue.clone(); } else { @@ -107,8 +109,9 @@ /** * Add a job to the queue. - * - * @param je A JobEntry job. + * + * @param je + * A JobEntry job. */ public synchronized void add(JobEntry je) { @@ -117,10 +120,11 @@ } /** - * Batch load jobs. Retains any already enqueued jobs. Called on + * Batch load jobs. Retains any already enqueued jobs. Called on * SchedulerService start-up. - * - * @param jobEntries A list of the JobEntry objects to load. + * + * @param jobEntries + * A list of the JobEntry objects to load. */ public synchronized void batchLoad(List jobEntries) { @@ -134,8 +138,9 @@ /** * Remove a job from the queue. - * - * @param je A JobEntry with the job to remove. + * + * @param je + * A JobEntry with the job to remove. */ public synchronized void remove(JobEntry je) { @@ -145,8 +150,9 @@ /** * Modify a job on the queue. - * - * @param je A JobEntry with the job to modify + * + * @param je + * A JobEntry with the job to modify */ public synchronized void modify(JobEntry je) { @@ -155,33 +161,35 @@ /** * Update the job for its next run time. - * - * @param je A JobEntry to be updated. - * @exception Exception, a generic exception. + * + * @param je + * A JobEntry to be updated. + * @exception Exception, + * a generic exception. */ - public synchronized void updateQueue(JobEntry je) - throws Exception + public synchronized void updateQueue(JobEntry je) throws Exception { je.calcRunTime(); sortQueue(); } /** - * Re-sort the existing queue. Consumers of this method should be + * Re-sort the existing queue. Consumers of this method should be * synchronized. */ private void sortQueue() { - Comparator aComparator = new Comparator () + Comparator aComparator = new Comparator() + { + + public int compare(Object o1, Object o2) { - public int compare(Object o1, Object o2) - { - Long time1 = new Long (((JobEntry)o1).getNextRuntime()); - Long time2 = new Long (((JobEntry)o2).getNextRuntime()); - return (time1.compareTo(time2)); - } - }; - - Collections.sort(queue,aComparator); + Long time1 = new Long(((JobEntry) o1).getNextRuntime()); + Long time2 = new Long(((JobEntry) o2).getNextRuntime()); + return (time1.compareTo(time2)); + } + }; + + Collections.sort(queue, aComparator); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/MemoryBasedScheduler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/MemoryBasedScheduler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/MemoryBasedScheduler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,54 +24,51 @@ import org.apache.commons.logging.LogFactory; /** - * Service for a cron like scheduler that uses the - * properties file instead of the database. - * The methods that operate on jobs ( get,add,update,remove ) - * only operate on the queue in memory and changes are not reflected - * to the properties file which was used to initilize the jobs. - * An example is given below. The job names are the class names that - * extend ScheduledJob. - * + * Service for a cron like scheduler that uses the properties file instead of + * the database. The methods that operate on jobs ( get,add,update,remove ) only + * operate on the queue in memory and changes are not reflected to the + * properties file which was used to initilize the jobs. An example is given + * below. The job names are the class names that extend ScheduledJob. + * *

        - *
          * services.SchedulerService.scheduler.jobs=scheduledJobName,scheduledJobName2
        - *
          * services.SchedulerService.scheduler.job.scheduledJobName.ID=1
          * services.SchedulerService.scheduler.job.scheduledJobName.SECOND=-1
          * services.SchedulerService.scheduler.job.scheduledJobName.MINUTE=-1
          * services.SchedulerService.scheduler.job.scheduledJobName.HOUR=7
          * services.SchedulerService.scheduler.job.scheduledJobName.WEEKDAY=-1
          * services.SchedulerService.scheduler.job.scheduledJobName.DAY_OF_MONTH=-1
        - *
          * services.SchedulerService.scheduler.job.scheduledJobName2.ID=1
          * services.SchedulerService.scheduler.job.scheduledJobName2.SECOND=-1
          * services.SchedulerService.scheduler.job.scheduledJobName2.MINUTE=-1
          * services.SchedulerService.scheduler.job.scheduledJobName2.HOUR=7
          * services.SchedulerService.scheduler.job.scheduledJobName2.WEEKDAY=-1
          * services.SchedulerService.scheduler.job.scheduledJobName2.DAY_OF_MONTH=-1
        - *
          * 
        - * + * * Based on TamboraSchedulerService written by John Thorhauer. - * + * * @author Jeff Brekke * @author John Thorhauer * @author David Sean Taylor * @version $Id: MemoryBasedScheduler.java 516448 2007-03-09 16:25:47Z ate $ */ -public class MemoryBasedScheduler - extends AbstractScheduler implements Scheduler +public class MemoryBasedScheduler extends AbstractScheduler implements + Scheduler { - private final static Log log = LogFactory.getLog(MemoryBasedScheduler.class); + + private final static Log log = LogFactory + .getLog(MemoryBasedScheduler.class); + private Configuration config; - + /** * Constructor. - * - * @exception Exception, a generic exception. + * + * @exception Exception, + * a generic exception. */ - public MemoryBasedScheduler(Configuration config) - throws Exception + public MemoryBasedScheduler(Configuration config) throws Exception { super(); this.config = config; @@ -81,56 +78,52 @@ { return config; } - + public void start() { try - { + { super.start(); scheduleQueue = new JobQueue(); mainLoop = new MainLoop(); - List jobProps = getConfiguration().getList("jobs"); + List jobProps = getConfiguration().getList("jobs"); List jobs = new ArrayList(); // If there are scheduler.jobs defined then set up a job vector // for the scheduleQueue if (!jobProps.isEmpty()) { - for (int i=0;i 0 ) + if (jobs != null && jobs.size() > 0) { -// System.out.println("Starting jobs = " + jobs.size()); - + // System.out.println("Starting jobs = " + jobs.size()); + scheduleQueue.batchLoad(jobs); restart(); } @@ -138,11 +131,11 @@ } catch (Exception e) { - log.error ("Cannot initialize SchedulerService!: ", e); + log.error("Cannot initialize SchedulerService!: ", e); } - + } - + public void stop() { super.stop(); @@ -150,31 +143,28 @@ /** * This method returns the job element from the internal queue. - * - * @param oid The int id for the job. + * + * @param oid + * The int id for the job. * @return A JobEntry. - * @exception Exception, a generic exception. + * @exception Exception, + * a generic exception. */ - public JobEntry getJob(int oid) - throws Exception + public JobEntry getJob(int oid) throws Exception { - JobEntry je = new JobEntry(-1, - -1, - -1, - -1, - -1, - null); + JobEntry je = new JobEntry(-1, -1, -1, -1, -1, null); return scheduleQueue.getJob(je); } /** * Add a new job to the queue. - * - * @param je A JobEntry with the job to add. - * @exception Exception, a generic exception. + * + * @param je + * A JobEntry with the job to add. + * @exception Exception, + * a generic exception. */ - public void addJob(JobEntry je) - throws Exception + public void addJob(JobEntry je) throws Exception { // Add to the queue. scheduleQueue.add(je); @@ -183,12 +173,13 @@ /** * Remove a job from the queue. - * - * @param je A JobEntry with the job to remove. - * @exception Exception, a generic exception. + * + * @param je + * A JobEntry with the job to remove. + * @exception Exception, + * a generic exception. */ - public void removeJob(JobEntry je) - throws Exception + public void removeJob(JobEntry je) throws Exception { // Remove from the queue. scheduleQueue.remove(je); @@ -197,24 +188,25 @@ /** * Modify a Job. - * - * @param je A JobEntry with the job to modify - * @exception Exception, a generic exception. + * + * @param je + * A JobEntry with the job to modify + * @exception Exception, + * a generic exception. */ - public void updateJob(JobEntry je) - throws Exception + public void updateJob(JobEntry je) throws Exception { try { je.calcRunTime(); } - catch(Exception e) + catch (Exception e) { // Log problems. log.error("Problem updating Scheduled Job: " + e); } // Update the queue. - scheduleQueue.modify(je); - restart(); + scheduleQueue.modify(je); + restart(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/ScheduledJob.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/ScheduledJob.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/ScheduledJob.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,33 +16,30 @@ */ package org.apache.jetspeed.scheduler; - /** - * All Scheduled jobs should extend this. The class that extends - * ScheduledJobs should contain the code that you actually want to - * execute at a specific time. The name of this class is what you - * register in the JobEntry. - * + * All Scheduled jobs should extend this. The class that extends ScheduledJobs + * should contain the code that you actually want to execute at a specific time. + * The name of this class is what you register in the JobEntry. + * * @author Dave Bryson * @version $Id: ScheduledJob.java 516448 2007-03-09 16:25:47Z ate $ */ public abstract class ScheduledJob { + /** * Run the Jobentry from the scheduler queue. - * - * @param job The job to run. + * + * @param job + * The job to run. */ - public abstract void run( JobEntry job ) - throws Exception; + public abstract void run(JobEntry job) throws Exception; /** - * This is a stop gap until the scheduler service - * is fully decoupled from modules. Modules - * are for the display system. + * This is a stop gap until the scheduler service is fully decoupled from + * modules. Modules are for the display system. */ - public void execute(JobEntry job) - throws Exception + public void execute(JobEntry job) throws Exception { run(job); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/Scheduler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/Scheduler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/Scheduler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,54 +20,59 @@ /** * ScheduleService interface. - * + * * @author Dave Bryson * @version $Id: Scheduler.java 516448 2007-03-09 16:25:47Z ate $ */ public interface Scheduler { + public static final String SERVICE_NAME = "scheduler"; /** * Get a specific Job from Storage. - * - * @param oid The int id for the job. + * + * @param oid + * The int id for the job. * @return A JobEntry. - * @exception Exception, a generic exception. + * @exception Exception, + * a generic exception. */ - public JobEntry getJob(int oid) - throws Exception; + public JobEntry getJob(int oid) throws Exception; /** * Add a new job to the queue. - * - * @param je A JobEntry with the job to add. - * @exception Exception, a generic exception. + * + * @param je + * A JobEntry with the job to add. + * @exception Exception, + * a generic exception. */ - public void addJob(JobEntry je) - throws Exception; + public void addJob(JobEntry je) throws Exception; /** * Modify a Job. - * - * @param je A JobEntry with the job to modify - * @exception Exception, a generic exception. + * + * @param je + * A JobEntry with the job to modify + * @exception Exception, + * a generic exception. */ - public void updateJob(JobEntry je) - throws Exception; + public void updateJob(JobEntry je) throws Exception; /** * Remove a job from the queue. - * - * @param je A JobEntry with the job to remove. - * @exception Exception, a generic exception. + * + * @param je + * A JobEntry with the job to remove. + * @exception Exception, + * a generic exception. */ - public void removeJob(JobEntry je) - throws Exception; + public void removeJob(JobEntry je) throws Exception; /** - * List jobs in the queue. This is used by the scheduler UI. - * + * List jobs in the queue. This is used by the scheduler UI. + * * @return A List of jobs. */ public List listJobs(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/WorkerThread.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/WorkerThread.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/scheduler/WorkerThread.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,17 +16,16 @@ */ package org.apache.jetspeed.scheduler; - /** * Wrapper for a JobEntry to actually perform the job's action. - * + * * @author Dave Bryson * @author Daniel Rall * @version $Id: WorkerThread.java 516448 2007-03-09 16:25:47Z ate $ */ -public class WorkerThread - implements Runnable +public class WorkerThread implements Runnable { + /** * The JobEntry to run. */ @@ -38,8 +37,9 @@ /** * Creates a new worker to run the specified JobEntry. - * - * @param je The JobEntry to create a worker for. + * + * @param je + * The JobEntry to create a worker for. */ public WorkerThread(JobEntry je) { @@ -51,14 +51,11 @@ */ public void run() { - if (je == null || je.isActive()) - { - return; - } + if (je == null || je.isActive()) { return; } try { - if (! je.isActive()) + if (!je.isActive()) { je.setActive(true); logStateChange("started"); @@ -69,17 +66,18 @@ // getTask() method to return a class name. String className = je.getTask(); - //If a FactoryService is registered, use it. Otherwise, - //instantiate the ScheduledJob directly. - ScheduledJob sc = (ScheduledJob)Class.forName(className).newInstance(); + // If a FactoryService is registered, use it. Otherwise, + // instantiate the ScheduledJob directly. + ScheduledJob sc = (ScheduledJob) Class.forName(className) + .newInstance(); sc.execute(je); } } catch (Exception e) { - //!! use the service for logging - //Log.error("Error in WorkerThread for sheduled job #" + - // je.getPrimaryKey() + ", task: " + je.getTask(), e); + // !! use the service for logging + // Log.error("Error in WorkerThread for sheduled job #" + + // je.getPrimaryKey() + ", task: " + je.getTask(), e); } finally { @@ -93,13 +91,14 @@ /** * Macro to log JobEntry status information. - * - * @param state The new state of the JobEntry. + * + * @param state + * The new state of the JobEntry. */ private final void logStateChange(String state) { - //!! use the service to log. - //Log.debug("Scheduled job #" + je.getPrimaryKey() + ' ' + state + - // ", task: " + je.getTask()); + // !! use the service to log. + // Log.debug("Scheduled job #" + je.getPrimaryKey() + ' ' + state + + // ", task: " + je.getTask()); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/util/OverwriteProperties.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/util/OverwriteProperties.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/jetspeed/src/java/org/apache/jetspeed/util/OverwriteProperties.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,143 +16,145 @@ */ package org.apache.jetspeed.util; +import java.io.BufferedReader; import java.io.File; -import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; - import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; /** * Task to overwrite Properties: used for JRP, TRP and Torque.properties - * - * @author David Sean Taylor - * @author Eric Pugh - * @created January 29, 2003 - * @version $Id: OverwriteProperties.java 516448 2007-03-09 16:25:47Z ate $ + * + * @author David Sean Taylor + * @author Eric Pugh + * @created January 29, 2003 + * @version $Id: OverwriteProperties.java 516448 2007-03-09 16:25:47Z ate $ */ public class OverwriteProperties { - /** The file to merge properties into */ + + /** The file to merge properties into */ protected File baseProperties; - /** The file to pull the properties from */ + + /** The file to pull the properties from */ protected File properties; - /** The directory to look in for include files */ + + /** The directory to look in for include files */ protected File includeRoot; - /** Description of the Field */ + /** Description of the Field */ public boolean verbose = false; - /** An array of all the properties */ + /** An array of all the properties */ protected ArrayList baseArray = new ArrayList(1024); - /** An array of all the properties that will be removed */ + + /** An array of all the properties that will be removed */ protected ArrayList removeArray = new ArrayList(128); - /** Description of the Field */ + + /** Description of the Field */ protected HashMap baseMap = new HashMap(); - /** What to use as a line seperator */ - protected String lineSeparator = System.getProperty("line.separator", "\r\n"); + /** What to use as a line seperator */ + protected String lineSeparator = System.getProperty("line.separator", + "\r\n"); /** - * Sets the file to merge properties into - * - * @param baseProperties The file path to merge properties into + * Sets the file to merge properties into + * + * @param baseProperties + * The file path to merge properties into */ public void setBaseProperties(File baseProperties) { this.baseProperties = baseProperties; } - /** - * Sets the file to pull properties from - * - * @param properties The file path to the pull the merge properties from + * Sets the file to pull properties from + * + * @param properties + * The file path to the pull the merge properties from */ public void setProperties(File properties) { this.properties = properties; } - /** - * Sets the directory to look for includes in. - * - * @param includeRoot the directory to look in. + * Sets the directory to look for includes in. + * + * @param includeRoot + * the directory to look in. */ public void setIncludeRoot(File includeRoot) { this.includeRoot = includeRoot; } - /** - * Sets whether to output extra debugging info - * - * @param verbose The new verbose value + * Sets whether to output extra debugging info + * + * @param verbose + * The new verbose value */ public void setVerbose(boolean verbose) { this.verbose = verbose; } - /** - * Return the file to merge propertie into - * - * @return The baseProperties value + * Return the file to merge propertie into + * + * @return The baseProperties value */ public File getBaseProperties() { return baseProperties; } - /** - * Gets the properties attribute of the OverwriteProperties object - * - * @return The properties value + * Gets the properties attribute of the OverwriteProperties object + * + * @return The properties value */ public File getProperties() { return properties; } - /** - * Gets the includeRoot attribute of the OverwriteProperties object - * - * @return The includeRoot value + * Gets the includeRoot attribute of the OverwriteProperties object + * + * @return The includeRoot value */ public File getIncludeRoot() { return includeRoot; } - /** - * Gets the verbose attribute of the OverwriteProperties object - * - * @return The verbose value + * Gets the verbose attribute of the OverwriteProperties object + * + * @return The verbose value */ public boolean getVerbose() { return verbose; } - /** - * The main program for the OverwriteProperties class - * - * @param args The command line arguments - * @exception Exception Description of the Exception + * The main program for the OverwriteProperties class + * + * @param args + * The command line arguments + * @exception Exception + * Description of the Exception */ - public static void main(String[] args) - throws Exception + public static void main(String[] args) throws Exception { OverwriteProperties overwriteProperties = new OverwriteProperties(); @@ -160,10 +162,12 @@ { if (args.length < 3) { - System.out.println("Usage: java OverwriteProperties c:/temp/File1.props c:/temp/File2.props c:/include-root/"); - System.out.println("Usage: File1 will be modified, new parameters from File 2 will be added,"); - System.out.println( - "Usage: and same parameters will be updated. The include-root is where include files are found."); + System.out + .println("Usage: java OverwriteProperties c:/temp/File1.props c:/temp/File2.props c:/include-root/"); + System.out + .println("Usage: File1 will be modified, new parameters from File 2 will be added,"); + System.out + .println("Usage: and same parameters will be updated. The include-root is where include files are found."); throw new Exception("Incorrect number of arguments supplied"); } overwriteProperties.setBaseProperties(new File(args[0])); @@ -187,87 +191,85 @@ } } - - /** Description of the Method */ - public void execute() throws FileNotFoundException, IOException, SecurityException + /** Description of the Method */ + public void execute() throws FileNotFoundException, IOException, + SecurityException { - if (verbose) - { - System.out.println("Merging into file " + getBaseProperties() + " file " + getProperties()); - } + if (verbose) + { + System.out.println("Merging into file " + getBaseProperties() + + " file " + getProperties()); + } - if (!getBaseProperties().exists()) - { - throw new FileNotFoundException("Could not find file:" + getBaseProperties()); - } + if (!getBaseProperties().exists()) { throw new FileNotFoundException( + "Could not find file:" + getBaseProperties()); } - if (!getProperties().exists()) - { - throw new FileNotFoundException("Could not find file:" + getProperties()); - } + if (!getProperties().exists()) { throw new FileNotFoundException( + "Could not find file:" + getProperties()); } - if (!getIncludeRoot().exists() || !getIncludeRoot().isDirectory()) + if (!getIncludeRoot().exists() || !getIncludeRoot().isDirectory()) { throw new FileNotFoundException( + "Could not find directory:" + getIncludeRoot()); } + + BufferedReader reader = new BufferedReader(new FileReader( + baseProperties)); + int index = 0; + String key = null; + String line = null; + while ((line = reader.readLine()) != null) + { + StringTokenizer tokenizer = new StringTokenizer(line, "="); + baseArray.add(index, line); + if (verbose) { - throw new FileNotFoundException("Could not find directory:" + getIncludeRoot()); + System.out.println("While reading baseArray[" + index + "] = " + + line); } - - BufferedReader reader = new BufferedReader(new FileReader(baseProperties)); - int index = 0; - String key = null; - String line = null; - while ((line = reader.readLine()) != null) + if (tokenizer.countTokens() >= 1 && !line.startsWith("#") + && !line.startsWith("include") + && !line.startsWith("module.packages")) { - StringTokenizer tokenizer = new StringTokenizer(line, "="); - baseArray.add(index, line); - if (verbose) + key = tokenizer.nextToken().trim(); + if (key != null && key.length() > 0) { - System.out.println("While reading baseArray[" + index + "] = " + line); - } - if (tokenizer.countTokens() >= 1 - && !line.startsWith("#") - && !line.startsWith("include") - && !line.startsWith("module.packages")) - { - key = tokenizer.nextToken().trim(); - if (key != null && key.length() > 0) + baseMap.put(key, new Integer(index)); + if (verbose) { - baseMap.put(key, new Integer(index)); - if (verbose) - { - System.out.println("baseMap[" + key + "," + index + "]"); - } + System.out + .println("baseMap[" + key + "," + index + "]"); } } - index++; } - reader.close(); - if (verbose) - { - System.out.println("\nOverwrite with Delta\n"); - } + index++; + } + reader.close(); + if (verbose) + { + System.out.println("\nOverwrite with Delta\n"); + } - readProperties(properties, index); + readProperties(properties, index); - boolean flags[] = removeProperties(); + boolean flags[] = removeProperties(); - baseArray.trimToSize(); - writeToFile(flags); + baseArray.trimToSize(); + writeToFile(flags); - } - /** - * Description of the Method - * - * @param flags Description of the Parameter - * @exception FileNotFoundException Description of the Exception - * @exception IOException Description of the Exception + * Description of the Method + * + * @param flags + * Description of the Parameter + * @exception FileNotFoundException + * Description of the Exception + * @exception IOException + * Description of the Exception */ - public void writeToFile(boolean[] flags) - throws FileNotFoundException, IOException - { + public void writeToFile(boolean[] flags) throws FileNotFoundException, + IOException + { FileOutputStream writer = new FileOutputStream(baseProperties); writer.flush(); for (int i = 0; i < baseArray.size(); i++) @@ -276,13 +278,15 @@ { if (verbose) { - System.out.println("Skipping property[" + i + "] = " + baseArray.get(i)); + System.out.println("Skipping property[" + i + "] = " + + baseArray.get(i)); } continue; } if (verbose) { - System.out.println("Writing property[" + i + "] = " + baseArray.get(i)); + System.out.println("Writing property[" + i + "] = " + + baseArray.get(i)); } writer.write(((String) baseArray.get(i)).getBytes()); writer.write(lineSeparator.getBytes()); @@ -292,11 +296,10 @@ } - /** - * Description of the Method - * - * @return Description of the Return Value + * Description of the Method + * + * @return Description of the Return Value */ public boolean[] removeProperties() { @@ -318,7 +321,8 @@ flags[iy] = true; if (verbose) { - System.out.println("flagging removal of property: " + line); + System.out.println("flagging removal of property: " + + line); } } } @@ -326,18 +330,21 @@ return flags; } - /** - * Reads in the properties from the specified file - * - * @param propFile Description of the Parameter - * @param index Description of the Parameter - * @exception FileNotFoundException Description of the Exception - * @exception IOException Description of the Exception + * Reads in the properties from the specified file + * + * @param propFile + * Description of the Parameter + * @param index + * Description of the Parameter + * @exception FileNotFoundException + * Description of the Exception + * @exception IOException + * Description of the Exception */ public void readProperties(File propFile, int index) - throws FileNotFoundException, IOException - { + throws FileNotFoundException, IOException + { BufferedReader reader = new BufferedReader(new FileReader(propFile)); String key = null; String line = null; @@ -350,10 +357,11 @@ if (count == 2 && line.startsWith("include")) { key = tokenizer.nextToken().trim(); - File includeFile = new File(includeRoot + tokenizer.nextToken().trim()); + File includeFile = new File(includeRoot + + tokenizer.nextToken().trim()); if (verbose) { - System.out.println("include File = " + includeFile); + System.out.println("include File = " + includeFile); } readProperties(includeFile, index); continue; @@ -363,7 +371,8 @@ baseArray.add(index, line); if (verbose) { - System.out.println("Adding module.package to baseArray[" + index + "] = " + line); + System.out.println("Adding module.package to baseArray[" + + index + "] = " + line); } index++; @@ -374,7 +383,8 @@ baseArray.set(ix, line); if (verbose) { - System.out.println("Resetting baseArray[" + ix + "] = " + line); + System.out.println("Resetting baseArray[" + ix + "] = " + + line); } } @@ -403,7 +413,8 @@ baseArray.set(ix, line); if (verbose) { - System.out.println("Resetting baseArray[" + ix + "] = " + line); + System.out.println("Resetting baseArray[" + ix + + "] = " + line); } } else @@ -411,12 +422,14 @@ baseArray.add(index, line); if (verbose) { - System.out.println("Adding new entry to baseArray[" + index + "] = " + line); + System.out.println("Adding new entry to baseArray[" + + index + "] = " + line); } baseMap.put(key, new Integer(index)); if (verbose) { - System.out.println("baseMap[" + key + "," + index + "]"); + System.out.println("baseMap[" + key + "," + index + + "]"); } index++; } @@ -427,5 +440,5 @@ reader.close(); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/locator/JetspeedLocatorDescriptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/locator/JetspeedLocatorDescriptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/locator/JetspeedLocatorDescriptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,38 +18,45 @@ /** * Jetspeed default Locator Descriptor implementation - * + * * @author David Sean Taylor * @version $Id: JetspeedLocatorDescriptor.java 516448 2007-03-09 16:25:47Z ate $ */ public class JetspeedLocatorDescriptor implements LocatorDescriptor { + public JetspeedLocatorDescriptor() { } - + private String type; + private String name; + private String mediaType; + private String language; - private String country; + + private String country; + private static final String DELIM = "/"; - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ public String toString() - { + { StringBuffer value = new StringBuffer(); // type if (type != null) { - value.append(LocatorDescriptor.PARAM_TYPE).append(DELIM); + value.append(LocatorDescriptor.PARAM_TYPE).append(DELIM); value.append(type).append(DELIM); } - + // media type if (mediaType != null) { @@ -63,27 +70,29 @@ value.append(LocatorDescriptor.PARAM_LANGUAGE).append(DELIM); value.append(language).append(DELIM); } - + // country if (country != null) { value.append(LocatorDescriptor.PARAM_COUNTRY).append(DELIM); value.append(country).append(DELIM); } - + // template name if (name != null) { - value.append(LocatorDescriptor.PARAM_NAME).append(DELIM); + value.append(LocatorDescriptor.PARAM_NAME).append(DELIM); value.append(name).append(DELIM); } - - value.deleteCharAt(value.length()-1); + + value.deleteCharAt(value.length() - 1); return value.toString(); - + } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.template.TemplateLocator#toPath() */ public String toPath() @@ -95,7 +104,7 @@ { value.append(type).append(DELIM); } - + // media type if (mediaType != null) { @@ -107,104 +116,124 @@ { value.append(language).append(DELIM); } - + // country if (country != null) { value.append(country).append(DELIM); } - + // template name if (name != null) { value.append(name).append(DELIM); } - - value.deleteCharAt(value.length()-1); + + value.deleteCharAt(value.length() - 1); return value.toString(); - + } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.template.TemplateLocator#getType() */ public String getType() { return type; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.template.TemplateLocator#setType(java.lang.String) */ public void setType(String type) { this.type = type; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.template.TemplateLocator#getName() */ public String getName() { return name; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.template.TemplateLocator#setName(java.lang.String) */ public void setName(String name) { this.name = name; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.template.TemplateLocator#getMediaType() */ public String getMediaType() { return mediaType; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.template.TemplateLocator#setMediaType(java.lang.String) */ public void setMediaType(String mediaType) { this.mediaType = mediaType; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.template.TemplateLocator#getLanguage() */ public String getLanguage() { return language; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.template.TemplateLocator#setLanguage(java.lang.String) */ public void setLanguage(String language) { this.language = language; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.template.TemplateLocator#getCountry() */ public String getCountry() { return country; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.template.TemplateLocator#setCountry(java.lang.String) */ public void setCountry(String country) { this.country = country; } - + /** * @see Object#clone * @return an instance copy of this object @@ -213,5 +242,5 @@ { return super.clone(); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/locator/JetspeedTemplateDescriptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/locator/JetspeedTemplateDescriptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/locator/JetspeedTemplateDescriptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,20 +20,23 @@ /** * Jetspeed default Template Descriptor implementation - * + * * @author David Sean Taylor * @version $Id: JetspeedTemplateDescriptor.java 516448 2007-03-09 16:25:47Z ate $ */ -public class JetspeedTemplateDescriptor extends JetspeedLocatorDescriptor implements TemplateDescriptor +public class JetspeedTemplateDescriptor extends JetspeedLocatorDescriptor + implements TemplateDescriptor { + String absolutePath; + String appRelativePath; - + public JetspeedTemplateDescriptor() { super(); } - + public JetspeedTemplateDescriptor(LocatorDescriptor locator) { this.setCountry(locator.getCountry()); @@ -42,8 +45,10 @@ this.setName(locator.getName()); this.setType(locator.getType()); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.template.Template#getAbsolutePath() */ public String getAbsolutePath() @@ -51,16 +56,16 @@ return this.absolutePath; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.template.Template#setAbsolutePath(java.lang.String) */ public void setAbsolutePath(String path) { this.absolutePath = (new File(path)).getAbsolutePath(); } - - - + /** * @see Object#clone * @return an instance copy of this object @@ -69,7 +74,7 @@ { return super.clone(); } - + /** * @return */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/locator/JetspeedTemplateLocator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/locator/JetspeedTemplateLocator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/locator/JetspeedTemplateLocator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,28 +30,30 @@ /** * Jetspeed's default implementation of a template locator. - * + * * @author David Sean Taylor * @version $Id: JetspeedTemplateLocator.java 587334 2007-10-23 00:30:49Z taylor $ */ public class JetspeedTemplateLocator implements TemplateLocator { - private final static Log log = LogFactory.getLog(JetspeedTemplateLocator.class); + private final static Log log = LogFactory + .getLog(JetspeedTemplateLocator.class); + private static final String PATH_SEPARATOR = "/"; /** the template root directories, all application root relative */ private List roots; - + /** Root of the application running this locator */ private String appRoot; - - /** the Template class is factory created */ - private Class templateClass = JetspeedTemplateDescriptor.class; - /** the TemplateLocator class is factory created */ - private Class locatorClass = JetspeedLocatorDescriptor.class; - + /** the Template class is factory created */ + private Class templateClass = JetspeedTemplateDescriptor.class; + + /** the TemplateLocator class is factory created */ + private Class locatorClass = JetspeedLocatorDescriptor.class; + /** the default locator type */ private String defaultLocatorType = "layout"; @@ -65,115 +67,135 @@ { // need to know roots } - + /** * Minimal assembly with a list of resource directory roots. * - * @param roots A list of resource root directories where templates are located. - * @param appRoot Root from where this application runs + * @param roots + * A list of resource root directories where templates are + * located. + * @param appRoot + * Root from where this application runs */ - public JetspeedTemplateLocator(List roots, String appRoot) throws FileNotFoundException + public JetspeedTemplateLocator(List roots, String appRoot) + throws FileNotFoundException { this.appRoot = appRoot; - log.info("Locator application root "+new File(appRoot).getAbsolutePath()); - this.roots = roots; + log.info("Locator application root " + + new File(appRoot).getAbsolutePath()); + this.roots = roots; Iterator itr = roots.iterator(); - while(itr.hasNext()) + while (itr.hasNext()) { - String path = (String) itr.next(); + String path = (String) itr.next(); File checkFile = new File(path); - if(!checkFile.exists()) - { - throw new FileNotFoundException("Locator resource root "+checkFile.getAbsolutePath()+" does not exist."); - } - } + if (!checkFile.exists()) { throw new FileNotFoundException( + "Locator resource root " + checkFile.getAbsolutePath() + + " does not exist."); } + } } /** * Construct with a root list and a default locator type. * - * @param roots A list of resource root directories where templates are located. - * @param defaultLocatorType Under root directories, subdirectories represent locator types. - * A locator type represents a classification of templates. - * Any value is allowed. Use locator types to group templates together. + * @param roots + * A list of resource root directories where templates are + * located. + * @param defaultLocatorType + * Under root directories, subdirectories represent locator + * types. A locator type represents a classification of + * templates. Any value is allowed. Use locator types to group + * templates together. */ - public JetspeedTemplateLocator(List roots, - String defaultLocatorType, - String appRoot) throws FileNotFoundException + public JetspeedTemplateLocator(List roots, String defaultLocatorType, + String appRoot) throws FileNotFoundException { this(roots, appRoot); this.defaultLocatorType = defaultLocatorType; } /** - * Assemble with list resource directory roots and OM classes and a defaultLocatorType. + * Assemble with list resource directory roots and OM classes and a + * defaultLocatorType. * - * @param roots A list of resource root directories where templates are located. - * @param omClasses Template replacable object model implementations for Template and TemplateLocator. - * Required order, with second optional: [ Template, TemplateLocator implementations. - * @param defaultLocatorType Under root directories, subdirectories represent locator types. - * A locator type represents a classification of templates. - * Any value is allowed. Use locator types to group templates together. + * @param roots + * A list of resource root directories where templates are + * located. + * @param omClasses + * Template replacable object model implementations for Template + * and TemplateLocator. Required order, with second optional: [ + * Template, TemplateLocator + * implementations. + * @param defaultLocatorType + * Under root directories, subdirectories represent locator + * types. A locator type represents a classification of + * templates. Any value is allowed. Use locator types to group + * templates together. */ - public JetspeedTemplateLocator(List roots, - List omClasses, - String defaultLocatorType, - String appRoot) throws FileNotFoundException + public JetspeedTemplateLocator(List roots, List omClasses, + String defaultLocatorType, String appRoot) + throws FileNotFoundException { - this(roots, defaultLocatorType, appRoot); - + this(roots, defaultLocatorType, appRoot); + if (omClasses.size() > 0) { - this.templateClass = (Class)omClasses.get(0); + this.templateClass = (Class) omClasses.get(0); if (omClasses.size() > 1) { - this.locatorClass = (Class)omClasses.get(1); + this.locatorClass = (Class) omClasses.get(1); } - } + } } - + public TemplateDescriptor locateTemplate(LocatorDescriptor locator) { for (int ix = 0; ix < roots.size(); ix++) - { - TemplateDescriptor template = locateTemplate(locator, (String)roots.get(ix), this.useNameCache); + { + TemplateDescriptor template = locateTemplate(locator, + (String) roots.get(ix), this.useNameCache); if (null == template) { - // Try to locate it directly on file system, perhaps it was recently added - template = locateTemplate(locator, (String)roots.get(ix), false); + // Try to locate it directly on file system, perhaps it was + // recently added + template = locateTemplate(locator, (String) roots.get(ix), + false); if (null != template) { // add it to the map templateMap.put(template.getAbsolutePath(), null); } } - if (template != null) - { - return template; - } + if (template != null) { return template; } } - return null; + return null; } - + /** - * General template location algorithm. Starts with the most specific resource, - * including mediatype + nls specification, and fallsback to least specific. - * - * @param locator The template locator - * @param root The root directory to search - * - * @return TemplateDescriptor the exact path to the template, or null if not found. + * General template location algorithm. Starts with the most specific + * resource, including mediatype + nls specification, and fallsback to least + * specific. + * + * @param locator + * The template locator + * @param root + * The root directory to search + * + * @return TemplateDescriptor the exact path to the template, or null if not + * found. */ - private TemplateDescriptor locateTemplate(LocatorDescriptor locator, String root, boolean useCache) + private TemplateDescriptor locateTemplate(LocatorDescriptor locator, + String root, boolean useCache) { - String templateName = locator.getName(); + String templateName = locator.getName(); String path = locator.toPath(); - + String realPath = null; String workingPath = null; int lastSeperator; - while (path !=null && (lastSeperator = path.lastIndexOf(PATH_SEPARATOR))> 0) + while (path != null + && (lastSeperator = path.lastIndexOf(PATH_SEPARATOR)) > 0) { path = path.substring(0, lastSeperator); @@ -185,42 +207,37 @@ { if (log.isDebugEnabled()) { - log.debug( - "TemplateLocator: template exists: " - + realPath - + " returning " - + workingPath); + log.debug("TemplateLocator: template exists: " + realPath + + " returning " + workingPath); } int appRootLength = appRoot.length(); // remove the application root path from the reall path to // give us a app relative path - String appRelativePath = realPath.substring(appRootLength, realPath.length()); - // return createTemplateFromPath(path, templateName, realPath, "/WEB-INF/templates" + workingPath); - return createTemplateFromPath(path, templateName, realPath, appRelativePath); + String appRelativePath = realPath.substring(appRootLength, + realPath.length()); + // return createTemplateFromPath(path, templateName, realPath, + // "/WEB-INF/templates" + workingPath); + return createTemplateFromPath(path, templateName, realPath, + appRelativePath); } } return null; } /** - * Checks for the existence of a template resource given a key. - * The key are absolute paths to the templates, and are cached - * in a template cache for performance. - * - * @param key The absolute path to the template resource. - * + * Checks for the existence of a template resource given a key. The key are + * absolute paths to the templates, and are cached in a template cache for + * performance. + * + * @param key + * The absolute path to the template resource. + * * @return True when the template is found, otherwise false. */ public boolean templateExists(String templateKey, boolean useCache) { - if (null == templateKey) - { - return false; - } - if (useCache == true) - { - return templateMap.containsKey(templateKey); - } + if (null == templateKey) { return false; } + if (useCache == true) { return templateMap.containsKey(templateKey); } return (new File(templateKey).exists()); } @@ -228,58 +245,67 @@ { return templateExists(templateKey, this.useNameCache); } - + public LocatorDescriptor createFromString(String path) - throws TemplateLocatorException + throws TemplateLocatorException { LocatorDescriptor locator = createLocatorDescriptor(this.defaultLocatorType); StringTokenizer tok = new StringTokenizer(path, "/"); while (tok.hasMoreTokens()) { String name = tok.nextToken(); - if (name.equals(LocatorDescriptor.PARAM_TYPE) && tok.hasMoreTokens()) + if (name.equals(LocatorDescriptor.PARAM_TYPE) + && tok.hasMoreTokens()) { - locator.setType( tok.nextToken() ); + locator.setType(tok.nextToken()); } - else if (name.equals(LocatorDescriptor.PARAM_MEDIA_TYPE) && tok.hasMoreTokens()) + else if (name.equals(LocatorDescriptor.PARAM_MEDIA_TYPE) + && tok.hasMoreTokens()) { locator.setMediaType(tok.nextToken()); } - else if (name.equals(LocatorDescriptor.PARAM_LANGUAGE) && tok.hasMoreTokens()) + else if (name.equals(LocatorDescriptor.PARAM_LANGUAGE) + && tok.hasMoreTokens()) { locator.setLanguage(tok.nextToken()); } - else if (name.equals(LocatorDescriptor.PARAM_COUNTRY) && tok.hasMoreTokens()) + else if (name.equals(LocatorDescriptor.PARAM_COUNTRY) + && tok.hasMoreTokens()) { locator.setCountry(tok.nextToken()); } - - else if (name.equals(LocatorDescriptor.PARAM_NAME) && tok.hasMoreTokens()) + + else if (name.equals(LocatorDescriptor.PARAM_NAME) + && tok.hasMoreTokens()) { locator.setName(tok.nextToken()); } - } - return locator; + } + return locator; } /** * Given a path, name and realPath creates a new template object * - * @param path the relative path to the template - * @param name the template name - * @param realPath the real path on the file system + * @param path + * the relative path to the template + * @param name + * the template name + * @param realPath + * the real path on the file system * @return newly created TemplateDescriptor */ - private TemplateDescriptor createTemplateFromPath(String path, String name, String realPath, String relativePath) - { + private TemplateDescriptor createTemplateFromPath(String path, String name, + String realPath, String relativePath) + { TemplateDescriptor template = this.createTemplate(); template.setAbsolutePath(realPath); - if(relativePath.indexOf("/") != 0) + if (relativePath.indexOf("/") != 0) { - relativePath = "/"+relativePath; + relativePath = "/" + relativePath; } template.setAppRelativePath(relativePath); - template.setName(name); + template.setName(name); StringTokenizer tok = new StringTokenizer(path, "/"); int count = 0; while (tok.hasMoreTokens()) @@ -287,64 +313,66 @@ String token = tok.nextToken(); switch (count) { - case 0: - template.setType(token); - break; - case 1: - template.setMediaType(token); - break; - case 2: - template.setLanguage(token); - break; - case 3: - template.setCountry(token); - break; + case 0: + template.setType(token); + break; + case 1: + template.setMediaType(token); + break; + case 2: + template.setLanguage(token); + break; + case 3: + template.setCountry(token); + break; } count++; - } - return template; + } + return template; } - + public LocatorDescriptor createLocatorDescriptor(String type) - throws TemplateLocatorException + throws TemplateLocatorException { LocatorDescriptor locator = null; - + try { - locator = (LocatorDescriptor)locatorClass.newInstance(); + locator = (LocatorDescriptor) locatorClass.newInstance(); locator.setType(type); } - catch(Exception e) + catch (Exception e) { - throw new TemplateLocatorException("Failed instantiate a Template Locator implementation object: ", e); + throw new TemplateLocatorException( + "Failed instantiate a Template Locator implementation object: ", + e); } - return locator; + return locator; } private TemplateDescriptor createTemplate() { TemplateDescriptor template = null; - + try { - template = (TemplateDescriptor)templateClass.newInstance(); + template = (TemplateDescriptor) templateClass.newInstance(); } - catch(Exception e) + catch (Exception e) { log.error("Failed to create template", e); - template = new JetspeedTemplateDescriptor(); + template = new JetspeedTemplateDescriptor(); } - return template; + return template; } public void start() - { + { this.templateMap = Collections.synchronizedMap(new HashMap()); for (int ix = 0; ix < roots.size(); ix++) { - String templateRoot = (String)roots.get(ix); + String templateRoot = (String) roots.get(ix); if (!templateRoot.endsWith(PATH_SEPARATOR)) { @@ -358,7 +386,7 @@ public void stop() { } - + public Iterator query(LocatorDescriptor locator) { return null; // TODO: implement this @@ -366,9 +394,11 @@ /** * Loads the template name cache map to accelerate template searches. - * - * @param path The template - * @param name just the name of the resource + * + * @param path + * The template + * @param name + * just the name of the resource */ private void loadNameCache(String path, String name) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/JetspeedProfileLocator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/JetspeedProfileLocator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/JetspeedProfileLocator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,13 +29,15 @@ /** * ProfileLocatorImpl - * + * * @author David Sean Taylor * @version $Id: JetspeedProfileLocator.java 517719 2007-03-13 15:05:48Z ate $ */ public class JetspeedProfileLocator implements ProfileLocatorControl -{ +{ + private LinkedList elements = new LinkedList(); + private String requestPath; public List getElements() @@ -55,21 +57,20 @@ } public Iterator iterator() - { + { return new ProfileFallbackIterator(this); } - + public String getValue(String name) { Iterator iter = elements.iterator(); while (iter.hasNext()) { - ProfileLocatorPropertyImpl element = (ProfileLocatorPropertyImpl)iter.next(); + ProfileLocatorPropertyImpl element = (ProfileLocatorPropertyImpl) iter + .next(); String elementName = element.getName(); - if (elementName != null && elementName.equals(name)) - { - return element.getValue(); - } + if (elementName != null && elementName.equals(name)) { return element + .getValue(); } } return null; } @@ -79,12 +80,11 @@ Iterator iter = elements.iterator(); while (iter.hasNext()) { - ProfileLocatorPropertyImpl element = (ProfileLocatorPropertyImpl)iter.next(); + ProfileLocatorPropertyImpl element = (ProfileLocatorPropertyImpl) iter + .next(); String elementName = element.getName(); - if (elementName != null && elementName.equals(name)) - { - return element.isControl(); - } + if (elementName != null && elementName.equals(name)) { return element + .isControl(); } } return false; } @@ -94,35 +94,39 @@ Iterator iter = elements.iterator(); while (iter.hasNext()) { - ProfileLocatorPropertyImpl element = (ProfileLocatorPropertyImpl)iter.next(); + ProfileLocatorPropertyImpl element = (ProfileLocatorPropertyImpl) iter + .next(); String elementName = element.getName(); - if (elementName != null && elementName.equals(name)) - { - return element.isNavigation(); - } + if (elementName != null && elementName.equals(name)) { return element + .isNavigation(); } } return false; } - - public void add(RuleCriterion criterion, boolean isControl, boolean isNavigation, String value) + + public void add(RuleCriterion criterion, boolean isControl, + boolean isNavigation, String value) { - elements.add(new ProfileLocatorPropertyImpl(criterion, isControl, isNavigation, value)); + elements.add(new ProfileLocatorPropertyImpl(criterion, isControl, + isNavigation, value)); } - public void add(String name, boolean isControl, boolean isNavigation, String value) + public void add(String name, boolean isControl, boolean isNavigation, + String value) { - elements.add(new ProfileLocatorPropertyImpl(name, isControl, isNavigation, value)); + elements.add(new ProfileLocatorPropertyImpl(name, isControl, + isNavigation, value)); } - + public void add(String name, String value) { add(name, true, false, value); } - + public void createFromLocatorPath(String path) { elements.clear(); - StringTokenizer tokenizer = new StringTokenizer(path, ProfileLocator.PATH_SEPARATOR); + StringTokenizer tokenizer = new StringTokenizer(path, + ProfileLocator.PATH_SEPARATOR); while (tokenizer.hasMoreTokens()) { String name = tokenizer.nextToken(); @@ -131,16 +135,17 @@ String value = tokenizer.nextToken(); this.add(name, true, false, value); } - } + } } - + public String getLocatorPath() { StringBuffer key = new StringBuffer(); ListIterator it = elements.listIterator(); while (it.hasNext()) { - ProfileLocatorPropertyImpl element = (ProfileLocatorPropertyImpl)it.next(); + ProfileLocatorPropertyImpl element = (ProfileLocatorPropertyImpl) it + .next(); key.append(element.getName()); key.append(ProfileLocator.PATH_SEPARATOR); key.append(element.getValue()); @@ -151,27 +156,26 @@ } return key.toString(); } - - public String getLocatorPath(ProfileLocatorProperty [] properties) + + public String getLocatorPath(ProfileLocatorProperty[] properties) { StringBuffer key = new StringBuffer(); - if (properties != null) - for (int i = 0; (i < properties.length); i++) - { - if (i > 0) - key.append(ProfileLocator.PATH_SEPARATOR); - key.append(properties[i].getName()); - key.append(ProfileLocator.PATH_SEPARATOR); - key.append(properties[i].getValue()); - } + if (properties != null) for (int i = 0; (i < properties.length); i++) + { + if (i > 0) key.append(ProfileLocator.PATH_SEPARATOR); + key.append(properties[i].getName()); + key.append(ProfileLocator.PATH_SEPARATOR); + key.append(properties[i].getValue()); + } return key.toString(); } public String toString() { - return getRequestPath() + ProfileLocator.PATH_SEPARATOR + getLocatorPath(); + return getRequestPath() + ProfileLocator.PATH_SEPARATOR + + getLocatorPath(); } - + public String getRequestPath() { return requestPath; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/ProfileFallbackIterator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/ProfileFallbackIterator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/ProfileFallbackIterator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,78 +24,88 @@ /** * ProfileFallbackIterator - * + * * @author David Sean Taylor * @version $Id: ProfileFallbackIterator.java 516448 2007-03-09 16:25:47Z ate $ */ public class ProfileFallbackIterator implements Iterator { + private ProfileLocatorControl locator; + private int last = 0; - private int state = RuleCriterion.FALLBACK_CONTINUE; + + private int state = RuleCriterion.FALLBACK_CONTINUE; + private ProfileFallbackIterator() { } - + public ProfileFallbackIterator(ProfileLocatorControl locator) { this.locator = locator; last = locator.getElements().size() - 1; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see java.util.Iterator#remove() */ public void remove() { // TODO Auto-generated method stub } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see java.util.Iterator#hasNext() */ public boolean hasNext() { boolean hasNext = false; - + List elements = locator.getElements(); - + if (last < 0 || last >= elements.size()) { state = RuleCriterion.FALLBACK_STOP; return false; } - + if (state == RuleCriterion.FALLBACK_STOP) { hasNext = false; - } - else if (state == RuleCriterion.FALLBACK_CONTINUE || - state == RuleCriterion.FALLBACK_LOOP) + } + else if (state == RuleCriterion.FALLBACK_CONTINUE + || state == RuleCriterion.FALLBACK_LOOP) { hasNext = true; } - + return hasNext; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see java.util.Iterator#next() */ public Object next() { - ProfileLocatorProperty [] properties = null; + ProfileLocatorProperty[] properties = null; if (last >= 0) { // generate properties list to return List elements = locator.getElements(); - properties = new ProfileLocatorProperty[last+1]; + properties = new ProfileLocatorProperty[last + 1]; ProfileLocatorProperty lastElement = null; Iterator it = elements.listIterator(); for (int count = 0; (count <= last) && it.hasNext(); count++) { - lastElement = (ProfileLocatorProperty)it.next(); + lastElement = (ProfileLocatorProperty) it.next(); properties[count] = lastElement; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/ProfileLocatorControl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/ProfileLocatorControl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/ProfileLocatorControl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,11 +22,12 @@ /** * ProfileLocatorControl - * + * * @author David Sean Taylor * @version $Id: ProfileLocatorControl.java 516448 2007-03-09 16:25:47Z ate $ */ public interface ProfileLocatorControl extends ProfileLocator { + List getElements(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/ProfileLocatorPropertyImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/ProfileLocatorPropertyImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/java/org/apache/jetspeed/profiler/impl/ProfileLocatorPropertyImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,20 +22,27 @@ /** * ProfileLocatorElement - * + * * @author David Sean Taylor * @version $Id: ProfileLocatorPropertyImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class ProfileLocatorPropertyImpl implements ProfileLocatorProperty { + private String name; + private String value; + private String type; + private int fallbackType; + private boolean isControl = true; + private boolean isNavigation = false; - - public ProfileLocatorPropertyImpl(RuleCriterion criterion, boolean isControl, boolean isNavigation, String value) + + public ProfileLocatorPropertyImpl(RuleCriterion criterion, + boolean isControl, boolean isNavigation, String value) { this.name = criterion.getName(); this.value = value; @@ -44,8 +51,9 @@ this.isControl = isControl; this.isNavigation = isNavigation; } - - public ProfileLocatorPropertyImpl(String name, boolean isControl, boolean isNavigation, String value) + + public ProfileLocatorPropertyImpl(String name, boolean isControl, + boolean isNavigation, String value) { this.name = name; this.value = value; @@ -71,7 +79,6 @@ this.value = value; } - /** * @return */ @@ -135,5 +142,5 @@ { return isNavigation; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/test/org/apache/jetspeed/locator/TestTemplateLocator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/test/org/apache/jetspeed/locator/TestTemplateLocator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/locator/src/test/org/apache/jetspeed/locator/TestTemplateLocator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,28 +24,30 @@ /** * TestTemplateLocator - * + * * @author David Sean Taylor * @version $Id: TestTemplateLocator.java 516448 2007-03-09 16:25:47Z ate $ */ public class TestTemplateLocator extends TestCase { + private JetspeedTemplateLocator templateLocator; - public TestTemplateLocator(String name) + public TestTemplateLocator(String name) { - super( name ); + super(name); } - /** * Start the tests. - * - * @param args the arguments. Not used + * + * @param args + * the arguments. Not used */ - public static void main(String args[]) + public static void main(String args[]) { - junit.awtui.TestRunner.main( new String[] { TestTemplateLocator.class.getName() } ); + junit.awtui.TestRunner.main(new String[] + {TestTemplateLocator.class.getName()}); } public static Test suite() @@ -53,73 +55,88 @@ // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestTemplateLocator.class); } - - public void testLocateTemplate() - throws Exception + + public void testLocateTemplate() throws Exception { - // TemplateLocator component = (TemplateLocator)componentManager.getComponent("TemplateLocator"); - assertNotNull("template service is null", templateLocator); - LocatorDescriptor locator = templateLocator.createLocatorDescriptor("email"); + // TemplateLocator component = + // (TemplateLocator)componentManager.getComponent("TemplateLocator"); + assertNotNull("template service is null", templateLocator); + LocatorDescriptor locator = templateLocator + .createLocatorDescriptor("email"); locator.setName("test.vm"); TemplateDescriptor template = templateLocator.locateTemplate(locator); assertNotNull("template is null", template); System.out.println("template1 = " + template); - assertTrue("template1 result", "type/email/name/test.vm".endsWith(template.toString())); - - LocatorDescriptor locator2 = templateLocator.createLocatorDescriptor("email"); + assertTrue("template1 result", "type/email/name/test.vm" + .endsWith(template.toString())); + + LocatorDescriptor locator2 = templateLocator + .createLocatorDescriptor("email"); locator2.setName("htmltest.vm"); - locator2.setMediaType("html"); + locator2.setMediaType("html"); template = templateLocator.locateTemplate(locator2); - assertNotNull("template is null", template); - System.out.println("template2 = " + template); - assertTrue("template2 result", "type/email/media-type/html/name/htmltest.vm".endsWith(template.toString())); + assertNotNull("template is null", template); + System.out.println("template2 = " + template); + assertTrue("template2 result", + "type/email/media-type/html/name/htmltest.vm".endsWith(template + .toString())); - LocatorDescriptor locator3 = templateLocator.createLocatorDescriptor("email"); + LocatorDescriptor locator3 = templateLocator + .createLocatorDescriptor("email"); locator3.setName("entest.vm"); locator3.setMediaType("html"); - locator3.setLanguage("en"); + locator3.setLanguage("en"); template = templateLocator.locateTemplate(locator3); - assertNotNull("template is null", template); - System.out.println("template3 = " + template); - assertTrue("template3 result", "type/email/media-type/html/language/en/name/entest.vm".endsWith(template.toString())); + assertNotNull("template is null", template); + System.out.println("template3 = " + template); + assertTrue("template3 result", + "type/email/media-type/html/language/en/name/entest.vm" + .endsWith(template.toString())); - LocatorDescriptor locator4 = templateLocator.createLocatorDescriptor("email"); + LocatorDescriptor locator4 = templateLocator + .createLocatorDescriptor("email"); locator4.setName("ustest.vm"); locator4.setMediaType("html"); locator4.setLanguage("en"); - locator4.setCountry("US"); + locator4.setCountry("US"); template = templateLocator.locateTemplate(locator4); - assertNotNull("template is null", template); - System.out.println("template4 = " + template); - assertTrue("template4 result", - "type/email/media-type/html/language/en/country/US/name/ustest.vm".endsWith(template.toString())); + assertNotNull("template is null", template); + System.out.println("template4 = " + template); + assertTrue("template4 result", + "type/email/media-type/html/language/en/country/US/name/ustest.vm" + .endsWith(template.toString())); // test fallback - LocatorDescriptor locator5 = templateLocator.createLocatorDescriptor("email"); + LocatorDescriptor locator5 = templateLocator + .createLocatorDescriptor("email"); locator5.setName("entest.vm"); locator5.setMediaType("html"); locator5.setLanguage("en"); - locator5.setCountry("UZ"); + locator5.setCountry("UZ"); template = templateLocator.locateTemplate(locator5); - assertNotNull("template is null", template); - System.out.println("template5 = " + template); - assertTrue("template5 result", - "type/email/media-type/html/language/en/name/entest.vm".endsWith(template.toString())); + assertNotNull("template is null", template); + System.out.println("template5 = " + template); + assertTrue("template5 result", + "type/email/media-type/html/language/en/name/entest.vm" + .endsWith(template.toString())); // test fallback all the way to email - LocatorDescriptor locator6 = templateLocator.createLocatorDescriptor("email"); + LocatorDescriptor locator6 = templateLocator + .createLocatorDescriptor("email"); locator6.setName("test.vm"); locator6.setMediaType("html"); locator6.setLanguage("en"); - locator6.setCountry("UZ"); + locator6.setCountry("UZ"); template = templateLocator.locateTemplate(locator6); - System.out.println("template6 = " + template); - assertTrue("template6 result", - "type/email/name/test.vm".endsWith(template.toString())); - + System.out.println("template6 = " + template); + assertTrue("template6 result", "type/email/name/test.vm" + .endsWith(template.toString())); + } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception @@ -129,8 +146,9 @@ ArrayList classes = new ArrayList(2); classes.add(JetspeedTemplateDescriptor.class); classes.add(JetspeedLocatorDescriptor.class); - - templateLocator = new JetspeedTemplateLocator(roots, classes, "email", "./"); + + templateLocator = new JetspeedTemplateLocator(roots, classes, "email", + "./"); templateLocator.start(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuDefinitionElement.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuDefinitionElement.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuDefinitionElement.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,13 +24,16 @@ */ public abstract class BaseMenuDefinitionElement { + private int id; + private String ojbConcreteClass = getClass().getName(); + private int elementOrder; /** * getElementOrder - * + * * @return element order */ public int getElementOrder() @@ -40,8 +43,9 @@ /** * setElementOrder - * - * @param order element order + * + * @param order + * element order */ public void setElementOrder(int order) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,25 +27,37 @@ * @author Randy Watler * @version $Id:$ */ -public abstract class BaseMenuDefinitionImpl extends BaseMenuDefinitionMetadata implements MenuDefinition +public abstract class BaseMenuDefinitionImpl extends BaseMenuDefinitionMetadata + implements MenuDefinition { + private String name; + private String options; + private int depth; + private boolean paths; + private boolean regexp; + private String profile; + private String order; + private String skin; + private String title; + private String shortTitle; + private List elements; /** * accessElements - * + * * Access mutable persistent collection member for List wrappers. - * + * * @return persistent collection */ public List accessElements() @@ -58,7 +70,9 @@ return elements; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getName() */ public String getName() @@ -66,7 +80,9 @@ return name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#setName(java.lang.String) */ public void setName(String name) @@ -74,7 +90,9 @@ this.name = name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getOptions() */ public String getOptions() @@ -82,7 +100,9 @@ return options; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#setOptions(java.lang.String) */ public void setOptions(String options) @@ -90,7 +110,9 @@ this.options = options; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getDepth() */ public int getDepth() @@ -98,7 +120,9 @@ return depth; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#setDepth(int) */ public void setDepth(int depth) @@ -106,23 +130,29 @@ this.depth = depth; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getPaths() */ public boolean isPaths() { return paths; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#setPaths(boolean) */ public void setPaths(boolean paths) { this.paths = paths; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getRegexp() */ public boolean isRegexp() @@ -130,7 +160,9 @@ return regexp; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#setRegexp(boolean) */ public void setRegexp(boolean regexp) @@ -138,7 +170,9 @@ this.regexp = regexp; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getProfile() */ public String getProfile() @@ -146,7 +180,9 @@ return profile; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#setProfile(java.lang.String) */ public void setProfile(String locatorName) @@ -154,7 +190,9 @@ profile = locatorName; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getOrder() */ public String getOrder() @@ -162,7 +200,9 @@ return order; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#setOrder(java.lang.String) */ public void setOrder(String order) @@ -170,7 +210,9 @@ this.order = order; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getSkin() */ public String getSkin() @@ -178,7 +220,9 @@ return skin; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#setSkin(java.lang.String) */ public void setSkin(String name) @@ -186,7 +230,9 @@ skin = name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getTitle() */ public String getTitle() @@ -194,7 +240,9 @@ return title; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#setTitle(java.lang.String) */ public void setTitle(String title) @@ -202,15 +250,19 @@ this.title = title; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getShortTitle() */ public String getShortTitle() { - return shortTitle; + return shortTitle; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#setShortTitle(java.lang.String) */ public void setShortTitle(String title) @@ -218,12 +270,16 @@ this.shortTitle = title; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getMenuElements() */ public abstract List getMenuElements(); - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#setMenuElements(java.util.List) */ public void setMenuElements(List elements) @@ -243,7 +299,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) @@ -252,25 +310,24 @@ { if (name != null) { - return name.equals(((BaseMenuDefinitionImpl)o).getName()); + return name.equals(((BaseMenuDefinitionImpl) o).getName()); } else { - return (((BaseMenuDefinitionImpl)o).getName() == null); + return (((BaseMenuDefinitionImpl) o).getName() == null); } } return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#hashCode() */ public int hashCode() { - if (name != null) - { - return name.hashCode(); - } + if (name != null) { return name.hashCode(); } return 0; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuDefinitionMetadata.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuDefinitionMetadata.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuDefinitionMetadata.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,27 +29,30 @@ * @author Randy Watler * @version $Id:$ */ -public abstract class BaseMenuDefinitionMetadata extends BaseMenuDefinitionElement +public abstract class BaseMenuDefinitionMetadata extends + BaseMenuDefinitionElement { + private Collection metadataFields; private PageMetadataImpl pageMetadata; /** * newPageMetadata - * + * * Construct page manager specific metadata implementation. - * - * @param fields mutable fields collection + * + * @param fields + * mutable fields collection * @return page metadata */ public abstract PageMetadataImpl newPageMetadata(Collection fields); /** * getPageMetadata - * + * * Get page manager specific metadata implementation. - * + * * @return page metadata */ public PageMetadataImpl getPageMetadata() @@ -65,7 +68,9 @@ return pageMetadata; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getTitle() * @see org.apache.jetspeed.om.folder.MenuSeparatorDefinition#getTitle() */ @@ -75,7 +80,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getShortTitle() */ public String getShortTitle() @@ -84,7 +91,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuSeparatorDefinition#getText() */ public String getText() @@ -93,7 +102,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getTitle(java.util.Locale) * @see org.apache.jetspeed.om.folder.MenuSeparatorDefinition#getTitle(java.util.Locale) */ @@ -108,7 +119,9 @@ return title; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getShortTitle(java.util.Locale) */ public String getShortTitle(Locale locale) @@ -131,7 +144,9 @@ return shortTitle; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuSeparatorDefinition#getText(java.util.Locale) */ public String getText(Locale locale) @@ -145,7 +160,9 @@ return text; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getMetadata() * @see org.apache.jetspeed.om.folder.MenuSeparatorDefinition#getMetadata() */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuExcludeDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuExcludeDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuExcludeDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,11 +24,15 @@ * @author Randy Watler * @version $Id:$ */ -public abstract class BaseMenuExcludeDefinitionImpl extends BaseMenuDefinitionElement implements MenuExcludeDefinition +public abstract class BaseMenuExcludeDefinitionImpl extends + BaseMenuDefinitionElement implements MenuExcludeDefinition { + private String name; - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuExcludeDefinition#getName() */ public String getName() @@ -36,7 +40,9 @@ return name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuExcludeDefinition#setName(java.lang.String) */ public void setName(String name) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuIncludeDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuIncludeDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuIncludeDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,12 +24,17 @@ * @author Randy Watler * @version $Id:$ */ -public abstract class BaseMenuIncludeDefinitionImpl extends BaseMenuDefinitionElement implements MenuIncludeDefinition +public abstract class BaseMenuIncludeDefinitionImpl extends + BaseMenuDefinitionElement implements MenuIncludeDefinition { + private String name; + private boolean nest; - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuIncludeDefinition#getName() */ public String getName() @@ -37,7 +42,9 @@ return name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuIncludeDefinition#setName(java.lang.String) */ public void setName(String name) @@ -45,15 +52,19 @@ this.name = name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuIncludeDefinition#isNest() */ public boolean isNest() { return nest; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuIncludeDefinition#setNest(boolean) */ public void setNest(boolean nest) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuOptionsDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuOptionsDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuOptionsDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,17 +24,27 @@ * @author Randy Watler * @version $Id:$ */ -public abstract class BaseMenuOptionsDefinitionImpl extends BaseMenuDefinitionElement implements MenuOptionsDefinition +public abstract class BaseMenuOptionsDefinitionImpl extends + BaseMenuDefinitionElement implements MenuOptionsDefinition { + private String options; + private int depth; + private boolean paths; + private boolean regexp; + private String profile; + private String order; + private String skin; - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuOptionsDefinition#getOptions() */ public String getOptions() @@ -42,7 +52,9 @@ return options; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuOptionsDefinition#setOptions(java.lang.String) */ public void setOptions(String options) @@ -50,7 +62,9 @@ this.options = options; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuOptionsDefinition#getDepth() */ public int getDepth() @@ -58,7 +72,9 @@ return depth; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuOptionsDefinition#setDepth(int) */ public void setDepth(int depth) @@ -66,23 +82,29 @@ this.depth = depth; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuOptionsDefinition#isPaths() */ public boolean isPaths() { return paths; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuOptionsDefinition#setPaths(boolean) */ public void setPaths(boolean paths) { this.paths = paths; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuOptionsDefinition#isRegexp() */ public boolean isRegexp() @@ -90,7 +112,9 @@ return regexp; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuOptionsDefinition#setRegexp(boolean) */ public void setRegexp(boolean regexp) @@ -98,7 +122,9 @@ this.regexp = regexp; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuOptionsDefinition#getProfile() */ public String getProfile() @@ -106,7 +132,9 @@ return profile; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuOptionsDefinition#setProfile(java.lang.String) */ public void setProfile(String locatorName) @@ -114,7 +142,9 @@ profile = locatorName; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuOptionsDefinition#getOrder() */ public String getOrder() @@ -122,7 +152,9 @@ return order; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuOptionsDefinition#setOrder(java.lang.String) */ public void setOrder(String order) @@ -130,7 +162,9 @@ this.order = order; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuOptionsDefinition#getSkin() */ public String getSkin() @@ -138,7 +172,9 @@ return skin; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuOptionsDefinition#setSkin(java.lang.String) */ public void setSkin(String name) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuSeparatorDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuSeparatorDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/BaseMenuSeparatorDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,13 +24,19 @@ * @author Randy Watler * @version $Id:$ */ -public abstract class BaseMenuSeparatorDefinitionImpl extends BaseMenuDefinitionMetadata implements MenuSeparatorDefinition +public abstract class BaseMenuSeparatorDefinitionImpl extends + BaseMenuDefinitionMetadata implements MenuSeparatorDefinition { + private String skin; + private String title; + private String text; - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuSeparatorDefinition#getSkin() */ public String getSkin() @@ -38,7 +44,9 @@ return skin; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuSeparatorDefinition#setSkin(java.lang.String) */ public void setSkin(String name) @@ -46,7 +54,9 @@ skin = name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuSeparatorDefinition#getTitle() */ public String getTitle() @@ -54,7 +64,9 @@ return title; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuSeparatorDefinition#setTitle(java.lang.String) */ public void setTitle(String title) @@ -62,7 +74,9 @@ this.title = title; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuSeparatorDefinition#getText() */ public String getText() @@ -70,7 +84,9 @@ return text; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuSeparatorDefinition#setText(java.lang.String) */ public void setText(String text) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -55,37 +55,61 @@ /** * FolderImpl - * + * * @author Randy Watler * @version $Id$ */ public class FolderImpl extends NodeImpl implements Folder { + private String defaultPage; + private String skin; + private String defaultLayoutDecorator; + private String defaultPortletDecorator; + private List orders; + private List menus; private PageManager pageManager; + private List folders; + private boolean foldersCached; + private List pages; + private boolean pagesCached; + private List links; + private boolean linksCached; + private PageSecurityImpl pageSecurity; + private boolean pageSecurityCached; + private List all; + private boolean allCached; + private FolderOrderList documentOrder; + private boolean documentOrderComparatorValid; + private Comparator documentOrderComparator; + private NodeSet foldersNodeSet; + private NodeSet pagesNodeSet; + private NodeSet linksNodeSet; + private NodeSet allNodeSet; + private FolderMenuDefinitionList menuDefinitions; public FolderImpl() @@ -95,9 +119,9 @@ /** * accessFolderOrders - * + * * Access mutable persistent collection member for List wrappers. - * + * * @return persistent collection */ List accessFolderOrders() @@ -112,9 +136,9 @@ /** * accessMenus - * + * * Access mutable persistent collection member for List wrappers. - * + * * @return persistent collection */ List accessMenus() @@ -129,10 +153,11 @@ /** * setPageManager - * + * * Infuses PageManager for use by this folder instance. - * - * @param pageManager page manager that manages this folder instance + * + * @param pageManager + * page manager that manages this folder instance */ public void setPageManager(PageManager pageManager) { @@ -141,9 +166,9 @@ /** * accessFolders - * + * * Access folders transient cache collection for use by PageManager. - * + * * @return folders collection */ public List accessFolders() @@ -158,10 +183,11 @@ /** * resetFolders - * + * * Reset folders transient caches for use by PageManager. - * - * @param cached set cached state for folders + * + * @param cached + * set cached state for folders */ public void resetFolders(boolean cached) { @@ -183,9 +209,9 @@ /** * accessPages - * + * * Access pages transient cache collection for use by PageManager. - * + * * @return pages collection */ public List accessPages() @@ -200,10 +226,11 @@ /** * resetPages - * + * * Reset pages transient caches for use by PageManager. - * - * @param cached set cached state for pages + * + * @param cached + * set cached state for pages */ public void resetPages(boolean cached) { @@ -225,9 +252,9 @@ /** * accessLinks - * + * * Access links transient cache collection for use by PageManager. - * + * * @return links collection */ public List accessLinks() @@ -242,10 +269,11 @@ /** * resetLinks - * + * * Reset links transient caches for use by PageManager. - * - * @param cached set cached state for links + * + * @param cached + * set cached state for links */ public void resetLinks(boolean cached) { @@ -267,9 +295,9 @@ /** * accessPageSecurity - * + * * Access pageSecurity cached instance for use by PageManager. - * + * * @return pageSecurity instance */ public PageSecurityImpl accessPageSecurity() @@ -279,13 +307,16 @@ /** * resetPageSecurity - * + * * Reset pageSecurity transient cache instance for use by PageManager. - * - * @param newPageSecurty cached page security instance. - * @param cached set cached state for page security + * + * @param newPageSecurty + * cached page security instance. + * @param cached + * set cached state for page security */ - public void resetPageSecurity(PageSecurityImpl newPageSecurity, boolean cached) + public void resetPageSecurity(PageSecurityImpl newPageSecurity, + boolean cached) { // save cached state pageSecurity = newPageSecurity; @@ -301,9 +332,9 @@ /** * accessAll - * + * * Access all transient cache collection for use by PageManager. - * + * * @return all collection */ public List accessAll() @@ -318,10 +349,11 @@ /** * resetAll - * + * * Reset all transient caches for use by PageManager. - * - * @param cached set cached state for all + * + * @param cached + * set cached state for all */ public void resetAll(boolean cached) { @@ -340,12 +372,12 @@ if (cached) { // populate node caches - synchronized(all) + synchronized (all) { Iterator nodeIter = accessAll().iterator(); while (nodeIter.hasNext()) { - Node node = (Node)nodeIter.next(); + Node node = (Node) nodeIter.next(); if (node instanceof PageImpl) { pages.add(node); @@ -360,7 +392,7 @@ } else if (node instanceof PageSecurityImpl) { - pageSecurity = (PageSecurityImpl)node; + pageSecurity = (PageSecurityImpl) node; } } } @@ -379,7 +411,7 @@ /** * createDocumentOrderComparator - * + * * @return document order comparator */ private Comparator createDocumentOrderComparator() @@ -390,55 +422,56 @@ // return null if no document order exists; // (null implies natural ordering by name) final List documentOrder = getDocumentOrder(); - if ((documentOrder == null) || documentOrder.isEmpty()) - { - return null; - } + if ((documentOrder == null) || documentOrder.isEmpty()) { return null; } // create new document order comparator documentOrderComparator = new Comparator() + { + + /* + * (non-Javadoc) + * + * @see java.util.Comparator#compare(java.lang.Object, + * java.lang.Object) + */ + public int compare(Object o1, Object o2) { - /* (non-Javadoc) - * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) - */ - public int compare(Object o1, Object o2) + // Compare node names using document order; + // use indicies as names if found in document + // order to force explicitly ordered items + // ahead of unordered items + String name1 = (String) o1; + int index1 = documentOrder.indexOf(name1); + if (index1 >= 0) { - // Compare node names using document order; - // use indicies as names if found in document - // order to force explicitly ordered items - // ahead of unordered items - String name1 = (String)o1; - int index1 = documentOrder.indexOf(name1); + // use order index as name1 + name1 = String.valueOf(index1); + } + String name2 = (String) o2; + int index2 = documentOrder.indexOf(name2); + if (index2 >= 0) + { + // use order index as name2 + name2 = String.valueOf(index2); if (index1 >= 0) { - // use order index as name1 - name1 = String.valueOf(index1); - } - String name2 = (String)o2; - int index2 = documentOrder.indexOf(name2); - if (index2 >= 0) - { - // use order index as name2 - name2 = String.valueOf(index2); - if (index1 >= 0) + // pad order indicies for numeric string compare + while (name1.length() != name2.length()) { - // pad order indicies for numeric string compare - while (name1.length() != name2.length()) + if (name1.length() < name2.length()) { - if (name1.length() < name2.length()) - { - name1 = "0" + name1; - } - else - { - name2 = "0" + name2; - } + name1 = "0" + name1; } + else + { + name2 = "0" + name2; + } } } - // compare names and/or indicies - return name1.compareTo(name2); } - }; + // compare names and/or indicies + return name1.compareTo(name2); + } + }; } return documentOrderComparator; } @@ -457,17 +490,22 @@ pagesNodeSet = null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.impl.NodeImpl#newPageMetadata(java.util.Collection) */ public PageMetadataImpl newPageMetadata(Collection fields) { - PageMetadataImpl pageMetadata = new PageMetadataImpl(FolderMetadataLocalizedFieldImpl.class); + PageMetadataImpl pageMetadata = new PageMetadataImpl( + FolderMetadataLocalizedFieldImpl.class); pageMetadata.setFields(fields); return pageMetadata; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#getEffectivePageSecurity() */ public PageSecurity getEffectivePageSecurity() @@ -488,24 +526,24 @@ { } } - else if (pageSecurity != null) - { - return pageSecurity; - } + else if (pageSecurity != null) { return pageSecurity; } // delegate to real parent folder implementation - FolderImpl parentFolderImpl = (FolderImpl)ProxyHelper.getRealObject(getParent()); - if (parentFolderImpl != null) - { - return parentFolderImpl.getEffectivePageSecurity(); - } + FolderImpl parentFolderImpl = (FolderImpl) ProxyHelper + .getRealObject(getParent()); + if (parentFolderImpl != null) { return parentFolderImpl + .getEffectivePageSecurity(); } return null; } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#checkPermissions(java.lang.String, int, boolean, boolean) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#checkPermissions(java.lang.String, + * int, boolean, boolean) */ - public void checkPermissions(String path, int mask, boolean checkNodeOnly, boolean checkParentsOnly) throws SecurityException + public void checkPermissions(String path, int mask, boolean checkNodeOnly, + boolean checkParentsOnly) throws SecurityException { // check granted folder permissions unless the check is // to be skipped due to explicity granted access @@ -519,7 +557,8 @@ // all parent permissions in hierarchy if (!checkNodeOnly) { - FolderImpl parentFolderImpl = (FolderImpl)ProxyHelper.getRealObject(getParent()); + FolderImpl parentFolderImpl = (FolderImpl) ProxyHelper + .getRealObject(getParent()); if (parentFolderImpl != null) { parentFolderImpl.checkPermissions(mask, false, false); @@ -527,7 +566,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#getTitle() */ public String getTitle() @@ -542,15 +583,19 @@ return title; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getSkin() */ public String getSkin() { return skin; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#setSkin(java.lang.String) */ public void setSkin(String skinName) @@ -558,7 +603,9 @@ this.skin = skinName; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getEffectiveDefaultDecorator(java.lang.String) */ public String getEffectiveDefaultDecorator(String fragmentType) @@ -568,16 +615,17 @@ if (decorator == null) { // delegate to parent folder - Folder parentFolder = (Folder)ProxyHelper.getRealObject(getParent()); - if (parentFolder != null) - { - return parentFolder.getEffectiveDefaultDecorator(fragmentType); - } + Folder parentFolder = (Folder) ProxyHelper + .getRealObject(getParent()); + if (parentFolder != null) { return parentFolder + .getEffectiveDefaultDecorator(fragmentType); } } return decorator; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getDefaultDecorator(java.lang.String) */ public String getDefaultDecorator(String fragmentType) @@ -585,19 +633,15 @@ // retrieve supported decorator types if (fragmentType != null) { - if (fragmentType.equals(Fragment.LAYOUT)) - { - return defaultLayoutDecorator; - } - if (fragmentType.equals(Fragment.PORTLET)) - { - return defaultPortletDecorator; - } + if (fragmentType.equals(Fragment.LAYOUT)) { return defaultLayoutDecorator; } + if (fragmentType.equals(Fragment.PORTLET)) { return defaultPortletDecorator; } } return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getDefaultDecorator(java.lang.String,java.lang.String) */ public void setDefaultDecorator(String decoratorName, String fragmentType) @@ -607,16 +651,18 @@ { if (fragmentType.equals(Fragment.LAYOUT)) { - defaultLayoutDecorator = decoratorName; + defaultLayoutDecorator = decoratorName; } if (fragmentType.equals(Fragment.PORTLET)) { - defaultPortletDecorator = decoratorName; + defaultPortletDecorator = decoratorName; } } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getDocumentOrder() */ public List getDocumentOrder() @@ -630,8 +676,10 @@ } return documentOrder; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#setDocumentOrder(java.util.List) */ public void setDocumentOrder(List docNames) @@ -651,15 +699,19 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getDefaultPage() */ public String getDefaultPage() { return defaultPage; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#setDefaultPage(java.lang.String) */ public void setDefaultPage(String defaultPage) @@ -667,7 +719,9 @@ this.defaultPage = defaultPage; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getFolders() */ public NodeSet getFolders() throws DocumentException @@ -683,11 +737,14 @@ // return nodes with view access return filterNodeSetByAccess(getFoldersNodeSet()); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getFolder(java.lang.String) */ - public Folder getFolder(String name) throws FolderNotFoundException, DocumentException + public Folder getFolder(String name) throws FolderNotFoundException, + DocumentException { // get folder instance if folders collection not available if (!foldersCached) @@ -698,19 +755,19 @@ } // select folder by name from cached folders collection - Folder folder = (Folder)getFoldersNodeSet().get(name); - if (folder == null) - { - throw new FolderNotFoundException("Folder not found: " + name); - } + Folder folder = (Folder) getFoldersNodeSet().get(name); + if (folder == null) { throw new FolderNotFoundException( + "Folder not found: " + name); } // check for view access on folder folder.checkAccess(JetspeedActions.VIEW); return folder; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getPages() */ public NodeSet getPages() throws NodeException @@ -726,11 +783,14 @@ // return nodes with view access return filterNodeSetByAccess(getPagesNodeSet()); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getPage(java.lang.String) */ - public Page getPage(String name) throws PageNotFoundException, NodeException + public Page getPage(String name) throws PageNotFoundException, + NodeException { // get page instance if pages collection not available if (!pagesCached) @@ -741,19 +801,19 @@ } // select page by name from cached pages collection - Page page = (Page)getPagesNodeSet().get(name); - if (page == null) - { - throw new PageNotFoundException("Page not found: " + name); - } + Page page = (Page) getPagesNodeSet().get(name); + if (page == null) { throw new PageNotFoundException("Page not found: " + + name); } // check for view access on page page.checkAccess(JetspeedActions.VIEW); return page; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getLinks() */ public NodeSet getLinks() throws NodeException @@ -769,11 +829,14 @@ // return nodes with view access return filterNodeSetByAccess(getLinksNodeSet()); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getLink(java.lang.String) */ - public Link getLink(String name) throws DocumentNotFoundException, NodeException + public Link getLink(String name) throws DocumentNotFoundException, + NodeException { // get link instance if links collection not available if (!linksCached) @@ -784,22 +847,23 @@ } // select link by name from cached links collection - Link link = (Link)getLinksNodeSet().get(name); - if (link == null) - { - throw new DocumentNotFoundException("Link not found: " + name); - } + Link link = (Link) getLinksNodeSet().get(name); + if (link == null) { throw new DocumentNotFoundException( + "Link not found: " + name); } // check for view access on link link.checkAccess(JetspeedActions.VIEW); return link; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getPageSecurity() */ - public PageSecurity getPageSecurity() throws DocumentNotFoundException, NodeException + public PageSecurity getPageSecurity() throws DocumentNotFoundException, + NodeException { // get page security instance if (!pageSecurityCached) @@ -808,18 +872,18 @@ // instance for this folder return getPageManager().getPageSecurity(this); } - if (pageSecurity == null) - { - throw new DocumentNotFoundException("Page security document not found"); - } + if (pageSecurity == null) { throw new DocumentNotFoundException( + "Page security document not found"); } // check for view access on document pageSecurity.checkAccess(JetspeedActions.VIEW); return pageSecurity; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getAll() */ public NodeSet getAll() throws DocumentException @@ -835,8 +899,10 @@ // return nodes with view access return filterNodeSetByAccess(getAllNodeSet()); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getMenuDefinitions() */ public List getMenuDefinitions() @@ -850,8 +916,10 @@ } return menuDefinitions; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#newMenuDefinition() */ public MenuDefinition newMenuDefinition() @@ -859,7 +927,9 @@ return new FolderMenuDefinitionImpl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#newMenuExcludeDefinition() */ public MenuExcludeDefinition newMenuExcludeDefinition() @@ -867,7 +937,9 @@ return new FolderMenuExcludeDefinitionImpl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#newMenuIncludeDefinition() */ public MenuIncludeDefinition newMenuIncludeDefinition() @@ -875,7 +947,9 @@ return new FolderMenuIncludeDefinitionImpl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#newMenuOptionsDefinition() */ public MenuOptionsDefinition newMenuOptionsDefinition() @@ -883,7 +957,9 @@ return new FolderMenuOptionsDefinitionImpl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#newMenuSeparatorDefinition() */ public MenuSeparatorDefinition newMenuSeparatorDefinition() @@ -891,7 +967,9 @@ return new FolderMenuSeparatorDefinitionImpl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#setMenuDefinitions(java.util.List) */ public void setMenuDefinitions(List definitions) @@ -911,7 +989,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#isReserved() */ public boolean isReserved() @@ -919,8 +999,10 @@ // folders are always concrete in this implementation return false; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getReservedType() */ public int getReservedType() @@ -929,7 +1011,9 @@ return RESERVED_FOLDER_NONE; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getType() */ public String getType() @@ -939,9 +1023,9 @@ /** * getFoldersNodeSet - * + * * Latently create and access folders node set. - * + * * @return folders node set */ private NodeSet getFoldersNodeSet() @@ -950,7 +1034,8 @@ { if ((folders != null) && !folders.isEmpty()) { - foldersNodeSet = new NodeSetImpl(folders, createDocumentOrderComparator()); + foldersNodeSet = new NodeSetImpl(folders, + createDocumentOrderComparator()); } else { @@ -959,12 +1044,12 @@ } return foldersNodeSet; } - + /** * getPagesNodeSet - * + * * Latently create and access pages node set. - * + * * @return folders node set */ private NodeSet getPagesNodeSet() throws NodeException @@ -973,7 +1058,8 @@ { if ((pages != null) && !pages.isEmpty()) { - pagesNodeSet = new NodeSetImpl(pages, createDocumentOrderComparator()); + pagesNodeSet = new NodeSetImpl(pages, + createDocumentOrderComparator()); } else { @@ -982,12 +1068,12 @@ } return pagesNodeSet; } - + /** * getLinksNodeSet - * + * * Latently create and access links node set. - * + * * @return folders node set */ private NodeSet getLinksNodeSet() throws NodeException @@ -996,7 +1082,8 @@ { if ((links != null) && !links.isEmpty()) { - linksNodeSet = new NodeSetImpl(links, createDocumentOrderComparator()); + linksNodeSet = new NodeSetImpl(links, + createDocumentOrderComparator()); } else { @@ -1005,12 +1092,12 @@ } return linksNodeSet; } - + /** * getAllNodeSet - * + * * Latently create and access all nodes node set. - * + * * @return all nodes node set */ private NodeSet getAllNodeSet() @@ -1020,11 +1107,12 @@ if ((all != null) && !all.isEmpty()) { List allCopy = new java.util.ArrayList(); - synchronized(all) + synchronized (all) { - allCopy.addAll(all); + allCopy.addAll(all); } - allNodeSet = new NodeSetImpl(allCopy, createDocumentOrderComparator()); + allNodeSet = new NodeSetImpl(allCopy, + createDocumentOrderComparator()); } else { @@ -1036,10 +1124,11 @@ /** * filterNodeSetByAccess - * + * * Filter node set elements for view access. - * - * @param nodes node set containing nodes to check + * + * @param nodes + * node set containing nodes to check * @return checked subset of nodes */ static NodeSet filterNodeSetByAccess(NodeSet nodes) @@ -1051,7 +1140,7 @@ Iterator checkAccessIter = nodes.iterator(); while (checkAccessIter.hasNext()) { - Node node = (Node)checkAccessIter.next(); + Node node = (Node) checkAccessIter.next(); try { // check access @@ -1075,7 +1164,7 @@ Iterator copyIter = nodes.iterator(); while (copyIter.hasNext()) { - Node copyNode = (Node)copyIter.next(); + Node copyNode = (Node) copyIter.next(); if (copyNode != node) { filteredNodes.add(copyNode); @@ -1090,20 +1179,18 @@ } // return filteredNodes nodes if generated - if (filteredNodes != null) - { - return filteredNodes; - } + if (filteredNodes != null) { return filteredNodes; } } return nodes; } - + public PageManager getPageManager() { - if(pageManager == null) + if (pageManager == null) { - pageManager = (PageManager)Jetspeed.getComponentManager().getComponent("PageManager"); - } + pageManager = (PageManager) Jetspeed.getComponentManager() + .getComponent("PageManager"); + } return pageManager; - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionElement.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionElement.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionElement.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,14 +24,19 @@ */ public interface FolderMenuDefinitionElement { + // new interface defined only to facilitate OJB table/class mapping - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.impl.BaseMenuDefinitionElement#getElementOrder() */ int getElementOrder(); - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.impl.BaseMenuDefinitionElement#setElementOrder(int) */ void setElementOrder(int order); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionElementList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionElementList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionElementList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,12 +20,13 @@ /** * FolderMenuDefinitionElementList - * + * * @author Randy Watler * @version $Id$ */ class FolderMenuDefinitionElementList extends AbstractList { + private FolderMenuDefinitionImpl menuDefinition; FolderMenuDefinitionElementList(FolderMenuDefinitionImpl menuDefinition) @@ -36,41 +37,43 @@ /** * validateMenuElementForAdd - * + * * Validates element to be added to this list. - * - * @param menuElement element to add + * + * @param menuElement + * element to add * @return list element to add */ - private FolderMenuDefinitionElement validateMenuElementForAdd(FolderMenuDefinitionElement menuElement) + private FolderMenuDefinitionElement validateMenuElementForAdd( + FolderMenuDefinitionElement menuElement) { // validate element instance class - if (menuElement == null) - { - throw new NullPointerException("Unable to add null to list."); - } + if (menuElement == null) { throw new NullPointerException( + "Unable to add null to list."); } return menuElement; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) { // implement for modifiable AbstractList: // validate index - if ((index < 0) || (index > menuDefinition.accessElements().size())) - { - throw new IndexOutOfBoundsException("Unable to add to list at index: " + index); - } + if ((index < 0) || (index > menuDefinition.accessElements().size())) { throw new IndexOutOfBoundsException( + "Unable to add to list at index: " + index); } // verify element - FolderMenuDefinitionElement menuElement = validateMenuElementForAdd((FolderMenuDefinitionElement)element); + FolderMenuDefinitionElement menuElement = validateMenuElementForAdd((FolderMenuDefinitionElement) element); // add to underlying ordered list menuDefinition.accessElements().add(index, menuElement); // set element order in added element if (index > 0) { - menuElement.setElementOrder(((FolderMenuDefinitionElement)menuDefinition.accessElements().get(index-1)).getElementOrder() + 1); + menuElement + .setElementOrder(((FolderMenuDefinitionElement) menuDefinition + .accessElements().get(index - 1)).getElementOrder() + 1); } else { @@ -79,11 +82,14 @@ // maintain element order in subsequent elements for (int i = index, limit = menuDefinition.accessElements().size() - 1; (i < limit); i++) { - FolderMenuDefinitionElement nextMenuElement = (FolderMenuDefinitionElement)menuDefinition.accessElements().get(i + 1); - if (nextMenuElement.getElementOrder() <= menuElement.getElementOrder()) + FolderMenuDefinitionElement nextMenuElement = (FolderMenuDefinitionElement) menuDefinition + .accessElements().get(i + 1); + if (nextMenuElement.getElementOrder() <= menuElement + .getElementOrder()) { // adjust element order for next element - nextMenuElement.setElementOrder(menuElement.getElementOrder() + 1); + nextMenuElement + .setElementOrder(menuElement.getElementOrder() + 1); menuElement = nextMenuElement; } else @@ -94,7 +100,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) @@ -103,7 +111,9 @@ return menuDefinition.accessElements().get(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) @@ -112,23 +122,28 @@ return menuDefinition.accessElements().remove(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) { // implement for modifiable AbstractList: // verify element - FolderMenuDefinitionElement newMenuElement = validateMenuElementForAdd((FolderMenuDefinitionElement)element); + FolderMenuDefinitionElement newMenuElement = validateMenuElementForAdd((FolderMenuDefinitionElement) element); // set in underlying ordered list - FolderMenuDefinitionElement menuElement = (FolderMenuDefinitionElement)menuDefinition.accessElements().set(index, newMenuElement); + FolderMenuDefinitionElement menuElement = (FolderMenuDefinitionElement) menuDefinition + .accessElements().set(index, newMenuElement); // set element order in new element newMenuElement.setElementOrder(menuElement.getElementOrder()); // return element return menuElement; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,23 +28,30 @@ * @author Randy Watler * @version $Id:$ */ -public class FolderMenuDefinitionImpl extends BaseMenuDefinitionImpl implements MenuDefinition, FolderMenuDefinitionElement +public class FolderMenuDefinitionImpl extends BaseMenuDefinitionImpl implements + MenuDefinition, FolderMenuDefinitionElement { + // new class defined only to facilitate OJB table/class mapping private FolderMenuDefinitionElementList menuElements; - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.impl.BaseMenuDefinitionMetadata#newPageMetadata() */ public PageMetadataImpl newPageMetadata(Collection fields) { - PageMetadataImpl pageMetadata = new PageMetadataImpl(FolderMenuMetadataLocalizedFieldImpl.class); + PageMetadataImpl pageMetadata = new PageMetadataImpl( + FolderMenuMetadataLocalizedFieldImpl.class); pageMetadata.setFields(fields); return pageMetadata; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getMenuElements() */ public List getMenuElements() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuDefinitionList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,12 +23,13 @@ /** * FolderMenuDefinitionList - * + * * @author Randy Watler * @version $Id$ */ class FolderMenuDefinitionList extends AbstractList { + private FolderImpl folder; private List removedMenuDefinitions; @@ -41,24 +42,23 @@ /** * validateDefinitionForAdd - * + * * Validates menu definition to be added to this list. - * - * @param definition menu definition to add + * + * @param definition + * menu definition to add * @return list element to add */ - private FolderMenuDefinitionImpl validateDefinitionForAdd(FolderMenuDefinitionImpl definition) + private FolderMenuDefinitionImpl validateDefinitionForAdd( + FolderMenuDefinitionImpl definition) { // only non-null definitions supported - if (definition == null) - { - throw new NullPointerException("Unable to add null to list."); - } + if (definition == null) { throw new NullPointerException( + "Unable to add null to list."); } // make sure element is unique - if (folder.accessMenus().contains(definition)) - { - throw new IllegalArgumentException("Unable to add duplicate entry to list: " + (definition).getName()); - } + if (folder.accessMenus().contains(definition)) { throw new IllegalArgumentException( + "Unable to add duplicate entry to list: " + + (definition).getName()); } // retrieve from removed list to reuse // previously removed element copying // menu definition data @@ -69,7 +69,8 @@ { // reuse menu definition with matching name FolderMenuDefinitionImpl addDefinition = definition; - definition = (FolderMenuDefinitionImpl)removedMenuDefinitions.remove(removedIndex); + definition = (FolderMenuDefinitionImpl) removedMenuDefinitions + .remove(removedIndex); // TODO: move this logic to copy methods on implementations // copy menu definition members definition.setOptions(addDefinition.getOptions()); @@ -91,7 +92,8 @@ // metadata members are required to be unique // and a removal list is not maintained for the // metadata fields collections yet - definition.getMetadata().copyFields(addDefinition.getMetadata().getFields()); + definition.getMetadata().copyFields( + addDefinition.getMetadata().getFields()); } } return definition; @@ -99,7 +101,7 @@ /** * getRemovedMenuDefinitions - * + * * @return removed menu definitions tracking collection */ private List getRemovedMenuDefinitions() @@ -111,24 +113,26 @@ return removedMenuDefinitions; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) { // implement for modifiable AbstractList: // validate index - if ((index < 0) || (index > folder.accessMenus().size())) - { - throw new IndexOutOfBoundsException("Unable to add to list at index: " + index); - } + if ((index < 0) || (index > folder.accessMenus().size())) { throw new IndexOutOfBoundsException( + "Unable to add to list at index: " + index); } // verify menu definition - FolderMenuDefinitionImpl definition = validateDefinitionForAdd((FolderMenuDefinitionImpl)element); + FolderMenuDefinitionImpl definition = validateDefinitionForAdd((FolderMenuDefinitionImpl) element); // add to underlying ordered list folder.accessMenus().add(index, definition); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) @@ -137,14 +141,17 @@ return folder.accessMenus().get(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) { // implement for modifiable AbstractList: - // save removed element - FolderMenuDefinitionImpl removed = (FolderMenuDefinitionImpl)folder.accessMenus().remove(index); + // save removed element + FolderMenuDefinitionImpl removed = (FolderMenuDefinitionImpl) folder + .accessMenus().remove(index); if (removed != null) { getRemovedMenuDefinitions().add(removed); @@ -152,23 +159,28 @@ return removed; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) { // implement for modifiable AbstractList: // verify menu definition - FolderMenuDefinitionImpl newDefinition = validateDefinitionForAdd((FolderMenuDefinitionImpl)element); + FolderMenuDefinitionImpl newDefinition = validateDefinitionForAdd((FolderMenuDefinitionImpl) element); // set in underlying ordered list - FolderMenuDefinitionImpl definition = (FolderMenuDefinitionImpl)folder.accessMenus().set(index, newDefinition); + FolderMenuDefinitionImpl definition = (FolderMenuDefinitionImpl) folder + .accessMenus().set(index, newDefinition); // save replaced element getRemovedMenuDefinitions().add(definition); // return menu definition return definition; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuExcludeDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuExcludeDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuExcludeDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,7 +24,9 @@ * @author Randy Watler * @version $Id:$ */ -public class FolderMenuExcludeDefinitionImpl extends BaseMenuExcludeDefinitionImpl implements MenuExcludeDefinition, FolderMenuDefinitionElement +public class FolderMenuExcludeDefinitionImpl extends + BaseMenuExcludeDefinitionImpl implements MenuExcludeDefinition, + FolderMenuDefinitionElement { // new class defined only to facilitate OJB table/class mapping } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuIncludeDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuIncludeDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuIncludeDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,7 +24,9 @@ * @author Randy Watler * @version $Id:$ */ -public class FolderMenuIncludeDefinitionImpl extends BaseMenuIncludeDefinitionImpl implements MenuIncludeDefinition, FolderMenuDefinitionElement +public class FolderMenuIncludeDefinitionImpl extends + BaseMenuIncludeDefinitionImpl implements MenuIncludeDefinition, + FolderMenuDefinitionElement { // new class defined only to facilitate OJB table/class mapping } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuMetadataLocalizedFieldImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuMetadataLocalizedFieldImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuMetadataLocalizedFieldImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,11 +20,12 @@ /** * FolderMenuMetadataLocalizedFieldImpl - * + * * @author Randy Watler * @version $Id$ */ -public class FolderMenuMetadataLocalizedFieldImpl extends PageLocalizedFieldImpl +public class FolderMenuMetadataLocalizedFieldImpl extends + PageLocalizedFieldImpl { // new class defined only to facilitate OJB table/class mapping } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuOptionsDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuOptionsDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuOptionsDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,7 +24,9 @@ * @author Randy Watler * @version $Id:$ */ -public class FolderMenuOptionsDefinitionImpl extends BaseMenuOptionsDefinitionImpl implements MenuOptionsDefinition, FolderMenuDefinitionElement +public class FolderMenuOptionsDefinitionImpl extends + BaseMenuOptionsDefinitionImpl implements MenuOptionsDefinition, + FolderMenuDefinitionElement { // new class defined only to facilitate OJB table/class mapping } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuSeparatorDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuSeparatorDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMenuSeparatorDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,16 +27,22 @@ * @author Randy Watler * @version $Id:$ */ -public class FolderMenuSeparatorDefinitionImpl extends BaseMenuSeparatorDefinitionImpl implements MenuSeparatorDefinition, FolderMenuDefinitionElement +public class FolderMenuSeparatorDefinitionImpl extends + BaseMenuSeparatorDefinitionImpl implements MenuSeparatorDefinition, + FolderMenuDefinitionElement { + // new class defined only to facilitate OJB table/class mapping - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.impl.BaseMenuDefinitionMetadata#newPageMetadata() */ public PageMetadataImpl newPageMetadata(Collection fields) { - PageMetadataImpl pageMetadata = new PageMetadataImpl(FolderMenuMetadataLocalizedFieldImpl.class); + PageMetadataImpl pageMetadata = new PageMetadataImpl( + FolderMenuMetadataLocalizedFieldImpl.class); pageMetadata.setFields(fields); return pageMetadata; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMetadataLocalizedFieldImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMetadataLocalizedFieldImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderMetadataLocalizedFieldImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,7 +20,7 @@ /** * FolderMetadataLocalizedFieldImpl - * + * * @author Randy Watler * @version $Id$ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderOrder.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderOrder.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderOrder.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,19 +18,22 @@ /** * FolderOrder - * + * * @author Randy Watler * @version $Id$ */ public class FolderOrder { + private int id; + private int sortOrder; + private String name; /** * getSortOrder - * + * * @return sort order */ public int getSortOrder() @@ -40,8 +43,9 @@ /** * setSortOrder - * - * @param order sort order + * + * @param order + * sort order */ public void setSortOrder(int order) { @@ -50,7 +54,7 @@ /** * getName - * + * * @return folder/page/link name */ public String getName() @@ -60,15 +64,18 @@ /** * setName - * - * @param name folder/page/link name + * + * @param name + * folder/page/link name */ public void setName(String name) { this.name = name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) @@ -77,25 +84,24 @@ { if (name != null) { - return name.equals(((FolderOrder)o).getName()); + return name.equals(((FolderOrder) o).getName()); } else { - return (((FolderOrder)o).getName() == null); + return (((FolderOrder) o).getName() == null); } } return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#hashCode() */ public int hashCode() { - if (name != null) - { - return name.hashCode(); - } + if (name != null) { return name.hashCode(); } return 0; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderOrderList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderOrderList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderOrderList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,12 +23,13 @@ /** * FolderOrderList - * + * * @author Randy Watler * @version $Id$ */ class FolderOrderList extends AbstractList { + private FolderImpl folder; private List removedFolderOrders; @@ -41,28 +42,25 @@ /** * wrapNameStringForAdd - * - * Wraps and validates folder order name string - * to be added to this list. - * - * @param name folder order name string to add + * + * Wraps and validates folder order name string to be added to this list. + * + * @param name + * folder order name string to add * @return list element to add */ private FolderOrder wrapNameStringForAdd(String name) { // only non-null names supported - if (name == null) - { - throw new NullPointerException("Unable to add null to list."); - } + if (name == null) { throw new NullPointerException( + "Unable to add null to list."); } // wrap folder order name string FolderOrder folderOrder = new FolderOrder(); folderOrder.setName(name); // make sure element is unique - if (folder.accessFolderOrders().contains(folderOrder)) - { - throw new IllegalArgumentException("Unable to add duplicate entry to list: " + folderOrder.getName()); - } + if (folder.accessFolderOrders().contains(folderOrder)) { throw new IllegalArgumentException( + "Unable to add duplicate entry to list: " + + folderOrder.getName()); } // retrieve from removed list to reuse // previously removed element if (removedFolderOrders != null) @@ -70,7 +68,8 @@ int removedIndex = removedFolderOrders.indexOf(folderOrder); if (removedIndex >= 0) { - folderOrder = (FolderOrder)removedFolderOrders.remove(removedIndex); + folderOrder = (FolderOrder) removedFolderOrders + .remove(removedIndex); } } return folderOrder; @@ -78,7 +77,7 @@ /** * getRemovedFolderOrders - * + * * @return removed folder orders tracking collection */ private List getRemovedFolderOrders() @@ -90,25 +89,26 @@ return removedFolderOrders; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) { // implement for modifiable AbstractList: // validate index - if ((index < 0) || (index > folder.accessFolderOrders().size())) - { - throw new IndexOutOfBoundsException("Unable to add to list at index: " + index); - } + if ((index < 0) || (index > folder.accessFolderOrders().size())) { throw new IndexOutOfBoundsException( + "Unable to add to list at index: " + index); } // wrap and verify folder order name string - FolderOrder folderOrder = wrapNameStringForAdd((String)element); + FolderOrder folderOrder = wrapNameStringForAdd((String) element); // add to underlying ordered list folder.accessFolderOrders().add(index, folderOrder); // set sort order in added element if (index > 0) { - folderOrder.setSortOrder(((FolderOrder)folder.accessFolderOrders().get(index-1)).getSortOrder() + 1); + folderOrder.setSortOrder(((FolderOrder) folder.accessFolderOrders() + .get(index - 1)).getSortOrder() + 1); } else { @@ -117,7 +117,8 @@ // maintain sort order in subsequent elements for (int i = index, limit = folder.accessFolderOrders().size() - 1; (i < limit); i++) { - FolderOrder nextFolderOrder = (FolderOrder)folder.accessFolderOrders().get(i + 1); + FolderOrder nextFolderOrder = (FolderOrder) folder + .accessFolderOrders().get(i + 1); if (nextFolderOrder.getSortOrder() <= folderOrder.getSortOrder()) { // adjust sort order for next element @@ -134,26 +135,31 @@ folder.clearDocumentOrderComparator(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) { // implement for modifiable AbstractList: // unwrap folder order name string - return ((FolderOrder)folder.accessFolderOrders().get(index)).getName(); + return ((FolderOrder) folder.accessFolderOrders().get(index)).getName(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) { // implement for modifiable AbstractList - FolderOrder removed = (FolderOrder)folder.accessFolderOrders().remove(index); + FolderOrder removed = (FolderOrder) folder.accessFolderOrders().remove( + index); if (removed != null) { - // save removed element + // save removed element getRemovedFolderOrders().add(removed); // clear all cached folder ordering folder.clearDocumentOrderComparator(); @@ -161,16 +167,19 @@ return removed; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) { // implement for modifiable AbstractList: // wrap and verify folder order name string - FolderOrder newFolderOrder = wrapNameStringForAdd((String)element); + FolderOrder newFolderOrder = wrapNameStringForAdd((String) element); // set in underlying ordered list - FolderOrder folderOrder = (FolderOrder)folder.accessFolderOrders().set(index, newFolderOrder); + FolderOrder folderOrder = (FolderOrder) folder.accessFolderOrders() + .set(index, newFolderOrder); // set sort order in new element newFolderOrder.setSortOrder(folderOrder.getSortOrder()); // save replaced element @@ -181,7 +190,9 @@ return folderOrder.getName(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderSecurityConstraintImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderSecurityConstraintImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderSecurityConstraintImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,7 +20,7 @@ /** * FolderSecurityConstraintImpl - * + * * @author Randy Watler * @version $Id$ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderSecurityConstraintsImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderSecurityConstraintsImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderSecurityConstraintsImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,13 +20,16 @@ /** * FolderSecurityConstraintsImpl - * + * * @author Randy Watler * @version $Id$ */ public class FolderSecurityConstraintsImpl extends SecurityConstraintsImpl { - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.SecurityConstraintsImpl#getSecurityConstraintClass() */ public Class getSecurityConstraintClass() @@ -34,7 +37,9 @@ return FolderSecurityConstraintImpl.class; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.SecurityConstraintsImpl#getSecurityConstraintsRefClass() */ public Class getSecurityConstraintsRefClass() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderSecurityConstraintsRef.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderSecurityConstraintsRef.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/impl/FolderSecurityConstraintsRef.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,7 +20,7 @@ /** * FolderSecurityConstraintsRef - * + * * @author Randy Watler * @version $Id$ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/FolderImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/FolderImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/FolderImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -63,16 +63,19 @@ */ public class FolderImpl extends AbstractNode implements Folder, Reset { - + private NodeSet allNodes; + private FolderMetaDataImpl metadata; + private FolderHandler folderHandler; + private int reservedType = RESERVED_FOLDER_NONE; - + private static final Log log = LogFactory.getLog(FolderImpl.class); - public FolderImpl( String path, FolderMetaDataImpl metadata, DocumentHandlerFactory handlerFactory, - FolderHandler folderHandler ) + public FolderImpl(String path, FolderMetaDataImpl metadata, + DocumentHandlerFactory handlerFactory, FolderHandler folderHandler) { this.metadata = metadata; this.metadata.setParent(this); @@ -84,7 +87,8 @@ setConstraintsEnabled(handlerFactory.getConstraintsEnabled()); } - public FolderImpl( String path, DocumentHandlerFactory handlerFactory, FolderHandler folderHandler ) + public FolderImpl(String path, DocumentHandlerFactory handlerFactory, + FolderHandler folderHandler) { this.metadata = new FolderMetaDataImpl(); this.metadata.setParent(this); @@ -103,7 +107,9 @@ setReservedType(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getSkin() */ public String getSkin() @@ -111,15 +117,19 @@ return metadata.getSkin(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#setSkin(java.lang.String) */ - public void setSkin( String skinName ) + public void setSkin(String skinName) { metadata.setSkin(skinName); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getEffectiveDefaultDecorator(java.lang.String) */ public String getEffectiveDefaultDecorator(String fragmentType) @@ -129,40 +139,47 @@ if (decorator == null) { // delegate to parent folder - Folder parentFolder = (Folder)getParent(); - if (parentFolder != null) - { - return parentFolder.getEffectiveDefaultDecorator(fragmentType); - } + Folder parentFolder = (Folder) getParent(); + if (parentFolder != null) { return parentFolder + .getEffectiveDefaultDecorator(fragmentType); } } return decorator; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getDefaultDecorator(java.lang.String) */ - public String getDefaultDecorator( String fragmentType ) + public String getDefaultDecorator(String fragmentType) { return metadata.getDefaultDecorator(fragmentType); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.folder.Folder#setDefaultDecorator(java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.folder.Folder#setDefaultDecorator(java.lang.String, + * java.lang.String) */ - public void setDefaultDecorator( String decoratorName, String fragmentType ) + public void setDefaultDecorator(String decoratorName, String fragmentType) { metadata.setDefaultDecorator(decoratorName, fragmentType); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getDocumentOrder() */ public List getDocumentOrder() { return metadata.getDocumentOrder(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#setDocumentOrder(java.util.List) */ public void setDocumentOrder(List docIndexes) @@ -170,20 +187,22 @@ metadata.setDocumentOrder(docIndexes); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Folder#getDefaultPage() */ public String getDefaultPage() { return metadata.getDefaultPage(); } - + /* * (non-Javadoc) * * @see org.apache.jetspeed.om.folder.Folder#setDefaultPage() */ - public void setDefaultPage( String defaultPage ) + public void setDefaultPage(String defaultPage) { metadata.setDefaultPage(defaultPage); } @@ -193,7 +212,8 @@ * getFolders *

        * - * @param checkAccess flag + * @param checkAccess + * flag * @return folders node set * @throws DocumentException */ @@ -227,19 +247,19 @@ *

        * * @param name - * @param checkAccess flag + * @param checkAccess + * flag * @return folder * @throws FolderNotFoundException * @throws DocumentException */ - public Folder getFolder(String name, boolean checkAccess) throws FolderNotFoundException, DocumentException + public Folder getFolder(String name, boolean checkAccess) + throws FolderNotFoundException, DocumentException { // get folder Folder folder = (Folder) getAllNodes().subset(FOLDER_TYPE).get(name); - if (folder == null) - { - throw new FolderNotFoundException("Jetspeed PSML folder not found: " + name); - } + if (folder == null) { throw new FolderNotFoundException( + "Jetspeed PSML folder not found: " + name); } // check access if (checkAccess) @@ -254,7 +274,8 @@ * * @see org.apache.jetspeed.om.folder.Folder#getFolder(java.lang.String) */ - public Folder getFolder(String name) throws FolderNotFoundException, DocumentException + public Folder getFolder(String name) throws FolderNotFoundException, + DocumentException { // by default enable access checks return getFolder(name, true); @@ -265,7 +286,8 @@ * getPages *

        * - * @param checkAccess flag + * @param checkAccess + * flag * @return pages node set * @throws NodeException */ @@ -299,19 +321,19 @@ *

        * * @param name - * @param checkAccess flag + * @param checkAccess + * flag * @return page * @throws PageNotFoundException * @throws NodeException */ - public Page getPage(String name, boolean checkAccess) throws PageNotFoundException, NodeException + public Page getPage(String name, boolean checkAccess) + throws PageNotFoundException, NodeException { // get page Page page = (Page) getAllNodes().subset(Page.DOCUMENT_TYPE).get(name); - if (page == null) - { - throw new PageNotFoundException("Jetspeed PSML page not found: " + name); - } + if (page == null) { throw new PageNotFoundException( + "Jetspeed PSML page not found: " + name); } // check access if (checkAccess) @@ -326,7 +348,8 @@ * * @see org.apache.jetspeed.om.folder.Folder#getPage(java.lang.String) */ - public Page getPage(String name) throws PageNotFoundException, NodeException + public Page getPage(String name) throws PageNotFoundException, + NodeException { // by default enable access checks return getPage(name, true); @@ -337,7 +360,8 @@ * getLinks *

        * - * @param checkAccess flag + * @param checkAccess + * flag * @return links node set * @throws NodeException */ @@ -371,19 +395,19 @@ *

        * * @param name - * @param checkAccess flag + * @param checkAccess + * flag * @return link * @throws DocumentNotFoundException * @throws NodeException */ - public Link getLink(String name, boolean checkAccess) throws DocumentNotFoundException, NodeException + public Link getLink(String name, boolean checkAccess) + throws DocumentNotFoundException, NodeException { // get link Link link = (Link) getAllNodes().subset(Link.DOCUMENT_TYPE).get(name); - if (link == null) - { - throw new DocumentNotFoundException("Jetspeed PSML link not found: " + name); - } + if (link == null) { throw new DocumentNotFoundException( + "Jetspeed PSML link not found: " + name); } // check access if (checkAccess) @@ -398,7 +422,8 @@ * * @see org.apache.jetspeed.om.folder.Folder#getLink(java.lang.String) */ - public Link getLink(String name) throws DocumentNotFoundException, NodeException + public Link getLink(String name) throws DocumentNotFoundException, + NodeException { // by default enable access checks return getLink(name, true); @@ -409,12 +434,14 @@ * getPageSecurity *

        * - * @param checkAccess flag + * @param checkAccess + * flag * @return page security * @throws DocumentNotFoundException * @throws NodeException */ - public PageSecurity getPageSecurity(boolean checkAccess) throws DocumentNotFoundException, NodeException + public PageSecurity getPageSecurity(boolean checkAccess) + throws DocumentNotFoundException, NodeException { // check access to this folder in place // of access to page security document @@ -424,11 +451,11 @@ } // get pageSecurity - PageSecurity pageSecurity = (PageSecurity) getAllNodes( false ).subset(PageSecurity.DOCUMENT_TYPE).get(PageSecurity.DOCUMENT_TYPE); - if (pageSecurity == null) - { - throw new DocumentNotFoundException("Jetspeed PSML page security not found: " + PageSecurity.DOCUMENT_TYPE); - } + PageSecurity pageSecurity = (PageSecurity) getAllNodes(false).subset( + PageSecurity.DOCUMENT_TYPE).get(PageSecurity.DOCUMENT_TYPE); + if (pageSecurity == null) { throw new DocumentNotFoundException( + "Jetspeed PSML page security not found: " + + PageSecurity.DOCUMENT_TYPE); } return pageSecurity; } @@ -437,7 +464,8 @@ * * @see org.apache.jetspeed.om.folder.Folder#getPageSecurity() */ - public PageSecurity getPageSecurity() throws DocumentNotFoundException, NodeException + public PageSecurity getPageSecurity() throws DocumentNotFoundException, + NodeException { // by default disable access checks return getPageSecurity(false); @@ -457,7 +485,7 @@ Iterator checkAccessIter = nodes.iterator(); while (checkAccessIter.hasNext()) { - Node node = (Node)checkAccessIter.next(); + Node node = (Node) checkAccessIter.next(); try { ((AbstractNode) node).checkAccess(JetspeedActions.VIEW); @@ -470,11 +498,12 @@ { if (filteredNodes == null) { - filteredNodes = new NodeSetImpl(getPath(), ((NodeSetImpl) nodes).getComparator()); + filteredNodes = new NodeSetImpl(getPath(), + ((NodeSetImpl) nodes).getComparator()); Iterator copyIter = nodes.iterator(); while (copyIter.hasNext()) { - Node copyNode = (Node)copyIter.next(); + Node copyNode = (Node) copyIter.next(); if (copyNode != node) { filteredNodes.add(copyNode); @@ -487,10 +516,7 @@ } } } - if (filteredNodes != null) - { - return filteredNodes; - } + if (filteredNodes != null) { return filteredNodes; } return nodes; } @@ -498,28 +524,34 @@ *

        * getAllNodes *

        - * + * * @return all nodes immediatley under this * @throws DocumentException */ public NodeSet getAllNodes() throws DocumentException { - return getAllNodes( true ); + return getAllNodes(true); } - - protected synchronized NodeSet getAllNodes( boolean folderExistenceRequired ) throws DocumentException + + protected synchronized NodeSet getAllNodes(boolean folderExistenceRequired) + throws DocumentException { - if((allNodes == null) && (folderHandler != null)) - { - if(metadata.getDocumentOrder() != null) + if ((allNodes == null) && (folderHandler != null)) + { + if (metadata.getDocumentOrder() != null) { if (getPath().endsWith(PATH_SEPARATOR)) { - allNodes = new NodeSetImpl(getPath(), new NodeOrderCompartaor(metadata.getDocumentOrder(), getPath())); + allNodes = new NodeSetImpl(getPath(), + new NodeOrderCompartaor( + metadata.getDocumentOrder(), getPath())); } else { - allNodes = new NodeSetImpl(getPath(), new NodeOrderCompartaor(metadata.getDocumentOrder(), getPath() + PATH_SEPARATOR)); + allNodes = new NodeSetImpl(getPath(), + new NodeOrderCompartaor( + metadata.getDocumentOrder(), getPath() + + PATH_SEPARATOR)); } } else @@ -539,61 +571,78 @@ { if (getPath().endsWith(PATH_SEPARATOR)) { - String full = PageManagerUtils.concatenatePaths(getPath(), nodeNames[i]); + String full = PageManagerUtils + .concatenatePaths(getPath(), + nodeNames[i]); if (!folderHandler.isFolder(full)) { - node = getHandlerFactory().getDocumentHandlerForPath(nodeNames[i]).getDocument(getPath() + nodeNames[i]); + node = getHandlerFactory() + .getDocumentHandlerForPath( + nodeNames[i]).getDocument( + getPath() + nodeNames[i]); } else { - node = folderHandler.getFolder(getPath() + nodeNames[i]); + node = folderHandler.getFolder(getPath() + + nodeNames[i]); } } else { - String full = PageManagerUtils.concatenatePaths(getPath(), nodeNames[i]); - if (!folderHandler.isFolder(full)) - //if(nodeNames[i].indexOf(".") > -1) + String full = PageManagerUtils + .concatenatePaths(getPath(), + nodeNames[i]); + if (!folderHandler.isFolder(full)) + // if(nodeNames[i].indexOf(".") > -1) { - node = getHandlerFactory().getDocumentHandlerForPath(nodeNames[i]).getDocument(getPath() + PATH_SEPARATOR + nodeNames[i]); + node = getHandlerFactory() + .getDocumentHandlerForPath( + nodeNames[i]).getDocument( + getPath() + PATH_SEPARATOR + + nodeNames[i]); } else { - node = folderHandler.getFolder(getPath() + PATH_SEPARATOR + nodeNames[i]); + node = folderHandler.getFolder(getPath() + + PATH_SEPARATOR + nodeNames[i]); } } node.setParent(this); allNodes.add(node); - } + } catch (UnsupportedDocumentTypeException e) { // Skip unsupported documents - log.info("getAllNodes() Skipping unsupported document: "+nodeNames[i]); + log + .info("getAllNodes() Skipping unsupported document: " + + nodeNames[i]); } catch (Exception e) { - log.warn("getAllNodes() failed to create Node: "+nodeNames[i]+":"+e.toString(), e); + log.warn("getAllNodes() failed to create Node: " + + nodeNames[i] + ":" + e.toString(), e); } - } + } } } catch (FolderNotFoundException fnfe) { - if ( folderExistenceRequired ) - { - log.error( "getAllNodes() unexpected missing folder: " + getPath(), fnfe ); - } + if (folderExistenceRequired) + { + log.error("getAllNodes() unexpected missing folder: " + + getPath(), fnfe); + } } } - + return allNodes; } - + /** *

        * getFolderMetaData *

        - * + * * @return implementation specific folder metadata */ public FolderMetaDataImpl getFolderMetaData() @@ -605,8 +654,9 @@ *

        * setFolderHandler *

        - * - * @param handler folder handler + * + * @param handler + * folder handler */ public void setFolderHandler(FolderHandler handler) { @@ -617,12 +667,12 @@ *

        * getMetadata *

        - * + * * @see org.apache.jetspeed.page.document.AbstractNode#getMetadata() * @return metadata */ public GenericMetadata getMetadata() - { + { return metadata.getMetadata(); } @@ -630,7 +680,7 @@ *

        * getSecurityConstraints *

        - * + * * @see org.apache.jetspeed.om.common.SecureResource#getSecurityConstraints() * @return */ @@ -638,11 +688,12 @@ { return metadata.getSecurityConstraints(); } + /** *

        * setSecurityConstraints *

        - * + * * @see org.apache.jetspeed.om.common.SecureResource#setSecurityConstraints(org.apache.jetspeed.om.common.SecurityConstraints) * @param constraints */ @@ -653,7 +704,7 @@ /** * getEffectivePageSecurity - * + * * @see org.apache.jetspeed.om.page.psml.AbstractElementImpl#getEffectivePageSecurity() */ public PageSecurity getEffectivePageSecurity() @@ -663,10 +714,7 @@ try { pageSecurity = getPageSecurity(false); - if (pageSecurity != null) - { - return pageSecurity; - } + if (pageSecurity != null) { return pageSecurity; } } catch (NodeException ne) { @@ -676,11 +724,9 @@ } // delegate to parent folder implementation - FolderImpl parentFolderImpl = (FolderImpl)getParent(); - if (parentFolderImpl != null) - { - return parentFolderImpl.getEffectivePageSecurity(); - } + FolderImpl parentFolderImpl = (FolderImpl) getParent(); + if (parentFolderImpl != null) { return parentFolderImpl + .getEffectivePageSecurity(); } return null; } @@ -688,14 +734,15 @@ *

        * checkPermissions *

        - * + * * @param path * @param mask * @param checkNodeOnly * @param checkParentsOnly * @throws SecurityException */ - public void checkPermissions(String path, int mask, boolean checkNodeOnly, boolean checkParentsOnly) throws SecurityException + public void checkPermissions(String path, int mask, boolean checkNodeOnly, + boolean checkParentsOnly) throws SecurityException { // check granted folder permissions unless the check is // to be skipped due to explicity granted access @@ -709,7 +756,7 @@ // all parent permissions in hierarchy if (!checkNodeOnly && (getParent() != null)) { - ((AbstractNode)getParent()).checkPermissions(mask, false, false); + ((AbstractNode) getParent()).checkPermissions(mask, false, false); } } @@ -717,20 +764,21 @@ *

        * getTitle *

        - * + * * @see org.apache.jetspeed.page.document.Node#getTitle(java.util.Locale) * @param locale * @return title in specified locale */ - public String getTitle( Locale locale ) + public String getTitle(Locale locale) { return metadata.getTitle(locale); } + /** *

        * getTitle *

        - * + * * @see org.apache.jetspeed.om.page.BaseElement#getTitle() * @return title */ @@ -738,36 +786,39 @@ { return metadata.getTitle(); } + /** *

        * setTitle *

        - * + * * @see org.apache.jetspeed.om.page.BaseElement#setTitle(java.lang.String) * @param title */ - public void setTitle( String title ) + public void setTitle(String title) { metadata.setTitle(title); } + /** *

        * getShortTitle *

        - * + * * @see org.apache.jetspeed.page.document.Node#getShortTitle(java.util.Locale) * @param locale * @return short title in supplied locate */ - public String getShortTitle( Locale locale ) + public String getShortTitle(Locale locale) { return metadata.getShortTitle(locale); } + /** *

        * getShortTitle *

        - * + * * @see org.apache.jetspeed.om.page.BaseElement#getShortTitle() * @return short title */ @@ -775,23 +826,25 @@ { return metadata.getShortTitle(); } + /** *

        * setShortTitle *

        - * + * * @see org.apache.jetspeed.om.page.BaseElement#setShortTitle(java.lang.String) * @param title */ - public void setShortTitle( String title ) + public void setShortTitle(String title) { metadata.setShortTitle(title); } + /** *

        * getType *

        - * + * * @see org.apache.jetspeed.page.document.Node#getType() * @return type string */ @@ -799,11 +852,12 @@ { return FOLDER_TYPE; } + /** *

        * isHidden *

        - * + * * @see org.apache.jetspeed.page.document.Node#isHidden() * @return whether folder is hidden */ @@ -811,31 +865,34 @@ { return metadata.isHidden(); } + /** *

        * setHidden *

        - * + * * @see org.apache.jetspeed.page.document.AbstractNode#setHidden(boolean) * @param hidden */ - public void setHidden( boolean hidden ) - { - ((AbstractNode)metadata).setHidden(hidden); + public void setHidden(boolean hidden) + { + ((AbstractNode) metadata).setHidden(hidden); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.Reset#reset() */ public void reset() { allNodes = null; - + } /** * getMenuDefinitions - get list of menu definitions - * + * * @return definition list */ public List getMenuDefinitions() @@ -845,7 +902,7 @@ /** * newMenuDefinition - creates a new empty menu definition - * + * * @return a newly created MenuDefinition object for use in Folder */ public MenuDefinition newMenuDefinition() @@ -855,7 +912,7 @@ /** * newMenuExcludeDefinition - creates a new empty menu exclude definition - * + * * @return a newly created MenuExcludeDefinition object for use in Folder */ public MenuExcludeDefinition newMenuExcludeDefinition() @@ -865,7 +922,7 @@ /** * newMenuIncludeDefinition - creates a new empty menu include definition - * + * * @return a newly created MenuIncludeDefinition object for use in Folder */ public MenuIncludeDefinition newMenuIncludeDefinition() @@ -875,7 +932,7 @@ /** * newMenuOptionsDefinition - creates a new empty menu options definition - * + * * @return a newly created MenuOptionsDefinition object for use in Folder */ public MenuOptionsDefinition newMenuOptionsDefinition() @@ -884,8 +941,9 @@ } /** - * newMenuSeparatorDefinition - creates a new empty menu separator definition - * + * newMenuSeparatorDefinition - creates a new empty menu separator + * definition + * * @return a newly created MenuSeparatorDefinition object for use in Folder */ public MenuSeparatorDefinition newMenuSeparatorDefinition() @@ -895,8 +953,9 @@ /** * setMenuDefinitions - set list of menu definitions - * - * @param definitions definition list + * + * @param definitions + * definition list */ public void setMenuDefinitions(List definitions) { @@ -904,8 +963,8 @@ } /** - * unmarshalled - notification that this instance has been - * loaded from the persistent store + * unmarshalled - notification that this instance has been loaded from the + * persistent store */ public void unmarshalled() { @@ -918,17 +977,17 @@ setTitle(getTitleName()); } } - + public boolean isReserved() { return (reservedType > RESERVED_FOLDER_NONE); } - + public int getReservedType() { return reservedType; } - + private void setReservedType() { String name = getName(); @@ -938,7 +997,7 @@ { reservedType = RESERVED_FOLDER_SUBSITES; } - else if (name.startsWith(RESERVED_FOLDER_PREFIX)) + else if (name.startsWith(RESERVED_FOLDER_PREFIX)) { if (name.equals(RESERVED_USER_FOLDER_NAME)) reservedType = RESERVED_FOLDER_USERS; @@ -953,9 +1012,9 @@ else if (name.equals(RESERVED_COUNTRY_FOLDER_NAME)) reservedType = RESERVED_FOLDER_COUNTRY; else - reservedType = RESERVED_FOLDER_OTHER; + reservedType = RESERVED_FOLDER_OTHER; } } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/FolderMetaDataImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/FolderMetaDataImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/FolderMetaDataImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,31 +34,34 @@ * * @author Scott T. Weaver * @version $Id: FolderMetaDataImpl.java 553014 2007-07-03 23:10:53Z ate $ - * + * */ public class FolderMetaDataImpl extends DocumentImpl implements Document { + public static final String DOCUMENT_TYPE = "folder.metadata"; private DefaultsImpl defaults = new DefaultsImpl(); + private List docOrder; + private String defaultPage; /** * menuDefinitions - menu definitions for folder */ private List menuDefinitions; - + public FolderMetaDataImpl() { docOrder = new ArrayList(4); } - + /** *

        * getType *

        - * + * * @return document type */ public String getType() @@ -70,7 +73,7 @@ *

        * getUrl *

        - * + * * @return url of folder */ public String getUrl() @@ -82,7 +85,7 @@ *

        * getSkin *

        - * + * * @return skin for folder */ public String getSkin() @@ -95,10 +98,11 @@ *

        * setSkin *

        - * - * @param skinName skin for folder + * + * @param skinName + * skin for folder */ - public void setSkin( String skinName ) + public void setSkin(String skinName) { // delegate to defaults implementation defaults.setSkin(skinName); @@ -108,11 +112,12 @@ *

        * getDefaultDecorator *

        - * - * @param fragmentType portlet or layout fragment type + * + * @param fragmentType + * portlet or layout fragment type * @return decorator name */ - public String getDefaultDecorator( String fragmentType ) + public String getDefaultDecorator(String fragmentType) { // delegate to defaults implementation return defaults.getDecorator(fragmentType); @@ -122,11 +127,13 @@ *

        * setDefaultDecorator *

        - * - * @param decoratorName decorator name - * @param fragmentType portlet or layout fragment type + * + * @param decoratorName + * decorator name + * @param fragmentType + * portlet or layout fragment type */ - public void setDefaultDecorator( String decoratorName, String fragmentType ) + public void setDefaultDecorator(String decoratorName, String fragmentType) { // delegate to defaults implementation defaults.setDecorator(fragmentType, decoratorName); @@ -136,7 +143,7 @@ *

        * getDocumentOrder *

        - * + * * @return document order */ public List getDocumentOrder() @@ -148,7 +155,7 @@ *

        * setDocumentOrder *

        - * + * * @param docIndexes */ public void setDocumentOrder(List docIndexes) @@ -165,16 +172,17 @@ } /** - * @param defaultPage The defaultPage to set. + * @param defaultPage + * The defaultPage to set. */ - public void setDefaultPage( String defaultPage ) + public void setDefaultPage(String defaultPage) { this.defaultPage = defaultPage; } /** * getMenuDefinitions - get list of menu definitions - * + * * @return definition list */ public List getMenuDefinitions() @@ -184,8 +192,9 @@ /** * setMenuDefinitions - set list of menu definitions - * - * @param definitions definition list + * + * @param definitions + * definition list */ public void setMenuDefinitions(List definitions) { @@ -194,7 +203,7 @@ /** * getDefaults - Castor access method for Defaults. - * + * * @return defaults instance */ public DefaultsImpl getDefaults() @@ -204,17 +213,18 @@ /** * setDefaults - Castor access method for Defaults. - * - * @param defaults defaults instance + * + * @param defaults + * defaults instance */ - public void setDefaults( DefaultsImpl defaults ) + public void setDefaults(DefaultsImpl defaults) { this.defaults = defaults; } /** - * unmarshalled - notification that this instance has been - * loaded from the persistent store + * unmarshalled - notification that this instance has been loaded from the + * persistent store */ public void unmarshalled() { @@ -228,14 +238,14 @@ Iterator menuIter = menuDefinitions.iterator(); while (menuIter.hasNext()) { - ((MenuDefinitionImpl)menuIter.next()).unmarshalled(); + ((MenuDefinitionImpl) menuIter.next()).unmarshalled(); } } } /** - * marshalling - notification that this instance is to - * be saved to the persistent store + * marshalling - notification that this instance is to be saved to the + * persistent store */ public void marshalling() { @@ -246,7 +256,7 @@ Iterator menuIter = menuDefinitions.iterator(); while (menuIter.hasNext()) { - ((MenuDefinitionImpl)menuIter.next()).marshalling(); + ((MenuDefinitionImpl) menuIter.next()).marshalling(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,15 +23,16 @@ import org.apache.jetspeed.om.folder.MenuDefinition; /** - * This class implements the MenuDefinition - * interface in a persistent object form for use by - * the page manager component. + * This class implements the MenuDefinition interface in a persistent object + * form for use by the page manager component. * * @author Randy Watler * @version $Id: MenuDefinitionImpl.java 516448 2007-03-09 16:25:47Z ate $ */ -public class MenuDefinitionImpl extends MenuMetadataImpl implements MenuDefinition +public class MenuDefinitionImpl extends MenuMetadataImpl implements + MenuDefinition { + /** * name - name of menu definition */ @@ -61,17 +62,17 @@ * profile - profile locator name filter for options */ private String profile; - + /** * order - comma separated list of ordering patterns for options */ private String order; - + /** * skin - skin name for menu */ private String skin; - + /** * title - title for menu */ @@ -83,8 +84,8 @@ private String shortTitle; /** - * menuElements - ordered polymorphic list of menu options nested - * menu, separator, include, and exclude definitions + * menuElements - ordered polymorphic list of menu options nested menu, + * separator, include, and exclude definitions */ private List menuElements; @@ -102,7 +103,7 @@ /** * getName - get menu name - * + * * @return menu name */ public String getName() @@ -112,8 +113,9 @@ /** * setName - set menu name - * - * @param name menu name + * + * @param name + * menu name */ public void setName(String name) { @@ -121,8 +123,9 @@ } /** - * getOptions - get comma separated menu options if not specified as elements - * + * getOptions - get comma separated menu options if not specified as + * elements + * * @return option paths specification */ public String getOptions() @@ -131,9 +134,11 @@ } /** - * setOptions - set comma separated menu options if not specified as elements - * - * @param options option paths specification + * setOptions - set comma separated menu options if not specified as + * elements + * + * @param options + * option paths specification */ public void setOptions(String options) { @@ -142,7 +147,7 @@ /** * getDepth - get depth of inclusion for folder menu options - * + * * @return inclusion depth */ public int getDepth() @@ -152,8 +157,9 @@ /** * setDepth - set depth of inclusion for folder menu options - * - * @param depth inclusion depth + * + * @param depth + * inclusion depth */ public void setDepth(int depth) { @@ -162,27 +168,28 @@ /** * isPaths - get generate ordered path options for specified options - * + * * @return paths options flag */ public boolean isPaths() { return paths; } - + /** * setPaths - set generate ordered path options for specified options - * - * @param paths paths options flag + * + * @param paths + * paths options flag */ public void setPaths(boolean paths) { this.paths = paths; } - + /** * isRegexp - get regexp flag for interpreting specified options - * + * * @return regexp flag */ public boolean isRegexp() @@ -192,8 +199,9 @@ /** * setRegexp - set regexp flag for interpreting specified options - * - * @param regexp regexp flag + * + * @param regexp + * regexp flag */ public void setRegexp(boolean regexp) { @@ -202,7 +210,7 @@ /** * getProfile - get profile locator used to filter specified options - * + * * @return profile locator name */ public String getProfile() @@ -212,8 +220,9 @@ /** * setProfile - set profile locator used to filter specified options - * - * @param locatorName profile locator name + * + * @param locatorName + * profile locator name */ public void setProfile(String locatorName) { @@ -222,7 +231,7 @@ /** * getOrder - get comma separated regexp ordering patterns for options - * + * * @return ordering patterns list */ public String getOrder() @@ -232,8 +241,9 @@ /** * setOrder - set comma separated regexp ordering patterns for options - * - * @param order ordering patterns list + * + * @param order + * ordering patterns list */ public void setOrder(String order) { @@ -242,7 +252,7 @@ /** * getSkin - get skin name for menu - * + * * @return skin name */ public String getSkin() @@ -252,8 +262,9 @@ /** * setSkin - set skin name for menu - * - * @param name skin name + * + * @param name + * skin name */ public void setSkin(String name) { @@ -262,7 +273,7 @@ /** * getTitle - get default title for menu - * + * * @return title text */ public String getTitle() @@ -272,8 +283,9 @@ /** * setTitle - set default title for menu - * - * @param title title text + * + * @param title + * title text */ public void setTitle(String title) { @@ -282,18 +294,19 @@ /** * getShortTitle - get default short title for menu - * + * * @return short title text */ public String getShortTitle() { - return shortTitle; + return shortTitle; } /** * setShortTitle - set default short title for menu - * - * @param title short title text + * + * @param title + * short title text */ public void setShortTitle(String title) { @@ -301,10 +314,9 @@ } /** - * getMenuElements - get ordered list of menu options, - * nested menus, separators, included - * menu, and excluded menu elements - * + * getMenuElements - get ordered list of menu options, nested menus, + * separators, included menu, and excluded menu elements + * * @return element list */ public List getMenuElements() @@ -314,8 +326,9 @@ /** * setMenuElements - set ordered list of menu elements - * - * @param elements element list + * + * @param elements + * element list */ public void setMenuElements(List elements) { @@ -324,7 +337,7 @@ /** * getMenuElementImpls - get ordered list of wrapped menu elements - * + * * @return element list */ public List getMenuElementImpls() @@ -333,10 +346,11 @@ } /** - * setMenuElementImpls - set ordered list of menu elements using - * a list of wrapped menu elements - * - * @param elements element list + * setMenuElementImpls - set ordered list of menu elements using a list of + * wrapped menu elements + * + * @param elements + * element list */ public void setMenuElementImpls(List elements) { @@ -344,8 +358,8 @@ } /** - * unmarshalled - notification that this instance has been - * loaded from the persistent store + * unmarshalled - notification that this instance has been loaded from the + * persistent store */ public void unmarshalled() { @@ -361,25 +375,26 @@ while (menuElementIter.hasNext()) { // unwrap menu element - Object menuElement = ((MenuElementImpl)menuElementIter.next()).getElement(); + Object menuElement = ((MenuElementImpl) menuElementIter.next()) + .getElement(); menuElements.add(menuElement); // propagate unmarshalled notification if (menuElement instanceof MenuMetadataImpl) { - ((MenuMetadataImpl)menuElement).unmarshalled(); + ((MenuMetadataImpl) menuElement).unmarshalled(); } } } else { - menuElements = null; + menuElements = null; } } /** - * marshalling - notification that this instance is to - * be saved to the persistent store + * marshalling - notification that this instance is to be saved to the + * persistent store */ public void marshalling() { @@ -398,13 +413,13 @@ // propagate marshalling notification if (menuElement instanceof MenuDefinitionImpl) { - ((MenuDefinitionImpl)menuElement).unmarshalled(); + ((MenuDefinitionImpl) menuElement).unmarshalled(); } } } else { - menuElementImpls = null; + menuElementImpls = null; } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuElementImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuElementImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuElementImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,14 +17,15 @@ package org.apache.jetspeed.om.folder.psml; /** - * This class implements a wrapper used to implement - * the ordered polymorphic menu elements collection. + * This class implements a wrapper used to implement the ordered polymorphic + * menu elements collection. * * @author Randy Watler * @version $Id: MenuElementImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class MenuElementImpl { + /** * element - wrapped menu element */ @@ -58,17 +59,15 @@ */ public MenuOptionsDefinitionImpl getOptions() { - if (element instanceof MenuOptionsDefinitionImpl) - { - return (MenuOptionsDefinitionImpl)element; - } + if (element instanceof MenuOptionsDefinitionImpl) { return (MenuOptionsDefinitionImpl) element; } return null; } /** * setOption - set wrapped menu options definition - * - * @param options menu options definition + * + * @param options + * menu options definition */ public void setOptions(MenuOptionsDefinitionImpl options) { @@ -80,17 +79,15 @@ */ public MenuDefinitionImpl getMenu() { - if (element instanceof MenuDefinitionImpl) - { - return (MenuDefinitionImpl)element; - } + if (element instanceof MenuDefinitionImpl) { return (MenuDefinitionImpl) element; } return null; } /** * setMenu - set wrapped menu menu definition - * - * @param menu menu definition + * + * @param menu + * menu definition */ public void setMenu(MenuDefinitionImpl menu) { @@ -102,17 +99,15 @@ */ public MenuSeparatorDefinitionImpl getSeparator() { - if (element instanceof MenuSeparatorDefinitionImpl) - { - return (MenuSeparatorDefinitionImpl)element; - } + if (element instanceof MenuSeparatorDefinitionImpl) { return (MenuSeparatorDefinitionImpl) element; } return null; } /** * setSeparator - set wrapped menu separator definition - * - * @param separator menu separator definition + * + * @param separator + * menu separator definition */ public void setSeparator(MenuSeparatorDefinitionImpl separator) { @@ -124,17 +119,15 @@ */ public MenuIncludeDefinitionImpl getInclude() { - if (element instanceof MenuIncludeDefinitionImpl) - { - return (MenuIncludeDefinitionImpl)element; - } + if (element instanceof MenuIncludeDefinitionImpl) { return (MenuIncludeDefinitionImpl) element; } return null; } /** * setInclude - set wrapped menu include definition - * - * @param include menu include definition + * + * @param include + * menu include definition */ public void setInclude(MenuIncludeDefinitionImpl include) { @@ -146,17 +139,15 @@ */ public MenuExcludeDefinitionImpl getExclude() { - if (element instanceof MenuExcludeDefinitionImpl) - { - return (MenuExcludeDefinitionImpl)element; - } + if (element instanceof MenuExcludeDefinitionImpl) { return (MenuExcludeDefinitionImpl) element; } return null; } /** * setExclude - set wrapped menu exclude definition - * - * @param exclude menu exclude definition + * + * @param exclude + * menu exclude definition */ public void setExclude(MenuExcludeDefinitionImpl exclude) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuExcludeDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuExcludeDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuExcludeDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,15 +19,15 @@ import org.apache.jetspeed.om.folder.MenuExcludeDefinition; /** - * This class implements the MenuExcludeDefinition - * interface in a persistent object form for use by - * the page manager component. + * This class implements the MenuExcludeDefinition interface in a persistent + * object form for use by the page manager component. * * @author Randy Watler * @version $Id: MenuExcludeDefinitionImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class MenuExcludeDefinitionImpl implements MenuExcludeDefinition { + /** * name - name of menu with options to exclude */ @@ -42,7 +42,7 @@ /** * getName - get menu name with options to exclude - * + * * @return menu name */ public String getName() @@ -52,8 +52,9 @@ /** * setName - set menu name with options to exclude - * - * @param name menu name + * + * @param name + * menu name */ public void setName(String name) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuIncludeDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuIncludeDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuIncludeDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,15 +19,15 @@ import org.apache.jetspeed.om.folder.MenuIncludeDefinition; /** - * This class implements the MenuIncludeDefinition - * interface in a persistent object form for use by - * the page manager component. + * This class implements the MenuIncludeDefinition interface in a persistent + * object form for use by the page manager component. * * @author Randy Watler * @version $Id: MenuIncludeDefinitionImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class MenuIncludeDefinitionImpl implements MenuIncludeDefinition { + /** * name - name of menu to include */ @@ -47,7 +47,7 @@ /** * getName - get menu name to nest or with options to include - * + * * @return menu name */ public String getName() @@ -57,8 +57,9 @@ /** * setName - set menu name to nest or with options to include - * - * @param name menu name + * + * @param name + * menu name */ public void setName(String name) { @@ -67,18 +68,19 @@ /** * isNest - get nesting for included menu - * + * * @return nest options flag */ public boolean isNest() { return nest; } - + /** * setNest - set nesting for included menu - * - * @param nest nest menu flag + * + * @param nest + * nest menu flag */ public void setNest(boolean nest) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuMetadataImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuMetadataImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuMetadataImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,14 +23,14 @@ import org.apache.jetspeed.om.page.PageMetadataImpl; /** - * This class implements metadata protocols for menu - * definition implementations. + * This class implements metadata protocols for menu definition implementations. * * @author Randy Watler * @version $Id: MenuMetadataImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public abstract class MenuMetadataImpl { + /** * metadata - page metadata to hold title information */ @@ -45,7 +45,7 @@ /** * getTitle - get default title protocol stub - * + * * @return null */ public String getTitle() @@ -55,7 +55,7 @@ /** * getShortTitle - get default short title protocol stub - * + * * @return short title text */ public String getShortTitle() @@ -65,7 +65,7 @@ /** * getText - get default text protocol stub - * + * * @return text */ public String getText() @@ -75,8 +75,9 @@ /** * getTitle - get locale specific title from metadata - * - * @param locale preferred locale + * + * @param locale + * preferred locale * @return title text */ public String getTitle(Locale locale) @@ -92,8 +93,9 @@ /** * getShortTitle - get locale specific short title from metadata - * - * @param locale preferred locale + * + * @param locale + * preferred locale * @return short title text */ public String getShortTitle(Locale locale) @@ -118,8 +120,9 @@ /** * getText - get locale specific text from metadata - * - * @param locale preferred locale + * + * @param locale + * preferred locale * @return text */ public String getText(Locale locale) @@ -135,7 +138,7 @@ /** * getMetadata - get generic metadata instance - * + * * @return metadata instance */ public GenericMetadata getMetadata() @@ -145,7 +148,7 @@ /** * getMetadataFields - get metadata fields collection - * + * * @return metadata fields collection */ public Collection getMetadataFields() @@ -157,8 +160,9 @@ /** * setMetadataFields - set metadata fields collection - * - * @param metadataFields metadata fields collection + * + * @param metadataFields + * metadata fields collection */ public void setMetadataFields(Collection metadataFields) { @@ -170,7 +174,7 @@ /** * getPageMetadata - get/construct page metadata instance - * + * * @return metadata instance */ private PageMetadataImpl getPageMetadata() @@ -183,8 +187,8 @@ } /** - * unmarshalled - notification that this instance has been - * loaded from the persistent store + * unmarshalled - notification that this instance has been loaded from the + * persistent store */ public void unmarshalled() { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuOptionsDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuOptionsDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuOptionsDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,15 +19,15 @@ import org.apache.jetspeed.om.folder.MenuOptionsDefinition; /** - * This class implements the MenuOptionsDefinition - * interface in a persistent object form for use by - * the page manager component. + * This class implements the MenuOptionsDefinition interface in a persistent + * object form for use by the page manager component. * * @author Randy Watler * @version $Id: MenuOptionsDefinitionImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class MenuOptionsDefinitionImpl implements MenuOptionsDefinition { + /** * options - comma separated option paths specification for menu */ @@ -52,17 +52,17 @@ * profile - profile locator name filter for options */ private String profile; - + /** * order - comma separated list of ordering patterns for options */ private String order; - + /** * skin - skin name for menu */ private String skin; - + /** * MenuOptionsDefinitionImpl - constructor */ @@ -72,7 +72,7 @@ /** * getOptions - get comma separated menu options - * + * * @return option paths specification */ public String getOptions() @@ -82,8 +82,9 @@ /** * setOptions - set comma separated menu options - * - * @param options option paths specification + * + * @param options + * option paths specification */ public void setOptions(String options) { @@ -92,7 +93,7 @@ /** * getDepth - get depth of inclusion for folder options - * + * * @return inclusion depth */ public int getDepth() @@ -102,8 +103,9 @@ /** * setDepth - set depth of inclusion for folder options - * - * @param depth inclusion depth + * + * @param depth + * inclusion depth */ public void setDepth(int depth) { @@ -112,27 +114,28 @@ /** * isPaths - get generate ordered path options - * + * * @return paths options flag */ public boolean isPaths() { return paths; } - + /** * setPaths - set generate ordered path options - * - * @param paths paths options flag + * + * @param paths + * paths options flag */ public void setPaths(boolean paths) { this.paths = paths; } - + /** * isRegexp - get regexp flag for interpreting options - * + * * @return regexp flag */ public boolean isRegexp() @@ -142,8 +145,9 @@ /** * setRegexp - set regexp flag for interpreting options - * - * @param regexp regexp flag + * + * @param regexp + * regexp flag */ public void setRegexp(boolean regexp) { @@ -152,7 +156,7 @@ /** * getProfile - get profile locator used to filter options - * + * * @return profile locator name */ public String getProfile() @@ -162,8 +166,9 @@ /** * setProfile - set profile locator used to filter options - * - * @param locatorName profile locator name + * + * @param locatorName + * profile locator name */ public void setProfile(String locatorName) { @@ -172,7 +177,7 @@ /** * getOrder - get comma separated regexp ordering patterns - * + * * @return ordering patterns list */ public String getOrder() @@ -182,8 +187,9 @@ /** * setOrder - set comma separated regexp ordering patterns - * - * @param order ordering patterns list + * + * @param order + * ordering patterns list */ public void setOrder(String order) { @@ -192,7 +198,7 @@ /** * getSkin - get skin name for options - * + * * @return skin name */ public String getSkin() @@ -202,8 +208,9 @@ /** * setSkin - set skin name for options - * - * @param name skin name + * + * @param name + * skin name */ public void setSkin(String name) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuSeparatorDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuSeparatorDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/folder/psml/MenuSeparatorDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,20 +19,22 @@ import org.apache.jetspeed.om.folder.MenuSeparatorDefinition; /** - * This class implements the MenuSeparatorDefinition - * interface in a persistent object form for use by - * the page manager component. + * This class implements the MenuSeparatorDefinition interface in a persistent + * object form for use by the page manager component. * * @author Randy Watler - * @version $Id: MenuSeparatorDefinitionImpl.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: MenuSeparatorDefinitionImpl.java 516448 2007-03-09 16:25:47Z + * ate $ */ -public class MenuSeparatorDefinitionImpl extends MenuMetadataImpl implements MenuSeparatorDefinition +public class MenuSeparatorDefinitionImpl extends MenuMetadataImpl implements + MenuSeparatorDefinition { + /** * skin - skin name for separator */ private String skin; - + /** * title - title for separator */ @@ -52,7 +54,7 @@ /** * getSkin - get skin name for separator - * + * * @return skin name */ public String getSkin() @@ -62,8 +64,9 @@ /** * setSkin - set skin name for separator - * - * @param name skin name + * + * @param name + * skin name */ public void setSkin(String name) { @@ -72,7 +75,7 @@ /** * getTitle - get default title for separator - * + * * @return title text */ public String getTitle() @@ -82,8 +85,9 @@ /** * setTitle - set default title for separator - * - * @param title title text + * + * @param title + * title text */ public void setTitle(String title) { @@ -92,7 +96,7 @@ /** * getText - get default text for separator - * + * * @return text */ public String getText() @@ -102,8 +106,9 @@ /** * setText - set default text for separator - * - * @param text text + * + * @param text + * text */ public void setText(String text) { @@ -112,24 +117,22 @@ /** * getTextChild - get default text for separator - * + * * @return text */ public String getTextChild() { // return text as child if any other child of // separator is defined - if ((getTitle() != null) || (getMetadata() != null)) - { - return getText(); - } + if ((getTitle() != null) || (getMetadata() != null)) { return getText(); } return null; } /** * setTextChild - set default text for separator - * - * @param text text + * + * @param text + * text */ public void setTextChild(String text) { @@ -142,24 +145,22 @@ /** * getTextBody - get default text for separator - * + * * @return text */ public String getTextBody() { // return text as body only if no other child of // separator is defined - if ((getTitle() == null) && (getMetadata() == null)) - { - return getText(); - } + if ((getTitle() == null) && (getMetadata() == null)) { return getText(); } return null; } /** * setTextBody - set default text for separator - * - * @param text text + * + * @param text + * text */ public void setTextBody(String text) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/ContentFragmentImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/ContentFragmentImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/ContentFragmentImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.om.page; import java.io.Serializable; @@ -33,51 +33,63 @@ public class ContentFragmentImpl implements ContentFragment { - private final Fragment fragment; + private StringBuffer overridenContent; + private PortletContent portletContent; + private List contentFragments; + private static final Log log = LogFactory.getLog(ContentFragmentImpl.class); + private final Map cachedFragments; + private Decoration decoration; + private boolean instantlyRendered; - public ContentFragmentImpl(Fragment fragment, Map cachedFagments) { this(fragment, cachedFagments, false); } - public ContentFragmentImpl(Fragment fragment, Map cachedFagments, boolean instantlyRendered) + public ContentFragmentImpl(Fragment fragment, Map cachedFagments, + boolean instantlyRendered) { this.fragment = fragment; this.cachedFragments = cachedFagments; this.instantlyRendered = instantlyRendered; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentFragment#getContentFragments() */ public List getContentFragments() - { - if(contentFragments == null) + { + if (contentFragments == null) { - contentFragments = new ContentFragmentList(); + contentFragments = new ContentFragmentList(); } return contentFragments; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentFragment#getFragments() */ public List getFragments() { return getContentFragments(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentFragment#getOverriddenContent() */ public String getOverriddenContent() @@ -85,21 +97,20 @@ return overridenContent != null ? overridenContent.toString() : null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentFragment#getRenderedContent() */ public String getRenderedContent() throws IllegalStateException - { - if(overridenContent != null) - { - return overridenContent.toString(); - } - - + { + if (overridenContent != null) { return overridenContent.toString(); } + if (portletContent != null) { - //TODO are you sure? Intellij warns, synchronization on a non-final field is - //unlikely to have useful semantics. + // TODO are you sure? Intellij warns, synchronization on a non-final + // field is + // unlikely to have useful semantics. synchronized (portletContent) { if (portletContent.isComplete()) @@ -120,25 +131,29 @@ } finally { - log.debug("Been notified that Faragment " + getId() + " is complete"); + log.debug("Been notified that Faragment " + getId() + + " is complete"); } } } } else { - throw new IllegalStateException("You cannot invoke getRenderedContent() until the content has been set."); + throw new IllegalStateException( + "You cannot invoke getRenderedContent() until the content has been set."); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentFragment#overrideRenderedContent(java.lang.String) */ public void overrideRenderedContent(String contnent) { - if ( contnent != null ) + if (contnent != null) { - if(overridenContent == null) + if (overridenContent == null) { overridenContent = new StringBuffer(); } @@ -148,143 +163,175 @@ overridenContent.append(contnent); } } - + } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentFragment#setPortletContent(org.apache.jetspeed.aggregator.PortletContent) */ public void setPortletContent(PortletContent portletContent) { - this.portletContent = portletContent; + this.portletContent = portletContent; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getDecorator() */ public String getDecorator() { - + return fragment.getDecorator(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getName() */ public String getName() { - + return fragment.getName(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getProperties() */ public Map getProperties() { - + return fragment.getProperties(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getProperty(java.lang.String) */ public String getProperty(String propName) { - + return fragment.getProperty(propName); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getIntProperty(java.lang.String) */ public int getIntProperty(String propName) { - + return fragment.getIntProperty(propName); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getFloatProperty(java.lang.String) */ public float getFloatProperty(String propName) { - + return fragment.getFloatProperty(propName); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getSkin() */ public String getSkin() { - + return fragment.getSkin(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getState() */ public String getState() { - + return fragment.getState(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getMode() */ public String getMode() { - + return fragment.getMode(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getType() */ public String getType() { - + return fragment.getType(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#isReference() */ public boolean isReference() { - + return fragment.isReference(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setDecorator(java.lang.String) */ public void setDecorator(String decoratorName) { - + fragment.setDecorator(decoratorName); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setName(java.lang.String) */ public void setName(String name) { - + fragment.setName(name); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutRow() */ public int getLayoutRow() { return fragment.getLayoutRow(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutColumn() */ public int getLayoutColumn() @@ -292,7 +339,9 @@ return fragment.getLayoutColumn(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutSizes() */ public String getLayoutSizes() @@ -300,7 +349,9 @@ return fragment.getLayoutSizes(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutX() */ public float getLayoutX() @@ -308,7 +359,9 @@ return fragment.getLayoutX(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutY() */ public float getLayoutY() @@ -316,7 +369,9 @@ return fragment.getLayoutY(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutZ() */ public float getLayoutZ() @@ -324,7 +379,9 @@ return fragment.getLayoutZ(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutWidth() */ public float getLayoutWidth() @@ -332,7 +389,9 @@ return fragment.getLayoutWidth(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutHeight() */ public float getLayoutHeight() @@ -340,39 +399,49 @@ return fragment.getLayoutHeight(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutRow(int) */ public void setLayoutRow(int row) { fragment.setLayoutRow(row); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutColumn(int) */ public void setLayoutColumn(int column) { fragment.setLayoutColumn(column); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutSizes(java.lang.String) */ public void setLayoutSizes(String sizes) { fragment.setLayoutSizes(sizes); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutX(float) */ public void setLayoutX(float x) { fragment.setLayoutX(x); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutY(float) */ public void setLayoutY(float y) @@ -380,7 +449,9 @@ fragment.setLayoutY(y); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutZ(float) */ public void setLayoutZ(float z) @@ -388,7 +459,9 @@ fragment.setLayoutZ(z); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutWidth(float) */ public void setLayoutWidth(float width) @@ -396,7 +469,9 @@ fragment.setLayoutWidth(width); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutHeight(float) */ public void setLayoutHeight(float height) @@ -404,174 +479,209 @@ fragment.setLayoutHeight(height); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setSkin(java.lang.String) */ public void setSkin(String skinName) { - + fragment.setSkin(skinName); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setState(java.lang.String) */ public void setState(String state) { - + fragment.setState(state); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setMode(java.lang.String) */ public void setMode(String mode) { - + fragment.setMode(mode); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setType(java.lang.String) */ public void setType(String type) { - + fragment.setType(type); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#getId() */ public String getId() { - + return fragment.getId(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#getShortTitle() */ public String getShortTitle() { - + return fragment.getShortTitle(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#getTitle() */ public String getTitle() { - + return fragment.getTitle(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#setShortTitle(java.lang.String) */ public void setShortTitle(String title) { - + fragment.setShortTitle(title); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#setTitle(java.lang.String) */ public void setTitle(String title) { - + fragment.setTitle(title); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#checkAccess(java.lang.String) */ public void checkAccess(String actions) throws SecurityException { - + fragment.checkAccess(actions); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#checkConstraints(java.lang.String) */ public void checkConstraints(String actions) throws SecurityException { - + fragment.checkConstraints(actions); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#checkPermissions(int) */ public void checkPermissions(int mask) throws SecurityException { - + fragment.checkPermissions(mask); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getConstraintsEnabled() */ public boolean getConstraintsEnabled() { - + return fragment.getConstraintsEnabled(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getPermissionsEnabled() */ public boolean getPermissionsEnabled() { - + return fragment.getPermissionsEnabled(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getSecurityConstraints() */ public SecurityConstraints getSecurityConstraints() { - + return fragment.getSecurityConstraints(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#newSecurityConstraints() */ public SecurityConstraints newSecurityConstraints() { - + return fragment.newSecurityConstraints(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#newSecurityConstraint() */ public SecurityConstraint newSecurityConstraint() { - + return fragment.newSecurityConstraint(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#setSecurityConstraints(org.apache.jetspeed.om.common.SecurityConstraints) */ public void setSecurityConstraints(SecurityConstraints constraints) { fragment.setSecurityConstraints(constraints); } - - + /** - * Checks the ContentFragment cache for a ContentFragment - * that matches the Id of this fragment. If - * one is found, it returned. If no matches are found, a new - * ContentFragment represnentive of the {@link Fragment} - * argument is subsequently created, stored into the cahce and returned. + * Checks the ContentFragment cache for a ContentFragment that matches the + * Id of this fragment. If one is found, it returned. If no + * matches are found, a new ContentFragment represnentive of + * the {@link Fragment} argument is subsequently created, stored into the + * cahce and returned. * * @param f * @return ContentFrament @@ -579,7 +689,7 @@ protected ContentFragment getContentFragment(Fragment f) { ContentFragment cf; - if(cachedFragments.containsKey(f.getId())) + if (cachedFragments.containsKey(f.getId())) { cf = (ContentFragment) cachedFragments.get(f.getId()); } @@ -590,123 +700,149 @@ } return cf; } - - + protected final class ContentFragmentList implements List, Serializable { + private List baseList = fragment.getFragments(); - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int, java.lang.Object) */ public void add(int index, Object element) { if (element instanceof ContentFragmentImpl) - element = ((ContentFragmentImpl)element).fragment; + element = ((ContentFragmentImpl) element).fragment; baseList.add(index, element); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(java.lang.Object) */ public boolean add(Object o) { if (o instanceof ContentFragmentImpl) - o = ((ContentFragmentImpl)o).fragment; + o = ((ContentFragmentImpl) o).fragment; return baseList.add(o); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#addAll(int, java.util.Collection) */ public boolean addAll(int index, Collection c) { - + return baseList.addAll(index, c); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#addAll(java.util.Collection) */ public boolean addAll(Collection c) { - + return baseList.addAll(c); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#clear() */ public void clear() { - + baseList.clear(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#contains(java.lang.Object) */ public boolean contains(Object o) { - + return baseList.contains(o); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#containsAll(java.util.Collection) */ public boolean containsAll(Collection c) { - + return baseList.containsAll(c); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#equals(java.lang.Object) */ public boolean equals(Object o) { - + return baseList.equals(o); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) { - Fragment f= (Fragment) baseList.get(index); - return getContentFragment(f); + Fragment f = (Fragment) baseList.get(index); + return getContentFragment(f); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#hashCode() */ public int hashCode() { - + return baseList.hashCode(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#indexOf(java.lang.Object) */ public int indexOf(Object o) { - + return baseList.indexOf(o); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#isEmpty() */ public boolean isEmpty() { - + return baseList.isEmpty(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#iterator() */ public Iterator iterator() @@ -714,16 +850,20 @@ return duplicateList().iterator(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#lastIndexOf(java.lang.Object) */ public int lastIndexOf(Object o) { - + return baseList.lastIndexOf(o); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#listIterator() */ public ListIterator listIterator() @@ -731,7 +871,9 @@ return duplicateList().listIterator(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#listIterator(int) */ public ListIterator listIterator(int index) @@ -739,61 +881,75 @@ return duplicateList().listIterator(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) { - + return baseList.remove(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(java.lang.Object) */ public boolean remove(Object o) { - + return baseList.remove(o); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#removeAll(java.util.Collection) */ public boolean removeAll(Collection c) { - + return baseList.removeAll(c); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#retainAll(java.util.Collection) */ public boolean retainAll(Collection c) { - + return baseList.retainAll(c); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int, java.lang.Object) */ public Object set(int index, Object element) { - + return baseList.set(index, element); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() { - + return baseList.size(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#subList(int, int) */ public List subList(int fromIndex, int toIndex) @@ -801,9 +957,9 @@ return duplicateList().subList(fromIndex, toIndex); } - - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#toArray() */ public Object[] toArray() @@ -811,31 +967,33 @@ return duplicateList().toArray(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#toArray(java.lang.Object[]) */ public Object[] toArray(Object[] a) { - return duplicateList().toArray(a); + return duplicateList().toArray(a); } - + private List duplicateList() - { + { List rFragList = DatabasePageManagerUtils.createList(); - for(int i=0; i < baseList.size(); i++) - { - Fragment f = (Fragment)baseList.get(i); + for (int i = 0; i < baseList.size(); i++) + { + Fragment f = (Fragment) baseList.get(i); ContentFragment cf = getContentFragment(f); rFragList.add(cf); } return rFragList; } - - } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getPreferences() */ public List getPreferences() @@ -847,8 +1005,10 @@ { return decoration; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setPreferences(java.util.List) */ public void setPreferences(List preferences) @@ -856,14 +1016,15 @@ fragment.setPreferences(preferences); } - public void setDecoration(Decoration decoration) { this.decoration = decoration; - + } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentFragment#isInstantlyRendered() */ public boolean isInstantlyRendered() @@ -875,5 +1036,5 @@ { return this.portletContent; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/ContentPageImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/ContentPageImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/ContentPageImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.om.page; @@ -35,11 +35,15 @@ public class ContentPageImpl implements ContentPage { + private final Page page; + private final Map cachedFragments; + private ContentFragment rootContentFragment; - private boolean dirty=false; - + + private boolean dirty = false; + public ContentPageImpl(Page page) { this.page = page; @@ -55,30 +59,34 @@ { return page.toString(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentPage#getContentFragmentById(java.lang.String) */ public ContentFragment getContentFragmentById(String id) { ContentFragment contentFragment = null; - if(cachedFragments.containsKey(id)) + if (cachedFragments.containsKey(id)) { contentFragment = (ContentFragment) cachedFragments.get(id); } else { Fragment f = page.getFragmentById(id); - if(f != null) + if (f != null) { contentFragment = new ContentFragmentImpl(f, cachedFragments); - cachedFragments.put(id, contentFragment); + cachedFragments.put(id, contentFragment); } } - return contentFragment; + return contentFragment; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentPage#getFragmentById(java.lang.String) */ public Fragment getFragmentById(String id) @@ -86,7 +94,9 @@ return getContentFragmentById(id); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentPage#removeFragmentById(java.lang.String) */ public Fragment removeFragmentById(String id) @@ -96,7 +106,8 @@ if (removed != null) { // reset content fragments if successfully removed - if ((rootContentFragment != null) && rootContentFragment.getId().equals(id)) + if ((rootContentFragment != null) + && rootContentFragment.getId().equals(id)) { rootContentFragment = null; } @@ -105,28 +116,29 @@ return removed; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentPage#getContentFragmentsByName(java.lang.String) */ public List getContentFragmentsByName(String name) { // get list of fragments by name List fragments = page.getFragmentsByName(name); - if (fragments == null) - { - return null; - } + if (fragments == null) { return null; } // convert list elements to content fragments ListIterator fragmentsIter = fragments.listIterator(); while (fragmentsIter.hasNext()) { - Fragment fragment = (Fragment)fragmentsIter.next(); + Fragment fragment = (Fragment) fragmentsIter.next(); String fragmentId = fragment.getId(); - ContentFragment contentFragment = (ContentFragment)cachedFragments.get(fragmentId); + ContentFragment contentFragment = (ContentFragment) cachedFragments + .get(fragmentId); if (contentFragment == null) { - contentFragment = new ContentFragmentImpl(fragment, cachedFragments); + contentFragment = new ContentFragmentImpl(fragment, + cachedFragments); cachedFragments.put(fragmentId, contentFragment); } fragmentsIter.set(contentFragment); @@ -134,7 +146,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentPage#getFragmentsByName(java.lang.String) */ public List getFragmentsByName(String name) @@ -142,80 +156,101 @@ return getContentFragmentsByName(name); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentPage#getRootContentFragment() */ public ContentFragment getRootContentFragment() { - if(rootContentFragment == null) + if (rootContentFragment == null) { - rootContentFragment = new ContentFragmentImpl(page.getRootFragment(), cachedFragments); - cachedFragments.put(rootContentFragment.getId(), rootContentFragment); + rootContentFragment = new ContentFragmentImpl(page + .getRootFragment(), cachedFragments); + cachedFragments.put(rootContentFragment.getId(), + rootContentFragment); } return rootContentFragment; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentPage#setRootFragment(org.apache.jetspeed.om.page.Fragment) */ public Fragment getRootFragment() { - return getRootContentFragment(); + return getRootContentFragment(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#getEffectiveDefaultDecorator(java.lang.String) */ public String getEffectiveDefaultDecorator(String fragmentType) - { + { return page.getEffectiveDefaultDecorator(fragmentType); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#getDefaultDecorator(java.lang.String) */ public String getDefaultDecorator(String fragmentType) - { + { return page.getDefaultDecorator(fragmentType); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#getSkin() */ public String getSkin() { - + return page.getSkin(); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.page.Page#setDefaultDecorator(java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.page.Page#setDefaultDecorator(java.lang.String, + * java.lang.String) */ public void setDefaultDecorator(String decoratorName, String fragmentType) { - + page.setDefaultDecorator(decoratorName, fragmentType); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#setSkin(java.lang.String) */ public void setSkin(String skinName) { - + page.setSkin(skinName); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#setRootFragment(org.apache.jetspeed.om.page.Fragment) */ public void setRootFragment(Fragment fragment) { - + page.setRootFragment(fragment); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#getMenuDefinitions() */ public List getMenuDefinitions() @@ -223,7 +258,9 @@ return page.getMenuDefinitions(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#newMenuDefinition() */ public MenuDefinition newMenuDefinition() @@ -231,7 +268,9 @@ return page.newMenuDefinition(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#newMenuExcludeDefinition() */ public MenuExcludeDefinition newMenuExcludeDefinition() @@ -239,7 +278,9 @@ return page.newMenuExcludeDefinition(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#newMenuIncludeDefinition() */ public MenuIncludeDefinition newMenuIncludeDefinition() @@ -247,7 +288,9 @@ return page.newMenuIncludeDefinition(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#newMenuOptionsDefinition() */ public MenuOptionsDefinition newMenuOptionsDefinition() @@ -255,7 +298,9 @@ return page.newMenuOptionsDefinition(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#newMenuSeparatorDefinition() */ public MenuSeparatorDefinition newMenuSeparatorDefinition() @@ -263,7 +308,9 @@ return page.newMenuSeparatorDefinition(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#setMenuDefinitions(java.util.List) */ public void setMenuDefinitions(List definitions) @@ -271,265 +318,319 @@ page.setMenuDefinitions(definitions); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getMetadata() */ public GenericMetadata getMetadata() { - + return page.getMetadata(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getName() */ public String getName() { - + return page.getName(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getParent() */ public Node getParent() { - + return page.getParent(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getPath() */ public String getPath() { - + return page.getPath(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getShortTitle(java.util.Locale) */ public String getShortTitle(Locale locale) { - + return page.getShortTitle(locale); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getTitle(java.util.Locale) */ public String getTitle(Locale locale) { - + return page.getTitle(locale); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getType() */ public String getType() { - + return page.getType(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getUrl() */ public String getUrl() { - + return page.getUrl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#isHidden() */ public boolean isHidden() { - + return page.isHidden(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#setHidden(boolean) */ public void setHidden(boolean hidden) { - + page.setHidden(hidden); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#setParent(org.apache.jetspeed.page.document.Node) */ public void setParent(Node parent) { - + page.setParent(parent); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#setPath(java.lang.String) */ public void setPath(String path) { - + page.setPath(path); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#checkAccess(java.lang.String) */ public void checkAccess(String actions) throws SecurityException { - + page.checkAccess(actions); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#checkConstraints(java.lang.String) */ public void checkConstraints(String actions) throws SecurityException { - + page.checkConstraints(actions); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#checkPermissions(int) */ public void checkPermissions(int mask) throws SecurityException { - + page.checkPermissions(mask); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getConstraintsEnabled() */ public boolean getConstraintsEnabled() { - + return page.getConstraintsEnabled(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getPermissionsEnabled() */ public boolean getPermissionsEnabled() { - + return page.getPermissionsEnabled(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getSecurityConstraints() */ public SecurityConstraints getSecurityConstraints() { - + return page.getSecurityConstraints(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#newSecurityConstraints() */ public SecurityConstraints newSecurityConstraints() { - + return page.newSecurityConstraints(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#newSecurityConstraint() */ public SecurityConstraint newSecurityConstraint() { - + return page.newSecurityConstraint(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#setSecurityConstraints(org.apache.jetspeed.om.common.SecurityConstraints) */ public void setSecurityConstraints(SecurityConstraints constraints) { - + page.setSecurityConstraints(constraints); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#getId() */ public String getId() { - + return page.getId(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#getShortTitle() */ public String getShortTitle() { - + return page.getShortTitle(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#getTitle() */ public String getTitle() { - + return page.getTitle(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#setShortTitle(java.lang.String) */ public void setShortTitle(String title) - { + { page.setShortTitle(title); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#setTitle(java.lang.String) */ public void setTitle(String title) { - + page.setTitle(title); } - + /** * getPage - access wrapped page - * + * * @return wrapped page */ public Page getPage() { return page; } - + public String getVersion() { return page.getVersion(); } - + public void setVersion(String version) { page.setVersion(version); } - - public boolean isDirty() { - return dirty; - } - - public void setDirty(boolean dirty) { - this.dirty = dirty; - } + public boolean isDirty() + { + return dirty; + } + + public void setDirty(boolean dirty) + { + this.dirty = dirty; + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/PageMetadataImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/PageMetadataImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/PageMetadataImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,11 +17,11 @@ package org.apache.jetspeed.om.page; import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; -import java.util.Collections; import org.apache.jetspeed.om.common.LocalizedField; import org.apache.jetspeed.om.impl.GenericMetadataImpl; @@ -33,6 +33,7 @@ */ public class PageMetadataImpl extends GenericMetadataImpl { + private Class fieldImplClass = PageLocalizedFieldImpl.class; public PageMetadataImpl() @@ -50,36 +51,45 @@ */ private Map localizedText; - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.GenericMetadata#createLocalizedField() */ public LocalizedField createLocalizedField() { try { - return (LocalizedField)fieldImplClass.newInstance(); + return (LocalizedField) fieldImplClass.newInstance(); } catch (Exception e) { - throw new RuntimeException("Failed to create LocalizedField object: " + fieldImplClass.getName(), e); + throw new RuntimeException( + "Failed to create LocalizedField object: " + + fieldImplClass.getName(), e); } } /** * getText - get localized text from metadata * - * @param name text name - * @param locale preferred locale + * @param name + * text name + * @param locale + * preferred locale * @return localized text or null if not available */ public String getText(String name, Locale locale) { // validate parameters - ArgUtil.assertNotNull(String.class, name, this, "getText(String, Locale)"); - ArgUtil.assertNotNull(Locale.class, locale, this, "getText(String, Locale)"); + ArgUtil.assertNotNull(String.class, name, this, + "getText(String, Locale)"); + ArgUtil.assertNotNull(Locale.class, locale, this, + "getText(String, Locale)"); // populate cache for named text by locale - Map namedLocalizedText = (Map)((localizedText != null) ? localizedText.get(name) : null); + Map namedLocalizedText = (Map) ((localizedText != null) ? localizedText + .get(name) : null); if ((namedLocalizedText == null) && (getFields() != null)) { Collection fields = getFields(name); @@ -87,14 +97,15 @@ { if (localizedText == null) { - localizedText = Collections.synchronizedMap(new HashMap(getFields().size())); + localizedText = Collections.synchronizedMap(new HashMap( + getFields().size())); } namedLocalizedText = new HashMap(getFields().size()); localizedText.put(name, namedLocalizedText); Iterator fieldsItr = fields.iterator(); while (fieldsItr.hasNext()) { - LocalizedField field = (LocalizedField)fieldsItr.next(); + LocalizedField field = (LocalizedField) fieldsItr.next(); namedLocalizedText.put(field.getLocale(), field); } } @@ -104,16 +115,12 @@ if (namedLocalizedText != null) { // test locale - if (namedLocalizedText.containsKey(locale) ) - { - return ((LocalizedField)namedLocalizedText.get(locale)).getValue().trim(); - } + if (namedLocalizedText.containsKey(locale)) { return ((LocalizedField) namedLocalizedText + .get(locale)).getValue().trim(); } // test language only locale Locale languageOnly = new Locale(locale.getLanguage()); - if (namedLocalizedText.containsKey(languageOnly)) - { - return ((LocalizedField)namedLocalizedText.get(languageOnly)).getValue().trim(); - } + if (namedLocalizedText.containsKey(languageOnly)) { return ((LocalizedField) namedLocalizedText + .get(languageOnly)).getValue().trim(); } } return null; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/SecurityConstraintImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/SecurityConstraintImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/SecurityConstraintImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,35 +24,44 @@ import org.apache.jetspeed.om.common.SecurityConstraint; import org.apache.jetspeed.page.impl.DatabasePageManagerUtils; - /** *

        * SecurityConstraintImpl *

        *

        - * + * *

        + * * @author Randy Watler * @version $Id: SecurityConstraintImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class SecurityConstraintImpl implements SecurityConstraint { + private int id; + private int applyOrder; + private List usersList; + private List rolesList; + private List groupsList; + private List permissionsList; private String users; + private String roles; + private String groups; + private String permissions; /** * getApplyOrder - * + * * @return apply order for constraints */ public int getApplyOrder() @@ -62,8 +71,9 @@ /** * setApplyOrder - * - * @param order apply order for constraints + * + * @param order + * apply order for constraints */ public void setApplyOrder(int order) { @@ -72,7 +82,7 @@ /** * getUsersAsString - * + * * @return users CSV list */ public String getUsersAsString() @@ -87,8 +97,9 @@ /** * setUsersAsString - * - * @param users users CSV list + * + * @param users + * users CSV list */ public void setUsersAsString(String users) { @@ -99,7 +110,7 @@ /** * getRolesAsString - * + * * @return roles CSV list */ public String getRolesAsString() @@ -111,11 +122,12 @@ } return roles; } - + /** * setRolesAsString - * - * @param roles roles CSV list + * + * @param roles + * roles CSV list */ public void setRolesAsString(String roles) { @@ -126,7 +138,7 @@ /** * getGroupsAsString - * + * * @return groups CSV list */ public String getGroupsAsString() @@ -138,11 +150,12 @@ } return groups; } - + /** * setGroupsAsString - * - * @param groups groups CSV list + * + * @param groups + * groups CSV list */ public void setGroupsAsString(String groups) { @@ -153,23 +166,25 @@ /** * getPermissionsAsString - * + * * @return permissions CSV list */ public String getPermissionsAsString() { // get from permissions list if not immediately available - if ((permissions == null) && (permissionsList != null) && !permissionsList.isEmpty()) + if ((permissions == null) && (permissionsList != null) + && !permissionsList.isEmpty()) { permissions = formatCSVList(permissionsList); } return permissions; } - + /** * setPermissionsAsString - * - * @param permissions permissions CSV list + * + * @param permissions + * permissions CSV list */ public void setPermissionsAsString(String permissions) { @@ -177,12 +192,12 @@ this.permissions = permissions; permissionsList = parseCSVList(permissions); } - + /** *

        * getUsers *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraint#getUsers() * @return users list */ @@ -190,14 +205,15 @@ { return usersList; } - + /** *

        * setUsers *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraint#setUsers(java.util.List) - * @param users users list + * @param users + * users list */ public void setUsers(List users) { @@ -210,7 +226,7 @@ *

        * getRoles *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraint#getRoles() * @return roles list */ @@ -218,14 +234,15 @@ { return rolesList; } - + /** *

        * setRoles *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraint#setRoles(java.util.List) - * @param roles roles list + * @param roles + * roles list */ public void setRoles(List roles) { @@ -238,7 +255,7 @@ *

        * getGroups *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraint#getGroups() * @return groups list */ @@ -246,14 +263,15 @@ { return groupsList; } - + /** *

        * setGroups *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraint#setGroups(java.util.List) - * @param groups groups list + * @param groups + * groups list */ public void setGroups(List groups) { @@ -266,7 +284,7 @@ *

        * getPermissions *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraint#getPermissions() * @return permissions list */ @@ -274,14 +292,15 @@ { return permissionsList; } - + /** *

        * setPermissions *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraint#setPermissions(java.util.List) - * @param permissions permissions list + * @param permissions + * permissions list */ public void setPermissions(List permissions) { @@ -297,24 +316,27 @@ *

        * Test user/role/group names against principal names. *

        - * + * * @param userPrincipals * @param rolePrincipals * @param groupPrincipals * @param allowDefault * @return match result */ - public boolean principalsMatch(List userPrincipals, List rolePrincipals, List groupPrincipals, boolean allowDefault) + public boolean principalsMatch(List userPrincipals, List rolePrincipals, + List groupPrincipals, boolean allowDefault) { // test match using users, roles, and groups list members // since these are the master representation in this impl - return ((allowDefault && (usersList == null) && (rolesList == null) && (groupsList == null)) || - ((usersList != null) && (userPrincipals != null) && - (containsAny(usersList, userPrincipals) || usersList.contains(WILD_CHAR))) || - ((rolesList != null) && (rolePrincipals != null) && - (containsAny(rolesList, rolePrincipals) || rolesList.contains(WILD_CHAR))) || - ((groupsList != null) && (groupPrincipals != null) && - (containsAny(groupsList, groupPrincipals) || groupsList.contains(WILD_CHAR)))); + return ((allowDefault && (usersList == null) && (rolesList == null) && (groupsList == null)) + || ((usersList != null) && (userPrincipals != null) && (containsAny( + usersList, userPrincipals) || usersList + .contains(WILD_CHAR))) + || ((rolesList != null) && (rolePrincipals != null) && (containsAny( + rolesList, rolePrincipals) || rolesList + .contains(WILD_CHAR))) || ((groupsList != null) + && (groupPrincipals != null) && (containsAny(groupsList, + groupPrincipals) || groupsList.contains(WILD_CHAR)))); } /** @@ -324,7 +346,7 @@ *

        * Test permission names against action name. *

        - * + * * @param action * @return match result */ @@ -332,8 +354,8 @@ { // test match using permissions list member since // this is the master representation in this impl - return ((permissionsList != null) && - (permissionsList.contains(action) || permissionsList.contains(WILD_CHAR))); + return ((permissionsList != null) && (permissionsList.contains(action) || permissionsList + .contains(WILD_CHAR))); } /** @@ -343,7 +365,7 @@ *

        * Utility to parse CSV string values into Lists. *

        - * + * * @param csv * @return parsed values list. */ @@ -376,7 +398,7 @@ *

        * Utility to format CSV List values into strings. *

        - * + * * @param list * @return formatted string value. */ @@ -392,7 +414,7 @@ { csv.append(","); } - csv.append((String)listIter.next()); + csv.append((String) listIter.next()); } return csv.toString(); } @@ -406,22 +428,20 @@ *

        * Utility implementation for contains any test against two collections. *

        - * + * * @param collection0 * @param collection1 * @return contains any result. */ - public static boolean containsAny(Collection collection0, Collection collection1) + public static boolean containsAny(Collection collection0, + Collection collection1) { if ((collection0 != null) && (collection1 != null)) { Iterator containsIter = collection1.iterator(); while (containsIter.hasNext()) { - if (collection0.contains(containsIter.next())) - { - return true; - } + if (collection0.contains(containsIter.next())) { return true; } } } return false; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/BaseElementImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/BaseElementImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/BaseElementImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -41,19 +41,25 @@ /** * BaseElementImpl - * + * * @author Randy Watler * @version $Id$ */ public abstract class BaseElementImpl implements BaseElement { + private int id; + private String name; + private String title; + private String shortTitle; + private SecurityConstraintsImpl constraints; private boolean constraintsEnabled; + private boolean permissionsEnabled; protected BaseElementImpl(SecurityConstraintsImpl constraints) @@ -63,7 +69,7 @@ /** * getName - * + * * @return element name */ public String getName() @@ -73,8 +79,9 @@ /** * setName - * - * @param name element name + * + * @param name + * element name */ public void setName(String name) { @@ -83,18 +90,20 @@ /** * setConstraintsEnabled - * - * @param enabled enable/disable security constraints checks + * + * @param enabled + * enable/disable security constraints checks */ public void setConstraintsEnabled(boolean enabled) { constraintsEnabled = enabled; } - + /** * setPermissionsEnabled - * - * @param enabled enable/disable security permissions checks + * + * @param enabled + * enable/disable security permissions checks */ public void setPermissionsEnabled(boolean enabled) { @@ -103,7 +112,7 @@ /** * grantViewActionAccess - * + * * @return granted access for view action */ public boolean grantViewActionAccess() @@ -114,7 +123,7 @@ /** * getEffectivePageSecurity - * + * * @return effective page security object */ public PageSecurity getEffectivePageSecurity() @@ -125,29 +134,40 @@ /** * checkConstraints - * - * Check fully parameterized principal against specified security constraint scope. - * - * @param actions actions to check - * @param userPrincipals principal users list - * @param rolePrincipals principal roles list - * @param groupPrincipals principal group list - * @param checkNodeOnly check node scope only - * @param checkParentsOnly check parent folder scope only + * + * Check fully parameterized principal against specified security constraint + * scope. + * + * @param actions + * actions to check + * @param userPrincipals + * principal users list + * @param rolePrincipals + * principal roles list + * @param groupPrincipals + * principal group list + * @param checkNodeOnly + * check node scope only + * @param checkParentsOnly + * check parent folder scope only * @throws SecurityException */ - public void checkConstraints(List actions, List userPrincipals, List rolePrincipals, List groupPrincipals, boolean checkNodeOnly, boolean checkParentsOnly) throws SecurityException + public void checkConstraints(List actions, List userPrincipals, + List rolePrincipals, List groupPrincipals, boolean checkNodeOnly, + boolean checkParentsOnly) throws SecurityException { // check node constraints if available if ((constraints != null) && !constraints.isEmpty()) { - constraints.checkConstraints(actions, userPrincipals, rolePrincipals, groupPrincipals, getEffectivePageSecurity()); + constraints + .checkConstraints(actions, userPrincipals, rolePrincipals, + groupPrincipals, getEffectivePageSecurity()); } } /** * getLogicalPermissionPath - * + * * @return path used for permissions checks */ public String getLogicalPermissionPath() @@ -158,7 +178,7 @@ /** * getPhysicalPermissionPath - * + * * @return path used for permissions checks */ public String getPhysicalPermissionPath() @@ -169,13 +189,17 @@ /** * checkPermissions - * - * @param mask mask of actions to check - * @param checkNodeOnly check node scope only - * @param checkParentsOnly check parent folder scope only + * + * @param mask + * mask of actions to check + * @param checkNodeOnly + * check node scope only + * @param checkParentsOnly + * check parent folder scope only * @throws SecurityException */ - public void checkPermissions(int mask, boolean checkNodeOnly, boolean checkParentsOnly) throws SecurityException + public void checkPermissions(int mask, boolean checkNodeOnly, + boolean checkParentsOnly) throws SecurityException { // check page and folder permissions String physicalPermissionPath = getPhysicalPermissionPath(); @@ -184,15 +208,19 @@ // check permissions using physical path try { - checkPermissions(physicalPermissionPath, mask, checkNodeOnly, checkParentsOnly); + checkPermissions(physicalPermissionPath, mask, checkNodeOnly, + checkParentsOnly); } catch (SecurityException physicalSE) { // fallback check using logical path if available and different String logicalPermissionPath = getLogicalPermissionPath(); - if ((logicalPermissionPath != null) && !logicalPermissionPath.equals(physicalPermissionPath)) + if ((logicalPermissionPath != null) + && !logicalPermissionPath + .equals(physicalPermissionPath)) { - checkPermissions(logicalPermissionPath, mask, checkNodeOnly, checkParentsOnly); + checkPermissions(logicalPermissionPath, mask, + checkNodeOnly, checkParentsOnly); } else { @@ -204,14 +232,19 @@ /** * checkPermissions - * - * @param path permissions path to check - * @param mask mask of actions to check - * @param checkNodeOnly check node scope only - * @param checkParentsOnly check parent folder scope only + * + * @param path + * permissions path to check + * @param mask + * mask of actions to check + * @param checkNodeOnly + * check node scope only + * @param checkParentsOnly + * check parent folder scope only * @throws SecurityException */ - public void checkPermissions(String path, int mask, boolean checkNodeOnly, boolean checkParentsOnly) throws SecurityException + public void checkPermissions(String path, int mask, boolean checkNodeOnly, + boolean checkParentsOnly) throws SecurityException { // check actions permissions try @@ -228,24 +261,30 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getConstraintsEnabled() */ public boolean getConstraintsEnabled() { return constraintsEnabled; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { // compare element by id - return ((o != null) && getClass().equals(o.getClass()) && (id != 0) && (id == ((BaseElementImpl)o).id)); + return ((o != null) && getClass().equals(o.getClass()) && (id != 0) && (id == ((BaseElementImpl) o).id)); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#hashCode() */ public int hashCode() @@ -254,15 +293,19 @@ return id; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getSecurityConstraints() */ public SecurityConstraints getSecurityConstraints() { return constraints; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#newSecurityConstraints() */ public SecurityConstraints newSecurityConstraints() @@ -273,61 +316,73 @@ return new SecurityConstraintsImpl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#newSecurityConstraint() */ public SecurityConstraint newSecurityConstraint() { // return constraints specific security constraint instance - if ((constraints != null) && (constraints.getSecurityConstraintClass() != null)) + if ((constraints != null) + && (constraints.getSecurityConstraintClass() != null)) { try { - return (SecurityConstraintImpl)constraints.getSecurityConstraintClass().newInstance(); + return (SecurityConstraintImpl) constraints + .getSecurityConstraintClass().newInstance(); } catch (InstantiationException ie) { - throw new ClassCastException("Unable to create security constraint instance: " + constraints.getSecurityConstraintClass().getName() + ", (" + ie + ")."); + throw new ClassCastException( + "Unable to create security constraint instance: " + + constraints.getSecurityConstraintClass() + .getName() + ", (" + ie + ")."); } catch (IllegalAccessException iae) { - throw new ClassCastException("Unable to create security constraint instance: " + constraints.getSecurityConstraintClass().getName() + ", (" + iae + ")."); + throw new ClassCastException( + "Unable to create security constraint instance: " + + constraints.getSecurityConstraintClass() + .getName() + ", (" + iae + ")."); } } // return universal security constraint instance return new SecurityConstraintImpl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#setSecurityConstraints(org.apache.jetspeed.om.common.SecurityConstraints) */ public void setSecurityConstraints(SecurityConstraints constraints) { if (this.constraints != null) { - // set constraints configuration in nested om implementation instance + // set constraints configuration in nested om implementation + // instance this.constraints.setOwner(constraints.getOwner()); - this.constraints.setSecurityConstraints(constraints.getSecurityConstraints()); - this.constraints.setSecurityConstraintsRefs(constraints.getSecurityConstraintsRefs()); + this.constraints.setSecurityConstraints(constraints + .getSecurityConstraints()); + this.constraints.setSecurityConstraintsRefs(constraints + .getSecurityConstraintsRefs()); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#checkConstraints(java.lang.String) */ public void checkConstraints(String actions) throws SecurityException { // skip checks if not enabled - if (!getConstraintsEnabled()) - { - return; - } + if (!getConstraintsEnabled()) { return; } // validate specified actions - if (actions == null) - { - throw new SecurityException("BaseElementImpl.checkConstraints(): No actions specified."); - } + if (actions == null) { throw new SecurityException( + "BaseElementImpl.checkConstraints(): No actions specified."); } // get action names lists; separate view and other // actions to mimic file system permissions logic @@ -354,10 +409,8 @@ // get current request context subject Subject subject = JSSubject.getSubject(AccessController.getContext()); - if (subject == null) - { - throw new SecurityException("BaseElementImpl.checkConstraints(): Missing JSSubject."); - } + if (subject == null) { throw new SecurityException( + "BaseElementImpl.checkConstraints(): Missing JSSubject."); } // get user/group/role principal names List userPrincipals = null; @@ -396,11 +449,13 @@ // check constraints using parsed action and access lists if (viewActionList != null) { - checkConstraints(viewActionList, userPrincipals, rolePrincipals, groupPrincipals, false, grantViewActionAccess()); + checkConstraints(viewActionList, userPrincipals, rolePrincipals, + groupPrincipals, false, grantViewActionAccess()); } if (otherActionsList != null) { - checkConstraints(otherActionsList, userPrincipals, rolePrincipals, groupPrincipals, true, false); + checkConstraints(otherActionsList, userPrincipals, rolePrincipals, + groupPrincipals, true, false); } } @@ -416,33 +471,36 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getPermissionsEnabled() */ public boolean getPermissionsEnabled() { return permissionsEnabled; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#checkPermissions(java.lang.String) */ public void checkPermissions(int mask) throws SecurityException { // skip checks if not enabled - if (!getPermissionsEnabled()) - { - return; - } + if (!getPermissionsEnabled()) { return; } - // separate view and other actions to mimic file system permissions logic + // separate view and other actions to mimic file system permissions + // logic boolean viewAction = (mask & JetspeedActions.MASK_VIEW) == JetspeedActions.MASK_VIEW; int otherMask = mask & ~JetspeedActions.MASK_VIEW; // check permissions using parsed actions if (viewAction) { - checkPermissions(JetspeedActions.MASK_VIEW, false, grantViewActionAccess()); + checkPermissions(JetspeedActions.MASK_VIEW, false, + grantViewActionAccess()); } if (otherMask != 0) { @@ -450,7 +508,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#checkAccess(java.lang.String) */ public void checkAccess(String actions) throws SecurityException @@ -467,7 +527,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#getId() */ public String getId() @@ -475,7 +537,9 @@ return Integer.toString(id); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#getTitle() */ public String getTitle() @@ -483,7 +547,9 @@ return title; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#setTitle(java.lang.String) */ public void setTitle(String title) @@ -491,7 +557,9 @@ this.title = title; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#getShortTitle() */ public String getShortTitle() @@ -499,7 +567,9 @@ return shortTitle; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#setShortTitle(java.lang.String) */ public void setShortTitle(String shortTitle) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/BaseSecurityConstraintsRef.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/BaseSecurityConstraintsRef.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/BaseSecurityConstraintsRef.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,19 +18,22 @@ /** * BaseSecurityConstraintsRef - * + * * @author Randy Watler * @version $Id$ */ public class BaseSecurityConstraintsRef { + private int id; + private int applyOrder; + private String name; /** * getApplyOrder - * + * * @return apply order for constraints */ public int getApplyOrder() @@ -40,8 +43,9 @@ /** * setApplyOrder - * - * @param order apply order for constraints + * + * @param order + * apply order for constraints */ public void setApplyOrder(int order) { @@ -50,7 +54,7 @@ /** * getName - * + * * @return name of referenced constraint */ public String getName() @@ -60,39 +64,39 @@ /** * setName - * - * @param name name of referenced constraint + * + * @param name + * name of referenced constraint */ public void setName(String name) { this.name = name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o instanceof BaseSecurityConstraintsRef) { - if (name != null) - { - return name.equals(((BaseSecurityConstraintsRef)o).getName()); - } - return (((BaseSecurityConstraintsRef)o).getName() == null); + if (name != null) { return name + .equals(((BaseSecurityConstraintsRef) o).getName()); } + return (((BaseSecurityConstraintsRef) o).getName() == null); } return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#hashCode() */ public int hashCode() { - if (name != null) - { - return name.hashCode(); - } + if (name != null) { return name.hashCode(); } return 0; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FilteredFragmentList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FilteredFragmentList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FilteredFragmentList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,13 +22,15 @@ /** * FragmentList - * + * * @author Randy Watler * @version $Id$ */ class FilteredFragmentList extends AbstractList { + private FragmentImpl fragment; + private List filteredList; FilteredFragmentList(FragmentImpl fragment, List filteredList) @@ -38,7 +40,9 @@ this.filteredList = filteredList; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) @@ -50,11 +54,13 @@ // maintain page implementation reference if ((fragment.getPage() != null) && (element instanceof FragmentImpl)) { - ((FragmentImpl)element).setPage(fragment.getPage()); + ((FragmentImpl) element).setPage(fragment.getPage()); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) @@ -63,7 +69,9 @@ return filteredList.get(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) @@ -86,7 +94,9 @@ return o; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) @@ -109,12 +119,14 @@ // maintain page implementation reference if ((fragment.getPage() != null) && (element instanceof FragmentImpl)) { - ((FragmentImpl)element).setPage(fragment.getPage()); + ((FragmentImpl) element).setPage(fragment.getPage()); } return o; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,35 +30,57 @@ /** * FragmentImpl - * + * * @author Randy Watler * @version $Id$ */ public class FragmentImpl extends BaseElementImpl implements Fragment { + private List fragments; + private String type; + private String skin; + private String decorator; + private String state; + private String mode; + private int layoutRowProperty = -1; + private int layoutColumnProperty = -1; + private String layoutSizesProperty; + private float layoutXProperty = -1.0F; + private float layoutYProperty = -1.0F; + private float layoutZProperty = -1.0F; + private float layoutWidthProperty = -1.0F; + private float layoutHeightProperty = -1.0F; + private String extendedPropertyName1; + private String extendedPropertyValue1; + private String extendedPropertyName2; + private String extendedPropertyValue2; + private List preferences; private FragmentList fragmentsList; + private FragmentPropertyMap propertiesMap; + private FragmentPreferenceList fragmentPreferences; + private PageImpl page; public FragmentImpl() @@ -68,9 +90,9 @@ /** * accessFragments - * + * * Access mutable persistent collection member for List wrappers. - * + * * @return persistent collection */ List accessFragments() @@ -85,9 +107,9 @@ /** * accessPreferences - * + * * Access mutable persistent collection member for List wrappers. - * + * * @return persistent collection */ List accessPreferences() @@ -102,9 +124,9 @@ /** * getPage - * + * * Get page implementation that owns fragment. - * + * * @return owning page implementation */ PageImpl getPage() @@ -114,11 +136,12 @@ /** * setPage - * - * Set page implementation that owns fragment and - * propagate to all child fragments. - * - * @param page owning page implementation + * + * Set page implementation that owns fragment and propagate to all child + * fragments. + * + * @param page + * owning page implementation */ void setPage(PageImpl page) { @@ -130,38 +153,33 @@ Iterator fragmentsIter = fragments.iterator(); while (fragmentsIter.hasNext()) { - ((FragmentImpl)fragmentsIter.next()).setPage(page); + ((FragmentImpl) fragmentsIter.next()).setPage(page); } } } /** * getFragmentById - * - * Retrieve fragment with matching id from - * this or child fragments. - * - * @param id fragment id to retrieve. + * + * Retrieve fragment with matching id from this or child fragments. + * + * @param id + * fragment id to retrieve. * @return matched fragment */ Fragment getFragmentById(String id) { // check for match - if (getId().equals(id)) - { - return this; - } + if (getId().equals(id)) { return this; } // match children if (fragments != null) { Iterator fragmentsIter = fragments.iterator(); while (fragmentsIter.hasNext()) { - Fragment matchedFragment = ((FragmentImpl)fragmentsIter.next()).getFragmentById(id); - if (matchedFragment != null) - { - return matchedFragment; - } + Fragment matchedFragment = ((FragmentImpl) fragmentsIter.next()) + .getFragmentById(id); + if (matchedFragment != null) { return matchedFragment; } } } return null; @@ -169,11 +187,11 @@ /** * removeFragmentById - * - * Remove fragment with matching id from - * child fragments. - * - * @param id fragment id to remove. + * + * Remove fragment with matching id from child fragments. + * + * @param id + * fragment id to remove. * @return removed fragment */ Fragment removeFragmentById(String id) @@ -184,14 +202,11 @@ Iterator fragmentsIter = fragments.iterator(); while (fragmentsIter.hasNext()) { - FragmentImpl fragment = (FragmentImpl)fragmentsIter.next(); + FragmentImpl fragment = (FragmentImpl) fragmentsIter.next(); if (!fragment.getId().equals(id)) { Fragment removed = fragment.removeFragmentById(id); - if (removed != null) - { - return removed; - } + if (removed != null) { return removed; } } else { @@ -205,11 +220,11 @@ /** * getFragmentsByName - * - * Retrieve fragments with matching name including - * this and child fragments. - * - * @param name fragment name to retrieve. + * + * Retrieve fragments with matching name including this and child fragments. + * + * @param name + * fragment name to retrieve. * @return list of matched fragments */ List getFragmentsByName(String name) @@ -230,7 +245,8 @@ Iterator fragmentsIter = fragments.iterator(); while (fragmentsIter.hasNext()) { - List matchedChildFragments = ((FragmentImpl)fragmentsIter.next()).getFragmentsByName(name); + List matchedChildFragments = ((FragmentImpl) fragmentsIter + .next()).getFragmentsByName(name); if (matchedChildFragments != null) { if (matchedFragments == null) @@ -249,9 +265,9 @@ /** * getPropertyMemberKeys - * + * * Get valid explicit property member keys. - * + * * @return list of property member keys with values */ List getPropertyMemberKeys() @@ -302,10 +318,11 @@ /** * getPropertyMember - * + * * Get explicit property member. - * - * @param key property name + * + * @param key + * property name * @return property setting */ String getPropertyMember(String key) @@ -313,17 +330,13 @@ // set fragment explicit property member if (key.equals(ROW_PROPERTY_NAME)) { - if (layoutRowProperty >= 0) - { - return String.valueOf(layoutRowProperty); - } + if (layoutRowProperty >= 0) { return String + .valueOf(layoutRowProperty); } } else if (key.equals(COLUMN_PROPERTY_NAME)) { - if (layoutColumnProperty >= 0) - { - return String.valueOf(layoutColumnProperty); - } + if (layoutColumnProperty >= 0) { return String + .valueOf(layoutColumnProperty); } } else if (key.equals(SIZES_PROPERTY_NAME)) { @@ -331,57 +344,46 @@ } else if (key.equals(X_PROPERTY_NAME)) { - if (layoutXProperty >= 0.0F) - { - return String.valueOf(layoutXProperty); - } + if (layoutXProperty >= 0.0F) { return String + .valueOf(layoutXProperty); } } else if (key.equals(Y_PROPERTY_NAME)) { - if (layoutYProperty >= 0.0F) - { - return String.valueOf(layoutYProperty); - } + if (layoutYProperty >= 0.0F) { return String + .valueOf(layoutYProperty); } } else if (key.equals(Z_PROPERTY_NAME)) { - if (layoutZProperty >= 0.0F) - { - return String.valueOf(layoutZProperty); - } + if (layoutZProperty >= 0.0F) { return String + .valueOf(layoutZProperty); } } else if (key.equals(WIDTH_PROPERTY_NAME)) { - if (layoutWidthProperty >= 0.0F) - { - return String.valueOf(layoutWidthProperty); - } + if (layoutWidthProperty >= 0.0F) { return String + .valueOf(layoutWidthProperty); } } else if (key.equals(HEIGHT_PROPERTY_NAME)) { - if (layoutHeightProperty >= 0.0F) - { - return String.valueOf(layoutHeightProperty); - } + if (layoutHeightProperty >= 0.0F) { return String + .valueOf(layoutHeightProperty); } } else if (key.equals(extendedPropertyName1)) { return extendedPropertyValue1; } - else if (key.equals(extendedPropertyName2)) - { - return extendedPropertyValue2; - } + else if (key.equals(extendedPropertyName2)) { return extendedPropertyValue2; } return null; } /** * setPropertyMember - * + * * Set explicit property member. - * - * @param key property name - * @param value property setting + * + * @param key + * property name + * @param value + * property setting */ void setPropertyMember(String key, String value) { @@ -438,16 +440,18 @@ } else { - throw new RuntimeException("Unable to set fragment property " + key + ", extended properties already used."); + throw new RuntimeException("Unable to set fragment property " + key + + ", extended properties already used."); } } /** * clearPropertyMember - * + * * Clear explicit property member. - * - * @param key property name + * + * @param key + * property name */ void clearPropertyMember(String key) { @@ -495,46 +499,49 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#getEffectivePageSecurity() */ public PageSecurity getEffectivePageSecurity() { // delegate to page implementation - if (page != null) - { - return page.getEffectivePageSecurity(); - } + if (page != null) { return page.getEffectivePageSecurity(); } return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#getLogicalPermissionPath() */ public String getLogicalPermissionPath() { // use page implementation path as base and append name - if ((page != null) && (getName() != null)) - { - return page.getLogicalPermissionPath() + Folder.PATH_SEPARATOR + getName(); - } + if ((page != null) && (getName() != null)) { return page + .getLogicalPermissionPath() + + Folder.PATH_SEPARATOR + getName(); } return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#getPhysicalPermissionPath() */ public String getPhysicalPermissionPath() { // use page implementation path as base and append name - if ((page != null) && (getName() != null)) - { - return page.getPhysicalPermissionPath() + Folder.PATH_SEPARATOR + getName(); - } + if ((page != null) && (getName() != null)) { return page + .getPhysicalPermissionPath() + + Folder.PATH_SEPARATOR + getName(); } return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#resetCachedSecurityConstraints() */ public void resetCachedSecurityConstraints() @@ -546,54 +553,61 @@ Iterator fragmentsIter = fragments.iterator(); while (fragmentsIter.hasNext()) { - ((FragmentImpl)fragmentsIter.next()).resetCachedSecurityConstraints(); + ((FragmentImpl) fragmentsIter.next()) + .resetCachedSecurityConstraints(); } } } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#checkPermissions(java.lang.String, int, boolean, boolean) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#checkPermissions(java.lang.String, + * int, boolean, boolean) */ - public void checkPermissions(String path, int mask, boolean checkNodeOnly, boolean checkParentsOnly) throws SecurityException + public void checkPermissions(String path, int mask, boolean checkNodeOnly, + boolean checkParentsOnly) throws SecurityException { // always check for granted fragment permissions FragmentPermission permission = new FragmentPermission(path, mask); AccessController.checkPermission(permission); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getConstraintsEnabled() */ public boolean getConstraintsEnabled() { - if (page != null) - { - return page.getConstraintsEnabled(); - } + if (page != null) { return page.getConstraintsEnabled(); } return false; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getPermissionsEnabled() */ public boolean getPermissionsEnabled() { - if (page != null) - { - return page.getPermissionsEnabled(); - } + if (page != null) { return page.getPermissionsEnabled(); } return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getType() */ public String getType() { return type; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setType(java.lang.String) */ public void setType(String type) @@ -601,15 +615,19 @@ this.type = type; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getSkin() */ public String getSkin() { return skin; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setSkin(java.lang.String) */ public void setSkin(String skinName) @@ -617,15 +635,19 @@ this.skin = skinName; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getDecorator() */ public String getDecorator() { return decorator; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setDecorator(java.lang.String) */ public void setDecorator(String decoratorName) @@ -633,15 +655,19 @@ this.decorator = decoratorName; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getState() */ public String getState() { return state; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setState(java.lang.String) */ public void setState(String state) @@ -649,15 +675,19 @@ this.state = state; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getMode() */ public String getMode() { return mode; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setMode(java.lang.String) */ public void setMode(String mode) @@ -665,7 +695,9 @@ this.mode = mode; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getFragments() */ public List getFragments() @@ -678,42 +710,44 @@ } return filterFragmentsByAccess(fragmentsList, true); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getProperty(java.lang.String) */ public String getProperty(String propName) { - return (String)getProperties().get(propName); + return (String) getProperties().get(propName); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getIntProperty(java.lang.String) */ public int getIntProperty(String propName) { - String propValue = (String)getProperties().get(propName); - if (propValue != null) - { - return Integer.parseInt(propValue); - } + String propValue = (String) getProperties().get(propName); + if (propValue != null) { return Integer.parseInt(propValue); } return -1; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getFloatProperty(java.lang.String) */ public float getFloatProperty(String propName) { - String propValue = (String)getProperties().get(propName); - if (propValue != null) - { - return Float.parseFloat(propValue); - } + String propValue = (String) getProperties().get(propName); + if (propValue != null) { return Float.parseFloat(propValue); } return -1.0F; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getProperties() */ public Map getProperties() @@ -725,8 +759,10 @@ } return propertiesMap; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutRow() */ public int getLayoutRow() @@ -734,8 +770,10 @@ // get standard int property return getIntProperty(ROW_PROPERTY_NAME); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutRow(int) */ public void setLayoutRow(int row) @@ -750,8 +788,10 @@ getProperties().remove(ROW_PROPERTY_NAME); } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutColumn() */ public int getLayoutColumn() @@ -759,8 +799,10 @@ // get standard int property return getIntProperty(COLUMN_PROPERTY_NAME); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutColumn(int) */ public void setLayoutColumn(int column) @@ -776,7 +818,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutSizes() */ public String getLayoutSizes() @@ -784,8 +828,10 @@ // get standard string property return getProperty(SIZES_PROPERTY_NAME); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutSizes(java.lang.String) */ public void setLayoutSizes(String sizes) @@ -800,8 +846,10 @@ getProperties().remove(SIZES_PROPERTY_NAME); } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutX() */ public float getLayoutX() @@ -809,8 +857,10 @@ // get standard float property return getFloatProperty(X_PROPERTY_NAME); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutX(float) */ public void setLayoutX(float x) @@ -825,8 +875,10 @@ getProperties().remove(X_PROPERTY_NAME); } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutY() */ public float getLayoutY() @@ -834,8 +886,10 @@ // get standard float property return getFloatProperty(Y_PROPERTY_NAME); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutY(float) */ public void setLayoutY(float y) @@ -851,7 +905,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutZ() */ public float getLayoutZ() @@ -859,8 +915,10 @@ // get standard float property return getFloatProperty(Z_PROPERTY_NAME); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutZ(float) */ public void setLayoutZ(float z) @@ -876,7 +934,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutWidth() */ public float getLayoutWidth() @@ -884,8 +944,10 @@ // get standard float property return getFloatProperty(WIDTH_PROPERTY_NAME); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutWidth(float) */ public void setLayoutWidth(float width) @@ -901,7 +963,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutHeight() */ public float getLayoutHeight() @@ -909,8 +973,10 @@ // get standard float property return getFloatProperty(HEIGHT_PROPERTY_NAME); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutHeight(float) */ public void setLayoutHeight(float height) @@ -926,15 +992,19 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#isReference() */ public boolean isReference() { return false; // NYI } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getPreferences() */ public List getPreferences() @@ -948,8 +1018,10 @@ } return fragmentPreferences; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setPreferences(java.util.List) */ public void setPreferences(List preferences) @@ -968,16 +1040,18 @@ } } } - + /** * filterFragmentsByAccess - * + * * Filter fragments list for view access. - * - * @param nodes list containing fragments to check - * @param mutable make returned list mutable - * @return original list if all elements viewable, a filtered - * partial list, or null if all filtered for view access + * + * @param nodes + * list containing fragments to check + * @param mutable + * make returned list mutable + * @return original list if all elements viewable, a filtered partial list, + * or null if all filtered for view access */ List filterFragmentsByAccess(List fragments, boolean mutable) { @@ -988,7 +1062,7 @@ Iterator checkAccessIter = fragments.iterator(); while (checkAccessIter.hasNext()) { - Fragment fragment = (Fragment)checkAccessIter.next(); + Fragment fragment = (Fragment) checkAccessIter.next(); try { // check access @@ -1007,12 +1081,14 @@ if (filteredFragments == null) { // not permitted, copy previously permitted fragments - // to new filteredFragments node set with same comparator - filteredFragments = DatabasePageManagerUtils.createList(); + // to new filteredFragments node set with same + // comparator + filteredFragments = DatabasePageManagerUtils + .createList(); Iterator copyIter = fragments.iterator(); while (copyIter.hasNext()) { - Fragment copyFragment = (Fragment)copyIter.next(); + Fragment copyFragment = (Fragment) copyIter.next(); if (copyFragment != fragment) { filteredFragments.add(copyFragment); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,12 +20,13 @@ /** * FragmentList - * + * * @author Randy Watler * @version $Id$ */ class FragmentList extends AbstractList { + private FragmentImpl fragment; FragmentList(FragmentImpl fragment) @@ -34,7 +35,9 @@ this.fragment = fragment; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) @@ -44,11 +47,13 @@ fragment.accessFragments().add(index, element); if ((fragment.getPage() != null) && (element instanceof FragmentImpl)) { - ((FragmentImpl)element).setPage(fragment.getPage()); + ((FragmentImpl) element).setPage(fragment.getPage()); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) @@ -57,7 +62,9 @@ return fragment.accessFragments().get(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) @@ -66,7 +73,9 @@ return fragment.accessFragments().remove(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) @@ -76,12 +85,14 @@ Object o = fragment.accessFragments().set(index, element); if ((fragment.getPage() != null) && (element instanceof FragmentImpl)) { - ((FragmentImpl)element).setPage(fragment.getPage()); + ((FragmentImpl) element).setPage(fragment.getPage()); } return o; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,24 +26,29 @@ /** * FragmentPreferenceImpl - * + * * @author Randy Watler * @version $Id$ */ -public class FragmentPreferenceImpl implements Preference, PreferenceCtrl, FragmentPreference +public class FragmentPreferenceImpl implements Preference, PreferenceCtrl, + FragmentPreference { + private int id; + private String name; + private boolean readOnly; + private List values; private FragmentPreferenceValueList preferenceValues; /** * accessValues - * + * * Access mutable persistent collection member for List wrappers. - * + * * @return persistent collection */ List accessValues() @@ -56,7 +61,9 @@ return values; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.preference.FragmentPreference#getName() * @see org.apache.pluto.om.common.Preference#getName() */ @@ -65,7 +72,9 @@ return name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.preference.FragmentPreference#setName(java.lang.String) * @see org.apache.pluto.om.common.PreferenceCtrl#setName(java.lang.String) */ @@ -74,7 +83,9 @@ this.name = name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.preference.FragmentPreference#isReadOnly() * @see org.apache.pluto.om.common.Preference#isReadOnly() */ @@ -83,7 +94,9 @@ return readOnly; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.preference.FragmentPreference#setReadOnly(boolean) */ public void setReadOnly(boolean readOnly) @@ -91,7 +104,9 @@ this.readOnly = readOnly; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.preference.FragmentPreference#getValueList() */ public List getValueList() @@ -104,8 +119,10 @@ } return preferenceValues; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.preference.FragmentPreference#setValueList(java.util.List) */ public void setValueList(List values) @@ -125,7 +142,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.pluto.om.common.Preference#getValues() */ public Iterator getValues() @@ -133,7 +152,9 @@ return getValueList().iterator(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.pluto.om.common.Preference#isValueSet() */ public boolean isValueSet() @@ -141,7 +162,9 @@ return !getValueList().isEmpty(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.pluto.om.common.PreferenceCtrl#setValues(java.util.List) */ public void setValues(List values) @@ -149,7 +172,9 @@ setValueList(values); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.pluto.om.common.PreferenceCtrl#setReadOnly(java.lang.String) */ public void setReadOnly(String readOnly) @@ -157,31 +182,30 @@ setReadOnly(new Boolean(readOnly).booleanValue()); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o instanceof FragmentPreferenceImpl) { - if (name != null) - { - return name.equals(((FragmentPreferenceImpl)o).getName()); - } - return (((FragmentPreferenceImpl)o).getName() == null); + if (name != null) { return name.equals(((FragmentPreferenceImpl) o) + .getName()); } + return (((FragmentPreferenceImpl) o).getName() == null); } return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#hashCode() */ public int hashCode() { - if (name != null) - { - return name.hashCode(); - } + if (name != null) { return name.hashCode(); } return 0; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,16 +18,18 @@ import java.util.AbstractList; import java.util.List; + import org.apache.jetspeed.page.impl.DatabasePageManagerUtils; /** * FragmentPreferenceList - * + * * @author Randy Watler * @version $Id$ */ class FragmentPreferenceList extends AbstractList { + private FragmentImpl fragment; private List removedPreferences; @@ -40,24 +42,23 @@ /** * validatePreferenceForAdd - * + * * Validates preference to be added to this list. - * - * @param preference preference to add + * + * @param preference + * preference to add * @return list element to add */ - private FragmentPreferenceImpl validatePreferenceForAdd(FragmentPreferenceImpl preference) + private FragmentPreferenceImpl validatePreferenceForAdd( + FragmentPreferenceImpl preference) { // only non-null definitions supported - if (preference == null) - { - throw new NullPointerException("Unable to add null to list."); - } + if (preference == null) { throw new NullPointerException( + "Unable to add null to list."); } // make sure element is unique - if (fragment.accessPreferences().contains(preference)) - { - throw new IllegalArgumentException("Unable to add duplicate entry to list: " + preference.getName()); - } + if (fragment.accessPreferences().contains(preference)) { throw new IllegalArgumentException( + "Unable to add duplicate entry to list: " + + preference.getName()); } // retrieve from removed list to reuse // previously removed element copying // security constraint defs @@ -67,7 +68,8 @@ if (removedIndex >= 0) { FragmentPreferenceImpl addPreference = preference; - preference = (FragmentPreferenceImpl)removedPreferences.remove(removedIndex); + preference = (FragmentPreferenceImpl) removedPreferences + .remove(removedIndex); // TODO: move this logic to copy methods on implementations preference.setReadOnly(addPreference.isReadOnly()); preference.setValueList(addPreference.getValueList()); @@ -78,7 +80,7 @@ /** * getRemovedPreferences - * + * * @return removed preferences tracking collection */ private List getRemovedPreferences() @@ -90,24 +92,26 @@ return removedPreferences; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) { // implement for modifiable AbstractList: // validate index - if ((index < 0) || (index > fragment.accessPreferences().size())) - { - throw new IndexOutOfBoundsException("Unable to add to list at index: " + index); - } + if ((index < 0) || (index > fragment.accessPreferences().size())) { throw new IndexOutOfBoundsException( + "Unable to add to list at index: " + index); } // verify preference - FragmentPreferenceImpl preference = validatePreferenceForAdd((FragmentPreferenceImpl)element); + FragmentPreferenceImpl preference = validatePreferenceForAdd((FragmentPreferenceImpl) element); // add to underlying ordered list fragment.accessPreferences().add(index, preference); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) @@ -116,14 +120,17 @@ return fragment.accessPreferences().get(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) { // implement for modifiable AbstractList: - // save removed element - FragmentPreferenceImpl removed = (FragmentPreferenceImpl)fragment.accessPreferences().remove(index); + // save removed element + FragmentPreferenceImpl removed = (FragmentPreferenceImpl) fragment + .accessPreferences().remove(index); if (removed != null) { getRemovedPreferences().add(removed); @@ -131,23 +138,28 @@ return removed; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) { // implement for modifiable AbstractList: // verify preference - FragmentPreferenceImpl newPreference = validatePreferenceForAdd((FragmentPreferenceImpl)element); + FragmentPreferenceImpl newPreference = validatePreferenceForAdd((FragmentPreferenceImpl) element); // set in underlying ordered list - FragmentPreferenceImpl preference = (FragmentPreferenceImpl)fragment.accessPreferences().set(index, newPreference); + FragmentPreferenceImpl preference = (FragmentPreferenceImpl) fragment + .accessPreferences().set(index, newPreference); // save replaced element getRemovedPreferences().add(preference); // return constraints ref return preference; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceValue.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceValue.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceValue.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,19 +18,22 @@ /** * FragmentPreferenceValue - * + * * @author Randy Watler * @version $Id$ */ public class FragmentPreferenceValue { + private int id; + private int valueOrder; + private String value; /** * getValueOrder - * + * * @return value order */ public int getValueOrder() @@ -40,8 +43,9 @@ /** * setValueOrder - * - * @param order value order + * + * @param order + * value order */ public void setValueOrder(int order) { @@ -50,7 +54,7 @@ /** * getValue - * + * * @return preference value */ public String getValue() @@ -60,8 +64,9 @@ /** * setValue - * - * @param value preference value + * + * @param value + * preference value */ public void setValue(String value) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceValueList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceValueList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPreferenceValueList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,12 +20,13 @@ /** * FragmentPreferenceValueList - * + * * @author Randy Watler * @version $Id$ */ class FragmentPreferenceValueList extends AbstractList { + private FragmentPreferenceImpl preference; FragmentPreferenceValueList(FragmentPreferenceImpl preference) @@ -36,45 +37,44 @@ /** * wrapValueStringForAdd - * - * Wraps and validates preference value string - * to be added to this list. - * - * @param value preference value string to add + * + * Wraps and validates preference value string to be added to this list. + * + * @param value + * preference value string to add * @return list element to add */ private FragmentPreferenceValue wrapValueStringForAdd(String value) { // only non-null values supported - if (value == null) - { - throw new NullPointerException("Unable to add null to list."); - } + if (value == null) { throw new NullPointerException( + "Unable to add null to list."); } // wrap preference value string FragmentPreferenceValue preferenceValue = new FragmentPreferenceValue(); preferenceValue.setValue(value); return preferenceValue; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) { // implement for modifiable AbstractList: // validate index - if ((index < 0) || (index > preference.accessValues().size())) - { - throw new IndexOutOfBoundsException("Unable to add to list at index: " + index); - } + if ((index < 0) || (index > preference.accessValues().size())) { throw new IndexOutOfBoundsException( + "Unable to add to list at index: " + index); } // wrap and verify preference value string - FragmentPreferenceValue preferenceValue = wrapValueStringForAdd((String)element); + FragmentPreferenceValue preferenceValue = wrapValueStringForAdd((String) element); // add to underlying ordered list preference.accessValues().add(index, preferenceValue); // set value order in added element if (index > 0) { - preferenceValue.setValueOrder(((FragmentPreferenceValue)preference.accessValues().get(index-1)).getValueOrder() + 1); + preferenceValue.setValueOrder(((FragmentPreferenceValue) preference + .accessValues().get(index - 1)).getValueOrder() + 1); } else { @@ -83,11 +83,14 @@ // maintain value order in subsequent elements for (int i = index, limit = preference.accessValues().size() - 1; (i < limit); i++) { - FragmentPreferenceValue nextPreferenceValue = (FragmentPreferenceValue)preference.accessValues().get(i + 1); - if (nextPreferenceValue.getValueOrder() <= preferenceValue.getValueOrder()) + FragmentPreferenceValue nextPreferenceValue = (FragmentPreferenceValue) preference + .accessValues().get(i + 1); + if (nextPreferenceValue.getValueOrder() <= preferenceValue + .getValueOrder()) { // adjust value order for next element - nextPreferenceValue.setValueOrder(preferenceValue.getValueOrder() + 1); + nextPreferenceValue.setValueOrder(preferenceValue + .getValueOrder() + 1); preferenceValue = nextPreferenceValue; } else @@ -98,17 +101,22 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) { // implement for modifiable AbstractList: // unwrap preference value string - return ((FragmentPreferenceValue)preference.accessValues().get(index)).getValue(); + return ((FragmentPreferenceValue) preference.accessValues().get(index)) + .getValue(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) @@ -117,23 +125,28 @@ return preference.accessValues().remove(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) { // implement for modifiable AbstractList: // wrap and verify preference value string - FragmentPreferenceValue newPreferenceValue = wrapValueStringForAdd((String)element); + FragmentPreferenceValue newPreferenceValue = wrapValueStringForAdd((String) element); // set in underlying ordered list - FragmentPreferenceValue preferenceValue = (FragmentPreferenceValue)preference.accessValues().set(index, newPreferenceValue); + FragmentPreferenceValue preferenceValue = (FragmentPreferenceValue) preference + .accessValues().set(index, newPreferenceValue); // set value order in new element newPreferenceValue.setValueOrder(preferenceValue.getValueOrder()); // return unwrapped preference value string return preferenceValue.getValue(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPropertyMap.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPropertyMap.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentPropertyMap.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,13 +27,15 @@ /** * FragmentPropertyMap - * + * * @author Randy Watler * @version $Id$ */ class FragmentPropertyMap extends AbstractMap { + private FragmentImpl fragment; + private FragmentPropertiesEntrySet entrySet; FragmentPropertyMap(FragmentImpl fragment) @@ -45,12 +47,15 @@ Iterator keyIter = fragment.getPropertyMemberKeys().iterator(); while (keyIter.hasNext()) { - String key = (String)keyIter.next(); - entrySet.add(new FragmentPropertiesEntry(key, fragment.getPropertyMember(key))); + String key = (String) keyIter.next(); + entrySet.add(new FragmentPropertiesEntry(key, fragment + .getPropertyMember(key))); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Map#put(java.lang.Object, java.lang.Object) */ public Object put(Object key, Object value) @@ -62,7 +67,8 @@ Iterator entryIter = entrySet.iterator(); while (entryIter.hasNext()) { - FragmentPropertiesEntry testEntry = (FragmentPropertiesEntry) entryIter.next(); + FragmentPropertiesEntry testEntry = (FragmentPropertiesEntry) entryIter + .next(); if (testEntry.equals(entry)) { Object oldValue = testEntry.getValue(); @@ -74,7 +80,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Map#entrySet() */ public Set entrySet() @@ -85,19 +93,24 @@ private class FragmentPropertiesEntrySet extends AbstractSet { - private Collection entries = DatabasePageManagerUtils.createCollection(); - /* (non-Javadoc) + private Collection entries = DatabasePageManagerUtils + .createCollection(); + + /* + * (non-Javadoc) + * * @see java.util.Set#add(java.lang.Object) */ public boolean add(Object o) { // implement for modifiable AbstractSet: - FragmentPropertiesEntry entry = (FragmentPropertiesEntry)o; + FragmentPropertiesEntry entry = (FragmentPropertiesEntry) o; if (!entries.contains(entry)) { // set fragment explicit property member - fragment.setPropertyMember(entry.getKey().toString(), entry.getValue().toString()); + fragment.setPropertyMember(entry.getKey().toString(), entry + .getValue().toString()); // add entry to set entries.add(o); return true; @@ -105,56 +118,67 @@ return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Set#iterator() */ public Iterator iterator() { // implement for modifiable AbstractSet: return new Iterator() + { + + private Iterator iter = entries.iterator(); + + private FragmentPropertiesEntry last; + + /* + * (non-Javadoc) + * + * @see java.util.Iterator#hasNext() + */ + public boolean hasNext() { - private Iterator iter = entries.iterator(); - private FragmentPropertiesEntry last; - - /* (non-Javadoc) - * @see java.util.Iterator#hasNext() - */ - public boolean hasNext() - { - // implement for modifiable AbstractSet: - return iter.hasNext(); - } + // implement for modifiable AbstractSet: + return iter.hasNext(); + } - /* (non-Javadoc) - * @see java.util.Iterator#next() - */ - public Object next() - { - // implement for modifiable AbstractSet: - last = (FragmentPropertiesEntry)iter.next(); - return last; - } + /* + * (non-Javadoc) + * + * @see java.util.Iterator#next() + */ + public Object next() + { + // implement for modifiable AbstractSet: + last = (FragmentPropertiesEntry) iter.next(); + return last; + } - /* (non-Javadoc) - * @see java.util.Iterator#remove() - */ - public void remove() - { - // implement for modifiable AbstractSet: - // clear fragment explicit property associated with entry - if (last == null) - { - throw new IllegalStateException("No preceding call to next() or remove() already invoked"); - } - FragmentPropertyMap.this.fragment.clearPropertyMember(last.getKey().toString()); - last = null; - // remove entry using iterator - iter.remove(); - } - }; + /* + * (non-Javadoc) + * + * @see java.util.Iterator#remove() + */ + public void remove() + { + // implement for modifiable AbstractSet: + // clear fragment explicit property associated with entry + if (last == null) { throw new IllegalStateException( + "No preceding call to next() or remove() already invoked"); } + FragmentPropertyMap.this.fragment.clearPropertyMember(last + .getKey().toString()); + last = null; + // remove entry using iterator + iter.remove(); + } + }; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Set#size() */ public int size() @@ -166,7 +190,9 @@ private class FragmentPropertiesEntry implements Map.Entry { + private Object key; + private Object value; public FragmentPropertiesEntry(Object key, Object value) @@ -175,7 +201,9 @@ this.value = value; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Map.Entry#getKey() */ public Object getKey() @@ -183,52 +211,56 @@ return key; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Map.Entry#getValue() */ public Object getValue() { return value; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see java.util.Map.Entry#setValue(java.lang.Object) */ public Object setValue(Object newValue) { // set fragment explicit property associated with entry - FragmentPropertyMap.this.fragment.setPropertyMember(key.toString(), newValue.toString()); + FragmentPropertyMap.this.fragment.setPropertyMember(key.toString(), + newValue.toString()); // set entry value Object oldValue = value; value = newValue; return oldValue; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o instanceof FragmentPropertiesEntry) { - if (key != null) - { - return key.equals(((FragmentPropertiesEntry)o).getKey()); - } - return (((FragmentPropertiesEntry)o).getKey() == null); + if (key != null) { return key + .equals(((FragmentPropertiesEntry) o).getKey()); } + return (((FragmentPropertiesEntry) o).getKey() == null); } return false; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see java.lang.Object#hashCode() */ public int hashCode() { - if (key != null) - { - return key.hashCode(); - } + if (key != null) { return key.hashCode(); } return 0; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentSecurityConstraintImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentSecurityConstraintImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentSecurityConstraintImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,7 +20,7 @@ /** * PageSecurityConstraintImpl - * + * * @author Randy Watler * @version $Id$ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentSecurityConstraintsImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentSecurityConstraintsImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentSecurityConstraintsImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,13 +18,16 @@ /** * FragmentSecurityConstraintsImpl - * + * * @author Randy Watler * @version $Id$ */ public class FragmentSecurityConstraintsImpl extends SecurityConstraintsImpl { - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.SecurityConstraintsImpl#getSecurityConstraintClass() */ public Class getSecurityConstraintClass() @@ -32,7 +35,9 @@ return FragmentSecurityConstraintImpl.class; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.SecurityConstraintsImpl#getSecurityConstraintsRefClass() */ public Class getSecurityConstraintsRefClass() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentSecurityConstraintsRef.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentSecurityConstraintsRef.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/FragmentSecurityConstraintsRef.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,7 +18,7 @@ /** * PageSecurityConstraintsRef - * + * * @author Randy Watler * @version $Id$ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,14 +24,17 @@ /** * LinkImpl - * + * * @author Randy Watler * @version $Id$ */ public class LinkImpl extends DocumentImpl implements Link { + private String skin; + private String target; + private String url; public LinkImpl() @@ -39,17 +42,22 @@ super(new LinkSecurityConstraintsImpl()); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.impl.NodeImpl#newPageMetadata(java.util.Collection) */ public PageMetadataImpl newPageMetadata(Collection fields) { - PageMetadataImpl pageMetadata = new PageMetadataImpl(LinkMetadataLocalizedFieldImpl.class); + PageMetadataImpl pageMetadata = new PageMetadataImpl( + LinkMetadataLocalizedFieldImpl.class); pageMetadata.setFields(fields); return pageMetadata; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#grantViewActionAccess() */ public boolean grantViewActionAccess() @@ -58,10 +66,13 @@ // are probably not a security related concern but rather // should always be viewable, (subject to folder access) String hrefUrl = getUrl(); - return ((hrefUrl != null) && (hrefUrl.startsWith("http://") || hrefUrl.startsWith("https://"))); + return ((hrefUrl != null) && (hrefUrl.startsWith("http://") || hrefUrl + .startsWith("https://"))); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getUrl() */ public String getUrl() @@ -69,7 +80,9 @@ return url; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Link#setUrl(java.lang.String) */ public void setUrl(String url) @@ -77,7 +90,9 @@ this.url = url; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Link#getSkin() */ public String getSkin() @@ -85,7 +100,9 @@ return skin; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Link#setSkin(java.lang.String) */ public void setSkin(String skin) @@ -93,7 +110,9 @@ this.skin = skin; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Link#getTarget() */ public String getTarget() @@ -101,7 +120,9 @@ return target; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Link#setTarget(java.lang.String) */ public void setTarget(String target) @@ -109,7 +130,9 @@ this.target = target; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getType() */ public String getType() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkMetadataLocalizedFieldImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkMetadataLocalizedFieldImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkMetadataLocalizedFieldImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,7 +20,7 @@ /** * LinkMetadataLocalizedFieldImpl - * + * * @author Randy Watler * @version $Id$ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkSecurityConstraintImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkSecurityConstraintImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkSecurityConstraintImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,7 +20,7 @@ /** * LinkSecurityConstraintImpl - * + * * @author Randy Watler * @version $Id$ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkSecurityConstraintsImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkSecurityConstraintsImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkSecurityConstraintsImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,13 +18,16 @@ /** * LinkSecurityConstraintsImpl - * + * * @author Randy Watler * @version $Id$ */ public class LinkSecurityConstraintsImpl extends SecurityConstraintsImpl { - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.SecurityConstraintsImpl#getSecurityConstraintClass() */ public Class getSecurityConstraintClass() @@ -32,7 +35,9 @@ return LinkSecurityConstraintImpl.class; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.SecurityConstraintsImpl#getSecurityConstraintsRefClass() */ public Class getSecurityConstraintsRefClass() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkSecurityConstraintsRef.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkSecurityConstraintsRef.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/LinkSecurityConstraintsRef.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,7 +18,7 @@ /** * LinkSecurityConstraintsRef - * + * * @author Randy Watler * @version $Id$ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -35,19 +35,25 @@ /** * PageImpl - * + * * @author Randy Watler * @version $Id$ */ public class PageImpl extends DocumentImpl implements Page { + private Collection fragment; + private String skin; + private String defaultLayoutDecorator; + private String defaultPortletDecorator; + private List menus; private PageMenuDefinitionList menuDefinitions; + private FragmentImpl removedFragment; public PageImpl() @@ -57,9 +63,9 @@ /** * accessMenus - * + * * Access mutable persistent collection member for List wrappers. - * + * * @return persistent collection */ List accessMenus() @@ -67,44 +73,54 @@ // create initial collection if necessary if (menus == null) { - menus = DatabasePageManagerUtils.createList();; + menus = DatabasePageManagerUtils.createList(); + ; } return menus; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#resetCachedSecurityConstraints() */ public void resetCachedSecurityConstraints() { // propagate to super and fragments super.resetCachedSecurityConstraints(); - FragmentImpl rootFragment = (FragmentImpl)getRootFragment(); + FragmentImpl rootFragment = (FragmentImpl) getRootFragment(); if (rootFragment != null) { rootFragment.resetCachedSecurityConstraints(); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.impl.NodeImpl#newPageMetadata(java.util.Collection) */ public PageMetadataImpl newPageMetadata(Collection fields) { - PageMetadataImpl pageMetadata = new PageMetadataImpl(PageMetadataLocalizedFieldImpl.class); + PageMetadataImpl pageMetadata = new PageMetadataImpl( + PageMetadataLocalizedFieldImpl.class); pageMetadata.setFields(fields); return pageMetadata; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#getSkin() */ public String getSkin() { return skin; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#setSkin(java.lang.String) */ public void setSkin(String skinName) @@ -112,7 +128,9 @@ this.skin = skinName; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#getEffectiveDefaultDecorator(java.lang.String) */ public String getEffectiveDefaultDecorator(String fragmentType) @@ -122,16 +140,17 @@ if (decorator == null) { // delegate to parent folder - Folder parentFolder = (Folder)ProxyHelper.getRealObject(getParent()); - if (parentFolder != null) - { - return parentFolder.getEffectiveDefaultDecorator(fragmentType); - } + Folder parentFolder = (Folder) ProxyHelper + .getRealObject(getParent()); + if (parentFolder != null) { return parentFolder + .getEffectiveDefaultDecorator(fragmentType); } } return decorator; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#getDefaultDecorator(java.lang.String) */ public String getDefaultDecorator(String fragmentType) @@ -139,19 +158,15 @@ // retrieve supported decorator types if (fragmentType != null) { - if (fragmentType.equals(Fragment.LAYOUT)) - { - return defaultLayoutDecorator; - } - if (fragmentType.equals(Fragment.PORTLET)) - { - return defaultPortletDecorator; - } + if (fragmentType.equals(Fragment.LAYOUT)) { return defaultLayoutDecorator; } + if (fragmentType.equals(Fragment.PORTLET)) { return defaultPortletDecorator; } } return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#getDefaultDecorator(java.lang.String,java.lang.String) */ public void setDefaultDecorator(String decoratorName, String fragmentType) @@ -161,16 +176,18 @@ { if (fragmentType.equals(Fragment.LAYOUT)) { - defaultLayoutDecorator = decoratorName; + defaultLayoutDecorator = decoratorName; } if (fragmentType.equals(Fragment.PORTLET)) { - defaultPortletDecorator = decoratorName; + defaultPortletDecorator = decoratorName; } } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#getRootFragment() */ public Fragment getRootFragment() @@ -179,7 +196,8 @@ // be made for root fragment if ((fragment != null) && !fragment.isEmpty()) { - FragmentImpl rootFragment = (FragmentImpl)fragment.iterator().next(); + FragmentImpl rootFragment = (FragmentImpl) fragment.iterator() + .next(); if (rootFragment.getPage() == null) { // set page implementation in root and children fragments @@ -189,8 +207,10 @@ } return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#setRootFragment(org.apache.jetspeed.om.page.Fragment) */ public void setRootFragment(Fragment fragment) @@ -206,7 +226,8 @@ } else if (!this.fragment.isEmpty()) { - removedFragment = (FragmentImpl)this.fragment.iterator().next(); + removedFragment = (FragmentImpl) this.fragment.iterator() + .next(); this.fragment.clear(); } @@ -215,7 +236,7 @@ if (removedFragment != null) { // reuse previously removed fragment - FragmentImpl addFragment = (FragmentImpl)fragment; + FragmentImpl addFragment = (FragmentImpl) fragment; fragment = removedFragment; removedFragment = null; // TODO: move this logic to copy methods on implementations @@ -226,7 +247,8 @@ fragment.setSkin(addFragment.getSkin()); fragment.setDecorator(addFragment.getDecorator()); fragment.setState(addFragment.getState()); - fragment.setSecurityConstraints(addFragment.getSecurityConstraints()); + fragment.setSecurityConstraints(addFragment + .getSecurityConstraints()); fragment.getProperties().clear(); fragment.getProperties().putAll(addFragment.getProperties()); fragment.setPreferences(addFragment.getPreferences()); @@ -236,7 +258,7 @@ this.fragment.add(fragment); // set page implementation in root and children fragments - ((FragmentImpl)fragment).setPage(this); + ((FragmentImpl) fragment).setPage(this); } else if (fragment == null) { @@ -244,19 +266,22 @@ // removed fragment for later reuse if ((this.fragment != null) && !this.fragment.isEmpty()) { - removedFragment = (FragmentImpl)this.fragment.iterator().next(); + removedFragment = (FragmentImpl) this.fragment.iterator() + .next(); this.fragment.clear(); } } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#getFragmentById(java.lang.String) */ public Fragment getFragmentById(String id) { // get fragment by id and check access - FragmentImpl rootFragment = (FragmentImpl)getRootFragment(); + FragmentImpl rootFragment = (FragmentImpl) getRootFragment(); if (rootFragment != null) { Fragment fragment = rootFragment.getFragmentById(id); @@ -276,13 +301,15 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#removeFragmentById(java.lang.String) */ public Fragment removeFragmentById(String id) { // remove fragment by id - FragmentImpl rootFragment = (FragmentImpl)getRootFragment(); + FragmentImpl rootFragment = (FragmentImpl) getRootFragment(); if (rootFragment != null) { if (rootFragment.getId().equals(id)) @@ -298,22 +325,27 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#getFragmentsByName(java.lang.String) */ public List getFragmentsByName(String name) { // get fragments by name and filter by access - FragmentImpl rootFragment = (FragmentImpl)getRootFragment(); + FragmentImpl rootFragment = (FragmentImpl) getRootFragment(); if (rootFragment != null) { // return immutable filtered fragment list - return rootFragment.filterFragmentsByAccess(rootFragment.getFragmentsByName(name), false); + return rootFragment.filterFragmentsByAccess(rootFragment + .getFragmentsByName(name), false); } return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#getMenuDefinitions() */ public List getMenuDefinitions() @@ -327,8 +359,10 @@ } return menuDefinitions; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#newMenuDefinition() */ public MenuDefinition newMenuDefinition() @@ -336,7 +370,9 @@ return new PageMenuDefinitionImpl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#newMenuExcludeDefinition() */ public MenuExcludeDefinition newMenuExcludeDefinition() @@ -344,7 +380,9 @@ return new PageMenuExcludeDefinitionImpl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#newMenuIncludeDefinition() */ public MenuIncludeDefinition newMenuIncludeDefinition() @@ -352,7 +390,9 @@ return new PageMenuIncludeDefinitionImpl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#newMenuOptionsDefinition() */ public MenuOptionsDefinition newMenuOptionsDefinition() @@ -360,7 +400,9 @@ return new PageMenuOptionsDefinitionImpl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#newMenuSeparatorDefinition() */ public MenuSeparatorDefinition newMenuSeparatorDefinition() @@ -368,7 +410,9 @@ return new PageMenuSeparatorDefinitionImpl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#setMenuDefinitions(java.util.List) */ public void setMenuDefinitions(List definitions) @@ -388,7 +432,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getType() */ public String getType() @@ -396,7 +442,8 @@ return DOCUMENT_TYPE; } - public String toString() { - return getPath(); - } + public String toString() + { + return getPath(); + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionElement.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionElement.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionElement.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,14 +24,19 @@ */ public interface PageMenuDefinitionElement { + // new interface defined only to facilitate OJB table/class mapping - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.impl.BaseMenuDefinitionElement#getElementOrder() */ int getElementOrder(); - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.impl.BaseMenuDefinitionElement#setElementOrder(int) */ void setElementOrder(int order); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionElementList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionElementList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionElementList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,12 +20,13 @@ /** * PageMenuDefinitionElementList - * + * * @author Randy Watler * @version $Id$ */ class PageMenuDefinitionElementList extends AbstractList { + private PageMenuDefinitionImpl menuDefinition; PageMenuDefinitionElementList(PageMenuDefinitionImpl menuDefinition) @@ -36,41 +37,43 @@ /** * validateMenuElementForAdd - * + * * Validates element to be added to this list. - * - * @param menuElement element to add + * + * @param menuElement + * element to add * @return list element to add */ - private PageMenuDefinitionElement validateMenuElementForAdd(PageMenuDefinitionElement menuElement) + private PageMenuDefinitionElement validateMenuElementForAdd( + PageMenuDefinitionElement menuElement) { // validate element instance - if (menuElement == null) - { - throw new NullPointerException("Unable to add null to list."); - } + if (menuElement == null) { throw new NullPointerException( + "Unable to add null to list."); } return menuElement; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) { // implement for modifiable AbstractList: // validate index - if ((index < 0) || (index > menuDefinition.accessElements().size())) - { - throw new IndexOutOfBoundsException("Unable to add to list at index: " + index); - } + if ((index < 0) || (index > menuDefinition.accessElements().size())) { throw new IndexOutOfBoundsException( + "Unable to add to list at index: " + index); } // verify element - PageMenuDefinitionElement menuElement = validateMenuElementForAdd((PageMenuDefinitionElement)element); + PageMenuDefinitionElement menuElement = validateMenuElementForAdd((PageMenuDefinitionElement) element); // add to underlying ordered list menuDefinition.accessElements().add(index, menuElement); // set element order in added element if (index > 0) { - menuElement.setElementOrder(((PageMenuDefinitionElement)menuDefinition.accessElements().get(index-1)).getElementOrder() + 1); + menuElement + .setElementOrder(((PageMenuDefinitionElement) menuDefinition + .accessElements().get(index - 1)).getElementOrder() + 1); } else { @@ -79,11 +82,14 @@ // maintain element order in subsequent elements for (int i = index, limit = menuDefinition.accessElements().size() - 1; (i < limit); i++) { - PageMenuDefinitionElement nextMenuElement = (PageMenuDefinitionElement)menuDefinition.accessElements().get(i + 1); - if (nextMenuElement.getElementOrder() <= menuElement.getElementOrder()) + PageMenuDefinitionElement nextMenuElement = (PageMenuDefinitionElement) menuDefinition + .accessElements().get(i + 1); + if (nextMenuElement.getElementOrder() <= menuElement + .getElementOrder()) { // adjust element order for next element - nextMenuElement.setElementOrder(menuElement.getElementOrder() + 1); + nextMenuElement + .setElementOrder(menuElement.getElementOrder() + 1); menuElement = nextMenuElement; } else @@ -94,7 +100,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) @@ -103,7 +111,9 @@ return menuDefinition.accessElements().get(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) @@ -112,23 +122,28 @@ return menuDefinition.accessElements().remove(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) { // implement for modifiable AbstractList: // verify element - PageMenuDefinitionElement newMenuElement = validateMenuElementForAdd((PageMenuDefinitionElement)element); + PageMenuDefinitionElement newMenuElement = validateMenuElementForAdd((PageMenuDefinitionElement) element); // set in underlying ordered list - PageMenuDefinitionElement menuElement = (PageMenuDefinitionElement)menuDefinition.accessElements().set(index, newMenuElement); + PageMenuDefinitionElement menuElement = (PageMenuDefinitionElement) menuDefinition + .accessElements().set(index, newMenuElement); // set element order in new element newMenuElement.setElementOrder(menuElement.getElementOrder()); // return element return menuElement; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,23 +29,30 @@ * @author Randy Watler * @version $Id:$ */ -public class PageMenuDefinitionImpl extends BaseMenuDefinitionImpl implements MenuDefinition, PageMenuDefinitionElement +public class PageMenuDefinitionImpl extends BaseMenuDefinitionImpl implements + MenuDefinition, PageMenuDefinitionElement { + // new class defined only to facilitate OJB table/class mapping private PageMenuDefinitionElementList menuElements; - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.impl.BaseMenuDefinitionMetadata#newPageMetadata() */ public PageMetadataImpl newPageMetadata(Collection fields) { - PageMetadataImpl pageMetadata = new PageMetadataImpl(PageMenuMetadataLocalizedFieldImpl.class); + PageMetadataImpl pageMetadata = new PageMetadataImpl( + PageMenuMetadataLocalizedFieldImpl.class); pageMetadata.setFields(fields); return pageMetadata; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.MenuDefinition#getMenuElements() */ public List getMenuElements() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuDefinitionList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,15 +21,15 @@ import org.apache.jetspeed.page.impl.DatabasePageManagerUtils; - /** * PageMenuDefinitionList - * + * * @author Randy Watler * @version $Id$ */ class PageMenuDefinitionList extends AbstractList { + private PageImpl page; private List removedMenuDefinitions; @@ -42,24 +42,23 @@ /** * validateDefinitionForAdd - * + * * Validates menu definition to be added to this list. - * - * @param definition menu definition to add + * + * @param definition + * menu definition to add * @return list element to add */ - private PageMenuDefinitionImpl validateDefinitionForAdd(PageMenuDefinitionImpl definition) + private PageMenuDefinitionImpl validateDefinitionForAdd( + PageMenuDefinitionImpl definition) { // only non-null definitions supported - if (definition == null) - { - throw new NullPointerException("Unable to add null to list."); - } + if (definition == null) { throw new NullPointerException( + "Unable to add null to list."); } // make sure element is unique - if (page.accessMenus().contains(definition)) - { - throw new IllegalArgumentException("Unable to add duplicate entry to list: " + (definition).getName()); - } + if (page.accessMenus().contains(definition)) { throw new IllegalArgumentException( + "Unable to add duplicate entry to list: " + + (definition).getName()); } // retrieve from removed list to reuse // previously removed element copying // menu definition data @@ -70,7 +69,8 @@ { // reuse menu definition with matching name PageMenuDefinitionImpl addDefinition = definition; - definition = (PageMenuDefinitionImpl)removedMenuDefinitions.remove(removedIndex); + definition = (PageMenuDefinitionImpl) removedMenuDefinitions + .remove(removedIndex); // TODO: move this logic to copy methods on implementations // copy menu definition members definition.setOptions(addDefinition.getOptions()); @@ -92,7 +92,8 @@ // metadata members are required to be unique // and a removal list is not maintained for the // metadata fields collections yet - definition.getMetadata().copyFields(addDefinition.getMetadata().getFields()); + definition.getMetadata().copyFields( + addDefinition.getMetadata().getFields()); } } return definition; @@ -100,7 +101,7 @@ /** * getRemovedMenuDefinitions - * + * * @return removed menu definitions tracking collection */ private List getRemovedMenuDefinitions() @@ -112,24 +113,26 @@ return removedMenuDefinitions; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) { // implement for modifiable AbstractList: // validate index - if ((index < 0) || (index > page.accessMenus().size())) - { - throw new IndexOutOfBoundsException("Unable to add to list at index: " + index); - } + if ((index < 0) || (index > page.accessMenus().size())) { throw new IndexOutOfBoundsException( + "Unable to add to list at index: " + index); } // verify menu definition - PageMenuDefinitionImpl definition = validateDefinitionForAdd((PageMenuDefinitionImpl)element); + PageMenuDefinitionImpl definition = validateDefinitionForAdd((PageMenuDefinitionImpl) element); // add to underlying ordered list page.accessMenus().add(index, definition); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) @@ -138,14 +141,17 @@ return page.accessMenus().get(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) { // implement for modifiable AbstractList: - // save removed element - PageMenuDefinitionImpl removed = (PageMenuDefinitionImpl)page.accessMenus().remove(index); + // save removed element + PageMenuDefinitionImpl removed = (PageMenuDefinitionImpl) page + .accessMenus().remove(index); if (removed != null) { getRemovedMenuDefinitions().add(removed); @@ -153,23 +159,28 @@ return removed; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) { // implement for modifiable AbstractList: // verify menu definition - PageMenuDefinitionImpl newDefinition = validateDefinitionForAdd((PageMenuDefinitionImpl)element); + PageMenuDefinitionImpl newDefinition = validateDefinitionForAdd((PageMenuDefinitionImpl) element); // set in underlying ordered list - PageMenuDefinitionImpl definition = (PageMenuDefinitionImpl)page.accessMenus().set(index, newDefinition); + PageMenuDefinitionImpl definition = (PageMenuDefinitionImpl) page + .accessMenus().set(index, newDefinition); // save replaced element getRemovedMenuDefinitions().add(definition); // return menu definition return definition; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuExcludeDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuExcludeDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuExcludeDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,7 +25,9 @@ * @author Randy Watler * @version $Id:$ */ -public class PageMenuExcludeDefinitionImpl extends BaseMenuExcludeDefinitionImpl implements MenuExcludeDefinition, PageMenuDefinitionElement +public class PageMenuExcludeDefinitionImpl extends + BaseMenuExcludeDefinitionImpl implements MenuExcludeDefinition, + PageMenuDefinitionElement { // new class defined only to facilitate OJB table/class mapping } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuIncludeDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuIncludeDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuIncludeDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,7 +25,9 @@ * @author Randy Watler * @version $Id:$ */ -public class PageMenuIncludeDefinitionImpl extends BaseMenuIncludeDefinitionImpl implements MenuIncludeDefinition, PageMenuDefinitionElement +public class PageMenuIncludeDefinitionImpl extends + BaseMenuIncludeDefinitionImpl implements MenuIncludeDefinition, + PageMenuDefinitionElement { // new class defined only to facilitate OJB table/class mapping } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuMetadataLocalizedFieldImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuMetadataLocalizedFieldImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuMetadataLocalizedFieldImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,7 +20,7 @@ /** * PageMenuMetadataLocalizedFieldImpl - * + * * @author Randy Watler * @version $Id$ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuOptionsDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuOptionsDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuOptionsDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,7 +25,9 @@ * @author Randy Watler * @version $Id:$ */ -public class PageMenuOptionsDefinitionImpl extends BaseMenuOptionsDefinitionImpl implements MenuOptionsDefinition, PageMenuDefinitionElement +public class PageMenuOptionsDefinitionImpl extends + BaseMenuOptionsDefinitionImpl implements MenuOptionsDefinition, + PageMenuDefinitionElement { // new class defined only to facilitate OJB table/class mapping } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuSeparatorDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuSeparatorDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMenuSeparatorDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,16 +28,22 @@ * @author Randy Watler * @version $Id:$ */ -public class PageMenuSeparatorDefinitionImpl extends BaseMenuSeparatorDefinitionImpl implements MenuSeparatorDefinition, PageMenuDefinitionElement +public class PageMenuSeparatorDefinitionImpl extends + BaseMenuSeparatorDefinitionImpl implements MenuSeparatorDefinition, + PageMenuDefinitionElement { + // new class defined only to facilitate OJB table/class mapping - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.folder.impl.BaseMenuDefinitionMetadata#newPageMetadata() */ public PageMetadataImpl newPageMetadata(Collection fields) { - PageMetadataImpl pageMetadata = new PageMetadataImpl(PageMenuMetadataLocalizedFieldImpl.class); + PageMetadataImpl pageMetadata = new PageMetadataImpl( + PageMenuMetadataLocalizedFieldImpl.class); pageMetadata.setFields(fields); return pageMetadata; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMetadataLocalizedFieldImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMetadataLocalizedFieldImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageMetadataLocalizedFieldImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,7 +20,7 @@ /** * PageMetadataLocalizedFieldImpl - * + * * @author Randy Watler * @version $Id$ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,7 +20,7 @@ /** * PageSecurityConstraintImpl - * + * * @author Randy Watler * @version $Id$ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsDefList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsDefList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsDefList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,12 +23,13 @@ /** * PageSecurityConstraintsDefList - * + * * @author Randy Watler * @version $Id$ */ class PageSecurityConstraintsDefList extends AbstractList { + private PageSecurityImpl pageSecurity; private List removedConstraintsDefs; @@ -41,24 +42,23 @@ /** * validateConstraintsDefForAdd - * + * * Validates constraints def to be added to this list. - * - * @param constraintsDef constraints definition to add + * + * @param constraintsDef + * constraints definition to add * @return list element to add */ - private SecurityConstraintsDefImpl validateConstraintsDefForAdd(SecurityConstraintsDefImpl constraintsDef) + private SecurityConstraintsDefImpl validateConstraintsDefForAdd( + SecurityConstraintsDefImpl constraintsDef) { // only non-null definitions supported - if (constraintsDef == null) - { - throw new NullPointerException("Unable to add null to list."); - } + if (constraintsDef == null) { throw new NullPointerException( + "Unable to add null to list."); } // make sure element is unique - if (pageSecurity.accessConstraintsDefs().contains(constraintsDef)) - { - throw new IllegalArgumentException("Unable to add duplicate entry to list: " + constraintsDef.getName()); - } + if (pageSecurity.accessConstraintsDefs().contains(constraintsDef)) { throw new IllegalArgumentException( + "Unable to add duplicate entry to list: " + + constraintsDef.getName()); } // retrieve from removed list to reuse // previously removed element copying // security constraint defs @@ -68,9 +68,11 @@ if (removedIndex >= 0) { SecurityConstraintsDefImpl addConstraintsDef = constraintsDef; - constraintsDef = (SecurityConstraintsDefImpl)removedConstraintsDefs.remove(removedIndex); + constraintsDef = (SecurityConstraintsDefImpl) removedConstraintsDefs + .remove(removedIndex); // TODO: move this logic to copy methods on implementations - constraintsDef.setSecurityConstraints(addConstraintsDef.getSecurityConstraints()); + constraintsDef.setSecurityConstraints(addConstraintsDef + .getSecurityConstraints()); } } return constraintsDef; @@ -78,7 +80,7 @@ /** * getRemovedConstraintsDefs - * + * * @return removed constraints defs tracking collection */ private List getRemovedConstraintsDefs() @@ -90,26 +92,29 @@ return removedConstraintsDefs; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) { // implement for modifiable AbstractList: // validate index - if ((index < 0) || (index > pageSecurity.accessConstraintsDefs().size())) - { - throw new IndexOutOfBoundsException("Unable to add to list at index: " + index); - } + if ((index < 0) + || (index > pageSecurity.accessConstraintsDefs().size())) { throw new IndexOutOfBoundsException( + "Unable to add to list at index: " + index); } // verify constraints definition - SecurityConstraintsDefImpl constraintsDef = validateConstraintsDefForAdd((SecurityConstraintsDefImpl)element); + SecurityConstraintsDefImpl constraintsDef = validateConstraintsDefForAdd((SecurityConstraintsDefImpl) element); // add to underlying ordered list pageSecurity.accessConstraintsDefs().add(index, constraintsDef); // clear cached security constraints definition map pageSecurity.clearSecurityConstraintsDefsMap(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) @@ -118,16 +123,19 @@ return pageSecurity.accessConstraintsDefs().get(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) { // implement for modifiable AbstractList - SecurityConstraintsDefImpl removed = (SecurityConstraintsDefImpl)pageSecurity.accessConstraintsDefs().remove(index); + SecurityConstraintsDefImpl removed = (SecurityConstraintsDefImpl) pageSecurity + .accessConstraintsDefs().remove(index); if (removed != null) { - // save removed element + // save removed element getRemovedConstraintsDefs().add(removed); // clear cached security constraints definition map pageSecurity.clearSecurityConstraintsDefsMap(); @@ -135,16 +143,19 @@ return removed; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) { // implement for modifiable AbstractList: // verify constraints definition - SecurityConstraintsDefImpl newConstraintsDef = validateConstraintsDefForAdd((SecurityConstraintsDefImpl)element); + SecurityConstraintsDefImpl newConstraintsDef = validateConstraintsDefForAdd((SecurityConstraintsDefImpl) element); // set in underlying ordered list - SecurityConstraintsDefImpl constraintsDef = (SecurityConstraintsDefImpl)pageSecurity.accessConstraintsDefs().set(index, newConstraintsDef); + SecurityConstraintsDefImpl constraintsDef = (SecurityConstraintsDefImpl) pageSecurity + .accessConstraintsDefs().set(index, newConstraintsDef); // save replaced element getRemovedConstraintsDefs().add(constraintsDef); // clear cached security constraints definition map @@ -153,7 +164,9 @@ return constraintsDef; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,13 +18,16 @@ /** * PageSecurityConstraintsImpl - * + * * @author Randy Watler * @version $Id$ */ public class PageSecurityConstraintsImpl extends SecurityConstraintsImpl { - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.SecurityConstraintsImpl#getSecurityConstraintClass() */ public Class getSecurityConstraintClass() @@ -32,7 +35,9 @@ return PageSecurityConstraintImpl.class; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.SecurityConstraintsImpl#getSecurityConstraintsRefClass() */ public Class getSecurityConstraintsRefClass() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsRef.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsRef.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsRef.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,7 +18,7 @@ /** * PageSecurityConstraintsRef - * + * * @author Randy Watler * @version $Id$ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsRefList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsRefList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityConstraintsRefList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,12 +23,13 @@ /** * PageSecurityConstraintsRefList - * + * * @author Randy Watler * @version $Id$ */ class PageSecurityConstraintsRefList extends AbstractList { + private PageSecurityImpl pageSecurity; private List removedConstraintsRefs; @@ -41,28 +42,26 @@ /** * wrapNameStringForAdd - * - * Wraps and validates constraints ref name string - * to be added to this list. - * - * @param name constraints ref name string to add + * + * Wraps and validates constraints ref name string to be added to this list. + * + * @param name + * constraints ref name string to add * @return list element to add */ - private PageSecurityGlobalSecurityConstraintsRef wrapNameStringForAdd(String name) + private PageSecurityGlobalSecurityConstraintsRef wrapNameStringForAdd( + String name) { // only non-null names supported - if (name == null) - { - throw new NullPointerException("Unable to add null to list."); - } + if (name == null) { throw new NullPointerException( + "Unable to add null to list."); } // wrap constraints ref name string PageSecurityGlobalSecurityConstraintsRef constraintsRef = new PageSecurityGlobalSecurityConstraintsRef(); constraintsRef.setName(name); // make sure element is unique - if (pageSecurity.accessGlobalConstraintsRefs().contains(constraintsRef)) - { - throw new IllegalArgumentException("Unable to add duplicate entry to list: " + constraintsRef.getName()); - } + if (pageSecurity.accessGlobalConstraintsRefs().contains(constraintsRef)) { throw new IllegalArgumentException( + "Unable to add duplicate entry to list: " + + constraintsRef.getName()); } // retrieve from removed list to reuse // previously removed element if (removedConstraintsRefs != null) @@ -70,7 +69,8 @@ int removedIndex = removedConstraintsRefs.indexOf(constraintsRef); if (removedIndex >= 0) { - constraintsRef = (PageSecurityGlobalSecurityConstraintsRef)removedConstraintsRefs.remove(removedIndex); + constraintsRef = (PageSecurityGlobalSecurityConstraintsRef) removedConstraintsRefs + .remove(removedIndex); } } return constraintsRef; @@ -78,7 +78,7 @@ /** * getRemovedConstraintsRefs - * + * * @return removed constraints refs tracking collection */ private List getRemovedConstraintsRefs() @@ -90,38 +90,46 @@ return removedConstraintsRefs; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) { // implement for modifiable AbstractList: // validate index - if ((index < 0) || (index > pageSecurity.accessGlobalConstraintsRefs().size())) - { - throw new IndexOutOfBoundsException("Unable to add to list at index: " + index); - } + if ((index < 0) + || (index > pageSecurity.accessGlobalConstraintsRefs().size())) { throw new IndexOutOfBoundsException( + "Unable to add to list at index: " + index); } // wrap and verify constraints ref name string - PageSecurityGlobalSecurityConstraintsRef constraintsRef = wrapNameStringForAdd((String)element); + PageSecurityGlobalSecurityConstraintsRef constraintsRef = wrapNameStringForAdd((String) element); // add to underlying ordered list pageSecurity.accessGlobalConstraintsRefs().add(index, constraintsRef); // set apply order in added element if (index > 0) { - constraintsRef.setApplyOrder(((PageSecurityGlobalSecurityConstraintsRef)pageSecurity.accessGlobalConstraintsRefs().get(index-1)).getApplyOrder() + 1); + constraintsRef + .setApplyOrder(((PageSecurityGlobalSecurityConstraintsRef) pageSecurity + .accessGlobalConstraintsRefs().get(index - 1)) + .getApplyOrder() + 1); } else { constraintsRef.setApplyOrder(0); } // maintain apply order in subsequent elements - for (int i = index, limit = pageSecurity.accessGlobalConstraintsRefs().size() - 1; (i < limit); i++) + for (int i = index, limit = pageSecurity.accessGlobalConstraintsRefs() + .size() - 1; (i < limit); i++) { - PageSecurityGlobalSecurityConstraintsRef nextConstraintsRef = (PageSecurityGlobalSecurityConstraintsRef)pageSecurity.accessGlobalConstraintsRefs().get(i + 1); - if (nextConstraintsRef.getApplyOrder() <= constraintsRef.getApplyOrder()) + PageSecurityGlobalSecurityConstraintsRef nextConstraintsRef = (PageSecurityGlobalSecurityConstraintsRef) pageSecurity + .accessGlobalConstraintsRefs().get(i + 1); + if (nextConstraintsRef.getApplyOrder() <= constraintsRef + .getApplyOrder()) { // adjust apply order for next element - nextConstraintsRef.setApplyOrder(constraintsRef.getApplyOrder() + 1); + nextConstraintsRef + .setApplyOrder(constraintsRef.getApplyOrder() + 1); constraintsRef = nextConstraintsRef; } else @@ -132,24 +140,30 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) { // implement for modifiable AbstractList: // unwrap constraints ref name string - return ((PageSecurityGlobalSecurityConstraintsRef)pageSecurity.accessGlobalConstraintsRefs().get(index)).getName(); + return ((PageSecurityGlobalSecurityConstraintsRef) pageSecurity + .accessGlobalConstraintsRefs().get(index)).getName(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) { // implement for modifiable AbstractList: - // save removed element - PageSecurityGlobalSecurityConstraintsRef removed = (PageSecurityGlobalSecurityConstraintsRef)pageSecurity.accessGlobalConstraintsRefs().remove(index); + // save removed element + PageSecurityGlobalSecurityConstraintsRef removed = (PageSecurityGlobalSecurityConstraintsRef) pageSecurity + .accessGlobalConstraintsRefs().remove(index); if (removed != null) { getRemovedConstraintsRefs().add(removed); @@ -157,16 +171,19 @@ return removed; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) { // implement for modifiable AbstractList: // wrap and verify constraints ref name string - PageSecurityGlobalSecurityConstraintsRef newConstraintsRef = wrapNameStringForAdd((String)element); + PageSecurityGlobalSecurityConstraintsRef newConstraintsRef = wrapNameStringForAdd((String) element); // set in underlying ordered list - PageSecurityGlobalSecurityConstraintsRef constraintsRef = (PageSecurityGlobalSecurityConstraintsRef)pageSecurity.accessGlobalConstraintsRefs().set(index, newConstraintsRef); + PageSecurityGlobalSecurityConstraintsRef constraintsRef = (PageSecurityGlobalSecurityConstraintsRef) pageSecurity + .accessGlobalConstraintsRefs().set(index, newConstraintsRef); // set apply order in new element newConstraintsRef.setApplyOrder(constraintsRef.getApplyOrder()); // save replaced element @@ -175,7 +192,9 @@ return constraintsRef.getName(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityGlobalSecurityConstraintsRef.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityGlobalSecurityConstraintsRef.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityGlobalSecurityConstraintsRef.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,11 +18,12 @@ /** * PageSecurityConstraintsRef - * + * * @author Randy Watler * @version $Id$ */ -public class PageSecurityGlobalSecurityConstraintsRef extends BaseSecurityConstraintsRef +public class PageSecurityGlobalSecurityConstraintsRef extends + BaseSecurityConstraintsRef { // new class defined only to facilitate OJB table/class mapping } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecurityImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,17 +29,21 @@ /** * PageSecurityImpl - * + * * @author Randy Watler * @version $Id$ */ public class PageSecurityImpl extends DocumentImpl implements PageSecurity { + private List constraintsDefs; + private List globalConstraintsRefs; private PageSecurityConstraintsDefList securityConstraintsDefs; + private Map securityConstraintsDefsMap; + private PageSecurityConstraintsRefList globalSecurityConstraintsRefs; public PageSecurityImpl() @@ -49,9 +53,9 @@ /** * accessConstraintsDefs - * + * * Access mutable persistent collection member for List wrappers. - * + * * @return persistent collection */ List accessConstraintsDefs() @@ -66,9 +70,9 @@ /** * accessGlobalConstraintsRefs - * + * * Access mutable persistent collection member for List wrappers. - * + * * @return persistent collection */ List accessGlobalConstraintsRefs() @@ -83,7 +87,7 @@ /** * clearSecurityConstraintsDefsMap - * + * * Clear previously cached security constraints definitions map. */ synchronized void clearSecurityConstraintsDefsMap() @@ -91,7 +95,9 @@ securityConstraintsDefsMap = null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#newSecurityConstraint() */ public SecurityConstraint newSecurityConstraint() @@ -100,7 +106,9 @@ return new PageSecuritySecurityConstraintImpl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.PageSecurity#getSecurityConstraintsDefs() */ public List getSecurityConstraintsDefs() @@ -114,8 +122,10 @@ } return securityConstraintsDefs; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#newSecurityConstraintsDef() */ public SecurityConstraintsDef newSecurityConstraintsDef() @@ -124,7 +134,9 @@ return new SecurityConstraintsDefImpl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.PageSecurity#setSecurityConstraintsDefs(java.util.List) */ public void setSecurityConstraintsDefs(List definitions) @@ -146,20 +158,26 @@ clearSecurityConstraintsDefsMap(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.PageSecurity#getSecurityConstraintsDef(java.lang.String) */ - public synchronized SecurityConstraintsDef getSecurityConstraintsDef(String name) + public synchronized SecurityConstraintsDef getSecurityConstraintsDef( + String name) { // build and cache security constraints definitions // map if necessary upon realization or after modification - if ((getSecurityConstraintsDefs() != null) && (securityConstraintsDefsMap == null)) + if ((getSecurityConstraintsDefs() != null) + && (securityConstraintsDefsMap == null)) { - securityConstraintsDefsMap = new HashMap((getSecurityConstraintsDefs().size() * 2) + 1); + securityConstraintsDefsMap = new HashMap( + (getSecurityConstraintsDefs().size() * 2) + 1); Iterator definitionsIter = getSecurityConstraintsDefs().iterator(); while (definitionsIter.hasNext()) { - SecurityConstraintsDef definition = (SecurityConstraintsDef)definitionsIter.next(); + SecurityConstraintsDef definition = (SecurityConstraintsDef) definitionsIter + .next(); String definitionName = definition.getName(); if (!securityConstraintsDefsMap.containsKey(definitionName)) { @@ -167,15 +185,15 @@ } } } - // lookup constraints definition using cached map - if (securityConstraintsDefsMap != null) - { - return (SecurityConstraintsDef)securityConstraintsDefsMap.get(name); - } + // lookup constraints definition using cached map + if (securityConstraintsDefsMap != null) { return (SecurityConstraintsDef) securityConstraintsDefsMap + .get(name); } return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.PageSecurity#getGlobalSecurityConstraintsRefs() */ public List getGlobalSecurityConstraintsRefs() @@ -185,12 +203,15 @@ // order and element uniqueness if (globalSecurityConstraintsRefs == null) { - globalSecurityConstraintsRefs = new PageSecurityConstraintsRefList(this); + globalSecurityConstraintsRefs = new PageSecurityConstraintsRefList( + this); } return globalSecurityConstraintsRefs; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.PageSecurity#setGlobalSecurityConstraintsRefs(java.util.List) */ public void setGlobalSecurityConstraintsRefs(List constraintsRefs) @@ -210,7 +231,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getType() */ public String getType() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecuritySecurityConstraintImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecuritySecurityConstraintImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/PageSecuritySecurityConstraintImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,7 +20,7 @@ /** * PageSecuritySecurityConstraintImpl - * + * * @author Randy Watler * @version $Id$ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintDefList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintDefList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintDefList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,12 +20,13 @@ /** * SecurityConstraintDefList - * + * * @author Randy Watler * @version $Id$ */ class SecurityConstraintDefList extends AbstractList { + private SecurityConstraintsDefImpl constraintsDef; SecurityConstraintDefList(SecurityConstraintsDefImpl constraintsDef) @@ -36,50 +37,56 @@ /** * validateConstraintForAdd - * + * * Validates constraint to be added to this list. - * - * @param constraint constraint to add + * + * @param constraint + * constraint to add * @return list element to add */ - private PageSecuritySecurityConstraintImpl validateConstraintForAdd(PageSecuritySecurityConstraintImpl constraint) + private PageSecuritySecurityConstraintImpl validateConstraintForAdd( + PageSecuritySecurityConstraintImpl constraint) { // validate constraint instance class - if (constraint == null) - { - throw new NullPointerException("Unable to add null to list."); - } + if (constraint == null) { throw new NullPointerException( + "Unable to add null to list."); } return constraint; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) { // implement for modifiable AbstractList: // validate index - if ((index < 0) || (index > constraintsDef.accessConstraintDefs().size())) - { - throw new IndexOutOfBoundsException("Unable to add to list at index: " + index); - } + if ((index < 0) + || (index > constraintsDef.accessConstraintDefs().size())) { throw new IndexOutOfBoundsException( + "Unable to add to list at index: " + index); } // verify constraint - PageSecuritySecurityConstraintImpl constraint = validateConstraintForAdd((PageSecuritySecurityConstraintImpl)element); + PageSecuritySecurityConstraintImpl constraint = validateConstraintForAdd((PageSecuritySecurityConstraintImpl) element); // add to underlying ordered list constraintsDef.accessConstraintDefs().add(index, constraint); // set apply order in added element if (index > 0) { - constraint.setApplyOrder(((PageSecuritySecurityConstraintImpl)constraintsDef.accessConstraintDefs().get(index-1)).getApplyOrder() + 1); + constraint + .setApplyOrder(((PageSecuritySecurityConstraintImpl) constraintsDef + .accessConstraintDefs().get(index - 1)) + .getApplyOrder() + 1); } else { constraint.setApplyOrder(0); } // maintain apply order in subsequent elements - for (int i = index, limit = constraintsDef.accessConstraintDefs().size() - 1; (i < limit); i++) + for (int i = index, limit = constraintsDef.accessConstraintDefs() + .size() - 1; (i < limit); i++) { - PageSecuritySecurityConstraintImpl nextConstraint = (PageSecuritySecurityConstraintImpl)constraintsDef.accessConstraintDefs().get(i + 1); + PageSecuritySecurityConstraintImpl nextConstraint = (PageSecuritySecurityConstraintImpl) constraintsDef + .accessConstraintDefs().get(i + 1); if (nextConstraint.getApplyOrder() <= constraint.getApplyOrder()) { // adjust apply order for next element @@ -94,7 +101,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) @@ -103,7 +112,9 @@ return constraintsDef.accessConstraintDefs().get(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) @@ -112,23 +123,28 @@ return constraintsDef.accessConstraintDefs().remove(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) { // implement for modifiable AbstractList: // verify constraint - PageSecuritySecurityConstraintImpl newConstraint = validateConstraintForAdd((PageSecuritySecurityConstraintImpl)element); + PageSecuritySecurityConstraintImpl newConstraint = validateConstraintForAdd((PageSecuritySecurityConstraintImpl) element); // set in underlying ordered list - PageSecuritySecurityConstraintImpl constraint = (PageSecuritySecurityConstraintImpl)constraintsDef.accessConstraintDefs().set(index, newConstraint); + PageSecuritySecurityConstraintImpl constraint = (PageSecuritySecurityConstraintImpl) constraintsDef + .accessConstraintDefs().set(index, newConstraint); // set apply order in new element newConstraint.setApplyOrder(constraint.getApplyOrder()); // return constraint return constraint; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,12 +22,13 @@ /** * SecurityConstraintList - * + * * @author Randy Watler * @version $Id$ */ class SecurityConstraintList extends AbstractList { + private SecurityConstraintsImpl constraints; SecurityConstraintList(SecurityConstraintsImpl constraints) @@ -38,46 +39,48 @@ /** * validateConstraintForAdd - * + * * Validates constraint to be added to this list. - * - * @param constraint to add + * + * @param constraint + * to add * @return list element to add */ - private SecurityConstraintImpl validateConstraintForAdd(SecurityConstraintImpl constraint) + private SecurityConstraintImpl validateConstraintForAdd( + SecurityConstraintImpl constraint) { // validate constraint instance class - if (constraint == null) - { - throw new NullPointerException("Unable to add null to list."); - } - if ((constraints.getSecurityConstraintClass() != null) && - !constraints.getSecurityConstraintClass().isInstance(constraint)) - { - throw new ClassCastException("Unable to add list element instance: expected " + constraints.getSecurityConstraintClass().getName() + ", got " + constraint.getClass().getName() + "."); - } + if (constraint == null) { throw new NullPointerException( + "Unable to add null to list."); } + if ((constraints.getSecurityConstraintClass() != null) + && !constraints.getSecurityConstraintClass().isInstance( + constraint)) { throw new ClassCastException( + "Unable to add list element instance: expected " + + constraints.getSecurityConstraintClass().getName() + + ", got " + constraint.getClass().getName() + "."); } return constraint; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) { // implement for modifiable AbstractList: // validate index - if ((index < 0) || (index > constraints.accessConstraints().size())) - { - throw new IndexOutOfBoundsException("Unable to add to list at index: " + index); - } + if ((index < 0) || (index > constraints.accessConstraints().size())) { throw new IndexOutOfBoundsException( + "Unable to add to list at index: " + index); } // verify constraint - SecurityConstraintImpl constraint = validateConstraintForAdd((SecurityConstraintImpl)element); + SecurityConstraintImpl constraint = validateConstraintForAdd((SecurityConstraintImpl) element); // add to underlying ordered list constraints.accessConstraints().add(index, constraint); // set apply order in added element if (index > 0) { - constraint.setApplyOrder(((SecurityConstraintImpl)constraints.accessConstraints().get(index-1)).getApplyOrder() + 1); + constraint.setApplyOrder(((SecurityConstraintImpl) constraints + .accessConstraints().get(index - 1)).getApplyOrder() + 1); } else { @@ -86,7 +89,8 @@ // maintain apply order in subsequent elements for (int i = index, limit = constraints.accessConstraints().size() - 1; (i < limit); i++) { - SecurityConstraintImpl nextConstraint = (SecurityConstraintImpl)constraints.accessConstraints().get(i + 1); + SecurityConstraintImpl nextConstraint = (SecurityConstraintImpl) constraints + .accessConstraints().get(i + 1); if (nextConstraint.getApplyOrder() <= constraint.getApplyOrder()) { // adjust apply order for next element @@ -103,7 +107,9 @@ constraints.clearAllSecurityConstraints(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) @@ -112,7 +118,9 @@ return constraints.accessConstraints().get(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) @@ -127,16 +135,19 @@ return removed; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) { // implement for modifiable AbstractList: // verify constraint - SecurityConstraintImpl newConstraint = validateConstraintForAdd((SecurityConstraintImpl)element); + SecurityConstraintImpl newConstraint = validateConstraintForAdd((SecurityConstraintImpl) element); // set in underlying ordered list - SecurityConstraintImpl constraint = (SecurityConstraintImpl)constraints.accessConstraints().set(index, newConstraint); + SecurityConstraintImpl constraint = (SecurityConstraintImpl) constraints + .accessConstraints().set(index, newConstraint); // set apply order in new element newConstraint.setApplyOrder(constraint.getApplyOrder()); // clear all cached security constraints @@ -145,7 +156,9 @@ return constraint; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintsDefImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintsDefImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintsDefImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,23 +23,26 @@ /** * SecurityConstraintsDefImpl - * + * * @author Randy Watler * @version $Id$ */ public class SecurityConstraintsDefImpl implements SecurityConstraintsDef { + private int id; + private String name; + private List constraintDefs = DatabasePageManagerUtils.createList(); private SecurityConstraintDefList securityConstraintDefs; /** * accessConstraintDefs - * + * * Access mutable persistent collection member for List wrappers. - * + * * @return persistent collection */ List accessConstraintDefs() @@ -52,7 +55,9 @@ return constraintDefs; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.SecurityConstraintsDef#getName() */ public String getName() @@ -60,7 +65,9 @@ return name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.SecurityConstraintsDef#setName(java.lang.String) */ public void setName(String name) @@ -68,7 +75,9 @@ this.name = name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.SecurityConstraintsDef#getSecurityConstraints() */ public List getSecurityConstraints() @@ -81,8 +90,10 @@ } return securityConstraintDefs; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.SecurityConstraintsDef#setSecurityConstraints(java.util.List) */ public void setSecurityConstraints(List constraints) @@ -102,31 +113,30 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { if (o instanceof SecurityConstraintsDefImpl) { - if (name != null) - { - return name.equals(((SecurityConstraintsDefImpl)o).getName()); - } - return (((SecurityConstraintsDefImpl)o).getName() == null); + if (name != null) { return name + .equals(((SecurityConstraintsDefImpl) o).getName()); } + return (((SecurityConstraintsDefImpl) o).getName() == null); } return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#hashCode() */ public int hashCode() { - if (name != null) - { - return name.hashCode(); - } + if (name != null) { return name.hashCode(); } return 0; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintsImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintsImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintsImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,26 +27,30 @@ /** * SecurityConstraintsImpl - * + * * @author Randy Watler * @version $Id$ */ public class SecurityConstraintsImpl implements SecurityConstraints { + private String owner; + private List constraints; + private List constraintsRefs; private SecurityConstraintList securityConstraints; + private SecurityConstraintsRefList securityConstraintsRefs; private List allConstraints; /** * accessConstraintsRefs - * + * * Access mutable persistent collection member for List wrappers. - * + * * @return persistent collection */ List accessConstraintsRefs() @@ -61,9 +65,9 @@ /** * accessConstraints - * + * * Access mutable persistent collection member for List wrappers. - * + * * @return persistent collection */ List accessConstraints() @@ -78,9 +82,9 @@ /** * getSecurityConstraintClass - * + * * Return class of persistent constraint instance. - * + * * @return constraint class */ public Class getSecurityConstraintClass() @@ -91,9 +95,9 @@ /** * getSecurityConstraintsRefClass - * + * * Return class of persistent constraints reference instance. - * + * * @return constraints reference class */ public Class getSecurityConstraintsRefClass() @@ -104,21 +108,26 @@ /** * checkConstraints - * - * @param actions actions to check - * @param userPrincipals principal users list - * @param rolePrincipals principal roles list - * @param groupPrincipals principal group list - * @param pageSecurity page security definitions + * + * @param actions + * actions to check + * @param userPrincipals + * principal users list + * @param rolePrincipals + * principal roles list + * @param groupPrincipals + * principal group list + * @param pageSecurity + * page security definitions * @throws SecurityException */ - public void checkConstraints(List actions, List userPrincipals, List rolePrincipals, List groupPrincipals, PageSecurity pageSecurity) throws SecurityException + public void checkConstraints(List actions, List userPrincipals, + List rolePrincipals, List groupPrincipals, PageSecurity pageSecurity) + throws SecurityException { // if owner defined, override all constraints and allow all access - if ((owner != null) && (userPrincipals != null) && userPrincipals.contains(owner)) - { - return; - } + if ((owner != null) && (userPrincipals != null) + && userPrincipals.contains(owner)) { return; } // skip missing or empty constraints: permit all access List checkConstraints = getAllSecurityConstraints(pageSecurity); @@ -131,29 +140,32 @@ { // check each action: // - if any actions explicity permitted, (including owner), - // assume no permissions are permitted by default + // assume no permissions are permitted by default // - if all constraints do not specify a permission, assume - // access is permitted by default - String action = (String)actionsIter.next(); + // access is permitted by default + String action = (String) actionsIter.next(); boolean actionPermitted = false; boolean actionNotPermitted = false; boolean anyActionsPermitted = (getOwner() != null); - + // check against constraints Iterator checkConstraintsIter = checkConstraints.iterator(); while (checkConstraintsIter.hasNext()) { - SecurityConstraintImpl constraint = (SecurityConstraintImpl)checkConstraintsIter.next(); - + SecurityConstraintImpl constraint = (SecurityConstraintImpl) checkConstraintsIter + .next(); + // if permissions specified, attempt to match constraint if (constraint.getPermissions() != null) { // explicit actions permitted anyActionsPermitted = true; - // test action permission match and user/role/group principal match - if (constraint.actionMatch(action) && - constraint.principalsMatch(userPrincipals, rolePrincipals, groupPrincipals, true)) + // test action permission match and user/role/group + // principal match + if (constraint.actionMatch(action) + && constraint.principalsMatch(userPrincipals, + rolePrincipals, groupPrincipals, true)) { actionPermitted = true; break; @@ -161,20 +173,22 @@ } else { - // permissions not specified: not permitted if any principal matched - if (constraint.principalsMatch(userPrincipals, rolePrincipals, groupPrincipals, false)) + // permissions not specified: not permitted if any + // principal matched + if (constraint.principalsMatch(userPrincipals, + rolePrincipals, groupPrincipals, false)) { actionNotPermitted = true; break; } } } - + // fail if any action not permitted - if ((!actionPermitted && anyActionsPermitted) || actionNotPermitted) - { - throw new SecurityException("SecurityConstraintsImpl.checkConstraints(): Access for " + action + " not permitted."); - } + if ((!actionPermitted && anyActionsPermitted) + || actionNotPermitted) { throw new SecurityException( + "SecurityConstraintsImpl.checkConstraints(): Access for " + + action + " not permitted."); } } } else @@ -183,8 +197,10 @@ // since no other constraints were found if ((getOwner() != null) && !actions.isEmpty()) { - String action = (String)actions.get(0); - throw new SecurityException("SecurityConstraintsImpl.checkConstraints(): Access for " + action + " not permitted, (not owner)."); + String action = (String) actions.get(0); + throw new SecurityException( + "SecurityConstraintsImpl.checkConstraints(): Access for " + + action + " not permitted, (not owner)."); } } } @@ -200,51 +216,56 @@ /** * getAllSecurityConstraints - * - * @param pageSecurity page security definitions + * + * @param pageSecurity + * page security definitions * @return all security constraints */ - private synchronized List getAllSecurityConstraints(PageSecurity pageSecurity) + private synchronized List getAllSecurityConstraints( + PageSecurity pageSecurity) { // return previously cached security constraints - if (allConstraints != null) - { - return allConstraints; - } + if (allConstraints != null) { return allConstraints; } // construct new ordered security constraints list allConstraints = DatabasePageManagerUtils.createList(); // add any defined security constraints - if ((getSecurityConstraints() != null) && !getSecurityConstraints().isEmpty()) + if ((getSecurityConstraints() != null) + && !getSecurityConstraints().isEmpty()) { allConstraints.addAll(securityConstraints); } // add any security constraints references - if ((getSecurityConstraintsRefs() != null) && !getSecurityConstraintsRefs().isEmpty()) + if ((getSecurityConstraintsRefs() != null) + && !getSecurityConstraintsRefs().isEmpty()) { - List referencedConstraints = dereferenceSecurityConstraintsRefs(getSecurityConstraintsRefs(), pageSecurity); + List referencedConstraints = dereferenceSecurityConstraintsRefs( + getSecurityConstraintsRefs(), pageSecurity); if (referencedConstraints != null) { allConstraints.addAll(referencedConstraints); } } - + // add any global decurity constraints references if (pageSecurity != null) { - List globalConstraintsRefs = pageSecurity.getGlobalSecurityConstraintsRefs(); - if ((globalConstraintsRefs != null) && !globalConstraintsRefs.isEmpty()) + List globalConstraintsRefs = pageSecurity + .getGlobalSecurityConstraintsRefs(); + if ((globalConstraintsRefs != null) + && !globalConstraintsRefs.isEmpty()) { - List referencedConstraints = dereferenceSecurityConstraintsRefs(globalConstraintsRefs, pageSecurity); + List referencedConstraints = dereferenceSecurityConstraintsRefs( + globalConstraintsRefs, pageSecurity); if (referencedConstraints != null) { allConstraints.addAll(referencedConstraints); } } } - + return allConstraints; } @@ -259,44 +280,54 @@ /** * dereferenceSecurityConstraintsRefs - * - * @param constraintsRefs contstraints references to be dereferenced - * @param pageSecurity page security definitions + * + * @param constraintsRefs + * contstraints references to be dereferenced + * @param pageSecurity + * page security definitions * @return security constraints */ - private List dereferenceSecurityConstraintsRefs(List constraintsRefs, PageSecurity pageSecurity) + private List dereferenceSecurityConstraintsRefs(List constraintsRefs, + PageSecurity pageSecurity) { List constraints = null; if (pageSecurity != null) - { + { // dereference each security constraints definition Iterator constraintsRefsIter = constraintsRefs.iterator(); while (constraintsRefsIter.hasNext()) { - String constraintsRef = (String)constraintsRefsIter.next(); - SecurityConstraintsDef securityConstraintsDef = pageSecurity.getSecurityConstraintsDef(constraintsRef); - if ((securityConstraintsDef != null) && (securityConstraintsDef.getSecurityConstraints() != null)) + String constraintsRef = (String) constraintsRefsIter.next(); + SecurityConstraintsDef securityConstraintsDef = pageSecurity + .getSecurityConstraintsDef(constraintsRef); + if ((securityConstraintsDef != null) + && (securityConstraintsDef.getSecurityConstraints() != null)) { if (constraints == null) { constraints = DatabasePageManagerUtils.createList(); } - constraints.addAll(securityConstraintsDef.getSecurityConstraints()); + constraints.addAll(securityConstraintsDef + .getSecurityConstraints()); } } } return constraints; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecurityConstraints#getOwner() */ public String getOwner() { return owner; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecurityConstraints#setOwner(java.lang.String) */ public void setOwner(String owner) @@ -306,7 +337,9 @@ clearAllSecurityConstraints(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecurityConstraints#getSecurityConstraints() */ public List getSecurityConstraints() @@ -319,8 +352,10 @@ } return securityConstraints; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecurityConstraints#setSecurityConstraints(java.util.List) */ public void setSecurityConstraints(List constraints) @@ -342,7 +377,9 @@ clearAllSecurityConstraints(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecurityConstraints#getSecurityConstraintsRefs() */ public List getSecurityConstraintsRefs() @@ -356,8 +393,10 @@ } return securityConstraintsRefs; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecurityConstraints#setSecurityConstraintsRefs(java.util.List) */ public void setSecurityConstraintsRefs(List constraintsRefs) @@ -379,14 +418,16 @@ clearAllSecurityConstraints(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecurityConstraints#isEmpty() */ public boolean isEmpty() { // test only persistent members for any specified constraints - return ((owner == null) && - ((constraints == null) || constraints.isEmpty()) && - ((constraintsRefs == null) || constraintsRefs.isEmpty())); + return ((owner == null) + && ((constraints == null) || constraints.isEmpty()) && ((constraintsRefs == null) || constraintsRefs + .isEmpty())); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintsRefList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintsRefList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/impl/SecurityConstraintsRefList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,12 +23,13 @@ /** * SecurityConstraintsRefList - * + * * @author Randy Watler * @version $Id$ */ class SecurityConstraintsRefList extends AbstractList { + private SecurityConstraintsImpl constraints; private List removedConstraintsRefs; @@ -41,20 +42,18 @@ /** * wrapNameStringForAdd - * - * Wraps and validates constraints ref name string - * to be added to this list. - * - * @param name constraints ref name string to add + * + * Wraps and validates constraints ref name string to be added to this list. + * + * @param name + * constraints ref name string to add * @return list element to add */ private BaseSecurityConstraintsRef wrapNameStringForAdd(String name) { // only non-null names supported - if (name == null) - { - throw new NullPointerException("Unable to add null to list."); - } + if (name == null) { throw new NullPointerException( + "Unable to add null to list."); } // wrap constraints ref name string; use // specific constraints ref name string wrapper BaseSecurityConstraintsRef constraintsRef = null; @@ -62,15 +61,22 @@ { try { - constraintsRef = (BaseSecurityConstraintsRef)constraints.getSecurityConstraintsRefClass().newInstance(); + constraintsRef = (BaseSecurityConstraintsRef) constraints + .getSecurityConstraintsRefClass().newInstance(); } catch (InstantiationException ie) { - throw new ClassCastException("Unable to create constratins reference list element instance: " + constraints.getSecurityConstraintsRefClass().getName() + ", (" + ie + ")."); + throw new ClassCastException( + "Unable to create constratins reference list element instance: " + + constraints.getSecurityConstraintsRefClass() + .getName() + ", (" + ie + ")."); } catch (IllegalAccessException iae) { - throw new ClassCastException("Unable to create constraints reference list element instance: " + constraints.getSecurityConstraintsRefClass().getName() + ", (" + iae + ")."); + throw new ClassCastException( + "Unable to create constraints reference list element instance: " + + constraints.getSecurityConstraintsRefClass() + .getName() + ", (" + iae + ")."); } } else @@ -79,10 +85,9 @@ } constraintsRef.setName(name); // make sure element is unique - if (constraints.accessConstraintsRefs().contains(constraintsRef)) - { - throw new IllegalArgumentException("Unable to add duplicate entry to list: " + constraintsRef.getName()); - } + if (constraints.accessConstraintsRefs().contains(constraintsRef)) { throw new IllegalArgumentException( + "Unable to add duplicate entry to list: " + + constraintsRef.getName()); } // retrieve from removed list to reuse // previously removed element if (removedConstraintsRefs != null) @@ -90,7 +95,8 @@ int removedIndex = removedConstraintsRefs.indexOf(constraintsRef); if (removedIndex >= 0) { - constraintsRef = (BaseSecurityConstraintsRef)removedConstraintsRefs.remove(removedIndex); + constraintsRef = (BaseSecurityConstraintsRef) removedConstraintsRefs + .remove(removedIndex); } } return constraintsRef; @@ -98,7 +104,7 @@ /** * getRemovedConstraintsRefs - * + * * @return removed constraints refs tracking collection */ private List getRemovedConstraintsRefs() @@ -110,25 +116,28 @@ return removedConstraintsRefs; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) { // implement for modifiable AbstractList: // validate index - if ((index < 0) || (index > constraints.accessConstraintsRefs().size())) - { - throw new IndexOutOfBoundsException("Unable to add to list at index: " + index); - } + if ((index < 0) || (index > constraints.accessConstraintsRefs().size())) { throw new IndexOutOfBoundsException( + "Unable to add to list at index: " + index); } // wrap and verify constraints ref name string - BaseSecurityConstraintsRef constraintsRef = wrapNameStringForAdd((String)element); + BaseSecurityConstraintsRef constraintsRef = wrapNameStringForAdd((String) element); // add to underlying ordered list constraints.accessConstraintsRefs().add(index, constraintsRef); // set apply order in added element if (index > 0) { - constraintsRef.setApplyOrder(((BaseSecurityConstraintsRef)constraints.accessConstraintsRefs().get(index-1)).getApplyOrder() + 1); + constraintsRef + .setApplyOrder(((BaseSecurityConstraintsRef) constraints + .accessConstraintsRefs().get(index - 1)) + .getApplyOrder() + 1); } else { @@ -137,11 +146,14 @@ // maintain apply order in subsequent elements for (int i = index, limit = constraints.accessConstraintsRefs().size() - 1; (i < limit); i++) { - BaseSecurityConstraintsRef nextConstraintsRef = (BaseSecurityConstraintsRef)constraints.accessConstraintsRefs().get(i + 1); - if (nextConstraintsRef.getApplyOrder() <= constraintsRef.getApplyOrder()) + BaseSecurityConstraintsRef nextConstraintsRef = (BaseSecurityConstraintsRef) constraints + .accessConstraintsRefs().get(i + 1); + if (nextConstraintsRef.getApplyOrder() <= constraintsRef + .getApplyOrder()) { // adjust apply order for next element - nextConstraintsRef.setApplyOrder(constraintsRef.getApplyOrder() + 1); + nextConstraintsRef + .setApplyOrder(constraintsRef.getApplyOrder() + 1); constraintsRef = nextConstraintsRef; } else @@ -154,26 +166,32 @@ constraints.clearAllSecurityConstraints(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) { // implement for modifiable AbstractList: // unwrap constraints ref name string - return ((BaseSecurityConstraintsRef)constraints.accessConstraintsRefs().get(index)).getName(); + return ((BaseSecurityConstraintsRef) constraints + .accessConstraintsRefs().get(index)).getName(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) { // implement for modifiable AbstractList - BaseSecurityConstraintsRef removed = (BaseSecurityConstraintsRef)constraints.accessConstraintsRefs().remove(index); + BaseSecurityConstraintsRef removed = (BaseSecurityConstraintsRef) constraints + .accessConstraintsRefs().remove(index); if (removed != null) { - // save removed element + // save removed element getRemovedConstraintsRefs().add(removed); // clear all cached security constraints constraints.clearAllSecurityConstraints(); @@ -181,16 +199,19 @@ return removed; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) { // implement for modifiable AbstractList: // wrap and verify constraints ref name string - BaseSecurityConstraintsRef newConstraintsRef = wrapNameStringForAdd((String)element); + BaseSecurityConstraintsRef newConstraintsRef = wrapNameStringForAdd((String) element); // set in underlying ordered list - BaseSecurityConstraintsRef constraintsRef = (BaseSecurityConstraintsRef)constraints.accessConstraintsRefs().set(index, newConstraintsRef); + BaseSecurityConstraintsRef constraintsRef = (BaseSecurityConstraintsRef) constraints + .accessConstraintsRefs().set(index, newConstraintsRef); // set apply order in new element newConstraintsRef.setApplyOrder(constraintsRef.getApplyOrder()); // save replaced element @@ -201,7 +222,9 @@ return constraintsRef.getName(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/AbstractBaseElement.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/AbstractBaseElement.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/AbstractBaseElement.java 2008-05-16 01:54:54 UTC (rev 940) @@ -47,13 +47,14 @@ import org.apache.jetspeed.security.RolePrincipal; import org.apache.jetspeed.security.UserPrincipal; - /** - * + * * @version $Id: AbstractBaseElement.java 516448 2007-03-09 16:25:47Z ate $ */ -public abstract class AbstractBaseElement implements java.io.Serializable, SecuredResource +public abstract class AbstractBaseElement implements java.io.Serializable, + SecuredResource { + private final static Log log = LogFactory.getLog(AbstractBaseElement.class); private String id = null; @@ -67,12 +68,12 @@ private SecurityConstraints constraints = null; private boolean permissionsEnabled; - + private DocumentHandlerFactory handlerFactory = null; public String getId() { - return this.id; + return this.id; } public void setId(String id) @@ -84,7 +85,7 @@ *

        * getTitle *

        - * + * * @see org.apache.jetspeed.om.page.BaseElement#getTitle() * @return */ @@ -97,7 +98,7 @@ *

        * setTitle *

        - * + * * @see org.apache.jetspeed.om.page.BaseElement#setTitle(java.lang.String) * @param title */ @@ -105,11 +106,12 @@ { this.title = title; } + /** *

        * getShortTitle *

        - * + * * @see org.apache.jetspeed.om.page.BaseElement#getShortTitle() * @return short title */ @@ -123,11 +125,12 @@ } return title; } + /** *

        * setShortTitle *

        - * + * * @see org.apache.jetspeed.om.page.BaseElement#setShortTitle(java.lang.String) * @param title */ @@ -140,7 +143,7 @@ *

        * getConstraintsEnabled *

        - * + * * @see org.apache.jetspeed.om.common.SecureResource#getConstraintsEnabled() * @return whether security relies on PSML constraints */ @@ -153,8 +156,9 @@ *

        * setConstraintsEnabled *

        - * - * @param enabled indicator + * + * @param enabled + * indicator */ public void setConstraintsEnabled(boolean enabled) { @@ -165,7 +169,7 @@ *

        * getSecurityConstraints *

        - * + * * @see org.apache.jetspeed.om.common.SecureResource#getSecurityConstraints() * @return the PSML security constraints */ @@ -173,14 +177,14 @@ { return constraints; } - + /** *

        * newSecurityConstraints *

        - * + * * @see org.apache.jetspeed.om.common.SecureResource#newSecurityConstraints() - * @return a new security constraints object + * @return a new security constraints object */ public SecurityConstraints newSecurityConstraints() { @@ -191,7 +195,7 @@ *

        * newSecurityConstraint *

        - * + * * @see org.apache.jetspeed.om.common.SecureResource#newSecurityConstraint() * @return security constraint */ @@ -204,7 +208,7 @@ *

        * setSecurityConstraints *

        - * + * * @see org.apache.jetspeed.om.common.SecureResource#setSecurityConstraints(org.apache.jetspeed.om.common.SecurityConstraints) * @param constraints */ @@ -217,7 +221,7 @@ *

        * checkConstraints *

        - * + * * @see org.apache.jetspeed.om.common.SecureResource#checkConstraints(java.lang.String) * @param actions * @throws SecurityException @@ -225,16 +229,11 @@ public void checkConstraints(String actions) throws SecurityException { // skip checks if not enabled - if (!getConstraintsEnabled()) - { - return; - } + if (!getConstraintsEnabled()) { return; } // validate specified actions - if (actions == null) - { - throw new SecurityException("AbstractBaseElement.checkConstraints(): No actions specified."); - } + if (actions == null) { throw new SecurityException( + "AbstractBaseElement.checkConstraints(): No actions specified."); } // get action names lists; separate view and other // actions to mimic file system permissions logic @@ -261,10 +260,8 @@ // get current request context subject Subject subject = JSSubject.getSubject(AccessController.getContext()); - if (subject == null) - { - throw new SecurityException("AbstractBaseElement.checkConstraints(): Missing JSSubject"); - } + if (subject == null) { throw new SecurityException( + "AbstractBaseElement.checkConstraints(): Missing JSSubject"); } // get user/group/role principal names List userPrincipals = null; @@ -303,11 +300,13 @@ // check constraints using parsed action and access lists if (viewActionList != null) { - checkConstraints(viewActionList, userPrincipals, rolePrincipals, groupPrincipals, false, grantViewActionAccess()); + checkConstraints(viewActionList, userPrincipals, rolePrincipals, + groupPrincipals, false, grantViewActionAccess()); } if (otherActionsList != null) { - checkConstraints(otherActionsList, userPrincipals, rolePrincipals, groupPrincipals, true, false); + checkConstraints(otherActionsList, userPrincipals, rolePrincipals, + groupPrincipals, true, false); } } @@ -315,7 +314,7 @@ *

        * checkConstraints *

        - * + * * @param actions * @param userPrincipals * @param rolePrincipals @@ -324,12 +323,16 @@ * @param checkParentsOnly * @throws SecurityException */ - public void checkConstraints(List actions, List userPrincipals, List rolePrincipals, List groupPrincipals, boolean checkNodeOnly, boolean checkParentsOnly) throws SecurityException + public void checkConstraints(List actions, List userPrincipals, + List rolePrincipals, List groupPrincipals, boolean checkNodeOnly, + boolean checkParentsOnly) throws SecurityException { // check node constraints if available if ((constraints != null) && !constraints.isEmpty()) { - ((SecurityConstraintsImpl)constraints).checkConstraints(actions, userPrincipals, rolePrincipals, groupPrincipals, getEffectivePageSecurity()); + ((SecurityConstraintsImpl) constraints).checkConstraints(actions, + userPrincipals, rolePrincipals, groupPrincipals, + getEffectivePageSecurity()); } } @@ -337,7 +340,7 @@ *

        * getPermissionsEnabled *

        - * + * * @see org.apache.jetspeed.om.common.SecureResource#getPermissionsEnabled() * @return */ @@ -350,8 +353,9 @@ *

        * setPermissionsEnabled *

        - * - * @param enabled indicator + * + * @param enabled + * indicator */ public void setPermissionsEnabled(boolean enabled) { @@ -362,44 +366,47 @@ *

        * checkPermissions *

        - * + * * @see org.apache.jetspeed.om.common.SecuredResource#checkPermissions(int) - * @param mask Mask of actions requested + * @param mask + * Mask of actions requested * @throws SecurityException */ public void checkPermissions(int mask) throws SecurityException { // skip checks if not enabled - if (!getPermissionsEnabled()) - { - return; - } + if (!getPermissionsEnabled()) { return; } - // separate view and other actions to mimic file system permissions logic + // separate view and other actions to mimic file system permissions + // logic boolean viewAction = (mask & JetspeedActions.MASK_VIEW) == JetspeedActions.MASK_VIEW; int otherMask = mask & ~JetspeedActions.MASK_VIEW; // check permissions using parsed actions if (viewAction) { - checkPermissions(JetspeedActions.MASK_VIEW, false, grantViewActionAccess()); + checkPermissions(JetspeedActions.MASK_VIEW, false, + grantViewActionAccess()); } if (otherMask != 0) { checkPermissions(otherMask, true, false); } } + /** *

        * checkPermissions *

        - * - * @param mask of actions + * + * @param mask + * of actions * @param checkNodeOnly * @param checkParentsOnly * @throws SecurityException */ - public void checkPermissions(int mask, boolean checkNodeOnly, boolean checkParentsOnly) throws SecurityException + public void checkPermissions(int mask, boolean checkNodeOnly, + boolean checkParentsOnly) throws SecurityException { // check page and folder permissions String physicalPermissionPath = getPhysicalPermissionPath(); @@ -408,15 +415,19 @@ // check permissions using physical path try { - checkPermissions(physicalPermissionPath, mask, checkNodeOnly, checkParentsOnly); + checkPermissions(physicalPermissionPath, mask, checkNodeOnly, + checkParentsOnly); } catch (SecurityException physicalSE) { // fallback check using logical path if available and different String logicalPermissionPath = getLogicalPermissionPath(); - if ((logicalPermissionPath != null) && !logicalPermissionPath.equals(physicalPermissionPath)) + if ((logicalPermissionPath != null) + && !logicalPermissionPath + .equals(physicalPermissionPath)) { - checkPermissions(logicalPermissionPath, mask, checkNodeOnly, checkParentsOnly); + checkPermissions(logicalPermissionPath, mask, + checkNodeOnly, checkParentsOnly); } else { @@ -425,18 +436,21 @@ } } } + /** *

        * checkPermissions *

        - * + * * @param path - * @param mask Mask of actions requested + * @param mask + * Mask of actions requested * @param checkNodeOnly * @param checkParentsOnly * @throws SecurityException */ - public void checkPermissions(String path, int mask, boolean checkNodeOnly, boolean checkParentsOnly) throws SecurityException + public void checkPermissions(String path, int mask, boolean checkNodeOnly, + boolean checkParentsOnly) throws SecurityException { // check actions permissions try @@ -457,7 +471,7 @@ *

        * getLogicalPermissionPath *

        - * + * * @return path used for permissions checks */ public String getLogicalPermissionPath() @@ -469,13 +483,15 @@ *

        * getPhysicalPermissionPath *

        - * + * * @return path used for permissions checks */ public String getPhysicalPermissionPath() { // no permissions path available by default - log.warn("getPhysicalPermissionPath(): no permission path available for " + this + " element."); + log + .warn("getPhysicalPermissionPath(): no permission path available for " + + this + " element."); return null; } @@ -483,7 +499,7 @@ *

        * checkAccess *

        - * + * * @see org.apache.jetspeed.om.common.SecureResource#checkAccess(java.lang.String) * @param actions * @throws SecurityException @@ -506,7 +522,7 @@ *

        * grantViewActionAccess *

        - * + * * @return granted access for view action */ public boolean grantViewActionAccess() @@ -517,7 +533,7 @@ /** * getEffectivePageSecurity - * + * * @return effective page security object */ public PageSecurity getEffectivePageSecurity() @@ -530,7 +546,7 @@ *

        * getHandlerFactory *

        - * + * * @return element handler factory */ public DocumentHandlerFactory getHandlerFactory() @@ -542,8 +558,9 @@ *

        * setHandlerFactory *

        - * - * @param factory element handler factory + * + * @param factory + * element handler factory */ public void setHandlerFactory(DocumentHandlerFactory factory) { @@ -554,29 +571,30 @@ *

        * equals *

        - * + * * @see java.lang.Object#equals(java.lang.Object) * @param obj * @return whether the supplied object equals this one */ - public boolean equals( Object obj ) + public boolean equals(Object obj) { - if(obj instanceof BaseElement) + if (obj instanceof BaseElement) { AbstractBaseElement element = (AbstractBaseElement) obj; - return id != null && element.getId() != null && id.equals(element.getId()); + return id != null && element.getId() != null + && id.equals(element.getId()); } else { return false; } } - + /** *

        * hashCode *

        - * + * * @see java.lang.Object#hashCode() * @return the hashcode for this object */ @@ -584,25 +602,26 @@ { return ((null != id) ? id.hashCode() : -1); } - + /** *

        * toString *

        - * + * * @see java.lang.Object#toString() * @return the id as a string representation of this object */ public String toString() - { + { return getId(); } /** *

        - * checkAccess returns a set of nodes we can access. It may be the passed in node set or a partial copy. + * checkAccess returns a set of nodes we can access. It may be the passed in + * node set or a partial copy. *

        - * + * * @param nodes * @param actions * @return a NodeSet containing the nodes allowing access @@ -616,7 +635,8 @@ Iterator checkAccessIter = nodes.iterator(); while (checkAccessIter.hasNext()) { - AbstractBaseElement node = (AbstractBaseElement)checkAccessIter.next(); + AbstractBaseElement node = (AbstractBaseElement) checkAccessIter + .next(); try { // check access @@ -626,7 +646,7 @@ if (filteredNodes != null) { // permitted, add to filteredNodes nodes - filteredNodes.add((Node)node); + filteredNodes.add((Node) node); } } catch (SecurityException se) @@ -636,11 +656,12 @@ { // not permitted, copy previously permitted nodes // to new filteredNodes node set with same comparator - filteredNodes = new NodeSetImpl(null, ((NodeSetImpl) nodes).getComparator()); + filteredNodes = new NodeSetImpl(null, + ((NodeSetImpl) nodes).getComparator()); Iterator copyIter = nodes.iterator(); while (copyIter.hasNext()) { - Node copyNode = (Node)copyIter.next(); + Node copyNode = (Node) copyIter.next(); if (copyNode != node) { filteredNodes.add(copyNode); @@ -655,17 +676,14 @@ } // return filteredNodes nodes if generated - if (filteredNodes != null) - { - return filteredNodes; - } + if (filteredNodes != null) { return filteredNodes; } } return nodes; } /** - * unmarshalled - notification that this instance has been - * loaded from the persistent store + * unmarshalled - notification that this instance has been loaded from the + * persistent store */ public void unmarshalled() { @@ -673,8 +691,8 @@ } /** - * marshalling - notification that this instance is to - * be saved to the persistent store + * marshalling - notification that this instance is to be saved to the + * persistent store */ public void marshalling() { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/DefaultsImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/DefaultsImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/DefaultsImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,8 +17,8 @@ package org.apache.jetspeed.om.page.psml; +import java.util.HashMap; import java.util.Map; -import java.util.HashMap; import org.apache.jetspeed.om.page.Fragment; @@ -29,11 +29,12 @@ { private String skin = null; + private Map decoratorMap = new HashMap(); /** * getSkin - * + * * @return skin name used in decorators */ public String getSkin() @@ -43,8 +44,9 @@ /** * setSkin - * - * @param skin name used in decorators + * + * @param skin + * name used in decorators */ public void setSkin(String skin) { @@ -53,29 +55,32 @@ /** * getDecorator - * - * @param type Fragment.LAYOUT or Fragment.PORTLET constants + * + * @param type + * Fragment.LAYOUT or Fragment.PORTLET constants * @return decorator name */ public String getDecorator(String type) { - return (String)decoratorMap.get(type); + return (String) decoratorMap.get(type); } /** * setDecorator - * - * @param type Fragment.LAYOUT or Fragment.PORTLET constants - * @param decorator decorator name + * + * @param type + * Fragment.LAYOUT or Fragment.PORTLET constants + * @param decorator + * decorator name */ public void setDecorator(String type, String decorator) { - decoratorMap.put(type,decorator); + decoratorMap.put(type, decorator); } /** * getLayoutDecorator - * + * * @return Fragment.LAYOUT decorator name */ public String getLayoutDecorator() @@ -85,17 +90,18 @@ /** * setLayoutDecorator - * - * @param decorator Fragment.LAYOUT decorator name + * + * @param decorator + * Fragment.LAYOUT decorator name */ public void setLayoutDecorator(String decorator) { - setDecorator(Fragment.LAYOUT,decorator); + setDecorator(Fragment.LAYOUT, decorator); } /** * getPortletDecorator - * + * * @return Fragment.PORTLET decorator name */ public String getPortletDecorator() @@ -105,12 +111,13 @@ /** * setPortletDecorator - * - * @param decorator Fragment.PORTLET decorator name + * + * @param decorator + * Fragment.PORTLET decorator name */ public void setPortletDecorator(String decorator) { - setDecorator(Fragment.PORTLET,decorator); + setDecorator(Fragment.PORTLET, decorator); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/DocumentImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/DocumentImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/DocumentImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,7 +19,6 @@ import org.apache.jetspeed.om.page.Document; import org.apache.jetspeed.page.document.psml.AbstractNode; - /** *

        * Link @@ -32,15 +31,16 @@ * @version $Id: LinkImpl.java 314803 2005-10-12 06:35:19Z rwatler $ * */ -public abstract class DocumentImpl extends AbstractNode implements Document +public abstract class DocumentImpl extends AbstractNode implements Document { - + private String version; - private boolean dirty=false; - /** - * unmarshalled - notification that this instance has been - * loaded from the persistent store + private boolean dirty = false; + + /** + * unmarshalled - notification that this instance has been loaded from the + * persistent store */ public void unmarshalled() { @@ -53,6 +53,7 @@ setVersion(getVersion()); } } + /** * @return Returns the version. */ @@ -60,20 +61,24 @@ { return version; } + /** - * @param version The version to set. + * @param version + * The version to set. */ public void setVersion(String version) { this.version = version; } - - public boolean isDirty() { - return dirty; - } - - public void setDirty(boolean dirty) { - this.dirty = dirty; - } + public boolean isDirty() + { + return dirty; + } + + public void setDirty(boolean dirty) + { + this.dirty = dirty; + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FilteredFragmentList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FilteredFragmentList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FilteredFragmentList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,13 +22,15 @@ /** * FragmentList - * + * * @author Randy Watler * @version $Id$ */ class FilteredFragmentList extends AbstractList { + private FragmentImpl fragment; + private List filteredList; FilteredFragmentList(FragmentImpl fragment, List filteredList) @@ -38,7 +40,9 @@ this.filteredList = filteredList; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) @@ -50,11 +54,13 @@ // maintain page implementation reference if ((fragment.getPage() != null) && (element instanceof FragmentImpl)) { - ((FragmentImpl)element).setPage(fragment.getPage()); + ((FragmentImpl) element).setPage(fragment.getPage()); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) @@ -63,7 +69,9 @@ return filteredList.get(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) @@ -86,7 +94,9 @@ return o; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) @@ -109,12 +119,14 @@ // maintain page implementation reference if ((fragment.getPage() != null) && (element instanceof FragmentImpl)) { - ((FragmentImpl)element).setPage(fragment.getPage()); + ((FragmentImpl) element).setPage(fragment.getPage()); } return o; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FragmentImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FragmentImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FragmentImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,11 +33,12 @@ /** * @version $Id: FragmentImpl.java 551606 2007-06-28 16:07:53Z taylor $ */ -public class FragmentImpl extends AbstractBaseElement implements Fragment, java.io.Serializable +public class FragmentImpl extends AbstractBaseElement implements Fragment, + java.io.Serializable { - private static int fragment_id_counter = 0; - + private static int fragment_id_counter = 0; + private String type = null; private String state = null; @@ -51,9 +52,9 @@ private List fragments = new ArrayList(); private List propertiesList = new ArrayList(); - + private List preferences = new ArrayList(); - + private Map propertiesMap = new HashMap(); private String name; @@ -63,6 +64,7 @@ private PageImpl page; private boolean dirty = false; + /** *

        * Default Constructor. @@ -74,12 +76,15 @@ public FragmentImpl(String id) { - if (id == null || id.length() == 0){ - setId(generateId()); - dirty=true; - } else { - setId(id); - } + if (id == null || id.length() == 0) + { + setId(generateId()); + dirty = true; + } + else + { + setId(id); + } } public String getType() @@ -87,7 +92,7 @@ return this.type; } - public void setType( String type ) + public void setType(String type) { this.type = type; } @@ -97,7 +102,7 @@ return this.state; } - public void setState( String state ) + public void setState(String state) { this.state = state; } @@ -107,7 +112,7 @@ return this.mode; } - public void setMode( String mode ) + public void setMode(String mode) { this.mode = mode; } @@ -117,7 +122,7 @@ return this.decorator; } - public void setDecorator( String decoratorName ) + public void setDecorator(String decoratorName) { this.decorator = decoratorName; } @@ -127,7 +132,7 @@ return this.skin; } - public void setSkin( String skin ) + public void setSkin(String skin) { this.skin = skin; } @@ -157,41 +162,35 @@ { return (List) this.propertiesList; } - + /** * @see org.apache.jetspeed.om.page.Fragment#getProperty(java.lang.String) */ public String getProperty(String propName) { - return (String)propertiesMap.get(propName); + return (String) propertiesMap.get(propName); } - + /** * @see org.apache.jetspeed.om.page.Fragment#getIntProperty(java.lang.String) */ public int getIntProperty(String propName) { - String prop = (String)propertiesMap.get(propName); - if (prop != null) - { - return Integer.parseInt(prop); - } + String prop = (String) propertiesMap.get(propName); + if (prop != null) { return Integer.parseInt(prop); } return -1; } - + /** * @see org.apache.jetspeed.om.page.Fragment#getFloatProperty(java.lang.String) */ public float getFloatProperty(String propName) { - String prop = (String)propertiesMap.get(propName); - if (prop != null) - { - return Float.parseFloat(prop); - } + String prop = (String) propertiesMap.get(propName); + if (prop != null) { return Float.parseFloat(prop); } return -1.0F; } - + /** * @see org.apache.jetspeed.om.page.Fragment#getProperties() */ @@ -222,7 +221,7 @@ propertiesMap.remove(ROW_PROPERTY_NAME); } } - + /** * @see org.apache.jetspeed.om.page.Fragment#getLayoutColumn() */ @@ -245,15 +244,15 @@ propertiesMap.remove(COLUMN_PROPERTY_NAME); } } - + /** * @see org.apache.jetspeed.om.page.Fragment#getLayoutSizes() */ public String getLayoutSizes() { - return (String)propertiesMap.get(SIZES_PROPERTY_NAME); + return (String) propertiesMap.get(SIZES_PROPERTY_NAME); } - + /** * @see org.apache.jetspeed.om.page.Fragment#setLayoutSizes(java.lang.String) */ @@ -291,7 +290,7 @@ propertiesMap.remove(X_PROPERTY_NAME); } } - + /** * @see org.apache.jetspeed.om.page.Fragment#getLayoutY() */ @@ -393,13 +392,14 @@ * @param obj * @return */ - public boolean equals( Object obj ) + public boolean equals(Object obj) { boolean isEqual = false; if (obj != null && obj instanceof Fragment) { Fragment aFragment = (Fragment) obj; - if ((null != aFragment.getId()) && (null != getId()) && (getId().equals(aFragment.getId()))) + if ((null != aFragment.getId()) && (null != getId()) + && (getId().equals(aFragment.getId()))) { isEqual = true; } @@ -448,7 +448,7 @@ * @see org.apache.jetspeed.om.page.Fragment#setName(java.lang.String) * @param name */ - public void setName( String name ) + public void setName(String name) { this.name = name; @@ -469,9 +469,9 @@ public void setPreferences(List preferences) { - this.preferences = preferences; - } - + this.preferences = preferences; + } + PageImpl getPage() { return page; @@ -481,96 +481,100 @@ { // set page implementation this.page = page; - if (dirty){ - page.setDirty(dirty); - } + if (dirty) + { + page.setDirty(dirty); + } // propagate to children if (fragments != null) { Iterator fragmentsIter = fragments.iterator(); while (fragmentsIter.hasNext()) { - ((FragmentImpl)fragmentsIter.next()).setPage(page); + ((FragmentImpl) fragmentsIter.next()).setPage(page); } } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.psml.AbstractElementImpl#getEffectivePageSecurity() */ public PageSecurity getEffectivePageSecurity() { // delegate to page implementation - if (page != null) - { - return page.getEffectivePageSecurity(); - } + if (page != null) { return page.getEffectivePageSecurity(); } return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.psml.AbstractElementImpl#getLogicalPermissionPath() */ public String getLogicalPermissionPath() { // use page implementation path as base and append name - if ((page != null) && (getName() != null)) - { - return page.getLogicalPermissionPath() + Folder.PATH_SEPARATOR + getName(); - } + if ((page != null) && (getName() != null)) { return page + .getLogicalPermissionPath() + + Folder.PATH_SEPARATOR + getName(); } return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.psml.AbstractBaseElementImpl#getPhysicalPermissionPath() */ public String getPhysicalPermissionPath() { // use page implementation path as base and append name - if ((page != null) && (getName() != null)) - { - return page.getPhysicalPermissionPath() + Folder.PATH_SEPARATOR + getName(); - } + if ((page != null) && (getName() != null)) { return page + .getPhysicalPermissionPath() + + Folder.PATH_SEPARATOR + getName(); } return null; } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.page.psml.AbstractElementImpl#checkPermissions(java.lang.String, int, boolean, boolean) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.page.psml.AbstractElementImpl#checkPermissions(java.lang.String, + * int, boolean, boolean) */ - public void checkPermissions(String path, int mask, boolean checkNodeOnly, boolean checkParentsOnly) throws SecurityException + public void checkPermissions(String path, int mask, boolean checkNodeOnly, + boolean checkParentsOnly) throws SecurityException { // always check for granted fragment permissions FragmentPermission permission = new FragmentPermission(path, mask); AccessController.checkPermission(permission); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getConstraintsEnabled() */ public boolean getConstraintsEnabled() { - if (page != null) - { - return page.getConstraintsEnabled(); - } + if (page != null) { return page.getConstraintsEnabled(); } return false; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getPermissionsEnabled() */ public boolean getPermissionsEnabled() { - if (page != null) - { - return page.getPermissionsEnabled(); - } + if (page != null) { return page.getPermissionsEnabled(); } return false; } /** - * unmarshalled - notification that this instance has been - * loaded from the persistent store + * unmarshalled - notification that this instance has been loaded from the + * persistent store */ public void unmarshalled() { @@ -582,7 +586,7 @@ Iterator fragmentIter = fragments.iterator(); while (fragmentIter.hasNext()) { - ((FragmentImpl)fragmentIter.next()).unmarshalled(); + ((FragmentImpl) fragmentIter.next()).unmarshalled(); } // load the properties map from list @@ -596,8 +600,8 @@ } /** - * marshalling - notification that this instance is to - * be saved to the persistent store + * marshalling - notification that this instance is to be saved to the + * persistent store */ public void marshalling() { @@ -621,8 +625,8 @@ { Map.Entry prop = (Map.Entry) propsIter.next(); PropertyImpl listProp = new PropertyImpl(); - listProp.setName((String)prop.getKey()); - listProp.setValue((String)prop.getValue()); + listProp.setName((String) prop.getKey()); + listProp.setValue((String) prop.getValue()); propertiesList.add(listProp); } } @@ -632,7 +636,7 @@ Iterator fragmentIter = fragments.iterator(); while (fragmentIter.hasNext()) { - ((FragmentImpl)fragmentIter.next()).marshalling(); + ((FragmentImpl) fragmentIter.next()).marshalling(); } // notify super class implementation @@ -641,12 +645,13 @@ /** * filterFragmentsByAccess - * + * * Filter fragments list for view access. - * - * @param nodes list containing fragments to check - * @return original list if all elements viewable, a filtered - * partial list, or null if all filtered for view access + * + * @param nodes + * list containing fragments to check + * @return original list if all elements viewable, a filtered partial list, + * or null if all filtered for view access */ List filterFragmentsByAccess(List fragments) { @@ -676,12 +681,13 @@ if (filteredFragments == null) { // not permitted, copy previously permitted fragments - // to new filteredFragments node set with same comparator + // to new filteredFragments node set with same + // comparator filteredFragments = new ArrayList(fragments.size()); Iterator copyIter = fragments.iterator(); while (copyIter.hasNext()) { - Fragment copyFragment = (Fragment)copyIter.next(); + Fragment copyFragment = (Fragment) copyIter.next(); if (copyFragment != fragment) { filteredFragments.add(copyFragment); @@ -699,14 +705,17 @@ if (filteredFragments != null) { // patch for JS2-633, security filtered (permission) lists - // were returning null, we need an empty fragment list + // were returning null, we need an empty fragment list return new FilteredFragmentList(this, filteredFragments); } } return fragments; } - - private synchronized static String generateId(){ - return new StringBuffer("F.").append(Long.toHexString(System.currentTimeMillis())).append(".").append(fragment_id_counter++).toString(); + + private synchronized static String generateId() + { + return new StringBuffer("F.").append( + Long.toHexString(System.currentTimeMillis())).append(".") + .append(fragment_id_counter++).toString(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FragmentList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FragmentList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FragmentList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,12 +20,13 @@ /** * FragmentList - * + * * @author Randy Watler * @version $Id$ */ class FragmentList extends AbstractList { + private FragmentImpl fragment; FragmentList(FragmentImpl fragment) @@ -34,7 +35,9 @@ this.fragment = fragment; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#add(int,java.lang.Object) */ public void add(int index, Object element) @@ -44,11 +47,13 @@ fragment.accessFragments().add(index, element); if ((fragment.getPage() != null) && (element instanceof FragmentImpl)) { - ((FragmentImpl)element).setPage(fragment.getPage()); + ((FragmentImpl) element).setPage(fragment.getPage()); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#get(int) */ public Object get(int index) @@ -57,7 +62,9 @@ return fragment.accessFragments().get(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#remove(int) */ public Object remove(int index) @@ -66,7 +73,9 @@ return fragment.accessFragments().remove(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#set(int,java.lang.Object) */ public Object set(int index, Object element) @@ -76,12 +85,14 @@ Object o = fragment.accessFragments().set(index, element); if ((fragment.getPage() != null) && (element instanceof FragmentImpl)) { - ((FragmentImpl)element).setPage(fragment.getPage()); + ((FragmentImpl) element).setPage(fragment.getPage()); } return o; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.List#size() */ public int size() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FragmentPreferenceImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FragmentPreferenceImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/FragmentPreferenceImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,58 +25,61 @@ /** * - * Preference implementation to be used with Fragment-based - * portlet Preferences. + * Preference implementation to be used with Fragment-based portlet Preferences. * * @author Scott T. Weaver - * + * */ -public class FragmentPreferenceImpl implements Preference, PreferenceCtrl, FragmentPreference +public class FragmentPreferenceImpl implements Preference, PreferenceCtrl, + FragmentPreference { + private String name; + private List values; + private boolean readOnly; - + public String getName() { return name; } - + public void setName(String name) { this.name = name; } - + public boolean isReadOnly() { return readOnly; } - + public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; } - + public void setReadOnly(String arg0) { - readOnly = new Boolean(arg0).booleanValue(); + readOnly = new Boolean(arg0).booleanValue(); } - + public Iterator getValues() { return getValueList().iterator(); } - + public List getValueList() { return this.values; } - + public void setValues(List values) { this.values = values; } - + public void setValueList(List values) { setValues(values); @@ -87,5 +90,4 @@ return values != null && values.size() > 0; } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/LinkImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/LinkImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/LinkImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,33 +23,36 @@ * Link *

        *

        - * + * *

        + * * @author Scott T. Weaver * @version $Id: LinkImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public class LinkImpl extends DocumentImpl implements Link +public class LinkImpl extends DocumentImpl implements Link { - + private String skin; private String target; - + /** *

        * getType *

        - * + * * @see org.apache.jetspeed.om.page.Document#getType() * @return */ public String getType() - { + { return DOCUMENT_TYPE; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Link#getSkin() */ public String getSkin() @@ -57,10 +60,12 @@ return skin; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Link#setSkin(java.lang.String) */ - public void setSkin( String skin ) + public void setSkin(String skin) { this.skin = skin; } @@ -72,11 +77,12 @@ { return target; } - + /** - * @param target The target to set. + * @param target + * The target to set. */ - public void setTarget( String target ) + public void setTarget(String target) { this.target = target; } @@ -85,7 +91,7 @@ *

        * grantViewActionAccess *

        - * + * * @return granted access for view action */ public boolean grantViewActionAccess() @@ -94,12 +100,13 @@ // are probably not a security related concern but rather // should always be viewable, (subject to folder access) String hrefUrl = getUrl(); - return ((hrefUrl != null) && (hrefUrl.startsWith("http://") || hrefUrl.startsWith("https://"))); + return ((hrefUrl != null) && (hrefUrl.startsWith("http://") || hrefUrl + .startsWith("https://"))); } /** - * unmarshalled - notification that this instance has been - * loaded from the persistent store + * unmarshalled - notification that this instance has been loaded from the + * persistent store */ public void unmarshalled() { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/PageImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/PageImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/PageImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -43,6 +43,7 @@ */ public class PageImpl extends DocumentImpl implements Page { + private DefaultsImpl defaults = new DefaultsImpl(); private Fragment root = null; @@ -53,7 +54,7 @@ * menuDefinitions - menu definitions for page */ private List menuDefinitions; - + public PageImpl() { // empty constructor @@ -64,17 +65,17 @@ *

        * setId *

        - * + * * @see org.apache.jetspeed.om.page.psml.AbstractBaseElement#setId(java.lang.String) * @param id */ - public void setId( String id ) + public void setId(String id) { // Cheaper to generate the hash code now then every call to hashCode() - hashCode = (Page.class.getName()+":"+id).hashCode(); - super.setId(id); + hashCode = (Page.class.getName() + ":" + id).hashCode(); + super.setId(id); } - + /** *

        * equals @@ -84,13 +85,13 @@ * @param obj * @return */ - public boolean equals( Object obj ) + public boolean equals(Object obj) { if (obj instanceof Page) { Page page = (Page) obj; - return page != null && page.getId() != null && - this.getId() != null && this.getId().equals(page.getId()); + return page != null && page.getId() != null && this.getId() != null + && this.getId().equals(page.getId()); } else { @@ -108,7 +109,7 @@ * @return */ public int hashCode() - { + { return hashCode; } @@ -117,12 +118,14 @@ return defaults.getSkin(); } - public void setSkin( String skinName ) + public void setSkin(String skinName) { defaults.setSkin(skinName); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Page#getEffectiveDefaultDecorator(java.lang.String) */ public String getEffectiveDefaultDecorator(String fragmentType) @@ -132,21 +135,19 @@ if (decorator == null) { // delegate to parent folder - Folder parentFolder = (Folder)getParent(); - if (parentFolder != null) - { - return parentFolder.getEffectiveDefaultDecorator(fragmentType); - } + Folder parentFolder = (Folder) getParent(); + if (parentFolder != null) { return parentFolder + .getEffectiveDefaultDecorator(fragmentType); } } return decorator; } - public String getDefaultDecorator( String fragmentType ) + public String getDefaultDecorator(String fragmentType) { return defaults.getDecorator(fragmentType); } - public void setDefaultDecorator( String decoratorName, String fragmentType ) + public void setDefaultDecorator(String decoratorName, String fragmentType) { defaults.setDecorator(fragmentType, decoratorName); } @@ -156,16 +157,16 @@ return this.root; } - public void setRootFragment( Fragment root ) + public void setRootFragment(Fragment root) { this.root = root; if (root instanceof FragmentImpl) { - ((FragmentImpl)root).setPage(this); - } + ((FragmentImpl) root).setPage(this); + } } - public Fragment getFragmentById( String id ) + public Fragment getFragmentById(String id) { Stack stack = new Stack(); if (getRootFragment() != null) @@ -197,7 +198,7 @@ return f; } - public Fragment removeFragmentById( String id ) + public Fragment removeFragmentById(String id) { // find fragment by id, tracking fragment parent Map parents = new HashMap(); @@ -213,7 +214,7 @@ while (i.hasNext()) { - Fragment child = (Fragment)i.next(); + Fragment child = (Fragment) i.next(); stack.push(child); parents.put(child, f); } @@ -231,13 +232,10 @@ // remove fragment from parent/page root if (f != null) { - Fragment parent = (Fragment)parents.get(f); + Fragment parent = (Fragment) parents.get(f); if (parent != null) { - if (parent.getFragments().remove(f)) - { - return f; - } + if (parent.getFragments().remove(f)) { return f; } } else { @@ -253,7 +251,7 @@ return null; } - public List getFragmentsByName( String name ) + public List getFragmentsByName(String name) { List fragments = DatabasePageManagerUtils.createList(); @@ -297,7 +295,7 @@ return this.defaults; } - public void setDefaults( DefaultsImpl defaults ) + public void setDefaults(DefaultsImpl defaults) { this.defaults = defaults; } @@ -306,18 +304,18 @@ *

        * getType *

        - * + * * @see org.apache.jetspeed.om.page.Document#getType() * @return */ public String getType() - { + { return DOCUMENT_TYPE; } /** * getMenuDefinitions - get list of menu definitions - * + * * @return definition list */ public List getMenuDefinitions() @@ -327,7 +325,7 @@ /** * newMenuDefinition - creates a new empty menu definition - * + * * @return a newly created MenuDefinition object for use in Page */ public MenuDefinition newMenuDefinition() @@ -337,7 +335,7 @@ /** * newMenuExcludeDefinition - creates a new empty menu exclude definition - * + * * @return a newly created MenuExcludeDefinition object for use in Page */ public MenuExcludeDefinition newMenuExcludeDefinition() @@ -347,7 +345,7 @@ /** * newMenuIncludeDefinition - creates a new empty menu include definition - * + * * @return a newly created MenuIncludeDefinition object for use in Page */ public MenuIncludeDefinition newMenuIncludeDefinition() @@ -357,7 +355,7 @@ /** * newMenuOptionsDefinition - creates a new empty menu options definition - * + * * @return a newly created MenuOptionsDefinition object for use in Page */ public MenuOptionsDefinition newMenuOptionsDefinition() @@ -366,8 +364,9 @@ } /** - * newMenuSeparatorDefinition - creates a new empty menu separator definition - * + * newMenuSeparatorDefinition - creates a new empty menu separator + * definition + * * @return a newly created MenuSeparatorDefinition object for use in Page */ public MenuSeparatorDefinition newMenuSeparatorDefinition() @@ -377,8 +376,9 @@ /** * setMenuDefinitions - set list of menu definitions - * - * @param definitions definition list + * + * @param definitions + * definition list */ public void setMenuDefinitions(List definitions) { @@ -386,8 +386,8 @@ } /** - * unmarshalled - notification that this instance has been - * loaded from the persistent store + * unmarshalled - notification that this instance has been loaded from the + * persistent store */ public void unmarshalled() { @@ -401,7 +401,7 @@ Iterator menuIter = menuDefinitions.iterator(); while (menuIter.hasNext()) { - ((MenuDefinitionImpl)menuIter.next()).unmarshalled(); + ((MenuDefinitionImpl) menuIter.next()).unmarshalled(); } } @@ -409,7 +409,7 @@ // to root fragment if (root != null) { - ((FragmentImpl)root).unmarshalled(); + ((FragmentImpl) root).unmarshalled(); } // default title of pages to name @@ -420,8 +420,8 @@ } /** - * marshalling - notification that this instance is to - * be saved to the persistent store + * marshalling - notification that this instance is to be saved to the + * persistent store */ public void marshalling() { @@ -429,7 +429,7 @@ // to root fragment if (root != null) { - ((FragmentImpl)root).marshalling(); + ((FragmentImpl) root).marshalling(); } // propagate marshalling notification @@ -439,7 +439,7 @@ Iterator menuIter = menuDefinitions.iterator(); while (menuIter.hasNext()) { - ((MenuDefinitionImpl)menuIter.next()).marshalling(); + ((MenuDefinitionImpl) menuIter.next()).marshalling(); } } @@ -447,4 +447,3 @@ super.marshalling(); } } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/PageSecurityImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/PageSecurityImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/PageSecurityImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,14 +29,16 @@ * SecurityImpl *

        *

        - * + * *

        + * * @author Randy Watler * @version $Id: PageSecurityImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class PageSecurityImpl extends DocumentImpl implements PageSecurity { + private List constraintsDefsList; private Map constraintsDefsMap; @@ -47,12 +49,12 @@ *

        * getType *

        - * + * * @see org.apache.jetspeed.om.page.Document#getType() * @return */ public String getType() - { + { return DOCUMENT_TYPE; } @@ -60,7 +62,7 @@ *

        * getSecurityConstraintsDefs *

        - * + * * @see org.apache.jetspeed.om.page.PageSecurity#getSecurityConstraintsDefs() * @return */ @@ -68,12 +70,12 @@ { return constraintsDefsList; } - + /** *

        * setSecurityConstraintsDefs *

        - * + * * @see org.apache.jetspeed.om.page.PageSecurity#setSecurityConstraintsDefs(java.util.List) * @param defintions */ @@ -87,7 +89,7 @@ *

        * newSecurityConstraintsDef *

        - * + * * @see org.apache.jetspeed.om.page.PageSecurity#newSecurityConstraintsDef() * @return security constraints definition */ @@ -100,7 +102,7 @@ *

        * getSecurityConstraintsDef *

        - * + * * @see org.apache.jetspeed.om.page.PageSecurity#getSecurityConstraintsDef(java.lang.String) * @param name * @return @@ -109,18 +111,18 @@ { if ((constraintsDefsList != null) && (constraintsDefsMap == null)) { - constraintsDefsMap = new HashMap((constraintsDefsList.size() * 2) + 1); + constraintsDefsMap = new HashMap( + (constraintsDefsList.size() * 2) + 1); Iterator definitionsIter = constraintsDefsList.iterator(); while (definitionsIter.hasNext()) { - SecurityConstraintsDef definition = (SecurityConstraintsDef)definitionsIter.next(); + SecurityConstraintsDef definition = (SecurityConstraintsDef) definitionsIter + .next(); constraintsDefsMap.put(definition.getName(), definition); } } - if (constraintsDefsMap != null) - { - return (SecurityConstraintsDef) constraintsDefsMap.get(name); - } + if (constraintsDefsMap != null) { return (SecurityConstraintsDef) constraintsDefsMap + .get(name); } return null; } @@ -128,7 +130,7 @@ *

        * getGlobalSecurityConstraintsRefs *

        - * + * * @see org.apache.jetspeed.om.page.PageSecurity#getGlobalSecurityConstraintsRefs() * @return */ @@ -136,12 +138,12 @@ { return globalConstraintsRefs; } - + /** *

        * setGlobalSecurityConstraintsRefs *

        - * + * * @see org.apache.jetspeed.om.page.PageSecurity#setGlobalSecurityConstraintsRefs(java.util.List) * @param constraintsRefs */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/PropertyImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/PropertyImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/PropertyImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,16 +18,18 @@ package org.apache.jetspeed.om.page.psml; /** - * Bean like implementation of the Parameter interface suitable for - * Castor serialization. - * + * Bean like implementation of the Parameter interface suitable for Castor + * serialization. + * * @see org.apache.jetspeed.om.registry.PsmlParameter * @author David Sean Taylor * @version $Id: PropertyImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class PropertyImpl implements java.io.Serializable { + private String name; + private String value; public PropertyImpl() @@ -69,12 +71,12 @@ *

        * getIntValue *

        - * + * * @see org.apache.jetspeed.om.page.Property#getIntValue() * @return */ public int getIntValue() - { + { return Integer.parseInt(value); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/ReferenceImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/ReferenceImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/ReferenceImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,9 +24,9 @@ */ public class ReferenceImpl extends FragmentImpl implements Reference { + public boolean isReference() { return true; } } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/SecurityConstraintsDefImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/SecurityConstraintsDefImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/SecurityConstraintsDefImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,14 +26,16 @@ * SecurityConstraintsImpl *

        *

        - * + * *

        + * * @author Randy Watler * @version $Id: SecurityConstraintsDefImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class SecurityConstraintsDefImpl implements SecurityConstraintsDef { + private String name; private List constraints = new ArrayList(4); @@ -42,7 +44,7 @@ *

        * getName *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraintsDef#getName() * @return */ @@ -50,12 +52,12 @@ { return name; } - + /** *

        * setName *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraintsDef#setName(java.lang.String) * @param name */ @@ -68,7 +70,7 @@ *

        * getSecurityConstraints *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraintsDef#getSecurityConstraints() * @return */ @@ -76,12 +78,12 @@ { return constraints; } - + /** *

        * setSecurityConstraint *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraintsDef#setSecurityConstraints(java.util.List) * @param constraints */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/SecurityConstraintsImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/SecurityConstraintsImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/om/page/psml/SecurityConstraintsImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,16 +33,20 @@ * SecurityConstraintsImpl *

        *

        - * + * *

        + * * @author Randy Watler - * @version $Id: SecurityConstraintsImpl.java 568811 2007-08-23 03:00:37Z woonsan $ - * + * @version $Id: SecurityConstraintsImpl.java 568811 2007-08-23 03:00:37Z + * woonsan $ + * */ public class SecurityConstraintsImpl implements SecurityConstraints { - private final static Log log = LogFactory.getLog(SecurityConstraintsImpl.class); + private final static Log log = LogFactory + .getLog(SecurityConstraintsImpl.class); + private String owner; private List constraints; @@ -55,7 +59,7 @@ *

        * getOwner *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraints#getOwner() * @return */ @@ -63,12 +67,12 @@ { return owner; } - + /** *

        * setOwner *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraints#setOwner(java.lang.String) * @param owner */ @@ -81,7 +85,7 @@ *

        * getSecurityConstraints *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraints#getSecurityConstraints() * @return */ @@ -90,20 +94,20 @@ if (this.constraints == null) { this.constraints = Collections.synchronizedList(new ArrayList()); - } + } return constraints; } - + /** *

        * setSecurityConstraint *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraints#setSecurityConstraints(java.util.List) * @param constraints */ public void setSecurityConstraints(List constraints) - { + { this.constraints = constraints; } @@ -111,7 +115,7 @@ *

        * getSecurityConstraintsRefs *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraints#getSecurityConstraintsRefs() * @return */ @@ -119,16 +123,17 @@ { if (this.constraintsRefs == null) { - this.constraintsRefs = Collections.synchronizedList(new ArrayList()); - } + this.constraintsRefs = Collections + .synchronizedList(new ArrayList()); + } return constraintsRefs; } - + /** *

        * setSecurityConstraintsRefs *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraints#setSecurityConstraintsRefs(java.util.List) * @param constraintsRefs */ @@ -141,7 +146,7 @@ *

        * isEmpty *

        - * + * * @see org.apache.jetspeed.om.common.SecurityConstraints#isEmpty() * @return flag indicating whether there are constraints or owner set */ @@ -154,22 +159,22 @@ *

        * checkConstraints *

        - * + * * @param actions * @param userPrincipals * @param rolePrincipals * @param groupPrincipals - * @param pageSecurity page security definitions + * @param pageSecurity + * page security definitions * @throws SecurityException */ - public void checkConstraints(List actions, List userPrincipals, List rolePrincipals, - List groupPrincipals, PageSecurity pageSecurity) throws SecurityException + public void checkConstraints(List actions, List userPrincipals, + List rolePrincipals, List groupPrincipals, PageSecurity pageSecurity) + throws SecurityException { // if owner defined, override all constraints and allow all access - if ((owner != null) && (userPrincipals != null) && userPrincipals.contains(owner)) - { - return; - } + if ((owner != null) && (userPrincipals != null) + && userPrincipals.contains(owner)) { return; } // skip missing or empty constraints: permit all access List checkConstraints = getAllSecurityConstraints(pageSecurity); @@ -182,29 +187,32 @@ { // check each action: // - if any actions explicity permitted, assume no permissions - // are permitted by default + // are permitted by default // - if all constraints do not specify a permission, assume - // access is permitted by default - String action = (String)actionsIter.next(); + // access is permitted by default + String action = (String) actionsIter.next(); boolean actionPermitted = false; boolean actionNotPermitted = false; boolean anyActionsPermitted = false; - + // check against constraints Iterator checkConstraintsIter = checkConstraints.iterator(); while (checkConstraintsIter.hasNext()) { - SecurityConstraintImpl constraint = (SecurityConstraintImpl)checkConstraintsIter.next(); - + SecurityConstraintImpl constraint = (SecurityConstraintImpl) checkConstraintsIter + .next(); + // if permissions specified, attempt to match constraint if (constraint.getPermissions() != null) { // explicit actions permitted anyActionsPermitted = true; - // test action permission match and user/role/group principal match - if (constraint.actionMatch(action) && - constraint.principalsMatch(userPrincipals, rolePrincipals, groupPrincipals, true)) + // test action permission match and user/role/group + // principal match + if (constraint.actionMatch(action) + && constraint.principalsMatch(userPrincipals, + rolePrincipals, groupPrincipals, true)) { actionPermitted = true; break; @@ -212,20 +220,22 @@ } else { - // permissions not specified: not permitted if any principal matched - if (constraint.principalsMatch(userPrincipals, rolePrincipals, groupPrincipals, false)) + // permissions not specified: not permitted if any + // principal matched + if (constraint.principalsMatch(userPrincipals, + rolePrincipals, groupPrincipals, false)) { actionNotPermitted = true; break; } } } - + // fail if any action not permitted - if ((!actionPermitted && anyActionsPermitted) || actionNotPermitted) - { - throw new SecurityException("SecurityConstraintsImpl.checkConstraints(): Access for " + action + " not permitted."); - } + if ((!actionPermitted && anyActionsPermitted) + || actionNotPermitted) { throw new SecurityException( + "SecurityConstraintsImpl.checkConstraints(): Access for " + + action + " not permitted."); } } } } @@ -234,18 +244,16 @@ *

        * getAllSecurityConstraints *

        - * + * * @param pageSecurity * @return all security constraints */ - private synchronized List getAllSecurityConstraints(PageSecurity pageSecurity) + private synchronized List getAllSecurityConstraints( + PageSecurity pageSecurity) { // return previously cached security constraints; note that // cache is assumed valid until owning document is evicted - if (allConstraints != null) - { - return allConstraints; - } + if (allConstraints != null) { return allConstraints; } // construct new ordered security constraints list allConstraints = Collections.synchronizedList(new ArrayList(8)); @@ -259,7 +267,8 @@ // add any security constraints references if ((constraintsRefs != null) && !constraintsRefs.isEmpty()) { - List referencedConstraints = dereferenceSecurityConstraintsRefs(constraintsRefs, pageSecurity); + List referencedConstraints = dereferenceSecurityConstraintsRefs( + constraintsRefs, pageSecurity); if (referencedConstraints != null) { allConstraints.addAll(referencedConstraints); @@ -269,16 +278,19 @@ // add any global decurity constraints references if (pageSecurity != null) { - List globalConstraintsRefs = pageSecurity.getGlobalSecurityConstraintsRefs(); - if ((globalConstraintsRefs != null) && !globalConstraintsRefs.isEmpty()) + List globalConstraintsRefs = pageSecurity + .getGlobalSecurityConstraintsRefs(); + if ((globalConstraintsRefs != null) + && !globalConstraintsRefs.isEmpty()) { - List referencedConstraints = dereferenceSecurityConstraintsRefs(globalConstraintsRefs, pageSecurity); + List referencedConstraints = dereferenceSecurityConstraintsRefs( + globalConstraintsRefs, pageSecurity); if (referencedConstraints != null) { allConstraints.addAll(referencedConstraints); } } - } + } return allConstraints; } @@ -287,43 +299,53 @@ *

        * dereferenceSecurityConstraintsRefs *

        - * + * * @param constraintsRefs * @param pageSecurity * @return security constraints */ - private List dereferenceSecurityConstraintsRefs(List constraintsRefs, PageSecurity pageSecurity) + private List dereferenceSecurityConstraintsRefs(List constraintsRefs, + PageSecurity pageSecurity) { // access security document to dereference security // constriants definitions List constraints = null; if (pageSecurity != null) - { + { // dereference each security constraints definition Iterator constraintsRefsIter = constraintsRefs.iterator(); while (constraintsRefsIter.hasNext()) { - String constraintsRef = (String)constraintsRefsIter.next(); - SecurityConstraintsDef securityConstraintsDef = pageSecurity.getSecurityConstraintsDef(constraintsRef); - if ((securityConstraintsDef != null) && (securityConstraintsDef.getSecurityConstraints() != null)) + String constraintsRef = (String) constraintsRefsIter.next(); + SecurityConstraintsDef securityConstraintsDef = pageSecurity + .getSecurityConstraintsDef(constraintsRef); + if ((securityConstraintsDef != null) + && (securityConstraintsDef.getSecurityConstraints() != null)) { if (constraints == null) { - constraints = Collections.synchronizedList(new ArrayList(constraintsRefs.size())); + constraints = Collections + .synchronizedList(new ArrayList(constraintsRefs + .size())); } - constraints.addAll(securityConstraintsDef.getSecurityConstraints()); + constraints.addAll(securityConstraintsDef + .getSecurityConstraints()); } else { - log.error("dereferenceSecurityConstraintsRefs(): Unable to dereference \"" + constraintsRef + "\" security constraints definition."); + log + .error("dereferenceSecurityConstraintsRefs(): Unable to dereference \"" + + constraintsRef + + "\" security constraints definition."); } } } else { - log.error("dereferenceSecurityConstraintsRefs(): Missing page security, unable to dereference security constraints definitions."); + log + .error("dereferenceSecurityConstraintsRefs(): Missing page security, unable to dereference security constraints definitions."); } - + return constraints; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/AbstractPageManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/AbstractPageManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/AbstractPageManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -48,42 +48,69 @@ /** * AbstractPageManagerService - * + * * @author David Sean Taylor * @version $Id: AbstractPageManager.java 517124 2007-03-12 08:10:25Z ate $ */ -public abstract class AbstractPageManager - implements PageManager +public abstract class AbstractPageManager implements PageManager { + private final static Log log = LogFactory.getLog(AbstractPageManager.class); - + private final static String FOLDER_NODE_TYPE = "folder"; + private final static String PAGE_NODE_TYPE = "page"; + private final static String FRAGMENT_NODE_TYPE = "fragment"; + private final static String LINK_NODE_TYPE = "link"; + protected Class fragmentClass; + protected Class pageClass; + protected Class folderClass; + protected Class linkClass; + protected Class pageSecurityClass; + protected Class propertyClass; + protected Class folderMenuDefinitionClass; + protected Class folderMenuExcludeDefinitionClass; + protected Class folderMenuIncludeDefinitionClass; + protected Class folderMenuOptionsDefinitionClass; + protected Class folderMenuSeparatorDefinitionClass; + protected Class pageMenuDefinitionClass; + protected Class pageMenuExcludeDefinitionClass; + protected Class pageMenuIncludeDefinitionClass; + protected Class pageMenuOptionsDefinitionClass; + protected Class pageMenuSeparatorDefinitionClass; + protected Class securityConstraintsClass; + protected Class folderSecurityConstraintClass; + protected Class pageSecurityConstraintClass; + protected Class fragmentSecurityConstraintClass; + protected Class linkSecurityConstraintClass; + protected Class pageSecuritySecurityConstraintClass; + protected Class securityConstraintsDefClass; + protected Class fragmentPreferenceClass; private boolean permissionsEnabled; @@ -92,46 +119,66 @@ private List listeners = new LinkedList(); - public AbstractPageManager(boolean permissionsEnabled, boolean constraintsEnabled) - { + public AbstractPageManager(boolean permissionsEnabled, + boolean constraintsEnabled) + { this.permissionsEnabled = permissionsEnabled; this.constraintsEnabled = constraintsEnabled; } - - public AbstractPageManager(boolean permissionsEnabled, boolean constraintsEnabled, Map modelClasses) + + public AbstractPageManager(boolean permissionsEnabled, + boolean constraintsEnabled, Map modelClasses) { - this(permissionsEnabled, constraintsEnabled); + this(permissionsEnabled, constraintsEnabled); - this.fragmentClass = (Class)modelClasses.get("FragmentImpl"); - this.pageClass = (Class)modelClasses.get("PageImpl"); - this.folderClass = (Class)modelClasses.get("FolderImpl"); - this.linkClass = (Class)modelClasses.get("LinkImpl"); - this.pageSecurityClass = (Class)modelClasses.get("PageSecurityImpl"); - this.folderMenuDefinitionClass = (Class)modelClasses.get("FolderMenuDefinitionImpl"); - this.folderMenuExcludeDefinitionClass = (Class)modelClasses.get("FolderMenuExcludeDefinitionImpl"); - this.folderMenuIncludeDefinitionClass = (Class)modelClasses.get("FolderMenuIncludeDefinitionImpl"); - this.folderMenuOptionsDefinitionClass = (Class)modelClasses.get("FolderMenuOptionsDefinitionImpl"); - this.folderMenuSeparatorDefinitionClass = (Class)modelClasses.get("FolderMenuSeparatorDefinitionImpl"); - this.pageMenuDefinitionClass = (Class)modelClasses.get("PageMenuDefinitionImpl"); - this.pageMenuExcludeDefinitionClass = (Class)modelClasses.get("PageMenuExcludeDefinitionImpl"); - this.pageMenuIncludeDefinitionClass = (Class)modelClasses.get("PageMenuIncludeDefinitionImpl"); - this.pageMenuOptionsDefinitionClass = (Class)modelClasses.get("PageMenuOptionsDefinitionImpl"); - this.pageMenuSeparatorDefinitionClass = (Class)modelClasses.get("PageMenuSeparatorDefinitionImpl"); - this.securityConstraintsClass = (Class)modelClasses.get("SecurityConstraintsImpl"); - this.folderSecurityConstraintClass = (Class)modelClasses.get("FolderSecurityConstraintImpl"); - this.pageSecurityConstraintClass = (Class)modelClasses.get("PageSecurityConstraintImpl"); - this.fragmentSecurityConstraintClass = (Class)modelClasses.get("FragmentSecurityConstraintImpl"); - this.linkSecurityConstraintClass = (Class)modelClasses.get("LinkSecurityConstraintImpl"); - this.pageSecuritySecurityConstraintClass = (Class)modelClasses.get("PageSecuritySecurityConstraintImpl"); - this.securityConstraintsDefClass = (Class)modelClasses.get("SecurityConstraintsDefImpl"); - this.fragmentPreferenceClass = (Class)modelClasses.get("FragmentPreferenceImpl"); + this.fragmentClass = (Class) modelClasses.get("FragmentImpl"); + this.pageClass = (Class) modelClasses.get("PageImpl"); + this.folderClass = (Class) modelClasses.get("FolderImpl"); + this.linkClass = (Class) modelClasses.get("LinkImpl"); + this.pageSecurityClass = (Class) modelClasses.get("PageSecurityImpl"); + this.folderMenuDefinitionClass = (Class) modelClasses + .get("FolderMenuDefinitionImpl"); + this.folderMenuExcludeDefinitionClass = (Class) modelClasses + .get("FolderMenuExcludeDefinitionImpl"); + this.folderMenuIncludeDefinitionClass = (Class) modelClasses + .get("FolderMenuIncludeDefinitionImpl"); + this.folderMenuOptionsDefinitionClass = (Class) modelClasses + .get("FolderMenuOptionsDefinitionImpl"); + this.folderMenuSeparatorDefinitionClass = (Class) modelClasses + .get("FolderMenuSeparatorDefinitionImpl"); + this.pageMenuDefinitionClass = (Class) modelClasses + .get("PageMenuDefinitionImpl"); + this.pageMenuExcludeDefinitionClass = (Class) modelClasses + .get("PageMenuExcludeDefinitionImpl"); + this.pageMenuIncludeDefinitionClass = (Class) modelClasses + .get("PageMenuIncludeDefinitionImpl"); + this.pageMenuOptionsDefinitionClass = (Class) modelClasses + .get("PageMenuOptionsDefinitionImpl"); + this.pageMenuSeparatorDefinitionClass = (Class) modelClasses + .get("PageMenuSeparatorDefinitionImpl"); + this.securityConstraintsClass = (Class) modelClasses + .get("SecurityConstraintsImpl"); + this.folderSecurityConstraintClass = (Class) modelClasses + .get("FolderSecurityConstraintImpl"); + this.pageSecurityConstraintClass = (Class) modelClasses + .get("PageSecurityConstraintImpl"); + this.fragmentSecurityConstraintClass = (Class) modelClasses + .get("FragmentSecurityConstraintImpl"); + this.linkSecurityConstraintClass = (Class) modelClasses + .get("LinkSecurityConstraintImpl"); + this.pageSecuritySecurityConstraintClass = (Class) modelClasses + .get("PageSecuritySecurityConstraintImpl"); + this.securityConstraintsDefClass = (Class) modelClasses + .get("SecurityConstraintsDefImpl"); + this.fragmentPreferenceClass = (Class) modelClasses + .get("FragmentPreferenceImpl"); } - + /** *

        * getPermissionsEnabled *

        - * + * * @see org.apache.jetspeed.page.PageManager#getPermissionsEnabled() * @return */ @@ -144,7 +191,7 @@ *

        * getConstraintsEnabled *

        - * + * * @see org.apache.jetspeed.page.PageManager#getConstraintsEnabled() * @return */ @@ -153,7 +200,9 @@ return constraintsEnabled; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newPage(java.lang.String) */ public Page newPage(String path) @@ -162,7 +211,7 @@ try { // factory create the page and set id/path - page = (Page)createObject(this.pageClass); + page = (Page) createObject(this.pageClass); if (!path.startsWith(Folder.PATH_SEPARATOR)) { path = Folder.PATH_SEPARATOR + path; @@ -172,19 +221,22 @@ path += Page.DOCUMENT_TYPE; } page.setPath(path); - + // create the default fragment - page.setRootFragment(newFragment()); + page.setRootFragment(newFragment()); } catch (ClassCastException e) { - String message = "Failed to create page object for " + this.pageClass; + String message = "Failed to create page object for " + + this.pageClass; log.error(message, e); } - return page; + return page; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newFolder(java.lang.String) */ public Folder newFolder(String path) @@ -193,7 +245,7 @@ try { // factory create the folder and set id/path - folder = (Folder)createObject(this.folderClass); + folder = (Folder) createObject(this.folderClass); if (!path.startsWith(Folder.PATH_SEPARATOR)) { path = Folder.PATH_SEPARATOR + path; @@ -202,13 +254,16 @@ } catch (ClassCastException e) { - String message = "Failed to create link object for " + this.linkClass; + String message = "Failed to create link object for " + + this.linkClass; log.error(message, e); } - return folder; + return folder; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newLink(java.lang.String) */ public Link newLink(String path) @@ -217,7 +272,7 @@ try { // factory create the page and set id/path - link = (Link)createObject(this.linkClass); + link = (Link) createObject(this.linkClass); if (!path.startsWith(Folder.PATH_SEPARATOR)) { path = Folder.PATH_SEPARATOR + path; @@ -230,13 +285,16 @@ } catch (ClassCastException e) { - String message = "Failed to create link object for " + this.linkClass; + String message = "Failed to create link object for " + + this.linkClass; log.error(message, e); } - return link; + return link; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newPageSecurity() */ public PageSecurity newPageSecurity() @@ -245,18 +303,22 @@ try { // factory create the document and set id/path - pageSecurity = (PageSecurity)createObject(this.pageSecurityClass); - pageSecurity.setPath(Folder.PATH_SEPARATOR + PageSecurity.DOCUMENT_TYPE); + pageSecurity = (PageSecurity) createObject(this.pageSecurityClass); + pageSecurity.setPath(Folder.PATH_SEPARATOR + + PageSecurity.DOCUMENT_TYPE); } catch (ClassCastException e) { - String message = "Failed to create page security object for " + this.pageClass; + String message = "Failed to create page security object for " + + this.pageClass; log.error(message, e); } - return pageSecurity; + return pageSecurity; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newFragment() */ public Fragment newFragment() @@ -264,19 +326,22 @@ Fragment fragment = null; try { - fragment = (Fragment)createObject(this.fragmentClass); - fragment.setType(Fragment.LAYOUT); + fragment = (Fragment) createObject(this.fragmentClass); + fragment.setType(Fragment.LAYOUT); } catch (ClassCastException e) { - String message = "Failed to create page object for " + this.pageClass; + String message = "Failed to create page object for " + + this.pageClass; log.error(message, e); // throw new NodeException(message, e); } - return fragment; + return fragment; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newPortletFragment() */ public Fragment newPortletFragment() @@ -284,108 +349,118 @@ Fragment fragment = null; try { - fragment = (Fragment)createObject(this.fragmentClass); - fragment.setType(Fragment.PORTLET); + fragment = (Fragment) createObject(this.fragmentClass); + fragment.setType(Fragment.PORTLET); } catch (ClassCastException e) { - String message = "Failed to create page object for " + this.pageClass; + String message = "Failed to create page object for " + + this.pageClass; log.error(message, e); // throw new NodeException(message, e); } - return fragment; + return fragment; } - + /** * newFolderMenuDefinition - creates a new empty menu definition - * + * * @return a newly created MenuDefinition object */ public MenuDefinition newFolderMenuDefinition() { try { - return (MenuDefinition)createObject(this.folderMenuDefinitionClass); + return (MenuDefinition) createObject(this.folderMenuDefinitionClass); } catch (ClassCastException e) { - String message = "Failed to create menu definition object for " + this.folderMenuDefinitionClass; + String message = "Failed to create menu definition object for " + + this.folderMenuDefinitionClass; log.error(message, e); } return null; } /** - * newFolderMenuExcludeDefinition - creates a new empty menu exclude definition - * + * newFolderMenuExcludeDefinition - creates a new empty menu exclude + * definition + * * @return a newly created MenuExcludeDefinition object */ public MenuExcludeDefinition newFolderMenuExcludeDefinition() { try { - return (MenuExcludeDefinition)createObject(this.folderMenuExcludeDefinitionClass); + return (MenuExcludeDefinition) createObject(this.folderMenuExcludeDefinitionClass); } catch (ClassCastException e) { - String message = "Failed to create menu exclude definition object for " + this.folderMenuExcludeDefinitionClass; + String message = "Failed to create menu exclude definition object for " + + this.folderMenuExcludeDefinitionClass; log.error(message, e); } return null; } /** - * newFolderMenuIncludeDefinition - creates a new empty menu include definition - * + * newFolderMenuIncludeDefinition - creates a new empty menu include + * definition + * * @return a newly created MenuIncludeDefinition object */ public MenuIncludeDefinition newFolderMenuIncludeDefinition() { try { - return (MenuIncludeDefinition)createObject(this.folderMenuIncludeDefinitionClass); + return (MenuIncludeDefinition) createObject(this.folderMenuIncludeDefinitionClass); } catch (ClassCastException e) { - String message = "Failed to create menu include definition object for " + this.folderMenuIncludeDefinitionClass; + String message = "Failed to create menu include definition object for " + + this.folderMenuIncludeDefinitionClass; log.error(message, e); } return null; } /** - * newFolderMenuOptionsDefinition - creates a new empty menu options definition - * + * newFolderMenuOptionsDefinition - creates a new empty menu options + * definition + * * @return a newly created MenuOptionsDefinition object */ public MenuOptionsDefinition newFolderMenuOptionsDefinition() { try { - return (MenuOptionsDefinition)createObject(this.folderMenuOptionsDefinitionClass); + return (MenuOptionsDefinition) createObject(this.folderMenuOptionsDefinitionClass); } catch (ClassCastException e) { - String message = "Failed to create menu options definition object for " + this.folderMenuOptionsDefinitionClass; + String message = "Failed to create menu options definition object for " + + this.folderMenuOptionsDefinitionClass; log.error(message, e); } return null; } /** - * newFolderMenuSeparatorDefinition - creates a new empty menu separator definition - * + * newFolderMenuSeparatorDefinition - creates a new empty menu separator + * definition + * * @return a newly created MenuSeparatorDefinition object */ public MenuSeparatorDefinition newFolderMenuSeparatorDefinition() { try { - return (MenuSeparatorDefinition)createObject(this.folderMenuSeparatorDefinitionClass); + return (MenuSeparatorDefinition) createObject(this.folderMenuSeparatorDefinitionClass); } catch (ClassCastException e) { - String message = "Failed to create menu separator definition object for " + this.folderMenuSeparatorDefinitionClass; + String message = "Failed to create menu separator definition object for " + + this.folderMenuSeparatorDefinitionClass; log.error(message, e); } return null; @@ -393,132 +468,145 @@ /** * newPageMenuDefinition - creates a new empty menu definition - * + * * @return a newly created MenuDefinition object */ public MenuDefinition newPageMenuDefinition() { try { - return (MenuDefinition)createObject(this.pageMenuDefinitionClass); + return (MenuDefinition) createObject(this.pageMenuDefinitionClass); } catch (ClassCastException e) { - String message = "Failed to create menu definition object for " + this.pageMenuDefinitionClass; + String message = "Failed to create menu definition object for " + + this.pageMenuDefinitionClass; log.error(message, e); } return null; } /** - * newPageMenuExcludeDefinition - creates a new empty menu exclude definition - * + * newPageMenuExcludeDefinition - creates a new empty menu exclude + * definition + * * @return a newly created MenuExcludeDefinition object */ public MenuExcludeDefinition newPageMenuExcludeDefinition() { try { - return (MenuExcludeDefinition)createObject(this.pageMenuExcludeDefinitionClass); + return (MenuExcludeDefinition) createObject(this.pageMenuExcludeDefinitionClass); } catch (ClassCastException e) { - String message = "Failed to create menu exclude definition object for " + this.pageMenuExcludeDefinitionClass; + String message = "Failed to create menu exclude definition object for " + + this.pageMenuExcludeDefinitionClass; log.error(message, e); } return null; } /** - * newPageMenuIncludeDefinition - creates a new empty menu include definition - * + * newPageMenuIncludeDefinition - creates a new empty menu include + * definition + * * @return a newly created MenuIncludeDefinition object */ public MenuIncludeDefinition newPageMenuIncludeDefinition() { try { - return (MenuIncludeDefinition)createObject(this.pageMenuIncludeDefinitionClass); + return (MenuIncludeDefinition) createObject(this.pageMenuIncludeDefinitionClass); } catch (ClassCastException e) { - String message = "Failed to create menu include definition object for " + this.pageMenuIncludeDefinitionClass; + String message = "Failed to create menu include definition object for " + + this.pageMenuIncludeDefinitionClass; log.error(message, e); } return null; } /** - * newPageMenuOptionsDefinition - creates a new empty menu options definition - * + * newPageMenuOptionsDefinition - creates a new empty menu options + * definition + * * @return a newly created MenuOptionsDefinition object */ public MenuOptionsDefinition newPageMenuOptionsDefinition() { try { - return (MenuOptionsDefinition)createObject(this.pageMenuOptionsDefinitionClass); + return (MenuOptionsDefinition) createObject(this.pageMenuOptionsDefinitionClass); } catch (ClassCastException e) { - String message = "Failed to create menu options definition object for " + this.pageMenuOptionsDefinitionClass; + String message = "Failed to create menu options definition object for " + + this.pageMenuOptionsDefinitionClass; log.error(message, e); } return null; } /** - * newPageMenuSeparatorDefinition - creates a new empty menu separator definition - * + * newPageMenuSeparatorDefinition - creates a new empty menu separator + * definition + * * @return a newly created MenuSeparatorDefinition object */ public MenuSeparatorDefinition newPageMenuSeparatorDefinition() { try { - return (MenuSeparatorDefinition)createObject(this.pageMenuSeparatorDefinitionClass); + return (MenuSeparatorDefinition) createObject(this.pageMenuSeparatorDefinitionClass); } catch (ClassCastException e) { - String message = "Failed to create menu separator definition object for " + this.pageMenuSeparatorDefinitionClass; + String message = "Failed to create menu separator definition object for " + + this.pageMenuSeparatorDefinitionClass; log.error(message, e); } return null; } /** - * newSecurityConstraints - creates a new empty security constraints definition - * + * newSecurityConstraints - creates a new empty security constraints + * definition + * * @return a newly created SecurityConstraints object */ public SecurityConstraints newSecurityConstraints() { try { - return (SecurityConstraints)createObject(this.securityConstraintsClass); + return (SecurityConstraints) createObject(this.securityConstraintsClass); } catch (ClassCastException e) { - String message = "Failed to create security constraints definition object for " + this.securityConstraintsClass; + String message = "Failed to create security constraints definition object for " + + this.securityConstraintsClass; log.error(message, e); } return null; } /** - * newFolderSecurityConstraint - creates a new security constraint definition - * + * newFolderSecurityConstraint - creates a new security constraint + * definition + * * @return a newly created SecurityConstraint object */ public SecurityConstraint newFolderSecurityConstraint() { try { - return (SecurityConstraint)createObject(this.folderSecurityConstraintClass); + return (SecurityConstraint) createObject(this.folderSecurityConstraintClass); } catch (ClassCastException e) { - String message = "Failed to create security constraint definition object for " + this.folderSecurityConstraintClass; + String message = "Failed to create security constraint definition object for " + + this.folderSecurityConstraintClass; log.error(message, e); } return null; @@ -526,37 +614,40 @@ /** * newPageSecurityConstraint - creates a new security constraint definition - * + * * @return a newly created SecurityConstraint object */ public SecurityConstraint newPageSecurityConstraint() { try { - return (SecurityConstraint)createObject(this.pageSecurityConstraintClass); + return (SecurityConstraint) createObject(this.pageSecurityConstraintClass); } catch (ClassCastException e) { - String message = "Failed to create security constraint definition object for " + this.pageSecurityConstraintClass; + String message = "Failed to create security constraint definition object for " + + this.pageSecurityConstraintClass; log.error(message, e); } return null; } /** - * newFragmentSecurityConstraint - creates a new security constraint definition - * + * newFragmentSecurityConstraint - creates a new security constraint + * definition + * * @return a newly created SecurityConstraint object */ public SecurityConstraint newFragmentSecurityConstraint() { try { - return (SecurityConstraint)createObject(this.fragmentSecurityConstraintClass); + return (SecurityConstraint) createObject(this.fragmentSecurityConstraintClass); } catch (ClassCastException e) { - String message = "Failed to create security constraint definition object for " + this.fragmentSecurityConstraintClass; + String message = "Failed to create security constraint definition object for " + + this.fragmentSecurityConstraintClass; log.error(message, e); } return null; @@ -564,37 +655,40 @@ /** * newLinkSecurityConstraint - creates a new security constraint definition - * + * * @return a newly created SecurityConstraint object */ public SecurityConstraint newLinkSecurityConstraint() { try { - return (SecurityConstraint)createObject(this.linkSecurityConstraintClass); + return (SecurityConstraint) createObject(this.linkSecurityConstraintClass); } catch (ClassCastException e) { - String message = "Failed to create security constraint definition object for " + this.linkSecurityConstraintClass; + String message = "Failed to create security constraint definition object for " + + this.linkSecurityConstraintClass; log.error(message, e); } return null; } /** - * newPageSecuritySecurityConstraint - creates a new security constraint definition - * + * newPageSecuritySecurityConstraint - creates a new security constraint + * definition + * * @return a newly created SecurityConstraint object */ public SecurityConstraint newPageSecuritySecurityConstraint() { try { - return (SecurityConstraint)createObject(this.pageSecuritySecurityConstraintClass); + return (SecurityConstraint) createObject(this.pageSecuritySecurityConstraintClass); } catch (ClassCastException e) { - String message = "Failed to create security constraint definition object for " + this.pageSecuritySecurityConstraintClass; + String message = "Failed to create security constraint definition object for " + + this.pageSecuritySecurityConstraintClass; log.error(message, e); } return null; @@ -602,18 +696,19 @@ /** * newSecurityConstraintsDef - creates a new security constraints definition - * + * * @return a newly created SecurityConstraintsDef object */ public SecurityConstraintsDef newSecurityConstraintsDef() { try { - return (SecurityConstraintsDef)createObject(this.securityConstraintsDefClass); + return (SecurityConstraintsDef) createObject(this.securityConstraintsDefClass); } catch (ClassCastException e) { - String message = "Failed to create security constraints definition object for " + this.securityConstraintsDefClass; + String message = "Failed to create security constraints definition object for " + + this.securityConstraintsDefClass; log.error(message, e); } return null; @@ -621,18 +716,19 @@ /** * newFragmentPreference - creates a new security constraints definition - * + * * @return a newly created FragmentPreference object */ public FragmentPreference newFragmentPreference() { try { - return (FragmentPreference)createObject(this.fragmentPreferenceClass); + return (FragmentPreference) createObject(this.fragmentPreferenceClass); } catch (ClassCastException e) { - String message = "Failed to create security constraints definition object for " + this.fragmentPreferenceClass; + String message = "Failed to create security constraints definition object for " + + this.fragmentPreferenceClass; log.error(message, e); } return null; @@ -640,8 +736,9 @@ /** * createObject - creates a new page manager implementation object - * - * @param classe implementation class + * + * @param classe + * implementation class * @return a newly created implementation object */ private Object createObject(Class classe) @@ -653,15 +750,18 @@ } catch (Exception e) { - log.error("Factory failed to create object: " + classe.getName(), e); + log + .error("Factory failed to create object: " + + classe.getName(), e); } - return object; - } + return object; + } /** * addListener - add page manager event listener - * - * @param listener page manager event listener + * + * @param listener + * page manager event listener */ public void addListener(PageManagerEventListener listener) { @@ -674,8 +774,9 @@ /** * removeListener - remove page manager event listener - * - * @param listener page manager event listener + * + * @param listener + * page manager event listener */ public void removeListener(PageManagerEventListener listener) { @@ -686,7 +787,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#reset() */ public void reset() @@ -695,10 +798,10 @@ } /** - * notifyNewNode - notify page manager event listeners of - * new node event - * - * @param node new managed node if known + * notifyNewNode - notify page manager event listeners of new node event + * + * @param node + * new managed node if known */ public void notifyNewNode(Node node) { @@ -712,7 +815,8 @@ Iterator listenersIter = listenersList.iterator(); while (listenersIter.hasNext()) { - PageManagerEventListener listener = (PageManagerEventListener)listenersIter.next(); + PageManagerEventListener listener = (PageManagerEventListener) listenersIter + .next(); try { listener.newNode(node); @@ -725,10 +829,11 @@ } /** - * notifyUpdatedNode - notify page manager event listeners of - * updated node event - * - * @param node updated managed node if known + * notifyUpdatedNode - notify page manager event listeners of updated node + * event + * + * @param node + * updated managed node if known */ public void notifyUpdatedNode(Node node) { @@ -742,7 +847,8 @@ Iterator listenersIter = listenersList.iterator(); while (listenersIter.hasNext()) { - PageManagerEventListener listener = (PageManagerEventListener)listenersIter.next(); + PageManagerEventListener listener = (PageManagerEventListener) listenersIter + .next(); try { listener.updatedNode(node); @@ -755,10 +861,11 @@ } /** - * notifyRemovedNode - notify page manager event listeners of - * removed node event - * - * @param node removed managed node if known + * notifyRemovedNode - notify page manager event listeners of removed node + * event + * + * @param node + * removed managed node if known */ public void notifyRemovedNode(Node node) { @@ -772,7 +879,8 @@ Iterator listenersIter = listenersList.iterator(); while (listenersIter.hasNext()) { - PageManagerEventListener listener = (PageManagerEventListener)listenersIter.next(); + PageManagerEventListener listener = (PageManagerEventListener) listenersIter + .next(); try { listener.removedNode(node); @@ -783,37 +891,39 @@ } } } - - public Folder copyFolder(Folder source, String path) - throws NodeException + + public Folder copyFolder(Folder source, String path) throws NodeException { // create the new folder and copy attributes Folder folder = newFolder(path); - folder.setDefaultPage(source.getDefaultPage()); + folder.setDefaultPage(source.getDefaultPage()); folder.setShortTitle(source.getShortTitle()); folder.setTitle(source.getTitle()); folder.setHidden(source.isHidden()); - folder.setDefaultDecorator(source.getDefaultDecorator(Fragment.LAYOUT), Fragment.LAYOUT); - folder.setDefaultDecorator(source.getDefaultDecorator(Fragment.PORTLET), Fragment.PORTLET); + folder.setDefaultDecorator(source.getDefaultDecorator(Fragment.LAYOUT), + Fragment.LAYOUT); + folder.setDefaultDecorator( + source.getDefaultDecorator(Fragment.PORTLET), Fragment.PORTLET); folder.setSkin(source.getSkin()); // copy locale specific metadata folder.getMetadata().copyFields(source.getMetadata().getFields()); - + // copy security constraints - SecurityConstraints srcSecurity = source.getSecurityConstraints(); + SecurityConstraints srcSecurity = source.getSecurityConstraints(); if ((srcSecurity != null) && !srcSecurity.isEmpty()) { - SecurityConstraints copiedSecurity = copySecurityConstraints(FOLDER_NODE_TYPE, srcSecurity); + SecurityConstraints copiedSecurity = copySecurityConstraints( + FOLDER_NODE_TYPE, srcSecurity); folder.setSecurityConstraints(copiedSecurity); - } - + } + // copy document orders folder.setDocumentOrder(DatabasePageManagerUtils.createList()); Iterator documentOrders = source.getDocumentOrder().iterator(); while (documentOrders.hasNext()) { - String name = (String)documentOrders.next(); + String name = (String) documentOrders.next(); folder.getDocumentOrder().add(name); } @@ -823,34 +933,36 @@ { List copiedMenus = copyMenuDefinitions(FOLDER_NODE_TYPE, menus); folder.setMenuDefinitions(copiedMenus); - } - + } + return folder; } - - public Page copyPage(Page source, String path) - throws NodeException + + public Page copyPage(Page source, String path) throws NodeException { // create the new page and copy attributes Page page = newPage(path); page.setTitle(source.getTitle()); page.setShortTitle(source.getShortTitle()); page.setVersion(source.getVersion()); - page.setDefaultDecorator(source.getDefaultDecorator(Fragment.LAYOUT), Fragment.LAYOUT); - page.setDefaultDecorator(source.getDefaultDecorator(Fragment.PORTLET), Fragment.PORTLET); + page.setDefaultDecorator(source.getDefaultDecorator(Fragment.LAYOUT), + Fragment.LAYOUT); + page.setDefaultDecorator(source.getDefaultDecorator(Fragment.PORTLET), + Fragment.PORTLET); page.setSkin(source.getSkin()); page.setHidden(source.isHidden()); - + // copy locale specific metadata page.getMetadata().copyFields(source.getMetadata().getFields()); - + // copy security constraints - SecurityConstraints srcSecurity = source.getSecurityConstraints(); + SecurityConstraints srcSecurity = source.getSecurityConstraints(); if ((srcSecurity != null) && !srcSecurity.isEmpty()) { - SecurityConstraints copiedSecurity = copySecurityConstraints(PAGE_NODE_TYPE, srcSecurity); + SecurityConstraints copiedSecurity = copySecurityConstraints( + PAGE_NODE_TYPE, srcSecurity); page.setSecurityConstraints(copiedSecurity); - } + } // copy menu definitions List menus = source.getMenuDefinitions(); @@ -858,17 +970,18 @@ { List copiedMenus = copyMenuDefinitions(PAGE_NODE_TYPE, menus); page.setMenuDefinitions(copiedMenus); - } - + } + // copy fragments - Fragment root = copyFragment(source.getRootFragment(), source.getRootFragment().getName()); + Fragment root = copyFragment(source.getRootFragment(), source + .getRootFragment().getName()); page.setRootFragment(root); - + return page; } public Fragment copyFragment(Fragment source, String name) - throws NodeException + throws NodeException { // create the new fragment and copy attributes Fragment copy = newFragment(); @@ -881,35 +994,36 @@ copy.setState(source.getState()); // copy security constraints - SecurityConstraints srcSecurity = source.getSecurityConstraints(); + SecurityConstraints srcSecurity = source.getSecurityConstraints(); if ((srcSecurity != null) && !srcSecurity.isEmpty()) { - SecurityConstraints copiedSecurity = copySecurityConstraints(FRAGMENT_NODE_TYPE, srcSecurity); + SecurityConstraints copiedSecurity = copySecurityConstraints( + FRAGMENT_NODE_TYPE, srcSecurity); copy.setSecurityConstraints(copiedSecurity); - } - + } + // copy properties Iterator props = source.getProperties().entrySet().iterator(); while (props.hasNext()) { - Map.Entry prop = (Map.Entry)props.next(); + Map.Entry prop = (Map.Entry) props.next(); copy.getProperties().put(prop.getKey(), prop.getValue()); } - + // copy preferences copy.setPreferences(DatabasePageManagerUtils.createList()); Iterator prefs = source.getPreferences().iterator(); while (prefs.hasNext()) { - FragmentPreference pref = (FragmentPreference)prefs.next(); + FragmentPreference pref = (FragmentPreference) prefs.next(); FragmentPreference newPref = this.newFragmentPreference(); newPref.setName(pref.getName()); newPref.setReadOnly(pref.isReadOnly()); newPref.setValueList(DatabasePageManagerUtils.createList()); - Iterator values = pref.getValueList().iterator(); + Iterator values = pref.getValueList().iterator(); while (values.hasNext()) { - String value = (String)values.next(); + String value = (String) values.next(); newPref.getValueList().add(value); } copy.getPreferences().add(newPref); @@ -919,15 +1033,14 @@ Iterator fragments = source.getFragments().iterator(); while (fragments.hasNext()) { - Fragment fragment = (Fragment)fragments.next(); + Fragment fragment = (Fragment) fragments.next(); Fragment copiedFragment = copyFragment(fragment, fragment.getName()); copy.getFragments().add(copiedFragment); } return copy; } - - public Link copyLink(Link source, String path) - throws NodeException + + public Link copyLink(Link source, String path) throws NodeException { // create the new link and copy attributes Link link = newLink(path); @@ -938,70 +1051,74 @@ link.setTarget(source.getTarget()); link.setUrl(source.getUrl()); link.setHidden(source.isHidden()); - + // copy locale specific metadata link.getMetadata().copyFields(source.getMetadata().getFields()); - + // copy security constraints - SecurityConstraints srcSecurity = source.getSecurityConstraints(); + SecurityConstraints srcSecurity = source.getSecurityConstraints(); if ((srcSecurity != null) && !srcSecurity.isEmpty()) { - SecurityConstraints copiedSecurity = copySecurityConstraints(LINK_NODE_TYPE, srcSecurity); + SecurityConstraints copiedSecurity = copySecurityConstraints( + LINK_NODE_TYPE, srcSecurity); link.setSecurityConstraints(copiedSecurity); - } + } return link; } - public PageSecurity copyPageSecurity(PageSecurity source) - throws NodeException + public PageSecurity copyPageSecurity(PageSecurity source) + throws NodeException { // create the new page security document and copy attributes PageSecurity copy = this.newPageSecurity(); copy.setPath(source.getPath()); - copy.setVersion(source.getVersion()); + copy.setVersion(source.getVersion()); // copy security constraint defintions - copy.setSecurityConstraintsDefs(DatabasePageManagerUtils.createList()); + copy.setSecurityConstraintsDefs(DatabasePageManagerUtils.createList()); Iterator defs = source.getSecurityConstraintsDefs().iterator(); while (defs.hasNext()) { - SecurityConstraintsDef def = (SecurityConstraintsDef)defs.next(); - SecurityConstraintsDef defCopy = this.newSecurityConstraintsDef(); + SecurityConstraintsDef def = (SecurityConstraintsDef) defs.next(); + SecurityConstraintsDef defCopy = this.newSecurityConstraintsDef(); defCopy.setName(def.getName()); List copiedConstraints = DatabasePageManagerUtils.createList(); Iterator constraints = def.getSecurityConstraints().iterator(); while (constraints.hasNext()) { - SecurityConstraint srcConstraint = (SecurityConstraint)constraints.next(); + SecurityConstraint srcConstraint = (SecurityConstraint) constraints + .next(); SecurityConstraint dstConstraint = newPageSecuritySecurityConstraint(); copyConstraint(srcConstraint, dstConstraint); copiedConstraints.add(dstConstraint); - } + } defCopy.setSecurityConstraints(copiedConstraints); copy.getSecurityConstraintsDefs().add(defCopy); } - + // copy global security constraint references - copy.setGlobalSecurityConstraintsRefs(DatabasePageManagerUtils.createList()); + copy.setGlobalSecurityConstraintsRefs(DatabasePageManagerUtils + .createList()); Iterator globals = source.getGlobalSecurityConstraintsRefs().iterator(); while (globals.hasNext()) { - String global = (String)globals.next(); + String global = (String) globals.next(); copy.getGlobalSecurityConstraintsRefs().add(global); } - + return copy; } protected List copyMenuDefinitions(String type, List srcMenus) { - List copiedMenus = DatabasePageManagerUtils.createList(); + List copiedMenus = DatabasePageManagerUtils.createList(); Iterator menus = srcMenus.iterator(); while (menus.hasNext()) { - MenuDefinition srcMenu = (MenuDefinition)menus.next(); - MenuDefinition copiedMenu = (MenuDefinition)copyMenuElement(type, srcMenu); + MenuDefinition srcMenu = (MenuDefinition) menus.next(); + MenuDefinition copiedMenu = (MenuDefinition) copyMenuElement(type, + srcMenu); if (copiedMenu != null) { copiedMenus.add(copiedMenu); @@ -1009,13 +1126,13 @@ } return copiedMenus; } - + protected Object copyMenuElement(String type, Object srcElement) { if (srcElement instanceof MenuDefinition) { // create the new menu element and copy attributes - MenuDefinition source = (MenuDefinition)srcElement; + MenuDefinition source = (MenuDefinition) srcElement; MenuDefinition menu = null; if (type.equals(PAGE_NODE_TYPE)) { @@ -1038,12 +1155,12 @@ // copy locale specific metadata menu.getMetadata().copyFields(source.getMetadata().getFields()); - + // recursively copy menu elements List elements = source.getMenuElements(); if (elements != null) { - List copiedElements = DatabasePageManagerUtils.createList(); + List copiedElements = DatabasePageManagerUtils.createList(); Iterator elementsIter = elements.iterator(); while (elementsIter.hasNext()) { @@ -1062,7 +1179,7 @@ else if (srcElement instanceof MenuExcludeDefinition) { // create the new menu exclude element and copy attributes - MenuExcludeDefinition source = (MenuExcludeDefinition)srcElement; + MenuExcludeDefinition source = (MenuExcludeDefinition) srcElement; MenuExcludeDefinition menuExclude = null; if (type.equals(PAGE_NODE_TYPE)) { @@ -1078,7 +1195,7 @@ else if (srcElement instanceof MenuIncludeDefinition) { // create the new menu include element and copy attributes - MenuIncludeDefinition source = (MenuIncludeDefinition)srcElement; + MenuIncludeDefinition source = (MenuIncludeDefinition) srcElement; MenuIncludeDefinition menuInclude = null; if (type.equals(PAGE_NODE_TYPE)) { @@ -1095,7 +1212,7 @@ else if (srcElement instanceof MenuOptionsDefinition) { // create the new menu options element and copy attributes - MenuOptionsDefinition source = (MenuOptionsDefinition)srcElement; + MenuOptionsDefinition source = (MenuOptionsDefinition) srcElement; MenuOptionsDefinition menuOptions = null; if (type.equals(PAGE_NODE_TYPE)) { @@ -1117,7 +1234,7 @@ else if (srcElement instanceof MenuSeparatorDefinition) { // create the new menu separator element and copy attributes - MenuSeparatorDefinition source = (MenuSeparatorDefinition)srcElement; + MenuSeparatorDefinition source = (MenuSeparatorDefinition) srcElement; MenuSeparatorDefinition menuSeparator = null; if (type.equals(PAGE_NODE_TYPE)) { @@ -1132,25 +1249,28 @@ menuSeparator.setText(source.getText()); // copy locale specific metadata - menuSeparator.getMetadata().copyFields(source.getMetadata().getFields()); - + menuSeparator.getMetadata().copyFields( + source.getMetadata().getFields()); + return menuSeparator; } return null; } - protected void copyConstraint(SecurityConstraint srcConstraint, SecurityConstraint dstConstraint) + protected void copyConstraint(SecurityConstraint srcConstraint, + SecurityConstraint dstConstraint) { - dstConstraint.setUsers(srcConstraint.getUsers()); + dstConstraint.setUsers(srcConstraint.getUsers()); dstConstraint.setRoles(srcConstraint.getRoles()); dstConstraint.setGroups(srcConstraint.getGroups()); - dstConstraint.setPermissions(srcConstraint.getPermissions()); + dstConstraint.setPermissions(srcConstraint.getPermissions()); } - - protected SecurityConstraints copySecurityConstraints(String type, SecurityConstraints source) + + protected SecurityConstraints copySecurityConstraints(String type, + SecurityConstraints source) { SecurityConstraints security = newSecurityConstraints(); - if (source.getOwner() != null) + if (source.getOwner() != null) { security.setOwner(source.getOwner()); } @@ -1160,7 +1280,8 @@ Iterator constraints = source.getSecurityConstraints().iterator(); while (constraints.hasNext()) { - SecurityConstraint srcConstraint = (SecurityConstraint)constraints.next(); + SecurityConstraint srcConstraint = (SecurityConstraint) constraints + .next(); SecurityConstraint dstConstraint = null; if (type.equals(PAGE_NODE_TYPE)) { @@ -1188,37 +1309,42 @@ List copiedRefs = DatabasePageManagerUtils.createList(); Iterator refs = source.getSecurityConstraintsRefs().iterator(); while (refs.hasNext()) - { - String constraintsRef = (String)refs.next(); + { + String constraintsRef = (String) refs.next(); copiedRefs.add(constraintsRef); } - security.setSecurityConstraintsRefs(copiedRefs); + security.setSecurityConstraintsRefs(copiedRefs); } return security; } - + /** * Deep copy a folder - * - * @param source source folder - * @param dest destination folder + * + * @param source + * source folder + * @param dest + * destination folder */ - public void deepCopyFolder(Folder srcFolder, String destinationPath, String owner) - throws NodeException + public void deepCopyFolder(Folder srcFolder, String destinationPath, + String owner) throws NodeException { - PageManagerUtils.deepCopyFolder(this, srcFolder, destinationPath, owner); + PageManagerUtils + .deepCopyFolder(this, srcFolder, destinationPath, owner); } - + public Page getUserPage(String userName, String pageName) - throws PageNotFoundException, NodeException + throws PageNotFoundException, NodeException { - return this.getPage(Folder.USER_FOLDER + userName + Folder.PATH_SEPARATOR + pageName); + return this.getPage(Folder.USER_FOLDER + userName + + Folder.PATH_SEPARATOR + pageName); } - - public Folder getUserFolder(String userName) - throws FolderNotFoundException, InvalidFolderException, NodeException + + public Folder getUserFolder(String userName) + throws FolderNotFoundException, InvalidFolderException, + NodeException { - return this.getFolder(Folder.USER_FOLDER + userName); + return this.getFolder(Folder.USER_FOLDER + userName); } public boolean folderExists(String folderName) @@ -1233,6 +1359,7 @@ } return true; } + public boolean pageExists(String pageName) { try @@ -1245,7 +1372,7 @@ } return true; } - + public boolean linkExists(String linkName) { try @@ -1271,12 +1398,13 @@ } return true; } - + public boolean userPageExists(String userName, String pageName) { try { - getPage(Folder.USER_FOLDER + userName + Folder.PATH_SEPARATOR + pageName); + getPage(Folder.USER_FOLDER + userName + Folder.PATH_SEPARATOR + + pageName); } catch (Exception e) { @@ -1284,16 +1412,17 @@ } return true; } - + /** - * Creates a user's home page from the roles of the current user. - * The use case: when a portal is setup to use shared pages, but then - * the user attempts to customize. At this point, we create the new page(s) for the user. + * Creates a user's home page from the roles of the current user. The use + * case: when a portal is setup to use shared pages, but then the user + * attempts to customize. At this point, we create the new page(s) for the + * user. * * @param subject */ public void createUserHomePagesFromRoles(Subject subject) - throws NodeException + throws NodeException { PageManagerUtils.createUserHomePagesFromRoles(this, subject); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/DelegatingPageManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/DelegatingPageManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/DelegatingPageManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,7 +33,6 @@ import org.apache.jetspeed.page.document.NodeSet; import org.apache.jetspeed.page.document.UnsupportedDocumentTypeException; - /** * DelegatingPageManager * @@ -43,15 +42,16 @@ public class DelegatingPageManager extends AbstractPageManager { - public DelegatingPageManager( - boolean isPermissionsSecurity, - boolean isConstraintsSecurity, - Map modelClasses) + + public DelegatingPageManager(boolean isPermissionsSecurity, + boolean isConstraintsSecurity, Map modelClasses) { super(isPermissionsSecurity, isConstraintsSecurity, modelClasses); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getPage(java.lang.String) */ public Page getPage(String id) throws PageNotFoundException, NodeException @@ -60,7 +60,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getContentPage(java.lang.String) */ public ContentPage getContentPage(String path) @@ -70,7 +72,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getLink(java.lang.String) */ public Link getLink(String name) throws DocumentNotFoundException, @@ -80,7 +84,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getPageSecurity() */ public PageSecurity getPageSecurity() throws DocumentNotFoundException, @@ -94,8 +100,10 @@ { return false; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getFolder(java.lang.String) */ public Folder getFolder(String folderPath) throws FolderNotFoundException, @@ -105,7 +113,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getFolders(org.apache.jetspeed.om.folder.Folder) */ public NodeSet getFolders(Folder folder) throws DocumentException @@ -114,16 +124,21 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getFolder(org.apache.jetspeed.om.folder.Folder,java.lang.String) */ - public Folder getFolder(Folder folder, String name) throws FolderNotFoundException, DocumentException + public Folder getFolder(Folder folder, String name) + throws FolderNotFoundException, DocumentException { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getPages(org.apache.jetspeed.om.folder.Folder) */ public NodeSet getPages(Folder folder) throws NodeException @@ -131,44 +146,57 @@ // TODO Auto-generated method stub return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getPage(org.apache.jetspeed.om.folder.Folder,java.lang.String) */ - public Page getPage(Folder folder, String name) throws PageNotFoundException, NodeException + public Page getPage(Folder folder, String name) + throws PageNotFoundException, NodeException { // TODO Auto-generated method stub return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getLinks(org.apache.jetspeed.om.folder.Folder) - */ + */ public NodeSet getLinks(Folder folder) throws NodeException { // TODO Auto-generated method stub return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getLink(org.apache.jetspeed.om.folder.Folder,java.lang.String) - */ - public Link getLink(Folder folder, String name) throws DocumentNotFoundException, NodeException + */ + public Link getLink(Folder folder, String name) + throws DocumentNotFoundException, NodeException { // TODO Auto-generated method stub return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getPageSecurity(org.apache.jetspeed.om.folder.Folder) - */ - public PageSecurity getPageSecurity(Folder folder) throws DocumentNotFoundException, NodeException + */ + public PageSecurity getPageSecurity(Folder folder) + throws DocumentNotFoundException, NodeException { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getAll(org.apache.jetspeed.om.folder.Folder) */ public NodeSet getAll(Folder folder) throws DocumentException @@ -177,7 +205,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#updatePage(org.apache.jetspeed.om.page.Page) */ public void updatePage(Page page) throws NodeException, @@ -187,7 +217,9 @@ } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#removePage(org.apache.jetspeed.om.page.Page) */ public void removePage(Page page) throws NodeException, @@ -197,7 +229,9 @@ } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#updateFolder(org.apache.jetspeed.om.folder.Folder) */ public void updateFolder(Folder folder) throws NodeException, @@ -207,7 +241,9 @@ } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#updateFolder(org.apache.jetspeed.om.folder.Folder,boolean) */ public void updateFolder(Folder folder, boolean deep) throws NodeException, @@ -217,7 +253,9 @@ } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#removeFolder(org.apache.jetspeed.om.folder.Folder) */ public void removeFolder(Folder folder) throws NodeException, @@ -227,7 +265,9 @@ } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#updateLink(org.apache.jetspeed.om.page.Link) */ public void updateLink(Link link) throws NodeException, @@ -237,7 +277,9 @@ } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#removeLink(org.apache.jetspeed.om.page.Link) */ public void removeLink(Link link) throws NodeException, @@ -247,28 +289,31 @@ } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#updatePageSecurity(org.apache.jetspeed.om.page.PageSecurity) */ - public void updatePageSecurity(PageSecurity pageSecurity) throws - NodeException, FailedToUpdateDocumentException + public void updatePageSecurity(PageSecurity pageSecurity) + throws NodeException, FailedToUpdateDocumentException { // TODO Auto-generated method stub } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#removePageSecurity(org.apache.jetspeed.om.page.PageSecurity) */ - public void removePageSecurity(PageSecurity pageSecurity) throws - NodeException, FailedToDeleteDocumentException + public void removePageSecurity(PageSecurity pageSecurity) + throws NodeException, FailedToDeleteDocumentException { // TODO Auto-generated method stub } - - public int addPages(Page[] pages) - throws NodeException + + public int addPages(Page[] pages) throws NodeException { throw new NodeException("not impl"); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/PageImporter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/PageImporter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/PageImporter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,54 +37,73 @@ public class PageImporter { + /* source page manager impl */ private PageManager sourceManager; + /* destination page manager impl */ - private PageManager destManager; + private PageManager destManager; + /* rootFolder to start importing from */ private String rootFolder; + /* flag: overwrite folders during import */ private boolean overwriteFolders = false; - /* flag: overwrite pages during import */ + + /* flag: overwrite pages during import */ private boolean overwritePages = true; - /* count of total folders imported */ - private int folderCount = 0; + + /* count of total folders imported */ + private int folderCount = 0; + /* count of total pages imported */ private int pageCount = 0; + /* count of total links imported */ private int linkCount = 0; - + public static void main(String args[]) { - String fileName = System.getProperty("org.apache.jetspeed.page.import.configuration", "import.properties"); + String fileName = System.getProperty( + "org.apache.jetspeed.page.import.configuration", + "import.properties"); PropertiesConfiguration configuration = new PropertiesConfiguration(); try { - configuration.load(fileName); - String [] bootAssemblies = configuration.getStringArray("boot.assemblies"); - String [] assemblies = configuration.getStringArray("assemblies"); - ClassPathXmlApplicationContext ctx; - + configuration.load(fileName); + String[] bootAssemblies = configuration + .getStringArray("boot.assemblies"); + String[] assemblies = configuration.getStringArray("assemblies"); + ClassPathXmlApplicationContext ctx; + if (bootAssemblies != null) { - ApplicationContext bootContext = new ClassPathXmlApplicationContext(bootAssemblies, true); - ctx = new ClassPathXmlApplicationContext(assemblies, true, bootContext); + ApplicationContext bootContext = new ClassPathXmlApplicationContext( + bootAssemblies, true); + ctx = new ClassPathXmlApplicationContext(assemblies, true, + bootContext); } else { ctx = new ClassPathXmlApplicationContext(assemblies, true); } - + String rootFolder = configuration.getString("root.folder", "/"); - boolean overwriteFolders = configuration.getBoolean("overwrite.folders", true); - boolean overwritePages = configuration.getBoolean("overwrite.pages", true); + boolean overwriteFolders = configuration.getBoolean( + "overwrite.folders", true); + boolean overwritePages = configuration.getBoolean( + "overwrite.pages", true); boolean fullImport = configuration.getBoolean("full.import", true); - String sourcePageManager = configuration.getString("source.page.manager", "castorPageManager"); - String destPageManager = configuration.getString("dest.page.manager", "dbPageManager"); - - PageManager srcManager = (PageManager)ctx.getBean(sourcePageManager); - PageManager dstManager = (PageManager)ctx.getBean(destPageManager); - PageImporter importer = new PageImporter(srcManager, dstManager, rootFolder, overwriteFolders, overwritePages); + String sourcePageManager = configuration.getString( + "source.page.manager", "castorPageManager"); + String destPageManager = configuration.getString( + "dest.page.manager", "dbPageManager"); + + PageManager srcManager = (PageManager) ctx + .getBean(sourcePageManager); + PageManager dstManager = (PageManager) ctx.getBean(destPageManager); + PageImporter importer = new PageImporter(srcManager, dstManager, + rootFolder, overwriteFolders, overwritePages); if (fullImport) { importer.fullImport(); @@ -99,14 +118,11 @@ System.err.println("Failed to import: " + e); e.printStackTrace(); } - + } - - public PageImporter(PageManager sourceManager, - PageManager destManager, - String rootFolder, - boolean overwriteFolders, - boolean overwritePages) + + public PageImporter(PageManager sourceManager, PageManager destManager, + String rootFolder, boolean overwriteFolders, boolean overwritePages) { this.sourceManager = sourceManager; this.destManager = destManager; @@ -114,14 +130,12 @@ this.overwriteFolders = overwriteFolders; this.overwritePages = overwritePages; } - - public void fullImport() - throws JetspeedException + + public void fullImport() throws JetspeedException { - Folder fsRoot = sourceManager.getFolder(rootFolder); + Folder fsRoot = sourceManager.getFolder(rootFolder); importFolder(fsRoot); - - + // create the root page security PageSecurity sourcePageSecurity = null; try @@ -132,39 +146,40 @@ { // skip over it, not found } - + if (sourcePageSecurity != null) { - PageSecurity rootSecurity = destManager.copyPageSecurity(sourcePageSecurity); + PageSecurity rootSecurity = destManager + .copyPageSecurity(sourcePageSecurity); destManager.updatePageSecurity(rootSecurity); } } - public void folderTreeImport() - throws JetspeedException + public void folderTreeImport() throws JetspeedException { - Folder fsRoot = sourceManager.getFolder(rootFolder); - importFolder(fsRoot); + Folder fsRoot = sourceManager.getFolder(rootFolder); + importFolder(fsRoot); } - - private Folder importFolder(Folder srcFolder) - throws JetspeedException + + private Folder importFolder(Folder srcFolder) throws JetspeedException { - Folder dstFolder = lookupFolder(srcFolder.getPath()); + Folder dstFolder = lookupFolder(srcFolder.getPath()); if (null != dstFolder) { if (isOverwriteFolders()) { System.out.println("overwriting folder " + srcFolder.getPath()); destManager.removeFolder(dstFolder); - dstFolder = destManager - .copyFolder(srcFolder, srcFolder.getPath()); + dstFolder = destManager.copyFolder(srcFolder, srcFolder + .getPath()); destManager.updateFolder(dstFolder); folderCount++; - } else + } + else System.out.println("skipping folder " + srcFolder.getPath()); - } else + } + else { System.out.println("importing new folder " + srcFolder.getPath()); dstFolder = destManager.copyFolder(srcFolder, srcFolder.getPath()); @@ -174,22 +189,22 @@ Iterator pages = srcFolder.getPages().iterator(); while (pages.hasNext()) { - Page srcPage = (Page)pages.next(); + Page srcPage = (Page) pages.next(); Page dstPage = lookupPage(srcPage.getPath()); if (null != dstPage) { if (isOverwritePages()) { - System.out.println("overwriting page " + srcPage.getPath()); + System.out.println("overwriting page " + srcPage.getPath()); destManager.removePage(dstPage); dstPage = destManager.copyPage(srcPage, srcPage.getPath()); destManager.updatePage(dstPage); - pageCount++; + pageCount++; } else - System.out.println("skipping page " + srcPage.getPath()); + System.out.println("skipping page " + srcPage.getPath()); } - else + else { System.out.println("importing new page " + srcPage.getPath()); dstPage = destManager.copyPage(srcPage, srcPage.getPath()); @@ -201,22 +216,22 @@ Iterator links = srcFolder.getLinks().iterator(); while (links.hasNext()) { - Link srcLink = (Link)links.next(); + Link srcLink = (Link) links.next(); Link dstLink = lookupLink(srcLink.getPath()); if (null != dstLink) { if (isOverwritePages()) { - System.out.println("overwriting link " + srcLink.getPath()); + System.out.println("overwriting link " + srcLink.getPath()); destManager.removeLink(dstLink); dstLink = destManager.copyLink(srcLink, srcLink.getPath()); destManager.updateLink(dstLink); - linkCount++; + linkCount++; } else - System.out.println("skipping link " + srcLink.getPath()); + System.out.println("skipping link " + srcLink.getPath()); } - else + else { System.out.println("importing new link " + srcLink.getPath()); dstLink = destManager.copyLink(srcLink, srcLink.getPath()); @@ -224,17 +239,17 @@ linkCount++; } } - + Iterator folders = srcFolder.getFolders().iterator(); while (folders.hasNext()) { - Folder folder = (Folder)folders.next(); + Folder folder = (Folder) folders.next(); importFolder(folder); } - + return dstFolder; } - + private Page lookupPage(String path) { try @@ -246,7 +261,7 @@ return null; } } - + private Link lookupLink(String path) { try @@ -258,7 +273,7 @@ return null; } } - + private Folder lookupFolder(String path) { try @@ -270,7 +285,7 @@ return null; } } - + /** * @return Returns the overwrite. */ @@ -278,14 +293,16 @@ { return overwriteFolders; } + /** - * @param overwrite The overwrite to set. + * @param overwrite + * The overwrite to set. */ public void setOverwriteFolders(boolean overwrite) { this.overwriteFolders = overwrite; } - + /** * @return Returns the destManager. */ @@ -293,13 +310,16 @@ { return destManager; } + /** - * @param destManager The destManager to set. + * @param destManager + * The destManager to set. */ public void setDestManager(PageManager destManager) { this.destManager = destManager; } + /** * @return Returns the folderCount. */ @@ -307,13 +327,16 @@ { return folderCount; } + /** - * @param folderCount The folderCount to set. + * @param folderCount + * The folderCount to set. */ public void setFolderCount(int folderCount) { this.folderCount = folderCount; } + /** * @return Returns the overwritePages. */ @@ -321,13 +344,16 @@ { return overwritePages; } + /** - * @param overwritePages The overwritePages to set. + * @param overwritePages + * The overwritePages to set. */ public void setOverwritePages(boolean overwritePages) { this.overwritePages = overwritePages; } + /** * @return Returns the pageCount. */ @@ -335,13 +361,16 @@ { return pageCount; } + /** - * @param pageCount The pageCount to set. + * @param pageCount + * The pageCount to set. */ public void setPageCount(int pageCount) { this.pageCount = pageCount; } + /** * @return Returns the linkCount. */ @@ -349,13 +378,16 @@ { return linkCount; } + /** - * @param linkCount The linkCount to set. + * @param linkCount + * The linkCount to set. */ public void setLinkCount(int linkCount) { this.linkCount = linkCount; } + /** * @return Returns the rootFolder. */ @@ -363,13 +395,16 @@ { return rootFolder; } + /** - * @param rootFolder The rootFolder to set. + * @param rootFolder + * The rootFolder to set. */ public void setRootFolder(String rootFolder) { this.rootFolder = rootFolder; } + /** * @return Returns the sourceManager. */ @@ -377,8 +412,10 @@ { return sourceManager; } + /** - * @param sourceManager The sourceManager to set. + * @param sourceManager + * The sourceManager to set. */ public void setSourceManager(PageManager sourceManager) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/PageManagerSecurityUtils.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/PageManagerSecurityUtils.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/PageManagerSecurityUtils.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,7 +34,6 @@ import org.apache.jetspeed.security.RolePrincipal; import org.apache.jetspeed.security.UserPrincipal; - /** * PageManagerUtils * @@ -43,8 +42,9 @@ */ public class PageManagerSecurityUtils { - public static boolean checkConstraint(SecurityConstraintsDef def, String actions) - throws DocumentException + + public static boolean checkConstraint(SecurityConstraintsDef def, + String actions) throws DocumentException { List viewActionList = SecurityConstraintImpl.parseCSVList(actions); List otherActionsList = null; @@ -69,10 +69,8 @@ // get current request context subject Subject subject = JSSubject.getSubject(AccessController.getContext()); - if (subject == null) - { - throw new SecurityException("Security Consraint Check: Missing JSSubject"); - } + if (subject == null) { throw new SecurityException( + "Security Consraint Check: Missing JSSubject"); } // get user/group/role principal names List userPrincipals = null; @@ -107,38 +105,48 @@ groupPrincipals.add(principal.getName()); } } - + boolean result = false; - + // check constraints using parsed action and access lists if (viewActionList != null) { - result = checkConstraints(viewActionList, userPrincipals, rolePrincipals, groupPrincipals, def); + result = checkConstraints(viewActionList, userPrincipals, + rolePrincipals, groupPrincipals, def); } if (otherActionsList != null) { - result = checkConstraints(otherActionsList, userPrincipals, rolePrincipals, groupPrincipals, def); + result = checkConstraints(otherActionsList, userPrincipals, + rolePrincipals, groupPrincipals, def); } return result; } + /** - * check access for the constraints list of a security constraints definition + * check access for the constraints list of a security constraints + * definition * - * @param actions given actions - * @param userPrincipals set of user principals - * @param rolePrincipals set of role principals - * @param groupPrincipals set oof group principals - * @param def the security constraint definition + * @param actions + * given actions + * @param userPrincipals + * set of user principals + * @param rolePrincipals + * set of role principals + * @param groupPrincipals + * set oof group principals + * @param def + * the security constraint definition * @throws SecurityException */ - public static boolean checkConstraints(List actions, List userPrincipals, List rolePrincipals, List groupPrincipals, SecurityConstraintsDef def) - throws DocumentException + public static boolean checkConstraints(List actions, List userPrincipals, + List rolePrincipals, List groupPrincipals, + SecurityConstraintsDef def) throws DocumentException { - + List checkConstraints = def.getSecurityConstraints(); - // SecurityConstraint c =(SecurityConstraint)constraints.next(); + // SecurityConstraint c =(SecurityConstraint)constraints.next(); // skip missing or empty constraints: permit all access - //List checkConstraints = getAllSecurityConstraints(pageSecurity); + // List checkConstraints = getAllSecurityConstraints(pageSecurity); if ((checkConstraints != null) && !checkConstraints.isEmpty()) { // test each action, constraints check passes only @@ -148,29 +156,33 @@ { // check each action: // - if any actions explicity permitted, (including owner), - // assume no permissions are permitted by default + // assume no permissions are permitted by default // - if all constraints do not specify a permission, assume - // access is permitted by default - String action = (String)actionsIter.next(); + // access is permitted by default + String action = (String) actionsIter.next(); boolean actionPermitted = false; boolean actionNotPermitted = false; - boolean anyActionsPermitted = true; // TODO:(getOwner() != null); - + boolean anyActionsPermitted = true; // TODO:(getOwner() != + // null); + // check against constraints Iterator checkConstraintsIter = checkConstraints.iterator(); while (checkConstraintsIter.hasNext()) { - SecurityConstraintImpl constraint = (SecurityConstraintImpl)checkConstraintsIter.next(); - + SecurityConstraintImpl constraint = (SecurityConstraintImpl) checkConstraintsIter + .next(); + // if permissions specified, attempt to match constraint if (constraint.getPermissions() != null) { // explicit actions permitted anyActionsPermitted = true; - // test action permission match and user/role/group principal match - if (constraint.actionMatch(action) && - constraint.principalsMatch(userPrincipals, rolePrincipals, groupPrincipals, true)) + // test action permission match and user/role/group + // principal match + if (constraint.actionMatch(action) + && constraint.principalsMatch(userPrincipals, + rolePrincipals, groupPrincipals, true)) { actionPermitted = true; break; @@ -178,19 +190,24 @@ } else { - // permissions not specified: not permitted if any principal matched - if (constraint.principalsMatch(userPrincipals, rolePrincipals, groupPrincipals, false)) + // permissions not specified: not permitted if any + // principal matched + if (constraint.principalsMatch(userPrincipals, + rolePrincipals, groupPrincipals, false)) { actionNotPermitted = true; break; } } } - + // fail if any action not permitted - if ((!actionPermitted && anyActionsPermitted) || actionNotPermitted) + if ((!actionPermitted && anyActionsPermitted) + || actionNotPermitted) { - //throw new SecurityException("SecurityConstraintsImpl.checkConstraints(): Access for " + action + " not permitted."); + // throw new + // SecurityException("SecurityConstraintsImpl.checkConstraints(): + // Access for " + action + " not permitted."); return false; } } @@ -199,10 +216,12 @@ { // fail for any action if owner specified // since no other constraints were found - if (/*(getOwner() != null) && */ !actions.isEmpty()) + if (/* (getOwner() != null) && */!actions.isEmpty()) { - //String action = (String)actions.get(0); - //throw new SecurityException("SecurityConstraintsImpl.checkConstraints(): Access for " + action + " not permitted, (not owner)."); + // String action = (String)actions.get(0); + // throw new + // SecurityException("SecurityConstraintsImpl.checkConstraints(): + // Access for " + action + " not permitted, (not owner)."); return false; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/PageManagerUtils.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/PageManagerUtils.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/PageManagerUtils.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,7 +33,6 @@ import org.apache.jetspeed.security.SecurityHelper; import org.apache.jetspeed.security.UserPrincipal; - /** * PageManagerUtils * @@ -43,19 +42,22 @@ */ public class PageManagerUtils { - protected static Log log = LogFactory.getLog(PageManagerUtils.class); - + + protected static Log log = LogFactory.getLog(PageManagerUtils.class); + /** - * Creates a user's home page from the roles of the current user. - * The use case: when a portal is setup to use shared pages, but then - * the user attempts to customize. At this point, we create the new page(s) for the user. + * Creates a user's home page from the roles of the current user. The use + * case: when a portal is setup to use shared pages, but then the user + * attempts to customize. At this point, we create the new page(s) for the + * user. * * @param subject */ - public static void createUserHomePagesFromRoles(PageManager pageManager, Subject subject) - throws NodeException + public static void createUserHomePagesFromRoles(PageManager pageManager, + Subject subject) throws NodeException { - Principal principal = SecurityHelper.getBestPrincipal(subject, UserPrincipal.class); + Principal principal = SecurityHelper.getBestPrincipal(subject, + UserPrincipal.class); if (principal == null) { String errorMessage = "Could not create user home for null principal"; @@ -64,7 +66,7 @@ } try { - String userName = principal.getName(); + String userName = principal.getName(); // get user home Folder newUserFolder; if (pageManager.userFolderExists(userName)) @@ -73,96 +75,97 @@ } else { - newUserFolder = pageManager.newFolder(Folder.USER_FOLDER + userName); - SecurityConstraints constraints = pageManager.newSecurityConstraints(); + newUserFolder = pageManager.newFolder(Folder.USER_FOLDER + + userName); + SecurityConstraints constraints = pageManager + .newSecurityConstraints(); newUserFolder.setSecurityConstraints(constraints); newUserFolder.getSecurityConstraints().setOwner(userName); - pageManager.updateFolder(newUserFolder); - } - // for each role for a user, deep copy the folder contents for that role + pageManager.updateFolder(newUserFolder); + } + // for each role for a user, deep copy the folder contents for that + // role // into the user's home // TODO: this algorithm could actually merge pages on dups - Iterator roles = SecurityHelper.getPrincipals(subject, RolePrincipal.class).iterator(); + Iterator roles = SecurityHelper.getPrincipals(subject, + RolePrincipal.class).iterator(); while (roles.hasNext()) - { - RolePrincipal role = (RolePrincipal)roles.next(); - if (pageManager.folderExists(Folder.ROLE_FOLDER + role.getName())) + { + RolePrincipal role = (RolePrincipal) roles.next(); + if (pageManager.folderExists(Folder.ROLE_FOLDER + + role.getName())) { - Folder roleFolder = pageManager.getFolder(Folder.ROLE_FOLDER + role.getName()); - deepMergeFolder(pageManager, roleFolder, Folder.USER_FOLDER + newUserFolder.getName(), userName, role.getName()); + Folder roleFolder = pageManager + .getFolder(Folder.ROLE_FOLDER + role.getName()); + deepMergeFolder(pageManager, roleFolder, Folder.USER_FOLDER + + newUserFolder.getName(), userName, role.getName()); } } } catch (Exception e) { - String errorMessage = "createUserHomePagesFromRoles failed: " + e.getMessage(); + String errorMessage = "createUserHomePagesFromRoles failed: " + + e.getMessage(); log.error(errorMessage, e); throw new NodeException(errorMessage, e); } } /** - * Deep merges from a source folder into a destination path for the given owner. - * The unique name is used in conflict resolution for name collisions. - * Example: deep merge a given role folder 'X' into /_user/david - * uniqueName = 'X' - * owner = 'david' - * destinationPath = '_user/david' - * + * Deep merges from a source folder into a destination path for the given + * owner. The unique name is used in conflict resolution for name + * collisions. Example: deep merge a given role folder 'X' into /_user/david + * uniqueName = 'X' owner = 'david' destinationPath = '_user/david' + * * @param srcFolder * @param destinationPath * @param owner * @param uniqueName * @throws NodeException */ - public static void deepMergeFolder(PageManager pageManager, Folder srcFolder, String destinationPath, String owner, String uniqueName) - throws NodeException - { + public static void deepMergeFolder(PageManager pageManager, + Folder srcFolder, String destinationPath, String owner, + String uniqueName) throws NodeException + { Iterator pages = srcFolder.getPages().iterator(); while (pages.hasNext()) { - Page srcPage = (Page)pages.next(); + Page srcPage = (Page) pages.next(); String path = concatenatePaths(destinationPath, srcPage.getName()); if (!pageManager.pageExists(path)) { Page dstPage = pageManager.copyPage(srcPage, path); pageManager.updatePage(dstPage); } - //Commented, as these were creating the duplicate objects - /* - else - { - path = concatenatePaths(destinationPath, uniqueName + "-" +srcPage.getName()); - Page dstPage = pageManager.copyPage(srcPage, path); - pageManager.updatePage(dstPage); - } - */ + // Commented, as these were creating the duplicate objects + /* + * else { path = concatenatePaths(destinationPath, uniqueName + "-" + * +srcPage.getName()); Page dstPage = pageManager.copyPage(srcPage, + * path); pageManager.updatePage(dstPage); } + */ } - + Iterator links = srcFolder.getLinks().iterator(); while (links.hasNext()) { - Link srcLink = (Link)links.next(); + Link srcLink = (Link) links.next(); String path = concatenatePaths(destinationPath, srcLink.getName()); if (!pageManager.linkExists(path)) { Link dstLink = pageManager.copyLink(srcLink, path); pageManager.updateLink(dstLink); } - //Commented, as these were creating the duplicate objects + // Commented, as these were creating the duplicate objects /* - else - { - path = concatenatePaths(destinationPath, uniqueName + "-" +srcLink.getName()); - Link dstLink = pageManager.copyLink(srcLink, path); - pageManager.updateLink(dstLink); - } - */ - } + * else { path = concatenatePaths(destinationPath, uniqueName + "-" + * +srcLink.getName()); Link dstLink = pageManager.copyLink(srcLink, + * path); pageManager.updateLink(dstLink); } + */ + } Iterator folders = srcFolder.getFolders().iterator(); while (folders.hasNext()) { - Folder folder = (Folder)folders.next(); + Folder folder = (Folder) folders.next(); String newPath = concatenatePaths(destinationPath, folder.getName()); if (!pageManager.folderExists(newPath)) { @@ -170,7 +173,7 @@ pageManager.updateFolder(dstFolder); } deepMergeFolder(pageManager, folder, newPath, null, uniqueName); - } + } } public static String concatenatePaths(String base, String path) @@ -178,31 +181,25 @@ String result = ""; if (base == null) { - if (path == null) - { - return result; - } + if (path == null) { return result; } return path; } else { - if (path == null) - { - return base; - } + if (path == null) { return base; } } - if (base.endsWith(Folder.PATH_SEPARATOR)) + if (base.endsWith(Folder.PATH_SEPARATOR)) { if (path.startsWith(Folder.PATH_SEPARATOR)) { result = base.concat(path.substring(1)); return result; } - + } else { - if (!path.startsWith(Folder.PATH_SEPARATOR)) + if (!path.startsWith(Folder.PATH_SEPARATOR)) { result = base.concat(Folder.PATH_SEPARATOR).concat(path); return result; @@ -210,15 +207,18 @@ } return base.concat(path); } - + /** * Deep copy a folder - * - * @param source source folder - * @param dest destination folder + * + * @param source + * source folder + * @param dest + * destination folder */ - public static void deepCopyFolder(PageManager pageManager, Folder srcFolder, String destinationPath, String owner) - throws NodeException + public static void deepCopyFolder(PageManager pageManager, + Folder srcFolder, String destinationPath, String owner) + throws NodeException { boolean found = true; try @@ -229,14 +229,12 @@ { found = false; } - if (found) - { - throw new NodeException("Destination already exists"); - } + if (found) { throw new NodeException("Destination already exists"); } Folder dstFolder = pageManager.copyFolder(srcFolder, destinationPath); if (owner != null) { - SecurityConstraints constraints = dstFolder.getSecurityConstraints(); + SecurityConstraints constraints = dstFolder + .getSecurityConstraints(); if (constraints == null) { constraints = pageManager.newSecurityConstraints(); @@ -245,32 +243,34 @@ dstFolder.getSecurityConstraints().setOwner(owner); } pageManager.updateFolder(dstFolder); - + Iterator pages = srcFolder.getPages().iterator(); while (pages.hasNext()) { - Page srcPage = (Page)pages.next(); - String path = PageManagerUtils.concatenatePaths(destinationPath, srcPage.getName()); + Page srcPage = (Page) pages.next(); + String path = PageManagerUtils.concatenatePaths(destinationPath, + srcPage.getName()); Page dstPage = pageManager.copyPage(srcPage, path); pageManager.updatePage(dstPage); } - + Iterator links = srcFolder.getLinks().iterator(); while (links.hasNext()) { - Link srcLink = (Link)links.next(); - String path = PageManagerUtils.concatenatePaths(destinationPath, srcLink.getName()); + Link srcLink = (Link) links.next(); + String path = PageManagerUtils.concatenatePaths(destinationPath, + srcLink.getName()); Link dstLink = pageManager.copyLink(srcLink, path); pageManager.updateLink(dstLink); } - + Iterator folders = srcFolder.getFolders().iterator(); while (folders.hasNext()) { - Folder folder = (Folder)folders.next(); - String newPath = concatenatePaths(destinationPath, folder.getName()); + Folder folder = (Folder) folders.next(); + String newPath = concatenatePaths(destinationPath, folder.getName()); deepCopyFolder(pageManager, folder, newPath, null); - } + } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/impl/DocumentImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/impl/DocumentImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/impl/DocumentImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,22 +21,25 @@ /** * DocumentImpl - * + * * @author Randy Watler * @version $Id$ */ public abstract class DocumentImpl extends NodeImpl implements Document { + private String version; - + private boolean dirty = false; - + public DocumentImpl(SecurityConstraintsImpl constraints) { super(constraints); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#getTitle() */ public String getTitle() @@ -51,7 +54,9 @@ return title; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Document#setVersion() */ public String getVersion() @@ -59,20 +64,24 @@ return version; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Document#setVersion(java.lang.String) */ public void setVersion(String version) { this.version = version; } - - public boolean isDirty() { - return dirty; - } - - public void setDirty(boolean dirty) { - this.dirty = dirty; - } + public boolean isDirty() + { + return dirty; + } + + public void setDirty(boolean dirty) + { + this.dirty = dirty; + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/impl/NodeImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/impl/NodeImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/impl/NodeImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,26 +33,39 @@ /** * NodeImpl - * + * * @author Randy Watler * @version $Id$ */ public abstract class NodeImpl extends BaseElementImpl implements Node { + private Node parent; + private boolean hidden; + private Collection metadataFields; + private String path = Folder.PATH_SEPARATOR; + private String subsite; + private String user; + private String role; + private String group; + private String mediatype; + private String locale; + private String extendedAttributeName; + private String extendedAttributeValue; private PageMetadataImpl pageMetadata; + private String logicalPath; public NodeImpl(SecurityConstraintsImpl constraints) @@ -62,10 +75,11 @@ /** * getCanonicalNodePath - * + * * Format paths used to set and query NodeImpl instances. - * - * @param path specified path + * + * @param path + * specified path * @return canonical path */ public static String getCanonicalNodePath(String path) @@ -79,7 +93,8 @@ { path = Folder.PATH_SEPARATOR + path; } - if (path.endsWith(Folder.PATH_SEPARATOR) && !path.equals(Folder.PATH_SEPARATOR)) + if (path.endsWith(Folder.PATH_SEPARATOR) + && !path.equals(Folder.PATH_SEPARATOR)) { path = path.substring(0, path.length() - 1); } @@ -88,10 +103,11 @@ /** * newPageMetadata - * + * * Construct page manager specific metadata implementation. - * - * @param fields mutable fields collection + * + * @param fields + * mutable fields collection * @return page metadata */ public PageMetadataImpl newPageMetadata(Collection fields) @@ -102,9 +118,9 @@ /** * getPageMetadata - * + * * Get page manager specific metadata implementation. - * + * * @return page metadata */ public PageMetadataImpl getPageMetadata() @@ -122,9 +138,9 @@ /** * defaultTitleFromName - * + * * Compute default title from name. - * + * * @return default title */ protected String defaultTitleFromName() @@ -136,7 +152,7 @@ // strip extensions and default root folder name if ((getType() != null) && title.endsWith(getType())) { - title = title.substring(0, title.length()-getType().length()); + title = title.substring(0, title.length() - getType().length()); } else if (title.equals(Folder.PATH_SEPARATOR)) { @@ -149,22 +165,24 @@ int wordIndex = -1; do { - if (!Character.isTitleCase(title.charAt(wordIndex+1))) + if (!Character.isTitleCase(title.charAt(wordIndex + 1))) { StringBuffer makeTitle = new StringBuffer(); - makeTitle.append(title.substring(0, wordIndex+1)); - makeTitle.append(Character.toTitleCase(title.charAt(wordIndex+1))); - makeTitle.append(title.substring(wordIndex+2)); + makeTitle.append(title.substring(0, wordIndex + 1)); + makeTitle.append(Character.toTitleCase(title + .charAt(wordIndex + 1))); + makeTitle.append(title.substring(wordIndex + 2)); title = makeTitle.toString(); } - wordIndex = title.indexOf(' ', wordIndex+1); - } - while (wordIndex != -1); + wordIndex = title.indexOf(' ', wordIndex + 1); + } while (wordIndex != -1); } return title; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#getName() */ public String getName() @@ -177,7 +195,8 @@ { if (!path.equals(Folder.PATH_SEPARATOR)) { - name = path.substring(path.lastIndexOf(Folder.PATH_SEPARATOR) + 1); + name = path.substring(path + .lastIndexOf(Folder.PATH_SEPARATOR) + 1); } else { @@ -189,7 +208,9 @@ return name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#setName(java.lang.String) */ public void setName(String name) @@ -202,7 +223,9 @@ // set path if (!name.equals(Folder.PATH_SEPARATOR)) { - path = path.substring(0, path.lastIndexOf(Folder.PATH_SEPARATOR) + 1) + name; + path = path.substring(0, path + .lastIndexOf(Folder.PATH_SEPARATOR) + 1) + + name; } else { @@ -216,24 +239,29 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#getEffectivePageSecurity() */ public PageSecurity getEffectivePageSecurity() { // by default, delegate to real parent node implementation - NodeImpl parentNodeImpl = (NodeImpl)ProxyHelper.getRealObject(parent); - if (parentNodeImpl != null) - { - return parentNodeImpl.getEffectivePageSecurity(); - } + NodeImpl parentNodeImpl = (NodeImpl) ProxyHelper.getRealObject(parent); + if (parentNodeImpl != null) { return parentNodeImpl + .getEffectivePageSecurity(); } return null; } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#checkConstraints(java.util.List, java.util.List, java.util.List, java.util.List, boolean, boolean) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#checkConstraints(java.util.List, + * java.util.List, java.util.List, java.util.List, boolean, boolean) */ - public void checkConstraints(List actions, List userPrincipals, List rolePrincipals, List groupPrincipals, boolean checkNodeOnly, boolean checkParentsOnly) throws SecurityException + public void checkConstraints(List actions, List userPrincipals, + List rolePrincipals, List groupPrincipals, boolean checkNodeOnly, + boolean checkParentsOnly) throws SecurityException { // check constraints in node hierarchy if (checkNodeOnly) @@ -241,17 +269,22 @@ // check node constraints if available; otherwise, // recursively check parent constraints until // default constraints for node are checked - SecurityConstraintsImpl constraintsImpl = (SecurityConstraintsImpl)getSecurityConstraints(); + SecurityConstraintsImpl constraintsImpl = (SecurityConstraintsImpl) getSecurityConstraints(); if ((constraintsImpl != null) && !constraintsImpl.isEmpty()) { - constraintsImpl.checkConstraints(actions, userPrincipals, rolePrincipals, groupPrincipals, getEffectivePageSecurity()); + constraintsImpl.checkConstraints(actions, userPrincipals, + rolePrincipals, groupPrincipals, + getEffectivePageSecurity()); } else { - NodeImpl parentNodeImpl = (NodeImpl)ProxyHelper.getRealObject(parent); + NodeImpl parentNodeImpl = (NodeImpl) ProxyHelper + .getRealObject(parent); if (parentNodeImpl != null) { - parentNodeImpl.checkConstraints(actions, userPrincipals, rolePrincipals, groupPrincipals, checkNodeOnly, false); + parentNodeImpl.checkConstraints(actions, userPrincipals, + rolePrincipals, groupPrincipals, checkNodeOnly, + false); } } } @@ -261,26 +294,34 @@ // to be skipped due to explicity granted access if (!checkParentsOnly) { - SecurityConstraintsImpl constraintsImpl = (SecurityConstraintsImpl)getSecurityConstraints(); + SecurityConstraintsImpl constraintsImpl = (SecurityConstraintsImpl) getSecurityConstraints(); if ((constraintsImpl != null) && !constraintsImpl.isEmpty()) { - constraintsImpl.checkConstraints(actions, userPrincipals, rolePrincipals, groupPrincipals, getEffectivePageSecurity()); + constraintsImpl.checkConstraints(actions, userPrincipals, + rolePrincipals, groupPrincipals, + getEffectivePageSecurity()); } } // recursively check all parent constraints in hierarchy - NodeImpl parentNodeImpl = (NodeImpl)ProxyHelper.getRealObject(parent); + NodeImpl parentNodeImpl = (NodeImpl) ProxyHelper + .getRealObject(parent); if (parentNodeImpl != null) { - parentNodeImpl.checkConstraints(actions, userPrincipals, rolePrincipals, groupPrincipals, false, false); + parentNodeImpl.checkConstraints(actions, userPrincipals, + rolePrincipals, groupPrincipals, false, false); } } } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#checkPermissions(java.lang.String, int, boolean, boolean) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#checkPermissions(java.lang.String, + * int, boolean, boolean) */ - public void checkPermissions(String path, int mask, boolean checkNodeOnly, boolean checkParentsOnly) throws SecurityException + public void checkPermissions(String path, int mask, boolean checkNodeOnly, + boolean checkParentsOnly) throws SecurityException { // check granted node permissions unless the check is // to be skipped due to explicity granted access @@ -288,12 +329,13 @@ { super.checkPermissions(path, mask, true, false); } - + // if not checking node only, recursively check // all parent permissions in hierarchy if (!checkNodeOnly) { - NodeImpl parentNodeImpl = (NodeImpl)ProxyHelper.getRealObject(parent); + NodeImpl parentNodeImpl = (NodeImpl) ProxyHelper + .getRealObject(parent); if (parentNodeImpl != null) { parentNodeImpl.checkPermissions(mask, false, false); @@ -301,7 +343,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#getLogicalPermissionPath() */ public String getLogicalPermissionPath() @@ -310,22 +354,27 @@ if (logicalPath == null) { // check for path attributes - if ((subsite != null) || (user != null) || (role != null) || (group != null) || (mediatype != null) || - (locale != null) || (extendedAttributeName != null) || (extendedAttributeValue != null)) + if ((subsite != null) || (user != null) || (role != null) + || (group != null) || (mediatype != null) + || (locale != null) || (extendedAttributeName != null) + || (extendedAttributeValue != null)) { // parse path, stripping reserved folders from path boolean skipAttribute = false; StringBuffer logicalPathBuffer = new StringBuffer(); - StringTokenizer pathElements = new StringTokenizer(path, Folder.PATH_SEPARATOR); + StringTokenizer pathElements = new StringTokenizer(path, + Folder.PATH_SEPARATOR); while (pathElements.hasMoreTokens()) { // classify path element String pathElement = pathElements.nextToken(); if (!skipAttribute) { - if (!pathElement.startsWith(Folder.RESERVED_SUBSITE_FOLDER_PREFIX)) + if (!pathElement + .startsWith(Folder.RESERVED_SUBSITE_FOLDER_PREFIX)) { - if (!pathElement.startsWith(Folder.RESERVED_FOLDER_PREFIX)) + if (!pathElement + .startsWith(Folder.RESERVED_FOLDER_PREFIX)) { // append to logical path logicalPathBuffer.append(Folder.PATH_SEPARATOR); @@ -344,7 +393,7 @@ skipAttribute = false; } } - + // set logical path if (logicalPathBuffer.length() > 0) { @@ -365,7 +414,9 @@ return logicalPath; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.impl.BaseElementImpl#getPhysicalPermissionPath() */ public String getPhysicalPermissionPath() @@ -374,15 +425,19 @@ return path; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getParent() */ public Node getParent() { return parent; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#setParent(org.apache.jetspeed.page.document.Node) */ public void setParent(Node parent) @@ -394,10 +449,11 @@ if (parent != null) { String parentPath = parent.getPath(); - if ((parentPath.equals(Folder.PATH_SEPARATOR) && - (path.lastIndexOf(Folder.PATH_SEPARATOR) > 0)) || - (!parentPath.equals(Folder.PATH_SEPARATOR) && - !parentPath.equals(path.substring(0, path.lastIndexOf(Folder.PATH_SEPARATOR))))) + if ((parentPath.equals(Folder.PATH_SEPARATOR) && (path + .lastIndexOf(Folder.PATH_SEPARATOR) > 0)) + || (!parentPath.equals(Folder.PATH_SEPARATOR) && !parentPath + .equals(path.substring(0, path + .lastIndexOf(Folder.PATH_SEPARATOR))))) { // set path path = parentPath + Folder.PATH_SEPARATOR + getName(); @@ -408,7 +464,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getPath() */ public String getPath() @@ -416,8 +474,10 @@ // return path from attributes and base path return path; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#setPath(java.lang.String) */ public void setPath(String path) @@ -430,7 +490,8 @@ // parse and set informational attributes from path String attributeName = null; - StringTokenizer pathElements = new StringTokenizer(this.path, Folder.PATH_SEPARATOR); + StringTokenizer pathElements = new StringTokenizer(this.path, + Folder.PATH_SEPARATOR); while (pathElements.hasMoreTokens()) { String pathElement = pathElements.nextToken(); @@ -441,19 +502,23 @@ { user = pathElement.toLowerCase(); } - else if (attributeName.startsWith(Folder.RESERVED_ROLE_FOLDER_NAME)) + else if (attributeName + .startsWith(Folder.RESERVED_ROLE_FOLDER_NAME)) { role = pathElement.toLowerCase(); } - else if (attributeName.startsWith(Folder.RESERVED_GROUP_FOLDER_NAME)) + else if (attributeName + .startsWith(Folder.RESERVED_GROUP_FOLDER_NAME)) { group = pathElement.toLowerCase(); } - else if (attributeName.startsWith(Folder.RESERVED_MEDIATYPE_FOLDER_NAME)) + else if (attributeName + .startsWith(Folder.RESERVED_MEDIATYPE_FOLDER_NAME)) { mediatype = pathElement.toLowerCase(); } - else if (attributeName.startsWith(Folder.RESERVED_LANGUAGE_FOLDER_NAME)) + else if (attributeName + .startsWith(Folder.RESERVED_LANGUAGE_FOLDER_NAME)) { if (locale != null) { @@ -465,30 +530,36 @@ locale = pathElement.toLowerCase(); } } - else if (attributeName.startsWith(Folder.RESERVED_COUNTRY_FOLDER_NAME)) + else if (attributeName + .startsWith(Folder.RESERVED_COUNTRY_FOLDER_NAME)) { if (locale != null) { // compose locale from language + country - locale = locale + "_" + pathElement.toLowerCase() ; + locale = locale + "_" + pathElement.toLowerCase(); } else { locale = pathElement.toLowerCase(); } } - else if (attributeName.startsWith(Folder.RESERVED_FOLDER_PREFIX)) + else if (attributeName + .startsWith(Folder.RESERVED_FOLDER_PREFIX)) { - extendedAttributeName = attributeName.substring(Folder.RESERVED_FOLDER_PREFIX.length()); + extendedAttributeName = attributeName + .substring(Folder.RESERVED_FOLDER_PREFIX.length()); extendedAttributeValue = pathElement.toLowerCase(); } // reset attribute name attributeName = null; } - else if (pathElement.startsWith(Folder.RESERVED_SUBSITE_FOLDER_PREFIX)) + else if (pathElement + .startsWith(Folder.RESERVED_SUBSITE_FOLDER_PREFIX)) { - subsite = pathElement.substring(Folder.RESERVED_SUBSITE_FOLDER_PREFIX.length()).toLowerCase(); + subsite = pathElement.substring( + Folder.RESERVED_SUBSITE_FOLDER_PREFIX.length()) + .toLowerCase(); } else if (pathElement.startsWith(Folder.RESERVED_FOLDER_PREFIX)) { @@ -500,7 +571,8 @@ // set name based on path if (!this.path.equals(Folder.PATH_SEPARATOR)) { - super.setName(this.path.substring(this.path.lastIndexOf(Folder.PATH_SEPARATOR) + 1)); + super.setName(this.path.substring(this.path + .lastIndexOf(Folder.PATH_SEPARATOR) + 1)); } else { @@ -511,25 +583,30 @@ if (parent != null) { String parentPath = parent.getPath(); - if ((parentPath.equals(Folder.PATH_SEPARATOR) && - (this.path.lastIndexOf(Folder.PATH_SEPARATOR) > 0)) || - (!parentPath.equals(Folder.PATH_SEPARATOR) && - !parentPath.equals(this.path.substring(0, this.path.lastIndexOf(Folder.PATH_SEPARATOR))))) + if ((parentPath.equals(Folder.PATH_SEPARATOR) && (this.path + .lastIndexOf(Folder.PATH_SEPARATOR) > 0)) + || (!parentPath.equals(Folder.PATH_SEPARATOR) && !parentPath + .equals(this.path.substring(0, this.path + .lastIndexOf(Folder.PATH_SEPARATOR))))) { parent = null; } } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getMetadata() */ public GenericMetadata getMetadata() { return getPageMetadata(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getTitle(java.util.Locale) */ public String getTitle(Locale locale) @@ -542,8 +619,10 @@ } return title; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getShortTitle(java.util.Locale) */ public String getShortTitle(Locale locale) @@ -565,33 +644,41 @@ } return shortTitle; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getType() */ public abstract String getType(); - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#getUrl() */ public String getUrl() { return path; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#isHidden() */ public boolean isHidden() { return hidden; - } + } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.Node#setHidden(boolean) */ public void setHidden(boolean hidden) { this.hidden = hidden; - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/impl/NodeSetImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/impl/NodeSetImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/impl/NodeSetImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,31 +29,33 @@ /** * NodeSetImpl - * + * * @author Randy Watler * @version $Id$ */ public class NodeSetImpl implements NodeSet { + public static final NodeSetImpl EMPTY_NODE_SET = new NodeSetImpl(); private static final Map patternCache = new LRUMap(128); private Map nodes; + private Comparator comparator; public NodeSetImpl(List nodes, Comparator comparator) { - this.nodes = new TreeMap(comparator); + this.nodes = new TreeMap(comparator); Object[] nodeToCopy = nodes.toArray(); for (int ix = 0; ix < nodeToCopy.length; ix++) { - Node node = (Node)nodeToCopy[ix]; - if (!this.nodes.containsKey( node.getName())) + Node node = (Node) nodeToCopy[ix]; + if (!this.nodes.containsKey(node.getName())) { this.nodes.put(node.getName(), node); } - } + } this.comparator = comparator; } @@ -69,7 +71,9 @@ public NodeSetImpl(NodeSet nodeSet) { - this((nodeSet instanceof NodeSetImpl) ? ((NodeSetImpl)nodeSet).comparator : (Comparator)null); + this( + (nodeSet instanceof NodeSetImpl) ? ((NodeSetImpl) nodeSet).comparator + : (Comparator) null); } public NodeSetImpl() @@ -78,8 +82,9 @@ /** * getCachedPattern - * - * @param regex pattern + * + * @param regex + * pattern * @return cached pattern */ private Pattern getCachedPattern(String regex) @@ -88,7 +93,7 @@ { if (patternCache.containsKey(regex)) { - return (Pattern)patternCache.get(regex); + return (Pattern) patternCache.get(regex); } else { @@ -99,7 +104,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.NodeSet#add(org.apache.jetspeed.page.document.Node) */ public void add(Node node) @@ -113,20 +120,21 @@ nodes.put(node.getName(), node); } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.NodeSet#get(java.lang.String) */ public Node get(String name) { - if (nodes != null) - { - return (Node)nodes.get(name); - } + if (nodes != null) { return (Node) nodes.get(name); } return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.NodeSet#iterator() */ public Iterator iterator() @@ -137,8 +145,10 @@ } return nodes.values().iterator(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.NodeSet#subset(java.lang.String) */ public NodeSet subset(String type) @@ -155,8 +165,10 @@ } return subset; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.NodeSet#inclusiveSubset(java.lang.String) */ public NodeSet inclusiveSubset(String regex) @@ -174,8 +186,10 @@ } return subset; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.NodeSet#exclusiveSubset(java.lang.String) */ public NodeSet exclusiveSubset(String regex) @@ -193,40 +207,37 @@ } return subset; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.NodeSet#size() */ public int size() { - if (nodes != null) - { - return nodes.size(); - } + if (nodes != null) { return nodes.size(); } return 0; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.NodeSet#contains(org.apache.jetspeed.page.document.Node) */ public boolean contains(Node node) { - if (nodes != null) - { - return nodes.containsValue(node); - } + if (nodes != null) { return nodes.containsValue(node); } return false; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.document.NodeSet#isEmpty() */ public boolean isEmpty() { - if (nodes != null) - { - return nodes.isEmpty(); - } + if (nodes != null) { return nodes.isEmpty(); } return true; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/AbstractNode.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/AbstractNode.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/AbstractNode.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,7 +29,6 @@ import org.apache.jetspeed.om.page.psml.SecurityConstraintsImpl; import org.apache.jetspeed.page.document.Node; - /** *

        * AbstractNode @@ -40,25 +39,32 @@ * * @author Scott T. Weaver * @version $Id: AbstractNode.java 551606 2007-06-28 16:07:53Z taylor $ - * + * */ public abstract class AbstractNode extends AbstractBaseElement implements Node { + private PageMetadataImpl metadata; + private Node parent; + private String path; + private String url; - private boolean hidden=false; + + private boolean hidden = false; + private String profiledPath; - private boolean dirty=false; - + + private boolean dirty = false; + public AbstractNode() { } /** * getMetadata - get/construct metadata - * + * * @return metadata */ public GenericMetadata getMetadata() @@ -68,8 +74,9 @@ /** * setMetadata - set metadata fields - * - * @param metadata metadata + * + * @param metadata + * metadata */ public void setMetadata(GenericMetadata metadata) { @@ -78,8 +85,8 @@ /** * getMetadataFields - get metadata fields collection for - * marshalling/unmarshalling - * + * marshalling/unmarshalling + * * @return metadata fields collection */ public Collection getMetadataFields() @@ -91,8 +98,9 @@ /** * setMetadataFields - set metadata fields collection - * - * @param metadataFields metadata fields collection + * + * @param metadataFields + * metadata fields collection */ public void setMetadataFields(Collection metadataFields) { @@ -104,7 +112,7 @@ /** * getPageMetadata - get/construct page metadata instance - * + * * @return metadata instance */ private PageMetadataImpl getPageMetadata() @@ -145,7 +153,7 @@ * @param locale * @return short title in specified locale */ - public String getShortTitle( Locale locale ) + public String getShortTitle(Locale locale) { // get short title from metadata or use title from metadata, // default short title, or default title @@ -170,7 +178,8 @@ * getParent *

        * - * @param checkAccess flag + * @param checkAccess + * flag * @return parent node */ public Node getParent(boolean checkAccess) @@ -209,7 +218,7 @@ * @see org.apache.jetspeed.page.document.Node#setParent(Node) * @param parent */ - public void setParent( Node parent ) + public void setParent(Node parent) { this.parent = parent; } @@ -218,7 +227,7 @@ *

        * getName *

        - * + * * @see org.apache.jetspeed.page.document.Node#getName() * @return Name */ @@ -230,16 +239,16 @@ { if (name.endsWith(PATH_SEPARATOR)) { - name = name.substring(0, name.length()-1); + name = name.substring(0, name.length() - 1); } - name = name.substring(name.lastIndexOf(PATH_SEPARATOR)+1); + name = name.substring(name.lastIndexOf(PATH_SEPARATOR) + 1); } return name; } /** * getTitleName - get name for use as default titles - * + * * @return title name */ public String getTitleName() @@ -250,7 +259,8 @@ // transform file system name to title if (titleName.endsWith(getType())) { - titleName = titleName.substring(0, titleName.length()-getType().length()); + titleName = titleName.substring(0, titleName.length() + - getType().length()); } else if (titleName.equals(PATH_SEPARATOR)) { @@ -261,17 +271,17 @@ int wordIndex = -1; do { - if (!Character.isTitleCase(titleName.charAt(wordIndex+1))) + if (!Character.isTitleCase(titleName.charAt(wordIndex + 1))) { StringBuffer makeTitle = new StringBuffer(); - makeTitle.append(titleName.substring(0, wordIndex+1)); - makeTitle.append(Character.toTitleCase(titleName.charAt(wordIndex+1))); - makeTitle.append(titleName.substring(wordIndex+2)); + makeTitle.append(titleName.substring(0, wordIndex + 1)); + makeTitle.append(Character.toTitleCase(titleName + .charAt(wordIndex + 1))); + makeTitle.append(titleName.substring(wordIndex + 2)); titleName = makeTitle.toString(); } - wordIndex = titleName.indexOf(' ', wordIndex+1); - } - while (wordIndex != -1); + wordIndex = titleName.indexOf(' ', wordIndex + 1); + } while (wordIndex != -1); } return titleName; } @@ -283,15 +293,16 @@ { return path; } - + /** *

        * setPath *

        - * - * @param path The path to set. + * + * @param path + * The path to set. */ - public void setPath( String path ) + public void setPath(String path) { // PSML id is always kept in sync with path, despite how the // id may be loaded from the persistent store @@ -304,16 +315,13 @@ * getUrl *

        * Same as invoking Node.getPath() unless url explicitly set. - * + * * @see org.apache.jetspeed.page.document.Node#getUrl() * @return url as string */ public String getUrl() { - if (url != null) - { - return url; - } + if (url != null) { return url; } return getPath(); } @@ -321,10 +329,11 @@ *

        * setUrl *

        - * - * @param url The url to set. + * + * @param url + * The url to set. */ - public void setUrl( String url ) + public void setUrl(String url) { this.url = url; } @@ -333,7 +342,7 @@ *

        * isHidden *

        - * + * * @see org.apache.jetspeed.page.document.Node#isHidden() * @return hidden */ @@ -341,10 +350,12 @@ { return hidden; } + /** - * @param hidden The hidden to set. + * @param hidden + * The hidden to set. */ - public void setHidden( boolean hidden ) + public void setHidden(boolean hidden) { this.hidden = hidden; } @@ -356,26 +367,26 @@ { return profiledPath; } + /** - * @param profiledPath The profiled path to set. + * @param profiledPath + * The profiled path to set. */ - public void setProfiledPath( String profiledPath ) + public void setProfiledPath(String profiledPath) { this.profiledPath = profiledPath; } /** * getEffectivePageSecurity - * + * * @see org.apache.jetspeed.om.page.psml.AbstractBaseElement#getEffectivePageSecurity() */ public PageSecurity getEffectivePageSecurity() { // by default, delegate to parent node implementation - if (parent != null) - { - return ((AbstractNode)parent).getEffectivePageSecurity(); - } + if (parent != null) { return ((AbstractNode) parent) + .getEffectivePageSecurity(); } return null; } @@ -383,7 +394,7 @@ *

        * checkConstraints *

        - * + * * @param actions * @param userPrincipals * @param rolePrincipals @@ -392,7 +403,9 @@ * @param checkParentsOnly * @throws SecurityException */ - public void checkConstraints(List actions, List userPrincipals, List rolePrincipals, List groupPrincipals, boolean checkNodeOnly, boolean checkParentsOnly) throws SecurityException + public void checkConstraints(List actions, List userPrincipals, + List rolePrincipals, List groupPrincipals, boolean checkNodeOnly, + boolean checkParentsOnly) throws SecurityException { // check constraints in node hierarchy if (checkNodeOnly) @@ -403,11 +416,15 @@ SecurityConstraints constraints = getSecurityConstraints(); if ((constraints != null) && !constraints.isEmpty()) { - ((SecurityConstraintsImpl)constraints).checkConstraints(actions, userPrincipals, rolePrincipals, groupPrincipals, getEffectivePageSecurity()); + ((SecurityConstraintsImpl) constraints).checkConstraints( + actions, userPrincipals, rolePrincipals, + groupPrincipals, getEffectivePageSecurity()); } else if (parent != null) { - ((AbstractNode)parent).checkConstraints(actions, userPrincipals, rolePrincipals, groupPrincipals, checkNodeOnly, false); + ((AbstractNode) parent).checkConstraints(actions, + userPrincipals, rolePrincipals, groupPrincipals, + checkNodeOnly, false); } } else @@ -419,14 +436,18 @@ SecurityConstraints constraints = getSecurityConstraints(); if ((constraints != null) && !constraints.isEmpty()) { - ((SecurityConstraintsImpl)constraints).checkConstraints(actions, userPrincipals, rolePrincipals, groupPrincipals, getEffectivePageSecurity()); + ((SecurityConstraintsImpl) constraints).checkConstraints( + actions, userPrincipals, rolePrincipals, + groupPrincipals, getEffectivePageSecurity()); } } // recursively check all parent constraints in hierarchy if (parent != null) { - ((AbstractNode)parent).checkConstraints(actions, userPrincipals, rolePrincipals, groupPrincipals, false, false); + ((AbstractNode) parent).checkConstraints(actions, + userPrincipals, rolePrincipals, groupPrincipals, false, + false); } } } @@ -435,14 +456,16 @@ *

        * checkPermissions *

        - * + * * @param path - * @param mask Mask of actions requested + * @param mask + * Mask of actions requested * @param checkNodeOnly * @param checkParentsOnly * @throws SecurityException */ - public void checkPermissions(String path, int mask, boolean checkNodeOnly, boolean checkParentsOnly) throws SecurityException + public void checkPermissions(String path, int mask, boolean checkNodeOnly, + boolean checkParentsOnly) throws SecurityException { // check granted node permissions unless the check is // to be skipped due to explicity granted access @@ -450,12 +473,12 @@ { super.checkPermissions(path, mask, true, false); } - + // if not checking node only, recursively check // all parent permissions in hierarchy if (!checkNodeOnly && (parent != null)) { - ((AbstractNode)parent).checkPermissions(mask, false, false); + ((AbstractNode) parent).checkPermissions(mask, false, false); } } @@ -463,7 +486,7 @@ *

        * getLogicalPermissionPath *

        - * + * * @return path used for permissions checks */ public String getLogicalPermissionPath() @@ -475,7 +498,7 @@ *

        * getPhysicalPermissionPath *

        - * + * * @return path used for permissions checks */ public String getPhysicalPermissionPath() @@ -484,8 +507,8 @@ } /** - * unmarshalled - notification that this instance has been - * loaded from the persistent store + * unmarshalled - notification that this instance has been loaded from the + * persistent store */ public void unmarshalled() { @@ -502,13 +525,14 @@ } } - public boolean isDirty() { - return dirty; - } + public boolean isDirty() + { + return dirty; + } - public void setDirty(boolean dirty) { - this.dirty=dirty; - } - - + public void setDirty(boolean dirty) + { + this.dirty = dirty; + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/CastorFileSystemDocumentHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/CastorFileSystemDocumentHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/CastorFileSystemDocumentHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -78,24 +78,36 @@ *

        * * @author Scott T. Weaver - * @version $Id: CastorFileSystemDocumentHandler.java 568113 2007-08-21 13:04:07Z woonsan $ - * + * @version $Id: CastorFileSystemDocumentHandler.java 568113 2007-08-21 + * 13:04:07Z woonsan $ + * */ -public class CastorFileSystemDocumentHandler implements org.apache.jetspeed.page.document.DocumentHandler, FileCacheEventListener +public class CastorFileSystemDocumentHandler implements + org.apache.jetspeed.page.document.DocumentHandler, + FileCacheEventListener { - private final static Log log = LogFactory.getLog(CastorFileSystemDocumentHandler.class); + private final static Log log = LogFactory + .getLog(CastorFileSystemDocumentHandler.class); + private final static String PSML_DOCUMENT_ENCODING = "UTF-8"; protected String documentType; + protected Class expectedReturnType; + protected String documentRoot; + protected File documentRootDir; + protected FileCache fileCache; - + private OutputFormat format; + private final XMLReader xmlReader; + private DocumentHandlerFactory handlerFactory; + private ClassDescriptorResolver classDescriptorResolver; /** @@ -107,8 +119,10 @@ * @param expectedReturnType * @throws FileNotFoundException */ - public CastorFileSystemDocumentHandler( String mappingFile, String documentType, Class expectedReturnType, - String documentRoot, FileCache fileCache ) throws FileNotFoundException,SAXException,ParserConfigurationException, MappingException + public CastorFileSystemDocumentHandler(String mappingFile, + String documentType, Class expectedReturnType, String documentRoot, + FileCache fileCache) throws FileNotFoundException, SAXException, + ParserConfigurationException, MappingException { super(); this.documentType = documentType; @@ -122,24 +136,28 @@ format.setIndenting(true); format.setIndent(4); format.setEncoding(PSML_DOCUMENT_ENCODING); - + SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); - + xmlReader = parser.getXMLReader(); xmlReader.setFeature("http://xml.org/sax/features/namespaces", false); - + /* - * Create ClassDescripterResolver for better performance. - * Mentioned as 'best practice' on the Castor website. + * Create ClassDescripterResolver for better performance. Mentioned as + * 'best practice' on the Castor website. */ createCastorClassDescriptorResolver(mappingFile); } - - public CastorFileSystemDocumentHandler( String mappingFile, String documentType, String expectedReturnType, - String documentRoot, FileCache fileCache ) throws FileNotFoundException, ClassNotFoundException,SAXException,ParserConfigurationException, MappingException + + public CastorFileSystemDocumentHandler(String mappingFile, + String documentType, String expectedReturnType, + String documentRoot, FileCache fileCache) + throws FileNotFoundException, ClassNotFoundException, SAXException, + ParserConfigurationException, MappingException { - this(mappingFile, documentType, Class.forName(expectedReturnType), documentRoot, fileCache); + this(mappingFile, documentType, Class.forName(expectedReturnType), + documentRoot, fileCache); } /** @@ -149,21 +167,23 @@ * * @see org.apache.jetspeed.page.document.DocumentHandler#getDocument(java.lang.String) * @param name - * @return @throws - * DocumentNotFoundException + * @return + * @throws DocumentNotFoundException * @throws DocumentException, * DocumentNotFoundException */ - public Document getDocument( String name ) throws NodeException, DocumentNotFoundException + public Document getDocument(String name) throws NodeException, + DocumentNotFoundException { return getDocument(name, true); } - - public void updateDocument( Document document ) throws FailedToUpdateDocumentException + + public void updateDocument(Document document) + throws FailedToUpdateDocumentException { - updateDocument(document, false); + updateDocument(document, false); } - + /** *

        * updateDocument @@ -171,9 +191,10 @@ * * @see org.apache.jetspeed.page.document.DocumentHandler#updateDocument(org.apache.jetspeed.om.page.Document) * @param document - * @param systemUpdate + * @param systemUpdate */ - protected void updateDocument( Document document, boolean systemUpdate) throws FailedToUpdateDocumentException + protected void updateDocument(Document document, boolean systemUpdate) + throws FailedToUpdateDocumentException { // sanity checks if (document == null) @@ -192,20 +213,25 @@ } document.setPath(path); } - AbstractBaseElement documentImpl = (AbstractBaseElement)document; + AbstractBaseElement documentImpl = (AbstractBaseElement) document; documentImpl.setHandlerFactory(handlerFactory); - if (systemUpdate){ - // on system update: temporarily turn off security + if (systemUpdate) + { + // on system update: temporarily turn off security documentImpl.setPermissionsEnabled(false); documentImpl.setConstraintsEnabled(false); - } else { - documentImpl.setPermissionsEnabled(handlerFactory.getPermissionsEnabled()); - documentImpl.setConstraintsEnabled(handlerFactory.getConstraintsEnabled()); } + else + { + documentImpl.setPermissionsEnabled(handlerFactory + .getPermissionsEnabled()); + documentImpl.setConstraintsEnabled(handlerFactory + .getConstraintsEnabled()); + } documentImpl.marshalling(); - + // marshal page to disk - String fileName = path; + String fileName = path; if (!fileName.endsWith(this.documentType)) { fileName = path + this.documentType; @@ -218,85 +244,100 @@ // marshal: use SAX II handler to filter document XML for // page and folder menu definition menu elements ordered // polymorphic collection to strip artifical - // tags enabling Castor XML binding; see JETSPEED-INF/castor/page-mapping.xml - writer = new OutputStreamWriter(new FileOutputStream(f), PSML_DOCUMENT_ENCODING); + // tags enabling Castor XML binding; see + // JETSPEED-INF/castor/page-mapping.xml + writer = new OutputStreamWriter(new FileOutputStream(f), + PSML_DOCUMENT_ENCODING); Serializer serializer = new XMLSerializer(writer, this.format); final ContentHandler handler = serializer.asContentHandler(); - + Marshaller marshaller = new Marshaller(new ContentHandler() + { + + private int menuDepth = 0; + + public void characters(char[] ch, int start, int length) + throws SAXException { - private int menuDepth = 0; - - public void characters(char[] ch, int start, int length) throws SAXException + handler.characters(ch, start, length); + } + + public void endDocument() throws SAXException + { + handler.endDocument(); + } + + public void ignorableWhitespace(char[] ch, int start, int length) + throws SAXException + { + handler.ignorableWhitespace(ch, start, length); + } + + public void processingInstruction(String target, String data) + throws SAXException + { + handler.processingInstruction(target, data); + } + + public void setDocumentLocator(Locator locator) + { + handler.setDocumentLocator(locator); + } + + public void startDocument() throws SAXException + { + handler.startDocument(); + } + + public void endElement(String uri, String localName, + String qName) throws SAXException + { + // track menu depth + if (qName.equals("menu")) { - handler.characters(ch, start, length); + menuDepth--; } - public void endDocument() throws SAXException + // filter menu-element noded within menu definition + if ((menuDepth == 0) || !qName.equals("menu-element")) { - handler.endDocument(); + handler.endElement(uri, localName, qName); } - - public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException + } + + public void endPrefixMapping(String prefix) throws SAXException + { + } + + public void skippedEntity(String name) throws SAXException + { + handler.skippedEntity(name); + } + + public void startElement(String uri, String localName, + String qName, Attributes atts) throws SAXException + { + // filter menu-element noded within menu definition + if ((menuDepth == 0) || !qName.equals("menu-element")) { - handler.ignorableWhitespace(ch, start, length); + handler.startElement(uri, localName, qName, atts); } - - public void processingInstruction(String target, String data) throws SAXException + + // track menu depth + if (qName.equals("menu")) { - handler.processingInstruction(target, data); + menuDepth++; } - - public void setDocumentLocator(Locator locator) - { - handler.setDocumentLocator(locator); - } - - public void startDocument() throws SAXException - { - handler.startDocument(); - } - - public void endElement(String uri, String localName, String qName) throws SAXException { - // track menu depth - if (qName.equals("menu")) - { - menuDepth--; - } + } - // filter menu-element noded within menu definition - if ((menuDepth == 0) || !qName.equals("menu-element")) - { - handler.endElement(uri, localName, qName); - } - } + public void startPrefixMapping(String prefix, String uri) + throws SAXException + { + } + }); + marshaller + .setResolver((XMLClassDescriptorResolver) classDescriptorResolver); - public void endPrefixMapping(String prefix) throws SAXException { - } - - public void skippedEntity(String name) throws SAXException { - handler.skippedEntity(name); - } - - public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { - // filter menu-element noded within menu definition - if ((menuDepth == 0) || !qName.equals("menu-element")) - { - handler.startElement(uri,localName, qName, atts); - } - - // track menu depth - if (qName.equals("menu")) - { - menuDepth++; - } - } - - public void startPrefixMapping(String prefix, String uri) throws SAXException { - } - }); - marshaller.setResolver((XMLClassDescriptorResolver) classDescriptorResolver); - marshaller.setValidation(false); // results in better performance marshaller.marshal(document); } @@ -322,12 +363,15 @@ } finally { - if (systemUpdate){ - // restore permissions / constraints - documentImpl.setPermissionsEnabled(handlerFactory.getPermissionsEnabled()); - documentImpl.setConstraintsEnabled(handlerFactory.getConstraintsEnabled()); + if (systemUpdate) + { + // restore permissions / constraints + documentImpl.setPermissionsEnabled(handlerFactory + .getPermissionsEnabled()); + documentImpl.setConstraintsEnabled(handlerFactory + .getConstraintsEnabled()); } - try + try { writer.close(); } @@ -338,10 +382,11 @@ } - protected void createCastorClassDescriptorResolver(String mappingFile) throws MappingException + protected void createCastorClassDescriptorResolver(String mappingFile) + throws MappingException { - Mapping mapping=null; - try + Mapping mapping = null; + try { InputStream stream = getClass().getResourceAsStream(mappingFile); @@ -359,18 +404,21 @@ } catch (Exception e) { - IllegalStateException ise = new IllegalStateException("Error in psml mapping creation"); + IllegalStateException ise = new IllegalStateException( + "Error in psml mapping creation"); ise.initCause(e); throw ise; } - this.classDescriptorResolver = - ClassDescriptorResolverFactory.createClassDescriptorResolver(BindingType.XML); - MappingUnmarshaller mappingUnmarshaller = new MappingUnmarshaller(); - MappingLoader mappingLoader = mappingUnmarshaller.getMappingLoader(mapping, BindingType.XML); - classDescriptorResolver.setMappingLoader(mappingLoader); + this.classDescriptorResolver = ClassDescriptorResolverFactory + .createClassDescriptorResolver(BindingType.XML); + MappingUnmarshaller mappingUnmarshaller = new MappingUnmarshaller(); + MappingLoader mappingLoader = mappingUnmarshaller.getMappingLoader( + mapping, BindingType.XML); + classDescriptorResolver.setMappingLoader(mappingLoader); } - protected Object unmarshallDocument( Class clazz, String path, String extension ) throws DocumentNotFoundException, + protected Object unmarshallDocument(Class clazz, String path, + String extension) throws DocumentNotFoundException, DocumentException { Document document = null; @@ -384,161 +432,233 @@ f = new File(this.documentRootDir, path + extension); } - if (!f.exists()) - { - throw new PageNotFoundException("Document not found: " + path); - } + if (!f.exists()) { throw new PageNotFoundException( + "Document not found: " + path); } try { // unmarshal: use SAX II parser to read document XML, filtering // for page and folder menu definition menu elements ordered // polymorphic collection to insert artifical - // tags enabling Castor XML binding; see JETSPEED-INF/castor/page-mapping.xml - - final InputSource readerInput = new InputSource(new InputStreamReader(new FileInputStream(f), PSML_DOCUMENT_ENCODING)); + // tags enabling Castor XML binding; see + // JETSPEED-INF/castor/page-mapping.xml + + final InputSource readerInput = new InputSource( + new InputStreamReader(new FileInputStream(f), + PSML_DOCUMENT_ENCODING)); Unmarshaller unmarshaller = new Unmarshaller(); - unmarshaller.setResolver((XMLClassDescriptorResolver) classDescriptorResolver); + unmarshaller + .setResolver((XMLClassDescriptorResolver) classDescriptorResolver); unmarshaller.setValidation(false); // results in better performance - + synchronized (xmlReader) { - document = (Document) unmarshaller.unmarshal(new SAX2EventProducer() - { - public void setContentHandler(final ContentHandler handler) + document = (Document) unmarshaller + .unmarshal(new SAX2EventProducer() { - xmlReader.setContentHandler(new ContentHandler() - { - private int menuDepth = 0; - public void characters(char[] ch, int start, int length) throws SAXException - { - handler.characters(ch, start, length); - } + public void setContentHandler( + final ContentHandler handler) + { + xmlReader + .setContentHandler(new ContentHandler() + { - public void endDocument() throws SAXException - { - handler.endDocument(); - } + private int menuDepth = 0; - public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException - { - handler.ignorableWhitespace(ch, start, length); - } + public void characters(char[] ch, + int start, int length) + throws SAXException + { + handler.characters(ch, start, + length); + } - public void processingInstruction(String target, String data) throws SAXException - { - handler.processingInstruction(target, data); - } + public void endDocument() + throws SAXException + { + handler.endDocument(); + } - public void setDocumentLocator(Locator locator) - { - handler.setDocumentLocator(locator); - } + public void ignorableWhitespace( + char[] ch, int start, + int length) + throws SAXException + { + handler.ignorableWhitespace(ch, + start, length); + } - public void startDocument() throws SAXException - { - handler.startDocument(); - } + public void processingInstruction( + String target, String data) + throws SAXException + { + handler.processingInstruction( + target, data); + } - public void endElement(String uri, String localName, String qName) throws SAXException { - // always include all elements - handler.endElement(uri,localName,qName); - // track menu depth and insert menu-element nodes - // to encapsulate menu elements to support collection - // polymorphism in Castor - if (qName.equals("menu")) - { - menuDepth--; - if (menuDepth > 0) + public void setDocumentLocator( + Locator locator) { - handler.endElement(null,null,"menu-element"); + handler + .setDocumentLocator(locator); } - } - else if ((menuDepth > 0) && - (qName.equals("options") || qName.equals("separator") || - qName.equals("include") || qName.equals("exclude"))) - { - handler.endElement(null,null,"menu-element"); - } - } - public void endPrefixMapping(String prefix) throws SAXException { - } + public void startDocument() + throws SAXException + { + handler.startDocument(); + } - public void skippedEntity(String name) throws SAXException { - handler.skippedEntity(name); - } + public void endElement(String uri, + String localName, + String qName) + throws SAXException + { + // always include all elements + handler.endElement(uri, + localName, qName); + // track menu depth and insert + // menu-element nodes + // to encapsulate menu elements + // to support collection + // polymorphism in Castor + if (qName.equals("menu")) + { + menuDepth--; + if (menuDepth > 0) + { + handler.endElement( + null, null, + "menu-element"); + } + } + else if ((menuDepth > 0) + && (qName + .equals("options") + || qName + .equals("separator") + || qName + .equals("include") || qName + .equals("exclude"))) + { + handler.endElement(null, + null, + "menu-element"); + } + } - public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { - // track menu depth and insert menu-element nodes - // to encapsulate menu elements to support collection - // polymorphism in Castor - - if (qName.equals("menu")) - { - if (menuDepth > 0) + public void endPrefixMapping( + String prefix) + throws SAXException { - handler.startElement(null,null,"menu-element", null); } - menuDepth++; - } - else if ((menuDepth > 0) && - (qName.equals("options") || qName.equals("separator") || - qName.equals("include") || qName.equals("exclude"))) - { - handler.startElement(null,null,"menu-element", null); - } - // always include all elements - handler.startElement(null,null, qName, atts); - } + public void skippedEntity( + String name) + throws SAXException + { + handler.skippedEntity(name); + } - public void startPrefixMapping(String prefix, String uri) throws SAXException { - } - }); - } - public void start() throws SAXException - { - try - { - xmlReader.parse(readerInput); + public void startElement( + String uri, + String localName, + String qName, + Attributes atts) + throws SAXException + { + // track menu depth and insert + // menu-element nodes + // to encapsulate menu elements + // to support collection + // polymorphism in Castor + + if (qName.equals("menu")) + { + if (menuDepth > 0) + { + handler.startElement( + null, null, + "menu-element", + null); + } + menuDepth++; + } + else if ((menuDepth > 0) + && (qName + .equals("options") + || qName + .equals("separator") + || qName + .equals("include") || qName + .equals("exclude"))) + { + handler.startElement(null, + null, + "menu-element", + null); + } + + // always include all elements + handler.startElement(null, + null, qName, atts); + } + + public void startPrefixMapping( + String prefix, String uri) + throws SAXException + { + } + }); } - catch (IOException ioe) + + public void start() throws SAXException { - throw new SAXException(ioe); + try + { + xmlReader.parse(readerInput); + } + catch (IOException ioe) + { + throw new SAXException(ioe); + } } - } - }); + }); } - + document.setPath(path); - AbstractBaseElement documentImpl = (AbstractBaseElement)document; + AbstractBaseElement documentImpl = (AbstractBaseElement) document; documentImpl.setHandlerFactory(handlerFactory); - documentImpl.setPermissionsEnabled(handlerFactory.getPermissionsEnabled()); - documentImpl.setConstraintsEnabled(handlerFactory.getConstraintsEnabled()); + documentImpl.setPermissionsEnabled(handlerFactory + .getPermissionsEnabled()); + documentImpl.setConstraintsEnabled(handlerFactory + .getConstraintsEnabled()); documentImpl.unmarshalled(); - if (document.isDirty()){ + if (document.isDirty()) + { updateDocument(document, true); document.setDirty(false); } } catch (IOException e) { - log.error("Could not load the file " + f.getAbsolutePath(), e); - throw new PageNotFoundException("Could not load the file " + f.getAbsolutePath(), e); + log.error("Could not load the file " + f.getAbsolutePath(), e); + throw new PageNotFoundException("Could not load the file " + + f.getAbsolutePath(), e); } catch (MarshalException e) { - log.error("Could not unmarshal the file " + f.getAbsolutePath(), e); - throw new PageNotFoundException("Could not unmarshal the file " + f.getAbsolutePath(), e); + log.error("Could not unmarshal the file " + f.getAbsolutePath(), e); + throw new PageNotFoundException("Could not unmarshal the file " + + f.getAbsolutePath(), e); } catch (ValidationException e) { - log.error("Document " + f.getAbsolutePath() + " is not valid", e); - throw new DocumentNotFoundException("Document " + f.getAbsolutePath() + " is not valid", e); + log.error("Document " + f.getAbsolutePath() + " is not valid", e); + throw new DocumentNotFoundException("Document " + + f.getAbsolutePath() + " is not valid", e); } - if (document == null) { @@ -546,26 +666,20 @@ } else { - if (!clazz.isAssignableFrom(document.getClass())) - { - throw new ClassCastException(document.getClass().getName() + " must implement or extend " - + clazz.getName()); - } + if (!clazz.isAssignableFrom(document.getClass())) { throw new ClassCastException( + document.getClass().getName() + + " must implement or extend " + clazz.getName()); } return document; } } - protected void verifyPath( File path ) throws FileNotFoundException + protected void verifyPath(File path) throws FileNotFoundException { - if (path == null) - { - throw new IllegalArgumentException("Page root cannot be null"); - } + if (path == null) { throw new IllegalArgumentException( + "Page root cannot be null"); } - if (!path.exists()) - { - throw new FileNotFoundException("Could not locate root pages path " + path.getAbsolutePath()); - } + if (!path.exists()) { throw new FileNotFoundException( + "Could not locate root pages path " + path.getAbsolutePath()); } } /** @@ -578,7 +692,8 @@ * @throws DocumentNotFoundException * @throws FailedToDeleteDocumentException */ - public void removeDocument( Document document ) throws DocumentNotFoundException, FailedToDeleteDocumentException + public void removeDocument(Document document) + throws DocumentNotFoundException, FailedToDeleteDocumentException { // sanity checks if (document == null) @@ -598,22 +713,21 @@ } // remove page from disk - String fileName = path; + String fileName = path; if (!fileName.endsWith(this.documentType)) { fileName = path + this.documentType; } File file = new File(this.documentRootDir, fileName); - if (!file.delete()) - { - throw new FailedToDeleteDocumentException(file.getAbsolutePath()+" document cannot be deleted."); - } + if (!file.delete()) { throw new FailedToDeleteDocumentException(file + .getAbsolutePath() + + " document cannot be deleted."); } // remove from cache fileCache.remove(path); // reset document - AbstractNode documentImpl = (AbstractNode)document; + AbstractNode documentImpl = (AbstractNode) document; documentImpl.setParent(null); } @@ -627,10 +741,11 @@ * @param name * @param fromCahe * Whether or not the Document should be pulled from the cache. - * @return @throws - * DocumentNotFoundException + * @return + * @throws DocumentNotFoundException */ - public Document getDocument( String name, boolean fromCache ) throws DocumentNotFoundException, NodeException + public Document getDocument(String name, boolean fromCache) + throws DocumentNotFoundException, NodeException { Document document = null; if (fromCache) @@ -639,13 +754,15 @@ document = (Document) obj; if (document == null) { - document = (Document) unmarshallDocument(expectedReturnType, name, documentType); + document = (Document) unmarshallDocument(expectedReturnType, + name, documentType); addToCache(name, document); } } else { - document = (Document) unmarshallDocument(expectedReturnType, name, documentType); + document = (Document) unmarshallDocument(expectedReturnType, name, + documentType); } return document; @@ -659,7 +776,7 @@ * @param path * @param objectToCache */ - protected void addToCache( String path, Object objectToCache ) + protected void addToCache(String path, Object objectToCache) { synchronized (fileCache) { @@ -673,8 +790,9 @@ catch (java.io.IOException e) { log.error("Error putting document: " + e); - IllegalStateException ise = new IllegalStateException("Error storing Document in the FileCache: " - + e.toString()); + IllegalStateException ise = new IllegalStateException( + "Error storing Document in the FileCache: " + + e.toString()); ise.initCause(e); } } @@ -689,25 +807,27 @@ * @param entry * @throws Exception */ - public void refresh( FileCacheEntry entry ) throws Exception + public void refresh(FileCacheEntry entry) throws Exception { log.debug("Entry is refreshing: " + entry.getFile().getName()); - if (entry.getDocument() instanceof Document && ((Document) entry.getDocument()).getPath().endsWith(documentType)) + if (entry.getDocument() instanceof Document + && ((Document) entry.getDocument()).getPath().endsWith( + documentType)) { Document document = (Document) entry.getDocument(); Document freshDoc = getDocument(document.getPath(), false); - Node parent = ((AbstractNode)document).getParent(false); - + Node parent = ((AbstractNode) document).getParent(false); + freshDoc.setParent(parent); - if(parent instanceof FolderImpl) + if (parent instanceof FolderImpl) { FolderImpl folder = (FolderImpl) parent; folder.getAllNodes().add(freshDoc); } - + freshDoc.setPath(document.getPath()); - entry.setDocument(freshDoc); + entry.setDocument(freshDoc); } } @@ -721,7 +841,7 @@ * @param entry * @throws Exception */ - public void evict( FileCacheEntry entry ) throws Exception + public void evict(FileCacheEntry entry) throws Exception { // TODO Auto-generated method stub @@ -731,7 +851,7 @@ *

        * getType *

        - * + * * @see org.apache.jetspeed.page.document.DocumentHandler#getType() * @return */ @@ -744,7 +864,7 @@ *

        * getHandlerFactory *

        - * + * * @see org.apache.jetspeed.page.document.DocumentHandler#getHandlerFactory() * @return */ @@ -757,7 +877,7 @@ *

        * setHandlerFactory *

        - * + * * @see org.apache.jetspeed.page.document.DocumentHandler#setHandlerFactory(org.apache.jetspeed.page.document.DocumentHandlerFactory) * @param factory */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/DocumentHandlerFactoryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/DocumentHandlerFactoryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/DocumentHandlerFactoryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,11 +23,10 @@ import org.apache.jetspeed.page.document.DocumentHandler; import org.apache.jetspeed.page.document.DocumentHandlerFactory; import org.apache.jetspeed.page.document.DocumentTypeAlreadyRegisteredException; +import org.apache.jetspeed.page.document.Node; import org.apache.jetspeed.page.document.UnsupportedDocumentTypeException; import org.apache.jetspeed.util.ArgUtil; -import org.apache.jetspeed.page.document.Node; - /** *

        * DocumentHandlerFactoryImpl @@ -38,40 +37,40 @@ * * @author Scott T. Weaver * @version $Id: DocumentHandlerFactoryImpl.java 517124 2007-03-12 08:10:25Z ate $ - * + * */ public class DocumentHandlerFactoryImpl implements DocumentHandlerFactory { + private Map handlers; private boolean permissionsEnabled; private boolean constraintsEnabled; - /** - * + * */ - public DocumentHandlerFactoryImpl( Map handlers ) + public DocumentHandlerFactoryImpl(Map handlers) { super(); - - ArgUtil.assertNotNull(Map.class, handlers, this); - - this.handlers = handlers; + ArgUtil.assertNotNull(Map.class, handlers, this); + + this.handlers = handlers; + // register this with handlers Iterator handlersIter = handlers.values().iterator(); while (handlersIter.hasNext()) { - ((DocumentHandler)handlersIter.next()).setHandlerFactory(this); + ((DocumentHandler) handlersIter.next()).setHandlerFactory(this); } } - + public DocumentHandlerFactoryImpl() { this(new HashMap()); - + } /** @@ -83,15 +82,18 @@ * @param documentType * @return */ - public DocumentHandler getDocumentHandler( String documentType ) throws UnsupportedDocumentTypeException - { - if(handlers.containsKey(documentType)) + public DocumentHandler getDocumentHandler(String documentType) + throws UnsupportedDocumentTypeException + { + if (handlers.containsKey(documentType)) { - return (DocumentHandler)handlers.get(documentType); + return (DocumentHandler) handlers.get(documentType); } else { - throw new UnsupportedDocumentTypeException("There are no DocumentHandlers defined for the type: "+documentType); + throw new UnsupportedDocumentTypeException( + "There are no DocumentHandlers defined for the type: " + + documentType); } } @@ -99,17 +101,16 @@ *

        * registerDocumentHandler *

        - * + * * @see org.apache.jetspeed.page.document.DocumentHandlerFactory#registerDocumentHandler(org.apache.jetspeed.page.documenthandler.DocumentHandler) * @param documentHandler * @throws DocumentTypeAlreadyRegisteredException */ - public void registerDocumentHandler( DocumentHandler documentHandler ) throws DocumentTypeAlreadyRegisteredException + public void registerDocumentHandler(DocumentHandler documentHandler) + throws DocumentTypeAlreadyRegisteredException { - if(handlers.containsKey(documentHandler.getType())) - { - throw new DocumentTypeAlreadyRegisteredException(documentHandler.getType()+" has already been registered."); - } + if (handlers.containsKey(documentHandler.getType())) { throw new DocumentTypeAlreadyRegisteredException( + documentHandler.getType() + " has already been registered."); } // register handler and this with handlers documentHandler.setHandlerFactory(this); @@ -120,16 +121,17 @@ *

        * getDocumentHandlerForPath *

        - * + * * @see org.apache.jetspeed.page.document.DocumentHandlerFactory#getDocumentHandlerForPath(java.lang.String) * @param documentPath * @return */ - public DocumentHandler getDocumentHandlerForPath( String documentPath ) throws UnsupportedDocumentTypeException + public DocumentHandler getDocumentHandlerForPath(String documentPath) + throws UnsupportedDocumentTypeException { int dotIndex = documentPath.indexOf('.'); - - if(dotIndex > -1) + + if (dotIndex > -1) { try { @@ -138,7 +140,7 @@ catch (UnsupportedDocumentTypeException e) { int lastSlash = documentPath.lastIndexOf(Node.PATH_SEPARATOR); - if(lastSlash < 0) + if (lastSlash < 0) { lastSlash = 0; } @@ -147,7 +149,8 @@ } else { - throw new UnsupportedDocumentTypeException("The path provided has no extension and may be a folder."); + throw new UnsupportedDocumentTypeException( + "The path provided has no extension and may be a folder."); } } @@ -155,7 +158,7 @@ *

        * getPermissionsEnabled *

        - * + * * @see org.apache.jetspeed.page.document.DocumentHandlerFactory#getPermissionsEnabled() * @return */ @@ -168,7 +171,7 @@ *

        * setPermissionsEnabled *

        - * + * * @see org.apache.jetspeed.page.document.DocumentHandlerFactory#setPermissionsEnabled(boolean) * @return */ @@ -181,7 +184,7 @@ *

        * getConstraintsEnabled *

        - * + * * @see org.apache.jetspeed.page.document.DocumentHandlerFactory#getConstraintsEnabled() * @return */ @@ -194,7 +197,7 @@ *

        * setConstraintsEnabled *

        - * + * * @see org.apache.jetspeed.page.document.DocumentHandlerFactory#setConstraintsEnabled(boolean) * @return */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/FileSystemFolderHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/FileSystemFolderHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/FileSystemFolderHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -35,7 +35,7 @@ import org.apache.jetspeed.om.folder.psml.FolderImpl; import org.apache.jetspeed.om.folder.psml.FolderMetaDataImpl; import org.apache.jetspeed.om.page.Document; - +import org.apache.jetspeed.page.document.DocumentException; import org.apache.jetspeed.page.document.DocumentHandler; import org.apache.jetspeed.page.document.DocumentHandlerFactory; import org.apache.jetspeed.page.document.DocumentNotFoundException; @@ -58,26 +58,31 @@ * * @author Scott T. Weaver * @version $Id: FileSystemFolderHandler.java 553584 2007-07-05 18:09:45Z taylor $ - * + * */ -public class FileSystemFolderHandler implements FolderHandler, FileCacheEventListener +public class FileSystemFolderHandler implements FolderHandler, + FileCacheEventListener { private File documentRootDir; + private DocumentHandler metadataDocHandler; + private DocumentHandlerFactory handlerFactory; - private final static Log log = LogFactory.getLog(FileSystemFolderHandler.class); + private final static Log log = LogFactory + .getLog(FileSystemFolderHandler.class); protected static final FilenameFilter FOLDER_FILTER = new FilenameFilter() { - public boolean accept( File pathname, String fileName ) + public boolean accept(File pathname, String fileName) { return new File(pathname, fileName).isDirectory(); } }; + private FileCache fileCache; /** @@ -96,14 +101,16 @@ * supports folder metadata (folder.metadata) in the * handlerFactory. */ - public FileSystemFolderHandler( String documentRoot, DocumentHandlerFactory handlerFactory, FileCache fileCache ) + public FileSystemFolderHandler(String documentRoot, + DocumentHandlerFactory handlerFactory, FileCache fileCache) throws FileNotFoundException, UnsupportedDocumentTypeException { super(); this.documentRootDir = new File(documentRoot); verifyPath(documentRootDir); this.handlerFactory = handlerFactory; - this.metadataDocHandler = handlerFactory.getDocumentHandler(FolderMetaDataImpl.DOCUMENT_TYPE); + this.metadataDocHandler = handlerFactory + .getDocumentHandler(FolderMetaDataImpl.DOCUMENT_TYPE); this.fileCache = fileCache; this.fileCache.addListener(this); } @@ -115,30 +122,27 @@ * * @see org.apache.jetspeed.page.document.FolderHandler#getFolder(java.lang.String) * @param path - * @return @throws - * FolderNotFoundException + * @return * @throws FolderNotFoundException + * @throws FolderNotFoundException * @throws InvalidFolderException * @throws NodeException * @throws DocumentNotFoundException */ - public Folder getFolder( String path ) throws FolderNotFoundException, InvalidFolderException, NodeException + public Folder getFolder(String path) throws FolderNotFoundException, + InvalidFolderException, NodeException { return getFolder(path, true); } - protected void verifyPath( File path ) throws FileNotFoundException + protected void verifyPath(File path) throws FileNotFoundException { - if (path == null) - { - throw new IllegalArgumentException("Page root cannot be null"); - } + if (path == null) { throw new IllegalArgumentException( + "Page root cannot be null"); } - if (!path.exists()) - { - throw new FileNotFoundException("Could not locate root pages path " + path.getAbsolutePath()); - } + if (!path.exists()) { throw new FileNotFoundException( + "Could not locate root pages path " + path.getAbsolutePath()); } } /** @@ -150,29 +154,29 @@ * boolean) * @param path * @param fromCache - * @return @throws - * DocumentException, FolderNotFoundException + * @return + * @throws DocumentException, + * FolderNotFoundException * @throws InvalidFolderException * @throws DocumentNotFoundException */ - public Folder getFolder( String path, boolean fromCache ) throws NodeException, FolderNotFoundException, InvalidFolderException + public Folder getFolder(String path, boolean fromCache) + throws NodeException, FolderNotFoundException, + InvalidFolderException { Folder folder = null; File folderFile = new File(documentRootDir, path); - if(!folderFile.exists()) - { - throw new FolderNotFoundException(folderFile.getAbsolutePath()+" does not exist."); - } - - if(!folderFile.isDirectory()) - { - throw new InvalidFolderException(folderFile.getAbsolutePath()+" is not a valid directory."); - } - + if (!folderFile.exists()) { throw new FolderNotFoundException( + folderFile.getAbsolutePath() + " does not exist."); } + + if (!folderFile.isDirectory()) { throw new InvalidFolderException( + folderFile.getAbsolutePath() + " is not a valid directory."); } + // cleanup trailing separators - if (!path.equals(Folder.PATH_SEPARATOR) && path.endsWith(Folder.PATH_SEPARATOR)) + if (!path.equals(Folder.PATH_SEPARATOR) + && path.endsWith(Folder.PATH_SEPARATOR)) { - path = path.substring(0, path.length()-1); + path = path.substring(0, path.length() - 1); } // check cache @@ -187,7 +191,9 @@ try { // look for metadata - FolderMetaDataImpl metadata = (FolderMetaDataImpl) metadataDocHandler.getDocument(path + Folder.PATH_SEPARATOR + FolderMetaDataImpl.DOCUMENT_TYPE); + FolderMetaDataImpl metadata = (FolderMetaDataImpl) metadataDocHandler + .getDocument(path + Folder.PATH_SEPARATOR + + FolderMetaDataImpl.DOCUMENT_TYPE); folder = new FolderImpl(path, metadata, handlerFactory, this); } catch (DocumentNotFoundException e) @@ -200,7 +206,8 @@ if (!path.equals(Folder.PATH_SEPARATOR)) { String parentPath = path; - int parentSeparatorIndex = parentPath.lastIndexOf(Folder.PATH_SEPARATOR_CHAR); + int parentSeparatorIndex = parentPath + .lastIndexOf(Folder.PATH_SEPARATOR_CHAR); if (parentSeparatorIndex > 0) { parentPath = parentPath.substring(0, parentSeparatorIndex); @@ -234,7 +241,8 @@ * @param folder * @throws FailedToUpdateFolderException */ - public void updateFolder(Folder folder) throws FailedToUpdateFolderException + public void updateFolder(Folder folder) + throws FailedToUpdateFolderException { // sanity checks if (folder == null) @@ -255,30 +263,35 @@ } // setup folder implementation - FolderImpl folderImpl = (FolderImpl)folder; + FolderImpl folderImpl = (FolderImpl) folder; folderImpl.setFolderHandler(this); folderImpl.setHandlerFactory(handlerFactory); - folderImpl.setPermissionsEnabled(handlerFactory.getPermissionsEnabled()); - folderImpl.setConstraintsEnabled(handlerFactory.getConstraintsEnabled()); + folderImpl + .setPermissionsEnabled(handlerFactory.getPermissionsEnabled()); + folderImpl + .setConstraintsEnabled(handlerFactory.getConstraintsEnabled()); folderImpl.marshalling(); // create underlying folder if it does not exist File folderFile = new File(documentRootDir, path); - if ((folderFile.exists() && !folderFile.isDirectory()) || (!folderFile.exists() && !folderFile.mkdir())) - { - throw new FailedToUpdateFolderException(folderFile.getAbsolutePath()+" does not exist and cannot be created."); - } + if ((folderFile.exists() && !folderFile.isDirectory()) + || (!folderFile.exists() && !folderFile.mkdir())) { throw new FailedToUpdateFolderException( + folderFile.getAbsolutePath() + + " does not exist and cannot be created."); } // update metadata try { FolderMetaDataImpl metadata = folderImpl.getFolderMetaData(); - metadata.setPath(path + Folder.PATH_SEPARATOR + FolderMetaDataImpl.DOCUMENT_TYPE); + metadata.setPath(path + Folder.PATH_SEPARATOR + + FolderMetaDataImpl.DOCUMENT_TYPE); metadataDocHandler.updateDocument(metadata); } catch (Exception e) { - throw new FailedToUpdateFolderException(folderFile.getAbsolutePath()+" failed to update folder.metadata", e); + throw new FailedToUpdateFolderException(folderFile + .getAbsolutePath() + + " failed to update folder.metadata", e); } // add to cache @@ -294,7 +307,8 @@ * @param folder * @throws FailedToDeleteFolderException */ - public void removeFolder(Folder folder) throws FailedToDeleteFolderException + public void removeFolder(Folder folder) + throws FailedToDeleteFolderException { // sanity checks if (folder == null) @@ -315,7 +329,7 @@ } // remove folder nodes - FolderImpl folderImpl = (FolderImpl)folder; + FolderImpl folderImpl = (FolderImpl) folder; try { // copy all folder nodes to remove @@ -325,31 +339,35 @@ { removeNodes.add(copyIter.next()); } - + // remove folder nodes Iterator removeIter = removeNodes.iterator(); while (removeIter.hasNext()) { - Node node = (Node)removeIter.next(); + Node node = (Node) removeIter.next(); if (node instanceof Folder) { // recursively remove folder - removeFolder((Folder)node); + removeFolder((Folder) node); } else if (node instanceof Document) { // remove folder document try { - handlerFactory.getDocumentHandler(node.getType()).removeDocument((Document)node); + handlerFactory.getDocumentHandler(node.getType()) + .removeDocument((Document) node); } catch (Exception e) { - File documentFile = new File(this.documentRootDir, node.getPath()); - throw new FailedToDeleteFolderException(documentFile.getAbsolutePath()+" document cannot be deleted."); + File documentFile = new File(this.documentRootDir, node + .getPath()); + throw new FailedToDeleteFolderException(documentFile + .getAbsolutePath() + + " document cannot be deleted."); } } - ((NodeSetImpl)folderImpl.getAllNodes()).remove(node); + ((NodeSetImpl) folderImpl.getAllNodes()).remove(node); } } catch (FailedToDeleteFolderException fdfe) @@ -364,9 +382,11 @@ // remove underlying folder and unknown files File folderFile = new File(this.documentRootDir, path); File metadataFile = null; - if ((folderImpl.getFolderMetaData() != null) && (folderImpl.getFolderMetaData().getPath() != null)) + if ((folderImpl.getFolderMetaData() != null) + && (folderImpl.getFolderMetaData().getPath() != null)) { - metadataFile = new File(this.documentRootDir, folderImpl.getFolderMetaData().getPath()); + metadataFile = new File(this.documentRootDir, folderImpl + .getFolderMetaData().getPath()); } if (folderFile.exists() && folderFile.isDirectory()) { @@ -377,28 +397,27 @@ File contentFile = new File(folderFile, contents[i]); if ((metadataFile == null) || !contentFile.equals(metadataFile)) { - if (!deleteFile(contentFile)) - { - throw new FailedToDeleteFolderException(folderFile.getAbsolutePath()+" unrecognized folder contents cannot be deleted."); - } + if (!deleteFile(contentFile)) { throw new FailedToDeleteFolderException( + folderFile.getAbsolutePath() + + " unrecognized folder contents cannot be deleted."); } } } // delete folder and metadata - if ((metadataFile != null) && metadataFile.exists() && !metadataFile.delete()) - { - throw new FailedToDeleteFolderException(folderFile.getAbsolutePath()+" folder metadata cannot be deleted."); - } + if ((metadataFile != null) && metadataFile.exists() + && !metadataFile.delete()) { throw new FailedToDeleteFolderException( + folderFile.getAbsolutePath() + + " folder metadata cannot be deleted."); } // delete folder and all remaining folder contents // unless folder is root folder which should be // preserved as PSML "mount point" - if (!path.equals(Folder.PATH_SEPARATOR) && !folderFile.delete()) - { - throw new FailedToDeleteFolderException(folderFile.getAbsolutePath()+" folder cannot be deleted."); - } + if (!path.equals(Folder.PATH_SEPARATOR) && !folderFile.delete()) { throw new FailedToDeleteFolderException( + folderFile.getAbsolutePath() + " folder cannot be deleted."); } } else { - throw new FailedToDeleteFolderException(folderFile.getAbsolutePath()+" not found."); + throw new FailedToDeleteFolderException(folderFile + .getAbsolutePath() + + " not found."); } // remove from cache @@ -420,10 +439,7 @@ String[] children = file.list(); for (int i = 0; (i < children.length); i++) { - if (!deleteFile(new File(file, children[i]))) - { - return false; - } + if (!deleteFile(new File(file, children[i]))) { return false; } } } return file.delete(); @@ -436,18 +452,20 @@ * * @see org.apache.jetspeed.page.document.FolderHandler#getFolders(java.lang.String) * @param path - * @return @throws - * FolderNotFoundException + * @return * @throws FolderNotFoundException + * @throws FolderNotFoundException * @throws InvalidFolderException * @throws NodeException */ - public NodeSet getFolders( String path ) throws FolderNotFoundException, InvalidFolderException, NodeException + public NodeSet getFolders(String path) throws FolderNotFoundException, + InvalidFolderException, NodeException { File parent = new File(documentRootDir, path); if (!parent.exists()) { - throw new FolderNotFoundException("No folder exists at the path: " + parent.getAbsolutePath()); + throw new FolderNotFoundException("No folder exists at the path: " + + parent.getAbsolutePath()); } else { @@ -461,7 +479,8 @@ } else { - folders.add(getFolder(path + Folder.PATH_SEPARATOR + children[i])); + folders.add(getFolder(path + Folder.PATH_SEPARATOR + + children[i])); } } return folders; @@ -470,9 +489,10 @@ public class DocumentTypeFilter implements FilenameFilter { + private String documentType; - public DocumentTypeFilter( String documentType ) + public DocumentTypeFilter(String documentType) { this.documentType = documentType; } @@ -487,7 +507,7 @@ * @param name * @return */ - public boolean accept( File dir, String name ) + public boolean accept(File dir, String name) { return name.endsWith(documentType); } @@ -501,12 +521,14 @@ * * @see org.apache.jetspeed.page.document.FolderHandler#list(java.lang.String) * @param documentType - * @return @throws - * FolderNotFoundException + * @return + * @throws FolderNotFoundException */ - public String[] list( String folderPath, String documentType ) throws FolderNotFoundException + public String[] list(String folderPath, String documentType) + throws FolderNotFoundException { - return getChildrenNames(folderPath, new DocumentTypeFilter(documentType)); + return getChildrenNames(folderPath, + new DocumentTypeFilter(documentType)); } /** @@ -516,20 +538,22 @@ * * @see org.apache.jetspeed.page.document.FolderHandler#listAll(java.lang.String) * @param folderPath - * @return @throws - * FolderNotFoundException + * @return + * @throws FolderNotFoundException */ - public String[] listAll( String folderPath ) throws FolderNotFoundException + public String[] listAll(String folderPath) throws FolderNotFoundException { return getChildrenNames(folderPath, null); } - protected String[] getChildrenNames( String path, FilenameFilter filter ) throws FolderNotFoundException + protected String[] getChildrenNames(String path, FilenameFilter filter) + throws FolderNotFoundException { File parent = new File(documentRootDir, path); if (!parent.exists()) { - throw new FolderNotFoundException("No folder exists at the path: " + parent.getAbsolutePath()); + throw new FolderNotFoundException("No folder exists at the path: " + + parent.getAbsolutePath()); } else { @@ -548,7 +572,7 @@ *

        * getChildNodes *

        - * + * * @see org.apache.jetspeed.page.document.FolderHandler#getNodes(java.lang.String,boolean,java.lang.String) * @param path * @param regexp @@ -560,30 +584,27 @@ * @throws NodeException */ public NodeSet getNodes(String path, boolean regexp, String documentType) - throws FolderNotFoundException, InvalidFolderException, NodeException + throws FolderNotFoundException, InvalidFolderException, + NodeException { // path must be valid absolute path - if ((path == null) || ! path.startsWith(Folder.PATH_SEPARATOR)) - { - throw new InvalidFolderException( "Invalid path specified " + path ); - } + if ((path == null) || !path.startsWith(Folder.PATH_SEPARATOR)) { throw new InvalidFolderException( + "Invalid path specified " + path); } // traverse folders and parse path from root, // accumualting matches in node set Folder folder = getFolder(Folder.PATH_SEPARATOR); NodeSetImpl matched = new NodeSetImpl(null); - getNodes(folder,path,regexp,matched); + getNodes(folder, path, regexp, matched); // return matched nodes filtered by document type - if (documentType != null) - { - return matched.subset(documentType); - } + if (documentType != null) { return matched.subset(documentType); } return matched; } - private void getNodes(Folder folder, String path, boolean regexp, NodeSet matched) - throws FolderNotFoundException, InvalidFolderException, NodeException + private void getNodes(Folder folder, String path, boolean regexp, + NodeSet matched) throws FolderNotFoundException, + InvalidFolderException, NodeException { // test for trivial folder match if (path.equals(Folder.PATH_SEPARATOR)) @@ -603,13 +624,18 @@ if (separatorIndex != -1) { // match folder name - String folderName = path.substring(0,separatorIndex); - String folderPath = (folder.getPath().endsWith(Folder.PATH_SEPARATOR) ? folder.getPath() : folder.getPath() + Folder.PATH_SEPARATOR) + folderName; + String folderName = path.substring(0, separatorIndex); + String folderPath = (folder.getPath().endsWith( + Folder.PATH_SEPARATOR) ? folder.getPath() : folder + .getPath() + + Folder.PATH_SEPARATOR) + + folderName; NodeSet matchedFolders = null; if (regexp) { // get regexp matched folders - matchedFolders = ((FolderImpl)folder).getFolders(false).inclusiveSubset(folderPath); + matchedFolders = ((FolderImpl) folder).getFolders(false) + .inclusiveSubset(folderPath); } else { @@ -621,10 +647,9 @@ matchedFolders.add(matchedFolder); } } - if ((matchedFolders == null) || (matchedFolders.size() == 0)) - { - throw new FolderNotFoundException("Cannot find folder" + folderName + " in " + folder.getPath()); - } + if ((matchedFolders == null) || (matchedFolders.size() == 0)) { throw new FolderNotFoundException( + "Cannot find folder" + folderName + " in " + + folder.getPath()); } // match recursively over matched folders path = path.substring(separatorIndex); @@ -639,11 +664,15 @@ // match node name String nodeName = path; - String nodePath = (folder.getPath().endsWith(Folder.PATH_SEPARATOR) ? folder.getPath() : folder.getPath() + Folder.PATH_SEPARATOR) + nodeName; + String nodePath = (folder.getPath().endsWith(Folder.PATH_SEPARATOR) ? folder + .getPath() + : folder.getPath() + Folder.PATH_SEPARATOR) + + nodeName; if (regexp) { // get regexp matched nodes - Iterator addIter = ((FolderImpl)folder).getAllNodes().inclusiveSubset(nodePath).iterator(); + Iterator addIter = ((FolderImpl) folder).getAllNodes() + .inclusiveSubset(nodePath).iterator(); while (addIter.hasNext()) { matched.add((Node) addIter.next()); @@ -652,7 +681,7 @@ else { // get single matched node - Iterator findIter = ((FolderImpl)folder).getAllNodes().iterator(); + Iterator findIter = ((FolderImpl) folder).getAllNodes().iterator(); while (findIter.hasNext()) { Node addNode = (Node) findIter.next(); @@ -665,7 +694,6 @@ } } - /** *

        * addToCache @@ -674,7 +702,7 @@ * @param id * @param objectToCache */ - protected void addToCache( String id, Object objectToCache ) + protected void addToCache(String id, Object objectToCache) { synchronized (fileCache) { @@ -688,7 +716,8 @@ catch (java.io.IOException e) { - String msg = "Error storing Document in the FileCache: " + e.toString(); + String msg = "Error storing Document in the FileCache: " + + e.toString(); log.error(msg); IllegalStateException ise = new IllegalStateException(msg); ise.initCause(e); @@ -705,31 +734,33 @@ * @param entry * @throws Exception */ - public void refresh( FileCacheEntry entry ) throws Exception + public void refresh(FileCacheEntry entry) throws Exception { - if (entry.getDocument() instanceof Folder ) + if (entry.getDocument() instanceof Folder) { - Folder folder = (Folder) entry.getDocument(); + Folder folder = (Folder) entry.getDocument(); entry.setDocument(getFolder(folder.getPath(), false)); - if (((AbstractNode)folder).getParent(false) != null) + if (((AbstractNode) folder).getParent(false) != null) { - FileCacheEntry parentEntry = fileCache.get(((AbstractNode)folder).getParent(false).getPath()); - refresh(parentEntry); + FileCacheEntry parentEntry = fileCache + .get(((AbstractNode) folder).getParent(false).getPath()); + refresh(parentEntry); } } - else if(entry.getDocument() instanceof Document) + else if (entry.getDocument() instanceof Document) { Document doc = (Document) entry.getDocument(); if (doc.getType().equals(FolderMetaDataImpl.DOCUMENT_TYPE)) { - FileCacheEntry folderEntry = fileCache.get(((AbstractNode)doc).getParent().getPath()); + FileCacheEntry folderEntry = fileCache.get(((AbstractNode) doc) + .getParent().getPath()); refresh(folderEntry); } } - - if(entry.getDocument() instanceof Reset) + + if (entry.getDocument() instanceof Reset) { - ((Reset)entry.getDocument()).reset(); + ((Reset) entry.getDocument()).reset(); } } @@ -743,13 +774,13 @@ * @param entry * @throws Exception */ - public void evict( FileCacheEntry entry ) throws Exception + public void evict(FileCacheEntry entry) throws Exception { } public boolean isFolder(String path) { - return new File(this.documentRootDir, path).isDirectory(); + return new File(this.documentRootDir, path).isDirectory(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/NodeOrderCompartaor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/NodeOrderCompartaor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/NodeOrderCompartaor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /* * Created on Aug 31, 2004 * @@ -35,20 +35,22 @@ * * @author Scott T. Weaver * @version $Id: NodeOrderCompartaor.java 516881 2007-03-11 10:34:21Z ate $ - * + * */ public class NodeOrderCompartaor implements Comparator { + private List nodeIndex; - private String relativePath=""; + private String relativePath = ""; + /** - * + * */ - public NodeOrderCompartaor( List nodeIndex, String relativePath ) + public NodeOrderCompartaor(List nodeIndex, String relativePath) { super(); - this.nodeIndex = nodeIndex; + this.nodeIndex = nodeIndex; this.relativePath = relativePath; } @@ -62,64 +64,64 @@ * @param o2 * @return */ - public int compare( Object o1, Object o2 ) + public int compare(Object o1, Object o2) { - - String node1 = null; - String node2 = null; - - if(relativePath.length() < o1.toString().length()) + + String node1 = null; + String node2 = null; + + if (relativePath.length() < o1.toString().length()) + { + node1 = o1.toString().substring(relativePath.length()); + } + else + { + node1 = o1.toString(); + } + + if (relativePath.length() < o2.toString().length()) + { + node2 = o2.toString().substring(relativePath.length()); + } + else + { + node2 = o2.toString(); + } + + String c1 = null; + String c2 = null; + + if (nodeIndex != null) + { + int index1 = nodeIndex.indexOf(node1); + int index2 = nodeIndex.indexOf(node2); + + if (index1 > -1) { - node1 = o1.toString().substring(relativePath.length()); + c1 = String.valueOf(index1); } else { - node1 = o1.toString(); + c1 = node1; } - - if(relativePath.length() < o2.toString().length()) - { - node2 = o2.toString().substring(relativePath.length()); - } - else - { - node2 = o2.toString(); - } - String c1 = null; - String c2 = null; - - if (nodeIndex != null) + if (index2 > -1) { - int index1 = nodeIndex.indexOf(node1); - int index2 = nodeIndex.indexOf(node2); - - if (index1 > -1) - { - c1 = String.valueOf(index1); - } - else - { - c1 = node1; - } - - if (index2 > -1) - { - c2 = String.valueOf(index2); - } - else - { - c2 = node2; - } + c2 = String.valueOf(index2); } else { - c1 = node1; c2 = node2; } + } + else + { + c1 = node1; + c2 = node2; + } - return c1.compareTo(c2); - + return c1.compareTo(c2); + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/NodeSetImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/NodeSetImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/document/psml/NodeSetImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -36,17 +36,22 @@ * * @author Scott T. Weaver * @version $Id: NodeSetImpl.java 568811 2007-08-23 03:00:37Z woonsan $ - * + * */ public class NodeSetImpl implements NodeSet { + private Map nodes; + private Map subsets; + private String resolveToPath; + private Comparator comparator; + protected static final Map patternCache = new HashMap(); - public NodeSetImpl( String resolveToPath ) + public NodeSetImpl(String resolveToPath) { this.resolveToPath = resolveToPath; nodes = new TreeMap(); @@ -58,7 +63,7 @@ * @param resolveToPath * @param comparator */ - public NodeSetImpl( String resolveToPath, Comparator comparator ) + public NodeSetImpl(String resolveToPath, Comparator comparator) { this.resolveToPath = resolveToPath; nodes = new TreeMap(comparator); @@ -76,7 +81,7 @@ * @param name * @return */ - public Node get( String name ) + public Node get(String name) { if (nodes.containsKey(name)) @@ -91,7 +96,8 @@ } else { - return (Node) nodes.get(resolveToPath + Node.PATH_SEPARATOR + name); + return (Node) nodes.get(resolveToPath + Node.PATH_SEPARATOR + + name); } } @@ -107,7 +113,7 @@ * @see org.apache.jetspeed.page.document.NodeSet#add(org.apache.jetspeed.page.document.Node) * @param document */ - public void add( Node node ) + public void add(Node node) { String path = node.getPath(); nodes.put(path, node); @@ -153,7 +159,7 @@ * @param type * @return */ - public NodeSet subset( String type ) + public NodeSet subset(String type) { NodeSet subset = (NodeSet) subsets.get(type); if (subset == null) @@ -169,7 +175,7 @@ subset.add(node); } } - + synchronized (subsets) { subsets.put(type, subset); @@ -188,7 +194,7 @@ * @param regex * @return */ - public NodeSet exclusiveSubset( String regex ) + public NodeSet exclusiveSubset(String regex) { Iterator allNodes = nodes.entrySet().iterator(); NodeSetImpl subset = new NodeSetImpl(resolveToPath, comparator); @@ -203,7 +209,7 @@ subset.add(node); } } - + return subset; } @@ -216,7 +222,7 @@ * @param regex * @return */ - public NodeSet inclusiveSubset( String regex ) + public NodeSet inclusiveSubset(String regex) { Iterator allNodes = nodes.entrySet().iterator(); NodeSetImpl subset = new NodeSetImpl(resolveToPath, comparator); @@ -231,10 +237,10 @@ subset.add(node); } } - + return subset; } - + /** * *

        @@ -253,7 +259,7 @@ *

        * matches *

        - * + * * @param pattern * @param value * @return @@ -262,28 +268,28 @@ { return pattern.matcher(value).matches(); } - + /** * *

        * getPattern *

        - * + * * @param regex * @return */ protected final Pattern getPattern(String regex) - { - if(patternCache.containsKey(regex)) + { + if (patternCache.containsKey(regex)) { - return (Pattern)patternCache.get(regex); + return (Pattern) patternCache.get(regex); } else { Pattern pattern = Pattern.compile(regex); patternCache.put(regex, pattern); return pattern; - } + } } /** @@ -294,7 +300,7 @@ * @see org.apache.jetspeed.page.document.NodeSet#contains() * @return */ - public boolean contains( Node node ) + public boolean contains(Node node) { return nodes.values().contains(node); } @@ -317,7 +323,8 @@ * remove *

        * - * @param node to remove + * @param node + * to remove * @return removed node */ public Node remove(Node node) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/DatabasePageManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/DatabasePageManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/DatabasePageManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -98,10 +98,14 @@ * @author Randy Watler * @version $Id: $ */ -public class DatabasePageManager extends InitablePersistenceBrokerDaoSupport implements PageManager +public class DatabasePageManager extends InitablePersistenceBrokerDaoSupport + implements PageManager { + private static final int DEFAULT_CACHE_SIZE = 128; + private static final int MIN_CACHE_EXPIRES_SECONDS = 30; + private static final int DEFAULT_CACHE_EXPIRES_SECONDS = 150; private static Map modelClasses = new HashMap(); @@ -112,38 +116,59 @@ modelClasses.put("FolderImpl", FolderImpl.class); modelClasses.put("LinkImpl", LinkImpl.class); modelClasses.put("PageSecurityImpl", PageSecurityImpl.class); - modelClasses.put("FolderMenuDefinitionImpl", FolderMenuDefinitionImpl.class); - modelClasses.put("FolderMenuExcludeDefinitionImpl", FolderMenuExcludeDefinitionImpl.class); - modelClasses.put("FolderMenuIncludeDefinitionImpl", FolderMenuIncludeDefinitionImpl.class); - modelClasses.put("FolderMenuOptionsDefinitionImpl", FolderMenuOptionsDefinitionImpl.class); - modelClasses.put("FolderMenuSeparatorDefinitionImpl", FolderMenuSeparatorDefinitionImpl.class); - modelClasses.put("PageMenuDefinitionImpl", PageMenuDefinitionImpl.class); - modelClasses.put("PageMenuExcludeDefinitionImpl", PageMenuExcludeDefinitionImpl.class); - modelClasses.put("PageMenuIncludeDefinitionImpl", PageMenuIncludeDefinitionImpl.class); - modelClasses.put("PageMenuOptionsDefinitionImpl", PageMenuOptionsDefinitionImpl.class); - modelClasses.put("PageMenuSeparatorDefinitionImpl", PageMenuSeparatorDefinitionImpl.class); - modelClasses.put("SecurityConstraintsImpl", SecurityConstraintsImpl.class); - modelClasses.put("FolderSecurityConstraintImpl", FolderSecurityConstraintImpl.class); - modelClasses.put("PageSecurityConstraintImpl", PageSecurityConstraintImpl.class); - modelClasses.put("FragmentSecurityConstraintImpl", FragmentSecurityConstraintImpl.class); - modelClasses.put("LinkSecurityConstraintImpl", LinkSecurityConstraintImpl.class); - modelClasses.put("PageSecuritySecurityConstraintImpl", PageSecuritySecurityConstraintImpl.class); - modelClasses.put("SecurityConstraintsDefImpl", SecurityConstraintsDefImpl.class); - modelClasses.put("FragmentPreferenceImpl", FragmentPreferenceImpl.class); + modelClasses.put("FolderMenuDefinitionImpl", + FolderMenuDefinitionImpl.class); + modelClasses.put("FolderMenuExcludeDefinitionImpl", + FolderMenuExcludeDefinitionImpl.class); + modelClasses.put("FolderMenuIncludeDefinitionImpl", + FolderMenuIncludeDefinitionImpl.class); + modelClasses.put("FolderMenuOptionsDefinitionImpl", + FolderMenuOptionsDefinitionImpl.class); + modelClasses.put("FolderMenuSeparatorDefinitionImpl", + FolderMenuSeparatorDefinitionImpl.class); + modelClasses + .put("PageMenuDefinitionImpl", PageMenuDefinitionImpl.class); + modelClasses.put("PageMenuExcludeDefinitionImpl", + PageMenuExcludeDefinitionImpl.class); + modelClasses.put("PageMenuIncludeDefinitionImpl", + PageMenuIncludeDefinitionImpl.class); + modelClasses.put("PageMenuOptionsDefinitionImpl", + PageMenuOptionsDefinitionImpl.class); + modelClasses.put("PageMenuSeparatorDefinitionImpl", + PageMenuSeparatorDefinitionImpl.class); + modelClasses.put("SecurityConstraintsImpl", + SecurityConstraintsImpl.class); + modelClasses.put("FolderSecurityConstraintImpl", + FolderSecurityConstraintImpl.class); + modelClasses.put("PageSecurityConstraintImpl", + PageSecurityConstraintImpl.class); + modelClasses.put("FragmentSecurityConstraintImpl", + FragmentSecurityConstraintImpl.class); + modelClasses.put("LinkSecurityConstraintImpl", + LinkSecurityConstraintImpl.class); + modelClasses.put("PageSecuritySecurityConstraintImpl", + PageSecuritySecurityConstraintImpl.class); + modelClasses.put("SecurityConstraintsDefImpl", + SecurityConstraintsDefImpl.class); + modelClasses + .put("FragmentPreferenceImpl", FragmentPreferenceImpl.class); } private DelegatingPageManager delegator; - + private int cacheSize; private int cacheExpiresSeconds; private PageManager pageManagerProxy; - public DatabasePageManager(String repositoryPath, int cacheSize, int cacheExpiresSeconds, boolean isPermissionsSecurity, boolean isConstraintsSecurity) + public DatabasePageManager(String repositoryPath, int cacheSize, + int cacheExpiresSeconds, boolean isPermissionsSecurity, + boolean isConstraintsSecurity) { super(repositoryPath); - delegator = new DelegatingPageManager(isPermissionsSecurity, isConstraintsSecurity, modelClasses); + delegator = new DelegatingPageManager(isPermissionsSecurity, + isConstraintsSecurity, modelClasses); this.cacheSize = Math.max(cacheSize, DEFAULT_CACHE_SIZE); if (cacheExpiresSeconds < 0) { @@ -155,14 +180,15 @@ } else { - this.cacheExpiresSeconds = Math.max(cacheExpiresSeconds, MIN_CACHE_EXPIRES_SECONDS); + this.cacheExpiresSeconds = Math.max(cacheExpiresSeconds, + MIN_CACHE_EXPIRES_SECONDS); } DatabasePageManagerCache.cacheInit(this); } /** * getCacheSize - * + * * @return configured cache size */ public int getCacheSize() @@ -172,7 +198,7 @@ /** * getCacheExpiresSeconds - * + * * @return configured cache expiration in seconds */ public int getCacheExpiresSeconds() @@ -182,10 +208,9 @@ /** * getPageManagerProxy - * - * @return proxied page manager interface used to - * inject into Folder instances to provide - * transaction/interception + * + * @return proxied page manager interface used to inject into Folder + * instances to provide transaction/interception */ public PageManager getPageManagerProxy() { @@ -194,10 +219,10 @@ /** * setPageManagerProxy - * - * @param proxy proxied page manager interface used to - * inject into Folder instances to provide - * transaction/interception + * + * @param proxy + * proxied page manager interface used to inject into Folder + * instances to provide transaction/interception */ public void setPageManagerProxy(PageManager proxy) { @@ -209,7 +234,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getConstraintsEnabled() */ public boolean getConstraintsEnabled() @@ -217,7 +244,9 @@ return delegator.getConstraintsEnabled(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getPermissionsEnabled() */ public boolean getPermissionsEnabled() @@ -225,7 +254,9 @@ return delegator.getPermissionsEnabled(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newPage(java.lang.String) */ public Page newPage(String path) @@ -233,7 +264,9 @@ return delegator.newPage(path); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newFolder(java.lang.String) */ public Folder newFolder(String path) @@ -241,7 +274,9 @@ return delegator.newFolder(path); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newLink(java.lang.String) */ public Link newLink(String path) @@ -249,7 +284,9 @@ return delegator.newLink(path); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newPageSecurity() */ public PageSecurity newPageSecurity() @@ -257,15 +294,19 @@ return delegator.newPageSecurity(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newFragment() */ public Fragment newFragment() { - return delegator.newFragment(); + return delegator.newFragment(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newPortletFragment() */ public Fragment newPortletFragment() @@ -273,7 +314,9 @@ return delegator.newPortletFragment(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newFolderMenuDefinition() */ public MenuDefinition newFolderMenuDefinition() @@ -281,7 +324,9 @@ return delegator.newFolderMenuDefinition(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newFolderMenuExcludeDefinition() */ public MenuExcludeDefinition newFolderMenuExcludeDefinition() @@ -289,7 +334,9 @@ return delegator.newFolderMenuExcludeDefinition(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newFolderMenuIncludeDefinition() */ public MenuIncludeDefinition newFolderMenuIncludeDefinition() @@ -297,7 +344,9 @@ return delegator.newFolderMenuIncludeDefinition(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newFolderMenuOptionsDefinition() */ public MenuOptionsDefinition newFolderMenuOptionsDefinition() @@ -305,7 +354,9 @@ return delegator.newFolderMenuOptionsDefinition(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newFolderMenuSeparatorDefinition() */ public MenuSeparatorDefinition newFolderMenuSeparatorDefinition() @@ -313,7 +364,9 @@ return delegator.newFolderMenuSeparatorDefinition(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newPageMenuDefinition() */ public MenuDefinition newPageMenuDefinition() @@ -321,7 +374,9 @@ return delegator.newPageMenuDefinition(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newPageMenuExcludeDefinition() */ public MenuExcludeDefinition newPageMenuExcludeDefinition() @@ -329,7 +384,9 @@ return delegator.newPageMenuExcludeDefinition(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newPageMenuIncludeDefinition() */ public MenuIncludeDefinition newPageMenuIncludeDefinition() @@ -337,7 +394,9 @@ return delegator.newPageMenuIncludeDefinition(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newPageMenuOptionsDefinition() */ public MenuOptionsDefinition newPageMenuOptionsDefinition() @@ -345,7 +404,9 @@ return delegator.newPageMenuOptionsDefinition(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newPageMenuSeparatorDefinition() */ public MenuSeparatorDefinition newPageMenuSeparatorDefinition() @@ -353,7 +414,9 @@ return delegator.newPageMenuSeparatorDefinition(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newSecurityConstraints() */ public SecurityConstraints newSecurityConstraints() @@ -361,7 +424,9 @@ return delegator.newSecurityConstraints(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newFolderSecurityConstraint() */ public SecurityConstraint newFolderSecurityConstraint() @@ -369,7 +434,9 @@ return delegator.newFolderSecurityConstraint(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newPageSecurityConstraint() */ public SecurityConstraint newPageSecurityConstraint() @@ -377,7 +444,9 @@ return delegator.newPageSecurityConstraint(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newFragmentSecurityConstraint() */ public SecurityConstraint newFragmentSecurityConstraint() @@ -385,7 +454,9 @@ return delegator.newFragmentSecurityConstraint(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newLinkSecurityConstraint() */ public SecurityConstraint newLinkSecurityConstraint() @@ -393,7 +464,9 @@ return delegator.newLinkSecurityConstraint(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newPageSecuritySecurityConstraint() */ public SecurityConstraint newPageSecuritySecurityConstraint() @@ -401,7 +474,9 @@ return delegator.newPageSecuritySecurityConstraint(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newSecurityConstraintsDef() */ public SecurityConstraintsDef newSecurityConstraintsDef() @@ -409,7 +484,9 @@ return delegator.newSecurityConstraintsDef(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#newFragmentPreference() */ public FragmentPreference newFragmentPreference() @@ -417,7 +494,9 @@ return delegator.newFragmentPreference(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#addListener(org.apache.jetspeed.page.PageManagerEventListener) */ public void addListener(PageManagerEventListener listener) @@ -425,7 +504,9 @@ delegator.addListener(listener); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#removeListener(org.apache.jetspeed.page.PageManagerEventListener) */ public void removeListener(PageManagerEventListener listener) @@ -433,7 +514,9 @@ delegator.removeListener(listener); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#reset() */ public void reset() @@ -445,10 +528,13 @@ DatabasePageManagerCache.cacheClear(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getPage(java.lang.String) */ - public Page getPage(String path) throws PageNotFoundException, NodeException + public Page getPage(String path) throws PageNotFoundException, + NodeException { // construct page attributes from path path = NodeImpl.getCanonicalNodePath(path); @@ -460,7 +546,7 @@ // check for view access on page cachedNode.checkAccess(JetspeedActions.VIEW); - return (Page)cachedNode; + return (Page) cachedNode; } // retrieve page from database @@ -468,14 +554,14 @@ { Criteria filter = new Criteria(); filter.addEqualTo("path", path); - QueryByCriteria query = QueryFactory.newQuery(PageImpl.class, filter); - Page page = (Page)getPersistenceBrokerTemplate().getObjectByQuery(query); - + QueryByCriteria query = QueryFactory.newQuery(PageImpl.class, + filter); + Page page = (Page) getPersistenceBrokerTemplate().getObjectByQuery( + query); + // return page or throw exception - if (page == null) - { - throw new PageNotFoundException("Page " + path + " not found."); - } + if (page == null) { throw new PageNotFoundException("Page " + path + + " not found."); } // check for view access on page page.checkAccess(JetspeedActions.VIEW); @@ -496,19 +582,25 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getContentPage(java.lang.String) */ - public ContentPage getContentPage(String path) throws PageNotFoundException, NodeException + public ContentPage getContentPage(String path) + throws PageNotFoundException, NodeException { // return proxied page return new ContentPageImpl(getPage(path)); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getLink(java.lang.String) */ - public Link getLink(String path) throws DocumentNotFoundException, NodeException + public Link getLink(String path) throws DocumentNotFoundException, + NodeException { // construct link attributes from path path = NodeImpl.getCanonicalNodePath(path); @@ -520,7 +612,7 @@ // check for view access on link cachedNode.checkAccess(JetspeedActions.VIEW); - return (Link)cachedNode; + return (Link) cachedNode; } // retrieve link from database @@ -528,14 +620,14 @@ { Criteria filter = new Criteria(); filter.addEqualTo("path", path); - QueryByCriteria query = QueryFactory.newQuery(LinkImpl.class, filter); - Link link = (Link)getPersistenceBrokerTemplate().getObjectByQuery(query); - + QueryByCriteria query = QueryFactory.newQuery(LinkImpl.class, + filter); + Link link = (Link) getPersistenceBrokerTemplate().getObjectByQuery( + query); + // return link or throw exception - if (link == null) - { - throw new DocumentNotFoundException("Link " + path + " not found."); - } + if (link == null) { throw new DocumentNotFoundException("Link " + + path + " not found."); } // check for view access on link link.checkAccess(JetspeedActions.VIEW); @@ -552,36 +644,39 @@ } catch (Exception e) { - throw new DocumentNotFoundException("Link " + path + " not found.", e); + throw new DocumentNotFoundException("Link " + path + " not found.", + e); } } /** - * Given a securityConstraintName definition and a set of actions, - * run a security constraint checks + * Given a securityConstraintName definition and a set of actions, run a + * security constraint checks */ public boolean checkConstraint(String securityConstraintName, String actions) { try { PageSecurity security = this.getPageSecurity(); - SecurityConstraintsDef def = security.getSecurityConstraintsDef(securityConstraintName); - if (def != null) - { - return PageManagerSecurityUtils.checkConstraint(def, actions); - } + SecurityConstraintsDef def = security + .getSecurityConstraintsDef(securityConstraintName); + if (def != null) { return PageManagerSecurityUtils.checkConstraint( + def, actions); } } - catch(Exception e) + catch (Exception e) { e.printStackTrace(); - } + } return false; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getPageSecurity() */ - public PageSecurity getPageSecurity() throws DocumentNotFoundException, NodeException + public PageSecurity getPageSecurity() throws DocumentNotFoundException, + NodeException { // construct document attributes from path String path = Folder.PATH_SEPARATOR + PageSecurity.DOCUMENT_TYPE; @@ -593,7 +688,7 @@ // check for view access on document cachedNode.checkAccess(JetspeedActions.VIEW); - return (PageSecurity)cachedNode; + return (PageSecurity) cachedNode; } // retrieve document from database @@ -601,14 +696,14 @@ { Criteria filter = new Criteria(); filter.addEqualTo("path", path); - QueryByCriteria query = QueryFactory.newQuery(PageSecurityImpl.class, filter); - PageSecurity document = (PageSecurity)getPersistenceBrokerTemplate().getObjectByQuery(query); - + QueryByCriteria query = QueryFactory.newQuery( + PageSecurityImpl.class, filter); + PageSecurity document = (PageSecurity) getPersistenceBrokerTemplate() + .getObjectByQuery(query); + // return page or throw exception - if (document == null) - { - throw new DocumentNotFoundException("Document " + path + " not found."); - } + if (document == null) { throw new DocumentNotFoundException( + "Document " + path + " not found."); } // check for view access on document document.checkAccess(JetspeedActions.VIEW); @@ -625,14 +720,18 @@ } catch (Exception e) { - throw new DocumentNotFoundException("Document " + path + " not found.", e); + throw new DocumentNotFoundException("Document " + path + + " not found.", e); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getFolder(java.lang.String) */ - public Folder getFolder(String folderPath) throws FolderNotFoundException, InvalidFolderException, NodeException + public Folder getFolder(String folderPath) throws FolderNotFoundException, + InvalidFolderException, NodeException { // construct folder attributes from path folderPath = NodeImpl.getCanonicalNodePath(folderPath); @@ -644,7 +743,7 @@ // check for view access on folder cachedNode.checkAccess(JetspeedActions.VIEW); - return (Folder)cachedNode; + return (Folder) cachedNode; } // retrieve folder from database @@ -652,14 +751,14 @@ { Criteria filter = new Criteria(); filter.addEqualTo("path", folderPath); - QueryByCriteria query = QueryFactory.newQuery(FolderImpl.class, filter); - Folder folder = (Folder)getPersistenceBrokerTemplate().getObjectByQuery(query); - + QueryByCriteria query = QueryFactory.newQuery(FolderImpl.class, + filter); + Folder folder = (Folder) getPersistenceBrokerTemplate() + .getObjectByQuery(query); + // return folder or throw exception - if (folder == null) - { - throw new FolderNotFoundException("Folder " + folderPath + " not found."); - } + if (folder == null) { throw new FolderNotFoundException("Folder " + + folderPath + " not found."); } // check for view access on folder folder.checkAccess(JetspeedActions.VIEW); @@ -676,16 +775,19 @@ } catch (Exception e) { - throw new FolderNotFoundException("Folder " + folderPath + " not found.", e); + throw new FolderNotFoundException("Folder " + folderPath + + " not found.", e); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getFolders(org.apache.jetspeed.om.folder.Folder) */ public NodeSet getFolders(Folder folder) throws DocumentException { - FolderImpl folderImpl = (FolderImpl)folder; + FolderImpl folderImpl = (FolderImpl) folder; // perform lookup of folder folders collection and cache in folder try @@ -693,8 +795,10 @@ // query for folders Criteria filter = new Criteria(); filter.addEqualTo("parent", Integer.valueOf(folderImpl.getId())); - QueryByCriteria query = QueryFactory.newQuery(FolderImpl.class, filter); - Collection folders = getPersistenceBrokerTemplate().getCollectionByQuery(query); + QueryByCriteria query = QueryFactory.newQuery(FolderImpl.class, + filter); + Collection folders = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); // cache folders in folder folderImpl.accessFolders().clear(); @@ -708,7 +812,8 @@ { // reset cache in folder folderImpl.resetFolders(false); - throw new DocumentException("Unable to access folders for folder " + folder.getPath() + "."); + throw new DocumentException("Unable to access folders for folder " + + folder.getPath() + "."); } // folder folders cache populated, get folders from folder @@ -716,10 +821,13 @@ return folder.getFolders(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getFolder(org.apache.jetspeed.om.folder.Folder,java.lang.String) */ - public Folder getFolder(Folder folder, String name) throws FolderNotFoundException, DocumentException + public Folder getFolder(Folder folder, String name) + throws FolderNotFoundException, DocumentException { // perform lookup by path so that cache can be used String folderPath = folder.getPath() + Folder.PATH_SEPARATOR + name; @@ -733,16 +841,19 @@ } catch (Exception e) { - throw new FolderNotFoundException("Folder " + folderPath + " not found.", e); + throw new FolderNotFoundException("Folder " + folderPath + + " not found.", e); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getPages(org.apache.jetspeed.om.folder.Folder) */ public NodeSet getPages(Folder folder) throws NodeException { - FolderImpl folderImpl = (FolderImpl)folder; + FolderImpl folderImpl = (FolderImpl) folder; // perform lookup of folder pages collection and cache in folder try @@ -750,8 +861,10 @@ // query for pages Criteria filter = new Criteria(); filter.addEqualTo("parent", Integer.valueOf(folderImpl.getId())); - QueryByCriteria query = QueryFactory.newQuery(PageImpl.class, filter); - Collection pages = getPersistenceBrokerTemplate().getCollectionByQuery(query); + QueryByCriteria query = QueryFactory.newQuery(PageImpl.class, + filter); + Collection pages = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); // cache pages in folder folderImpl.accessPages().clear(); @@ -765,18 +878,22 @@ { // reset cache in folder folderImpl.resetPages(false); - throw new NodeException("Unable to access pages for folder " + folder.getPath() + "."); + throw new NodeException("Unable to access pages for folder " + + folder.getPath() + "."); } // folder pages cache populated, get pages from folder // to provide packaging as filtered node set return folder.getPages(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getPage(org.apache.jetspeed.om.folder.Folder,java.lang.String) */ - public Page getPage(Folder folder, String name) throws PageNotFoundException, NodeException + public Page getPage(Folder folder, String name) + throws PageNotFoundException, NodeException { // perform lookup by path so that cache can be used String pagePath = folder.getPath() + Folder.PATH_SEPARATOR + name; @@ -790,16 +907,19 @@ } catch (Exception e) { - throw new PageNotFoundException("Page " + pagePath + " not found.", e); + throw new PageNotFoundException("Page " + pagePath + " not found.", + e); } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getLinks(org.apache.jetspeed.om.folder.Folder) - */ + */ public NodeSet getLinks(Folder folder) throws NodeException { - FolderImpl folderImpl = (FolderImpl)folder; + FolderImpl folderImpl = (FolderImpl) folder; // perform lookup of folder links collection and cache in folder try @@ -807,8 +927,10 @@ // query for links Criteria filter = new Criteria(); filter.addEqualTo("parent", Integer.valueOf(folderImpl.getId())); - QueryByCriteria query = QueryFactory.newQuery(LinkImpl.class, filter); - Collection links = getPersistenceBrokerTemplate().getCollectionByQuery(query); + QueryByCriteria query = QueryFactory.newQuery(LinkImpl.class, + filter); + Collection links = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); // cache links in folder folderImpl.accessLinks().clear(); @@ -822,18 +944,22 @@ { // reset cache in folder folderImpl.resetLinks(false); - throw new NodeException("Unable to access links for folder " + folder.getPath() + "."); + throw new NodeException("Unable to access links for folder " + + folder.getPath() + "."); } // folder links cache populated, get links from folder // to provide packaging as filtered node set return folder.getLinks(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getLink(org.apache.jetspeed.om.folder.Folder,java.lang.String) - */ - public Link getLink(Folder folder, String name) throws DocumentNotFoundException, NodeException + */ + public Link getLink(Folder folder, String name) + throws DocumentNotFoundException, NodeException { // perform lookup by path so that cache can be used String linkPath = folder.getPath() + Folder.PATH_SEPARATOR + name; @@ -847,16 +973,20 @@ } catch (Exception e) { - throw new DocumentNotFoundException("Link " + linkPath + " not found.", e); + throw new DocumentNotFoundException("Link " + linkPath + + " not found.", e); } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getPageSecurity(org.apache.jetspeed.om.folder.Folder) - */ - public PageSecurity getPageSecurity(Folder folder) throws DocumentNotFoundException, NodeException + */ + public PageSecurity getPageSecurity(Folder folder) + throws DocumentNotFoundException, NodeException { - FolderImpl folderImpl = (FolderImpl)folder; + FolderImpl folderImpl = (FolderImpl) folder; // perform lookup of page security document and cache // in folder; limit lookup to root folder since page @@ -868,18 +998,24 @@ { // query for page security Criteria filter = new Criteria(); - filter.addEqualTo("parent", Integer.valueOf(folderImpl.getId())); - QueryByCriteria query = QueryFactory.newQuery(PageSecurityImpl.class, filter); - PageSecurity document = (PageSecurity)getPersistenceBrokerTemplate().getObjectByQuery(query); + filter + .addEqualTo("parent", Integer.valueOf(folderImpl + .getId())); + QueryByCriteria query = QueryFactory.newQuery( + PageSecurityImpl.class, filter); + PageSecurity document = (PageSecurity) getPersistenceBrokerTemplate() + .getObjectByQuery(query); // cache page security in folder - folderImpl.resetPageSecurity((PageSecurityImpl)document, true); + folderImpl.resetPageSecurity((PageSecurityImpl) document, true); } catch (Exception e) { // reset page security in folder folderImpl.resetPageSecurity(null, true); - throw new NodeException("Unable to access page security for folder " + folder.getPath() + "."); + throw new NodeException( + "Unable to access page security for folder " + + folder.getPath() + "."); } } else @@ -893,12 +1029,14 @@ return folder.getPageSecurity(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getAll(org.apache.jetspeed.om.folder.Folder) */ public NodeSet getAll(Folder folder) throws DocumentException { - FolderImpl folderImpl = (FolderImpl)folder; + FolderImpl folderImpl = (FolderImpl) folder; // perform lookup of folder nodes collection and cache in folder try @@ -907,26 +1045,31 @@ List all = DatabasePageManagerUtils.createList(); Criteria filter = new Criteria(); filter.addEqualTo("parent", Integer.valueOf(folderImpl.getId())); - QueryByCriteria query = QueryFactory.newQuery(FolderImpl.class, filter); - Collection folders = getPersistenceBrokerTemplate().getCollectionByQuery(query); + QueryByCriteria query = QueryFactory.newQuery(FolderImpl.class, + filter); + Collection folders = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); if (folders != null) { all.addAll(folders); } query = QueryFactory.newQuery(PageImpl.class, filter); - Collection pages = getPersistenceBrokerTemplate().getCollectionByQuery(query); + Collection pages = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); if (pages != null) { all.addAll(pages); } query = QueryFactory.newQuery(LinkImpl.class, filter); - Collection links = getPersistenceBrokerTemplate().getCollectionByQuery(query); + Collection links = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); if (links != null) { all.addAll(links); } query = QueryFactory.newQuery(PageSecurityImpl.class, filter); - PageSecurity document = (PageSecurity)getPersistenceBrokerTemplate().getObjectByQuery(query); + PageSecurity document = (PageSecurity) getPersistenceBrokerTemplate() + .getObjectByQuery(query); if (document != null) { all.add(document); @@ -941,7 +1084,9 @@ { // reset cache in folder folderImpl.resetAll(false); - throw new DocumentException("Unable to access all nodes for folder " + folder.getPath() + "."); + throw new DocumentException( + "Unable to access all nodes for folder " + folder.getPath() + + "."); } // folder all nodes cache populated, get all from folder @@ -949,40 +1094,45 @@ return folder.getAll(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#updatePage(org.apache.jetspeed.om.page.Page) */ - public void updatePage(Page page) throws NodeException, PageNotUpdatedException + public void updatePage(Page page) throws NodeException, + PageNotUpdatedException { try { // dereference page in case proxy is supplied if (page instanceof ContentPageImpl) { - page = ((ContentPageImpl)page).getPage(); + page = ((ContentPageImpl) page).getPage(); } - page = (Page)ProxyHelper.getRealObject(page); + page = (Page) ProxyHelper.getRealObject(page); // look up and set parent folder if necessary - FolderImpl parent = (FolderImpl)page.getParent(); + FolderImpl parent = (FolderImpl) page.getParent(); if (parent == null) { // access folder by path String pagePath = page.getPath(); - String parentPath = pagePath.substring(0, pagePath.lastIndexOf(Folder.PATH_SEPARATOR)); + String parentPath = pagePath.substring(0, pagePath + .lastIndexOf(Folder.PATH_SEPARATOR)); if (parentPath.length() == 0) { parentPath = Folder.PATH_SEPARATOR; } try { - parent = (FolderImpl)getFolder(parentPath); + parent = (FolderImpl) getFolder(parentPath); } catch (FolderNotFoundException fnfe) { - throw new PageNotUpdatedException("Missing parent folder: " + parentPath); + throw new PageNotUpdatedException("Missing parent folder: " + + parentPath); } - + // check for edit access on parent folder; page // access not checked on create parent.checkAccess(JetspeedActions.EDIT); @@ -990,7 +1140,10 @@ // update page and mark cache transaction page.setParent(parent); getPersistenceBrokerTemplate().store(page); - DatabasePageManagerCache.addTransaction(new TransactionedOperation(page.getPath(), TransactionedOperation.ADD_OPERATION)); + DatabasePageManagerCache + .addTransaction(new TransactionedOperation(page + .getPath(), + TransactionedOperation.ADD_OPERATION)); // reset parent folder pages cache if (parent != null) @@ -1008,8 +1161,11 @@ // update page and mark cache transaction getPersistenceBrokerTemplate().store(page); - DatabasePageManagerCache.addTransaction(new TransactionedOperation(page.getPath(), TransactionedOperation.UPDATE_OPERATION)); - + DatabasePageManagerCache + .addTransaction(new TransactionedOperation(page + .getPath(), + TransactionedOperation.UPDATE_OPERATION)); + // reset parent folder pages cache in case // parent is holding an out of date copy of // this page that was removed from the cache @@ -1033,23 +1189,27 @@ } catch (Exception e) { - throw new PageNotUpdatedException("Page " + page.getPath() + " not updated.", e); - } + throw new PageNotUpdatedException("Page " + page.getPath() + + " not updated.", e); + } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#removePage(org.apache.jetspeed.om.page.Page) */ - public void removePage(Page page) throws NodeException, PageNotRemovedException + public void removePage(Page page) throws NodeException, + PageNotRemovedException { try { // dereference page in case proxy is supplied if (page instanceof ContentPageImpl) { - page = ((ContentPageImpl)page).getPage(); + page = ((ContentPageImpl) page).getPage(); } - page = (Page)ProxyHelper.getRealObject(page); + page = (Page) ProxyHelper.getRealObject(page); // check for edit access on page and parent folder page.checkAccess(JetspeedActions.EDIT); @@ -1057,11 +1217,12 @@ // look up and update parent folder if necessary if (page.getParent() != null) { - FolderImpl parent = (FolderImpl)ProxyHelper.getRealObject(page.getParent()); - + FolderImpl parent = (FolderImpl) ProxyHelper.getRealObject(page + .getParent()); + // delete page getPersistenceBrokerTemplate().delete(page); - + // reset parent folder pages cache if (parent != null) { @@ -1083,49 +1244,59 @@ } catch (Exception e) { - throw new PageNotRemovedException("Page " + page.getPath() + " not removed.", e); + throw new PageNotRemovedException("Page " + page.getPath() + + " not removed.", e); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#updateFolder(org.apache.jetspeed.om.folder.Folder) */ - public void updateFolder(Folder folder) throws NodeException, FolderNotUpdatedException + public void updateFolder(Folder folder) throws NodeException, + FolderNotUpdatedException { // shallow update by default updateFolder(folder, false); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#updateFolder(org.apache.jetspeed.om.folder.Folder,boolean) */ - public void updateFolder(Folder folder, boolean deep) throws NodeException, FolderNotUpdatedException + public void updateFolder(Folder folder, boolean deep) throws NodeException, + FolderNotUpdatedException { try { // dereference folder in case proxy is supplied - folder = (Folder)ProxyHelper.getRealObject(folder); + folder = (Folder) ProxyHelper.getRealObject(folder); // look up and set parent folder if required - FolderImpl parent = (FolderImpl)folder.getParent(); - if ((parent == null) && !folder.getPath().equals(Folder.PATH_SEPARATOR)) + FolderImpl parent = (FolderImpl) folder.getParent(); + if ((parent == null) + && !folder.getPath().equals(Folder.PATH_SEPARATOR)) { // access folder by path String folderPath = folder.getPath(); - String parentPath = folderPath.substring(0, folderPath.lastIndexOf(Folder.PATH_SEPARATOR)); + String parentPath = folderPath.substring(0, folderPath + .lastIndexOf(Folder.PATH_SEPARATOR)); if (parentPath.length() == 0) { parentPath = Folder.PATH_SEPARATOR; } try { - parent = (FolderImpl)getFolder(parentPath); + parent = (FolderImpl) getFolder(parentPath); } catch (FolderNotFoundException fnfe) { - throw new FolderNotUpdatedException("Missing parent folder: " + parentPath); + throw new FolderNotUpdatedException( + "Missing parent folder: " + parentPath); } - + // check for edit access on parent folder; folder // access not checked on create parent.checkAccess(JetspeedActions.EDIT); @@ -1133,7 +1304,10 @@ // update folder and mark cache transaction folder.setParent(parent); getPersistenceBrokerTemplate().store(folder); - DatabasePageManagerCache.addTransaction(new TransactionedOperation(folder.getPath(), TransactionedOperation.ADD_OPERATION)); + DatabasePageManagerCache + .addTransaction(new TransactionedOperation(folder + .getPath(), + TransactionedOperation.ADD_OPERATION)); // reset parent folder folders cache if (parent != null) @@ -1152,20 +1326,28 @@ // check for edit access on folder and parent folder // if not being initially created; access is not // checked on create - if (!newFolder || !folder.getPath().equals(Folder.PATH_SEPARATOR)) + if (!newFolder + || !folder.getPath().equals(Folder.PATH_SEPARATOR)) { folder.checkAccess(JetspeedActions.EDIT); } - // create root folder or update folder and mark cache transaction + // create root folder or update folder and mark cache + // transaction getPersistenceBrokerTemplate().store(folder); if (newFolder && !folder.getId().equals("0")) { - DatabasePageManagerCache.addTransaction(new TransactionedOperation(folder.getPath(), TransactionedOperation.ADD_OPERATION)); + DatabasePageManagerCache + .addTransaction(new TransactionedOperation(folder + .getPath(), + TransactionedOperation.ADD_OPERATION)); } else { - DatabasePageManagerCache.addTransaction(new TransactionedOperation(folder.getPath(), TransactionedOperation.UPDATE_OPERATION)); + DatabasePageManagerCache + .addTransaction(new TransactionedOperation(folder + .getPath(), + TransactionedOperation.UPDATE_OPERATION)); } // reset parent folder folders cache in case @@ -1192,7 +1374,7 @@ if (deep) { // update recursively, (breadth first) - updateFolderNodes((FolderImpl)folder); + updateFolderNodes((FolderImpl) folder); } } catch (FolderNotUpdatedException fnue) @@ -1205,17 +1387,21 @@ } catch (Exception e) { - throw new FolderNotUpdatedException("Folder " + folder.getPath() + " not updated.", e); + throw new FolderNotUpdatedException("Folder " + folder.getPath() + + " not updated.", e); } } /** * updateFolderNodes - recusively update all folder nodes - * - * @param folderImpl folder whose nodes are to be updated - * @param throws FolderNotUpdatedException + * + * @param folderImpl + * folder whose nodes are to be updated + * @param throws + * FolderNotUpdatedException */ - private void updateFolderNodes(FolderImpl folderImpl) throws FolderNotUpdatedException + private void updateFolderNodes(FolderImpl folderImpl) + throws FolderNotUpdatedException { try { @@ -1224,32 +1410,36 @@ filter.addEqualTo("parent", Integer.valueOf(folderImpl.getId())); // update pages - QueryByCriteria query = QueryFactory.newQuery(PageImpl.class, filter); - Collection pages = getPersistenceBrokerTemplate().getCollectionByQuery(query); + QueryByCriteria query = QueryFactory.newQuery(PageImpl.class, + filter); + Collection pages = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); if (pages != null) { Iterator pagesIter = pages.iterator(); while (pagesIter.hasNext()) { - updatePage((Page)pagesIter.next()); + updatePage((Page) pagesIter.next()); } } // update links query = QueryFactory.newQuery(LinkImpl.class, filter); - Collection links = getPersistenceBrokerTemplate().getCollectionByQuery(query); + Collection links = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); if (links != null) { Iterator linksIter = links.iterator(); while (linksIter.hasNext()) { - updateLink((Link)linksIter.next()); + updateLink((Link) linksIter.next()); } } // update page security query = QueryFactory.newQuery(PageSecurityImpl.class, filter); - PageSecurity document = (PageSecurity)getPersistenceBrokerTemplate().getObjectByQuery(query); + PageSecurity document = (PageSecurity) getPersistenceBrokerTemplate() + .getObjectByQuery(query); if (document != null) { updatePageSecurity(document); @@ -1257,13 +1447,14 @@ // update folders last: breadth first recursion query = QueryFactory.newQuery(FolderImpl.class, filter); - Collection folders = getPersistenceBrokerTemplate().getCollectionByQuery(query); + Collection folders = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); if (folders != null) { Iterator foldersIter = folders.iterator(); while (foldersIter.hasNext()) { - updateFolder((Folder)foldersIter.next(), true); + updateFolder((Folder) foldersIter.next(), true); } } } @@ -1277,33 +1468,38 @@ } catch (Exception e) { - throw new FolderNotUpdatedException("Folder " + folderImpl.getPath() + " not updated.", e); + throw new FolderNotUpdatedException("Folder " + + folderImpl.getPath() + " not updated.", e); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#removeFolder(org.apache.jetspeed.om.folder.Folder) */ - public void removeFolder(Folder folder) throws NodeException, FolderNotRemovedException + public void removeFolder(Folder folder) throws NodeException, + FolderNotRemovedException { try { // dereference folder in case proxy is supplied - folder = (Folder)ProxyHelper.getRealObject(folder); + folder = (Folder) ProxyHelper.getRealObject(folder); // check for edit access on folder and parent folder folder.checkAccess(JetspeedActions.EDIT); // reset folder nodes cache - ((FolderImpl)folder).resetAll(false); + ((FolderImpl) folder).resetAll(false); // remove recursively, (depth first) - removeFolderNodes((FolderImpl)folder); + removeFolderNodes((FolderImpl) folder); // look up and update parent folder if necessary if (folder.getParent() != null) { - FolderImpl parent = (FolderImpl)ProxyHelper.getRealObject(folder.getParent()); + FolderImpl parent = (FolderImpl) ProxyHelper + .getRealObject(folder.getParent()); // delete folder getPersistenceBrokerTemplate().delete(folder); @@ -1321,7 +1517,7 @@ } // notify page manager listeners - delegator.notifyRemovedNode((FolderImpl)folder); + delegator.notifyRemovedNode((FolderImpl) folder); } catch (SecurityException se) { @@ -1329,17 +1525,21 @@ } catch (Exception e) { - throw new FolderNotRemovedException("Folder " + folder.getPath() + " not removed.", e); + throw new FolderNotRemovedException("Folder " + folder.getPath() + + " not removed.", e); } } /** * removeFolderNodes - recusively remove all folder nodes - * - * @param folderImpl folder whose nodes are to be removed - * @param throws FolderNotRemovedException + * + * @param folderImpl + * folder whose nodes are to be removed + * @param throws + * FolderNotRemovedException */ - private void removeFolderNodes(FolderImpl folderImpl) throws FolderNotRemovedException + private void removeFolderNodes(FolderImpl folderImpl) + throws FolderNotRemovedException { try { @@ -1348,44 +1548,49 @@ filter.addEqualTo("parent", Integer.valueOf(folderImpl.getId())); // remove folders first: depth first recursion - QueryByCriteria query = QueryFactory.newQuery(FolderImpl.class, filter); - Collection folders = getPersistenceBrokerTemplate().getCollectionByQuery(query); + QueryByCriteria query = QueryFactory.newQuery(FolderImpl.class, + filter); + Collection folders = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); if (folders != null) { Iterator foldersIter = folders.iterator(); while (foldersIter.hasNext()) { - removeFolder((Folder)foldersIter.next()); + removeFolder((Folder) foldersIter.next()); } } // remove pages query = QueryFactory.newQuery(PageImpl.class, filter); - Collection pages = getPersistenceBrokerTemplate().getCollectionByQuery(query); + Collection pages = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); if (pages != null) { Iterator pagesIter = pages.iterator(); while (pagesIter.hasNext()) { - removePage((Page)pagesIter.next()); + removePage((Page) pagesIter.next()); } } // remove links query = QueryFactory.newQuery(LinkImpl.class, filter); - Collection links = getPersistenceBrokerTemplate().getCollectionByQuery(query); + Collection links = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); if (links != null) { Iterator linksIter = links.iterator(); while (linksIter.hasNext()) { - removeLink((Link)linksIter.next()); + removeLink((Link) linksIter.next()); } } // remove page security query = QueryFactory.newQuery(PageSecurityImpl.class, filter); - PageSecurity document = (PageSecurity)getPersistenceBrokerTemplate().getObjectByQuery(query); + PageSecurity document = (PageSecurity) getPersistenceBrokerTemplate() + .getObjectByQuery(query); if (document != null) { removePageSecurity(document); @@ -1401,40 +1606,46 @@ } catch (Exception e) { - throw new FolderNotRemovedException("Folder " + folderImpl.getPath() + " not removed.", e); + throw new FolderNotRemovedException("Folder " + + folderImpl.getPath() + " not removed.", e); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#updateLink(org.apache.jetspeed.om.page.Link) */ - public void updateLink(Link link) throws NodeException, LinkNotUpdatedException + public void updateLink(Link link) throws NodeException, + LinkNotUpdatedException { try { // dereference link in case proxy is supplied - link = (Link)ProxyHelper.getRealObject(link); + link = (Link) ProxyHelper.getRealObject(link); // look up and set parent folder if necessary - FolderImpl parent = (FolderImpl)link.getParent(); + FolderImpl parent = (FolderImpl) link.getParent(); if (parent == null) { // access folder by path String linkPath = link.getPath(); - String parentPath = linkPath.substring(0, linkPath.lastIndexOf(Folder.PATH_SEPARATOR)); + String parentPath = linkPath.substring(0, linkPath + .lastIndexOf(Folder.PATH_SEPARATOR)); if (parentPath.length() == 0) { parentPath = Folder.PATH_SEPARATOR; } try { - parent = (FolderImpl)getFolder(parentPath); + parent = (FolderImpl) getFolder(parentPath); } catch (FolderNotFoundException fnfe) { - throw new FailedToUpdateDocumentException("Missing parent folder: " + parentPath); + throw new FailedToUpdateDocumentException( + "Missing parent folder: " + parentPath); } - + // check for edit access on parent folder; link // access not checked on create parent.checkAccess(JetspeedActions.EDIT); @@ -1442,7 +1653,10 @@ // update link and mark cache transaction link.setParent(parent); getPersistenceBrokerTemplate().store(link); - DatabasePageManagerCache.addTransaction(new TransactionedOperation(link.getPath(), TransactionedOperation.ADD_OPERATION)); + DatabasePageManagerCache + .addTransaction(new TransactionedOperation(link + .getPath(), + TransactionedOperation.ADD_OPERATION)); // reset parent folder links cache if (parent != null) @@ -1460,7 +1674,10 @@ // update link and mark cache transaction getPersistenceBrokerTemplate().store(link); - DatabasePageManagerCache.addTransaction(new TransactionedOperation(link.getPath(), TransactionedOperation.UPDATE_OPERATION)); + DatabasePageManagerCache + .addTransaction(new TransactionedOperation(link + .getPath(), + TransactionedOperation.UPDATE_OPERATION)); // reset parent folder links cache in case // parent is holding an out of date copy of @@ -1485,19 +1702,23 @@ } catch (Exception e) { - throw new FailedToUpdateDocumentException("Link " + link.getPath() + " not updated.", e); + throw new FailedToUpdateDocumentException("Link " + link.getPath() + + " not updated.", e); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#removeLink(org.apache.jetspeed.om.page.Link) */ - public void removeLink(Link link) throws NodeException, LinkNotRemovedException + public void removeLink(Link link) throws NodeException, + LinkNotRemovedException { try { // dereference link in case proxy is supplied - link = (Link)ProxyHelper.getRealObject(link); + link = (Link) ProxyHelper.getRealObject(link); // check for edit access on link and parent folder link.checkAccess(JetspeedActions.EDIT); @@ -1505,14 +1726,15 @@ // look up and update parent folder if necessary if (link.getParent() != null) { - FolderImpl parent = (FolderImpl)ProxyHelper.getRealObject(link.getParent()); + FolderImpl parent = (FolderImpl) ProxyHelper.getRealObject(link + .getParent()); // delete link getPersistenceBrokerTemplate().delete(link); // reset parent folder links cache if (parent != null) - { + { parent.resetLinks(false); } } @@ -1531,66 +1753,79 @@ } catch (Exception e) { - throw new FailedToDeleteDocumentException("Link " + link.getPath() + " not removed.", e); + throw new FailedToDeleteDocumentException("Link " + link.getPath() + + " not removed.", e); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#updatePageSecurity(org.apache.jetspeed.om.page.PageSecurity) */ - public void updatePageSecurity(PageSecurity pageSecurity) throws NodeException, FailedToUpdateDocumentException + public void updatePageSecurity(PageSecurity pageSecurity) + throws NodeException, FailedToUpdateDocumentException { try { // dereference document in case proxy is supplied - pageSecurity = (PageSecurity)ProxyHelper.getRealObject(pageSecurity); + pageSecurity = (PageSecurity) ProxyHelper + .getRealObject(pageSecurity); // look up and set parent folder if necessary - FolderImpl parent = (FolderImpl)pageSecurity.getParent(); + FolderImpl parent = (FolderImpl) pageSecurity.getParent(); if (parent == null) { // access folder by path String pageSecurityPath = pageSecurity.getPath(); - String parentPath = pageSecurityPath.substring(0, pageSecurityPath.lastIndexOf(Folder.PATH_SEPARATOR)); + String parentPath = pageSecurityPath.substring(0, + pageSecurityPath.lastIndexOf(Folder.PATH_SEPARATOR)); if (parentPath.length() == 0) { parentPath = Folder.PATH_SEPARATOR; } try { - parent = (FolderImpl)getFolder(parentPath); + parent = (FolderImpl) getFolder(parentPath); } catch (FolderNotFoundException fnfe) { - throw new FailedToUpdateDocumentException("Missing parent folder: " + parentPath); + throw new FailedToUpdateDocumentException( + "Missing parent folder: " + parentPath); } // do not replace existing page security documents try { parent.getPageSecurity(); - throw new FailedToUpdateDocumentException("Parent folder page security exists: " + parentPath); + throw new FailedToUpdateDocumentException( + "Parent folder page security exists: " + parentPath); } catch (DocumentNotFoundException dnfe) { // check for edit access on parent folder; document // access not checked on create parent.checkAccess(JetspeedActions.EDIT); - + // update document and mark cache transaction pageSecurity.setParent(parent); getPersistenceBrokerTemplate().store(pageSecurity); - DatabasePageManagerCache.addTransaction(new TransactionedOperation(pageSecurity.getPath(), TransactionedOperation.ADD_OPERATION)); + DatabasePageManagerCache + .addTransaction(new TransactionedOperation( + pageSecurity.getPath(), + TransactionedOperation.ADD_OPERATION)); // reset parent folder page security cache if (parent != null) - { - parent.resetPageSecurity((PageSecurityImpl)pageSecurity, true); + { + parent.resetPageSecurity( + (PageSecurityImpl) pageSecurity, true); } } catch (Exception e) { - throw new FailedToUpdateDocumentException("Parent folder page security exists: " + parentPath); + throw new FailedToUpdateDocumentException( + "Parent folder page security exists: " + parentPath); } // notify page manager listeners @@ -1603,15 +1838,19 @@ // update document and mark cache transaction getPersistenceBrokerTemplate().store(pageSecurity); - DatabasePageManagerCache.addTransaction(new TransactionedOperation(pageSecurity.getPath(), TransactionedOperation.UPDATE_OPERATION)); + DatabasePageManagerCache + .addTransaction(new TransactionedOperation(pageSecurity + .getPath(), + TransactionedOperation.UPDATE_OPERATION)); // reset parent folder page security cache in case // parent is holding an out of date copy of this // page security that was removed from the cache // before this one was accessed if (parent != null) - { - parent.resetPageSecurity((PageSecurityImpl)pageSecurity, true); + { + parent.resetPageSecurity((PageSecurityImpl) pageSecurity, + true); } // notify page manager listeners @@ -1631,19 +1870,24 @@ } catch (Exception e) { - throw new FailedToUpdateDocumentException("Document " + pageSecurity.getPath() + " not updated.", e); + throw new FailedToUpdateDocumentException("Document " + + pageSecurity.getPath() + " not updated.", e); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#removePageSecurity(org.apache.jetspeed.om.page.PageSecurity) */ - public void removePageSecurity(PageSecurity pageSecurity) throws NodeException, FailedToDeleteDocumentException + public void removePageSecurity(PageSecurity pageSecurity) + throws NodeException, FailedToDeleteDocumentException { try { // dereference document in case proxy is supplied - pageSecurity = (PageSecurity)ProxyHelper.getRealObject(pageSecurity); + pageSecurity = (PageSecurity) ProxyHelper + .getRealObject(pageSecurity); // check for edit access on document and parent folder pageSecurity.checkAccess(JetspeedActions.EDIT); @@ -1651,14 +1895,15 @@ // look up and update parent folder if necessary if (pageSecurity.getParent() != null) { - FolderImpl parent = (FolderImpl)ProxyHelper.getRealObject(pageSecurity.getParent()); + FolderImpl parent = (FolderImpl) ProxyHelper + .getRealObject(pageSecurity.getParent()); // delete document getPersistenceBrokerTemplate().delete(pageSecurity); // reset parent folder page security cache if (parent != null) - { + { parent.resetPageSecurity(null, true); } } @@ -1680,74 +1925,93 @@ } catch (Exception e) { - throw new FailedToDeleteDocumentException("Document " + pageSecurity.getPath() + " not removed.", e); + throw new FailedToDeleteDocumentException("Document " + + pageSecurity.getPath() + " not removed.", e); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#copyPage(org.apache.jetspeed.om.page.Page,java.lang.String) */ - public Page copyPage(Page source, String path) - throws NodeException, PageNotUpdatedException + public Page copyPage(Page source, String path) throws NodeException, + PageNotUpdatedException { return this.delegator.copyPage(source, path); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#copyLink(org.apache.jetspeed.om.page.Link,java.lang.String) */ - public Link copyLink(Link source, String path) - throws NodeException, LinkNotUpdatedException + public Link copyLink(Link source, String path) throws NodeException, + LinkNotUpdatedException { return this.delegator.copyLink(source, path); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#copyFolder(org.apache.jetspeed.om.folder.Folder,java.lang.String) */ - public Folder copyFolder(Folder source, String path) - throws NodeException, PageNotUpdatedException + public Folder copyFolder(Folder source, String path) throws NodeException, + PageNotUpdatedException { return this.delegator.copyFolder(source, path); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#copyFragment(org.apache.jetspeed.om.page.Fragment,java.lang.String) */ public Fragment copyFragment(Fragment source, String name) - throws NodeException, PageNotUpdatedException + throws NodeException, PageNotUpdatedException { return this.delegator.copyFragment(source, name); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#copyPageSecurity(org.apache.jetspeed.om.page.PageSecurity) */ - public PageSecurity copyPageSecurity(PageSecurity source) - throws NodeException + public PageSecurity copyPageSecurity(PageSecurity source) + throws NodeException { return this.delegator.copyPageSecurity(source); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getUserPage(java.lang.String,java.lang.String) */ public Page getUserPage(String userName, String pageName) - throws PageNotFoundException, NodeException + throws PageNotFoundException, NodeException { - return this.getPage(Folder.USER_FOLDER + userName + Folder.PATH_SEPARATOR + pageName); + return this.getPage(Folder.USER_FOLDER + userName + + Folder.PATH_SEPARATOR + pageName); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getUserFolder(java.lang.String) */ - public Folder getUserFolder(String userName) - throws FolderNotFoundException, InvalidFolderException, NodeException + public Folder getUserFolder(String userName) + throws FolderNotFoundException, InvalidFolderException, + NodeException { - return this.getFolder(Folder.USER_FOLDER + userName); + return this.getFolder(Folder.USER_FOLDER + userName); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#folderExists(java.lang.String) */ public boolean folderExists(String folderName) @@ -1763,7 +2027,9 @@ return true; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#pageExists(java.lang.String) */ public boolean pageExists(String pageName) @@ -1778,8 +2044,10 @@ } return true; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#linkExists(java.lang.String) */ public boolean linkExists(String linkName) @@ -1795,7 +2063,9 @@ return true; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#userFolderExists(java.lang.String) */ public boolean userFolderExists(String userName) @@ -1810,15 +2080,18 @@ } return true; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#userPageExists(java.lang.String) */ public boolean userPageExists(String userName, String pageName) { try { - getPage(Folder.USER_FOLDER + userName + Folder.PATH_SEPARATOR + pageName); + getPage(Folder.USER_FOLDER + userName + Folder.PATH_SEPARATOR + + pageName); } catch (Exception e) { @@ -1826,31 +2099,37 @@ } return true; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#createUserHomePagesFromRoles(java.security.auth.Subject) */ public void createUserHomePagesFromRoles(Subject subject) - throws NodeException + throws NodeException { PageManagerUtils.createUserHomePagesFromRoles(this, subject); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#deepCopyFolder(org.apache.jetspeed.om.folder.Folder,java.lang.String,java.lang.String) */ - public void deepCopyFolder(Folder srcFolder, String destinationPath, String owner) - throws NodeException, PageNotUpdatedException + public void deepCopyFolder(Folder srcFolder, String destinationPath, + String owner) throws NodeException, PageNotUpdatedException { - PageManagerUtils.deepCopyFolder(this, srcFolder, destinationPath, owner); + PageManagerUtils + .deepCopyFolder(this, srcFolder, destinationPath, owner); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#addPages(org.apache.jetspeed.om.page.Page[]) */ - public int addPages(Page[] pages) - throws NodeException - { + public int addPages(Page[] pages) throws NodeException + { if (pages.length > 0 && pages[0].getPath().equals("/tx__test1.psml")) { // for tx testing @@ -1867,5 +2146,5 @@ } return pages.length; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/DatabasePageManagerUtils.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/DatabasePageManagerUtils.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/DatabasePageManagerUtils.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,7 +24,6 @@ import org.apache.ojb.broker.util.collections.RemovalAwareCollection; import org.apache.ojb.broker.util.collections.RemovalAwareList; - /** * DatabasePageManagerUtils * @@ -33,25 +32,28 @@ */ public class DatabasePageManagerUtils { - protected static Log log = LogFactory.getLog(DatabasePageManagerUtils.class); - + + protected static Log log = LogFactory + .getLog(DatabasePageManagerUtils.class); + /** - * OJB 1.0.3 requires collections to be removal aware. - * Thus we can't seem to get away with just creating ArrayLists - * This issue on occurs when persisting newly create object collections - * When persisting objects retrieved with OJB, this issue does not occur + * OJB 1.0.3 requires collections to be removal aware. Thus we can't seem to + * get away with just creating ArrayLists This issue on occurs when + * persisting newly create object collections When persisting objects + * retrieved with OJB, this issue does not occur * * @see JS2-590 * @return */ public static final Collection createCollection() { - return java.util.Collections.synchronizedCollection(new RemovalAwareCollection()); + return java.util.Collections + .synchronizedCollection(new RemovalAwareCollection()); } - + public static final List createList() { return java.util.Collections.synchronizedList(new RemovalAwareList()); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/TransactionedOperation.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/TransactionedOperation.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/impl/TransactionedOperation.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,48 +16,47 @@ */ package org.apache.jetspeed.page.impl; - /** - * A transactioned operation is a single Page Manager DML operation that was applied - * to the OJB cache. Im finding that OJB is not properly synchronizing its cache - * upon rollback of database transactions. This code may not be needed in future - * versions of OJB which have fixed this bug. + * A transactioned operation is a single Page Manager DML operation that was + * applied to the OJB cache. Im finding that OJB is not properly synchronizing + * its cache upon rollback of database transactions. This code may not be needed + * in future versions of OJB which have fixed this bug. * * @author David Sean Taylor * @version $Id: $ */ -public class TransactionedOperation +public class TransactionedOperation { + public static final int ADD_OPERATION = 0; + public static final int UPDATE_OPERATION = 1; + private String path; + private int transactionType; - + public TransactionedOperation(String path, int type) { this.path = path; this.transactionType = type; } - public String getPath() { return path; } - public void setPath(String path) { this.path = path; } - public int getTransactionType() { return transactionType; } - public void setTransactionType(int transactionType) { this.transactionType = transactionType; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/psml/CastorXmlPageManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/psml/CastorXmlPageManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/page/psml/CastorXmlPageManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -78,10 +78,13 @@ * @author Scott T Weaver * @version $Id: CastorXmlPageManager.java 516448 2007-03-09 16:25:47Z ate $ */ -public class CastorXmlPageManager extends AbstractPageManager implements PageManager, FileCacheEventListener +public class CastorXmlPageManager extends AbstractPageManager implements + PageManager, FileCacheEventListener { - private final static Log log = LogFactory.getLog(CastorXmlPageManager.class); + private final static Log log = LogFactory + .getLog(CastorXmlPageManager.class); + private static Map modelClasses = new HashMap(); static { @@ -91,33 +94,53 @@ modelClasses.put("LinkImpl", LinkImpl.class); modelClasses.put("PageSecurityImpl", PageSecurityImpl.class); modelClasses.put("FolderMenuDefinitionImpl", MenuDefinitionImpl.class); - modelClasses.put("FolderMenuExcludeDefinitionImpl", MenuExcludeDefinitionImpl.class); - modelClasses.put("FolderMenuIncludeDefinitionImpl", MenuIncludeDefinitionImpl.class); - modelClasses.put("FolderMenuOptionsDefinitionImpl", MenuOptionsDefinitionImpl.class); - modelClasses.put("FolderMenuSeparatorDefinitionImpl", MenuSeparatorDefinitionImpl.class); + modelClasses.put("FolderMenuExcludeDefinitionImpl", + MenuExcludeDefinitionImpl.class); + modelClasses.put("FolderMenuIncludeDefinitionImpl", + MenuIncludeDefinitionImpl.class); + modelClasses.put("FolderMenuOptionsDefinitionImpl", + MenuOptionsDefinitionImpl.class); + modelClasses.put("FolderMenuSeparatorDefinitionImpl", + MenuSeparatorDefinitionImpl.class); modelClasses.put("PageMenuDefinitionImpl", MenuDefinitionImpl.class); - modelClasses.put("PageMenuExcludeDefinitionImpl", MenuExcludeDefinitionImpl.class); - modelClasses.put("PageMenuIncludeDefinitionImpl", MenuIncludeDefinitionImpl.class); - modelClasses.put("PageMenuOptionsDefinitionImpl", MenuOptionsDefinitionImpl.class); - modelClasses.put("PageMenuSeparatorDefinitionImpl", MenuSeparatorDefinitionImpl.class); - modelClasses.put("SecurityConstraintsImpl", SecurityConstraintsImpl.class); - modelClasses.put("FolderSecurityConstraintImpl", SecurityConstraintImpl.class); - modelClasses.put("PageSecurityConstraintImpl", SecurityConstraintImpl.class); - modelClasses.put("FragmentSecurityConstraintImpl", SecurityConstraintImpl.class); - modelClasses.put("LinkSecurityConstraintImpl", SecurityConstraintImpl.class); - modelClasses.put("PageSecuritySecurityConstraintImpl", SecurityConstraintImpl.class); - modelClasses.put("SecurityConstraintsDefImpl", SecurityConstraintsDefImpl.class); - modelClasses.put("FragmentPreferenceImpl", FragmentPreferenceImpl.class); + modelClasses.put("PageMenuExcludeDefinitionImpl", + MenuExcludeDefinitionImpl.class); + modelClasses.put("PageMenuIncludeDefinitionImpl", + MenuIncludeDefinitionImpl.class); + modelClasses.put("PageMenuOptionsDefinitionImpl", + MenuOptionsDefinitionImpl.class); + modelClasses.put("PageMenuSeparatorDefinitionImpl", + MenuSeparatorDefinitionImpl.class); + modelClasses.put("SecurityConstraintsImpl", + SecurityConstraintsImpl.class); + modelClasses.put("FolderSecurityConstraintImpl", + SecurityConstraintImpl.class); + modelClasses.put("PageSecurityConstraintImpl", + SecurityConstraintImpl.class); + modelClasses.put("FragmentSecurityConstraintImpl", + SecurityConstraintImpl.class); + modelClasses.put("LinkSecurityConstraintImpl", + SecurityConstraintImpl.class); + modelClasses.put("PageSecuritySecurityConstraintImpl", + SecurityConstraintImpl.class); + modelClasses.put("SecurityConstraintsDefImpl", + SecurityConstraintsDefImpl.class); + modelClasses + .put("FragmentPreferenceImpl", FragmentPreferenceImpl.class); } private IdGenerator generator = null; + private DocumentHandlerFactory handlerFactory; + private FolderHandler folderHandler; + private FileCache fileCache; - public CastorXmlPageManager( IdGenerator generator, DocumentHandlerFactory handlerFactory, - FolderHandler folderHandler, FileCache fileCache, - boolean permissionsEnabled, boolean constraintsEnabled ) throws FileNotFoundException + public CastorXmlPageManager(IdGenerator generator, + DocumentHandlerFactory handlerFactory, FolderHandler folderHandler, + FileCache fileCache, boolean permissionsEnabled, + boolean constraintsEnabled) throws FileNotFoundException { super(permissionsEnabled, constraintsEnabled, modelClasses); this.generator = generator; @@ -140,7 +163,7 @@ public Fragment newFragment() { // FragmentImpl requires generated ids - FragmentImpl fragment = (FragmentImpl)super.newFragment(); + FragmentImpl fragment = (FragmentImpl) super.newFragment(); fragment.setId(generator.getNextPeid()); return fragment; } @@ -148,12 +171,12 @@ public Fragment newPortletFragment() { // FragmentImpl requires generated ids - FragmentImpl fragment = (FragmentImpl)super.newFragment(); + FragmentImpl fragment = (FragmentImpl) super.newFragment(); fragment.setType(Fragment.PORTLET); fragment.setId(generator.getNextPeid()); return fragment; } - + /** *

        * getPage @@ -166,7 +189,8 @@ * @throws NodeException * @throws FolderNotFoundException */ - public Page getPage(String path) throws PageNotFoundException, NodeException + public Page getPage(String path) throws PageNotFoundException, + NodeException { // get page via folder, (access checked in Folder.getPage()) try @@ -192,7 +216,7 @@ // unwrap page to be registered if (page instanceof ContentPageImpl) { - page = ((ContentPageImpl)page).getPage(); + page = ((ContentPageImpl) page).getPage(); } // make sure path and related members are set @@ -222,20 +246,24 @@ } // enable permissions/constraints - PageImpl pageImpl = (PageImpl)page; - pageImpl.setPermissionsEnabled(handlerFactory.getPermissionsEnabled()); - pageImpl.setConstraintsEnabled(handlerFactory.getConstraintsEnabled()); - + PageImpl pageImpl = (PageImpl) page; + pageImpl.setPermissionsEnabled(handlerFactory + .getPermissionsEnabled()); + pageImpl.setConstraintsEnabled(handlerFactory + .getConstraintsEnabled()); + // check for edit access page.checkAccess(JetspeedActions.EDIT); - + // update page - handlerFactory.getDocumentHandler(Page.DOCUMENT_TYPE).updateDocument(page); - + handlerFactory.getDocumentHandler(Page.DOCUMENT_TYPE) + .updateDocument(page); + // update parent folder if (parentFolder != null) { - NodeSetImpl parentAllNodes = (NodeSetImpl)parentFolder.getAllNodes(); + NodeSetImpl parentAllNodes = (NodeSetImpl) parentFolder + .getAllNodes(); if (!parentAllNodes.contains(page)) { // add new page @@ -245,11 +273,11 @@ else if (parentAllNodes.get(page.getPath()) != page) { // remove stale page and add updated page - parentAllNodes.remove(page); + parentAllNodes.remove(page); parentAllNodes.add(page); } } - + // notify page manager listeners if (newPage) { @@ -278,7 +306,7 @@ // unwrap page to be removed if (page instanceof ContentPageImpl) { - page = ((ContentPageImpl)page).getPage(); + page = ((ContentPageImpl) page).getPage(); } // check for edit access @@ -289,11 +317,12 @@ FolderImpl folder = getNodeFolder(page.getPath()); // remove page - handlerFactory.getDocumentHandler(Page.DOCUMENT_TYPE).removeDocument(page); - + handlerFactory.getDocumentHandler(Page.DOCUMENT_TYPE) + .removeDocument(page); + // update folder - ((NodeSetImpl)folder.getAllNodes()).remove(page); - + ((NodeSetImpl) folder.getAllNodes()).remove(page); + // notify page manager listeners notifyRemovedNode(page); } @@ -319,7 +348,8 @@ * @throws UnsupportedDocumentTypeException * @throws NodeException */ - public Link getLink(String path) throws DocumentNotFoundException, UnsupportedDocumentTypeException, NodeException + public Link getLink(String path) throws DocumentNotFoundException, + UnsupportedDocumentTypeException, NodeException { // get link via folder, (access checked in Folder.getLink()) try @@ -367,22 +397,26 @@ link.setParent(parentFolder); newLink = true; } - + // enable permissions/constraints - LinkImpl linkImpl = (LinkImpl)link; - linkImpl.setPermissionsEnabled(handlerFactory.getPermissionsEnabled()); - linkImpl.setConstraintsEnabled(handlerFactory.getConstraintsEnabled()); - + LinkImpl linkImpl = (LinkImpl) link; + linkImpl.setPermissionsEnabled(handlerFactory + .getPermissionsEnabled()); + linkImpl.setConstraintsEnabled(handlerFactory + .getConstraintsEnabled()); + // check for edit access link.checkAccess(JetspeedActions.EDIT); - + // update link - handlerFactory.getDocumentHandler(Link.DOCUMENT_TYPE).updateDocument(link); - + handlerFactory.getDocumentHandler(Link.DOCUMENT_TYPE) + .updateDocument(link); + // update parent folder if (parentFolder != null) { - NodeSetImpl parentAllNodes = (NodeSetImpl)parentFolder.getAllNodes(); + NodeSetImpl parentAllNodes = (NodeSetImpl) parentFolder + .getAllNodes(); if (!parentAllNodes.contains(link)) { // add new link @@ -396,7 +430,7 @@ parentAllNodes.add(link); } } - + // notify page manager listeners if (newLink) { @@ -430,11 +464,12 @@ FolderImpl folder = getNodeFolder(link.getPath()); // remove link - handlerFactory.getDocumentHandler(Link.DOCUMENT_TYPE).removeDocument(link); - + handlerFactory.getDocumentHandler(Link.DOCUMENT_TYPE) + .removeDocument(link); + // update folder - ((NodeSetImpl)folder.getAllNodes()).remove(link); - + ((NodeSetImpl) folder.getAllNodes()).remove(link); + // notify page manager listeners notifyRemovedNode(link); } @@ -453,11 +488,10 @@ try { PageSecurity security = this.getPageSecurity(); - SecurityConstraintsDef def = security.getSecurityConstraintsDef(securityConstraintName); - if (def != null) - { - return PageManagerSecurityUtils.checkConstraint(def, actions); - } + SecurityConstraintsDef def = security + .getSecurityConstraintsDef(securityConstraintName); + if (def != null) { return PageManagerSecurityUtils.checkConstraint( + def, actions); } } catch (Exception e) { @@ -465,7 +499,7 @@ } return false; } - + /** *

        * getPageSecurity @@ -477,7 +511,8 @@ * @throws UnsupportedDocumentTypeException * @throws NodeException */ - public PageSecurity getPageSecurity() throws DocumentNotFoundException, UnsupportedDocumentTypeException, NodeException + public PageSecurity getPageSecurity() throws DocumentNotFoundException, + UnsupportedDocumentTypeException, NodeException { // get page security via folder, (always allow access) try @@ -491,18 +526,23 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#updatePageSecurity(org.apache.jetspeed.om.page.PageSecurity) */ - public void updatePageSecurity(PageSecurity pageSecurity) throws NodeException, FailedToUpdateDocumentException + public void updatePageSecurity(PageSecurity pageSecurity) + throws NodeException, FailedToUpdateDocumentException { // validate path... must exist in root folder and // make sure path and related members are set if (pageSecurity.getPath() != null) { - if (!pageSecurity.getPath().equals(Folder.PATH_SEPARATOR + PageSecurity.DOCUMENT_TYPE)) + if (!pageSecurity.getPath().equals( + Folder.PATH_SEPARATOR + PageSecurity.DOCUMENT_TYPE)) { - log.error("PageSecurity path must be: " + Folder.PATH_SEPARATOR + PageSecurity.DOCUMENT_TYPE); + log.error("PageSecurity path must be: " + Folder.PATH_SEPARATOR + + PageSecurity.DOCUMENT_TYPE); return; } if (!pageSecurity.getPath().equals(pageSecurity.getId())) @@ -527,22 +567,26 @@ pageSecurity.setParent(parentFolder); newPageSecurity = true; } - + // enable permissions/constraints - PageSecurityImpl pageSecurityImpl = (PageSecurityImpl)pageSecurity; - pageSecurityImpl.setPermissionsEnabled(handlerFactory.getPermissionsEnabled()); - pageSecurityImpl.setConstraintsEnabled(handlerFactory.getConstraintsEnabled()); - + PageSecurityImpl pageSecurityImpl = (PageSecurityImpl) pageSecurity; + pageSecurityImpl.setPermissionsEnabled(handlerFactory + .getPermissionsEnabled()); + pageSecurityImpl.setConstraintsEnabled(handlerFactory + .getConstraintsEnabled()); + // check for edit access pageSecurity.checkAccess(JetspeedActions.EDIT); - + // update pageSecurity - handlerFactory.getDocumentHandler(PageSecurity.DOCUMENT_TYPE).updateDocument(pageSecurity); - + handlerFactory.getDocumentHandler(PageSecurity.DOCUMENT_TYPE) + .updateDocument(pageSecurity); + // update parent folder if (parentFolder != null) { - NodeSetImpl parentAllNodes = (NodeSetImpl)parentFolder.getAllNodes(); + NodeSetImpl parentAllNodes = (NodeSetImpl) parentFolder + .getAllNodes(); if (!parentAllNodes.contains(pageSecurity)) { // add new page security @@ -556,7 +600,7 @@ parentAllNodes.add(pageSecurity); } } - + // notify page manager listeners if (newPageSecurity) { @@ -573,10 +617,13 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#removePageSecurity(org.apache.jetspeed.om.page.PageSecurity) */ - public void removePageSecurity(PageSecurity pageSecurity) throws NodeException, FailedToDeleteDocumentException + public void removePageSecurity(PageSecurity pageSecurity) + throws NodeException, FailedToDeleteDocumentException { // check for edit access pageSecurity.checkAccess(JetspeedActions.EDIT); @@ -586,11 +633,12 @@ FolderImpl folder = getNodeFolder(Folder.PATH_SEPARATOR); // remove page security - handlerFactory.getDocumentHandler(PageSecurity.DOCUMENT_TYPE).removeDocument(pageSecurity); - + handlerFactory.getDocumentHandler(PageSecurity.DOCUMENT_TYPE) + .removeDocument(pageSecurity); + // update folder - ((NodeSetImpl)folder.getAllNodes()).remove(pageSecurity); - + ((NodeSetImpl) folder.getAllNodes()).remove(pageSecurity); + // notify page manager listeners notifyRemovedNode(pageSecurity); } @@ -616,7 +664,8 @@ * @throws NodeException * @throws InvalidFolderException */ - public Folder getFolder(String folderPath) throws FolderNotFoundException, InvalidFolderException, NodeException + public Folder getFolder(String folderPath) throws FolderNotFoundException, + InvalidFolderException, NodeException { // get folder and check access before returning Folder folder = folderHandler.getFolder(folderPath); @@ -624,7 +673,9 @@ return folder; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getFolders(org.apache.jetspeed.om.folder.Folder) */ public NodeSet getFolders(Folder folder) throws DocumentException @@ -633,16 +684,21 @@ return folder.getFolders(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getFolder(org.apache.jetspeed.om.folder.Folder,java.lang.String) */ - public Folder getFolder(Folder folder, String name) throws FolderNotFoundException, DocumentException + public Folder getFolder(Folder folder, String name) + throws FolderNotFoundException, DocumentException { // delegate back to folder instance return folder.getFolder(name); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getPages(org.apache.jetspeed.om.folder.Folder) */ public NodeSet getPages(Folder folder) throws NodeException @@ -650,44 +706,57 @@ // delegate back to folder instance return folder.getPages(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getPage(org.apache.jetspeed.om.folder.Folder,java.lang.String) */ - public Page getPage(Folder folder, String name) throws PageNotFoundException, NodeException + public Page getPage(Folder folder, String name) + throws PageNotFoundException, NodeException { // delegate back to folder instance return folder.getPage(name); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getLinks(org.apache.jetspeed.om.folder.Folder) - */ + */ public NodeSet getLinks(Folder folder) throws NodeException { // delegate back to folder instance return folder.getLinks(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getLink(org.apache.jetspeed.om.folder.Folder,java.lang.String) - */ - public Link getLink(Folder folder, String name) throws DocumentNotFoundException, NodeException + */ + public Link getLink(Folder folder, String name) + throws DocumentNotFoundException, NodeException { // delegate back to folder instance return folder.getLink(name); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getPageSecurity(org.apache.jetspeed.om.folder.Folder) - */ - public PageSecurity getPageSecurity(Folder folder) throws DocumentNotFoundException, NodeException + */ + public PageSecurity getPageSecurity(Folder folder) + throws DocumentNotFoundException, NodeException { // delegate back to folder instance return folder.getPageSecurity(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getAll(org.apache.jetspeed.om.folder.Folder) */ public NodeSet getAll(Folder folder) throws DocumentException @@ -703,16 +772,20 @@ * * @see org.apache.jetspeed.services.page.PageManagerService#updateFolder(org.apache.jetspeed.om.folder.Folder) */ - public void updateFolder(Folder folder) throws NodeException, FolderNotUpdatedException + public void updateFolder(Folder folder) throws NodeException, + FolderNotUpdatedException { // shallow update by default updateFolder(folder, false); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#updateFolder(org.apache.jetspeed.om.folder.Folder,boolean) */ - public void updateFolder(Folder folder, boolean deep) throws NodeException, FolderNotUpdatedException + public void updateFolder(Folder folder, boolean deep) throws NodeException, + FolderNotUpdatedException { // make sure path and related members are set if (folder.getPath() != null) @@ -745,26 +818,29 @@ } else { - folder.setParent(null); + folder.setParent(null); } - + // enable permissions/constraints and configure // folder handler before access is checked - FolderImpl folderImpl = (FolderImpl)folder; - folderImpl.setPermissionsEnabled(handlerFactory.getPermissionsEnabled()); - folderImpl.setConstraintsEnabled(handlerFactory.getConstraintsEnabled()); + FolderImpl folderImpl = (FolderImpl) folder; + folderImpl.setPermissionsEnabled(handlerFactory + .getPermissionsEnabled()); + folderImpl.setConstraintsEnabled(handlerFactory + .getConstraintsEnabled()); folderImpl.setFolderHandler(folderHandler); - + // check for edit access folder.checkAccess(JetspeedActions.EDIT); - + // update folder folderHandler.updateFolder(folder); - + // update parent folder if (parentFolder != null) { - NodeSetImpl parentAllNodes = (NodeSetImpl)parentFolder.getAllNodes(); + NodeSetImpl parentAllNodes = (NodeSetImpl) parentFolder + .getAllNodes(); if (!parentAllNodes.contains(folder)) { // add new folder @@ -778,14 +854,14 @@ parentAllNodes.add(folder); } } - + // update deep recursively if specified if (deep) { // update recursively, (breadth first) updateFolderNodes(folderImpl); } - + // notify page manager listeners if (newFolder) { @@ -794,7 +870,7 @@ else { notifyUpdatedNode(folder); - } + } } catch (FolderNotFoundException fnfe) { @@ -804,11 +880,14 @@ /** * updateFolderNodes - recusively update all folder nodes - * - * @param folderImpl folder whose nodes are to be updated - * @param throws FolderNotUpdatedException + * + * @param folderImpl + * folder whose nodes are to be updated + * @param throws + * FolderNotUpdatedException */ - private void updateFolderNodes(FolderImpl folderImpl) throws FolderNotUpdatedException + private void updateFolderNodes(FolderImpl folderImpl) + throws FolderNotUpdatedException { try { @@ -820,15 +899,15 @@ Node node = (Node) nodesIter.next(); if (node instanceof Page) { - updatePage((Page)node); + updatePage((Page) node); } else if (node instanceof Link) { - updateLink((Link)node); + updateLink((Link) node); } else if (node instanceof PageSecurity) { - updatePageSecurity((PageSecurity)node); + updatePageSecurity((PageSecurity) node); } } @@ -839,7 +918,7 @@ Node node = (Node) nodesIter.next(); if (node instanceof Folder) { - updateFolder((Folder)node, true); + updateFolder((Folder) node, true); } } } @@ -853,7 +932,8 @@ } catch (Exception e) { - throw new FolderNotUpdatedException("Folder " + folderImpl.getPath() + " not updated.", e); + throw new FolderNotUpdatedException("Folder " + + folderImpl.getPath() + " not updated.", e); } } @@ -883,7 +963,7 @@ // update parent folder if (parentFolder != null) { - ((NodeSetImpl)parentFolder.getAllNodes()).remove(folder); + ((NodeSetImpl) parentFolder.getAllNodes()).remove(folder); } // notify page manager listeners @@ -895,7 +975,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#reset() */ public void reset() @@ -919,13 +1001,12 @@ * @throws InvalidFolderException * @throws FolderNotFoundException */ - private FolderImpl getNodeFolder(String nodePath) throws NodeException, InvalidFolderException, FolderNotFoundException + private FolderImpl getNodeFolder(String nodePath) throws NodeException, + InvalidFolderException, FolderNotFoundException { int folderIndex = nodePath.lastIndexOf(Folder.PATH_SEPARATOR); - if (folderIndex > 0) - { - return (FolderImpl) folderHandler.getFolder(nodePath.substring(0, folderIndex)); - } + if (folderIndex > 0) { return (FolderImpl) folderHandler + .getFolder(nodePath.substring(0, folderIndex)); } return (FolderImpl) folderHandler.getFolder(Folder.PATH_SEPARATOR); } @@ -940,10 +1021,7 @@ private String getNodeName(String nodePath) { int folderIndex = nodePath.lastIndexOf(Folder.PATH_SEPARATOR); - if (folderIndex > -1) - { - return nodePath.substring(folderIndex+1); - } + if (folderIndex > -1) { return nodePath.substring(folderIndex + 1); } return nodePath; } @@ -956,14 +1034,14 @@ * @param entry * @throws Exception */ - public void refresh( FileCacheEntry entry ) throws Exception + public void refresh(FileCacheEntry entry) throws Exception { // file cache managed component refreshed: // notify page manager listeners Node refreshedNode = null; if (entry.getDocument() instanceof Node) { - refreshedNode = (Node)entry.getDocument(); + refreshedNode = (Node) entry.getDocument(); } if (entry.getFile().exists()) { @@ -984,7 +1062,7 @@ * @param entry * @throws Exception */ - public void evict( FileCacheEntry entry ) throws Exception + public void evict(FileCacheEntry entry) throws Exception { // file cache managed component evicted: // no notifications required since eviction @@ -993,25 +1071,27 @@ // this page manager } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManager#getContentPage(java.lang.String) */ - public ContentPage getContentPage(String path) throws PageNotFoundException, NodeException - { + public ContentPage getContentPage(String path) + throws PageNotFoundException, NodeException + { return new ContentPageImpl(getPage(path)); - } + } public Page copy(Page source) { return null; } - - public int addPages(Page[] pages) - throws NodeException + + public int addPages(Page[] pages) throws NodeException { this.updatePage(pages[0]); this.updatePage(pages[1]); throw new NodeException("Its gonna blow captain!"); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/MethodReplayDecisionMaker.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/MethodReplayDecisionMaker.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/MethodReplayDecisionMaker.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,6 +27,7 @@ */ public interface MethodReplayDecisionMaker { + /** * * @param invocation Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/MethodReplayInterceptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/MethodReplayInterceptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/MethodReplayInterceptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -61,7 +61,8 @@ try { return invocation.proceed(); - } catch (Exception exp) + } + catch (Exception exp) { // determine whether to retry or just throw the exception back up @@ -106,7 +107,8 @@ // returning from a finally block will discard the // exception return invocation.proceed(); - } catch (Exception exp2) + } + catch (Exception exp2) { // determine whether to retry or just throw the exception // back up Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/PageManagerInterceptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/PageManagerInterceptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/PageManagerInterceptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,7 +22,7 @@ /** * Aspect that will attempt to rollback cache entries upon Page Manager failures - * + * * @author David Sean Taylor */ public class PageManagerInterceptor implements MethodInterceptor @@ -38,9 +38,9 @@ public Object invoke(MethodInvocation invocation) throws Throwable { try - { + { return invocation.proceed(); - } + } catch (Exception exp) { DatabasePageManagerCache.rollbackTransactions(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/TransactionalMethodReplayDecisionMaker.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/TransactionalMethodReplayDecisionMaker.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/interceptors/TransactionalMethodReplayDecisionMaker.java 2008-05-16 01:54:54 UTC (rev 940) @@ -57,7 +57,7 @@ if (exception instanceof SQLException) { foundException = (SQLException) exception; - } + } else { // Look at the cause Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/ojb/ACLFieldConversion.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/ojb/ACLFieldConversion.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/java/org/apache/jetspeed/util/ojb/ACLFieldConversion.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,14 +25,14 @@ import org.apache.ojb.broker.accesslayer.conversions.FieldConversion; /** - * ACLFieldConversion - * - * OJB field conversion: Helps transparently map ACL List members - * to/from database table column that that contains an ordered - * CSV list of strings. + * ACLFieldConversion + * + * OJB field conversion: Helps transparently map ACL List members to/from + * database table column that that contains an ordered CSV list of strings. */ public class ACLFieldConversion implements FieldConversion { + private static final String DELIM = ","; /** @@ -49,7 +49,7 @@ Iterator values = csvList.iterator(); while (values.hasNext()) { - String value = (String)values.next(); + String value = (String) values.next(); if (value.length() > 0) { if (buffer == null) @@ -63,18 +63,12 @@ buffer.append(value); } } - if (buffer != null) - { - return buffer.toString(); - } + if (buffer != null) { return buffer.toString(); } } else if (!csvList.isEmpty()) { - String value = (String)csvList.get(0); - if (value.length() > 0) - { - return value; - } + String value = (String) csvList.get(0); + if (value.length() > 0) { return value; } } return ""; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/om/page/TestPageObjectModel.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/om/page/TestPageObjectModel.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/om/page/TestPageObjectModel.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,7 +28,7 @@ /** * TestMarshalPsml - * + * * @author David Sean Taylor * @version $Id: TestPageObjectModel.java 516448 2007-03-09 16:25:47Z ate $ */ @@ -37,22 +37,25 @@ /** * Defines the testcase name for JUnit. - * - * @param name the testcase's name. + * + * @param name + * the testcase's name. */ - public TestPageObjectModel( String name ) + public TestPageObjectModel(String name) { - super( name ); + super(name); } /** * Start the tests. - * - * @param args the arguments. Not used + * + * @param args + * the arguments. Not used */ public static void main(String args[]) { - junit.awtui.TestRunner.main( new String[] { TestPageObjectModel.class.getName() } ); + junit.awtui.TestRunner.main(new String[] + {TestPageObjectModel.class.getName()}); } public void setup() @@ -62,9 +65,9 @@ /** * Creates the test suite. - * - * @return a test suite (TestSuite) that includes all methods - * starting with "test" + * + * @return a test suite (TestSuite) that includes all + * methods starting with "test" */ public static Test suite() { @@ -129,10 +132,10 @@ frag2.getFragments().add(frag3); root.getFragments().add(frag2); - //Check the construct - assertTrue(root.getFragments().size()==2); + // Check the construct + assertTrue(root.getFragments().size() == 2); Iterator i = root.getFragments().iterator(); - FragmentImpl f = (FragmentImpl)i.next(); + FragmentImpl f = (FragmentImpl) i.next(); assertNotNull(f); assertTrue(f.getName().equals("Portlet1")); assertTrue(f.getType().equals(Fragment.PORTLET)); @@ -140,34 +143,34 @@ assertNull(f.getTitle()); assertNull(f.getDecorator()); assertNull(f.getState()); - assertTrue(f.getFragments().size()==0); - f = (FragmentImpl)i.next(); + assertTrue(f.getFragments().size() == 0); + f = (FragmentImpl) i.next(); assertNotNull(f); assertTrue(f.getName().equals("TwoColumns")); assertTrue(f.getType().equals(Fragment.LAYOUT)); - assertTrue(f.getFragments().size()==1); + assertTrue(f.getFragments().size() == 1); assertTrue(f.getDecorator().equals("test")); - assertTrue(f.getFragments().size()==1); + assertTrue(f.getFragments().size() == 1); i = f.getFragments().iterator(); - frag1 = (FragmentImpl)i.next(); + frag1 = (FragmentImpl) i.next(); assertNotNull(frag1); assertTrue(frag1.getName().equals("Portlet3")); assertTrue(frag1.getType().equals(Fragment.PORTLET)); - //Now change the inner child to a new portlet + // Now change the inner child to a new portlet frag2 = new FragmentImpl(); frag2.setId("FR4"); frag2.setType(Fragment.PORTLET); frag2.setName("P4"); - frag3 = (FragmentImpl)page.getFragmentById("F3"); + frag3 = (FragmentImpl) page.getFragmentById("F3"); assertNotNull(frag3); f.getFragments().remove(frag3); - frag3 = (FragmentImpl)page.getFragmentById("F3"); + frag3 = (FragmentImpl) page.getFragmentById("F3"); assertNull(frag3); f.getFragments().add(frag2); - assertTrue(f.getFragments().size()==1); - f = (FragmentImpl)f.getFragments().get(0); + assertTrue(f.getFragments().size() == 1); + f = (FragmentImpl) f.getFragments().get(0); assertNotNull(f); assertTrue(f.getName().equals("P4")); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/DirectoryXMLTransform.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/DirectoryXMLTransform.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/DirectoryXMLTransform.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.page; import java.io.File; @@ -39,140 +39,161 @@ import org.apache.commons.lang.StringUtils; import org.apache.jetspeed.util.DirectoryHelper; - /** * @author ddam - * + * */ public class DirectoryXMLTransform extends DirectoryHelper { + private SAXTransformerFactory transformerFactory; private SAXParserFactory saxFactory; - + private Map xsltMapping; - - public DirectoryXMLTransform(File base, Map extensionToXslt) { - super(base); - this.xsltMapping=extensionToXslt; - System.setProperty("javax.xml.transform.TransformerFactory", - "org.apache.xalan.processor.TransformerFactoryImpl"); - System.setProperty("javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl"); - System.setProperty("org.xml.sax.driver", "org.apache.xerces.parsers.SAXParser"); - transformerFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); - saxFactory = SAXParserFactory.newInstance(); - saxFactory.setValidating(false); + public DirectoryXMLTransform(File base, Map extensionToXslt) + { + super(base); + this.xsltMapping = extensionToXslt; + System.setProperty("javax.xml.transform.TransformerFactory", + "org.apache.xalan.processor.TransformerFactoryImpl"); + System.setProperty("javax.xml.parsers.SAXParserFactory", + "org.apache.xerces.jaxp.SAXParserFactoryImpl"); + System.setProperty("org.xml.sax.driver", + "org.apache.xerces.parsers.SAXParser"); + transformerFactory = (SAXTransformerFactory) TransformerFactory + .newInstance(); + saxFactory = SAXParserFactory.newInstance(); + saxFactory.setValidating(false); + + } + + protected void setBaseDirectory(File directory) + { + if (!directory.exists()) + { + directory.mkdirs(); } - - protected void setBaseDirectory(File directory){ - if(!directory.exists()) + + if (!directory.isDirectory()) { throw new IllegalArgumentException( + "DirectoryHelper(File) requires directory not a file."); } + this.directory = directory; + + } + + private Transformer getXSLTForFile(File f) + { + String extension = StringUtils.substringAfterLast(f.getName(), "."); + + if (!StringUtils.isEmpty(extension) + && xsltMapping.containsKey(extension.toLowerCase())) + { + + Object t_obj = xsltMapping.get(extension.toLowerCase()); + if (t_obj instanceof Transformer) { return (Transformer) t_obj; } + if (t_obj instanceof String) { - directory.mkdirs(); - } - - if(!directory.isDirectory()) - { - throw new IllegalArgumentException("DirectoryHelper(File) requires directory not a file."); - } - this.directory = directory; - - } + String t_path = (String) t_obj; + Transformer transformer; + try + { + transformer = transformerFactory + .newTransformer(new StreamSource(t_path)); + xsltMapping.put(extension, transformer); + return transformer; + } + catch (TransformerConfigurationException e) + { - private Transformer getXSLTForFile(File f){ - String extension = StringUtils.substringAfterLast(f.getName(),"."); - - if (!StringUtils.isEmpty(extension) && xsltMapping.containsKey(extension.toLowerCase())){ - - Object t_obj = xsltMapping.get(extension.toLowerCase()); - if (t_obj instanceof Transformer){ - return (Transformer)t_obj; } - if (t_obj instanceof String){ - String t_path = (String) t_obj; - Transformer transformer; - try{ - transformer = transformerFactory.newTransformer(new StreamSource(t_path)); - xsltMapping.put(extension, transformer); - return transformer; - } catch(TransformerConfigurationException e){ - - } - } } - - return null; } - - /** - *

        - * copyFrom - *

        - * - * @see org.apache.jetspeed.util.FileSystemHelper#copyFrom(java.io.File, java.io.FileFilter) - * @param directory - * @param fileFilter - * @throws IOException - */ - public void copyFromAndTransform( File srcDirectory, FileFilter fileFilter ) throws IOException - { - if(!srcDirectory.isDirectory()) - { - throw new IllegalArgumentException("DirectoryHelper.copyFrom(File) requires directory not a file."); - } - copyFilesAndTransform(srcDirectory, directory, fileFilter); - } + return null; + } - /** - * - *

        - * copyFiles - *

        - * - * @param srcDir Source directory to copy from. - * @param dstDir Destination directory to copy to. - * @throws IOException - * @throws FileNotFoundException + /** + *

        + * copyFrom + *

        + * + * @see org.apache.jetspeed.util.FileSystemHelper#copyFrom(java.io.File, + * java.io.FileFilter) + * @param directory + * @param fileFilter + * @throws IOException + */ + public void copyFromAndTransform(File srcDirectory, FileFilter fileFilter) + throws IOException + { + if (!srcDirectory.isDirectory()) { throw new IllegalArgumentException( + "DirectoryHelper.copyFrom(File) requires directory not a file."); } + copyFilesAndTransform(srcDirectory, directory, fileFilter); - */ - protected void copyFilesAndTransform(File srcDir, File dstDir, FileFilter fileFilter) throws IOException + } + + /** + * + *

        + * copyFiles + *

        + * + * @param srcDir + * Source directory to copy from. + * @param dstDir + * Destination directory to copy to. + * @throws IOException + * @throws FileNotFoundException + * + */ + protected void copyFilesAndTransform(File srcDir, File dstDir, + FileFilter fileFilter) throws IOException + { + FileChannel srcChannel = null; + FileChannel dstChannel = null; + + try { - FileChannel srcChannel = null; - FileChannel dstChannel = null; - - try - { File[] children = srcDir.listFiles(fileFilter); - for(int i=0; iRandy Watler * @version $Id: $ - * + * */ interface PageManagerTestShared { + class Shared { + /** * makeCastorXMLPageManager - * + * * Create and configure a Castor XML PageManager. - * + * * @param pagesDirName * @param permissionsEnabled * @param constraintsEnabled * @return page manager instance */ - static CastorXmlPageManager makeCastorXMLPageManager(String pagesDirName, boolean permissionsEnabled, boolean constraintsEnabled) - throws Exception + static CastorXmlPageManager makeCastorXMLPageManager( + String pagesDirName, boolean permissionsEnabled, + boolean constraintsEnabled) throws Exception { Map extensionsToXslt = new HashMap(); - extensionsToXslt.put("psml","resources/stripIds.xslt"); - + extensionsToXslt.put("psml", "resources/stripIds.xslt"); + File pagesDirFile = new File("target/testdata/" + pagesDirName); - - - DirectoryXMLTransform dirHelper = new DirectoryXMLTransform(pagesDirFile,extensionsToXslt); + + DirectoryXMLTransform dirHelper = new DirectoryXMLTransform( + pagesDirFile, extensionsToXslt); FileFilter noCVSorSVNorBackups = new FileFilter() + { + + public boolean accept(File pathname) { - public boolean accept( File pathname ) - { - return !pathname.getName().equals("CVS") && !pathname.getName().equals(".svn") && !pathname.getName().endsWith("~"); - } - }; - dirHelper.copyFrom(new File("testdata/" + pagesDirName), noCVSorSVNorBackups); - + return !pathname.getName().equals("CVS") + && !pathname.getName().equals(".svn") + && !pathname.getName().endsWith("~"); + } + }; + dirHelper.copyFrom(new File("testdata/" + pagesDirName), + noCVSorSVNorBackups); + // copy documents under webapp/pages folder and strip fragment Ids - File webappDestDirFile = new File("target/testdata/" + pagesDirName+"/webapp-no-ids"); + File webappDestDirFile = new File("target/testdata/" + pagesDirName + + "/webapp-no-ids"); dirHelper.setBaseDirectory(webappDestDirFile); File webappPagesDirFile = new File("../../src/webapp/WEB-INF/pages"); - dirHelper.copyFromAndTransform(webappPagesDirFile, noCVSorSVNorBackups); + dirHelper.copyFromAndTransform(webappPagesDirFile, + noCVSorSVNorBackups); - // copy documents under webapp/pages folder without transforming them - webappDestDirFile = new File("target/testdata/" + pagesDirName+"/webapp-ids"); + // copy documents under webapp/pages folder without transforming + // them + webappDestDirFile = new File("target/testdata/" + pagesDirName + + "/webapp-ids"); dirHelper.setBaseDirectory(webappDestDirFile); dirHelper.copyFrom(webappPagesDirFile, noCVSorSVNorBackups); - IdGenerator idGen = new JetspeedIdGenerator(65536,"P-",""); + IdGenerator idGen = new JetspeedIdGenerator(65536, "P-", ""); FileCache cache = new FileCache(10, 12); - - DocumentHandler psmlHandler = new CastorFileSystemDocumentHandler("/JETSPEED-INF/castor/page-mapping.xml", Page.DOCUMENT_TYPE, PageImpl.class, "target/testdata/" + pagesDirName, cache); - DocumentHandler linkHandler = new CastorFileSystemDocumentHandler("/JETSPEED-INF/castor/page-mapping.xml", Link.DOCUMENT_TYPE, LinkImpl.class, "target/testdata/" + pagesDirName, cache); - DocumentHandler folderMetaDataHandler = new CastorFileSystemDocumentHandler("/JETSPEED-INF/castor/page-mapping.xml", FolderMetaDataImpl.DOCUMENT_TYPE, FolderMetaDataImpl.class, "target/testdata/" + pagesDirName, cache); - DocumentHandler pageSecurityHandler = new CastorFileSystemDocumentHandler("/JETSPEED-INF/castor/page-mapping.xml", PageSecurityImpl.DOCUMENT_TYPE, PageSecurity.class, "target/testdata/" + pagesDirName, cache); - + + DocumentHandler psmlHandler = new CastorFileSystemDocumentHandler( + "/JETSPEED-INF/castor/page-mapping.xml", + Page.DOCUMENT_TYPE, PageImpl.class, "target/testdata/" + + pagesDirName, cache); + DocumentHandler linkHandler = new CastorFileSystemDocumentHandler( + "/JETSPEED-INF/castor/page-mapping.xml", + Link.DOCUMENT_TYPE, LinkImpl.class, "target/testdata/" + + pagesDirName, cache); + DocumentHandler folderMetaDataHandler = new CastorFileSystemDocumentHandler( + "/JETSPEED-INF/castor/page-mapping.xml", + FolderMetaDataImpl.DOCUMENT_TYPE, FolderMetaDataImpl.class, + "target/testdata/" + pagesDirName, cache); + DocumentHandler pageSecurityHandler = new CastorFileSystemDocumentHandler( + "/JETSPEED-INF/castor/page-mapping.xml", + PageSecurityImpl.DOCUMENT_TYPE, PageSecurity.class, + "target/testdata/" + pagesDirName, cache); + DocumentHandlerFactory handlerFactory = new DocumentHandlerFactoryImpl(); handlerFactory.registerDocumentHandler(psmlHandler); handlerFactory.registerDocumentHandler(linkHandler); handlerFactory.registerDocumentHandler(folderMetaDataHandler); handlerFactory.registerDocumentHandler(pageSecurityHandler); - FolderHandler folderHandler = new FileSystemFolderHandler("target/testdata/" + pagesDirName, handlerFactory, cache); + FolderHandler folderHandler = new FileSystemFolderHandler( + "target/testdata/" + pagesDirName, handlerFactory, cache); - return new CastorXmlPageManager(idGen, handlerFactory, folderHandler, cache, permissionsEnabled, constraintsEnabled); + return new CastorXmlPageManager(idGen, handlerFactory, + folderHandler, cache, permissionsEnabled, + constraintsEnabled); } /** * makeListFromCSV - * - * Create List of String values from CSV String for principals/permissions. * - * @param csv CSV string + * Create List of String values from CSV String for + * principals/permissions. + * + * @param csv + * CSV string * @return values list */ static List makeListFromCSV(String csv) @@ -168,15 +196,17 @@ } return csvList; } - return null; + return null; } /** * makeCSVFromList - * - * Create CSV String for principals/permissions from List of String values * - * @param list values list + * Create CSV String for principals/permissions from List of String + * values + * + * @param list + * values list * @return CSV string */ static String makeCSVFromList(List list) @@ -191,7 +221,7 @@ { csv.append(","); } - csv.append((String)listIter.next()); + csv.append((String) listIter.next()); } return csv.toString(); } @@ -200,460 +230,609 @@ /** * testSecurePageManager - * - * @param test case - * @param page manager + * + * @param test + * case + * @param page + * manager */ - static void testSecurePageManager(final TestCase test, final PageManager pageManager) throws Exception + static void testSecurePageManager(final TestCase test, + final PageManager pageManager) throws Exception { // tracking - final String [] somePortletId = new String[1]; + final String[] somePortletId = new String[1]; // reset page manager cache pageManager.reset(); - + // setup test subjects Principal userPrincipal = new UserPrincipalImpl("admin"); Principal rolePrincipal = new RolePrincipalImpl("admin"); Set principals = new PrincipalsSet(); principals.add(userPrincipal); principals.add(rolePrincipal); - Subject adminSubject = new Subject(true, principals, new HashSet(), new HashSet()); - + Subject adminSubject = new Subject(true, principals, new HashSet(), + new HashSet()); + userPrincipal = new UserPrincipalImpl("user"); principals = new PrincipalsSet(); principals.add(userPrincipal); - Subject userSubject = new Subject(true, principals, new HashSet(), new HashSet()); - + Subject userSubject = new Subject(true, principals, new HashSet(), + new HashSet()); + userPrincipal = new UserPrincipalImpl("manager"); rolePrincipal = new RolePrincipalImpl("manager"); principals = new PrincipalsSet(); principals.add(userPrincipal); principals.add(rolePrincipal); - Subject managerSubject = new Subject(true, principals, new HashSet(), new HashSet()); + Subject managerSubject = new Subject(true, principals, + new HashSet(), new HashSet()); userPrincipal = new UserPrincipalImpl("guest"); principals = new PrincipalsSet(); principals.add(userPrincipal); - Subject guestSubject = new Subject(true, principals, new HashSet(), new HashSet()); + Subject guestSubject = new Subject(true, principals, new HashSet(), + new HashSet()); // setup test as admin user - Exception setup = (Exception)JSSubject.doAsPrivileged(adminSubject, new PrivilegedAction() - { - public Object run() + Exception setup = (Exception) JSSubject.doAsPrivileged( + adminSubject, new PrivilegedAction() { - try + + public Object run() { - // reset page manager to initial state try { - Folder removeRootFolder = pageManager.getFolder("/"); - pageManager.removeFolder(removeRootFolder); - pageManager.reset(); + // reset page manager to initial state + try + { + Folder removeRootFolder = pageManager + .getFolder("/"); + pageManager.removeFolder(removeRootFolder); + pageManager.reset(); + } + catch (FolderNotFoundException e) + { + } + + // create test documents and folders + Folder folder = pageManager.newFolder("/"); + SecurityConstraints constraints = pageManager + .newSecurityConstraints(); + constraints.setOwner("admin"); + List constraintsRefs = new ArrayList(1); + constraintsRefs.add("public-view"); + constraints + .setSecurityConstraintsRefs(constraintsRefs); + folder.setSecurityConstraints(constraints); + pageManager.updateFolder(folder); + + PageSecurity pageSecurity = pageManager + .newPageSecurity(); + List constraintsDefs = new ArrayList(2); + SecurityConstraintsDef constraintsDef = pageManager + .newSecurityConstraintsDef(); + constraintsDef.setName("public-view"); + List defConstraints = new ArrayList(1); + SecurityConstraint defConstraint = pageManager + .newPageSecuritySecurityConstraint(); + defConstraint.setUsers(Shared + .makeListFromCSV("*")); + defConstraint.setPermissions(Shared + .makeListFromCSV("view")); + defConstraints.add(defConstraint); + constraintsDef + .setSecurityConstraints(defConstraints); + constraintsDefs.add(constraintsDef); + constraintsDef = pageManager + .newSecurityConstraintsDef(); + constraintsDef.setName("admin-all"); + defConstraints = new ArrayList(1); + defConstraint = pageManager + .newPageSecuritySecurityConstraint(); + defConstraint.setRoles(Shared + .makeListFromCSV("admin")); + defConstraint.setPermissions(Shared + .makeListFromCSV("view,edit")); + defConstraints.add(defConstraint); + constraintsDef + .setSecurityConstraints(defConstraints); + constraintsDefs.add(constraintsDef); + pageSecurity + .setSecurityConstraintsDefs(constraintsDefs); + List globalConstraintsRefs = new ArrayList(1); + globalConstraintsRefs.add("admin-all"); + pageSecurity + .setGlobalSecurityConstraintsRefs(globalConstraintsRefs); + pageManager.updatePageSecurity(pageSecurity); + + Page page = pageManager + .newPage("/default-page.psml"); + constraints = pageManager + .newSecurityConstraints(); + constraints.setOwner("admin"); + List inlineConstraints = new ArrayList(1); + SecurityConstraint constraint = pageManager + .newPageSecurityConstraint(); + constraint.setRoles(Shared + .makeListFromCSV("manager")); + constraint.setPermissions(Shared + .makeListFromCSV("edit")); + inlineConstraints.add(constraint); + constraints + .setSecurityConstraints(inlineConstraints); + constraintsRefs = new ArrayList(1); + constraintsRefs.add("public-view"); + constraints + .setSecurityConstraintsRefs(constraintsRefs); + page.setSecurityConstraints(constraints); + Fragment root = page.getRootFragment(); + root + .setName("jetspeed-layouts::VelocityTwoColumns"); + Fragment portlet = pageManager + .newPortletFragment(); + portlet.setName("security::LoginPortlet"); + root.getFragments().add(portlet); + portlet = pageManager.newPortletFragment(); + portlet.setName("some-app::SomePortlet"); + SecurityConstraints fragmentConstraints = pageManager + .newSecurityConstraints(); + fragmentConstraints.setOwner("user"); + portlet + .setSecurityConstraints(fragmentConstraints); + root.getFragments().add(portlet); + pageManager.updatePage(page); + TestCase.assertNotNull(page.getRootFragment()); + TestCase.assertNotNull(page.getRootFragment() + .getFragments()); + TestCase.assertEquals(2, page.getRootFragment() + .getFragments().size()); + TestCase.assertEquals("some-app::SomePortlet", + ((Fragment) page.getRootFragment() + .getFragments().get(1)) + .getName()); + TestCase + .assertFalse("0" + .equals(((Fragment) page + .getRootFragment() + .getFragments().get(1)) + .getId())); + somePortletId[0] = ((Fragment) page + .getRootFragment().getFragments() + .get(1)).getId(); + + page = pageManager.newPage("/user-page.psml"); + constraints = pageManager + .newSecurityConstraints(); + inlineConstraints = new ArrayList(1); + constraint = pageManager + .newPageSecurityConstraint(); + constraint.setUsers(Shared + .makeListFromCSV("user")); + constraint.setPermissions(Shared + .makeListFromCSV("view,edit")); + inlineConstraints.add(constraint); + constraints + .setSecurityConstraints(inlineConstraints); + page.setSecurityConstraints(constraints); + pageManager.updatePage(page); + + Link link = pageManager + .newLink("/default.link"); + link.setUrl("http://www.default.org/"); + constraints = pageManager + .newSecurityConstraints(); + constraints.setOwner("admin"); + inlineConstraints = new ArrayList(1); + constraint = pageManager + .newLinkSecurityConstraint(); + constraint.setRoles(Shared + .makeListFromCSV("manager")); + constraint.setPermissions(Shared + .makeListFromCSV("edit")); + inlineConstraints.add(constraint); + constraints + .setSecurityConstraints(inlineConstraints); + link.setSecurityConstraints(constraints); + pageManager.updateLink(link); + + return null; } - catch (FolderNotFoundException e) + catch (Exception e) { + return e; } - - // create test documents and folders - Folder folder = pageManager.newFolder("/"); - SecurityConstraints constraints = pageManager.newSecurityConstraints(); - constraints.setOwner("admin"); - List constraintsRefs = new ArrayList(1); - constraintsRefs.add("public-view"); - constraints.setSecurityConstraintsRefs(constraintsRefs); - folder.setSecurityConstraints(constraints); - pageManager.updateFolder(folder); - - PageSecurity pageSecurity = pageManager.newPageSecurity(); - List constraintsDefs = new ArrayList(2); - SecurityConstraintsDef constraintsDef = pageManager.newSecurityConstraintsDef(); - constraintsDef.setName("public-view"); - List defConstraints = new ArrayList(1); - SecurityConstraint defConstraint = pageManager.newPageSecuritySecurityConstraint(); - defConstraint.setUsers(Shared.makeListFromCSV("*")); - defConstraint.setPermissions(Shared.makeListFromCSV("view")); - defConstraints.add(defConstraint); - constraintsDef.setSecurityConstraints(defConstraints); - constraintsDefs.add(constraintsDef); - constraintsDef = pageManager.newSecurityConstraintsDef(); - constraintsDef.setName("admin-all"); - defConstraints = new ArrayList(1); - defConstraint = pageManager.newPageSecuritySecurityConstraint(); - defConstraint.setRoles(Shared.makeListFromCSV("admin")); - defConstraint.setPermissions(Shared.makeListFromCSV("view,edit")); - defConstraints.add(defConstraint); - constraintsDef.setSecurityConstraints(defConstraints); - constraintsDefs.add(constraintsDef); - pageSecurity.setSecurityConstraintsDefs(constraintsDefs); - List globalConstraintsRefs = new ArrayList(1); - globalConstraintsRefs.add("admin-all"); - pageSecurity.setGlobalSecurityConstraintsRefs(globalConstraintsRefs); - pageManager.updatePageSecurity(pageSecurity); - - Page page = pageManager.newPage("/default-page.psml"); - constraints = pageManager.newSecurityConstraints(); - constraints.setOwner("admin"); - List inlineConstraints = new ArrayList(1); - SecurityConstraint constraint = pageManager.newPageSecurityConstraint(); - constraint.setRoles(Shared.makeListFromCSV("manager")); - constraint.setPermissions(Shared.makeListFromCSV("edit")); - inlineConstraints.add(constraint); - constraints.setSecurityConstraints(inlineConstraints); - constraintsRefs = new ArrayList(1); - constraintsRefs.add("public-view"); - constraints.setSecurityConstraintsRefs(constraintsRefs); - page.setSecurityConstraints(constraints); - Fragment root = page.getRootFragment(); - root.setName("jetspeed-layouts::VelocityTwoColumns"); - Fragment portlet = pageManager.newPortletFragment(); - portlet.setName("security::LoginPortlet"); - root.getFragments().add(portlet); - portlet = pageManager.newPortletFragment(); - portlet.setName("some-app::SomePortlet"); - SecurityConstraints fragmentConstraints = pageManager.newSecurityConstraints(); - fragmentConstraints.setOwner("user"); - portlet.setSecurityConstraints(fragmentConstraints); - root.getFragments().add(portlet); - pageManager.updatePage(page); - TestCase.assertNotNull(page.getRootFragment()); - TestCase.assertNotNull(page.getRootFragment().getFragments()); - TestCase.assertEquals(2, page.getRootFragment().getFragments().size()); - TestCase.assertEquals("some-app::SomePortlet", ((Fragment)page.getRootFragment().getFragments().get(1)).getName()); - TestCase.assertFalse("0".equals(((Fragment)page.getRootFragment().getFragments().get(1)).getId())); - somePortletId[0] = ((Fragment)page.getRootFragment().getFragments().get(1)).getId(); - - page = pageManager.newPage("/user-page.psml"); - constraints = pageManager.newSecurityConstraints(); - inlineConstraints = new ArrayList(1); - constraint = pageManager.newPageSecurityConstraint(); - constraint.setUsers(Shared.makeListFromCSV("user")); - constraint.setPermissions(Shared.makeListFromCSV("view,edit")); - inlineConstraints.add(constraint); - constraints.setSecurityConstraints(inlineConstraints); - page.setSecurityConstraints(constraints); - pageManager.updatePage(page); - - Link link = pageManager.newLink("/default.link"); - link.setUrl("http://www.default.org/"); - constraints = pageManager.newSecurityConstraints(); - constraints.setOwner("admin"); - inlineConstraints = new ArrayList(1); - constraint = pageManager.newLinkSecurityConstraint(); - constraint.setRoles(Shared.makeListFromCSV("manager")); - constraint.setPermissions(Shared.makeListFromCSV("edit")); - inlineConstraints.add(constraint); - constraints.setSecurityConstraints(inlineConstraints); - link.setSecurityConstraints(constraints); - pageManager.updateLink(link); - - return null; } - catch (Exception e) - { - return e; - } - } - }, null); - if (setup != null) - { - throw setup; - } + }, null); + if (setup != null) { throw setup; } // reset page manager cache pageManager.reset(); // access test as admin user - Exception adminAccess = (Exception)JSSubject.doAsPrivileged(adminSubject, new PrivilegedAction() - { - public Object run() + Exception adminAccess = (Exception) JSSubject.doAsPrivileged( + adminSubject, new PrivilegedAction() { - try - { - // test view access - Folder folder = pageManager.getFolder("/"); - TestCase.assertNotNull(folder.getPageSecurity()); - TestCase.assertNotNull(folder.getPages()); - TestCase.assertEquals(2, folder.getPages().size()); - TestCase.assertNotNull(pageManager.getPages(folder)); - TestCase.assertEquals(2, pageManager.getPages(folder).size()); - PageSecurity pageSecurity = pageManager.getPageSecurity(); - Page page0 = pageManager.getPage("/default-page.psml"); - TestCase.assertNotNull(page0.getRootFragment()); - TestCase.assertNotNull(page0.getRootFragment().getFragments()); - TestCase.assertEquals(2, page0.getRootFragment().getFragments().size()); - TestCase.assertNotNull(page0.getFragmentById(somePortletId[0])); - TestCase.assertNotNull(page0.getFragmentsByName("some-app::SomePortlet")); - TestCase.assertEquals(1, page0.getFragmentsByName("some-app::SomePortlet").size()); - Page page1 = pageManager.getPage("/user-page.psml"); - Link link = pageManager.getLink("/default.link"); - // test edit access - pageManager.updateFolder(folder); - pageManager.updatePageSecurity(pageSecurity); - pageManager.updatePage(page0); - pageManager.updatePage(page1); - pageManager.updateLink(link); - return null; - } - catch (Exception e) - { - return e; - } - } - }, null); - if (adminAccess != null) - { - throw adminAccess; - } - // access test as user user - Exception userAccess = (Exception)JSSubject.doAsPrivileged(userSubject, new PrivilegedAction() - { - public Object run() - { - try + public Object run() { - // test view access - Folder folder = pageManager.getFolder("/"); - TestCase.assertNotNull(folder.getPageSecurity()); - TestCase.assertNotNull(folder.getPages()); - TestCase.assertEquals(2, folder.getPages().size()); - PageSecurity pageSecurity = pageManager.getPageSecurity(); - Page page0 = pageManager.getPage("/default-page.psml"); - TestCase.assertNotNull(page0.getRootFragment()); - TestCase.assertNotNull(page0.getRootFragment().getFragments()); - TestCase.assertEquals(2, page0.getRootFragment().getFragments().size()); - TestCase.assertNotNull(page0.getFragmentById(somePortletId[0])); - TestCase.assertNotNull(page0.getFragmentsByName("some-app::SomePortlet")); - TestCase.assertEquals(1, page0.getFragmentsByName("some-app::SomePortlet").size()); - Page page1 = pageManager.getPage("/user-page.psml"); - Link link = pageManager.getLink("/default.link"); - // test edit access try { + // test view access + Folder folder = pageManager.getFolder("/"); + TestCase + .assertNotNull(folder.getPageSecurity()); + TestCase.assertNotNull(folder.getPages()); + TestCase.assertEquals(2, folder.getPages() + .size()); + TestCase.assertNotNull(pageManager + .getPages(folder)); + TestCase.assertEquals(2, pageManager.getPages( + folder).size()); + PageSecurity pageSecurity = pageManager + .getPageSecurity(); + Page page0 = pageManager + .getPage("/default-page.psml"); + TestCase.assertNotNull(page0.getRootFragment()); + TestCase.assertNotNull(page0.getRootFragment() + .getFragments()); + TestCase.assertEquals(2, page0 + .getRootFragment().getFragments() + .size()); + TestCase.assertNotNull(page0 + .getFragmentById(somePortletId[0])); + TestCase + .assertNotNull(page0 + .getFragmentsByName("some-app::SomePortlet")); + TestCase + .assertEquals( + 1, + page0 + .getFragmentsByName( + "some-app::SomePortlet") + .size()); + Page page1 = pageManager + .getPage("/user-page.psml"); + Link link = pageManager + .getLink("/default.link"); + // test edit access pageManager.updateFolder(folder); - TestCase.assertTrue("Folder / not editable for user", false); - } - catch (SecurityException se) - { - } - try - { pageManager.updatePageSecurity(pageSecurity); - TestCase.assertTrue("PageSecurity not editable for user", false); - } - catch (SecurityException se) - { - } - try - { pageManager.updatePage(page0); - TestCase.assertTrue("Page /default-page.psml not editable for user", false); + pageManager.updatePage(page1); + pageManager.updateLink(link); + return null; } - catch (SecurityException se) + catch (Exception e) { + return e; } - pageManager.updatePage(page1); + } + }, null); + if (adminAccess != null) { throw adminAccess; } + + // access test as user user + Exception userAccess = (Exception) JSSubject.doAsPrivileged( + userSubject, new PrivilegedAction() + { + + public Object run() + { try { - pageManager.updateLink(link); - TestCase.assertTrue("Page /default.link not editable for user", false); + // test view access + Folder folder = pageManager.getFolder("/"); + TestCase + .assertNotNull(folder.getPageSecurity()); + TestCase.assertNotNull(folder.getPages()); + TestCase.assertEquals(2, folder.getPages() + .size()); + PageSecurity pageSecurity = pageManager + .getPageSecurity(); + Page page0 = pageManager + .getPage("/default-page.psml"); + TestCase.assertNotNull(page0.getRootFragment()); + TestCase.assertNotNull(page0.getRootFragment() + .getFragments()); + TestCase.assertEquals(2, page0 + .getRootFragment().getFragments() + .size()); + TestCase.assertNotNull(page0 + .getFragmentById(somePortletId[0])); + TestCase + .assertNotNull(page0 + .getFragmentsByName("some-app::SomePortlet")); + TestCase + .assertEquals( + 1, + page0 + .getFragmentsByName( + "some-app::SomePortlet") + .size()); + Page page1 = pageManager + .getPage("/user-page.psml"); + Link link = pageManager + .getLink("/default.link"); + // test edit access + try + { + pageManager.updateFolder(folder); + TestCase.assertTrue( + "Folder / not editable for user", + false); + } + catch (SecurityException se) + { + } + try + { + pageManager + .updatePageSecurity(pageSecurity); + TestCase + .assertTrue( + "PageSecurity not editable for user", + false); + } + catch (SecurityException se) + { + } + try + { + pageManager.updatePage(page0); + TestCase + .assertTrue( + "Page /default-page.psml not editable for user", + false); + } + catch (SecurityException se) + { + } + pageManager.updatePage(page1); + try + { + pageManager.updateLink(link); + TestCase + .assertTrue( + "Page /default.link not editable for user", + false); + } + catch (SecurityException se) + { + } + return null; } - catch (SecurityException se) + catch (Exception e) { + return e; } - return null; } - catch (Exception e) - { - return e; - } - } - }, null); - if (userAccess != null) - { - throw userAccess; - } + }, null); + if (userAccess != null) { throw userAccess; } // access test as manager user - Exception managerAccess = (Exception)JSSubject.doAsPrivileged(managerSubject, new PrivilegedAction() - { - public Object run() + Exception managerAccess = (Exception) JSSubject.doAsPrivileged( + managerSubject, new PrivilegedAction() { - try + + public Object run() { - // test view access - Folder folder = pageManager.getFolder("/"); - TestCase.assertNotNull(folder.getPageSecurity()); - TestCase.assertNotNull(folder.getPages()); - TestCase.assertEquals(1, folder.getPages().size()); - PageSecurity pageSecurity = pageManager.getPageSecurity(); - Page page0 = pageManager.getPage("/default-page.psml"); - TestCase.assertNotNull(page0.getRootFragment()); - TestCase.assertNotNull(page0.getRootFragment().getFragments()); - TestCase.assertEquals(1, page0.getRootFragment().getFragments().size()); - TestCase.assertNull(page0.getFragmentById(somePortletId[0])); - TestCase.assertTrue(page0.getFragmentsByName("some-app::SomePortlet").isEmpty()); - Link link = pageManager.getLink("/default.link"); try { - pageManager.getPage("/user-page.psml"); - TestCase.assertTrue("Page /user-page.psml not viewable for manager", false); + // test view access + Folder folder = pageManager.getFolder("/"); + TestCase + .assertNotNull(folder.getPageSecurity()); + TestCase.assertNotNull(folder.getPages()); + TestCase.assertEquals(1, folder.getPages() + .size()); + PageSecurity pageSecurity = pageManager + .getPageSecurity(); + Page page0 = pageManager + .getPage("/default-page.psml"); + TestCase.assertNotNull(page0.getRootFragment()); + TestCase.assertNotNull(page0.getRootFragment() + .getFragments()); + TestCase.assertEquals(1, page0 + .getRootFragment().getFragments() + .size()); + TestCase.assertNull(page0 + .getFragmentById(somePortletId[0])); + TestCase.assertTrue(page0.getFragmentsByName( + "some-app::SomePortlet").isEmpty()); + Link link = pageManager + .getLink("/default.link"); + try + { + pageManager.getPage("/user-page.psml"); + TestCase + .assertTrue( + "Page /user-page.psml not viewable for manager", + false); + } + catch (SecurityException se) + { + } + // test edit access + try + { + pageManager.updateFolder(folder); + TestCase + .assertTrue( + "Folder / not editable for manager", + false); + } + catch (SecurityException se) + { + } + try + { + pageManager + .updatePageSecurity(pageSecurity); + TestCase + .assertTrue( + "PageSecurity not editable for manager", + false); + } + catch (SecurityException se) + { + } + pageManager.updatePage(page0); + pageManager.updateLink(link); + return null; } - catch (SecurityException se) + catch (Exception e) { - } - // test edit access - try - { - pageManager.updateFolder(folder); - TestCase.assertTrue("Folder / not editable for manager", false); + return e; } - catch (SecurityException se) - { - } - try - { - pageManager.updatePageSecurity(pageSecurity); - TestCase.assertTrue("PageSecurity not editable for manager", false); - } - catch (SecurityException se) - { - } - pageManager.updatePage(page0); - pageManager.updateLink(link); - return null; } - catch (Exception e) - { - return e; - } - } - }, null); - if (managerAccess != null) - { - throw managerAccess; - } + }, null); + if (managerAccess != null) { throw managerAccess; } // access test as guest user - Exception guestAccess = (Exception)JSSubject.doAsPrivileged(guestSubject, new PrivilegedAction() - { - public Object run() + Exception guestAccess = (Exception) JSSubject.doAsPrivileged( + guestSubject, new PrivilegedAction() { - try + + public Object run() { - // test view access - Folder folder = pageManager.getFolder("/"); - TestCase.assertNotNull(folder.getPageSecurity()); - TestCase.assertNotNull(folder.getPages()); - TestCase.assertEquals(1, folder.getPages().size()); - PageSecurity pageSecurity = pageManager.getPageSecurity(); - Page page0 = pageManager.getPage("/default-page.psml"); - TestCase.assertNotNull(page0.getRootFragment()); - TestCase.assertNotNull(page0.getRootFragment().getFragments()); - TestCase.assertEquals(1, page0.getRootFragment().getFragments().size()); - TestCase.assertNull(page0.getFragmentById(somePortletId[0])); - TestCase.assertTrue(page0.getFragmentsByName("some-app::SomePortlet").isEmpty()); - Link link = pageManager.getLink("/default.link"); try { - pageManager.getPage("/user-page.psml"); - TestCase.assertTrue("Page /user-page.psml not viewable for guest", false); + // test view access + Folder folder = pageManager.getFolder("/"); + TestCase + .assertNotNull(folder.getPageSecurity()); + TestCase.assertNotNull(folder.getPages()); + TestCase.assertEquals(1, folder.getPages() + .size()); + PageSecurity pageSecurity = pageManager + .getPageSecurity(); + Page page0 = pageManager + .getPage("/default-page.psml"); + TestCase.assertNotNull(page0.getRootFragment()); + TestCase.assertNotNull(page0.getRootFragment() + .getFragments()); + TestCase.assertEquals(1, page0 + .getRootFragment().getFragments() + .size()); + TestCase.assertNull(page0 + .getFragmentById(somePortletId[0])); + TestCase.assertTrue(page0.getFragmentsByName( + "some-app::SomePortlet").isEmpty()); + Link link = pageManager + .getLink("/default.link"); + try + { + pageManager.getPage("/user-page.psml"); + TestCase + .assertTrue( + "Page /user-page.psml not viewable for guest", + false); + } + catch (SecurityException se) + { + } + // test edit access + try + { + pageManager.updateFolder(folder); + TestCase.assertTrue( + "Folder / not editable for guest", + false); + } + catch (SecurityException se) + { + } + try + { + pageManager + .updatePageSecurity(pageSecurity); + TestCase + .assertTrue( + "PageSecurity not editable for guest", + false); + } + catch (SecurityException se) + { + } + try + { + pageManager.updatePage(page0); + TestCase + .assertTrue( + "Page /default-page.psml not editable for guest", + false); + } + catch (SecurityException se) + { + } + try + { + pageManager.updateLink(link); + TestCase + .assertTrue( + "Page /default.link not editable for guest", + false); + } + catch (SecurityException se) + { + } + return null; } - catch (SecurityException se) + catch (Exception e) { - } - // test edit access - try - { - pageManager.updateFolder(folder); - TestCase.assertTrue("Folder / not editable for guest", false); + return e; } - catch (SecurityException se) - { - } - try - { - pageManager.updatePageSecurity(pageSecurity); - TestCase.assertTrue("PageSecurity not editable for guest", false); - } - catch (SecurityException se) - { - } - try - { - pageManager.updatePage(page0); - TestCase.assertTrue("Page /default-page.psml not editable for guest", false); - } - catch (SecurityException se) - { - } - try - { - pageManager.updateLink(link); - TestCase.assertTrue("Page /default.link not editable for guest", false); - } - catch (SecurityException se) - { - } - return null; } - catch (Exception e) - { - return e; - } - } - }, null); - if (guestAccess != null) - { - throw guestAccess; - } + }, null); + if (guestAccess != null) { throw guestAccess; } // reset page manager cache pageManager.reset(); // cleanup test as admin user - Exception cleanup = (Exception)JSSubject.doAsPrivileged(adminSubject, new PrivilegedAction() - { - public Object run() + Exception cleanup = (Exception) JSSubject.doAsPrivileged( + adminSubject, new PrivilegedAction() { - try + + public Object run() { - // cleanup by removing root folder try { - Folder remove = pageManager.getFolder("/"); - TestCase.assertEquals("/", remove.getPath()); - pageManager.removeFolder(remove); + // cleanup by removing root folder + try + { + Folder remove = pageManager.getFolder("/"); + TestCase + .assertEquals("/", remove.getPath()); + pageManager.removeFolder(remove); + } + catch (FolderNotFoundException e) + { + TestCase.assertTrue("Folder / NOT FOUND", + false); + } + + return null; } - catch (FolderNotFoundException e) + catch (Exception e) { - TestCase.assertTrue("Folder / NOT FOUND", false); + return e; } - - return null; } - catch (Exception e) - { - return e; - } - } - }, null); - if (cleanup != null) - { - throw cleanup; - } + }, null); + if (cleanup != null) { throw cleanup; } } } /** * PageManagerPermissionsPolicy - * - * Policy implementation for permissions based security - * tests against testSecurePageManager test case above. + * + * Policy implementation for permissions based security tests against + * testSecurePageManager test case above. */ static class PageManagerPermissionsPolicy extends Policy { + private Policy defaultPolicy; public PageManagerPermissionsPolicy(Policy defaultPolicy) @@ -668,10 +847,10 @@ // call stack, so this method will be invoked 2-3 times for each // access check with the identical principals and permission Principal[] principals = domain.getPrincipals(); - if ((principals != null) && (principals.length > 0) && - ((permission instanceof FolderPermission) || - (permission instanceof PagePermission) || - (permission instanceof FragmentPermission))) + if ((principals != null) + && (principals.length > 0) + && ((permission instanceof FolderPermission) + || (permission instanceof PagePermission) || (permission instanceof FragmentPermission))) { // check permission using principals if available Permissions permissions = new Permissions(); @@ -684,24 +863,33 @@ if (user.equals("admin")) { // owner permissions - permissions.add(new FolderPermission("/", "view, edit")); - permissions.add(new PagePermission("/default-page.psml", "view, edit")); + permissions.add(new FolderPermission("/", + "view, edit")); + permissions.add(new PagePermission( + "/default-page.psml", "view, edit")); } else if (user.equals("user")) { // owner permissions - permissions.add(new FragmentPermission("/default-page.psml/some-app::SomePortlet", "view, edit")); - + permissions.add(new FragmentPermission( + "/default-page.psml/some-app::SomePortlet", + "view, edit")); + // granted permissions - permissions.add(new PagePermission("/user-page.psml", "view, edit")); - permissions.add(new FragmentPermission("/user-page.psml/*", "view")); + permissions.add(new PagePermission( + "/user-page.psml", "view, edit")); + permissions.add(new FragmentPermission( + "/user-page.psml/*", "view")); } - + // public view permissions permissions.add(new FolderPermission("/", "view")); - permissions.add(new PagePermission("/default-page.psml", "view")); - permissions.add(new PagePermission("/page.security", "view")); - permissions.add(new FragmentPermission("security::*", "view")); + permissions.add(new PagePermission( + "/default-page.psml", "view")); + permissions.add(new PagePermission("/page.security", + "view")); + permissions.add(new FragmentPermission("security::*", + "view")); } else if (principals[i] instanceof RolePrincipal) { @@ -710,30 +898,29 @@ if (role.equals("admin")) { // global permissions - permissions.add(new FolderPermission("<>", "view, edit")); - permissions.add(new FragmentPermission("<>", "view, edit")); + permissions.add(new FolderPermission( + "<>", "view, edit")); + permissions.add(new FragmentPermission( + "<>", "view, edit")); } else if (role.equals("manager")) { // granted permissions - permissions.add(new PagePermission("/default-page.psml", "edit")); - permissions.add(new PagePermission("/default.link", "edit")); + permissions.add(new PagePermission( + "/default-page.psml", "edit")); + permissions.add(new PagePermission("/default.link", + "edit")); } } } - + // check permission - if (permissions.implies(permission)) - { - return true; - } + if (permissions.implies(permission)) { return true; } } // check default permissions - if (defaultPolicy != null) - { - return defaultPolicy.implies(domain, permission); - } + if (defaultPolicy != null) { return defaultPolicy.implies(domain, + permission); } return false; } @@ -741,10 +928,8 @@ { // return default permissions only since // domain and permsission not available - if (defaultPolicy != null) - { - return defaultPolicy.getPermissions(domain); - } + if (defaultPolicy != null) { return defaultPolicy + .getPermissions(domain); } return new Permissions(); } @@ -752,10 +937,8 @@ { // return default permissions only since // domain and permsission not available - if (defaultPolicy != null) - { - return defaultPolicy.getPermissions(codesource); - } + if (defaultPolicy != null) { return defaultPolicy + .getPermissions(codesource); } return new Permissions(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestCastorXmlPageManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestCastorXmlPageManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestCastorXmlPageManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -53,16 +53,25 @@ * * @author Rapha\u00ebl Luta * @author Randy Watler - * @version $Id: TestCastorXmlPageManager.java 553584 2007-07-05 18:09:45Z taylor $ + * @version $Id: TestCastorXmlPageManager.java 553584 2007-07-05 18:09:45Z + * taylor $ */ -public class TestCastorXmlPageManager extends TestCase implements PageManagerTestShared +public class TestCastorXmlPageManager extends TestCase implements + PageManagerTestShared { + private String testPage002 = "/test002.psml"; + private String testPage003 = "/test003.psml"; + private String testPage004 = "/folder2/test004.psml"; + private String testFolder2 = "/folder2"; + private String testFolder3 = "/folder3"; + private String testLink002 = "/test002.link"; + private String testLink003 = "/test003.link"; protected CastorXmlPageManager pageManager; @@ -97,7 +106,7 @@ * @param name * the testcase's name. */ - public TestCastorXmlPageManager( String name ) + public TestCastorXmlPageManager(String name) { super(name); } @@ -108,9 +117,10 @@ * @param args * the arguments. Not used */ - public static void main( String args[] ) + public static void main(String args[]) { - junit.awtui.TestRunner.main(new String[]{TestCastorXmlPageManager.class.getName()}); + junit.awtui.TestRunner.main(new String[] + {TestCastorXmlPageManager.class.getName()}); } /** @@ -169,9 +179,12 @@ assertTrue(testpage.getId().equals("/test001.psml")); assertTrue(testpage.getTitle().equals("Test Page")); assertTrue(testpage.getSkin().equals("test-skin")); - assertTrue(testpage.getEffectiveDefaultDecorator(Fragment.LAYOUT).equals("test-layout")); - assertTrue(testpage.getDefaultDecorator(Fragment.LAYOUT).equals("test-layout")); - assertTrue(testpage.getDefaultDecorator(Fragment.PORTLET).equals("test-portlet")); + assertTrue(testpage.getEffectiveDefaultDecorator(Fragment.LAYOUT) + .equals("test-layout")); + assertTrue(testpage.getDefaultDecorator(Fragment.LAYOUT).equals( + "test-layout")); + assertTrue(testpage.getDefaultDecorator(Fragment.PORTLET).equals( + "test-portlet")); assertTrue(testpage.getVersion().equals("2.77")); GenericMetadata md = testpage.getMetadata(); @@ -206,27 +219,35 @@ assertNotNull(f.getProperty(Fragment.X_PROPERTY_NAME)); assertTrue(f.getProperty(Fragment.X_PROPERTY_NAME).startsWith("11.1")); assertTrue((f.getLayoutX() > 11.0F) && (f.getLayoutX() < 12.0F)); - assertTrue((f.getFloatProperty(Fragment.X_PROPERTY_NAME) > 11.0F) && - (f.getFloatProperty(Fragment.X_PROPERTY_NAME) < 12.0F)); + assertTrue((f.getFloatProperty(Fragment.X_PROPERTY_NAME) > 11.0F) + && (f.getFloatProperty(Fragment.X_PROPERTY_NAME) < 12.0F)); assertTrue((f.getLayoutY() > 22.0F) && (f.getLayoutY() < 23.0F)); assertTrue((f.getLayoutZ() > 33.0F) && (f.getLayoutZ() < 34.0F)); assertTrue((f.getLayoutWidth() > 44.0F) && (f.getLayoutWidth() < 45.0F)); - assertTrue((f.getLayoutHeight() > 55.0F) && (f.getLayoutWidth() < 56.0F)); + assertTrue((f.getLayoutHeight() > 55.0F) + && (f.getLayoutWidth() < 56.0F)); List preferences = f.getPreferences(); assertNotNull(preferences); assertTrue(preferences.size() == 2); - assertEquals("pref0", ((FragmentPreference)preferences.get(0)).getName()); - assertTrue(((FragmentPreference)preferences.get(0)).isReadOnly()); - assertNotNull(((FragmentPreference)preferences.get(0)).getValueList()); - assertEquals(2, ((FragmentPreference)preferences.get(0)).getValueList().size()); - assertEquals("pref0-value0", (String)((FragmentPreference)preferences.get(0)).getValueList().get(0)); - assertEquals("pref0-value1", (String)((FragmentPreference)preferences.get(0)).getValueList().get(1)); - assertEquals("pref1", ((FragmentPreference)preferences.get(1)).getName()); - assertFalse(((FragmentPreference)preferences.get(1)).isReadOnly()); - assertNotNull(((FragmentPreference)preferences.get(1)).getValueList()); - assertEquals(1, ((FragmentPreference)preferences.get(1)).getValueList().size()); - assertEquals("pref1-value", (String)((FragmentPreference)preferences.get(1)).getValueList().get(0)); + assertEquals("pref0", ((FragmentPreference) preferences.get(0)) + .getName()); + assertTrue(((FragmentPreference) preferences.get(0)).isReadOnly()); + assertNotNull(((FragmentPreference) preferences.get(0)).getValueList()); + assertEquals(2, ((FragmentPreference) preferences.get(0)) + .getValueList().size()); + assertEquals("pref0-value0", (String) ((FragmentPreference) preferences + .get(0)).getValueList().get(0)); + assertEquals("pref0-value1", (String) ((FragmentPreference) preferences + .get(0)).getValueList().get(1)); + assertEquals("pref1", ((FragmentPreference) preferences.get(1)) + .getName()); + assertFalse(((FragmentPreference) preferences.get(1)).isReadOnly()); + assertNotNull(((FragmentPreference) preferences.get(1)).getValueList()); + assertEquals(1, ((FragmentPreference) preferences.get(1)) + .getValueList().size()); + assertEquals("pref1-value", (String) ((FragmentPreference) preferences + .get(1)).getValueList().get(0)); f = (Fragment) children.get(1); assertTrue(f.getId().equals("pe002")); @@ -251,9 +272,10 @@ List fragments = testpage.getFragmentsByName("JMXPortlet"); assertNotNull(fragments); assertEquals(1, fragments.size()); - assertTrue(((Fragment)fragments.get(0)).getId().equals("pe002")); - assertTrue(((Fragment)fragments.get(0)).getName().equals("JMXPortlet")); - assertTrue(((Fragment)fragments.get(0)).getType().equals(Fragment.PORTLET)); + assertTrue(((Fragment) fragments.get(0)).getId().equals("pe002")); + assertTrue(((Fragment) fragments.get(0)).getName().equals("JMXPortlet")); + assertTrue(((Fragment) fragments.get(0)).getType().equals( + Fragment.PORTLET)); } public void testCreatePage() throws Exception @@ -264,7 +286,8 @@ page.setTitle("Created Page"); GenericMetadata metadata = page.getMetadata(); metadata.addField(Locale.FRENCH, "title", "Created Page de PSML"); - metadata.addField(Locale.JAPANESE, "title", "Created \u3078\u3088\u3046\u3053\u305d"); + metadata.addField(Locale.JAPANESE, "title", + "Created \u3078\u3088\u3046\u3053\u305d"); Fragment root = page.getRootFragment(); root.setName("TestLayout"); @@ -282,7 +305,8 @@ SecurityConstraint constraint = page.newSecurityConstraint(); constraint.setUsers(Shared.makeListFromCSV("user10,user11")); constraint.setRoles(Shared.makeListFromCSV("*")); - constraint.setPermissions(Shared.makeListFromCSV(JetspeedActions.EDIT + "," + JetspeedActions.VIEW)); + constraint.setPermissions(Shared.makeListFromCSV(JetspeedActions.EDIT + + "," + JetspeedActions.VIEW)); constraintsList.add(constraint); constraints.setSecurityConstraints(constraintsList); List constraintsRefsList = new ArrayList(1); @@ -307,7 +331,8 @@ assertTrue(page.getId().equals(this.testPage002)); assertEquals("Created Page", page.getTitle()); assertEquals("Created Page de PSML", page.getTitle(Locale.FRENCH)); - assertEquals("Created \u3078\u3088\u3046\u3053\u305d", page.getTitle(Locale.JAPANESE)); + assertEquals("Created \u3078\u3088\u3046\u3053\u305d", page + .getTitle(Locale.JAPANESE)); assertNotNull(page.getRootFragment()); assertTrue(page.getRootFragment().getName().equals("TestLayout")); assertTrue(page.getRootFragment().getFragments().size() == 1); @@ -343,9 +368,12 @@ assertTrue(folder.getId().equals(this.testFolder2)); assertTrue(folder.getTitle().equals("Created Folder")); assertTrue(folder.getSkin().equals("test-skin")); - assertTrue(folder.getEffectiveDefaultDecorator(Fragment.LAYOUT).equals("test-layout")); - assertTrue(folder.getDefaultDecorator(Fragment.LAYOUT).equals("test-layout")); - assertTrue(folder.getDefaultDecorator(Fragment.PORTLET).equals("test-portlet")); + assertTrue(folder.getEffectiveDefaultDecorator(Fragment.LAYOUT).equals( + "test-layout")); + assertTrue(folder.getDefaultDecorator(Fragment.LAYOUT).equals( + "test-layout")); + assertTrue(folder.getDefaultDecorator(Fragment.PORTLET).equals( + "test-portlet")); } public void testCreateLink() throws Exception @@ -383,7 +411,7 @@ assertNotNull(root); assertNotNull(root.getFragments()); assertEquals(1, root.getFragments().size()); - String testId = ((Fragment)root.getFragments().get(0)).getId(); + String testId = ((Fragment) root.getFragments().get(0)).getId(); assertNotNull(page.removeFragmentById(testId)); try @@ -498,23 +526,26 @@ int count = 0; while (ssi.hasNext()) { - Folder folder = (Folder)ssi.next(); + Folder folder = (Folder) ssi.next(); System.out.println("folder = " + folder.getName()); count++; } assertEquals(4, count); } - + public void testFolders() throws Exception { Folder folder1 = pageManager.getFolder("/folder1"); assertNotNull(folder1); assertTrue(folder1.getSkin().equals("test-skin")); - assertTrue(folder1.getEffectiveDefaultDecorator(Fragment.LAYOUT).equals("test-layout")); - assertTrue(folder1.getDefaultDecorator(Fragment.LAYOUT).equals("test-layout")); - assertTrue(folder1.getDefaultDecorator(Fragment.PORTLET).equals("test-portlet")); - + assertTrue(folder1.getEffectiveDefaultDecorator(Fragment.LAYOUT) + .equals("test-layout")); + assertTrue(folder1.getDefaultDecorator(Fragment.LAYOUT).equals( + "test-layout")); + assertTrue(folder1.getDefaultDecorator(Fragment.PORTLET).equals( + "test-portlet")); + assertEquals(2, folder1.getFolders().size()); assertEquals(2, pageManager.getFolders(folder1).size()); Iterator childItr = folder1.getFolders().iterator(); @@ -530,58 +561,69 @@ assertEquals(2, pageManager.getPages(folder3).size()); // test folder decoration inheritance - Page page = (Page)folder3.getPages().get("test001.psml"); - assertTrue(page.getEffectiveDefaultDecorator(Fragment.LAYOUT).equals("test-layout")); - assertTrue(page.getEffectiveDefaultDecorator(Fragment.PORTLET).equals("test-portlet")); - + Page page = (Page) folder3.getPages().get("test001.psml"); + assertTrue(page.getEffectiveDefaultDecorator(Fragment.LAYOUT).equals( + "test-layout")); + assertTrue(page.getEffectiveDefaultDecorator(Fragment.PORTLET).equals( + "test-portlet")); + // Check link order assertEquals(6, folder3.getAll().size()); assertEquals(6, pageManager.getAll(folder3).size()); Iterator linkItr = folder3.getAll().iterator(); - assertEquals("Jetspeed2Wiki.link", ((Link)linkItr.next()).getName()); - assertEquals("Jetspeed2.link", ((Link)linkItr.next()).getName()); - assertEquals("apache_portals.link", ((Link)linkItr.next()).getName()); - assertEquals("apache.link", ((Link)linkItr.next()).getName()); - assertEquals("test001.psml", ((Page)linkItr.next()).getName()); - assertEquals("default-page.psml", ((Page)linkItr.next()).getName()); + assertEquals("Jetspeed2Wiki.link", ((Link) linkItr.next()).getName()); + assertEquals("Jetspeed2.link", ((Link) linkItr.next()).getName()); + assertEquals("apache_portals.link", ((Link) linkItr.next()).getName()); + assertEquals("apache.link", ((Link) linkItr.next()).getName()); + assertEquals("test001.psml", ((Page) linkItr.next()).getName()); + assertEquals("default-page.psml", ((Page) linkItr.next()).getName()); - //Test FolderSet with both absolute and relative names + // Test FolderSet with both absolute and relative names assertNotNull(folder1.getFolders().get("/folder1/folder2")); assertNotNull(folder1.getFolders().get("folder2")); - assertEquals(folder1.getFolders().get("/folder1/folder2"), folder1.getFolders().get("folder2")); + assertEquals(folder1.getFolders().get("/folder1/folder2"), folder1 + .getFolders().get("folder2")); - //Test PageSet with both absolute and relative names + // Test PageSet with both absolute and relative names assertNotNull(folder3.getPages().get("/folder1/folder3/test001.psml")); assertNotNull(folder3.getPages().get("test001.psml")); - assertEquals("test001.psml", folder3.getPages().get("/folder1/folder3/test001.psml").getName()); - + assertEquals("test001.psml", folder3.getPages().get( + "/folder1/folder3/test001.psml").getName()); + assertTrue(folder3.isHidden()); assertTrue(folder3.getPage("default-page.psml").isHidden()); assertTrue(folder3.getLinks().get("Jetspeed2.link").isHidden()); assertFalse(folder3.getLinks().get("apache.link").isHidden()); - + assertNotNull(folder3.getAll().get("Jetspeed2.link")); - assertNull(folder3.getAll().exclusiveSubset("Jetspeed2\\.link").get("Jetspeed2.link")); - assertNull(folder3.getAll().inclusiveSubset("apache\\.link").get("Jetspeed2.link")); - assertNotNull(folder3.getAll().inclusiveSubset("apache\\.link").get("apache.link")); + assertNull(folder3.getAll().exclusiveSubset("Jetspeed2\\.link").get( + "Jetspeed2.link")); + assertNull(folder3.getAll().inclusiveSubset("apache\\.link").get( + "Jetspeed2.link")); + assertNotNull(folder3.getAll().inclusiveSubset("apache\\.link").get( + "apache.link")); } public void testFolderMetaData() throws Exception { - Folder folder1French = pageManager.getFolder("/folder1"); + Folder folder1French = pageManager.getFolder("/folder1"); - assertEquals("Titre francais pour la chemise 1", folder1French.getTitle(Locale.FRENCH)); - assertEquals("Titre francais pour la chemise 1", folder1French.getTitle(Locale.FRANCE)); + assertEquals("Titre francais pour la chemise 1", folder1French + .getTitle(Locale.FRENCH)); + assertEquals("Titre francais pour la chemise 1", folder1French + .getTitle(Locale.FRANCE)); Folder folder1English = pageManager.getFolder("/folder1"); - assertEquals("English Title for Folder 1", folder1English.getTitle(Locale.ENGLISH)); + assertEquals("English Title for Folder 1", folder1English + .getTitle(Locale.ENGLISH)); // check that default works Folder folder1German = pageManager.getFolder("/folder1"); - - assertEquals("Default Title for Folder 1", folder1German.getTitle(Locale.GERMAN)); - + + assertEquals("Default Title for Folder 1", folder1German + .getTitle(Locale.GERMAN)); + // Test folder with no metadata assigned Folder rootFolder = pageManager.getFolder("/"); assertEquals(rootFolder.getTitle(), rootFolder.getTitle(Locale.FRENCH)); @@ -589,7 +631,8 @@ public void testDefaultTitles() throws Exception { - Page defaultPage = pageManager.getPage("/folder1/folder2/default-page.psml"); + Page defaultPage = pageManager + .getPage("/folder1/folder2/default-page.psml"); assertNotNull(defaultPage); assertEquals("Default Page", defaultPage.getTitle()); @@ -618,15 +661,17 @@ assertNotNull(link); assertEquals("http://portals.apache.org", link.getUrl()); assertEquals("Apache Portals Website", link.getTitle()); - assertEquals("Apache Software Foundation [french]", link.getTitle(Locale.FRENCH)); + assertEquals("Apache Software Foundation [french]", link + .getTitle(Locale.FRENCH)); assertEquals("test-skin", link.getSkin()); Folder folder = pageManager.getFolder("/"); assertNotNull(folder); assertNotNull(folder.getLinks()); - assertEquals(2,folder.getLinks().size()); - assertEquals(2,pageManager.getLinks(folder).size()); - assertEquals("http://portals.apache.org", ((Document) folder.getLinks().get("/apache_portals.link")).getUrl()); + assertEquals(2, folder.getLinks().size()); + assertEquals(2, pageManager.getLinks(folder).size()); + assertEquals("http://portals.apache.org", ((Document) folder.getLinks() + .get("/apache_portals.link")).getUrl()); } public void testMenuDefinitions() throws Exception @@ -638,15 +683,17 @@ assertNotNull(menus); assertEquals(5, menus.size()); - MenuDefinition simpleMenu = (MenuDefinition)menus.get(0); + MenuDefinition simpleMenu = (MenuDefinition) menus.get(0); assertNotNull(simpleMenu); assertEquals("simple", simpleMenu.getName()); assertNotNull(simpleMenu.getMenuElements()); assertEquals(1, simpleMenu.getMenuElements().size()); assertTrue(simpleMenu.getMenuElements().get(0) instanceof MenuOptionsDefinition); - assertEquals("/test001.psml,/folder1/folder2", ((MenuOptionsDefinition)simpleMenu.getMenuElements().get(0)).getOptions()); + assertEquals("/test001.psml,/folder1/folder2", + ((MenuOptionsDefinition) simpleMenu.getMenuElements().get(0)) + .getOptions()); - MenuDefinition top2LevelsMenu = (MenuDefinition)menus.get(1); + MenuDefinition top2LevelsMenu = (MenuDefinition) menus.get(1); assertNotNull(top2LevelsMenu); assertEquals("top-2-levels", top2LevelsMenu.getName()); assertNull(top2LevelsMenu.getMenuElements()); @@ -654,19 +701,19 @@ assertEquals(2, top2LevelsMenu.getDepth()); assertEquals("dhtml-pull-down", top2LevelsMenu.getSkin()); - MenuDefinition topRolePagesMenu = (MenuDefinition)menus.get(2); + MenuDefinition topRolePagesMenu = (MenuDefinition) menus.get(2); assertNotNull(topRolePagesMenu); assertEquals("top-role-pages", topRolePagesMenu.getName()); assertTrue(topRolePagesMenu.isRegexp()); assertEquals("roles", topRolePagesMenu.getProfile()); assertEquals("*.psml,*.link", topRolePagesMenu.getOrder()); - MenuDefinition breadCrumbsMenu = (MenuDefinition)menus.get(3); + MenuDefinition breadCrumbsMenu = (MenuDefinition) menus.get(3); assertNotNull(breadCrumbsMenu); assertEquals("bread-crumbs", breadCrumbsMenu.getName()); assertTrue(breadCrumbsMenu.isPaths()); - MenuDefinition topCustomMenu = (MenuDefinition)menus.get(4); + MenuDefinition topCustomMenu = (MenuDefinition) menus.get(4); assertNotNull(topCustomMenu); assertEquals("top-custom", topCustomMenu.getName()); assertEquals("Top Menu", topCustomMenu.getTitle()); @@ -676,38 +723,61 @@ assertNotNull(topCustomMenu.getMenuElements()); assertEquals(5, topCustomMenu.getMenuElements().size()); assertTrue(topCustomMenu.getMenuElements().get(0) instanceof MenuOptionsDefinition); - assertTrue(((MenuOptionsDefinition)topCustomMenu.getMenuElements().get(0)).isRegexp()); - assertEquals("groups", ((MenuOptionsDefinition)topCustomMenu.getMenuElements().get(0)).getProfile()); + assertTrue(((MenuOptionsDefinition) topCustomMenu.getMenuElements() + .get(0)).isRegexp()); + assertEquals("groups", ((MenuOptionsDefinition) topCustomMenu + .getMenuElements().get(0)).getProfile()); assertTrue(topCustomMenu.getMenuElements().get(1) instanceof MenuDefinition); assertTrue(topCustomMenu.getMenuElements().get(2) instanceof MenuExcludeDefinition); - assertEquals("top-role-pages", ((MenuExcludeDefinition)topCustomMenu.getMenuElements().get(2)).getName()); + assertEquals("top-role-pages", ((MenuExcludeDefinition) topCustomMenu + .getMenuElements().get(2)).getName()); assertTrue(topCustomMenu.getMenuElements().get(3) instanceof MenuSeparatorDefinition); - assertEquals("More Top Pages", ((MenuSeparatorDefinition)topCustomMenu.getMenuElements().get(3)).getText()); + assertEquals("More Top Pages", ((MenuSeparatorDefinition) topCustomMenu + .getMenuElements().get(3)).getText()); assertTrue(topCustomMenu.getMenuElements().get(4) instanceof MenuIncludeDefinition); - assertEquals("simple", ((MenuIncludeDefinition)topCustomMenu.getMenuElements().get(4)).getName()); - assertTrue(((MenuIncludeDefinition)topCustomMenu.getMenuElements().get(4)).isNest()); + assertEquals("simple", ((MenuIncludeDefinition) topCustomMenu + .getMenuElements().get(4)).getName()); + assertTrue(((MenuIncludeDefinition) topCustomMenu.getMenuElements() + .get(4)).isNest()); - MenuDefinition topCustomNestedMenu = (MenuDefinition)topCustomMenu.getMenuElements().get(1); + MenuDefinition topCustomNestedMenu = (MenuDefinition) topCustomMenu + .getMenuElements().get(1); assertEquals("/", topCustomNestedMenu.getOptions()); assertEquals("page", topCustomNestedMenu.getProfile()); assertEquals(5, topCustomNestedMenu.getMenuElements().size()); assertTrue(topCustomNestedMenu.getMenuElements().get(0) instanceof MenuSeparatorDefinition); - assertEquals("Top Pages", ((MenuSeparatorDefinition)topCustomNestedMenu.getMenuElements().get(0)).getText()); - assertEquals("Ye Olde Top Pages", ((MenuSeparatorDefinition)topCustomNestedMenu.getMenuElements().get(0)).getText(Locale.ENGLISH)); - assertEquals("Select from Top Pages menu...", ((MenuSeparatorDefinition)topCustomNestedMenu.getMenuElements().get(0)).getTitle()); - assertEquals("Haut", ((MenuSeparatorDefinition)topCustomNestedMenu.getMenuElements().get(0)).getTitle(Locale.FRENCH)); + assertEquals("Top Pages", + ((MenuSeparatorDefinition) topCustomNestedMenu + .getMenuElements().get(0)).getText()); + assertEquals("Ye Olde Top Pages", + ((MenuSeparatorDefinition) topCustomNestedMenu + .getMenuElements().get(0)).getText(Locale.ENGLISH)); + assertEquals("Select from Top Pages menu...", + ((MenuSeparatorDefinition) topCustomNestedMenu + .getMenuElements().get(0)).getTitle()); + assertEquals("Haut", ((MenuSeparatorDefinition) topCustomNestedMenu + .getMenuElements().get(0)).getTitle(Locale.FRENCH)); assertTrue(topCustomNestedMenu.getMenuElements().get(1) instanceof MenuOptionsDefinition); assertTrue(topCustomNestedMenu.getMenuElements().get(2) instanceof MenuSeparatorDefinition); - assertEquals("bold", ((MenuSeparatorDefinition)topCustomNestedMenu.getMenuElements().get(2)).getSkin()); - assertEquals("Custom Pages", ((MenuSeparatorDefinition)topCustomNestedMenu.getMenuElements().get(2)).getTitle()); + assertEquals("bold", ((MenuSeparatorDefinition) topCustomNestedMenu + .getMenuElements().get(2)).getSkin()); + assertEquals("Custom Pages", + ((MenuSeparatorDefinition) topCustomNestedMenu + .getMenuElements().get(2)).getTitle()); assertTrue(topCustomNestedMenu.getMenuElements().get(3) instanceof MenuOptionsDefinition); - assertEquals(1, ((MenuOptionsDefinition)topCustomNestedMenu.getMenuElements().get(3)).getDepth()); - assertEquals("*.psml", ((MenuOptionsDefinition)topCustomNestedMenu.getMenuElements().get(3)).getOrder()); + assertEquals(1, ((MenuOptionsDefinition) topCustomNestedMenu + .getMenuElements().get(3)).getDepth()); + assertEquals("*.psml", ((MenuOptionsDefinition) topCustomNestedMenu + .getMenuElements().get(3)).getOrder()); assertTrue(topCustomNestedMenu.getMenuElements().get(4) instanceof MenuOptionsDefinition); - assertTrue(((MenuOptionsDefinition)topCustomNestedMenu.getMenuElements().get(4)).isPaths()); - assertEquals("*", ((MenuOptionsDefinition)topCustomNestedMenu.getMenuElements().get(4)).getProfile()); - assertEquals("links", ((MenuOptionsDefinition)topCustomNestedMenu.getMenuElements().get(4)).getSkin()); - assertEquals("@", ((MenuOptionsDefinition)topCustomNestedMenu.getMenuElements().get(4)).getOptions()); + assertTrue(((MenuOptionsDefinition) topCustomNestedMenu + .getMenuElements().get(4)).isPaths()); + assertEquals("*", ((MenuOptionsDefinition) topCustomNestedMenu + .getMenuElements().get(4)).getProfile()); + assertEquals("links", ((MenuOptionsDefinition) topCustomNestedMenu + .getMenuElements().get(4)).getSkin()); + assertEquals("@", ((MenuOptionsDefinition) topCustomNestedMenu + .getMenuElements().get(4)).getOptions()); // test page resident menu definitions Page page = pageManager.getPage("/test001.psml"); @@ -716,7 +786,7 @@ assertNotNull(menus); assertEquals(1, menus.size()); - simpleMenu = (MenuDefinition)menus.get(0); + simpleMenu = (MenuDefinition) menus.get(0); assertNotNull(simpleMenu); assertEquals("simple", simpleMenu.getName()); assertNotNull(simpleMenu.getMenuElements()); @@ -729,7 +799,8 @@ newMenu.setName("updated-menu"); newMenu.setSkin("tabs"); newMenu.setMenuElements(new ArrayList()); - MenuSeparatorDefinition newSeparator = page.newMenuSeparatorDefinition(); + MenuSeparatorDefinition newSeparator = page + .newMenuSeparatorDefinition(); newSeparator.setText("-- Updated Menu --"); newMenu.getMenuElements().add(newSeparator); MenuOptionsDefinition newOptions0 = page.newMenuOptionsDefinition(); @@ -765,14 +836,22 @@ page = pageManager.getPage(this.testPage002); assertNotNull(page.getMenuDefinitions()); assertEquals(1, page.getMenuDefinitions().size()); - assertNotNull(((MenuDefinition)page.getMenuDefinitions().get(0)).getMenuElements()); - assertEquals(6,((MenuDefinition)page.getMenuDefinitions().get(0)).getMenuElements().size()); - assertTrue(((MenuDefinition)page.getMenuDefinitions().get(0)).getMenuElements().get(0) instanceof MenuSeparatorDefinition); - assertTrue(((MenuDefinition)page.getMenuDefinitions().get(0)).getMenuElements().get(1) instanceof MenuOptionsDefinition); - assertTrue(((MenuDefinition)page.getMenuDefinitions().get(0)).getMenuElements().get(2) instanceof MenuOptionsDefinition); - assertTrue(((MenuDefinition)page.getMenuDefinitions().get(0)).getMenuElements().get(3) instanceof MenuDefinition); - assertTrue(((MenuDefinition)page.getMenuDefinitions().get(0)).getMenuElements().get(4) instanceof MenuExcludeDefinition); - assertTrue(((MenuDefinition)page.getMenuDefinitions().get(0)).getMenuElements().get(5) instanceof MenuIncludeDefinition); + assertNotNull(((MenuDefinition) page.getMenuDefinitions().get(0)) + .getMenuElements()); + assertEquals(6, ((MenuDefinition) page.getMenuDefinitions().get(0)) + .getMenuElements().size()); + assertTrue(((MenuDefinition) page.getMenuDefinitions().get(0)) + .getMenuElements().get(0) instanceof MenuSeparatorDefinition); + assertTrue(((MenuDefinition) page.getMenuDefinitions().get(0)) + .getMenuElements().get(1) instanceof MenuOptionsDefinition); + assertTrue(((MenuDefinition) page.getMenuDefinitions().get(0)) + .getMenuElements().get(2) instanceof MenuOptionsDefinition); + assertTrue(((MenuDefinition) page.getMenuDefinitions().get(0)) + .getMenuElements().get(3) instanceof MenuDefinition); + assertTrue(((MenuDefinition) page.getMenuDefinitions().get(0)) + .getMenuElements().get(4) instanceof MenuExcludeDefinition); + assertTrue(((MenuDefinition) page.getMenuDefinitions().get(0)) + .getMenuElements().get(5) instanceof MenuIncludeDefinition); // test writing folder menu definitions folder = pageManager.getFolder(this.testFolder2); @@ -797,9 +876,13 @@ folder = pageManager.getFolder(this.testFolder2); assertNotNull(folder.getMenuDefinitions()); assertEquals(1, folder.getMenuDefinitions().size()); - assertEquals("updated-menu", ((MenuDefinition)folder.getMenuDefinitions().get(0)).getName()); - assertEquals("bread-crumbs", ((MenuDefinition)folder.getMenuDefinitions().get(0)).getSkin()); - assertEquals("./", ((MenuDefinition)folder.getMenuDefinitions().get(0)).getOptions()); + assertEquals("updated-menu", ((MenuDefinition) folder + .getMenuDefinitions().get(0)).getName()); + assertEquals("bread-crumbs", ((MenuDefinition) folder + .getMenuDefinitions().get(0)).getSkin()); + assertEquals("./", + ((MenuDefinition) folder.getMenuDefinitions().get(0)) + .getOptions()); } public void testRemovePage() throws Exception @@ -885,28 +968,31 @@ } assertTrue(exceptionFound); } - + public void testClonePage() throws Exception { Page testpage = pageManager.getPage("/clonetest.psml"); assertNotNull(testpage); Page clone = pageManager.copyPage(testpage, "/cloned.psml"); assertNotNull(clone); - + assertTrue(clone.getId().equals("/cloned.psml")); assertTrue(clone.getName().equals("cloned.psml")); assertTrue(clone.getTitle().equals("Test Page")); assertTrue(clone.getSkin().equals("test-skin")); - assertTrue(clone.getEffectiveDefaultDecorator(Fragment.LAYOUT).equals("test-layout")); - assertTrue(clone.getDefaultDecorator(Fragment.LAYOUT).equals("test-layout")); - assertTrue(clone.getDefaultDecorator(Fragment.PORTLET).equals("test-portlet")); + assertTrue(clone.getEffectiveDefaultDecorator(Fragment.LAYOUT).equals( + "test-layout")); + assertTrue(clone.getDefaultDecorator(Fragment.LAYOUT).equals( + "test-layout")); + assertTrue(clone.getDefaultDecorator(Fragment.PORTLET).equals( + "test-portlet")); // TODO: Test Meta data Fragment root = testpage.getRootFragment(); Fragment cloneRoot = clone.getRootFragment(); - + assertNotNull(cloneRoot); - assertNotNull(cloneRoot.getId()); + assertNotNull(cloneRoot.getId()); assertFalse(cloneRoot.getId().equals(root.getId())); assertTrue(cloneRoot.getName().equals("TwoColumns")); assertTrue(cloneRoot.getType().equals(Fragment.LAYOUT)); @@ -949,130 +1035,153 @@ cf = (Fragment) cloneChildren.get(2); String id = cf.getId(); cf = clone.getFragmentById(id); - - assertNotNull(cf); - assertNotNull(cf.getId()); + + assertNotNull(cf); + assertNotNull(cf.getId()); assertFalse(cf.getId().equals(f.getId())); assertTrue(cf.getName().equals("Card")); assertTrue(cf.getType().equals(Fragment.LAYOUT)); assertTrue(cf.getDecorator().equals("Tab")); assertNotNull(cf.getFragments()); assertTrue(cf.getFragments().size() == 2); - + // security testing SecurityConstraints constraints = clone.getSecurityConstraints(); - assertNotNull(constraints); + assertNotNull(constraints); assertTrue(constraints.getOwner().equals("new-user")); List secs = constraints.getSecurityConstraints(); assertNotNull(secs); assertTrue(secs.size() == 1); - SecurityConstraint constraint = (SecurityConstraint)secs.get(0); + SecurityConstraint constraint = (SecurityConstraint) secs.get(0); assertNotNull(constraint); assertTrue(constraint.getUsers() != null); assertTrue(constraint.getUsers().size() == 2); - assertTrue(Shared.makeCSVFromList(constraint.getUsers()).equals("user10,user11")); + assertTrue(Shared.makeCSVFromList(constraint.getUsers()).equals( + "user10,user11")); assertTrue(constraint.getRoles() != null); assertTrue(constraint.getRoles().size() == 1); assertTrue(Shared.makeCSVFromList(constraint.getRoles()).equals("*")); assertTrue(constraint.getPermissions() != null); assertTrue(constraint.getPermissions().size() == 2); - assertTrue(Shared.makeCSVFromList(constraint.getPermissions()).equals("edit,view")); + assertTrue(Shared.makeCSVFromList(constraint.getPermissions()).equals( + "edit,view")); List refs = constraints.getSecurityConstraintsRefs(); assertNotNull(refs); assertTrue(refs.size() == 1); - String ref = (String)refs.get(0); + String ref = (String) refs.get(0); assertNotNull(ref); assertTrue(ref.equals("public-view")); - + // TODO: menu testing } - - public Collection collectIds(Folder f) throws Exception { + + public Collection collectIds(Folder f) throws Exception + { Collection result = new ArrayList(); - + for (Iterator iter = f.getAll().iterator(); iter.hasNext();) { - Object obj = iter.next(); - - if (obj instanceof Page){ - Page thisPage = (Page) obj; - if (thisPage.getRootFragment()!=null){ - result.addAll(collectIds(thisPage.getRootFragment())); - } - } else - if (obj instanceof Folder){ - Folder thisFolder = (Folder)obj; - result.addAll(collectIds((Folder)obj)); - } - } - + Object obj = iter.next(); + + if (obj instanceof Page) + { + Page thisPage = (Page) obj; + if (thisPage.getRootFragment() != null) + { + result.addAll(collectIds(thisPage.getRootFragment())); + } + } + else if (obj instanceof Folder) + { + Folder thisFolder = (Folder) obj; + result.addAll(collectIds((Folder) obj)); + } + } + return result; } - - public Collection collectIds(Fragment f){ - Collection result = new ArrayList(); - - - result.add(f.getId()); - if (f.getFragments().size() > 0){ - for (Iterator iter = f.getFragments().iterator(); iter.hasNext();) { - Fragment child = (Fragment) iter.next(); - result.addAll(collectIds(child)); - } - } - return result; + + public Collection collectIds(Fragment f) + { + Collection result = new ArrayList(); + + result.add(f.getId()); + if (f.getFragments().size() > 0) + { + for (Iterator iter = f.getFragments().iterator(); iter.hasNext();) + { + Fragment child = (Fragment) iter.next(); + result.addAll(collectIds(child)); + } + } + return result; } - - private int countFragments(Fragment f){ + + private int countFragments(Fragment f) + { int result = 1; for (Iterator iter = f.getFragments().iterator(); iter.hasNext();) { - result+=countFragments((Fragment)iter.next()); + result += countFragments((Fragment) iter.next()); } - + return result; } - - private void compareFolders(Folder folder1, Folder folder2) throws Exception { + + private void compareFolders(Folder folder1, Folder folder2) + throws Exception + { for (Iterator iter = folder1.getAll().iterator(); iter.hasNext();) { - Object obj = iter.next(); - - if (obj instanceof Page){ - Page thisPage = (Page) obj; - Page otherPage = folder2.getPage(thisPage.getName()); - assertEquals(thisPage.getRootFragment()!=null,otherPage.getRootFragment() != null); - if (thisPage.getRootFragment() != null){ - Fragment thisRootFragment = thisPage.getRootFragment(); - Fragment otherRootFragment = otherPage.getRootFragment(); - assertEquals(thisRootFragment.getFragments().size(),otherRootFragment.getFragments().size()); - assertEquals(countFragments(thisRootFragment),countFragments(otherRootFragment)); - } - } else - if (obj instanceof Folder){ - Folder thisFolder = (Folder)obj; - compareFolders(thisFolder, folder2.getFolder(thisFolder.getName())); - } - - } + Object obj = iter.next(); + + if (obj instanceof Page) + { + Page thisPage = (Page) obj; + Page otherPage = folder2.getPage(thisPage.getName()); + assertEquals(thisPage.getRootFragment() != null, otherPage + .getRootFragment() != null); + if (thisPage.getRootFragment() != null) + { + Fragment thisRootFragment = thisPage.getRootFragment(); + Fragment otherRootFragment = otherPage.getRootFragment(); + assertEquals(thisRootFragment.getFragments().size(), + otherRootFragment.getFragments().size()); + assertEquals(countFragments(thisRootFragment), + countFragments(otherRootFragment)); + } + } + else if (obj instanceof Folder) + { + Folder thisFolder = (Folder) obj; + compareFolders(thisFolder, folder2.getFolder(thisFolder + .getName())); + } + + } } - - public void testIdGeneration() throws Exception{ + + public void testIdGeneration() throws Exception + { Folder webappIds = pageManager.getFolder("/webapp-ids"); Folder webappNoIds = pageManager.getFolder("/webapp-no-ids"); - - compareFolders(webappIds,webappNoIds); - - Collection allIds = collectIds(webappNoIds); - for (Iterator iter = allIds.iterator(); iter.hasNext();) { - String id = (String) iter.next(); - assertNotNull(id); - assertEquals(true,id.length() > 0); - if (CollectionUtils.cardinality(id, allIds) > 1){ - System.out.println("Fragment with id "+id+" has duplicates"); + + compareFolders(webappIds, webappNoIds); + + Collection allIds = collectIds(webappNoIds); + for (Iterator iter = allIds.iterator(); iter.hasNext();) + { + String id = (String) iter.next(); + assertNotNull(id); + assertEquals(true, id.length() > 0); + if (CollectionUtils.cardinality(id, allIds) > 1) + { + System.out + .println("Fragment with id " + id + " has duplicates"); } - assertEquals(1, CollectionUtils.cardinality(id, allIds)); // uniqueness test - } + assertEquals(1, CollectionUtils.cardinality(id, allIds)); // uniqueness + // test + } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestCreateUserHomePagesFromRoles.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestCreateUserHomePagesFromRoles.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestCreateUserHomePagesFromRoles.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,8 +37,10 @@ * @author Randy Watler * @version $Id$ */ -public class TestCreateUserHomePagesFromRoles extends TestCase implements PageManagerTestShared +public class TestCreateUserHomePagesFromRoles extends TestCase implements + PageManagerTestShared { + protected CastorXmlPageManager pageManager; /* @@ -49,7 +51,8 @@ protected void setUp() throws Exception { super.setUp(); - pageManager = Shared.makeCastorXMLPageManager("secure-pages", false, true); + pageManager = Shared.makeCastorXMLPageManager("secure-pages", false, + true); } /** @@ -71,7 +74,7 @@ * @param name * the testcase's name. */ - public TestCreateUserHomePagesFromRoles( String name ) + public TestCreateUserHomePagesFromRoles(String name) { super(name); } @@ -82,9 +85,10 @@ * @param args * the arguments. Not used */ - public static void main( String args[] ) + public static void main(String args[]) { - junit.awtui.TestRunner.main(new String[]{TestCreateUserHomePagesFromRoles.class.getName()}); + junit.awtui.TestRunner.main(new String[] + {TestCreateUserHomePagesFromRoles.class.getName()}); } /** @@ -99,28 +103,46 @@ return new TestSuite(TestCreateUserHomePagesFromRoles.class); } - static final String FOLDER1 = Folder.ROLE_FOLDER + "role1"; + static final String FOLDER2 = Folder.ROLE_FOLDER + "role2"; + static final String FOLDER3 = Folder.ROLE_FOLDER + "role3"; - - static final String DEFAULT_PAGE = Folder.USER_FOLDER + "david" + Folder.PATH_SEPARATOR + "default-page.psml"; - static final String ROLE_PAGE_1 = Folder.USER_FOLDER + "david" + Folder.PATH_SEPARATOR + "role1-default-page.psml"; - static final String ROLE_PAGE_2 = Folder.USER_FOLDER + "david" + Folder.PATH_SEPARATOR + "role2-default-page.psml"; - static final String ROLE_PAGE_3 = Folder.USER_FOLDER + "david" + Folder.PATH_SEPARATOR + "role3-default-page.psml"; - static final String SUB_PAGE = Folder.USER_FOLDER + "david" + Folder.PATH_SEPARATOR + "sub1" + Folder.PATH_SEPARATOR + "default-page.psml"; - static final String SUB_LINK = Folder.USER_FOLDER + "david" + Folder.PATH_SEPARATOR + "sub1" + Folder.PATH_SEPARATOR + "apache_portals.link"; - + + static final String DEFAULT_PAGE = Folder.USER_FOLDER + "david" + + Folder.PATH_SEPARATOR + "default-page.psml"; + + static final String ROLE_PAGE_1 = Folder.USER_FOLDER + "david" + + Folder.PATH_SEPARATOR + "role1-default-page.psml"; + + static final String ROLE_PAGE_2 = Folder.USER_FOLDER + "david" + + Folder.PATH_SEPARATOR + "role2-default-page.psml"; + + static final String ROLE_PAGE_3 = Folder.USER_FOLDER + "david" + + Folder.PATH_SEPARATOR + "role3-default-page.psml"; + + static final String SUB_PAGE = Folder.USER_FOLDER + "david" + + Folder.PATH_SEPARATOR + "sub1" + Folder.PATH_SEPARATOR + + "default-page.psml"; + + static final String SUB_LINK = Folder.USER_FOLDER + "david" + + Folder.PATH_SEPARATOR + "sub1" + Folder.PATH_SEPARATOR + + "apache_portals.link"; + public void testCreateUserHomePagesFromRoles() throws Exception { - PageManager pageManager = Shared.makeCastorXMLPageManager("pages", false, false); + PageManager pageManager = Shared.makeCastorXMLPageManager("pages", + false, false); - assertTrue("folder1 failed to create", pageManager.folderExists(FOLDER1)); - assertTrue("folder2 failed to create", pageManager.folderExists(FOLDER2)); - assertTrue("folder3 failed to create", pageManager.folderExists(FOLDER3)); - + assertTrue("folder1 failed to create", pageManager + .folderExists(FOLDER1)); + assertTrue("folder2 failed to create", pageManager + .folderExists(FOLDER2)); + assertTrue("folder3 failed to create", pageManager + .folderExists(FOLDER3)); + Set principals = new HashSet(); - + // create the role principals Principal rolePrincipal1 = new RolePrincipalImpl("role1"); Principal rolePrincipal2 = new RolePrincipalImpl("role2"); @@ -128,19 +150,23 @@ principals.add(rolePrincipal1); principals.add(rolePrincipal2); principals.add(rolePrincipal3); - + // create the user principal - Principal userPrincipal = new UserPrincipalImpl("david"); + Principal userPrincipal = new UserPrincipalImpl("david"); principals.add(userPrincipal); - + // create the subject - Subject subject = new Subject(true, principals, new HashSet(), new HashSet()); + Subject subject = new Subject(true, principals, new HashSet(), + new HashSet()); pageManager.createUserHomePagesFromRoles(subject); - - assertTrue("failed to create default page", pageManager.pageExists(DEFAULT_PAGE)); - assertTrue("failed to create sub page", pageManager.pageExists(SUB_PAGE)); - assertTrue("failed to create sub link", pageManager.linkExists(SUB_LINK)); + + assertTrue("failed to create default page", pageManager + .pageExists(DEFAULT_PAGE)); + assertTrue("failed to create sub page", pageManager + .pageExists(SUB_PAGE)); + assertTrue("failed to create sub link", pageManager + .linkExists(SUB_LINK)); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestDatabasePageManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestDatabasePageManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestDatabasePageManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,6 +20,10 @@ import java.util.Iterator; import java.util.List; import java.util.Locale; + +import junit.framework.Test; +import junit.framework.TestSuite; + import org.apache.jetspeed.components.util.DatasourceEnabledSpringTestCase; import org.apache.jetspeed.om.common.GenericMetadata; import org.apache.jetspeed.om.common.SecurityConstraint; @@ -40,39 +44,41 @@ import org.apache.jetspeed.page.document.DocumentNotFoundException; import org.apache.jetspeed.page.document.FailedToUpdateDocumentException; import org.apache.jetspeed.page.document.Node; - import org.springframework.context.support.ClassPathXmlApplicationContext; -import junit.framework.Test; -import junit.framework.TestSuite; - /** * TestPageXmlPersistence * * @author David Sean Taylor * @version $Id: $ - * + * */ -public class TestDatabasePageManager extends DatasourceEnabledSpringTestCase implements PageManagerTestShared, PageManagerEventListener +public class TestDatabasePageManager extends DatasourceEnabledSpringTestCase + implements PageManagerTestShared, PageManagerEventListener { + private String deepFolderPath = "/__subsite-rootx/_user/userx/_role/rolex/_group/groupx/_mediatype/xhtml/_language/en/_country/us/_custom/customx"; + private String deepPagePath = deepFolderPath + "/default-page.psml"; private static ClassPathXmlApplicationContext context; + private static boolean lastTestRun; private static PageManager pageManager; private static int newNodeCount; + private static int updatedNodeCount; + private static int removedNodeCount; public static void main(String args[]) { junit.awtui.TestRunner.main(new String[] - { TestDatabasePageManager.class.getName() }); + {TestDatabasePageManager.class.getName()}); } - + protected void setUp() throws Exception { // reuse context between test cases below @@ -86,7 +92,7 @@ lastTestRun = false; // lookup page manager in context and reset to initial state - pageManager = (PageManager)context.getBean("pageManager"); + pageManager = (PageManager) context.getBean("pageManager"); try { Folder removeRootFolder = pageManager.getFolder("/"); @@ -117,20 +123,22 @@ } super.tearDown(); } - + public static Test suite() { // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestDatabasePageManager.class); } - + protected String[] getConfigurations() { return new String[] - { "database-page-manager.xml", "transaction.xml" }; + {"database-page-manager.xml", "transaction.xml"}; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManagerEventListener#newNode(org.apache.jetspeed.page.document.Node) */ public void newNode(Node node) @@ -138,7 +146,9 @@ newNodeCount++; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManagerEventListener#newNode(org.apache.jetspeed.page.document.Node) */ public void updatedNode(Node node) @@ -146,7 +156,9 @@ updatedNodeCount++; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.page.PageManagerEventListener#newNode(org.apache.jetspeed.page.document.Node) */ public void removedNode(Node node) @@ -170,10 +182,12 @@ folder.setShortTitle("Root"); GenericMetadata metadata = folder.getMetadata(); metadata.addField(Locale.FRENCH, "title", "[fr] Root Folder"); - SecurityConstraints folderConstraints = pageManager.newSecurityConstraints(); + SecurityConstraints folderConstraints = pageManager + .newSecurityConstraints(); folderConstraints.setOwner("admin"); List inlineFolderConstraints = new ArrayList(2); - SecurityConstraint folderConstraint = pageManager.newFolderSecurityConstraint(); + SecurityConstraint folderConstraint = pageManager + .newFolderSecurityConstraint(); folderConstraint.setUsers(Shared.makeListFromCSV("user,admin")); folderConstraint.setRoles(Shared.makeListFromCSV("manager")); folderConstraint.setGroups(Shared.makeListFromCSV("*")); @@ -200,7 +214,8 @@ metadata = newMenu.getMetadata(); metadata.addField(Locale.FRENCH, "short-title", "[fr] Folder Menu"); metadata.addField(Locale.FRENCH, "title", "[fr] The Test Folder Menu"); - MenuSeparatorDefinition newSeparator = folder.newMenuSeparatorDefinition(); + MenuSeparatorDefinition newSeparator = folder + .newMenuSeparatorDefinition(); newSeparator.setText("-- Folder Menu --"); newSeparator.setTitle("Rollover: Folder Menu"); newSeparator.setSkin("header"); @@ -227,10 +242,12 @@ newNestedMenu.setOrder("/x*/,/y*/,/z*/"); newNestedMenu.setSkin("bold"); newMenu.getMenuElements().add(newNestedMenu); - MenuExcludeDefinition newExcludeMenu = folder.newMenuExcludeDefinition(); + MenuExcludeDefinition newExcludeMenu = folder + .newMenuExcludeDefinition(); newExcludeMenu.setName("exclude-menu"); newMenu.getMenuElements().add(newExcludeMenu); - MenuIncludeDefinition newIncludeMenu = folder.newMenuIncludeDefinition(); + MenuIncludeDefinition newIncludeMenu = folder + .newMenuIncludeDefinition(); newIncludeMenu.setName("include-menu"); newIncludeMenu.setNest(true); newMenu.getMenuElements().add(newIncludeMenu); @@ -242,7 +259,7 @@ newMenu.setPaths(true); folder.getMenuDefinitions().add(newMenu); pageManager.updateFolder(folder); - + assertNull(folder.getParent()); Page page = pageManager.newPage("/default-page.psml"); @@ -307,7 +324,7 @@ root.setLayoutSizes("50%,50%"); root.getProperties().put("custom-prop1", "custom-prop-value1"); root.getProperties().put("custom-prop2", "custom-prop-value2"); - + Fragment portlet = pageManager.newPortletFragment(); portlet.setName("security::LoginPortlet"); portlet.setShortTitle("Portlet"); @@ -349,7 +366,8 @@ portlet.setLayoutZ(33.33F); portlet.setLayoutWidth(44.44F); portlet.setLayoutHeight(55.55F); - SecurityConstraints fragmentConstraints = portlet.newSecurityConstraints(); + SecurityConstraints fragmentConstraints = portlet + .newSecurityConstraints(); fragmentConstraints.setOwner("user"); portlet.setSecurityConstraints(fragmentConstraints); root.getFragments().add(portlet); @@ -412,7 +430,8 @@ PageSecurity pageSecurity = pageManager.newPageSecurity(); List constraintsDefs = new ArrayList(2); - SecurityConstraintsDef constraintsDef = pageManager.newSecurityConstraintsDef(); + SecurityConstraintsDef constraintsDef = pageManager + .newSecurityConstraintsDef(); constraintsDef.setName("public-view"); List defConstraints = new ArrayList(1); SecurityConstraint defConstraint = pageSecurity.newSecurityConstraint(); @@ -488,16 +507,20 @@ int pathIndex = deepFolderPath.indexOf('/', 1); while ((pathIndex != -1) && (pathIndex <= deepFolderPath.length())) { - deepFolder = pageManager.newFolder(deepFolderPath.substring(0, pathIndex)); + deepFolder = pageManager.newFolder(deepFolderPath.substring(0, + pathIndex)); pageManager.updateFolder(deepFolder); assertNotNull(deepFolder.getParent()); - assertNotNull(((Folder)deepFolder.getParent()).getFolders()); - assertEquals(1, ((Folder)deepFolder.getParent()).getFolders().size()); - assertNotNull(pageManager.getFolders((Folder)deepFolder.getParent())); - assertEquals(1, pageManager.getFolders((Folder)deepFolder.getParent()).size()); + assertNotNull(((Folder) deepFolder.getParent()).getFolders()); + assertEquals(1, ((Folder) deepFolder.getParent()).getFolders() + .size()); + assertNotNull(pageManager.getFolders((Folder) deepFolder + .getParent())); + assertEquals(1, pageManager.getFolders( + (Folder) deepFolder.getParent()).size()); if (pathIndex < deepFolderPath.length()) { - pathIndex = deepFolderPath.indexOf('/', pathIndex+1); + pathIndex = deepFolderPath.indexOf('/', pathIndex + 1); if (pathIndex == -1) { pathIndex = deepFolderPath.length(); @@ -523,12 +546,12 @@ assertNotNull(pageManager.getAll(folder)); assertEquals(6, pageManager.getAll(folder).size()); Iterator all = folder.getAll().iterator(); - assertEquals("some-other-page.psml", ((Node)all.next()).getName()); - assertEquals("default-page.psml", ((Node)all.next()).getName()); - assertEquals("__subsite-rootx", ((Node)all.next()).getName()); - assertEquals("another-page.psml", ((Node)all.next()).getName()); - assertEquals("default.link", ((Node)all.next()).getName()); - assertEquals("page.security", ((Node)all.next()).getName()); + assertEquals("some-other-page.psml", ((Node) all.next()).getName()); + assertEquals("default-page.psml", ((Node) all.next()).getName()); + assertEquals("__subsite-rootx", ((Node) all.next()).getName()); + assertEquals("another-page.psml", ((Node) all.next()).getName()); + assertEquals("default.link", ((Node) all.next()).getName()); + assertEquals("page.security", ((Node) all.next()).getName()); assertNotNull(folder.getAll().subset(Page.DOCUMENT_TYPE)); assertEquals(3, folder.getAll().subset(Page.DOCUMENT_TYPE).size()); assertNotNull(folder.getAll().inclusiveSubset(".*other.*")); @@ -543,7 +566,7 @@ { // reset page manager cache pageManager.reset(); - + // read documents and folders from persisted store try { @@ -553,19 +576,49 @@ assertEquals("/page.security", check.getUrl()); assertNotNull(check.getSecurityConstraintsDefs()); assertEquals(2, check.getSecurityConstraintsDefs().size()); - assertEquals("admin-all", ((SecurityConstraintsDef)check.getSecurityConstraintsDefs().get(0)).getName()); - assertNotNull(((SecurityConstraintsDef)check.getSecurityConstraintsDefs().get(0)).getSecurityConstraints()); - assertEquals(2, ((SecurityConstraintsDef)check.getSecurityConstraintsDefs().get(0)).getSecurityConstraints().size()); - assertEquals("view,edit", Shared.makeCSVFromList(((SecurityConstraint)((SecurityConstraintsDef)check.getSecurityConstraintsDefs().get(0)).getSecurityConstraints().get(0)).getPermissions())); - assertEquals("public-view", ((SecurityConstraintsDef)check.getSecurityConstraintsDefs().get(1)).getName()); - assertNotNull(((SecurityConstraintsDef)check.getSecurityConstraintsDefs().get(1)).getSecurityConstraints()); - assertEquals(1, ((SecurityConstraintsDef)check.getSecurityConstraintsDefs().get(1)).getSecurityConstraints().size()); - assertEquals("*", Shared.makeCSVFromList(((SecurityConstraint)((SecurityConstraintsDef)check.getSecurityConstraintsDefs().get(1)).getSecurityConstraints().get(0)).getUsers())); - assertEquals("view", Shared.makeCSVFromList(((SecurityConstraint)((SecurityConstraintsDef)check.getSecurityConstraintsDefs().get(1)).getSecurityConstraints().get(0)).getPermissions())); + assertEquals("admin-all", ((SecurityConstraintsDef) check + .getSecurityConstraintsDefs().get(0)).getName()); + assertNotNull(((SecurityConstraintsDef) check + .getSecurityConstraintsDefs().get(0)) + .getSecurityConstraints()); + assertEquals(2, ((SecurityConstraintsDef) check + .getSecurityConstraintsDefs().get(0)) + .getSecurityConstraints().size()); + assertEquals( + "view,edit", + Shared + .makeCSVFromList(((SecurityConstraint) ((SecurityConstraintsDef) check + .getSecurityConstraintsDefs().get(0)) + .getSecurityConstraints().get(0)) + .getPermissions())); + assertEquals("public-view", ((SecurityConstraintsDef) check + .getSecurityConstraintsDefs().get(1)).getName()); + assertNotNull(((SecurityConstraintsDef) check + .getSecurityConstraintsDefs().get(1)) + .getSecurityConstraints()); + assertEquals(1, ((SecurityConstraintsDef) check + .getSecurityConstraintsDefs().get(1)) + .getSecurityConstraints().size()); + assertEquals( + "*", + Shared + .makeCSVFromList(((SecurityConstraint) ((SecurityConstraintsDef) check + .getSecurityConstraintsDefs().get(1)) + .getSecurityConstraints().get(0)) + .getUsers())); + assertEquals( + "view", + Shared + .makeCSVFromList(((SecurityConstraint) ((SecurityConstraintsDef) check + .getSecurityConstraintsDefs().get(1)) + .getSecurityConstraints().get(0)) + .getPermissions())); assertNotNull(check.getGlobalSecurityConstraintsRefs()); assertEquals(2, check.getGlobalSecurityConstraintsRefs().size()); - assertEquals("admin-all", (String)check.getGlobalSecurityConstraintsRefs().get(0)); - assertEquals("public-view", (String)check.getGlobalSecurityConstraintsRefs().get(1)); + assertEquals("admin-all", (String) check + .getGlobalSecurityConstraintsRefs().get(0)); + assertEquals("public-view", (String) check + .getGlobalSecurityConstraintsRefs().get(1)); assertNotNull(check.getParent()); } catch (DocumentNotFoundException e) @@ -578,7 +631,7 @@ assertEquals("/default.link", check.getPath()); assertEquals("default.link", check.getName()); assertEquals("Default Link", check.getTitle()); - assertEquals("1.23", check.getVersion()); + assertEquals("1.23", check.getVersion()); assertEquals("Default", check.getShortTitle()); assertEquals("top", check.getTarget()); assertEquals("http://www.default.org/", check.getUrl()); @@ -587,12 +640,21 @@ assertEquals("[de] Default Link", check.getTitle(Locale.GERMAN)); assertNotNull(check.getSecurityConstraints()); assertEquals("user", check.getSecurityConstraints().getOwner()); - assertNotNull(check.getSecurityConstraints().getSecurityConstraintsRefs()); - assertEquals(1, check.getSecurityConstraints().getSecurityConstraintsRefs().size()); - assertEquals("manager-edit", (String)check.getSecurityConstraints().getSecurityConstraintsRefs().get(0)); - assertNotNull(check.getSecurityConstraints().getSecurityConstraints()); - assertEquals(1, check.getSecurityConstraints().getSecurityConstraints().size()); - assertEquals("jetspeed", Shared.makeCSVFromList(((SecurityConstraint)check.getSecurityConstraints().getSecurityConstraints().get(0)).getUsers())); + assertNotNull(check.getSecurityConstraints() + .getSecurityConstraintsRefs()); + assertEquals(1, check.getSecurityConstraints() + .getSecurityConstraintsRefs().size()); + assertEquals("manager-edit", (String) check + .getSecurityConstraints().getSecurityConstraintsRefs().get( + 0)); + assertNotNull(check.getSecurityConstraints() + .getSecurityConstraints()); + assertEquals(1, check.getSecurityConstraints() + .getSecurityConstraints().size()); + assertEquals("jetspeed", Shared + .makeCSVFromList(((SecurityConstraint) check + .getSecurityConstraints().getSecurityConstraints() + .get(0)).getUsers())); assertNotNull(check.getParent()); } catch (PageNotFoundException e) @@ -606,10 +668,12 @@ assertEquals("default-page.psml", check.getName()); assertEquals("/default-page.psml", check.getUrl()); assertEquals("Default Page", check.getTitle()); - assertEquals("6.89", check.getVersion()); - assertEquals("tigris", check.getEffectiveDefaultDecorator(Fragment.LAYOUT)); + assertEquals("6.89", check.getVersion()); + assertEquals("tigris", check + .getEffectiveDefaultDecorator(Fragment.LAYOUT)); assertEquals("tigris", check.getDefaultDecorator(Fragment.LAYOUT)); - assertEquals("blue-gradient", check.getDefaultDecorator(Fragment.PORTLET)); + assertEquals("blue-gradient", check + .getDefaultDecorator(Fragment.PORTLET)); assertEquals("skin-1", check.getSkin()); assertEquals("Default", check.getShortTitle()); assertNotNull(check.getMetadata()); @@ -617,48 +681,71 @@ assertEquals("[ja] Default Page", check.getTitle(Locale.JAPANESE)); assertNotNull(check.getSecurityConstraints()); assertEquals("user", check.getSecurityConstraints().getOwner()); - assertNotNull(check.getSecurityConstraints().getSecurityConstraintsRefs()); - assertEquals(1, check.getSecurityConstraints().getSecurityConstraintsRefs().size()); - assertEquals("manager-edit", (String)check.getSecurityConstraints().getSecurityConstraintsRefs().get(0)); - assertNotNull(check.getSecurityConstraints().getSecurityConstraints()); - assertEquals(1, check.getSecurityConstraints().getSecurityConstraints().size()); - assertEquals("jetspeed", Shared.makeCSVFromList(((SecurityConstraint)check.getSecurityConstraints().getSecurityConstraints().get(0)).getUsers())); + assertNotNull(check.getSecurityConstraints() + .getSecurityConstraintsRefs()); + assertEquals(1, check.getSecurityConstraints() + .getSecurityConstraintsRefs().size()); + assertEquals("manager-edit", (String) check + .getSecurityConstraints().getSecurityConstraintsRefs().get( + 0)); + assertNotNull(check.getSecurityConstraints() + .getSecurityConstraints()); + assertEquals(1, check.getSecurityConstraints() + .getSecurityConstraints().size()); + assertEquals("jetspeed", Shared + .makeCSVFromList(((SecurityConstraint) check + .getSecurityConstraints().getSecurityConstraints() + .get(0)).getUsers())); assertNotNull(check.getMenuDefinitions()); assertEquals(2, check.getMenuDefinitions().size()); - MenuDefinition checkMenu = (MenuDefinition)check.getMenuDefinitions().get(0); + MenuDefinition checkMenu = (MenuDefinition) check + .getMenuDefinitions().get(0); assertEquals("page-menu-1", checkMenu.getName()); assertEquals("The Test Page Menu", checkMenu.getTitle()); - assertEquals("[fr] The Test Page Menu", checkMenu.getTitle(Locale.FRENCH)); + assertEquals("[fr] The Test Page Menu", checkMenu + .getTitle(Locale.FRENCH)); assertNotNull(checkMenu.getMenuElements()); - assertEquals(5,checkMenu.getMenuElements().size()); + assertEquals(5, checkMenu.getMenuElements().size()); assertTrue(checkMenu.getMenuElements().get(0) instanceof MenuSeparatorDefinition); - assertEquals("-- Page Menu --", ((MenuSeparatorDefinition)checkMenu.getMenuElements().get(0)).getText()); + assertEquals("-- Page Menu --", + ((MenuSeparatorDefinition) checkMenu.getMenuElements().get( + 0)).getText()); assertTrue(checkMenu.getMenuElements().get(1) instanceof MenuOptionsDefinition); - assertEquals("/*.psml", ((MenuOptionsDefinition)checkMenu.getMenuElements().get(1)).getOptions()); + assertEquals("/*.psml", ((MenuOptionsDefinition) checkMenu + .getMenuElements().get(1)).getOptions()); assertTrue(checkMenu.getMenuElements().get(2) instanceof MenuDefinition); - assertEquals("/*/", ((MenuDefinition)checkMenu.getMenuElements().get(2)).getOptions()); - assertNotNull(((MenuDefinition)checkMenu.getMenuElements().get(2)).getMenuElements()); - assertTrue(((MenuDefinition)checkMenu.getMenuElements().get(2)).getMenuElements().isEmpty()); + assertEquals("/*/", ((MenuDefinition) checkMenu.getMenuElements() + .get(2)).getOptions()); + assertNotNull(((MenuDefinition) checkMenu.getMenuElements().get(2)) + .getMenuElements()); + assertTrue(((MenuDefinition) checkMenu.getMenuElements().get(2)) + .getMenuElements().isEmpty()); assertTrue(checkMenu.getMenuElements().get(3) instanceof MenuExcludeDefinition); - assertEquals("exclude-menu", ((MenuExcludeDefinition)checkMenu.getMenuElements().get(3)).getName()); + assertEquals("exclude-menu", ((MenuExcludeDefinition) checkMenu + .getMenuElements().get(3)).getName()); assertTrue(checkMenu.getMenuElements().get(4) instanceof MenuIncludeDefinition); - assertEquals("include-menu", ((MenuIncludeDefinition)checkMenu.getMenuElements().get(4)).getName()); - checkMenu = (MenuDefinition)check.getMenuDefinitions().get(1); + assertEquals("include-menu", ((MenuIncludeDefinition) checkMenu + .getMenuElements().get(4)).getName()); + checkMenu = (MenuDefinition) check.getMenuDefinitions().get(1); assertEquals("page-menu-2", checkMenu.getName()); assertNotNull(checkMenu.getMenuElements()); assertTrue(checkMenu.getMenuElements().isEmpty()); assertNotNull(check.getRootFragment()); - assertEquals("blue-gradient", check.getRootFragment().getDecorator()); - assertEquals("jetspeed-layouts::VelocityTwoColumns", check.getRootFragment().getName()); + assertEquals("blue-gradient", check.getRootFragment() + .getDecorator()); + assertEquals("jetspeed-layouts::VelocityTwoColumns", check + .getRootFragment().getName()); assertEquals("Root", check.getRootFragment().getShortTitle()); assertEquals("Root Fragment", check.getRootFragment().getTitle()); assertEquals("Normal", check.getRootFragment().getState()); assertEquals("50%,50%", check.getRootFragment().getLayoutSizes()); assertNotNull(check.getRootFragment().getProperties()); - assertEquals("custom-prop-value1", check.getRootFragment().getProperty("custom-prop1")); + assertEquals("custom-prop-value1", check.getRootFragment() + .getProperty("custom-prop1")); assertNotNull(check.getRootFragment().getFragments()); assertEquals(2, check.getRootFragment().getFragments().size()); - Fragment check0 = (Fragment)check.getRootFragment().getFragments().get(0); + Fragment check0 = (Fragment) check.getRootFragment().getFragments() + .get(0); assertEquals("security::LoginPortlet", check0.getName()); assertEquals("Portlet", check0.getShortTitle()); assertEquals("Portlet Fragment", check0.getTitle()); @@ -667,44 +754,68 @@ assertEquals(88, check0.getIntProperty(Fragment.ROW_PROPERTY_NAME)); assertEquals(99, check0.getLayoutColumn()); assertNotNull(check0.getProperty(Fragment.X_PROPERTY_NAME)); - assertTrue(check0.getProperty(Fragment.X_PROPERTY_NAME).startsWith("12.3")); - assertTrue((check0.getLayoutX() > 12.0F) && (check0.getLayoutX() < 13.0F)); - assertTrue((check0.getFloatProperty(Fragment.X_PROPERTY_NAME) > 12.0F) && - (check0.getFloatProperty(Fragment.X_PROPERTY_NAME) < 13.0F)); - assertTrue((check0.getLayoutY() > 23.0F) && (check0.getLayoutY() < 24.0F)); - assertTrue((check0.getLayoutZ() > 34.0F) && (check0.getLayoutZ() < 35.0F)); - assertTrue((check0.getLayoutWidth() > 45.0F) && (check0.getLayoutWidth() < 46.0F)); - assertTrue((check0.getLayoutHeight() > 56.0F) && (check0.getLayoutWidth() < 57.0F)); + assertTrue(check0.getProperty(Fragment.X_PROPERTY_NAME).startsWith( + "12.3")); + assertTrue((check0.getLayoutX() > 12.0F) + && (check0.getLayoutX() < 13.0F)); + assertTrue((check0.getFloatProperty(Fragment.X_PROPERTY_NAME) > 12.0F) + && (check0.getFloatProperty(Fragment.X_PROPERTY_NAME) < 13.0F)); + assertTrue((check0.getLayoutY() > 23.0F) + && (check0.getLayoutY() < 24.0F)); + assertTrue((check0.getLayoutZ() > 34.0F) + && (check0.getLayoutZ() < 35.0F)); + assertTrue((check0.getLayoutWidth() > 45.0F) + && (check0.getLayoutWidth() < 46.0F)); + assertTrue((check0.getLayoutHeight() > 56.0F) + && (check0.getLayoutWidth() < 57.0F)); assertNotNull(check0.getPreferences()); assertEquals(2, check0.getPreferences().size()); - assertEquals("pref0", ((FragmentPreference)check0.getPreferences().get(0)).getName()); - assertTrue(((FragmentPreference)check0.getPreferences().get(0)).isReadOnly()); - assertNotNull(((FragmentPreference)check0.getPreferences().get(0)).getValueList()); - assertEquals(2, ((FragmentPreference)check0.getPreferences().get(0)).getValueList().size()); - assertEquals("pref0-value0", (String)((FragmentPreference)check0.getPreferences().get(0)).getValueList().get(0)); - assertEquals("pref0-value1", (String)((FragmentPreference)check0.getPreferences().get(0)).getValueList().get(1)); - assertEquals("pref1", ((FragmentPreference)check0.getPreferences().get(1)).getName()); - assertFalse(((FragmentPreference)check0.getPreferences().get(1)).isReadOnly()); - assertNotNull(((FragmentPreference)check0.getPreferences().get(1)).getValueList()); - assertEquals(1, ((FragmentPreference)check0.getPreferences().get(1)).getValueList().size()); - assertEquals("pref1-value", (String)((FragmentPreference)check0.getPreferences().get(1)).getValueList().get(0)); - Fragment check1 = (Fragment)check.getRootFragment().getFragments().get(1); + assertEquals("pref0", ((FragmentPreference) check0.getPreferences() + .get(0)).getName()); + assertTrue(((FragmentPreference) check0.getPreferences().get(0)) + .isReadOnly()); + assertNotNull(((FragmentPreference) check0.getPreferences().get(0)) + .getValueList()); + assertEquals(2, ((FragmentPreference) check0.getPreferences() + .get(0)).getValueList().size()); + assertEquals("pref0-value0", (String) ((FragmentPreference) check0 + .getPreferences().get(0)).getValueList().get(0)); + assertEquals("pref0-value1", (String) ((FragmentPreference) check0 + .getPreferences().get(0)).getValueList().get(1)); + assertEquals("pref1", ((FragmentPreference) check0.getPreferences() + .get(1)).getName()); + assertFalse(((FragmentPreference) check0.getPreferences().get(1)) + .isReadOnly()); + assertNotNull(((FragmentPreference) check0.getPreferences().get(1)) + .getValueList()); + assertEquals(1, ((FragmentPreference) check0.getPreferences() + .get(1)).getValueList().size()); + assertEquals("pref1-value", (String) ((FragmentPreference) check0 + .getPreferences().get(1)).getValueList().get(0)); + Fragment check1 = (Fragment) check.getRootFragment().getFragments() + .get(1); assertEquals("some-app::SomePortlet", check1.getName()); assertEquals("Some Portlet", check1.getShortTitle()); assertEquals("Some Portlet Fragment", check1.getTitle()); assertEquals("Normal", check1.getState()); assertEquals(22, check1.getLayoutRow()); assertEquals(11, check1.getLayoutColumn()); - assertTrue((check1.getLayoutX() > 11.0F) && (check1.getLayoutX() < 12.0F)); - assertTrue((check1.getLayoutY() > 22.0F) && (check1.getLayoutY() < 23.0F)); - assertTrue((check1.getLayoutZ() > 33.0F) && (check1.getLayoutZ() < 34.0F)); - assertTrue((check1.getLayoutWidth() > 44.0F) && (check1.getLayoutWidth() < 45.0F)); - assertTrue((check1.getLayoutHeight() > 55.0F) && (check1.getLayoutWidth() < 56.0F)); + assertTrue((check1.getLayoutX() > 11.0F) + && (check1.getLayoutX() < 12.0F)); + assertTrue((check1.getLayoutY() > 22.0F) + && (check1.getLayoutY() < 23.0F)); + assertTrue((check1.getLayoutZ() > 33.0F) + && (check1.getLayoutZ() < 34.0F)); + assertTrue((check1.getLayoutWidth() > 44.0F) + && (check1.getLayoutWidth() < 45.0F)); + assertTrue((check1.getLayoutHeight() > 55.0F) + && (check1.getLayoutWidth() < 56.0F)); assertNotNull(check1.getSecurityConstraints()); assertEquals("user", check1.getSecurityConstraints().getOwner()); assertNotNull(check.getFragmentById(check0.getId())); assertNotNull(check.getFragmentsByName("some-app::SomePortlet")); - assertEquals(1, check.getFragmentsByName("some-app::SomePortlet").size()); + assertEquals(1, check.getFragmentsByName("some-app::SomePortlet") + .size()); assertNotNull(check.getParent()); } catch (PageNotFoundException e) @@ -718,9 +829,11 @@ assertEquals("/", check.getName()); assertEquals("/", check.getUrl()); assertEquals("Root Folder", check.getTitle()); - assertEquals("jetspeed", check.getEffectiveDefaultDecorator(Fragment.LAYOUT)); + assertEquals("jetspeed", check + .getEffectiveDefaultDecorator(Fragment.LAYOUT)); assertEquals("jetspeed", check.getDefaultDecorator(Fragment.LAYOUT)); - assertEquals("gray-gradient", check.getDefaultDecorator(Fragment.PORTLET)); + assertEquals("gray-gradient", check + .getDefaultDecorator(Fragment.PORTLET)); assertEquals("skin-1", check.getSkin()); assertEquals("default-page.psml", check.getDefaultPage()); assertEquals("Root", check.getShortTitle()); @@ -728,19 +841,38 @@ assertEquals("[fr] Root Folder", check.getTitle(Locale.FRENCH)); assertNotNull(check.getSecurityConstraints()); assertEquals("admin", check.getSecurityConstraints().getOwner()); - assertNotNull(check.getSecurityConstraints().getSecurityConstraintsRefs()); - assertEquals(2, check.getSecurityConstraints().getSecurityConstraintsRefs().size()); - assertEquals("public-edit", (String)check.getSecurityConstraints().getSecurityConstraintsRefs().get(1)); - assertNotNull(check.getSecurityConstraints().getSecurityConstraints()); - assertEquals(2, check.getSecurityConstraints().getSecurityConstraints().size()); - assertEquals("user,admin", Shared.makeCSVFromList(((SecurityConstraint)check.getSecurityConstraints().getSecurityConstraints().get(0)).getUsers())); - assertEquals("manager", Shared.makeCSVFromList(((SecurityConstraint)check.getSecurityConstraints().getSecurityConstraints().get(0)).getRoles())); - assertEquals("*", Shared.makeCSVFromList(((SecurityConstraint)check.getSecurityConstraints().getSecurityConstraints().get(0)).getGroups())); - assertEquals("edit", Shared.makeCSVFromList(((SecurityConstraint)check.getSecurityConstraints().getSecurityConstraints().get(1)).getPermissions())); + assertNotNull(check.getSecurityConstraints() + .getSecurityConstraintsRefs()); + assertEquals(2, check.getSecurityConstraints() + .getSecurityConstraintsRefs().size()); + assertEquals("public-edit", (String) check.getSecurityConstraints() + .getSecurityConstraintsRefs().get(1)); + assertNotNull(check.getSecurityConstraints() + .getSecurityConstraints()); + assertEquals(2, check.getSecurityConstraints() + .getSecurityConstraints().size()); + assertEquals("user,admin", Shared + .makeCSVFromList(((SecurityConstraint) check + .getSecurityConstraints().getSecurityConstraints() + .get(0)).getUsers())); + assertEquals("manager", Shared + .makeCSVFromList(((SecurityConstraint) check + .getSecurityConstraints().getSecurityConstraints() + .get(0)).getRoles())); + assertEquals("*", Shared + .makeCSVFromList(((SecurityConstraint) check + .getSecurityConstraints().getSecurityConstraints() + .get(0)).getGroups())); + assertEquals("edit", Shared + .makeCSVFromList(((SecurityConstraint) check + .getSecurityConstraints().getSecurityConstraints() + .get(1)).getPermissions())); assertNotNull(check.getDocumentOrder()); assertEquals(2, check.getDocumentOrder().size()); - assertEquals("some-other-page.psml", (String)check.getDocumentOrder().get(0)); - assertEquals("default-page.psml", (String)check.getDocumentOrder().get(1)); + assertEquals("some-other-page.psml", (String) check + .getDocumentOrder().get(0)); + assertEquals("default-page.psml", (String) check.getDocumentOrder() + .get(1)); assertNull(check.getParent()); assertNotNull(check.getPageSecurity()); assertNotNull(check.getPages()); @@ -752,59 +884,89 @@ assertNotNull(check.getAll()); assertEquals(6, check.getAll().size()); Iterator all = check.getAll().iterator(); - assertEquals("some-other-page.psml", ((Node)all.next()).getName()); - assertEquals("default-page.psml", ((Node)all.next()).getName()); - assertEquals("__subsite-rootx", ((Node)all.next()).getName()); - assertEquals("another-page.psml", ((Node)all.next()).getName()); - assertEquals("default.link", ((Node)all.next()).getName()); - assertEquals("page.security", ((Node)all.next()).getName()); + assertEquals("some-other-page.psml", ((Node) all.next()).getName()); + assertEquals("default-page.psml", ((Node) all.next()).getName()); + assertEquals("__subsite-rootx", ((Node) all.next()).getName()); + assertEquals("another-page.psml", ((Node) all.next()).getName()); + assertEquals("default.link", ((Node) all.next()).getName()); + assertEquals("page.security", ((Node) all.next()).getName()); assertNotNull(check.getMenuDefinitions()); assertEquals(2, check.getMenuDefinitions().size()); - MenuDefinition checkMenu = (MenuDefinition)check.getMenuDefinitions().get(0); + MenuDefinition checkMenu = (MenuDefinition) check + .getMenuDefinitions().get(0); assertEquals("folder-breadcrumb-menu", checkMenu.getName()); assertEquals("bread-crumbs", checkMenu.getSkin()); assertEquals("./", checkMenu.getOptions()); assertTrue(checkMenu.isPaths()); assertNotNull(checkMenu.getMenuElements()); assertTrue(checkMenu.getMenuElements().isEmpty()); - checkMenu = (MenuDefinition)check.getMenuDefinitions().get(1); + checkMenu = (MenuDefinition) check.getMenuDefinitions().get(1); assertEquals("folder-menu", checkMenu.getName()); assertEquals("The Test Folder Menu", checkMenu.getTitle()); assertEquals("Folder Menu", checkMenu.getShortTitle()); assertEquals("group-fallback", checkMenu.getProfile()); - assertEquals("[fr] Folder Menu", checkMenu.getShortTitle(Locale.FRENCH)); - assertEquals("[fr] The Test Folder Menu", checkMenu.getTitle(Locale.FRENCH)); + assertEquals("[fr] Folder Menu", checkMenu + .getShortTitle(Locale.FRENCH)); + assertEquals("[fr] The Test Folder Menu", checkMenu + .getTitle(Locale.FRENCH)); assertNotNull(checkMenu.getMenuElements()); - assertEquals(6,checkMenu.getMenuElements().size()); + assertEquals(6, checkMenu.getMenuElements().size()); assertTrue(checkMenu.getMenuElements().get(0) instanceof MenuSeparatorDefinition); - assertEquals("-- Folder Menu --", ((MenuSeparatorDefinition)checkMenu.getMenuElements().get(0)).getText()); - assertEquals("Rollover: Folder Menu", ((MenuSeparatorDefinition)checkMenu.getMenuElements().get(0)).getTitle()); - assertEquals("header", ((MenuSeparatorDefinition)checkMenu.getMenuElements().get(0)).getSkin()); - assertEquals("-- [fr] Folder Menu --", ((MenuSeparatorDefinition)checkMenu.getMenuElements().get(0)).getText(Locale.FRENCH)); - assertEquals("[fr] Rollover: Folder Menu", ((MenuSeparatorDefinition)checkMenu.getMenuElements().get(0)).getTitle(Locale.FRENCH)); + assertEquals("-- Folder Menu --", + ((MenuSeparatorDefinition) checkMenu.getMenuElements().get( + 0)).getText()); + assertEquals("Rollover: Folder Menu", + ((MenuSeparatorDefinition) checkMenu.getMenuElements().get( + 0)).getTitle()); + assertEquals("header", ((MenuSeparatorDefinition) checkMenu + .getMenuElements().get(0)).getSkin()); + assertEquals("-- [fr] Folder Menu --", + ((MenuSeparatorDefinition) checkMenu.getMenuElements().get( + 0)).getText(Locale.FRENCH)); + assertEquals("[fr] Rollover: Folder Menu", + ((MenuSeparatorDefinition) checkMenu.getMenuElements().get( + 0)).getTitle(Locale.FRENCH)); assertTrue(checkMenu.getMenuElements().get(1) instanceof MenuOptionsDefinition); - assertEquals("/*.psml", ((MenuOptionsDefinition)checkMenu.getMenuElements().get(1)).getOptions()); - assertTrue(((MenuOptionsDefinition)checkMenu.getMenuElements().get(1)).isRegexp()); - assertEquals("flash", ((MenuOptionsDefinition)checkMenu.getMenuElements().get(1)).getSkin()); + assertEquals("/*.psml", ((MenuOptionsDefinition) checkMenu + .getMenuElements().get(1)).getOptions()); + assertTrue(((MenuOptionsDefinition) checkMenu.getMenuElements() + .get(1)).isRegexp()); + assertEquals("flash", ((MenuOptionsDefinition) checkMenu + .getMenuElements().get(1)).getSkin()); assertTrue(checkMenu.getMenuElements().get(2) instanceof MenuOptionsDefinition); - assertEquals("/folder0", ((MenuOptionsDefinition)checkMenu.getMenuElements().get(2)).getOptions()); - assertEquals("role-fallback", ((MenuOptionsDefinition)checkMenu.getMenuElements().get(2)).getProfile()); - assertEquals("/folder*", ((MenuOptionsDefinition)checkMenu.getMenuElements().get(2)).getOrder()); - assertEquals(1, ((MenuOptionsDefinition)checkMenu.getMenuElements().get(2)).getDepth()); - assertTrue(((MenuOptionsDefinition)checkMenu.getMenuElements().get(2)).isPaths()); + assertEquals("/folder0", ((MenuOptionsDefinition) checkMenu + .getMenuElements().get(2)).getOptions()); + assertEquals("role-fallback", ((MenuOptionsDefinition) checkMenu + .getMenuElements().get(2)).getProfile()); + assertEquals("/folder*", ((MenuOptionsDefinition) checkMenu + .getMenuElements().get(2)).getOrder()); + assertEquals(1, ((MenuOptionsDefinition) checkMenu + .getMenuElements().get(2)).getDepth()); + assertTrue(((MenuOptionsDefinition) checkMenu.getMenuElements() + .get(2)).isPaths()); assertTrue(checkMenu.getMenuElements().get(3) instanceof MenuDefinition); - assertEquals("/*/", ((MenuDefinition)checkMenu.getMenuElements().get(3)).getOptions()); - assertTrue(((MenuDefinition)checkMenu.getMenuElements().get(3)).isRegexp()); - assertEquals(2, ((MenuDefinition)checkMenu.getMenuElements().get(3)).getDepth()); - assertEquals("/x*/,/y*/,/z*/", ((MenuDefinition)checkMenu.getMenuElements().get(3)).getOrder()); - assertEquals("bold", ((MenuDefinition)checkMenu.getMenuElements().get(3)).getSkin()); - assertNotNull(((MenuDefinition)checkMenu.getMenuElements().get(3)).getMenuElements()); - assertTrue(((MenuDefinition)checkMenu.getMenuElements().get(3)).getMenuElements().isEmpty()); + assertEquals("/*/", ((MenuDefinition) checkMenu.getMenuElements() + .get(3)).getOptions()); + assertTrue(((MenuDefinition) checkMenu.getMenuElements().get(3)) + .isRegexp()); + assertEquals(2, ((MenuDefinition) checkMenu.getMenuElements() + .get(3)).getDepth()); + assertEquals("/x*/,/y*/,/z*/", ((MenuDefinition) checkMenu + .getMenuElements().get(3)).getOrder()); + assertEquals("bold", ((MenuDefinition) checkMenu.getMenuElements() + .get(3)).getSkin()); + assertNotNull(((MenuDefinition) checkMenu.getMenuElements().get(3)) + .getMenuElements()); + assertTrue(((MenuDefinition) checkMenu.getMenuElements().get(3)) + .getMenuElements().isEmpty()); assertTrue(checkMenu.getMenuElements().get(4) instanceof MenuExcludeDefinition); - assertEquals("exclude-menu", ((MenuExcludeDefinition)checkMenu.getMenuElements().get(4)).getName()); + assertEquals("exclude-menu", ((MenuExcludeDefinition) checkMenu + .getMenuElements().get(4)).getName()); assertTrue(checkMenu.getMenuElements().get(5) instanceof MenuIncludeDefinition); - assertEquals("include-menu", ((MenuIncludeDefinition)checkMenu.getMenuElements().get(5)).getName()); - assertTrue(((MenuIncludeDefinition)checkMenu.getMenuElements().get(5)).isNest()); + assertEquals("include-menu", ((MenuIncludeDefinition) checkMenu + .getMenuElements().get(5)).getName()); + assertTrue(((MenuIncludeDefinition) checkMenu.getMenuElements() + .get(5)).isNest()); } catch (FolderNotFoundException e) { @@ -816,8 +978,10 @@ assertEquals("/another-page.psml", check.getPath()); assertEquals("another-page.psml", check.getName()); assertEquals("Another Page", check.getTitle()); - assertEquals("jetspeed", check.getEffectiveDefaultDecorator(Fragment.LAYOUT)); - assertEquals("gray-gradient", check.getEffectiveDefaultDecorator(Fragment.PORTLET)); + assertEquals("jetspeed", check + .getEffectiveDefaultDecorator(Fragment.LAYOUT)); + assertEquals("gray-gradient", check + .getEffectiveDefaultDecorator(Fragment.PORTLET)); assertNull(check.getDefaultDecorator(Fragment.LAYOUT)); assertNull(check.getDefaultDecorator(Fragment.PORTLET)); } @@ -852,7 +1016,7 @@ { // reset page manager cache pageManager.reset(); - + // update documents and folders in persisted store PageSecurity pageSecurity = pageManager.getPageSecurity(); assertEquals("/page.security", pageSecurity.getPath()); @@ -866,11 +1030,13 @@ page.getRootFragment().getProperties().put("UPDATED", "UPDATED"); assertNotNull(page.getRootFragment().getFragments()); assertEquals(2, page.getRootFragment().getFragments().size()); - String removeId = ((Fragment)page.getRootFragment().getFragments().get(1)).getId(); + String removeId = ((Fragment) page.getRootFragment().getFragments() + .get(1)).getId(); assertNotNull(page.removeFragmentById(removeId)); SecurityConstraint pageConstraint = page.newSecurityConstraint(); pageConstraint.setUsers(Shared.makeListFromCSV("UPDATED")); - page.getSecurityConstraints().getSecurityConstraints().add(0, pageConstraint); + page.getSecurityConstraints().getSecurityConstraints().add(0, + pageConstraint); pageManager.updatePage(page); Link link = pageManager.getLink("/default.link"); @@ -885,17 +1051,20 @@ folder.getDocumentOrder().remove("some-other-page.psml"); folder.getDocumentOrder().add("UPDATED"); folder.getDocumentOrder().add("some-other-page.psml"); - MenuDefinition updateMenu = (MenuDefinition)folder.getMenuDefinitions().get(1); + MenuDefinition updateMenu = (MenuDefinition) folder + .getMenuDefinitions().get(1); updateMenu.setName("UPDATED"); updateMenu.setTitle("UPDATED"); - updateMenu.getMetadata().addField(Locale.JAPANESE, "short-title", "[ja] UPDATED"); - ((MenuOptionsDefinition)updateMenu.getMenuElements().get(2)).setProfile("UPDATED"); + updateMenu.getMetadata().addField(Locale.JAPANESE, "short-title", + "[ja] UPDATED"); + ((MenuOptionsDefinition) updateMenu.getMenuElements().get(2)) + .setProfile("UPDATED"); pageManager.updateFolder(folder); assertNotNull(folder.getAll()); assertEquals(6, folder.getAll().size()); Iterator all = folder.getAll().iterator(); - assertEquals("default-page.psml", ((Node)all.next()).getName()); - assertEquals("some-other-page.psml", ((Node)all.next()).getName()); + assertEquals("default-page.psml", ((Node) all.next()).getName()); + assertEquals("some-other-page.psml", ((Node) all.next()).getName()); folder.setTitle("FOLDER-UPDATED-DEEP"); page.setTitle("FOLDER-UPDATED-DEEP"); @@ -911,7 +1080,7 @@ { // reset page manager cache pageManager.reset(); - + // remove root folder try { @@ -923,10 +1092,10 @@ { assertTrue("Folder / NOT FOUND", false); } - + // reset page manager cache pageManager.reset(); - + // verify root folder deep removal try { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestMappings.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestMappings.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestMappings.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,23 +34,24 @@ Mapping mapping = new Mapping(); // 1. Load the mapping information from the file - mapping.loadMapping(new InputSource(getClass().getClassLoader().getResourceAsStream( - "JETSPEED-INF/castor/page-mapping.xml"))); + mapping.loadMapping(new InputSource(getClass().getClassLoader() + .getResourceAsStream("JETSPEED-INF/castor/page-mapping.xml"))); // 2. Unmarshal the data Unmarshaller unmar = new Unmarshaller(mapping); - Fragment fragment = (Fragment) unmar.unmarshal(new InputSource(getClass().getClassLoader().getResourceAsStream( - "fragment-test.xml"))); - + Fragment fragment = (Fragment) unmar.unmarshal(new InputSource( + getClass().getClassLoader().getResourceAsStream( + "fragment-test.xml"))); + assertNotNull(fragment); assertEquals(1, fragment.getPreferences().size()); Preference pref = (Preference) fragment.getPreferences().get(0); - + assertEquals("Google", pref.getName()); assertEquals(false, pref.isReadOnly()); Iterator itr = pref.getValues(); - String value = (String )itr.next(); - assertEquals("http://www.google.com", value ); + String value = (String) itr.next(); + assertEquals("http://www.google.com", value); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecureCastorXmlPageManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecureCastorXmlPageManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecureCastorXmlPageManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,8 +28,10 @@ * @author Randy Watler * @version $Id$ */ -public class TestSecureCastorXmlPageManager extends TestCase implements PageManagerTestShared +public class TestSecureCastorXmlPageManager extends TestCase implements + PageManagerTestShared { + protected CastorXmlPageManager pageManager; /* @@ -40,7 +42,8 @@ protected void setUp() throws Exception { super.setUp(); - pageManager = Shared.makeCastorXMLPageManager("secure-pages", false, true); + pageManager = Shared.makeCastorXMLPageManager("secure-pages", false, + true); } /** @@ -62,7 +65,7 @@ * @param name * the testcase's name. */ - public TestSecureCastorXmlPageManager( String name ) + public TestSecureCastorXmlPageManager(String name) { super(name); } @@ -73,9 +76,10 @@ * @param args * the arguments. Not used */ - public static void main( String args[] ) + public static void main(String args[]) { - junit.awtui.TestRunner.main(new String[]{TestSecureCastorXmlPageManager.class.getName()}); + junit.awtui.TestRunner.main(new String[] + {TestSecureCastorXmlPageManager.class.getName()}); } /** Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecureDatabasePageManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecureDatabasePageManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecureDatabasePageManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,33 +16,36 @@ */ package org.apache.jetspeed.page; -import org.apache.jetspeed.components.util.DatasourceEnabledSpringTestCase; import junit.framework.Test; import junit.framework.TestSuite; +import org.apache.jetspeed.components.util.DatasourceEnabledSpringTestCase; + /** * TestSecureDatabasePageManager * * @author Randy Watler * @version $Id: $ - * + * */ -public class TestSecureDatabasePageManager extends DatasourceEnabledSpringTestCase implements PageManagerTestShared +public class TestSecureDatabasePageManager extends + DatasourceEnabledSpringTestCase implements PageManagerTestShared { + protected PageManager pageManager; protected String somePortletId; - + public static void main(String args[]) { junit.awtui.TestRunner.main(new String[] - { TestSecureDatabasePageManager.class.getName() }); + {TestSecureDatabasePageManager.class.getName()}); } - + protected void setUp() throws Exception { super.setUp(); - pageManager = (PageManager)ctx.getBean("pageManager"); + pageManager = (PageManager) ctx.getBean("pageManager"); } public static Test suite() @@ -50,11 +53,11 @@ // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestSecureDatabasePageManager.class); } - + protected String[] getConfigurations() { return new String[] - { "secure-database-page-manager.xml", "transaction.xml" }; + {"secure-database-page-manager.xml", "transaction.xml"}; } public void testSecurePageManager() throws Exception Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecurePermissionsCastorXmlPageManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecurePermissionsCastorXmlPageManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecurePermissionsCastorXmlPageManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,16 +27,19 @@ * @author Randy Watler * @version $Id$ */ -public class TestSecurePermissionsCastorXmlPageManager extends TestSecureCastorXmlPageManager +public class TestSecurePermissionsCastorXmlPageManager extends + TestSecureCastorXmlPageManager { - public TestSecurePermissionsCastorXmlPageManager( String name ) + + public TestSecurePermissionsCastorXmlPageManager(String name) { super(name); } - public static void main( String args[] ) + public static void main(String args[]) { - junit.awtui.TestRunner.main(new String[]{TestSecurePermissionsCastorXmlPageManager.class.getName()}); + junit.awtui.TestRunner.main(new String[] + {TestSecurePermissionsCastorXmlPageManager.class.getName()}); } protected void setUp() throws Exception Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecurePermissionsDatabasePageManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecurePermissionsDatabasePageManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestSecurePermissionsDatabasePageManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,16 +26,18 @@ * * @author Randy Watler * @version $Id: $ - * + * */ -public class TestSecurePermissionsDatabasePageManager extends TestSecureDatabasePageManager +public class TestSecurePermissionsDatabasePageManager extends + TestSecureDatabasePageManager { + public static void main(String args[]) { junit.awtui.TestRunner.main(new String[] - { TestSecurePermissionsDatabasePageManager.class.getName() }); + {TestSecurePermissionsDatabasePageManager.class.getName()}); } - + protected void setUp() throws Exception { super.setUp(); @@ -50,10 +52,10 @@ // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestSecurePermissionsDatabasePageManager.class); } - + protected String[] getConfigurations() { return new String[] - { "secure-permissions-database-page-manager.xml", "transaction.xml" }; + {"secure-permissions-database-page-manager.xml", "transaction.xml"}; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestTransactions.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestTransactions.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/TestTransactions.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,49 +30,53 @@ * @author Randy Watler * @author David Sean Taylor * @version $Id: $ - * + * */ -public class TestTransactions extends DatasourceEnabledSpringTestCase implements PageManagerTestShared +public class TestTransactions extends DatasourceEnabledSpringTestCase implements + PageManagerTestShared { + protected PageManager pageManager; protected String somePortletId; - + public static void main(String args[]) { junit.awtui.TestRunner.main(new String[] - { TestTransactions.class.getName() }); + {TestTransactions.class.getName()}); } - + protected void setUp() throws Exception { - super.setUp(); - pageManager = (PageManager)ctx.getBean("pageManager"); + super.setUp(); + pageManager = (PageManager) ctx.getBean("pageManager"); } public static Test suite() { -// System.setProperty("org.apache.jetspeed.database.url", "jdbc:mysql://j2-server/j2"); -// System.setProperty("org.apache.jetspeed.database.driver", "com.mysql.jdbc.Driver"); -// System.setProperty("org.apache.jetspeed.database.user", "j2"); -// System.setProperty("org.apache.jetspeed.database.password", "xxxxx"); - + // System.setProperty("org.apache.jetspeed.database.url", + // "jdbc:mysql://j2-server/j2"); + // System.setProperty("org.apache.jetspeed.database.driver", + // "com.mysql.jdbc.Driver"); + // System.setProperty("org.apache.jetspeed.database.user", "j2"); + // System.setProperty("org.apache.jetspeed.database.password", "xxxxx"); + // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestTransactions.class); } - + protected String[] getConfigurations() { return new String[] - { "tx-page-manager.xml", "transaction.xml", "interceptors.xml" }; + {"tx-page-manager.xml", "transaction.xml", "interceptors.xml"}; } protected String[] getBootConfigurations() { return new String[] - { "boot/datasource.xml"}; + {"boot/datasource.xml"}; } - + public void testTx() throws Exception { if (pageManager.folderExists("/")) @@ -81,18 +85,18 @@ } Folder root = pageManager.newFolder("/"); pageManager.updateFolder(root); - + System.out.println("--- before new Page"); DatabasePageManagerCache.dump(); - + Page[] pages = new Page[3]; pages[0] = pageManager.newPage("/tx__test1.psml"); pages[1] = pageManager.newPage("/tx__test2.psml"); pages[2] = pageManager.newPage("/tx__test3.psml"); - + System.out.println("--- after new Page"); DatabasePageManagerCache.dump(); - + try { pageManager.addPages(pages); @@ -100,8 +104,8 @@ catch (Exception e) { System.out.println("Exception adding pages" + e); - // e.printStackTrace(); - + // e.printStackTrace(); + } System.out.println("--- after rollback"); DatabasePageManagerCache.dump(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/document/psml/TestCastorFileSystemDocumentHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/document/psml/TestCastorFileSystemDocumentHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/page-manager/src/test/org/apache/jetspeed/page/document/psml/TestCastorFileSystemDocumentHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,22 +16,19 @@ */ package org.apache.jetspeed.page.document.psml; -import java.util.Iterator; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; -import java.util.ArrayList; import java.util.Map; -import java.util.HashMap; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; +import org.apache.jetspeed.cache.file.FileCache; +import org.apache.jetspeed.om.folder.psml.FolderMetaDataImpl; import org.apache.jetspeed.om.page.Document; -import org.apache.jetspeed.om.folder.psml.FolderMetaDataImpl; -import org.apache.jetspeed.page.psml.CastorXmlPageManager; import org.apache.jetspeed.page.document.DocumentHandlerFactory; -import org.apache.jetspeed.page.document.psml.DocumentHandlerFactoryImpl; -import org.apache.jetspeed.cache.file.FileCache; /** *

        @@ -43,7 +40,7 @@ * * @author Woonsan Ko * @version $Id$ - * + * */ public class TestCastorFileSystemDocumentHandler extends TestCase { @@ -58,17 +55,15 @@ protected void setUp() throws Exception { super.setUp(); - + folderMetaDataDocumentHandler = new CastorFileSystemDocumentHandler( - "/JETSPEED-INF/castor/page-mapping.xml", - "folder.metadata", - FolderMetaDataImpl.class, - "testdata/pages", - new FileCache()); - + "/JETSPEED-INF/castor/page-mapping.xml", "folder.metadata", + FolderMetaDataImpl.class, "testdata/pages", new FileCache()); + Map handlerMap = new HashMap(); handlerMap.put("folder.metadata", folderMetaDataDocumentHandler); - DocumentHandlerFactory handlerFactory = new DocumentHandlerFactoryImpl(handlerMap); + DocumentHandlerFactory handlerFactory = new DocumentHandlerFactoryImpl( + handlerMap); folderMetaDataDocumentHandler.setHandlerFactory(handlerFactory); } @@ -91,7 +86,7 @@ * @param name * the testcase's name. */ - public TestCastorFileSystemDocumentHandler( String name ) + public TestCastorFileSystemDocumentHandler(String name) { super(name); } @@ -102,9 +97,10 @@ * @param args * the arguments. Not used */ - public static void main( String args[] ) + public static void main(String args[]) { - junit.awtui.TestRunner.main(new String[]{TestCastorFileSystemDocumentHandler.class.getName()}); + junit.awtui.TestRunner.main(new String[] + {TestCastorFileSystemDocumentHandler.class.getName()}); } /** @@ -118,10 +114,11 @@ // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestCastorFileSystemDocumentHandler.class); } - + public void testFolderMetaData() throws Exception { - Document doc = folderMetaDataDocumentHandler.getDocument("/folder1/folder.metadata", false); + Document doc = folderMetaDataDocumentHandler.getDocument( + "/folder1/folder.metadata", false); assertNotNull(doc); String title = doc.getTitle(); assertEquals("Default Title for Folder 1", title); @@ -129,40 +126,44 @@ public void testFolderMetaDataInParallel() throws Exception { - Thread [] threads = new Thread[10]; + Thread[] threads = new Thread[10]; int i; final List exceptions = new ArrayList(10); - + for (i = 0; i < threads.length; i++) { threads[i] = new Thread(new Runnable() + { + + public void run() { - public void run() + try { - try - { - Document doc = folderMetaDataDocumentHandler.getDocument("/folder1/folder.metadata", false); - } - catch (Exception e) - { - e.printStackTrace(System.out); - exceptions.add(e); - } + Document doc = folderMetaDataDocumentHandler + .getDocument("/folder1/folder.metadata", false); } - }); + catch (Exception e) + { + e.printStackTrace(System.out); + exceptions.add(e); + } + } + }); } - + for (i = 0; i < threads.length; i++) { threads[i].start(); } - + for (i = 0; i < threads.length; i++) { threads[i].join(); } - - assertTrue("folderMetaDataDocumentHandler.getDocument() is not thread-safe!", exceptions.size() == 0); + + assertTrue( + "folderMetaDataDocumentHandler.getDocument() is not thread-safe!", + exceptions.size() == 0); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/AbstractAuthFilter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/AbstractAuthFilter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/AbstractAuthFilter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -48,7 +48,9 @@ import org.apache.jetspeed.security.impl.PrincipalsSet; import org.apache.jetspeed.security.impl.UserSubjectPrincipalImpl; -public abstract class AbstractAuthFilter implements Filter { +public abstract class AbstractAuthFilter implements Filter +{ + private static final Log log = LogFactory.getLog(AbstractAuthFilter.class); protected String guest = "guest"; @@ -59,42 +61,52 @@ protected boolean skipPasswordCheck = false; - public void init(FilterConfig filterConfig) throws ServletException { + public void init(FilterConfig filterConfig) throws ServletException + { PortalConfiguration config = Jetspeed.getConfiguration(); - if (config != null) { + if (config != null) + { guest = config.getString("default.user.principal"); } usernameKey = filterConfig.getInitParameter("username.key"); - if (usernameKey == null) { + if (usernameKey == null) + { usernameKey = LoginConstants.USERNAME; } passwordKey = filterConfig.getInitParameter("password.key"); - if (passwordKey == null) { + if (passwordKey == null) + { passwordKey = LoginConstants.PASSWORD; } String value = filterConfig.getInitParameter("skip.password.check"); - if (value != null && value.equalsIgnoreCase("true")) { + if (value != null && value.equalsIgnoreCase("true")) + { skipPasswordCheck = true; } // debug - if (log.isDebugEnabled()) { + if (log.isDebugEnabled()) + { log.debug("usernameKey=" + usernameKey); log.debug("passwordKey=" + passwordKey); log.debug("skipPasswordCheck=" + skipPasswordCheck); } } - public void destroy() { + public void destroy() + { } public void doFilter(ServletRequest sRequest, ServletResponse sResponse, - FilterChain filterChain) throws IOException, ServletException { - if (sRequest instanceof HttpServletRequest) { + FilterChain filterChain) throws IOException, ServletException + { + if (sRequest instanceof HttpServletRequest) + { HttpServletRequest request = (HttpServletRequest) sRequest; String username = getUsername(request); - if (username != null) { + if (username != null) + { UserManager userManager = (UserManager) Jetspeed .getComponentManager().getComponent( "org.apache.jetspeed.security.UserManager"); @@ -103,13 +115,15 @@ "org.apache.jetspeed.audit.AuditActivity"); boolean success = true; - if (!skipPasswordCheck) { + if (!skipPasswordCheck) + { // check password success = userManager.authenticate(username, getPassword(request)); } - if (success) { + if (success) + { audit.logUserActivity(username, request.getRemoteAddr(), AuditActivity.AUTHENTICATION_SUCCESS, "PortalFilter"); @@ -118,22 +132,28 @@ .getComponent( "org.apache.jetspeed.administration.PortalAuthenticationConfiguration"); - if (authenticationConfiguration.isCreateNewSessionOnLogin()) { + if (authenticationConfiguration.isCreateNewSessionOnLogin()) + { // invalidate session request.getSession().invalidate(); } Subject subject = null; - try { + try + { // load the user info User user = userManager.getUser(username); - if (user != null) { + if (user != null) + { subject = user.getSubject(); } - } catch (SecurityException sex) { } + catch (SecurityException sex) + { + } - if (subject == null) { + if (subject == null) + { Set principals = new PrincipalsSet(); UserSubjectPrincipalImpl userPrincipal = new UserSubjectPrincipalImpl( username); @@ -152,7 +172,9 @@ session.setAttribute( PortalReservedParameters.SESSION_KEY_SUBJECT, subject); - } else { + } + else + { audit.logUserActivity(username, request.getRemoteAddr(), AuditActivity.AUTHENTICATION_FAILURE, "PortalFilter"); @@ -160,20 +182,27 @@ LoginConstants.ERROR_INVALID_PASSWORD); // debug - if (log.isDebugEnabled()) { + if (log.isDebugEnabled()) + { log.debug("Authentication failure: username=" + username); } } - } else { + } + else + { Subject subject = (Subject) request.getSession().getAttribute( PortalReservedParameters.SESSION_KEY_SUBJECT); - if (subject != null) { + if (subject != null) + { Principal principal = SecurityHelper.getPrincipal(subject, UserPrincipal.class); if (principal != null - && principal.getName().equals(this.guest)) { - } else { + && principal.getName().equals(this.guest)) + { + } + else + { sRequest = wrapperRequest(request, subject, principal); } } @@ -183,13 +212,15 @@ PortalReservedParameters.PORTAL_FILTER_ATTRIBUTE, "true"); } - if (filterChain != null) { + if (filterChain != null) + { filterChain.doFilter(sRequest, sResponse); } } private ServletRequest wrapperRequest(HttpServletRequest request, - Subject subject, Principal principal) { + Subject subject, Principal principal) + { PortalRequestWrapper wrapper = new PortalRequestWrapper(request, subject, principal); return wrapper; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/CookieAuthFilter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/CookieAuthFilter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/CookieAuthFilter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -3,23 +3,28 @@ import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; -public class CookieAuthFilter extends AbstractAuthFilter { +public class CookieAuthFilter extends AbstractAuthFilter +{ - public String getPassword(HttpServletRequest request) { + public String getPassword(HttpServletRequest request) + { return getValueFromCookies(request, passwordKey); } - public String getUsername(HttpServletRequest request) { + public String getUsername(HttpServletRequest request) + { return getValueFromCookies(request, usernameKey); } - protected String getValueFromCookies(HttpServletRequest request, String key) { + protected String getValueFromCookies(HttpServletRequest request, String key) + { Cookie[] cookies = request.getCookies(); - if (cookies != null) { - for (int i = 0; i < cookies.length; i++) { - if (key.equals(cookies[i].getName())) { - return cookies[i].getValue(); - } + if (cookies != null) + { + for (int i = 0; i < cookies.length; i++) + { + if (key.equals(cookies[i].getName())) { return cookies[i] + .getValue(); } } } return null; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/CookieTransferFilter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/CookieTransferFilter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/CookieTransferFilter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,7 +25,9 @@ import org.apache.jetspeed.security.User; import org.apache.jetspeed.security.UserManager; -public class CookieTransferFilter implements Filter { +public class CookieTransferFilter implements Filter +{ + private static final Log log = LogFactory .getLog(CookieTransferFilter.class); @@ -60,36 +62,48 @@ protected Map transferredInfo; - public void init(FilterConfig filterConfig) throws ServletException { + public void init(FilterConfig filterConfig) throws ServletException + { path = filterConfig.getInitParameter(PATH); domain = filterConfig.getInitParameter(DOMAIN); String value = filterConfig.getInitParameter(MAX_AGE); - if (value != null) { - try { + if (value != null) + { + try + { maxAge = Integer.parseInt(value); - } catch (NumberFormatException e) { } + catch (NumberFormatException e) + { + } } value = filterConfig.getInitParameter(SECURE); - if (value != null && value.equalsIgnoreCase("true")) { + if (value != null && value.equalsIgnoreCase("true")) + { secure = true; } transferredInfo = new HashMap(); value = filterConfig.getInitParameter(TRANSFERRED_INFO); - if (value != null) { + if (value != null) + { StringTokenizer st = new StringTokenizer(value, ", \t\n\r\f"); - while (st.hasMoreTokens()) { + while (st.hasMoreTokens()) + { String pair = st.nextToken(); int index = pair.indexOf("="); - if (index > 0 && index + 1 < pair.length()) { + if (index > 0 && index + 1 < pair.length()) + { String k = pair.substring(0, index); String v = pair.substring(index + 1); - if (USERNAME.equals(v)) { + if (USERNAME.equals(v)) + { usernameKey = k; - } else { + } + else + { transferredInfo.put(k, v); } } @@ -97,7 +111,8 @@ } // debug - if (log.isDebugEnabled()) { + if (log.isDebugEnabled()) + { log.debug("path=" + path); log.debug("domain=" + domain); log.debug("maxAge=" + maxAge); @@ -106,7 +121,8 @@ } } - public void destroy() { + public void destroy() + { path = null; domain = null; usernameKey = null; @@ -114,42 +130,53 @@ } public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { + FilterChain chain) throws IOException, ServletException + { if (request instanceof HttpServletRequest - && response instanceof HttpServletResponse) { + && response instanceof HttpServletResponse) + { HttpServletRequest hRequest = (HttpServletRequest) request; HttpServletResponse hResponse = (HttpServletResponse) response; String username = hRequest.getRemoteUser(); - if (username != null) { - if (!checkTransferredInfo(hRequest, false)) { + if (username != null) + { + if (!checkTransferredInfo(hRequest, false)) + { UserManager userManager = (UserManager) Jetspeed .getComponentManager().getComponent( "org.apache.jetspeed.security.UserManager"); - if (usernameKey != null) { + if (usernameKey != null) + { hResponse.addCookie(createNewCookie(usernameKey, username)); } - if (!transferredInfo.isEmpty()) { - try { + if (!transferredInfo.isEmpty()) + { + try + { User user = userManager.getUser(username); Preferences userAttributes = user .getUserAttributes(); Iterator itr = transferredInfo.entrySet() .iterator(); - while (itr.hasNext()) { + while (itr.hasNext()) + { Map.Entry entry = (Map.Entry) itr.next(); String value = userAttributes .get((String) entry.getValue(), EMPTY_STRING); - if (!value.equals(EMPTY_STRING)) { + if (!value.equals(EMPTY_STRING)) + { hResponse.addCookie(createNewCookie( (String) entry.getKey(), value)); } } - } catch (SecurityException e) { + } + catch (SecurityException e) + { log.warn( "Could not get the user info: " + username, e); @@ -162,16 +189,22 @@ hRequest.getSession().setAttribute(IS_TRANSFERRED, Boolean.TRUE); } - } else { - if (checkTransferredInfo(hRequest, true)) { + } + else + { + if (checkTransferredInfo(hRequest, true)) + { - if (usernameKey != null) { + if (usernameKey != null) + { hResponse.addCookie(createExpiredCookie(usernameKey)); } - if (!transferredInfo.isEmpty()) { + if (!transferredInfo.isEmpty()) + { Iterator itr = transferredInfo.entrySet().iterator(); - while (itr.hasNext()) { + while (itr.hasNext()) + { Map.Entry entry = (Map.Entry) itr.next(); hResponse .addCookie(createExpiredCookie((String) entry @@ -188,54 +221,64 @@ } } - if (chain != null) { + if (chain != null) + { chain.doFilter(request, response); } } protected boolean checkTransferredInfo(HttpServletRequest hRequest, - boolean defaultValue) { + boolean defaultValue) + { HttpSession session = hRequest.getSession(false); - if (session != null) { + if (session != null) + { Boolean isTransferredInfo = (Boolean) session .getAttribute(IS_TRANSFERRED); - if (isTransferredInfo != null) { - return isTransferredInfo.booleanValue(); - } + if (isTransferredInfo != null) { return isTransferredInfo + .booleanValue(); } } return defaultValue; } - protected Cookie createNewCookie(String name, String value) { + protected Cookie createNewCookie(String name, String value) + { return createCookie(name, value, maxAge); } - protected Cookie createExpiredCookie(String name) { + protected Cookie createExpiredCookie(String name) + { return createCookie(name, EMPTY_STRING, 0); } - private Cookie createCookie(String name, String value, int age) { + private Cookie createCookie(String name, String value, int age) + { Cookie cookie = new Cookie(name, value); - if (domain != null) { + if (domain != null) + { cookie.setDomain(domain); } - if (path != null) { + if (path != null) + { cookie.setPath("/"); } cookie.setMaxAge(age); - if (secure) { + if (secure) + { cookie.setSecure(secure); } return cookie; } protected void storeCookies(HttpServletRequest hRequest, - HttpServletResponse hResponse) { + HttpServletResponse hResponse) + { } protected void removeCookies(HttpServletRequest hRequest, - HttpServletResponse hResponse) { + HttpServletResponse hResponse) + { } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/RequestHeaderAuthFilter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/RequestHeaderAuthFilter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/RequestHeaderAuthFilter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -2,13 +2,16 @@ import javax.servlet.http.HttpServletRequest; -public class RequestHeaderAuthFilter extends AbstractAuthFilter { +public class RequestHeaderAuthFilter extends AbstractAuthFilter +{ - public String getPassword(HttpServletRequest request) { + public String getPassword(HttpServletRequest request) + { return request.getHeader(passwordKey); } - public String getUsername(HttpServletRequest request) { + public String getUsername(HttpServletRequest request) + { return request.getHeader(usernameKey); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/RequestParameterAuthFilter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/RequestParameterAuthFilter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/filter/RequestParameterAuthFilter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -2,12 +2,16 @@ import javax.servlet.http.HttpServletRequest; -public class RequestParameterAuthFilter extends AbstractAuthFilter { - public String getUsername(HttpServletRequest request) { +public class RequestParameterAuthFilter extends AbstractAuthFilter +{ + + public String getUsername(HttpServletRequest request) + { return request.getParameter(usernameKey); } - public String getPassword(HttpServletRequest request) { + public String getPassword(HttpServletRequest request) + { return request.getParameter(passwordKey); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/servlet/UserManagerServlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/servlet/UserManagerServlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/jp/sf/pal/portal/servlet/UserManagerServlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,401 +29,495 @@ * @author shinsuke * */ -public class UserManagerServlet extends HttpServlet { - private static final Log log = LogFactory.getLog(UserManagerServlet.class); +public class UserManagerServlet extends HttpServlet +{ - private static final long serialVersionUID = 7998348249338123303L; + private static final Log log = LogFactory.getLog(UserManagerServlet.class); - public static final String CREATE_ACTION = "create"; - public static final String UPDATE_ACTION = "update"; - public static final String DELETE_ACTION = "delete"; - public static final String AUTHENTICATE_ACTION = "authenticate"; + private static final long serialVersionUID = 7998348249338123303L; - public static final String ACTION_PARAM = "action"; - public static final String USERNAME_PARAM = "username"; - public static final String PASSWORD_PARAM = "password"; + public static final String CREATE_ACTION = "create"; - public static final String SUCCESS_STATUS = "success"; - public static final String AUTHENTICATION_FAILED_STATUS = "authentication-failed"; - public static final String SERVER_ERROR_STATUS = "server-error"; - public static final String INVALID_PARAMETER_STATUS = "invalid-parameter"; - public static final String USER_NOT_FOUND_STATUS = "user-not-found"; - public static final String USER_ALREADY_EXISTS_STATUS = "user-already-exists"; - public static final String EXCLUDED_USER_STATUS = "excluded-user"; + public static final String UPDATE_ACTION = "update"; - private UserManager userManager; - private GroupManager groupManager; - private RoleManager roleManager; - private Profiler profiler; + public static final String DELETE_ACTION = "delete"; - private String[] excludedUsernames; - private String[] defaultRolenames; - private String[] defaultGroupnames; - private String defaultPageRule; + public static final String AUTHENTICATE_ACTION = "authenticate"; - /* - * (non-Javadoc) - * - * @see javax.servlet.GenericServlet#destroy() - */ - public void destroy() { - userManager = null; - } + public static final String ACTION_PARAM = "action"; - /* - * (non-Javadoc) - * - * @see javax.servlet.GenericServlet#init() - */ - public void init() throws ServletException { - userManager = (UserManager) Jetspeed.getComponentManager() - .getComponent("org.apache.jetspeed.security.UserManager"); - if (userManager == null) { - log.error("Could not create UserManager."); - throw new ServletException("Could not create UserManager."); - } - // RoleManager - roleManager = (RoleManager) Jetspeed.getComponentManager() - .getComponent("org.apache.jetspeed.security.RoleManager"); - if (roleManager == null) { - log.error("Could not create RoleManager."); - throw new ServletException("Could not create RoleManager."); - } + public static final String USERNAME_PARAM = "username"; - // GroupManager - groupManager = (GroupManager) Jetspeed.getComponentManager() - .getComponent("org.apache.jetspeed.security.GroupManager"); - if (groupManager == null) { - log.error("Could not create GroupManager."); - throw new ServletException("Could not create GroupManager."); - } + public static final String PASSWORD_PARAM = "password"; - // Profiler - profiler = (Profiler) Jetspeed.getComponentManager().getComponent( - "org.apache.jetspeed.profiler.Profiler"); - if (profiler == null) { - log.error("Could not create Profiler."); - throw new ServletException("Could not create Profiler."); - } + public static final String SUCCESS_STATUS = "success"; - // excludedUsernames - String excludedUsernameList = getServletConfig().getInitParameter( - "excludedUsernames"); - if (excludedUsernameList == null) { - excludedUsernames = new String[0]; - } else { - excludedUsernames = excludedUsernameList.split(","); - } + public static final String AUTHENTICATION_FAILED_STATUS = "authentication-failed"; - // roles - String defaultRoleList = getServletConfig().getInitParameter("roles"); - if (defaultRoleList == null) { - defaultRolenames = new String[0]; - } else { - defaultRolenames = defaultRoleList.split(","); - } + public static final String SERVER_ERROR_STATUS = "server-error"; - // groups - String defaultGroupList = getServletConfig().getInitParameter("groups"); - if (defaultGroupList == null) { - defaultGroupnames = new String[0]; - } else { - defaultGroupnames = defaultGroupList.split(","); - } + public static final String INVALID_PARAMETER_STATUS = "invalid-parameter"; - // rule - defaultPageRule = getServletConfig().getInitParameter("pageRule"); - if (defaultPageRule == null) { - defaultPageRule = "j2"; - } - } + public static final String USER_NOT_FOUND_STATUS = "user-not-found"; - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - doPost(req, resp); - } + public static final String USER_ALREADY_EXISTS_STATUS = "user-already-exists"; - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - String action = req.getParameter(ACTION_PARAM); - if (action == null) { - PrintWriter printWriter = resp.getWriter(); - setResponseHeader(resp); - printResult(printWriter, INVALID_PARAMETER_STATUS, - "action is null.", null); - return; - } else if (AUTHENTICATE_ACTION.equals(action)) { - authenticateUser(req, resp); - } else if (CREATE_ACTION.equals(action)) { - createNewUser(req, resp); - } else if (UPDATE_ACTION.equals(action)) { - updateUser(req, resp); - } else if (DELETE_ACTION.equals(action)) { - deleteUser(req, resp); - } else { - PrintWriter printWriter = resp.getWriter(); - setResponseHeader(resp); - printResult(printWriter, INVALID_PARAMETER_STATUS, - "Invalid action parameter: action=" + action + "", null); - return; - } + public static final String EXCLUDED_USER_STATUS = "excluded-user"; - } + private UserManager userManager; - private boolean checkExcludedUsername(String username) { - for (int i = 0; i < excludedUsernames.length; i++) { - if (username.equals(excludedUsernames[i])) { - return false; - } - } - return true; - } + private GroupManager groupManager; - protected void authenticateUser(HttpServletRequest req, - HttpServletResponse resp) throws IOException { - PrintWriter printWriter = resp.getWriter(); - String username = req.getParameter(USERNAME_PARAM); - String password = req.getParameter(PASSWORD_PARAM); + private RoleManager roleManager; - if (username == null || password == null) { - setResponseHeader(resp); - printResult(printWriter, INVALID_PARAMETER_STATUS, - "Invalid parameter(s): username=" + username - + ", password=" + password, null); - return; - } + private Profiler profiler; - if (!checkExcludedUsername(username)) { - setResponseHeader(resp); - printResult(printWriter, EXCLUDED_USER_STATUS, username - + " is an excluded username. ", null); - return; - } + private String[] excludedUsernames; - if (userManager.authenticate(username, password)) { - // authentication succeeded - setResponseHeader(resp); - printResult(printWriter, SUCCESS_STATUS, null, null); - return; - } else { - // authentication failed - setResponseHeader(resp); - printResult(printWriter, AUTHENTICATION_FAILED_STATUS, null, null); - // TODO check if user exists.. - return; - } - } + private String[] defaultRolenames; - protected void createNewUser(HttpServletRequest req, - HttpServletResponse resp) throws IOException { - PrintWriter printWriter = resp.getWriter(); - String username = req.getParameter(USERNAME_PARAM); - String password = req.getParameter(PASSWORD_PARAM); + private String[] defaultGroupnames; - if (username == null || password == null) { - setResponseHeader(resp); - printResult(printWriter, INVALID_PARAMETER_STATUS, - "Invalid parameter(s): username=" + username - + ", password=" + password, null); - return; - } + private String defaultPageRule; - if (!checkExcludedUsername(username)) { - setResponseHeader(resp); - printResult(printWriter, EXCLUDED_USER_STATUS, username - + " is an excluded username. ", null); - return; - } + /* + * (non-Javadoc) + * + * @see javax.servlet.GenericServlet#destroy() + */ + public void destroy() + { + userManager = null; + } - try { - if (userManager.userExists(username)) { - setResponseHeader(resp); - printResult(printWriter, USER_ALREADY_EXISTS_STATUS, username - + " exists. ", null); - return; - } - // create a user - userManager.addUser(username, password); - } catch (SecurityException e) { - setResponseHeader(resp); - printResult(printWriter, SERVER_ERROR_STATUS, - "Could not create a user: " + e.getMessage(), null); - log.error("Could not create a user: " + e.getMessage(), e); - return; - } + /* + * (non-Javadoc) + * + * @see javax.servlet.GenericServlet#init() + */ + public void init() throws ServletException + { + userManager = (UserManager) Jetspeed.getComponentManager() + .getComponent("org.apache.jetspeed.security.UserManager"); + if (userManager == null) + { + log.error("Could not create UserManager."); + throw new ServletException("Could not create UserManager."); + } + // RoleManager + roleManager = (RoleManager) Jetspeed.getComponentManager() + .getComponent("org.apache.jetspeed.security.RoleManager"); + if (roleManager == null) + { + log.error("Could not create RoleManager."); + throw new ServletException("Could not create RoleManager."); + } - try { - // set roles - if (defaultRolenames != null) { - for (int i = 0; i < defaultRolenames.length; i++) { - roleManager.addRoleToUser(username, defaultRolenames[i]); - } - } + // GroupManager + groupManager = (GroupManager) Jetspeed.getComponentManager() + .getComponent("org.apache.jetspeed.security.GroupManager"); + if (groupManager == null) + { + log.error("Could not create GroupManager."); + throw new ServletException("Could not create GroupManager."); + } - // set groups - if (defaultGroupnames != null) { - for (int i = 0; i < defaultGroupnames.length; i++) { - groupManager.addUserToGroup(username, defaultGroupnames[i]); - } - } + // Profiler + profiler = (Profiler) Jetspeed.getComponentManager().getComponent( + "org.apache.jetspeed.profiler.Profiler"); + if (profiler == null) + { + log.error("Could not create Profiler."); + throw new ServletException("Could not create Profiler."); + } - // profiler - User user = userManager.getUser(username); - Principal userPrincipal = getPrincipal(user.getSubject(), - UserPrincipal.class); - if (userPrincipal != null) { - profiler.setRuleForPrincipal(userPrincipal, profiler - .getRule(defaultPageRule), "page"); - } + // excludedUsernames + String excludedUsernameList = getServletConfig().getInitParameter( + "excludedUsernames"); + if (excludedUsernameList == null) + { + excludedUsernames = new String[0]; + } + else + { + excludedUsernames = excludedUsernameList.split(","); + } - setResponseHeader(resp); - printResult(printWriter, SUCCESS_STATUS, null, null); - return; - } catch (SecurityException e) { - setResponseHeader(resp); - printResult(printWriter, SERVER_ERROR_STATUS, - "Could not create a user: " + e.getMessage(), null); - log.error("Could not create a user: " + e.getMessage(), e); - try { - userManager.removeUser(username); - } catch (SecurityException e1) { - log.error("Could not remove a user: " + e1.getMessage(), e1); - } - return; - } + // roles + String defaultRoleList = getServletConfig().getInitParameter("roles"); + if (defaultRoleList == null) + { + defaultRolenames = new String[0]; + } + else + { + defaultRolenames = defaultRoleList.split(","); + } - } + // groups + String defaultGroupList = getServletConfig().getInitParameter("groups"); + if (defaultGroupList == null) + { + defaultGroupnames = new String[0]; + } + else + { + defaultGroupnames = defaultGroupList.split(","); + } - private Principal getPrincipal(Subject subject, Class cls) { - Principal principal = null; - Iterator principals = subject.getPrincipals().iterator(); - while (principals.hasNext()) { - Principal p = (Principal) principals.next(); - if (cls.isInstance(p)) { - principal = p; - break; - } - } - return principal; - } + // rule + defaultPageRule = getServletConfig().getInitParameter("pageRule"); + if (defaultPageRule == null) + { + defaultPageRule = "j2"; + } + } - protected void updateUser(HttpServletRequest req, HttpServletResponse resp) - throws IOException { - PrintWriter printWriter = resp.getWriter(); - String username = req.getParameter(USERNAME_PARAM); - String password = req.getParameter(PASSWORD_PARAM); + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException + { + doPost(req, resp); + } - if (username == null || password == null) { - setResponseHeader(resp); - printResult(printWriter, INVALID_PARAMETER_STATUS, - "Invalid parameter(s): username=" + username - + ", password=" + password, null); - return; - } + protected void doPost(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException + { + String action = req.getParameter(ACTION_PARAM); + if (action == null) + { + PrintWriter printWriter = resp.getWriter(); + setResponseHeader(resp); + printResult(printWriter, INVALID_PARAMETER_STATUS, + "action is null.", null); + return; + } + else if (AUTHENTICATE_ACTION.equals(action)) + { + authenticateUser(req, resp); + } + else if (CREATE_ACTION.equals(action)) + { + createNewUser(req, resp); + } + else if (UPDATE_ACTION.equals(action)) + { + updateUser(req, resp); + } + else if (DELETE_ACTION.equals(action)) + { + deleteUser(req, resp); + } + else + { + PrintWriter printWriter = resp.getWriter(); + setResponseHeader(resp); + printResult(printWriter, INVALID_PARAMETER_STATUS, + "Invalid action parameter: action=" + action + "", null); + return; + } - if (!checkExcludedUsername(username)) { - setResponseHeader(resp); - printResult(printWriter, EXCLUDED_USER_STATUS, username - + " is an excluded username. ", null); - return; - } + } - try { - if (!userManager.userExists(username)) { - setResponseHeader(resp); - printResult(printWriter, USER_NOT_FOUND_STATUS, username - + " is not found. ", null); - return; - } - // update password - userManager.setPassword(username, null, password); - setResponseHeader(resp); - printResult(printWriter, SUCCESS_STATUS, null, null); - return; - } catch (SecurityException e) { - setResponseHeader(resp); - printResult(printWriter, SERVER_ERROR_STATUS, - "Could not update a user: " + e.getMessage(), null); - log.error("Could not update a user: " + e.getMessage(), e); - return; - } + private boolean checkExcludedUsername(String username) + { + for (int i = 0; i < excludedUsernames.length; i++) + { + if (username.equals(excludedUsernames[i])) { return false; } + } + return true; + } - } + protected void authenticateUser(HttpServletRequest req, + HttpServletResponse resp) throws IOException + { + PrintWriter printWriter = resp.getWriter(); + String username = req.getParameter(USERNAME_PARAM); + String password = req.getParameter(PASSWORD_PARAM); - protected void deleteUser(HttpServletRequest req, HttpServletResponse resp) - throws IOException { - PrintWriter printWriter = resp.getWriter(); - String username = req.getParameter(USERNAME_PARAM); + if (username == null || password == null) + { + setResponseHeader(resp); + printResult(printWriter, INVALID_PARAMETER_STATUS, + "Invalid parameter(s): username=" + username + + ", password=" + password, null); + return; + } - if (username == null) { - setResponseHeader(resp); - printResult(printWriter, INVALID_PARAMETER_STATUS, - "Invalid parameter(s): username=" + username, null); - return; - } + if (!checkExcludedUsername(username)) + { + setResponseHeader(resp); + printResult(printWriter, EXCLUDED_USER_STATUS, username + + " is an excluded username. ", null); + return; + } - if (!checkExcludedUsername(username)) { - setResponseHeader(resp); - printResult(printWriter, EXCLUDED_USER_STATUS, username - + " is an excluded username. ", null); - return; - } + if (userManager.authenticate(username, password)) + { + // authentication succeeded + setResponseHeader(resp); + printResult(printWriter, SUCCESS_STATUS, null, null); + return; + } + else + { + // authentication failed + setResponseHeader(resp); + printResult(printWriter, AUTHENTICATION_FAILED_STATUS, null, null); + // TODO check if user exists.. + return; + } + } - try { - if (!userManager.userExists(username)) { - setResponseHeader(resp); - printResult(printWriter, USER_NOT_FOUND_STATUS, username - + " is not found. ", null); - return; - } - // remove a user - userManager.removeUser(username); - setResponseHeader(resp); - printResult(printWriter, SUCCESS_STATUS, null, null); - return; + protected void createNewUser(HttpServletRequest req, + HttpServletResponse resp) throws IOException + { + PrintWriter printWriter = resp.getWriter(); + String username = req.getParameter(USERNAME_PARAM); + String password = req.getParameter(PASSWORD_PARAM); - } catch (SecurityException e) { - setResponseHeader(resp); - printResult(printWriter, SERVER_ERROR_STATUS, - "Could not remove a user: " + e.getMessage(), null); - log.error("Could not remove a user: " + e.getMessage(), e); - return; - } - } + if (username == null || password == null) + { + setResponseHeader(resp); + printResult(printWriter, INVALID_PARAMETER_STATUS, + "Invalid parameter(s): username=" + username + + ", password=" + password, null); + return; + } - protected void setResponseHeader(HttpServletResponse resp) { - resp.setStatus(HttpServletResponse.SC_OK); - resp.setContentType("text/xml; charset=UTF-8"); - } + if (!checkExcludedUsername(username)) + { + setResponseHeader(resp); + printResult(printWriter, EXCLUDED_USER_STATUS, username + + " is an excluded username. ", null); + return; + } - protected void printResult(PrintWriter printWriter, String status, - String message, Map results) { - StringBuilder buf = new StringBuilder(); - buf.append(""); - buf.append(""); - buf.append(""); - buf.append(status); - buf.append(""); - if (message != null) { - buf.append(""); - buf.append(message); - buf.append(""); - } - if (results != null) { - buf.append(""); - for (Iterator i = results.entrySet().iterator(); i.hasNext();) { - Map.Entry entry = (Map.Entry) i.next(); - buf.append(""); - buf.append(entry.getKey()); - buf.append(""); - buf.append(""); - buf.append(entry.getValue()); - buf.append(""); - } - buf.append(""); - } - buf.append(""); - printWriter.print(buf.toString()); - printWriter.flush(); - } + try + { + if (userManager.userExists(username)) + { + setResponseHeader(resp); + printResult(printWriter, USER_ALREADY_EXISTS_STATUS, username + + " exists. ", null); + return; + } + // create a user + userManager.addUser(username, password); + } + catch (SecurityException e) + { + setResponseHeader(resp); + printResult(printWriter, SERVER_ERROR_STATUS, + "Could not create a user: " + e.getMessage(), null); + log.error("Could not create a user: " + e.getMessage(), e); + return; + } + + try + { + // set roles + if (defaultRolenames != null) + { + for (int i = 0; i < defaultRolenames.length; i++) + { + roleManager.addRoleToUser(username, defaultRolenames[i]); + } + } + + // set groups + if (defaultGroupnames != null) + { + for (int i = 0; i < defaultGroupnames.length; i++) + { + groupManager.addUserToGroup(username, defaultGroupnames[i]); + } + } + + // profiler + User user = userManager.getUser(username); + Principal userPrincipal = getPrincipal(user.getSubject(), + UserPrincipal.class); + if (userPrincipal != null) + { + profiler.setRuleForPrincipal(userPrincipal, profiler + .getRule(defaultPageRule), "page"); + } + + setResponseHeader(resp); + printResult(printWriter, SUCCESS_STATUS, null, null); + return; + } + catch (SecurityException e) + { + setResponseHeader(resp); + printResult(printWriter, SERVER_ERROR_STATUS, + "Could not create a user: " + e.getMessage(), null); + log.error("Could not create a user: " + e.getMessage(), e); + try + { + userManager.removeUser(username); + } + catch (SecurityException e1) + { + log.error("Could not remove a user: " + e1.getMessage(), e1); + } + return; + } + + } + + private Principal getPrincipal(Subject subject, Class cls) + { + Principal principal = null; + Iterator principals = subject.getPrincipals().iterator(); + while (principals.hasNext()) + { + Principal p = (Principal) principals.next(); + if (cls.isInstance(p)) + { + principal = p; + break; + } + } + return principal; + } + + protected void updateUser(HttpServletRequest req, HttpServletResponse resp) + throws IOException + { + PrintWriter printWriter = resp.getWriter(); + String username = req.getParameter(USERNAME_PARAM); + String password = req.getParameter(PASSWORD_PARAM); + + if (username == null || password == null) + { + setResponseHeader(resp); + printResult(printWriter, INVALID_PARAMETER_STATUS, + "Invalid parameter(s): username=" + username + + ", password=" + password, null); + return; + } + + if (!checkExcludedUsername(username)) + { + setResponseHeader(resp); + printResult(printWriter, EXCLUDED_USER_STATUS, username + + " is an excluded username. ", null); + return; + } + + try + { + if (!userManager.userExists(username)) + { + setResponseHeader(resp); + printResult(printWriter, USER_NOT_FOUND_STATUS, username + + " is not found. ", null); + return; + } + // update password + userManager.setPassword(username, null, password); + setResponseHeader(resp); + printResult(printWriter, SUCCESS_STATUS, null, null); + return; + } + catch (SecurityException e) + { + setResponseHeader(resp); + printResult(printWriter, SERVER_ERROR_STATUS, + "Could not update a user: " + e.getMessage(), null); + log.error("Could not update a user: " + e.getMessage(), e); + return; + } + + } + + protected void deleteUser(HttpServletRequest req, HttpServletResponse resp) + throws IOException + { + PrintWriter printWriter = resp.getWriter(); + String username = req.getParameter(USERNAME_PARAM); + + if (username == null) + { + setResponseHeader(resp); + printResult(printWriter, INVALID_PARAMETER_STATUS, + "Invalid parameter(s): username=" + username, null); + return; + } + + if (!checkExcludedUsername(username)) + { + setResponseHeader(resp); + printResult(printWriter, EXCLUDED_USER_STATUS, username + + " is an excluded username. ", null); + return; + } + + try + { + if (!userManager.userExists(username)) + { + setResponseHeader(resp); + printResult(printWriter, USER_NOT_FOUND_STATUS, username + + " is not found. ", null); + return; + } + // remove a user + userManager.removeUser(username); + setResponseHeader(resp); + printResult(printWriter, SUCCESS_STATUS, null, null); + return; + + } + catch (SecurityException e) + { + setResponseHeader(resp); + printResult(printWriter, SERVER_ERROR_STATUS, + "Could not remove a user: " + e.getMessage(), null); + log.error("Could not remove a user: " + e.getMessage(), e); + return; + } + } + + protected void setResponseHeader(HttpServletResponse resp) + { + resp.setStatus(HttpServletResponse.SC_OK); + resp.setContentType("text/xml; charset=UTF-8"); + } + + protected void printResult(PrintWriter printWriter, String status, + String message, Map results) + { + StringBuilder buf = new StringBuilder(); + buf.append(""); + buf.append(""); + buf.append(""); + buf.append(status); + buf.append(""); + if (message != null) + { + buf.append(""); + buf.append(message); + buf.append(""); + } + if (results != null) + { + buf.append(""); + for (Iterator i = results.entrySet().iterator(); i.hasNext();) + { + Map.Entry entry = (Map.Entry) i.next(); + buf.append(""); + buf.append(entry.getKey()); + buf.append(""); + buf.append(""); + buf.append(entry.getValue()); + buf.append(""); + } + buf.append(""); + } + buf.append(""); + printWriter.print(buf.toString()); + printWriter.flush(); + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/JetspeedPortalContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/JetspeedPortalContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/JetspeedPortalContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,17 +31,21 @@ /** * Implementation of Portal Context associated with running thread of the engine - * + * * @author David Sean Taylor * @version $Id: JetspeedPortalContext.java 553375 2007-07-05 05:37:00Z taylor $ */ public class JetspeedPortalContext implements PortalContext { + private static final String SUPPORTED_WINDOWSTATE_ATTR = "supported.windowstate"; + private static final String SUPPORTED_PORTLETMODE_ATTR = "supported.portletmode"; + private static final String PORTAL_VERSION_ATTR = "portal.version"; + private static final String PORTAL_NAME_ATTR = "portal.name"; - + /** * The engine associated with this context. */ @@ -61,31 +65,36 @@ * The base from which the Jetspped application will operate. */ private String applicationRoot; - + private final String portalInfo; - public JetspeedPortalContext(Engine engine, PortalConfiguration configuration, String applicationRoot) + public JetspeedPortalContext(Engine engine, + PortalConfiguration configuration, String applicationRoot) { this.engine = engine; this.configuration = configuration; this.applicationRoot = applicationRoot; - - portalInfo = configuration.getString(PORTAL_NAME_ATTR) + "/" + configuration.getString(PORTAL_VERSION_ATTR); - + + portalInfo = configuration.getString(PORTAL_NAME_ATTR) + "/" + + configuration.getString(PORTAL_VERSION_ATTR); + // Inititalize supported portlet modes and window states - String[] supportedModes = configuration.getStringArray(SUPPORTED_PORTLETMODE_ATTR); - String[] supportedStates = configuration.getStringArray(SUPPORTED_WINDOWSTATE_ATTR); + String[] supportedModes = configuration + .getStringArray(SUPPORTED_PORTLETMODE_ATTR); + String[] supportedStates = configuration + .getStringArray(SUPPORTED_WINDOWSTATE_ATTR); new JetspeedActions(supportedModes, supportedStates); } // ------------------------------------------------------------------------ - // A C C E S S O R S + // A C C E S S O R S // ------------------------------------------------------------------------ /** * Returns the configuration properties for this Jetspeed engine context. - * - * @return a Configuration containing the configuration properties for this Jetspeed context. + * + * @return a Configuration containing the configuration + * properties for this Jetspeed context. */ public PortalConfiguration getConfiguration() { @@ -104,8 +113,9 @@ /** * Set the configuration properties for this Jetspeed engine context. - * - * @param configuration - the configuration properties + * + * @param configuration - + * the configuration properties */ public void setConfiguration(PortalConfiguration configuration) { @@ -114,8 +124,9 @@ /** * Returns the application root for this Jetspeed engine context. - * - * @return a String containing the application root path for this Jetspeed context. + * + * @return a String containing the application root path for + * this Jetspeed context. */ public String getApplicationRoot() { @@ -124,8 +135,9 @@ /** * Sets the application root path for this Jetspeed engine context. - * - * @param applicationRoot - the applicationRoot path on the file system. + * + * @param applicationRoot - + * the applicationRoot path on the file system. */ public void setApplicationRoot(String applicationRoot) { @@ -134,7 +146,7 @@ /** * Returns the engine associated with this context. - * + * * @return an Engine associated with this context */ public Engine getEngine() @@ -143,66 +155,75 @@ } /** - * Returns the engine attribute with the given name, or null if there is no attribute by that name. - * - * @return an Object containing the value of the attribute, or null if no attribute exists matching the given name + * Returns the engine attribute with the given name, or null if there is no + * attribute by that name. + * + * @return an Object containing the value of the attribute, + * or null if no attribute exists matching the given name */ public Object getAttribute(String name) { return attributes.get(name); } - /** * Binds an object to a given attribute name in this servlet context. - * - * @param name - a String specifying the name of the attribute - * @param value - an Object representing the attribute to be bound + * + * @param name - + * a String specifying the name of the attribute + * @param value - + * an Object representing the attribute to be + * bound */ public void setAttribute(String name, Object value) { attributes.put(name, value); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.portlet.PortalContext#getProperty(java.lang.String) */ public String getProperty(String name) { - if (name == null) - { - throw new IllegalArgumentException("Property name == null"); - } - return(String) configuration.getString(name); + if (name == null) { throw new IllegalArgumentException( + "Property name == null"); } + return (String) configuration.getString(name); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.portlet.PortalContext#getPropertyNames() */ public Enumeration getPropertyNames() { return new Enumerator(configuration.getKeys()); } - + private Collection getSupportedModes() { PortletRequestContext ctx = PortletRequestContext.getContext(); - if ( ctx != null ) + if (ctx != null) { - PortletApplication pa = ((PortletApplication)ctx.getPortletDefinition().getPortletApplicationDefinition()); + PortletApplication pa = ((PortletApplication) ctx + .getPortletDefinition().getPortletApplicationDefinition()); return pa.getSupportedPortletModes(); } return JetspeedActions.getStandardPortletModes(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.portlet.PortalContext#getSupportedPortletModes() */ public Enumeration getSupportedPortletModes() { return new Enumerator(getSupportedModes()); } - + public boolean isPortletModeAllowed(PortletMode mode) { return getSupportedModes().contains(mode); @@ -211,28 +232,33 @@ private Collection getSupportedStates() { PortletRequestContext ctx = PortletRequestContext.getContext(); - if ( ctx != null ) + if (ctx != null) { - PortletApplication pa = ((PortletApplication)ctx.getPortletDefinition().getPortletApplicationDefinition()); + PortletApplication pa = ((PortletApplication) ctx + .getPortletDefinition().getPortletApplicationDefinition()); return pa.getSupportedWindowStates(); } return JetspeedActions.getStandardWindowStates(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortalContext#getSupportedWindowStates() */ public Enumeration getSupportedWindowStates() { return new Enumerator(getSupportedStates()); } - + public boolean isWindowStateAllowed(WindowState state) { return getSupportedStates().contains(state); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.portlet.PortalContext#getPortalInfo() */ public String getPortalInfo() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/PortalContextFactoryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/PortalContextFactoryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/PortalContextFactoryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed; import java.util.Map; @@ -25,6 +25,7 @@ public class PortalContextFactoryImpl implements PortalContextFactory { + public PortalContext getPortalContext() { return Jetspeed.getContext(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/AdminUtil.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/AdminUtil.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/AdminUtil.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,75 +32,75 @@ */ public class AdminUtil { + /** the list of characters from which a password can be generatored. */ - protected static final char[] PASS_CHARS = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', - '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}; - // removed these for aesthetic purposes - //'!', '&', '-', '_', '=', - // '*','@', '#', '$', '%', '^', - //'+', + protected static final char[] PASS_CHARS = + {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', + 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', + 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', + '3', '4', '5', '6', '7', '8', '9', '0'}; + // removed these for aesthetic purposes + // '!', '&', '-', '_', '=', + // '*','@', '#', '$', '%', '^', + // '+', + public String generatePassword() { RandomStrg rs = new RandomStrg(); - - //TODO put in a more secure random number provider - //rs.setAlgorithm(); -- ideally call this for super security. need rnd provider - + + // TODO put in a more secure random number provider + // rs.setAlgorithm(); -- ideally call this for super security. need rnd + // provider + try { rs.generateRandomObject(); - } catch (JspException e) + } + catch (JspException e) { - // this would only get thrown if we tried a secure random and the provider + // this would only get thrown if we tried a secure random and the + // provider // was not available. e.printStackTrace(); } rs.setLength(new Integer(12)); - rs.setSingle(PASS_CHARS,PASS_CHARS.length); + rs.setSingle(PASS_CHARS, PASS_CHARS.length); ArrayList upper = new ArrayList(); ArrayList lower = new ArrayList(); - //upper.add(new Character('A')); - //lower.add(new Character('B')); - rs.setRanges(upper,lower); + // upper.add(new Character('A')); + // lower.add(new Character('B')); + rs.setRanges(upper, lower); String retval = rs.getRandom(); - - return retval; + + return retval; } - + protected String concatenatePaths(String base, String path) { String result = ""; if (base == null) { - if (path == null) - { - return result; - } + if (path == null) { return result; } return path; } else { - if (path == null) - { - return base; - } + if (path == null) { return base; } } - if (base.endsWith(Folder.PATH_SEPARATOR)) + if (base.endsWith(Folder.PATH_SEPARATOR)) { if (path.startsWith(Folder.PATH_SEPARATOR)) { result = base.concat(path.substring(1)); return result; } - + } else { - if (!path.startsWith(Folder.PATH_SEPARATOR)) + if (!path.startsWith(Folder.PATH_SEPARATOR)) { result = base.concat(Folder.PATH_SEPARATOR).concat(path); return result; @@ -108,5 +108,5 @@ } return base.concat(path); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/PortalAdministrationImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/PortalAdministrationImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/PortalAdministrationImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -61,12 +61,8 @@ import org.springframework.mail.javamail.JavaMailSender; /** - * PortalAdministrationImpl - * Implements aggregate portal administration functions: - * - Emails - * - Registration - * - Password Generation - * - + * PortalAdministrationImpl Implements aggregate portal administration + * functions: - Emails - Registration - Password Generation - * * @author David Sean Taylor * @author Chris Schaefer @@ -75,39 +71,51 @@ public class PortalAdministrationImpl implements PortalAdministration { - private final static Log log = LogFactory.getLog(PortalAdministrationImpl.class); - + + private final static Log log = LogFactory + .getLog(PortalAdministrationImpl.class); + /** administration services */ protected Configuration config; + protected UserManager userManager; + protected RoleManager roleManager; + protected GroupManager groupManager; + protected PageManager pageManager; - private PreferencesProvider preferences; + + private PreferencesProvider preferences; + protected Profiler profiler; + protected JavaMailSender mailSender; + protected VelocityEngine velocityEngine; + protected AdminUtil adminUtil; - + /** list of default roles for a registered user */ protected List defaultRoles; + /** list of default groups for a registered user */ protected List defaultGroups; + /** map of default profiling rules for a registered user */ protected Map defaultRules; + /** name of PSML Folder Template to clone from when registering new user */ protected String folderTemplate; + /** default administrative user */ protected String adminUser; - - public PortalAdministrationImpl( UserManager userManager, - RoleManager roleManager, - GroupManager groupManager, - PageManager pageManager, - PreferencesProvider preferences, - Profiler profiler, - JavaMailSender mailSender, - VelocityEngine velocityEngine) + + public PortalAdministrationImpl(UserManager userManager, + RoleManager roleManager, GroupManager groupManager, + PageManager pageManager, PreferencesProvider preferences, + Profiler profiler, JavaMailSender mailSender, + VelocityEngine velocityEngine) { this.userManager = userManager; this.roleManager = roleManager; @@ -122,68 +130,67 @@ public void start() { - this.config = (Configuration) Jetspeed.getComponentManager().getComponent("portal_configuration"); - - this.defaultRoles = - config.getList(PortalConfigurationConstants.REGISTRATION_ROLES_DEFAULT); - this.defaultGroups = - config.getList(PortalConfigurationConstants.REGISTRATION_GROUPS_DEFAULT); - - Object[] profileRuleNames = config.getList(PortalConfigurationConstants.PROFILER_RULE_NAMES_DEFAULT).toArray(); - Object[] profileRuleValues = config.getList(PortalConfigurationConstants.PROFILER_RULE_VALUES_DEFAULT).toArray(); + this.config = (Configuration) Jetspeed.getComponentManager() + .getComponent("portal_configuration"); + + this.defaultRoles = config + .getList(PortalConfigurationConstants.REGISTRATION_ROLES_DEFAULT); + this.defaultGroups = config + .getList(PortalConfigurationConstants.REGISTRATION_GROUPS_DEFAULT); + + Object[] profileRuleNames = config.getList( + PortalConfigurationConstants.PROFILER_RULE_NAMES_DEFAULT) + .toArray(); + Object[] profileRuleValues = config.getList( + PortalConfigurationConstants.PROFILER_RULE_VALUES_DEFAULT) + .toArray(); defaultRules = new HashMap(); if (profileRuleNames != null && profileRuleValues != null) { - for (int ix = 0; ix < ((profileRuleNames.length < profileRuleValues.length) ? profileRuleNames.length : profileRuleValues.length); ix++) + for (int ix = 0; ix < ((profileRuleNames.length < profileRuleValues.length) ? profileRuleNames.length + : profileRuleValues.length); ix++) { defaultRules.put(profileRuleNames[ix], profileRuleValues[ix]); } } - this.folderTemplate = - config.getString(PortalConfigurationConstants.PSML_TEMPLATE_FOLDER); - this.adminUser = config.getString(PortalConfigurationConstants.USERS_DEFAULT_ADMIN); - + this.folderTemplate = config + .getString(PortalConfigurationConstants.PSML_TEMPLATE_FOLDER); + this.adminUser = config + .getString(PortalConfigurationConstants.USERS_DEFAULT_ADMIN); + } - + public void registerUser(String userName, String password) - throws RegistrationException + throws RegistrationException { - registerUser(userName, password, (List)null, null, null, null, null); + registerUser(userName, password, (List) null, null, null, null, null); } - public void registerUser( - String userName, - String password, - List roles, - List groups, - Map userInfo, - Map rules, - String folderTemplate) - throws RegistrationException + public void registerUser(String userName, String password, List roles, + List groups, Map userInfo, Map rules, String folderTemplate) + throws RegistrationException { - registerUser(userName, password, roles, groups, userInfo, rules, folderTemplate, null); + registerUser(userName, password, roles, groups, userInfo, rules, + folderTemplate, null); } - - /* (non-Javadoc) - * @see org.apache.jetspeed.administration.PortalAdministration#registerUser(java.lang.String, java.lang.String, java.util.Map, java.awt.List, java.awt.List, java.lang.String) - */ - public void registerUser( - String userName, - String password, - List roles, - List groups, - Map userInfo, - Map rules, - String folderTemplate, - String subsite) - throws RegistrationException + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.administration.PortalAdministration#registerUser(java.lang.String, + * java.lang.String, java.util.Map, java.awt.List, java.awt.List, + * java.lang.String) + */ + public void registerUser(String userName, String password, List roles, + List groups, Map userInfo, Map rules, String folderTemplate, + String subsite) throws RegistrationException { - try + try { // create the user userManager.addUser(userName, password); User user = userManager.getUser(userName); - + // assign roles to user if (roles == null || roles.isEmpty()) { @@ -194,12 +201,12 @@ Iterator roleList = roles.iterator(); while (roleList.hasNext()) { - String role = (String)roleList.next(); + String role = (String) roleList.next(); if (role.trim().length() > 0) roleManager.addRoleToUser(userName, role); } } - + // assign groups to user if (groups == null || groups.isEmpty()) { @@ -210,25 +217,26 @@ Iterator groupsList = groups.iterator(); while (groupsList.hasNext()) { - String group = (String)groupsList.next(); + String group = (String) groupsList.next(); if (group.trim().length() > 0) { groupManager.addUserToGroup(userName, group); } } } - + // assign user attributes to user if (userInfo != null) { Iterator info = userInfo.entrySet().iterator(); while (info.hasNext()) - { - Map.Entry entry = (Map.Entry)info.next(); - user.getUserAttributes().put((String)entry.getKey(), (String)entry.getValue()); + { + Map.Entry entry = (Map.Entry) info.next(); + user.getUserAttributes().put((String) entry.getKey(), + (String) entry.getValue()); } } - + // assign profiling rules to user if (rules == null || rules.isEmpty()) { @@ -238,76 +246,95 @@ { Iterator ruleEntries = rules.entrySet().iterator(); while (ruleEntries.hasNext()) - { - Map.Entry entry = (Map.Entry)ruleEntries.next(); - ProfilingRule rule = profiler.getRule((String)entry.getValue()); + { + Map.Entry entry = (Map.Entry) ruleEntries.next(); + ProfilingRule rule = profiler.getRule((String) entry + .getValue()); if (rule != null) { - Principal principal = SecurityHelper.getBestPrincipal(user.getSubject(), UserPrincipal.class); - profiler.setRuleForPrincipal(principal, rule, (String)entry.getKey()); + Principal principal = SecurityHelper.getBestPrincipal( + user.getSubject(), UserPrincipal.class); + profiler.setRuleForPrincipal(principal, rule, + (String) entry.getKey()); } } } - + if (folderTemplate == null) { - folderTemplate = this.folderTemplate; + folderTemplate = this.folderTemplate; } - + if (subsite == null) { subsite = Folder.USER_FOLDER + userName; } else { - subsite = subsite + Folder.USER_FOLDER + userName; - } - - - // This next chunk of code is the fancy way to force the creation of the user + subsite = subsite + Folder.USER_FOLDER + userName; + } + + // This next chunk of code is the fancy way to force the creation of + // the user // template pages to be created with subject equal to the new user - // otherwise it would be created as guest, and guest does not have enough privs. + // otherwise it would be created as guest, and guest does not have + // enough privs. final String innerFolderTemplate = folderTemplate; final String innerSubsite = subsite; final PageManager innerPageManager = pageManager; final String innerUserName = userName; final User innerUser = user; User powerUser = userManager.getUser(this.adminUser); - JetspeedException pe = (JetspeedException) JSSubject.doAsPrivileged(powerUser.getSubject(), new PrivilegedAction() - { - public Object run() - { - try - { - if (innerSubsite != null) - { - Preferences attributes = innerUser.getUserAttributes(); - attributes.put(User.USER_INFO_SUBSITE, innerSubsite); - } - // create user's home folder - // deep copy from the default folder template tree, creating a deep-copy of the template - // in the new user's folder tree - Folder source = innerPageManager.getFolder(innerFolderTemplate); - - - innerPageManager.deepCopyFolder(source, innerSubsite, innerUserName); - Folder newFolder = pageManager.getFolder(innerSubsite); - newFolder.setTitle("Home Folder"); - newFolder.setShortTitle("Home"); - - return null; - } - catch (FolderNotFoundException e1) { - return e1; - } catch (InvalidFolderException e1){ - return e1; - } catch (NodeException e1){ - return e1; - } - } - }, null); - - if(pe != null) + JetspeedException pe = (JetspeedException) JSSubject + .doAsPrivileged(powerUser.getSubject(), + new PrivilegedAction() + { + + public Object run() + { + try + { + if (innerSubsite != null) + { + Preferences attributes = innerUser + .getUserAttributes(); + attributes.put( + User.USER_INFO_SUBSITE, + innerSubsite); + } + // create user's home folder + // deep copy from the default folder + // template tree, creating a deep-copy + // of the template + // in the new user's folder tree + Folder source = innerPageManager + .getFolder(innerFolderTemplate); + + innerPageManager.deepCopyFolder(source, + innerSubsite, innerUserName); + Folder newFolder = pageManager + .getFolder(innerSubsite); + newFolder.setTitle("Home Folder"); + newFolder.setShortTitle("Home"); + + return null; + } + catch (FolderNotFoundException e1) + { + return e1; + } + catch (InvalidFolderException e1) + { + return e1; + } + catch (NodeException e1) + { + return e1; + } + } + }, null); + + if (pe != null) { // rollback user creation and cascade roles, groups, etc try @@ -319,22 +346,27 @@ } catch (Exception e) { - log.error("Registration Error: Failed to rollback user " + userName); + log.error("Registration Error: Failed to rollback user " + + userName); } - log.error("Registration Error: Failed to create user folders for " + userName + ", " + pe.toString()); + log + .error("Registration Error: Failed to create user folders for " + + userName + ", " + pe.toString()); throw pe; } - + } - catch (Exception e) + catch (Exception e) { - log.error("Registration Error: Failed to create registered user " + userName + ", " + e.toString()); - throw new RegistrationException(e); - } + log.error("Registration Error: Failed to create registered user " + + userName + ", " + e.toString()); + throw new RegistrationException(e); + } } - - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.administration.PortalAdministration#generatePassword() */ public String generatePassword() @@ -342,25 +374,26 @@ return adminUtil.generatePassword(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.administration.PortalAdministration#sendPassword(java.lang.String) */ - public void sendEmail(PortletConfig portletConfig, - String emailAddress, - String localizedSubject, - String localizedTemplatePath, - Map userAttributes) - throws AdministrationEmailException - { - - String from = config.getString(PortalConfigurationConstants.EMAIL_SENDER); + public void sendEmail(PortletConfig portletConfig, String emailAddress, + String localizedSubject, String localizedTemplatePath, + Map userAttributes) throws AdministrationEmailException + { + + String from = config + .getString(PortalConfigurationConstants.EMAIL_SENDER); String subject = localizedSubject; String to = emailAddress; - String text = mergeEmailTemplate(portletConfig, userAttributes, "map", localizedTemplatePath); + String text = mergeEmailTemplate(portletConfig, userAttributes, "map", + localizedTemplatePath); sendEmail(from, subject, to, text); - + } - + /** * @param from * @param subject @@ -368,15 +401,16 @@ * @param text * @throws AdministrationEmailException */ - public void sendEmail(String from, String subject, String to, String text) throws AdministrationEmailException + public void sendEmail(String from, String subject, String to, String text) + throws AdministrationEmailException { SimpleMailMessage msg = new SimpleMailMessage(); - if(from == null) + if (from == null) { from = "jetspeed-admin ¡÷ apache.org"; } msg.setFrom(from); - if(subject == null) + if (subject == null) { subject = "message from jetspeed"; } @@ -386,61 +420,60 @@ try { mailSender.send(msg); - } + } catch (MailException ex) { throw new AdministrationEmailException( - "Failed to send forgotten password email to user with email address because "+ex.getMessage() - ); //+ user.getEmail()); + "Failed to send forgotten password email to user with email address because " + + ex.getMessage()); // + user.getEmail()); } } - - public String mergeEmailTemplate(PortletConfig portletConfig, Map attributes, String attributesName, String template) - throws AdministrationEmailException + + public String mergeEmailTemplate(PortletConfig portletConfig, + Map attributes, String attributesName, String template) + throws AdministrationEmailException { VelocityContext context = new VelocityContext(); context.put(attributesName, attributes); StringWriter writer = new StringWriter(); - + try { - String realTemplatePath = portletConfig.getPortletContext().getRealPath(template); + String realTemplatePath = portletConfig.getPortletContext() + .getRealPath(template); FileReader templateReader = new FileReader(realTemplatePath); - velocityEngine.evaluate(context, writer, "UserEmailProcessor", templateReader); - } catch (Exception e) + velocityEngine.evaluate(context, writer, "UserEmailProcessor", + templateReader); + } + catch (Exception e) { throw new AdministrationEmailException( "Failed to generate email text for email template " + template, e); } - + String buffer = writer.getBuffer().toString(); - + return buffer; } - + private static final String USER_NOT_FOUND_FROM_EMAIL = "User not found for Email address: "; - + public User lookupUserFromEmail(String email) - throws AdministrationEmailException + throws AdministrationEmailException { - Collection result = preferences.lookupPreference("userinfo", "user.business-info.online.email", email); - if (result.size() == 0) - { - throw new AdministrationEmailException(USER_NOT_FOUND_FROM_EMAIL + email); - } + Collection result = preferences.lookupPreference("userinfo", + "user.business-info.online.email", email); + if (result.size() == 0) { throw new AdministrationEmailException( + USER_NOT_FOUND_FROM_EMAIL + email); } Iterator nodes = result.iterator(); - Node node = (Node)nodes.next(); + Node node = (Node) nodes.next(); String nodePath = node.getFullPath(); - if (nodePath == null) - { - throw new AdministrationEmailException(USER_NOT_FOUND_FROM_EMAIL + email); - } + if (nodePath == null) { throw new AdministrationEmailException( + USER_NOT_FOUND_FROM_EMAIL + email); } String[] paths = nodePath.split("/"); - if (paths == null || paths.length != 4) - { - throw new AdministrationEmailException(USER_NOT_FOUND_FROM_EMAIL + email); - } + if (paths == null || paths.length != 4) { throw new AdministrationEmailException( + USER_NOT_FOUND_FROM_EMAIL + email); } String userName = paths[2]; try { @@ -448,60 +481,68 @@ } catch (Exception e) { - throw new AdministrationEmailException(USER_NOT_FOUND_FROM_EMAIL + email); + throw new AdministrationEmailException(USER_NOT_FOUND_FROM_EMAIL + + email); } } /** * Helper for admin portlets to generate portal urls */ - public String getPortalURL(PortletRequest request, PortletResponse response, String path) + public String getPortalURL(PortletRequest request, + PortletResponse response, String path) { // get internal request context - RequestContext context = (RequestContext) - request.getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); + RequestContext context = (RequestContext) request + .getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); String baseUrl = context.getPortalURL().getBaseURL(); - String jetspeedPath = adminUtil.concatenatePaths(baseUrl, context.getPortalURL().getBasePath()); - if (path == null) - return jetspeedPath; - return adminUtil.concatenatePaths(jetspeedPath, response.encodeURL(path)); + String jetspeedPath = adminUtil.concatenatePaths(baseUrl, context + .getPortalURL().getBasePath()); + if (path == null) return jetspeedPath; + return adminUtil.concatenatePaths(jetspeedPath, response + .encodeURL(path)); } - - + Map forgottenPasswordData = new HashMap(); - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.administration.PortalAdministration#getNewLoginInfo(java.lang.String) */ public Map getNewLoginInfo(String guid) { - synchronized(forgottenPasswordData) { + synchronized (forgottenPasswordData) + { return (Map) forgottenPasswordData.get(guid); } } - /* (non-Javadoc) - * @see org.apache.jetspeed.administration.PortalAdministration#setNewLoginInfo(java.lang.String, org.apache.jetspeed.administration.PortalAdministration.ResetPasswordInfo) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.administration.PortalAdministration#setNewLoginInfo(java.lang.String, + * org.apache.jetspeed.administration.PortalAdministration.ResetPasswordInfo) */ public void putNewLoginInfo(String guid, Map info) { - synchronized(forgottenPasswordData) { - forgottenPasswordData.put(guid,info); + synchronized (forgottenPasswordData) + { + forgottenPasswordData.put(guid, info); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.administration.PortalAdministration#removeNewLoginInfo(java.lang.String) */ public void removeNewLoginInfo(String guid) { - synchronized(forgottenPasswordData) { + synchronized (forgottenPasswordData) + { forgottenPasswordData.remove(guid); } } - - - - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/PortalAuthenticationConfigurationImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/PortalAuthenticationConfigurationImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/PortalAuthenticationConfigurationImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,29 +16,39 @@ */ package org.apache.jetspeed.administration; -import org.apache.jetspeed.administration.PortalAuthenticationConfiguration; - /** * PasswordCredentialValve - * + * * @author David Sean Taylor * @version $Id: $ */ -public class PortalAuthenticationConfigurationImpl implements PortalAuthenticationConfiguration +public class PortalAuthenticationConfigurationImpl implements + PortalAuthenticationConfiguration { + protected boolean createNewSessionOnLogin = false; + protected int maxSessionHardLimit = 0; + protected long msMaxSessionHardLimit = 1; + protected String timeoutRedirectLocation = ""; - + /** * Portal Authentication Configuration stored and accessed from this bean * - * @param createNewSessionOnLogin Should a new session be created upon logging on to the system - * @param maxSessionHardLimit The maximum session hard limit, ignores user activity, set to zero to turn off this feature - * @param timeoutRedirectLocation Path to redirection upon logging out user on session limit experiation, only used with maxSessionHardLimit + * @param createNewSessionOnLogin + * Should a new session be created upon logging on to the system + * @param maxSessionHardLimit + * The maximum session hard limit, ignores user activity, set to + * zero to turn off this feature + * @param timeoutRedirectLocation + * Path to redirection upon logging out user on session limit + * experiation, only used with maxSessionHardLimit */ - public PortalAuthenticationConfigurationImpl(boolean createNewSessionOnLogin, int maxSessionHardLimit, String timeoutRedirectLocation) + public PortalAuthenticationConfigurationImpl( + boolean createNewSessionOnLogin, int maxSessionHardLimit, + String timeoutRedirectLocation) { this.createNewSessionOnLogin = createNewSessionOnLogin; this.maxSessionHardLimit = maxSessionHardLimit; @@ -50,51 +60,42 @@ { return this.maxSessionHardLimit > 0; } - + public int getMaxSessionHardLimit() { return maxSessionHardLimit; } - public void setMaxSessionHardLimit(int maxSessionHardLimit) { this.maxSessionHardLimit = maxSessionHardLimit; } - public long getMsMaxSessionHardLimit() { return msMaxSessionHardLimit; } - public void setMsMaxSessionHardLimit(long msMaxSessionHardLimit) { this.msMaxSessionHardLimit = msMaxSessionHardLimit; } - public String getTimeoutRedirectLocation() { return timeoutRedirectLocation; } - public void setTimeoutRedirectLocation(String timeoutRedirectLocation) { this.timeoutRedirectLocation = timeoutRedirectLocation; } - - public boolean isCreateNewSessionOnLogin() { return createNewSessionOnLogin; } - - public void setCreateNewSessionOnLogin(boolean createNewSessionOnLogin) { this.createNewSessionOnLogin = createNewSessionOnLogin; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/PortalConfigurationImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/PortalConfigurationImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/administration/PortalConfigurationImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,27 +21,27 @@ import org.apache.commons.configuration.Configuration; - /** * Portal Configuration * - * Retrieve basic data types from the jetspeed.properties configuration - * This is a subset of Commons Configuration functionality - * Not the best solution wrappering commons configuration, but it does continue - * with the requirements of interface-driven development and zero dependencies in API - * + * Retrieve basic data types from the jetspeed.properties configuration This is + * a subset of Commons Configuration functionality Not the best solution + * wrappering commons configuration, but it does continue with the requirements + * of interface-driven development and zero dependencies in API + * * @author David Sean Taylor * @version $Id: $ */ public class PortalConfigurationImpl implements PortalConfiguration { + Configuration configuration; - + public PortalConfigurationImpl(Configuration configuration) { this.configuration = configuration; } - + public boolean getBoolean(String key, boolean defaultValue) { return configuration.getBoolean(key, defaultValue); @@ -74,12 +74,12 @@ public int getInt(String key, int defaultValue) { - return configuration.getInt(key, defaultValue); + return configuration.getInt(key, defaultValue); } public int getInt(String key) { - return configuration.getInt(key); + return configuration.getInt(key); } public List getList(String key) @@ -89,34 +89,34 @@ public long getLong(String key, long defaultValue) { - return configuration.getLong(key, defaultValue); + return configuration.getLong(key, defaultValue); } public long getLong(String key) { - return configuration.getLong(key); + return configuration.getLong(key); } public String getString(String key, String defaultValue) { - return configuration.getString(key, defaultValue); + return configuration.getString(key, defaultValue); } public String getString(String key) { - return configuration.getString(key); + return configuration.getString(key); } public String[] getStringArray(String key) { - return configuration.getStringArray(key); + return configuration.getStringArray(key); } - + public Iterator getKeys() { return configuration.getKeys(); } - + public void setString(String key, String value) { configuration.setProperty(key, value); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/AggregatorValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/AggregatorValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/AggregatorValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,22 +24,22 @@ /** * Invokes the aggregator service in the request pipeline - * + * * @author David Sean Taylor * @version $Id: AggregatorValve.java 517124 2007-03-12 08:10:25Z ate $ */ -public class AggregatorValve - extends AbstractValve +public class AggregatorValve extends AbstractValve { + private Aggregator aggregator; - + public AggregatorValve(Aggregator aggregator) { this.aggregator = aggregator; } - - public void invoke( RequestContext request, ValveContext context ) - throws PipelineException + + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { try { @@ -50,7 +50,7 @@ throw new PipelineException(e.toString(), e); } // Pass control to the next Valve in the Pipeline - context.invokeNext( request ); + context.invokeNext(request); } public String toString() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/FileServerValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/FileServerValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/FileServerValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,52 +24,60 @@ /** * FileServerValve - * + * * @author David Sean Taylor * @version $Id: $ */ public class FileServerValve extends AbstractValve { + private String portletName; + private String portletEntity; - + public FileServerValve(String portletName, String portletEntity) { this.portletName = portletName; this.portletEntity = portletEntity; } - - public void invoke( RequestContext request, ValveContext context ) - throws PipelineException + + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { try { - String entity = request.getRequestParameter(PortalReservedParameters.PORTLET_ENTITY); + String entity = request + .getRequestParameter(PortalReservedParameters.PORTLET_ENTITY); if (entity == null) { - entity = (String)request.getAttribute(PortalReservedParameters.PORTLET_ENTITY); + entity = (String) request + .getAttribute(PortalReservedParameters.PORTLET_ENTITY); } if (entity == null) { - request.setAttribute(PortalReservedParameters.PORTLET_ENTITY, portletEntity); - } + request.setAttribute(PortalReservedParameters.PORTLET_ENTITY, + portletEntity); + } - String name = request.getRequestParameter(PortalReservedParameters.PORTLET); + String name = request + .getRequestParameter(PortalReservedParameters.PORTLET); if (name == null) { - name = (String)request.getAttribute(PortalReservedParameters.PORTLET); + name = (String) request + .getAttribute(PortalReservedParameters.PORTLET); } if (name == null) { - request.setAttribute(PortalReservedParameters.PORTLET, portletName); - } + request.setAttribute(PortalReservedParameters.PORTLET, + portletName); + } } catch (Exception e) { throw new PipelineException(e); } // Pass control to the next Valve in the Pipeline - context.invokeNext( request ); + context.invokeNext(request); } public String toString() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/HeaderAggregatorValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/HeaderAggregatorValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/HeaderAggregatorValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,22 +24,22 @@ /** * Invokes the header aggregator service in the request pipeline - * + * * @author David Sean Taylor * @version $Id: $ */ -public class HeaderAggregatorValve - extends AbstractValve +public class HeaderAggregatorValve extends AbstractValve { + private Aggregator aggregator; - + public HeaderAggregatorValve(Aggregator aggregator) { this.aggregator = aggregator; } - - public void invoke( RequestContext request, ValveContext context ) - throws PipelineException + + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { try { @@ -50,7 +50,7 @@ throw new PipelineException(e.toString(), e); } // Pass control to the next Valve in the Pipeline - context.invokeNext( request ); + context.invokeNext(request); } public String toString() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/PortletValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/PortletValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/PortletValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,24 +23,25 @@ /** * PortletValve - * + * * @author David Sean Taylor * @version $Id: PortletValve.java 517124 2007-03-12 08:10:25Z ate $ */ public class PortletValve extends AbstractValve { + private PortletAggregator aggregator; - + public PortletValve(PortletAggregator aggregator) { this.aggregator = aggregator; } - - public void invoke( RequestContext request, ValveContext context ) - throws PipelineException + + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { try - { + { aggregator.build(request); } catch (Exception e) @@ -48,7 +49,7 @@ throw new PipelineException(e); } // Pass control to the next Valve in the Pipeline - context.invokeNext( request ); + context.invokeNext(request); } public String toString() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/AsyncPageAggregatorImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/AsyncPageAggregatorImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/AsyncPageAggregatorImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,19 +37,22 @@ import org.apache.pluto.om.window.PortletWindow; /** - * Asynchronous Page Aggregator builds the content required to render a - * page of portlets by rendering the portlets in parallel. Each portlet is - * rendered on its own thread. A work manager handles the thread pooling - * and synchronization of worker threads. + * Asynchronous Page Aggregator builds the content required to render a page of + * portlets by rendering the portlets in parallel. Each portlet is rendered on + * its own thread. A work manager handles the thread pooling and synchronization + * of worker threads. * * @author David Sean Taylor * @author Woonsan Ko * @version $Id: $ */ -public class AsyncPageAggregatorImpl extends BaseAggregatorImpl implements PageAggregator +public class AsyncPageAggregatorImpl extends BaseAggregatorImpl implements + PageAggregator { - protected final static Log log = LogFactory.getLog(AsyncPageAggregatorImpl.class); + protected final static Log log = LogFactory + .getLog(AsyncPageAggregatorImpl.class); + protected PortletRenderer renderer; protected List fallBackContentPathes; @@ -64,18 +67,15 @@ * * @return Unique Portlet Entity ID */ - public void build( RequestContext context ) throws JetspeedException, IOException + public void build(RequestContext context) throws JetspeedException, + IOException { ContentPage page = context.getPage(); - if (null == page) - { - throw new JetspeedException("Failed to find PSML Pin ContentPageAggregator.build"); - } + if (null == page) { throw new JetspeedException( + "Failed to find PSML Pin ContentPageAggregator.build"); } ContentFragment root = page.getRootContentFragment(); - if (root == null) - { - throw new JetspeedException("No root ContentFragment found in ContentPage"); - } + if (root == null) { throw new JetspeedException( + "No root ContentFragment found in ContentPage"); } // handle maximized state NavigationalState nav = context.getPortalURL().getNavigationalState(); PortletWindow window = nav.getMaximizedWindow(); @@ -86,15 +86,17 @@ else { aggregateAndRender(root, context, page, true, null, null, null); - } - //dispatcher.include(root); + } + // dispatcher.include(root); context.getResponse().getWriter().write(root.getRenderedContent()); if (null != window) { - context.getRequest().removeAttribute(PortalReservedParameters.MAXIMIZED_FRAGMENT_ATTRIBUTE); - context.getRequest().removeAttribute(PortalReservedParameters.MAXIMIZED_LAYOUT_ATTRIBUTE); + context.getRequest().removeAttribute( + PortalReservedParameters.MAXIMIZED_FRAGMENT_ATTRIBUTE); + context.getRequest().removeAttribute( + PortalReservedParameters.MAXIMIZED_LAYOUT_ATTRIBUTE); } - releaseBuffers(root, context); + releaseBuffers(root, context); } /** @@ -110,49 +112,61 @@ * @param window * @throws FailedToRenderContentFragmentException */ - protected void renderMaximizedWindow( RequestContext context, ContentPage page, ContentFragment layoutContentFragment, - PortletWindow window ) throws FailedToRenderFragmentException + protected void renderMaximizedWindow(RequestContext context, + ContentPage page, ContentFragment layoutContentFragment, + PortletWindow window) throws FailedToRenderFragmentException { - ContentFragment maxedContentFragment = page.getContentFragmentById(window.getId().toString()); + ContentFragment maxedContentFragment = page + .getContentFragmentById(window.getId().toString()); if (maxedContentFragment != null) { - context.getRequest().setAttribute(PortalReservedParameters.MAXIMIZED_FRAGMENT_ATTRIBUTE, maxedContentFragment); - context.getRequest().setAttribute(PortalReservedParameters.FRAGMENT_ATTRIBUTE, maxedContentFragment); - context.getRequest().setAttribute(PortalReservedParameters.MAXIMIZED_LAYOUT_ATTRIBUTE, page.getRootContentFragment()); + context.getRequest().setAttribute( + PortalReservedParameters.MAXIMIZED_FRAGMENT_ATTRIBUTE, + maxedContentFragment); + context.getRequest().setAttribute( + PortalReservedParameters.FRAGMENT_ATTRIBUTE, + maxedContentFragment); + context.getRequest().setAttribute( + PortalReservedParameters.MAXIMIZED_LAYOUT_ATTRIBUTE, + page.getRootContentFragment()); try { renderer.renderNow(maxedContentFragment, context); - renderer.renderNow(layoutContentFragment, context); + renderer.renderNow(layoutContentFragment, context); } catch (Exception e) { log.error(e.getMessage(), e); - maxedContentFragment.overrideRenderedContent("Sorry, but we were unable access the requested portlet. Send the following message to your portal admin: "+ e.getMessage()); + maxedContentFragment + .overrideRenderedContent("Sorry, but we were unable access the requested portlet. Send the following message to your portal admin: " + + e.getMessage()); } } } - protected void aggregateAndRender(ContentFragment f, RequestContext context, ContentPage page, boolean isRoot, - List sequentialJobs, List parallelJobs, List layoutFragments) + protected void aggregateAndRender(ContentFragment f, + RequestContext context, ContentPage page, boolean isRoot, + List sequentialJobs, List parallelJobs, List layoutFragments) throws FailedToRenderFragmentException { - // First Pass, kick off async render threads for all portlets on page + // First Pass, kick off async render threads for all portlets on page // Store portlet rendering jobs in the list to wait later. // Store layout fragment in the list to render later. - if (sequentialJobs == null) + if (sequentialJobs == null) { sequentialJobs = new ArrayList(); } - if (parallelJobs == null) + if (parallelJobs == null) { parallelJobs = new ArrayList(); - } + } if (layoutFragments == null) { layoutFragments = new ArrayList(); } - if (f.getContentFragments() != null && f.getContentFragments().size() > 0) + if (f.getContentFragments() != null + && f.getContentFragments().size() > 0) { Iterator children = f.getContentFragments().iterator(); while (children.hasNext()) @@ -162,11 +176,14 @@ { if (child.getType().equals(ContentFragment.PORTLET)) { - // create and store the portlet rendering job into the jobs lists. - RenderingJob job = renderer.createRenderingJob(child, context); + // create and store the portlet rendering job into the + // jobs lists. + RenderingJob job = renderer.createRenderingJob(child, + context); - // The returned job can be null for some reason, such as invalid portlet entity. - if (job != null) + // The returned job can be null for some reason, such as + // invalid portlet entity. + if (job != null) { if (job.getTimeout() > 0) parallelJobs.add(job); @@ -176,9 +193,11 @@ } else { - // walk thru layout - // and store the layout rendering job into the layout jobs list. - aggregateAndRender(child, context, page, false, sequentialJobs, parallelJobs, layoutFragments); + // walk thru layout + // and store the layout rendering job into the layout + // jobs list. + aggregateAndRender(child, context, page, false, + sequentialJobs, parallelJobs, layoutFragments); layoutFragments.add(child); } } @@ -186,17 +205,17 @@ } // If the fragment is not root, skip the following. - if (!isRoot) - return; - + if (!isRoot) return; + int parallelJobCount = parallelJobs.size(); int sequentialJobCount = sequentialJobs.size(); - + if (log.isInfoEnabled()) { - log.info("Aggregating " + page.getPath() + ". Parallel: " + parallelJobCount + ", Sequential: " + sequentialJobCount); + log.info("Aggregating " + page.getPath() + ". Parallel: " + + parallelJobCount + ", Sequential: " + sequentialJobCount); } - + CurrentWorkerContext.setParallelRenderingMode(parallelJobCount > 0); // kick off the parallel rendering jobs @@ -217,27 +236,28 @@ // synchronize on completion of all jobs renderer.waitForRenderingJobs(parallelJobs); - + // Now, restore it to non parallel mode for rendering layout portlets. CurrentWorkerContext.setParallelRenderingMode(false); - + // render layout fragments. iter = layoutFragments.iterator(); - while (iter.hasNext()) + while (iter.hasNext()) { ContentFragment child = (ContentFragment) iter.next(); renderer.renderNow(child, context); } - + // Start the actual rendering process - String defaultPortletDecorator = page.getEffectiveDefaultDecorator(ContentFragment.PORTLET); + String defaultPortletDecorator = page + .getEffectiveDefaultDecorator(ContentFragment.PORTLET); if (log.isDebugEnabled()) { - log.debug("Rendering portlet fragment: [[name, " + f.getName() + "], [id, " + f.getId() + "]]"); - } - + log.debug("Rendering portlet fragment: [[name, " + f.getName() + + "], [id, " + f.getId() + "]]"); + } + renderer.renderNow(f, context); } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/BaseAggregatorImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/BaseAggregatorImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/BaseAggregatorImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,17 +23,19 @@ import org.apache.jetspeed.request.RequestContext; /** - * Share common code for all aggregators + * Share common code for all aggregators * * @author David Sean Taylor * @author Woonsan Ko * @version $Id: $ */ -public abstract class BaseAggregatorImpl +public abstract class BaseAggregatorImpl { + protected void releaseBuffers(ContentFragment f, RequestContext context) { - if (f.getContentFragments() != null && f.getContentFragments().size() > 0) + if (f.getContentFragments() != null + && f.getContentFragments().size() > 0) { Iterator children = f.getContentFragments().iterator(); while (children.hasNext()) @@ -46,9 +48,9 @@ } } PortletContent content = f.getPortletContent(); - if (content != null && content.getExpiration() == 0) + if (content != null && content.getExpiration() == 0) { content.release(); } - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/CommonjWorkerMonitorImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/CommonjWorkerMonitorImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/CommonjWorkerMonitorImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,80 +19,88 @@ import java.security.AccessControlContext; import java.security.AccessController; -import java.util.List; import java.util.ArrayList; -import java.util.Iterator; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; import java.util.Map; -import java.util.HashMap; -import java.util.Arrays; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.jetspeed.aggregator.PortletContent; import org.apache.jetspeed.aggregator.RenderingJob; import org.apache.jetspeed.aggregator.Worker; import org.apache.jetspeed.aggregator.WorkerMonitor; -import org.apache.jetspeed.aggregator.PortletContent; - +import org.apache.pluto.om.common.ObjectID; import org.apache.pluto.om.window.PortletWindow; -import org.apache.pluto.om.common.ObjectID; -import commonj.work.WorkManager; import commonj.work.Work; +import commonj.work.WorkEvent; import commonj.work.WorkItem; import commonj.work.WorkListener; -import commonj.work.WorkEvent; +import commonj.work.WorkManager; /** * The CommonjWorkerMonitorImpl is responsible for dispatching jobs to workers - * It wraps CommonJ WorkManager supported by IBM WebSphere and BEA WebLogic sever. - * + * It wraps CommonJ WorkManager supported by IBM WebSphere and BEA WebLogic + * sever. + * * @author Woonsan Ko * @version $Id: CommonjWorkerMonitorImpl.java 568339 2007-08-22 00:14:51Z ate $ */ public class CommonjWorkerMonitorImpl implements WorkerMonitor, WorkListener { - public static final String ACCESS_CONTROL_CONTEXT_WORKER_ATTR = AccessControlContext.class.getName(); - public static final String COMMONJ_WORK_ITEM_ATTR = WorkItem.class.getName(); + public static final String ACCESS_CONTROL_CONTEXT_WORKER_ATTR = AccessControlContext.class + .getName(); + + public static final String COMMONJ_WORK_ITEM_ATTR = WorkItem.class + .getName(); + public static final String WORKER_THREAD_ATTR = Worker.class.getName(); - + /** CommonJ Work Manamger provided by JavaEE container */ protected WorkManager workManager; /** If true, invoke interrupt() on the worker thread when the job is timeout. */ protected boolean interruptOnTimeout = true; - + /** Enable rendering job works monitor thread for timeout checking */ protected boolean jobWorksMonitorEnabled = true; - + /** Rendering job works to be monitored for timeout checking */ - protected Map jobWorksMonitored = Collections.synchronizedMap(new HashMap()); - + protected Map jobWorksMonitored = Collections + .synchronizedMap(new HashMap()); + public CommonjWorkerMonitorImpl(WorkManager workManager) { this(workManager, true); } - - public CommonjWorkerMonitorImpl(WorkManager workManager, boolean jobWorksMonitorEnabled) + + public CommonjWorkerMonitorImpl(WorkManager workManager, + boolean jobWorksMonitorEnabled) { this(workManager, jobWorksMonitorEnabled, true); } - - public CommonjWorkerMonitorImpl(WorkManager workManager, boolean jobWorksMonitorEnabled, boolean interruptOnTimeout) + + public CommonjWorkerMonitorImpl(WorkManager workManager, + boolean jobWorksMonitorEnabled, boolean interruptOnTimeout) { this.workManager = workManager; this.jobWorksMonitorEnabled = jobWorksMonitorEnabled; this.interruptOnTimeout = interruptOnTimeout; } - + /** Commons logging */ - protected final static Log log = LogFactory.getLog(CommonjWorkerMonitorImpl.class); - + protected final static Log log = LogFactory + .getLog(CommonjWorkerMonitorImpl.class); + /** Renering Job Timeout monitor */ protected CommonjWorkerRenderingJobTimeoutMonitor jobMonitor = null; - + public void start() { if (this.jobWorksMonitorEnabled) @@ -111,24 +119,25 @@ jobMonitor = null; } - + /** - * Assign a job to a worker and execute it or queue the job if no - * worker is available. - * - * @param job the Job to process + * Assign a job to a worker and execute it or queue the job if no worker is + * available. + * + * @param job + * the Job to process */ public void process(RenderingJob job) { AccessControlContext context = AccessController.getContext(); job.setWorkerAttribute(ACCESS_CONTROL_CONTEXT_WORKER_ATTR, context); - + try { RenderingJobCommonjWork jobWork = new RenderingJobCommonjWork(job); WorkItem workItem = this.workManager.schedule(jobWork, this); job.setWorkerAttribute(COMMONJ_WORK_ITEM_ATTR, workItem); - + if (this.jobWorksMonitorEnabled) { this.jobWorksMonitored.put(workItem, jobWork); @@ -144,25 +153,28 @@ { return 0; } - + /** - * Wait for all rendering jobs in the collection to finish successfully or otherwise. - * @param renderingJobs the Collection of rendering job objects to wait for. + * Wait for all rendering jobs in the collection to finish successfully or + * otherwise. + * + * @param renderingJobs + * the Collection of rendering job objects to wait for. */ public void waitForRenderingJobs(List renderingJobs) { if (this.jobWorksMonitorEnabled) { - try + try { - for (Iterator iter = renderingJobs.iterator(); iter.hasNext(); ) + for (Iterator iter = renderingJobs.iterator(); iter.hasNext();) { RenderingJob job = (RenderingJob) iter.next(); PortletContent portletContent = job.getPortletContent(); - - synchronized (portletContent) + + synchronized (portletContent) { - if (!portletContent.isComplete()) + if (!portletContent.isComplete()) { portletContent.wait(); } @@ -171,62 +183,75 @@ } catch (Exception e) { - log.error("Exception during synchronizing all portlet rendering jobs.", e); + log + .error( + "Exception during synchronizing all portlet rendering jobs.", + e); } } else { - // We cannot use WorkingManager#waitForAll(workitems, timeout_ms) for timeout. - // The second argument could be either WorkManager.IMMEDIATE or WorkManager.INDEFINITE. - + // We cannot use WorkingManager#waitForAll(workitems, timeout_ms) + // for timeout. + // The second argument could be either WorkManager.IMMEDIATE or + // WorkManager.INDEFINITE. + try { if (!renderingJobs.isEmpty()) { Object lock = new Object(); - MonitoringJobCommonjWork monitoringWork = new MonitoringJobCommonjWork(lock, renderingJobs); - + MonitoringJobCommonjWork monitoringWork = new MonitoringJobCommonjWork( + lock, renderingJobs); + synchronized (lock) { - WorkItem monitorWorkItem = this.workManager.schedule(monitoringWork, this); + WorkItem monitorWorkItem = this.workManager.schedule( + monitoringWork, this); lock.wait(); } } } catch (Exception e) { - log.error("Exception during synchronizing all portlet rendering jobs.", e); + log + .error( + "Exception during synchronizing all portlet rendering jobs.", + e); } } } - + /** * Returns a snapshot of the available jobs + * * @return available jobs */ public int getAvailableJobsCount() { return 0; } - + public int getRunningJobsCount() { return 0; } - + // commonj.work.WorkListener implementations - + public void workAccepted(WorkEvent we) { WorkItem workItem = we.getWorkItem(); - if (log.isDebugEnabled()) log.debug("[CommonjWorkMonitorImpl] workAccepted: " + workItem); + if (log.isDebugEnabled()) + log.debug("[CommonjWorkMonitorImpl] workAccepted: " + workItem); } public void workRejected(WorkEvent we) { WorkItem workItem = we.getWorkItem(); - if (log.isDebugEnabled()) log.debug("[CommonjWorkMonitorImpl] workRejected: " + workItem); - + if (log.isDebugEnabled()) + log.debug("[CommonjWorkMonitorImpl] workRejected: " + workItem); + if (this.jobWorksMonitorEnabled) { removeMonitoredJobWork(workItem); @@ -236,25 +261,27 @@ public void workStarted(WorkEvent we) { WorkItem workItem = we.getWorkItem(); - if (log.isDebugEnabled()) log.debug("[CommonjWorkMonitorImpl] workStarted: " + workItem); + if (log.isDebugEnabled()) + log.debug("[CommonjWorkMonitorImpl] workStarted: " + workItem); } public void workCompleted(WorkEvent we) { WorkItem workItem = we.getWorkItem(); - if (log.isDebugEnabled()) log.debug("[CommonjWorkMonitorImpl] workCompleted: " + workItem); - + if (log.isDebugEnabled()) + log.debug("[CommonjWorkMonitorImpl] workCompleted: " + workItem); + if (this.jobWorksMonitorEnabled) { removeMonitoredJobWork(workItem); } } - + protected Object removeMonitoredJobWork(WorkItem workItem) { return this.jobWorksMonitored.remove(workItem); } - + class RenderingJobCommonjWork implements Work { @@ -269,21 +296,22 @@ { return false; } - + public void run() { if (jobWorksMonitorEnabled || interruptOnTimeout) { - this.job.setWorkerAttribute(WORKER_THREAD_ATTR, Thread.currentThread()); + this.job.setWorkerAttribute(WORKER_THREAD_ATTR, Thread + .currentThread()); } - + this.job.run(); } - + public void release() { } - + public RenderingJob getRenderingJob() { return this.job; @@ -292,8 +320,9 @@ class MonitoringJobCommonjWork implements Work { - + protected Object lock; + protected List renderingJobs; public MonitoringJobCommonjWork(Object lock, List jobs) @@ -301,44 +330,48 @@ this.lock = lock; this.renderingJobs = new ArrayList(jobs); } - + public boolean isDaemon() { return false; } - + public void run() { try { while (!this.renderingJobs.isEmpty()) { - for (Iterator it = this.renderingJobs.iterator(); it.hasNext(); ) + for (Iterator it = this.renderingJobs.iterator(); it + .hasNext();) { RenderingJob job = (RenderingJob) it.next(); - WorkItem workItem = (WorkItem) job.getWorkerAttribute(COMMONJ_WORK_ITEM_ATTR); + WorkItem workItem = (WorkItem) job + .getWorkerAttribute(COMMONJ_WORK_ITEM_ATTR); int status = WorkEvent.WORK_ACCEPTED; - + if (workItem != null) { status = workItem.getStatus(); } - + boolean isTimeout = job.isTimeout(); - + if (isTimeout) { PortletContent content = job.getPortletContent(); - + if (interruptOnTimeout) { - Thread worker = (Thread) job.getWorkerAttribute(WORKER_THREAD_ATTR); - + Thread worker = (Thread) job + .getWorkerAttribute(WORKER_THREAD_ATTR); + if (worker != null) { synchronized (content) { - if (!content.isComplete()) { + if (!content.isComplete()) + { worker.interrupt(); content.wait(); } @@ -353,13 +386,15 @@ } } } - - if (status == WorkEvent.WORK_COMPLETED || status == WorkEvent.WORK_REJECTED || isTimeout) + + if (status == WorkEvent.WORK_COMPLETED + || status == WorkEvent.WORK_REJECTED + || isTimeout) { it.remove(); - } + } } - + if (!this.renderingJobs.isEmpty()) { synchronized (this) @@ -368,7 +403,7 @@ } } } - + synchronized (this.lock) { this.lock.notify(); @@ -379,124 +414,145 @@ log.error("Exceptiong during job timeout monitoring.", e); } } - + public void release() { } - + } - class CommonjWorkerRenderingJobTimeoutMonitor extends Thread { + class CommonjWorkerRenderingJobTimeoutMonitor extends Thread + { long interval = 1000; + boolean shouldRun = true; - - CommonjWorkerRenderingJobTimeoutMonitor(long interval) + + CommonjWorkerRenderingJobTimeoutMonitor(long interval) { super("CommonjWorkerRenderingJobTimeoutMonitor"); - if (interval > 0) + if (interval > 0) { this.interval = interval; } } + /** - * Thread.stop() is deprecated. - * This method achieves the same by setting the run varaible "shouldRun" to false and interrupting the Thread, + * Thread.stop() is deprecated. This method achieves the same by setting + * the run varaible "shouldRun" to false and interrupting the Thread, * effectively causing the thread to shutdown correctly. - * + * */ public void endThread() { - shouldRun = false; - this.interrupt(); + shouldRun = false; + this.interrupt(); } - - public void run() { - while (shouldRun) { - try + + public void run() + { + while (shouldRun) + { + try { List timeoutJobWorks = new ArrayList(); - Collection jobWorks = Arrays.asList(jobWorksMonitored.values().toArray()); - - for (Iterator it = jobWorks.iterator(); it.hasNext(); ) + Collection jobWorks = Arrays.asList(jobWorksMonitored + .values().toArray()); + + for (Iterator it = jobWorks.iterator(); it.hasNext();) { - RenderingJobCommonjWork jobWork = (RenderingJobCommonjWork) it.next(); + RenderingJobCommonjWork jobWork = (RenderingJobCommonjWork) it + .next(); RenderingJob job = jobWork.getRenderingJob(); - + if (job.isTimeout()) { timeoutJobWorks.add(jobWork); } } - + // Now, we can kill the timeout worker(s). - for (Iterator it = timeoutJobWorks.iterator(); it.hasNext(); ) + for (Iterator it = timeoutJobWorks.iterator(); it.hasNext();) { - RenderingJobCommonjWork jobWork = (RenderingJobCommonjWork) it.next(); + RenderingJobCommonjWork jobWork = (RenderingJobCommonjWork) it + .next(); RenderingJob job = jobWork.getRenderingJob(); - // If the job is just completed, then do not kill the worker. + // If the job is just completed, then do not kill the + // worker. if (job.isTimeout()) { killJobWork(jobWork); } } - } - catch (Exception e) + } + catch (Exception e) { log.error("Exception during job monitoring.", e); } - - try + + try { - synchronized (this) + synchronized (this) { wait(this.interval); } - } - catch (InterruptedException e) + } + catch (InterruptedException e) { ; } } } - - public void killJobWork(RenderingJobCommonjWork jobWork) { + + public void killJobWork(RenderingJobCommonjWork jobWork) + { RenderingJob job = jobWork.getRenderingJob(); - - try { - if (log.isWarnEnabled()) { + + try + { + if (log.isWarnEnabled()) + { PortletWindow window = job.getWindow(); ObjectID windowId = (null != window ? window.getId() : null); - log.warn("Portlet Rendering job to be interrupted by timeout (" + job.getTimeout() + "ms): " + windowId); + log + .warn("Portlet Rendering job to be interrupted by timeout (" + + job.getTimeout() + "ms): " + windowId); } PortletContent content = job.getPortletContent(); - Thread worker = (Thread) job.getWorkerAttribute(WORKER_THREAD_ATTR); - + Thread worker = (Thread) job + .getWorkerAttribute(WORKER_THREAD_ATTR); + if (worker != null) { synchronized (content) { - if (!content.isComplete()) { + if (!content.isComplete()) + { worker.interrupt(); content.wait(); } } } - } catch (Exception e) { + } + catch (Exception e) + { log.error("Exceptiong during job killing.", e); - } finally { - WorkItem workItem = (WorkItem) job.getWorkerAttribute(COMMONJ_WORK_ITEM_ATTR); - + } + finally + { + WorkItem workItem = (WorkItem) job + .getWorkerAttribute(COMMONJ_WORK_ITEM_ATTR); + if (workItem != null) { removeMonitoredJobWork(workItem); } } } - + } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/ContentDispatcherImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/ContentDispatcherImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/ContentDispatcherImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -35,37 +35,43 @@ */ public class ContentDispatcherImpl implements ContentDispatcherCtrl { + private PortletContent content = null; - private ContentDispatcherImpl() - {} - + private ContentDispatcherImpl() + { + } + public ContentDispatcherImpl(PortletContent content) { this.content = content; } - public HttpServletResponse getResponseForWindow( PortletWindow window, RequestContext request ) + public HttpServletResponse getResponseForWindow(PortletWindow window, + RequestContext request) { - return new HttpBufferedResponse(request.getResponse(), this.content.getWriter()); + return new HttpBufferedResponse(request.getResponse(), this.content + .getWriter()); } - - public HttpServletResponse getResponseForFragment( Fragment fragment, RequestContext request ) + + public HttpServletResponse getResponseForFragment(Fragment fragment, + RequestContext request) { - return new HttpBufferedResponse(request.getResponse(), this.content.getWriter()); + return new HttpBufferedResponse(request.getResponse(), this.content + .getWriter()); } /** *

        * getPortletContent *

        - * + * * @see org.apache.jetspeed.aggregator.ContentDispatcher#getPortletContent(org.apache.jetspeed.om.page.Fragment) * @param fragment * @return */ - public PortletContent getPortletContent( Fragment fragment ) - { + public PortletContent getPortletContent(Fragment fragment) + { return this.content; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/HeaderAggregatorImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/HeaderAggregatorImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/HeaderAggregatorImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,18 +17,18 @@ package org.apache.jetspeed.aggregator.impl; import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Map; -import java.util.HashMap; -import java.util.List; -import java.util.ArrayList; -import java.util.Collections; import javax.portlet.Portlet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - +import org.apache.jetspeed.PortalReservedParameters; import org.apache.jetspeed.aggregator.FailedToRenderFragmentException; import org.apache.jetspeed.aggregator.PageAggregator; import org.apache.jetspeed.container.state.NavigationalState; @@ -47,7 +47,6 @@ import org.apache.jetspeed.portlet.PortletHeaderResponse; import org.apache.jetspeed.portlet.SupportsHeaderPhase; import org.apache.jetspeed.request.RequestContext; -import org.apache.jetspeed.PortalReservedParameters; import org.apache.pluto.om.portlet.PortletDefinition; import org.apache.pluto.om.window.PortletWindow; @@ -61,45 +60,51 @@ */ public class HeaderAggregatorImpl implements PageAggregator { - protected final static Log log = LogFactory.getLog( HeaderAggregatorImpl.class ); - protected final static String EOL = "\r\n"; // html eol + protected final static Log log = LogFactory + .getLog(HeaderAggregatorImpl.class); + + protected final static String EOL = "\r\n"; // html eol + private PortletFactory factory; + private PortletWindowAccessor windowAccessor; + private HeaderResourceFactory headerResourceFactory; + private DecorationFactory decorationFactory; - + private boolean isDesktop; - + private Map headerConfiguration; + private Map headerResourceRegistry; + private Map headerDynamicConfigurationDefault; + private Map headerNamedResourcesDefault; + private Map headerNamedResourcesAddedFragmentsDefault; - + /** base portal URL to override default URL server info from servlet */ private BasePortalURL baseUrlAccess = null; - - - public HeaderAggregatorImpl( PortletFactory factory, - PortletWindowAccessor windowAccessor, - HeaderResourceFactory headerResourceFactory, - boolean isDesktop, - Map headerConfiguration, - Map headerResourceRegistry, - DecorationFactory decorationFactory ) + + public HeaderAggregatorImpl(PortletFactory factory, + PortletWindowAccessor windowAccessor, + HeaderResourceFactory headerResourceFactory, boolean isDesktop, + Map headerConfiguration, Map headerResourceRegistry, + DecorationFactory decorationFactory) { - this( factory, windowAccessor, headerResourceFactory, isDesktop, headerConfiguration, headerResourceRegistry, decorationFactory, null ); + this(factory, windowAccessor, headerResourceFactory, isDesktop, + headerConfiguration, headerResourceRegistry, decorationFactory, + null); } - - public HeaderAggregatorImpl( PortletFactory factory, - PortletWindowAccessor windowAccessor, - HeaderResourceFactory headerResourceFactory, - boolean isDesktop, - Map headerConfiguration, - Map headerResourceRegistry, - DecorationFactory decorationFactory, - BasePortalURL baseUrlAccess ) + + public HeaderAggregatorImpl(PortletFactory factory, + PortletWindowAccessor windowAccessor, + HeaderResourceFactory headerResourceFactory, boolean isDesktop, + Map headerConfiguration, Map headerResourceRegistry, + DecorationFactory decorationFactory, BasePortalURL baseUrlAccess) { this.factory = factory; this.windowAccessor = windowAccessor; @@ -107,744 +112,1101 @@ this.isDesktop = isDesktop; this.baseUrlAccess = baseUrlAccess; this.decorationFactory = decorationFactory; - initializeHeaderConfiguration( headerConfiguration, headerResourceRegistry ); + initializeHeaderConfiguration(headerConfiguration, + headerResourceRegistry); } - + /** - * Initialize header configuration, making immutable copies of the data structures and - * compiling as much finished static header content as possible (to minimize repetitive work per request) + * Initialize header configuration, making immutable copies of the data + * structures and compiling as much finished static header content as + * possible (to minimize repetitive work per request) */ - private void initializeHeaderConfiguration( Map headerConfigArg, Map headerRsrcRegistryArg ) + private void initializeHeaderConfiguration(Map headerConfigArg, + Map headerRsrcRegistryArg) { this.headerConfiguration = null; this.headerResourceRegistry = null; this.headerDynamicConfigurationDefault = null; this.headerNamedResourcesDefault = null; this.headerNamedResourcesAddedFragmentsDefault = null; - - if ( headerConfigArg != null && headerConfigArg.size() > 0 ) + + if (headerConfigArg != null && headerConfigArg.size() > 0) { // attempt to make safe immutable copy of headerConfigArg HashMap headerConfig = new HashMap(); - Iterator headerConfigEntryIter = headerConfigArg.entrySet().iterator(); - while ( headerConfigEntryIter.hasNext() ) + Iterator headerConfigEntryIter = headerConfigArg.entrySet() + .iterator(); + while (headerConfigEntryIter.hasNext()) { - Map.Entry headerConfigEntry = (Map.Entry)headerConfigEntryIter.next(); + Map.Entry headerConfigEntry = (Map.Entry) headerConfigEntryIter + .next(); Object headerConfigKey = headerConfigEntry.getKey(); Object headerConfigVal = headerConfigEntry.getValue(); - if ( headerConfigVal instanceof Map ) + if (headerConfigVal instanceof Map) { - headerConfig.put( headerConfigKey, Collections.unmodifiableMap( new HashMap( (Map)headerConfigVal ) ) ); + headerConfig.put(headerConfigKey, + Collections.unmodifiableMap(new HashMap( + (Map) headerConfigVal))); } - else if ( headerConfigVal instanceof List ) + else if (headerConfigVal instanceof List) { - headerConfig.put( headerConfigKey, Collections.unmodifiableList( new ArrayList( (List)headerConfigVal ) ) ); + headerConfig.put(headerConfigKey, Collections + .unmodifiableList(new ArrayList( + (List) headerConfigVal))); } else { - headerConfig.put( headerConfigKey, headerConfigVal ); + headerConfig.put(headerConfigKey, headerConfigVal); } } - this.headerConfiguration = Collections.unmodifiableMap( headerConfig ); - - // make modifiable copy of headerRsrcRegistryArg - is made immutable at end of initializeHeaderConfiguration() + this.headerConfiguration = Collections + .unmodifiableMap(headerConfig); + + // make modifiable copy of headerRsrcRegistryArg - is made immutable + // at end of initializeHeaderConfiguration() Map headerRsrcRegistry = null; - if ( headerRsrcRegistryArg != null && headerRsrcRegistryArg.size() > 0 ) + if (headerRsrcRegistryArg != null + && headerRsrcRegistryArg.size() > 0) { - headerRsrcRegistry = new HashMap( headerRsrcRegistryArg ); - // leave modifiable during initializeHeaderConfigurationDefaults() protocol - // (so that entries can be removed - possibly leading to an empty map which will save a bunch of gratuitous lookups) + headerRsrcRegistry = new HashMap(headerRsrcRegistryArg); + // leave modifiable during + // initializeHeaderConfigurationDefaults() protocol + // (so that entries can be removed - possibly leading to an + // empty map which will save a bunch of gratuitous lookups) } else { headerRsrcRegistry = new HashMap(); } - this.headerResourceRegistry = headerRsrcRegistry; + this.headerResourceRegistry = headerRsrcRegistry; HashMap namedResourcesDefault = new HashMap(); HashMap namedResourcesAddedFragmentsDefault = new HashMap(); - - Map dynamicConfigurationDefault = initializeHeaderConfigurationDefaults( namedResourcesDefault, namedResourcesAddedFragmentsDefault ); - if ( dynamicConfigurationDefault != null ) - this.headerDynamicConfigurationDefault = Collections.unmodifiableMap( dynamicConfigurationDefault ); - - this.headerNamedResourcesDefault = Collections.unmodifiableMap( namedResourcesDefault ); - this.headerNamedResourcesAddedFragmentsDefault = Collections.unmodifiableMap( namedResourcesAddedFragmentsDefault ); - + + Map dynamicConfigurationDefault = initializeHeaderConfigurationDefaults( + namedResourcesDefault, namedResourcesAddedFragmentsDefault); + if (dynamicConfigurationDefault != null) + this.headerDynamicConfigurationDefault = Collections + .unmodifiableMap(dynamicConfigurationDefault); + + this.headerNamedResourcesDefault = Collections + .unmodifiableMap(namedResourcesDefault); + this.headerNamedResourcesAddedFragmentsDefault = Collections + .unmodifiableMap(namedResourcesAddedFragmentsDefault); + this.headerResourceRegistry = null; - if ( headerRsrcRegistry != null && headerRsrcRegistry.size() > 0 ) + if (headerRsrcRegistry != null && headerRsrcRegistry.size() > 0) { - this.headerResourceRegistry = Collections.unmodifiableMap( headerRsrcRegistry ); + this.headerResourceRegistry = Collections + .unmodifiableMap(headerRsrcRegistry); } } } /** - * Initialize dynamic-header-configuration and call initializeHeaderConfigurationEntryDefaults() for - * each key in headerConfiguration Map, allowing for each to add resources and settings to: - * headerNamedResourcesDefault, headerNamedResourcesAddedFragmentsDefault and headerDynamicConfigurationDefault + * Initialize dynamic-header-configuration and call + * initializeHeaderConfigurationEntryDefaults() for each key in + * headerConfiguration Map, allowing for each to add resources and settings + * to: headerNamedResourcesDefault, + * headerNamedResourcesAddedFragmentsDefault and + * headerDynamicConfigurationDefault * - * If no specific handler is defined for a headerConfiguration key, the entry is copied to headerDynamicConfigurationDefault - * otherwise the handler is responsible for adding information to headerDynamicConfigurationDefault + * If no specific handler is defined for a headerConfiguration key, the + * entry is copied to headerDynamicConfigurationDefault otherwise the + * handler is responsible for adding information to + * headerDynamicConfigurationDefault * - * headerConfiguration handlers are currently defined for the headerConfiguration keys: - * "header.order" - HeaderResource.HEADER_CONFIG_ORDER - * "header.types" - HeaderResource.HEADER_CONFIG_TYPES - * "header.requiredflag" - HeaderResource.HEADER_CONFIG_REQUIREDFLAG - * "dojo" - HeaderResource.HEADER_CONFIG_DOJO - * "desktop" - HeaderResource.HEADER_CONFIG_DESKTOP + * headerConfiguration handlers are currently defined for the + * headerConfiguration keys: "header.order" - + * HeaderResource.HEADER_CONFIG_ORDER "header.types" - + * HeaderResource.HEADER_CONFIG_TYPES "header.requiredflag" - + * HeaderResource.HEADER_CONFIG_REQUIREDFLAG "dojo" - + * HeaderResource.HEADER_CONFIG_DOJO "desktop" - + * HeaderResource.HEADER_CONFIG_DESKTOP */ - protected Map initializeHeaderConfigurationDefaults( HashMap namedResourcesDefault, HashMap namedResourcesAddedFragmentsDefault ) + protected Map initializeHeaderConfigurationDefaults( + HashMap namedResourcesDefault, + HashMap namedResourcesAddedFragmentsDefault) { - if ( this.headerConfiguration == null ) - { - return null; - } - + if (this.headerConfiguration == null) { return null; } + HashMap headerDynamicConfigurationDefault = new HashMap(); - - initializeHeaderOrderConfigurationDefaults( namedResourcesDefault, namedResourcesAddedFragmentsDefault, headerDynamicConfigurationDefault ); + initializeHeaderOrderConfigurationDefaults(namedResourcesDefault, + namedResourcesAddedFragmentsDefault, + headerDynamicConfigurationDefault); + // setting header.basetag type - without adding it to order - setNamedHeaderResourceProperties( HeaderResource.HEADER_SECTION_BASE_TAG, HeaderResource.HEADER_TYPE_BASE_TAG, null, headerDynamicConfigurationDefault ); - - Iterator hConfigEntryIter = this.headerConfiguration.entrySet().iterator(); - while ( hConfigEntryIter.hasNext() ) + setNamedHeaderResourceProperties( + HeaderResource.HEADER_SECTION_BASE_TAG, + HeaderResource.HEADER_TYPE_BASE_TAG, null, + headerDynamicConfigurationDefault); + + Iterator hConfigEntryIter = this.headerConfiguration.entrySet() + .iterator(); + while (hConfigEntryIter.hasNext()) { - Map.Entry hConfigEntry = (Map.Entry)hConfigEntryIter.next(); + Map.Entry hConfigEntry = (Map.Entry) hConfigEntryIter.next(); Object hConfigKey = hConfigEntry.getKey(); Object hConfigVal = hConfigEntry.getValue(); - - if ( ! initializeHeaderConfigurationEntryDefaults( hConfigKey, hConfigVal, namedResourcesDefault, namedResourcesAddedFragmentsDefault, headerDynamicConfigurationDefault ) ) + + if (!initializeHeaderConfigurationEntryDefaults(hConfigKey, + hConfigVal, namedResourcesDefault, + namedResourcesAddedFragmentsDefault, + headerDynamicConfigurationDefault)) { - if ( hConfigVal instanceof Map ) + if (hConfigVal instanceof Map) { - headerDynamicConfigurationDefault.put( hConfigKey, Collections.unmodifiableMap( new HashMap( (Map)hConfigVal ) ) ); + headerDynamicConfigurationDefault.put(hConfigKey, + Collections.unmodifiableMap(new HashMap( + (Map) hConfigVal))); } - else if ( hConfigVal instanceof List ) + else if (hConfigVal instanceof List) { - headerDynamicConfigurationDefault.put( hConfigKey, Collections.unmodifiableList( new ArrayList( (List)hConfigVal ) ) ); + headerDynamicConfigurationDefault.put(hConfigKey, + Collections.unmodifiableList(new ArrayList( + (List) hConfigVal))); } else { - headerDynamicConfigurationDefault.put( hConfigKey, hConfigVal ); + headerDynamicConfigurationDefault.put(hConfigKey, + hConfigVal); } } } - initializeMissingHeaderConfigurationEntryDefaults( namedResourcesDefault, namedResourcesAddedFragmentsDefault, headerDynamicConfigurationDefault ); - - postinitializeHeaderOrderConfigurationDefaults( headerDynamicConfigurationDefault ); - + initializeMissingHeaderConfigurationEntryDefaults( + namedResourcesDefault, namedResourcesAddedFragmentsDefault, + headerDynamicConfigurationDefault); + + postinitializeHeaderOrderConfigurationDefaults(headerDynamicConfigurationDefault); + return headerDynamicConfigurationDefault; } - - protected void initializeHeaderOrderConfigurationDefaults( HashMap namedResourcesDefault, HashMap namedResourcesAddedFragmentsDefault, HashMap headerDynamicConfigurationDefault ) + + protected void initializeHeaderOrderConfigurationDefaults( + HashMap namedResourcesDefault, + HashMap namedResourcesAddedFragmentsDefault, + HashMap headerDynamicConfigurationDefault) { - if ( this.headerConfiguration != null ) + if (this.headerConfiguration != null) { - List headerOrderConfigList = (List)this.headerConfiguration.get( HeaderResource.HEADER_CONFIG_ORDER ); - if ( headerOrderConfigList != null && headerOrderConfigList.size() > 0 ) + List headerOrderConfigList = (List) this.headerConfiguration + .get(HeaderResource.HEADER_CONFIG_ORDER); + if (headerOrderConfigList != null + && headerOrderConfigList.size() > 0) { ArrayList headerOrderList = new ArrayList(); Map headerNames = new HashMap(); Iterator headerOrderListIter = headerOrderConfigList.iterator(); - while ( headerOrderListIter.hasNext() ) + while (headerOrderListIter.hasNext()) { Object headerNameObj = headerOrderListIter.next(); - if ( headerNameObj != null ) + if (headerNameObj != null) { String headerName = headerNameObj.toString(); - if ( headerName != null && headerName.length() > 0 ) + if (headerName != null && headerName.length() > 0) { - headerOrderList.add( headerName ); - headerNames.put( headerName, Boolean.TRUE ); + headerOrderList.add(headerName); + headerNames.put(headerName, Boolean.TRUE); } } } - // add modifiable structures at this point - so that later initialization steps can manipulate the defaults - // needs to be made unmodifiable at end of processing by calling postinitializeHeaderOrderConfigurationDefaults() - headerDynamicConfigurationDefault.put( HeaderResource.HEADER_CONFIG_ORDER, headerOrderList ); - headerDynamicConfigurationDefault.put( HeaderResource.HEADER_INTERNAL_INCLUDED_NAMES, headerNames ); + // add modifiable structures at this point - so that later + // initialization steps can manipulate the defaults + // needs to be made unmodifiable at end of processing by calling + // postinitializeHeaderOrderConfigurationDefaults() + headerDynamicConfigurationDefault.put( + HeaderResource.HEADER_CONFIG_ORDER, headerOrderList); + headerDynamicConfigurationDefault.put( + HeaderResource.HEADER_INTERNAL_INCLUDED_NAMES, + headerNames); } - + Map headerTypes = null; - Map headerTypesConfig = (Map)this.headerConfiguration.get( HeaderResource.HEADER_CONFIG_TYPES ); - if ( headerTypesConfig != null && headerTypesConfig.size() > 0 ) + Map headerTypesConfig = (Map) this.headerConfiguration + .get(HeaderResource.HEADER_CONFIG_TYPES); + if (headerTypesConfig != null && headerTypesConfig.size() > 0) { headerTypes = new HashMap(); - Iterator headerTypesConfigIter = headerTypesConfig.entrySet().iterator(); - while ( headerTypesConfigIter.hasNext() ) + Iterator headerTypesConfigIter = headerTypesConfig.entrySet() + .iterator(); + while (headerTypesConfigIter.hasNext()) { - Map.Entry headerTypeEntry = (Map.Entry)headerTypesConfigIter.next(); + Map.Entry headerTypeEntry = (Map.Entry) headerTypesConfigIter + .next(); Object headerNameObj = headerTypeEntry.getKey(); Object headerTypeObj = headerTypeEntry.getValue(); - if ( headerNameObj != null && headerTypeObj != null ) + if (headerNameObj != null && headerTypeObj != null) { String headerName = headerNameObj.toString(); - int headerTypeId = HeaderResourceLib.getHeaderTypeId( headerTypeObj.toString() ); - if ( headerName != null ) + int headerTypeId = HeaderResourceLib + .getHeaderTypeId(headerTypeObj.toString()); + if (headerName != null) { - if ( headerTypeId >= 0 ) + if (headerTypeId >= 0) { - headerTypes.put( headerName, new Object[] { new Integer( headerTypeId ), null } ); + headerTypes.put(headerName, new Object[] + {new Integer(headerTypeId), null}); } else { - log.error( "HeaderAggregatorImpl.initializeHeaderOrderConfigurationDefaults() ignoring specification of unknown header section type; header-section-name=" + headerName + " header-section-type=" + headerTypeObj.toString() ); + log + .error("HeaderAggregatorImpl.initializeHeaderOrderConfigurationDefaults() ignoring specification of unknown header section type; header-section-name=" + + headerName + + " header-section-type=" + + headerTypeObj.toString()); } } } } } - - Map headerRequiredFlagConfig = (Map)this.headerConfiguration.get( HeaderResource.HEADER_CONFIG_REQUIREDFLAG ); - if ( headerRequiredFlagConfig != null && headerRequiredFlagConfig.size() > 0 ) + + Map headerRequiredFlagConfig = (Map) this.headerConfiguration + .get(HeaderResource.HEADER_CONFIG_REQUIREDFLAG); + if (headerRequiredFlagConfig != null + && headerRequiredFlagConfig.size() > 0) { - if ( headerTypes == null ) + if (headerTypes == null) { headerTypes = new HashMap(); } - Iterator headerRequiredFlagConfigIter = headerRequiredFlagConfig.entrySet().iterator(); - while ( headerRequiredFlagConfigIter.hasNext() ) + Iterator headerRequiredFlagConfigIter = headerRequiredFlagConfig + .entrySet().iterator(); + while (headerRequiredFlagConfigIter.hasNext()) { - Map.Entry headerRequiredFlagEntry = (Map.Entry)headerRequiredFlagConfigIter.next(); + Map.Entry headerRequiredFlagEntry = (Map.Entry) headerRequiredFlagConfigIter + .next(); Object headerNameObj = headerRequiredFlagEntry.getKey(); - Object headerReqFlagObj = headerRequiredFlagEntry.getValue(); - if ( headerNameObj != null && headerReqFlagObj != null ) + Object headerReqFlagObj = headerRequiredFlagEntry + .getValue(); + if (headerNameObj != null && headerReqFlagObj != null) { String headerName = headerNameObj.toString(); String headerReqFlag = headerReqFlagObj.toString(); - if ( headerName != null && headerName.length() > 0 && headerReqFlag != null ) + if (headerName != null && headerName.length() > 0 + && headerReqFlag != null) { - Object[] headerTypePair = (Object[])headerTypes.get( headerName ); - if ( headerTypePair != null ) + Object[] headerTypePair = (Object[]) headerTypes + .get(headerName); + if (headerTypePair != null) { headerTypePair[1] = headerReqFlag; } else { - headerTypePair = new Object[] { null, headerReqFlag }; - headerTypes.put( headerName, headerTypePair ); + headerTypePair = new Object[] + {null, headerReqFlag}; + headerTypes.put(headerName, headerTypePair); } } } } } - if ( headerTypes != null && headerTypes.size() > 0 ) + if (headerTypes != null && headerTypes.size() > 0) { - headerDynamicConfigurationDefault.put( HeaderResource.HEADER_CONFIG_TYPES, headerTypes ); + headerDynamicConfigurationDefault.put( + HeaderResource.HEADER_CONFIG_TYPES, headerTypes); } } } - protected void postinitializeHeaderOrderConfigurationDefaults( HashMap headerDynamicConfigurationDefault ) + + protected void postinitializeHeaderOrderConfigurationDefaults( + HashMap headerDynamicConfigurationDefault) { - if ( headerDynamicConfigurationDefault != null ) + if (headerDynamicConfigurationDefault != null) { - Map headerNames = (Map)headerDynamicConfigurationDefault.get( HeaderResource.HEADER_INTERNAL_INCLUDED_NAMES ); - if ( headerNames != null ) + Map headerNames = (Map) headerDynamicConfigurationDefault + .get(HeaderResource.HEADER_INTERNAL_INCLUDED_NAMES); + if (headerNames != null) { - headerDynamicConfigurationDefault.put( HeaderResource.HEADER_INTERNAL_INCLUDED_NAMES, Collections.unmodifiableMap( headerNames ) ); + headerDynamicConfigurationDefault.put( + HeaderResource.HEADER_INTERNAL_INCLUDED_NAMES, + Collections.unmodifiableMap(headerNames)); } - Map headerTypes = (Map)headerDynamicConfigurationDefault.get( HeaderResource.HEADER_CONFIG_TYPES ); - if ( headerTypes != null ) + Map headerTypes = (Map) headerDynamicConfigurationDefault + .get(HeaderResource.HEADER_CONFIG_TYPES); + if (headerTypes != null) { - headerDynamicConfigurationDefault.put( HeaderResource.HEADER_CONFIG_TYPES, Collections.unmodifiableMap( headerTypes ) ); + headerDynamicConfigurationDefault.put( + HeaderResource.HEADER_CONFIG_TYPES, Collections + .unmodifiableMap(headerTypes)); } - List headerOrderList = (List)headerDynamicConfigurationDefault.get( HeaderResource.HEADER_CONFIG_ORDER ); - if ( headerOrderList != null ) + List headerOrderList = (List) headerDynamicConfigurationDefault + .get(HeaderResource.HEADER_CONFIG_ORDER); + if (headerOrderList != null) { - headerDynamicConfigurationDefault.put( HeaderResource.HEADER_CONFIG_ORDER, Collections.unmodifiableList( headerOrderList ) ); + headerDynamicConfigurationDefault.put( + HeaderResource.HEADER_CONFIG_ORDER, Collections + .unmodifiableList(headerOrderList)); } } } - + /** * Intended as derived class hook into header configuration process * - * @return true if headerConfigKey has been processed or false if default processing should occur + * @return true if headerConfigKey has been processed or false if default + * processing should occur */ - protected boolean initializeHeaderConfigurationEntryDefaults( Object headerConfigKey, Object headerConfigValue, HashMap namedResourcesDefault, HashMap namedResourcesAddedFragmentsDefault, HashMap headerDynamicConfigurationDefault ) + protected boolean initializeHeaderConfigurationEntryDefaults( + Object headerConfigKey, Object headerConfigValue, + HashMap namedResourcesDefault, + HashMap namedResourcesAddedFragmentsDefault, + HashMap headerDynamicConfigurationDefault) { - if ( headerConfigKey.equals( HeaderResource.HEADER_CONFIG_ORDER ) || headerConfigKey.equals( HeaderResource.HEADER_CONFIG_TYPES ) || headerConfigKey.equals( HeaderResource.HEADER_CONFIG_REQUIREDFLAG ) ) + if (headerConfigKey.equals(HeaderResource.HEADER_CONFIG_ORDER) + || headerConfigKey.equals(HeaderResource.HEADER_CONFIG_TYPES) + || headerConfigKey + .equals(HeaderResource.HEADER_CONFIG_REQUIREDFLAG)) { - // do nothing - processed earlier with call to initializeHeaderOrderConfigurationDefaults() + // do nothing - processed earlier with call to + // initializeHeaderOrderConfigurationDefaults() return true; } - else if ( headerConfigKey.equals( HeaderResource.HEADER_CONFIG_DOJO ) ) + else if (headerConfigKey.equals(HeaderResource.HEADER_CONFIG_DOJO)) { - initializeDojoHeaderConfigurationDefaults( (Map)headerConfigValue, namedResourcesDefault, namedResourcesAddedFragmentsDefault, headerDynamicConfigurationDefault ); + initializeDojoHeaderConfigurationDefaults((Map) headerConfigValue, + namedResourcesDefault, namedResourcesAddedFragmentsDefault, + headerDynamicConfigurationDefault); return true; } - else if ( headerConfigKey.equals( HeaderResource.HEADER_CONFIG_DESKTOP ) ) + else if (headerConfigKey.equals(HeaderResource.HEADER_CONFIG_DESKTOP)) { - initializeDesktopHeaderConfigurationDefaults( (Map)headerConfigValue, namedResourcesDefault, namedResourcesAddedFragmentsDefault, headerDynamicConfigurationDefault ); + initializeDesktopHeaderConfigurationDefaults( + (Map) headerConfigValue, namedResourcesDefault, + namedResourcesAddedFragmentsDefault, + headerDynamicConfigurationDefault); return true; } return false; } - - protected void initializeMissingHeaderConfigurationEntryDefaults( HashMap namedResourcesDefault, HashMap namedResourcesAddedFragmentsDefault, HashMap headerDynamicConfigurationDefault ) + + protected void initializeMissingHeaderConfigurationEntryDefaults( + HashMap namedResourcesDefault, + HashMap namedResourcesAddedFragmentsDefault, + HashMap headerDynamicConfigurationDefault) { - if ( isDesktop() ) + if (isDesktop()) { - if ( this.headerConfiguration.get( HeaderResource.HEADER_CONFIG_DOJO ) == null ) + if (this.headerConfiguration.get(HeaderResource.HEADER_CONFIG_DOJO) == null) { - initializeDojoHeaderConfigurationDefaults( null, namedResourcesDefault, namedResourcesAddedFragmentsDefault, headerDynamicConfigurationDefault ); + initializeDojoHeaderConfigurationDefaults(null, + namedResourcesDefault, + namedResourcesAddedFragmentsDefault, + headerDynamicConfigurationDefault); } - if ( this.headerConfiguration.get( HeaderResource.HEADER_CONFIG_DESKTOP ) == null ) + if (this.headerConfiguration + .get(HeaderResource.HEADER_CONFIG_DESKTOP) == null) { - initializeDesktopHeaderConfigurationDefaults( null, namedResourcesDefault, namedResourcesAddedFragmentsDefault, headerDynamicConfigurationDefault ); + initializeDesktopHeaderConfigurationDefaults(null, + namedResourcesDefault, + namedResourcesAddedFragmentsDefault, + headerDynamicConfigurationDefault); } } } - - protected void registerAndOrderNamedHeaderResource( String headerName, String headerType, String headerReqFlag, Map headerDynamicConfigurationDefault ) + + protected void registerAndOrderNamedHeaderResource(String headerName, + String headerType, String headerReqFlag, + Map headerDynamicConfigurationDefault) { - orderNamedHeaderResource( headerName, headerDynamicConfigurationDefault ); - setNamedHeaderResourceProperties( headerName, headerType, headerReqFlag, headerDynamicConfigurationDefault ); + orderNamedHeaderResource(headerName, headerDynamicConfigurationDefault); + setNamedHeaderResourceProperties(headerName, headerType, headerReqFlag, + headerDynamicConfigurationDefault); } - - protected void orderNamedHeaderResource( String headerName, Map headerDynamicConfigurationDefault ) + + protected void orderNamedHeaderResource(String headerName, + Map headerDynamicConfigurationDefault) { - if ( headerName != null ) + if (headerName != null) { - Map headerNames = (Map)headerDynamicConfigurationDefault.get( HeaderResource.HEADER_INTERNAL_INCLUDED_NAMES ); - if ( headerNames == null ) + Map headerNames = (Map) headerDynamicConfigurationDefault + .get(HeaderResource.HEADER_INTERNAL_INCLUDED_NAMES); + if (headerNames == null) { headerNames = new HashMap(); - headerDynamicConfigurationDefault.put( HeaderResource.HEADER_INTERNAL_INCLUDED_NAMES, headerNames ); + headerDynamicConfigurationDefault.put( + HeaderResource.HEADER_INTERNAL_INCLUDED_NAMES, + headerNames); } - - Object headerNamesVal = headerNames.get( headerName ); - if ( headerNamesVal == null ) + + Object headerNamesVal = headerNames.get(headerName); + if (headerNamesVal == null) { - List headerOrderList = (List)headerDynamicConfigurationDefault.get( HeaderResource.HEADER_CONFIG_ORDER ); - if ( headerOrderList == null ) + List headerOrderList = (List) headerDynamicConfigurationDefault + .get(HeaderResource.HEADER_CONFIG_ORDER); + if (headerOrderList == null) { headerOrderList = new ArrayList(); - headerDynamicConfigurationDefault.put( HeaderResource.HEADER_CONFIG_ORDER, headerOrderList ); + headerDynamicConfigurationDefault + .put(HeaderResource.HEADER_CONFIG_ORDER, + headerOrderList); } - - headerOrderList.add( headerName ); - headerNames.put( headerName, Boolean.TRUE ); + + headerOrderList.add(headerName); + headerNames.put(headerName, Boolean.TRUE); } } } - - protected void setNamedHeaderResourceProperties( String headerName, String headerType, String headerReqFlag, Map headerDynamicConfigurationDefault ) + + protected void setNamedHeaderResourceProperties(String headerName, + String headerType, String headerReqFlag, + Map headerDynamicConfigurationDefault) { - if ( headerName != null ) + if (headerName != null) { - int headerTypeId = HeaderResourceLib.getHeaderTypeId( headerType ); - - boolean headerRefFlagSpecified = ( headerReqFlag != null && headerReqFlag.length() > 0 ); - if ( headerTypeId < 0 && ! headerRefFlagSpecified ) + int headerTypeId = HeaderResourceLib.getHeaderTypeId(headerType); + + boolean headerRefFlagSpecified = (headerReqFlag != null && headerReqFlag + .length() > 0); + if (headerTypeId < 0 && !headerRefFlagSpecified) { - log.error( "HeaderAggregatorImpl.registerAndOrderNamedHeaderResource() ignoring specification of unknown header section type; header-section-name=" + headerName + " header-section-type=" + headerType ); + log + .error("HeaderAggregatorImpl.registerAndOrderNamedHeaderResource() ignoring specification of unknown header section type; header-section-name=" + + headerName + + " header-section-type=" + + headerType); } - - if ( ( headerTypeId >= 0 ) || headerRefFlagSpecified ) + + if ((headerTypeId >= 0) || headerRefFlagSpecified) { - Map headerTypes = (Map)headerDynamicConfigurationDefault.get( HeaderResource.HEADER_CONFIG_TYPES ); - if ( headerTypes == null ) + Map headerTypes = (Map) headerDynamicConfigurationDefault + .get(HeaderResource.HEADER_CONFIG_TYPES); + if (headerTypes == null) { headerTypes = new HashMap(); - headerDynamicConfigurationDefault.put( HeaderResource.HEADER_CONFIG_TYPES, headerTypes ); + headerDynamicConfigurationDefault.put( + HeaderResource.HEADER_CONFIG_TYPES, headerTypes); } - - Object[] headerTypePair = (Object[])headerTypes.get( headerName ); - if ( headerTypePair == null ) + + Object[] headerTypePair = (Object[]) headerTypes + .get(headerName); + if (headerTypePair == null) { - headerTypePair = new Object[] { null, null }; - headerTypes.put( headerName, headerTypePair ); + headerTypePair = new Object[] + {null, null}; + headerTypes.put(headerName, headerTypePair); } - if ( headerTypePair[0] == null && headerTypeId >= 0 ) - { // change only if value from configuration is null - headerTypePair[0] = new Integer( headerTypeId ); + if (headerTypePair[0] == null && headerTypeId >= 0) + { // change only if value from configuration is null + headerTypePair[0] = new Integer(headerTypeId); } - if ( headerTypePair[1] == null && headerReqFlag != null && headerReqFlag.length() > 0 ) - { // change only if value from configuration is null + if (headerTypePair[1] == null && headerReqFlag != null + && headerReqFlag.length() > 0) + { // change only if value from configuration is null headerTypePair[1] = headerReqFlag; } } } } - - protected boolean canAddHeaderNamedResourceFragment( String headerFragmentName, HashMap namedResourcesAddedFragmentsDefault, String[] registryContent ) + + protected boolean canAddHeaderNamedResourceFragment( + String headerFragmentName, + HashMap namedResourcesAddedFragmentsDefault, + String[] registryContent) { - if ( headerFragmentName != null && ! namedResourcesAddedFragmentsDefault.containsKey( headerFragmentName ) ) + if (headerFragmentName != null + && !namedResourcesAddedFragmentsDefault + .containsKey(headerFragmentName)) { - namedResourcesAddedFragmentsDefault.put( headerFragmentName, Boolean.TRUE ); - if ( registryContent != null ) + namedResourcesAddedFragmentsDefault.put(headerFragmentName, + Boolean.TRUE); + if (registryContent != null) { - String registryContentVal = (String)this.headerResourceRegistry.get( headerFragmentName ); + String registryContentVal = (String) this.headerResourceRegistry + .get(headerFragmentName); registryContent[0] = registryContentVal; - if ( registryContentVal != null ) + if (registryContentVal != null) { - this.headerResourceRegistry.remove( headerFragmentName ); + this.headerResourceRegistry.remove(headerFragmentName); } } return true; } - if ( registryContent != null ) + if (registryContent != null) { registryContent[0] = null; } return false; } - - protected void initializeDesktopHeaderConfigurationDefaults( Map desktopConfigMap, HashMap namedResourcesDefault, HashMap namedResourcesAddedFragmentsDefault, HashMap headerDynamicConfigurationDefault ) + + protected void initializeDesktopHeaderConfigurationDefaults( + Map desktopConfigMap, HashMap namedResourcesDefault, + HashMap namedResourcesAddedFragmentsDefault, + HashMap headerDynamicConfigurationDefault) { - if ( desktopConfigMap == null ) + if (desktopConfigMap == null) { desktopConfigMap = new HashMap(); } - + StringBuffer desktopDojoConfigContent = new StringBuffer(); - + String layoutDecorationDefaultName = HeaderResource.HEADER_CONFIG_DESKTOP_LAYOUT_DECORATION_DEFAULT; - String layoutDecoration = (String)desktopConfigMap.get( layoutDecorationDefaultName ); - if ( layoutDecoration != null && layoutDecoration.length() > 0 ) + String layoutDecoration = (String) desktopConfigMap + .get(layoutDecorationDefaultName); + if (layoutDecoration != null && layoutDecoration.length() > 0) { - decorationFactory.setDefaultDesktopLayoutDecoration( layoutDecoration ); + decorationFactory + .setDefaultDesktopLayoutDecoration(layoutDecoration); } - + String portletDecorationDefaultName = HeaderResource.HEADER_CONFIG_DESKTOP_PORTLET_DECORATION_DEFAULT; - String portletDecoration = (String)desktopConfigMap.get( portletDecorationDefaultName ); - if ( portletDecoration == null || portletDecoration.length() == 0 ) + String portletDecoration = (String) desktopConfigMap + .get(portletDecorationDefaultName); + if (portletDecoration == null || portletDecoration.length() == 0) { - portletDecoration = decorationFactory.getDefaultDesktopPortletDecoration(); + portletDecoration = decorationFactory + .getDefaultDesktopPortletDecoration(); } - if ( portletDecoration != null && portletDecoration.length() > 0 ) + if (portletDecoration != null && portletDecoration.length() > 0) { - if ( canAddHeaderNamedResourceFragment( portletDecorationDefaultName, namedResourcesAddedFragmentsDefault, null ) ) + if (canAddHeaderNamedResourceFragment(portletDecorationDefaultName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME ).append( ".windowDecoration = \"" ).append( portletDecoration ).append( "\";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME) + .append(".windowDecoration = \"").append( + portletDecoration).append("\";").append(EOL); } - decorationFactory.setDefaultDesktopPortletDecoration( portletDecoration ); + decorationFactory + .setDefaultDesktopPortletDecoration(portletDecoration); } - + String desktopPageAjaxNavName = HeaderResource.HEADER_CONFIG_DESKTOP_PAGE_AJAXNAVIGATION; - String desktopPageAjaxNav = HeaderResourceLib.makeJSONBoolean( desktopConfigMap.get( desktopPageAjaxNavName ) ); - if ( desktopPageAjaxNav != null && canAddHeaderNamedResourceFragment( desktopPageAjaxNavName, namedResourcesAddedFragmentsDefault, null ) ) + String desktopPageAjaxNav = HeaderResourceLib + .makeJSONBoolean(desktopConfigMap.get(desktopPageAjaxNavName)); + if (desktopPageAjaxNav != null + && canAddHeaderNamedResourceFragment(desktopPageAjaxNavName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME ).append( ".ajaxPageNavigation = " ).append( desktopPageAjaxNav ).append( ";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME) + .append(".ajaxPageNavigation = ") + .append(desktopPageAjaxNav).append(";").append(EOL); } - + String desktopWindowTilingName = HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_TILING; - String desktopWindowTiling = HeaderResourceLib.makeJSONBoolean( desktopConfigMap.get( desktopWindowTilingName ) ); - if ( desktopWindowTiling != null && canAddHeaderNamedResourceFragment( desktopWindowTilingName, namedResourcesAddedFragmentsDefault, null ) ) + String desktopWindowTiling = HeaderResourceLib + .makeJSONBoolean(desktopConfigMap.get(desktopWindowTilingName)); + if (desktopWindowTiling != null + && canAddHeaderNamedResourceFragment(desktopWindowTilingName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME ).append( ".windowTiling = " ).append( desktopWindowTiling ).append( ";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME) + .append(".windowTiling = ").append(desktopWindowTiling) + .append(";").append(EOL); } - + String desktopWindowHeightExpandName = HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_HEIGHT_EXPAND; - String desktopWindowHeightExpand = HeaderResourceLib.makeJSONBoolean( desktopConfigMap.get( desktopWindowHeightExpandName ) ); - if ( desktopWindowHeightExpand != null && canAddHeaderNamedResourceFragment( desktopWindowHeightExpandName, namedResourcesAddedFragmentsDefault, null ) ) + String desktopWindowHeightExpand = HeaderResourceLib + .makeJSONBoolean(desktopConfigMap + .get(desktopWindowHeightExpandName)); + if (desktopWindowHeightExpand != null + && canAddHeaderNamedResourceFragment( + desktopWindowHeightExpandName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME ).append( ".windowHeightExpand = " ).append( desktopWindowHeightExpand ).append( ";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME) + .append(".windowHeightExpand = ").append( + desktopWindowHeightExpand).append(";").append(EOL); } String desktopWindowHeightName = HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_HEIGHT; - String desktopWindowHeight = HeaderResourceLib.makeJSONInteger( desktopConfigMap.get( desktopWindowHeightName ), true ); - if ( desktopWindowHeight != null && canAddHeaderNamedResourceFragment( desktopWindowHeightName, namedResourcesAddedFragmentsDefault, null ) ) + String desktopWindowHeight = HeaderResourceLib.makeJSONInteger( + desktopConfigMap.get(desktopWindowHeightName), true); + if (desktopWindowHeight != null + && canAddHeaderNamedResourceFragment(desktopWindowHeightName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME ).append( ".windowHeight = " ).append( desktopWindowHeight ).append( ";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME) + .append(".windowHeight = ").append(desktopWindowHeight) + .append(";").append(EOL); } - + String desktopWindowWidthName = HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_WIDTH; - String desktopWindowWidth = HeaderResourceLib.makeJSONInteger( desktopConfigMap.get( desktopWindowWidthName ), true ); - if ( desktopWindowWidth != null && canAddHeaderNamedResourceFragment( desktopWindowWidthName, namedResourcesAddedFragmentsDefault, null ) ) + String desktopWindowWidth = HeaderResourceLib.makeJSONInteger( + desktopConfigMap.get(desktopWindowWidthName), true); + if (desktopWindowWidth != null + && canAddHeaderNamedResourceFragment(desktopWindowWidthName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME ).append( ".windowWidth = " ).append( desktopWindowWidth ).append( ";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME) + .append(".windowWidth = ").append(desktopWindowWidth) + .append(";").append(EOL); } - + List actionList = new ArrayList(); - + String windowActionButtonOrderName = HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ACTION_BUTTON_ORDER; - String actionButtonOrderContent = HeaderResourceLib.makeJSONStringArray( (List)desktopConfigMap.get( windowActionButtonOrderName ), actionList ); - if ( actionButtonOrderContent != null && actionButtonOrderContent.length() > 0 ) + String actionButtonOrderContent = HeaderResourceLib + .makeJSONStringArray((List) desktopConfigMap + .get(windowActionButtonOrderName), actionList); + if (actionButtonOrderContent != null + && actionButtonOrderContent.length() > 0) { - if ( canAddHeaderNamedResourceFragment( windowActionButtonOrderName, namedResourcesAddedFragmentsDefault, null ) ) + if (canAddHeaderNamedResourceFragment(windowActionButtonOrderName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE ).append( HeaderResource.DESKTOP_JSON_WINDOW_ACTION_BUTTON_ORDER ).append( " = " ).append( actionButtonOrderContent ).append( ";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE) + .append( + HeaderResource.DESKTOP_JSON_WINDOW_ACTION_BUTTON_ORDER) + .append(" = ").append(actionButtonOrderContent).append( + ";").append(EOL); } } - + String windowActionNoImageName = HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ACTION_NOIMAGE; - String actionNoImageContent = HeaderResourceLib.makeJSONStringArray( (List)desktopConfigMap.get( windowActionNoImageName ), actionList ); - if ( actionNoImageContent != null && actionNoImageContent.length() > 0 ) + String actionNoImageContent = HeaderResourceLib.makeJSONStringArray( + (List) desktopConfigMap.get(windowActionNoImageName), + actionList); + if (actionNoImageContent != null && actionNoImageContent.length() > 0) { - if ( canAddHeaderNamedResourceFragment( windowActionNoImageName, namedResourcesAddedFragmentsDefault, null ) ) + if (canAddHeaderNamedResourceFragment(windowActionNoImageName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE ).append( HeaderResource.DESKTOP_JSON_WINDOW_ACTION_NOIMAGE ).append( " = " ).append( actionNoImageContent ).append( ";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE) + .append( + HeaderResource.DESKTOP_JSON_WINDOW_ACTION_NOIMAGE) + .append(" = ").append(actionNoImageContent).append(";") + .append(EOL); } } - + String windowActionMenuOrderName = HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ACTION_MENU_ORDER; - String actionMenuOrderContent = HeaderResourceLib.makeJSONStringArray( (List)desktopConfigMap.get( windowActionMenuOrderName ), actionList ); - if ( actionMenuOrderContent != null && actionMenuOrderContent.length() > 0 ) + String actionMenuOrderContent = HeaderResourceLib.makeJSONStringArray( + (List) desktopConfigMap.get(windowActionMenuOrderName), + actionList); + if (actionMenuOrderContent != null + && actionMenuOrderContent.length() > 0) { - if ( canAddHeaderNamedResourceFragment( windowActionMenuOrderName, namedResourcesAddedFragmentsDefault, null ) ) + if (canAddHeaderNamedResourceFragment(windowActionMenuOrderName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE ).append( HeaderResource.DESKTOP_JSON_WINDOW_ACTION_MENU_ORDER ).append( " = " ).append( actionMenuOrderContent ).append( ";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE) + .append( + HeaderResource.DESKTOP_JSON_WINDOW_ACTION_MENU_ORDER) + .append(" = ").append(actionMenuOrderContent).append( + ";").append(EOL); } } - headerDynamicConfigurationDefault.put( HeaderResource.HEADER_INTERNAL_CONFIG_DESKTOP_WINDOW_ACTION, actionList ); - + headerDynamicConfigurationDefault.put( + HeaderResource.HEADER_INTERNAL_CONFIG_DESKTOP_WINDOW_ACTION, + actionList); + String windowActionButtonTooltipName = HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ACTION_BUTTON_TOOLTIP; - String windowActionButtonTooltip = HeaderResourceLib.makeJSONBoolean( desktopConfigMap.get( windowActionButtonTooltipName ) ); - if ( windowActionButtonTooltip != null && canAddHeaderNamedResourceFragment( windowActionButtonTooltipName, namedResourcesAddedFragmentsDefault, null ) ) + String windowActionButtonTooltip = HeaderResourceLib + .makeJSONBoolean(desktopConfigMap + .get(windowActionButtonTooltipName)); + if (windowActionButtonTooltip != null + && canAddHeaderNamedResourceFragment( + windowActionButtonTooltipName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE ).append( HeaderResource.DESKTOP_JSON_WINDOW_ACTION_BUTTON_TOOLTIP ).append( " = " ).append( windowActionButtonTooltip ).append( ";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE) + .append( + HeaderResource.DESKTOP_JSON_WINDOW_ACTION_BUTTON_TOOLTIP) + .append(" = ").append(windowActionButtonTooltip) + .append(";").append(EOL); } String windowActionButtonMaxName = HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ACTION_BUTTON_MAX; - String windowActionButtonMax = HeaderResourceLib.makeJSONInteger( desktopConfigMap.get( windowActionButtonMaxName ), false ); - if ( windowActionButtonMax != null && canAddHeaderNamedResourceFragment( windowActionButtonMaxName, namedResourcesAddedFragmentsDefault, null ) ) + String windowActionButtonMax = HeaderResourceLib.makeJSONInteger( + desktopConfigMap.get(windowActionButtonMaxName), false); + if (windowActionButtonMax != null + && canAddHeaderNamedResourceFragment(windowActionButtonMaxName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE ).append( HeaderResource.DESKTOP_JSON_WINDOW_ACTION_BUTTON_MAX ).append( " = " ).append( windowActionButtonMax ).append( ";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE) + .append( + HeaderResource.DESKTOP_JSON_WINDOW_ACTION_BUTTON_MAX) + .append(" = ").append(windowActionButtonMax).append(";") + .append(EOL); } - + String windowIconEnabledName = HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ICON_ENABLED; - String iconEnabledContent = HeaderResourceLib.makeJSONBoolean( desktopConfigMap.get( windowIconEnabledName ) ); - if ( iconEnabledContent != null && iconEnabledContent.length() > 0 ) + String iconEnabledContent = HeaderResourceLib + .makeJSONBoolean(desktopConfigMap.get(windowIconEnabledName)); + if (iconEnabledContent != null && iconEnabledContent.length() > 0) { - if ( canAddHeaderNamedResourceFragment( windowIconEnabledName, namedResourcesAddedFragmentsDefault, null ) ) + if (canAddHeaderNamedResourceFragment(windowIconEnabledName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE ).append( HeaderResource.DESKTOP_JSON_WINDOW_ICON_ENABLED ).append( " = " ).append( iconEnabledContent ).append( ";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE) + .append(HeaderResource.DESKTOP_JSON_WINDOW_ICON_ENABLED) + .append(" = ").append(iconEnabledContent).append(";") + .append(EOL); } } - + String windowIconPathName = HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ICON_PATH; - String iconPathContent = (String)desktopConfigMap.get( windowIconPathName ); - if ( iconPathContent != null && iconPathContent.length() > 0 ) + String iconPathContent = (String) desktopConfigMap + .get(windowIconPathName); + if (iconPathContent != null && iconPathContent.length() > 0) { - if ( canAddHeaderNamedResourceFragment( windowIconPathName, namedResourcesAddedFragmentsDefault, null ) ) + if (canAddHeaderNamedResourceFragment(windowIconPathName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE ).append( HeaderResource.DESKTOP_JSON_WINDOW_ICON_PATH ).append( " = \"" ).append( iconPathContent ).append( "\";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE) + .append(HeaderResource.DESKTOP_JSON_WINDOW_ICON_PATH) + .append(" = \"").append(iconPathContent).append("\";") + .append(EOL); } } - + String windowTitlebarEnabledName = HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_TITLEBAR_ENABLED; - String titlebarEnabledContent = HeaderResourceLib.makeJSONBoolean( desktopConfigMap.get( windowTitlebarEnabledName ) ); - if ( titlebarEnabledContent != null && titlebarEnabledContent.length() > 0 ) + String titlebarEnabledContent = HeaderResourceLib + .makeJSONBoolean(desktopConfigMap + .get(windowTitlebarEnabledName)); + if (titlebarEnabledContent != null + && titlebarEnabledContent.length() > 0) { - if ( canAddHeaderNamedResourceFragment( windowTitlebarEnabledName, namedResourcesAddedFragmentsDefault, null ) ) + if (canAddHeaderNamedResourceFragment(windowTitlebarEnabledName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE ).append( HeaderResource.DESKTOP_JSON_WINDOW_TITLEBAR_ENABLED ).append( " = " ).append( titlebarEnabledContent ).append( ";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE) + .append( + HeaderResource.DESKTOP_JSON_WINDOW_TITLEBAR_ENABLED) + .append(" = ").append(titlebarEnabledContent).append( + ";").append(EOL); } } - + String windowResizebarEnabledName = HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_RESIZEBAR_ENABLED; - String resizebarEnabledContent = HeaderResourceLib.makeJSONBoolean( desktopConfigMap.get( windowResizebarEnabledName ) ); - if ( resizebarEnabledContent != null && resizebarEnabledContent.length() > 0 ) + String resizebarEnabledContent = HeaderResourceLib + .makeJSONBoolean(desktopConfigMap + .get(windowResizebarEnabledName)); + if (resizebarEnabledContent != null + && resizebarEnabledContent.length() > 0) { - if ( canAddHeaderNamedResourceFragment( windowResizebarEnabledName, namedResourcesAddedFragmentsDefault, null ) ) + if (canAddHeaderNamedResourceFragment(windowResizebarEnabledName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE ).append( HeaderResource.DESKTOP_JSON_WINDOW_TITLEBAR_ENABLED ).append( " = " ).append( resizebarEnabledContent ).append( ";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE) + .append( + HeaderResource.DESKTOP_JSON_WINDOW_TITLEBAR_ENABLED) + .append(" = ").append(resizebarEnabledContent).append( + ";").append(EOL); } } - + String pageActionButtonTooltipName = HeaderResource.HEADER_CONFIG_DESKTOP_PAGE_ACTION_BUTTON_TOOLTIP; - String pageActionButtonTooltip = HeaderResourceLib.makeJSONBoolean( desktopConfigMap.get( pageActionButtonTooltipName ) ); - if ( pageActionButtonTooltip != null && canAddHeaderNamedResourceFragment( pageActionButtonTooltipName, namedResourcesAddedFragmentsDefault, null ) ) + String pageActionButtonTooltip = HeaderResourceLib + .makeJSONBoolean(desktopConfigMap + .get(pageActionButtonTooltipName)); + if (pageActionButtonTooltip != null + && canAddHeaderNamedResourceFragment( + pageActionButtonTooltipName, + namedResourcesAddedFragmentsDefault, null)) { - desktopDojoConfigContent.append( " " ).append( HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME ).append( ".pageActionButtonTooltip = " ).append( pageActionButtonTooltip ).append( ";" ).append( EOL ); + desktopDojoConfigContent + .append(" ") + .append( + HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME) + .append(".pageActionButtonTooltip = ").append( + pageActionButtonTooltip).append(";").append(EOL); } - if ( desktopDojoConfigContent.length() > 0 ) + if (desktopDojoConfigContent.length() > 0) { - namedResourcesDefault.put( HeaderResource.HEADER_SECTION_DOJO_CONFIG, desktopDojoConfigContent.toString() ); + namedResourcesDefault.put( + HeaderResource.HEADER_SECTION_DOJO_CONFIG, + desktopDojoConfigContent.toString()); } - + StringBuffer desktopInitScript = new StringBuffer(); - desktopInitScript.append( " function doRender(bindArgs,portletEntityId) { " ); - desktopInitScript.append( "jetspeed.doRender(bindArgs,portletEntityId); }" ).append( EOL ); - desktopInitScript.append( " function doAction(bindArgs,portletEntityId) { " ); - desktopInitScript.append( "jetspeed.doAction(bindArgs,portletEntityId); }" ).append( EOL ); - desktopInitScript.append( " dojo.addOnLoad( jetspeed.initializeDesktop );" ).append( EOL ); - if ( canAddHeaderNamedResourceFragment( "desktop.init", namedResourcesAddedFragmentsDefault, null ) ) + desktopInitScript + .append(" function doRender(bindArgs,portletEntityId) { "); + desktopInitScript.append( + "jetspeed.doRender(bindArgs,portletEntityId); }").append(EOL); + desktopInitScript + .append(" function doAction(bindArgs,portletEntityId) { "); + desktopInitScript.append( + "jetspeed.doAction(bindArgs,portletEntityId); }").append(EOL); + desktopInitScript.append( + " dojo.addOnLoad( jetspeed.initializeDesktop );") + .append(EOL); + if (canAddHeaderNamedResourceFragment("desktop.init", + namedResourcesAddedFragmentsDefault, null)) { - namedResourcesDefault.put( HeaderResource.HEADER_SECTION_DESKTOP_INIT, desktopInitScript.toString() ); - setNamedHeaderResourceProperties( HeaderResource.HEADER_SECTION_DESKTOP_INIT, HeaderResource.HEADER_TYPE_SCRIPT_BLOCK_START, null, headerDynamicConfigurationDefault ); + namedResourcesDefault.put( + HeaderResource.HEADER_SECTION_DESKTOP_INIT, + desktopInitScript.toString()); + setNamedHeaderResourceProperties( + HeaderResource.HEADER_SECTION_DESKTOP_INIT, + HeaderResource.HEADER_TYPE_SCRIPT_BLOCK_START, null, + headerDynamicConfigurationDefault); } } - + /** - * Read dojo header configuration settings and compile dojo header resource defaults + * Read dojo header configuration settings and compile dojo header resource + * defaults */ - protected void initializeDojoHeaderConfigurationDefaults( Map dojoConfigMap, HashMap namedResourcesDefault, HashMap namedResourcesAddedFragmentsDefault, HashMap headerDynamicConfigurationDefault ) + protected void initializeDojoHeaderConfigurationDefaults(Map dojoConfigMap, + HashMap namedResourcesDefault, + HashMap namedResourcesAddedFragmentsDefault, + HashMap headerDynamicConfigurationDefault) { - if ( dojoConfigMap == null ) + if (dojoConfigMap == null) { dojoConfigMap = new HashMap(); } - String[] registryContent = new String[] { null }; - + String[] registryContent = new String[] + {null}; + // add dojo.enable and dojo.path to dynamic configuration String dojoEnableName = HeaderResource.HEADER_CONFIG_DOJO_ENABLE; - Object dojoEnableObj = dojoConfigMap.get( dojoEnableName ); - String dojoEnable = ( ( dojoEnableObj == null ) ? (String)null : dojoEnableObj.toString() ); - if ( dojoEnable == null || ! dojoEnable.equals( "true" ) ) + Object dojoEnableObj = dojoConfigMap.get(dojoEnableName); + String dojoEnable = ((dojoEnableObj == null) ? (String) null + : dojoEnableObj.toString()); + if (dojoEnable == null || !dojoEnable.equals("true")) { dojoEnable = "false"; } - headerDynamicConfigurationDefault.put( dojoEnableName, dojoEnable ); - String dojoPath = (String)dojoConfigMap.get( HeaderResource.HEADER_CONFIG_DOJO_PATH ); - if ( dojoPath == null || dojoPath.length() == 0 ) + headerDynamicConfigurationDefault.put(dojoEnableName, dojoEnable); + String dojoPath = (String) dojoConfigMap + .get(HeaderResource.HEADER_CONFIG_DOJO_PATH); + if (dojoPath == null || dojoPath.length() == 0) { dojoPath = "/javascript/dojo/"; } - headerDynamicConfigurationDefault.put( HeaderResource.HEADER_CONFIG_DOJO_PATH, dojoPath ); - + headerDynamicConfigurationDefault.put( + HeaderResource.HEADER_CONFIG_DOJO_PATH, dojoPath); + // dojo parameters - djConfig parameters boolean dojoDebugEnabled = false; - String dojoParamDebug = (String)dojoConfigMap.get( HeaderResource.HEADER_CONFIG_DOJO_PARAM_ISDEBUG ); + String dojoParamDebug = (String) dojoConfigMap + .get(HeaderResource.HEADER_CONFIG_DOJO_PARAM_ISDEBUG); String dojoParamDebugAtAllCosts = null; - if ( dojoParamDebug != null ) - dojoParamDebug = dojoParamDebug.toLowerCase(); - if ( dojoParamDebug == null || dojoParamDebug.length() == 0 || dojoParamDebug.equals( "false" ) ) + if (dojoParamDebug != null) + dojoParamDebug = dojoParamDebug.toLowerCase(); + if (dojoParamDebug == null || dojoParamDebug.length() == 0 + || dojoParamDebug.equals("false")) { - dojoParamDebug = null; + dojoParamDebug = null; } - else if ( dojoParamDebug.equals( "true" ) ) + else if (dojoParamDebug.equals("true")) { - dojoDebugEnabled = true; - dojoParamDebugAtAllCosts = (String)dojoConfigMap.get( HeaderResource.HEADER_CONFIG_DOJO_PARAM_DEBUGALLCOSTS ); - if ( dojoParamDebugAtAllCosts != null ) - { - dojoParamDebugAtAllCosts = dojoParamDebugAtAllCosts.toLowerCase(); - if ( ! dojoParamDebugAtAllCosts.equals( "true") ) - { - dojoParamDebugAtAllCosts = null; - } - } + dojoDebugEnabled = true; + dojoParamDebugAtAllCosts = (String) dojoConfigMap + .get(HeaderResource.HEADER_CONFIG_DOJO_PARAM_DEBUGALLCOSTS); + if (dojoParamDebugAtAllCosts != null) + { + dojoParamDebugAtAllCosts = dojoParamDebugAtAllCosts + .toLowerCase(); + if (!dojoParamDebugAtAllCosts.equals("true")) + { + dojoParamDebugAtAllCosts = null; + } + } } - - String dojoParamPreventBackBtnFix = (String)dojoConfigMap.get( HeaderResource.HEADER_CONFIG_DOJO_PARAM_PREVENT_BACKBUTTON_FIX ); - String dojoParams = (String)dojoConfigMap.get( HeaderResource.HEADER_CONFIG_DOJO_PARAMS ); - if ( dojoParamDebug != null || dojoParamDebugAtAllCosts != null || dojoParamPreventBackBtnFix != null || dojoParams != null ) + + String dojoParamPreventBackBtnFix = (String) dojoConfigMap + .get(HeaderResource.HEADER_CONFIG_DOJO_PARAM_PREVENT_BACKBUTTON_FIX); + String dojoParams = (String) dojoConfigMap + .get(HeaderResource.HEADER_CONFIG_DOJO_PARAMS); + if (dojoParamDebug != null || dojoParamDebugAtAllCosts != null + || dojoParamPreventBackBtnFix != null || dojoParams != null) { StringBuffer dojoConfigContent = new StringBuffer(); boolean addedMembers = false; - if ( dojoParams != null && dojoParams.length() > 0 ) + if (dojoParams != null && dojoParams.length() > 0) { - dojoConfigContent.append( dojoParams ); + dojoConfigContent.append(dojoParams); addedMembers = true; } - if ( dojoParamDebug != null && dojoParamDebug.length() > 0 ) + if (dojoParamDebug != null && dojoParamDebug.length() > 0) { - if ( addedMembers ) + if (addedMembers) { - dojoConfigContent.append( ", " ); + dojoConfigContent.append(", "); } - dojoConfigContent.append( "isDebug: " ).append( dojoParamDebug ) ; + dojoConfigContent.append("isDebug: ").append(dojoParamDebug); addedMembers = true; } - if ( dojoParamDebugAtAllCosts != null && dojoParamDebugAtAllCosts.length() > 0 ) + if (dojoParamDebugAtAllCosts != null + && dojoParamDebugAtAllCosts.length() > 0) { - if ( addedMembers ) + if (addedMembers) { - dojoConfigContent.append( ", " ); + dojoConfigContent.append(", "); } - dojoConfigContent.append( "debugAtAllCosts: " ).append( dojoParamDebugAtAllCosts ) ; + dojoConfigContent.append("debugAtAllCosts: ").append( + dojoParamDebugAtAllCosts); addedMembers = true; } - if ( dojoParamPreventBackBtnFix != null && dojoParamPreventBackBtnFix.length() > 0 ) + if (dojoParamPreventBackBtnFix != null + && dojoParamPreventBackBtnFix.length() > 0) { - if ( addedMembers ) + if (addedMembers) { - dojoConfigContent.append( ", " ); + dojoConfigContent.append(", "); } - dojoConfigContent.append( "preventBackButtonFix: " ).append( dojoParamPreventBackBtnFix ) ; + dojoConfigContent.append("preventBackButtonFix: ").append( + dojoParamPreventBackBtnFix); addedMembers = true; } - if ( addedMembers ) + if (addedMembers) { - dojoConfigContent.append( ", " ); + dojoConfigContent.append(", "); } - dojoConfigContent.append( HeaderResource.HEADER_INTERNAL_JETSPEED_VAR_NAME ).append( ": {}" ) ; + dojoConfigContent.append( + HeaderResource.HEADER_INTERNAL_JETSPEED_VAR_NAME).append( + ": {}"); addedMembers = true; - - if ( canAddHeaderNamedResourceFragment( HeaderResource.HEADER_CONFIG_DOJO_PARAMS, namedResourcesAddedFragmentsDefault, registryContent ) ) + + if (canAddHeaderNamedResourceFragment( + HeaderResource.HEADER_CONFIG_DOJO_PARAMS, + namedResourcesAddedFragmentsDefault, registryContent)) { String dojoParamContent = dojoConfigContent.toString(); - if ( registryContent[0] != null ) + if (registryContent[0] != null) { dojoParamContent = registryContent[0]; } - if ( dojoParamContent.length() > 0 ) + if (dojoParamContent.length() > 0) { - namedResourcesDefault.put( HeaderResource.HEADER_SECTION_DOJO_PARAMETERS, ( " var djConfig = {" + dojoParamContent + "};" + EOL ) ); + namedResourcesDefault + .put(HeaderResource.HEADER_SECTION_DOJO_PARAMETERS, + (" var djConfig = {" + dojoParamContent + + "};" + EOL)); } } - registerAndOrderNamedHeaderResource( HeaderResource.HEADER_SECTION_DOJO_PARAMETERS, HeaderResource.HEADER_TYPE_SCRIPT_BLOCK_START, dojoEnableName, headerDynamicConfigurationDefault ); + registerAndOrderNamedHeaderResource( + HeaderResource.HEADER_SECTION_DOJO_PARAMETERS, + HeaderResource.HEADER_TYPE_SCRIPT_BLOCK_START, + dojoEnableName, headerDynamicConfigurationDefault); } - - // dojo preinit - for automatically added members to djConfig (eg. djConfig.baseScriptUri="...") - // - adding to order only at this point - // - if header contains content, generated content will not be added - registerAndOrderNamedHeaderResource( HeaderResource.HEADER_SECTION_DOJO_PREINIT, null, dojoEnableName, headerDynamicConfigurationDefault ); - - // dojo config - for adding members to djConfig (eg. djConfig.parseWidgets=false) - // - adding to order only at this point - registerAndOrderNamedHeaderResource( HeaderResource.HEADER_SECTION_DOJO_CONFIG, null, dojoEnableName, headerDynamicConfigurationDefault ); - + + // dojo preinit - for automatically added members to djConfig (eg. + // djConfig.baseScriptUri="...") + // - adding to order only at this point + // - if header contains content, generated content will not be added + registerAndOrderNamedHeaderResource( + HeaderResource.HEADER_SECTION_DOJO_PREINIT, null, + dojoEnableName, headerDynamicConfigurationDefault); + + // dojo config - for adding members to djConfig (eg. + // djConfig.parseWidgets=false) + // - adding to order only at this point + registerAndOrderNamedHeaderResource( + HeaderResource.HEADER_SECTION_DOJO_CONFIG, null, + dojoEnableName, headerDynamicConfigurationDefault); + // dojo init - script tag for dojo.js - // - adding to order only at this point - // - if header contains content, generated content will not be added - registerAndOrderNamedHeaderResource( HeaderResource.HEADER_SECTION_DOJO_INIT, HeaderResource.HEADER_TYPE_SCRIPT_TAG, dojoEnableName, headerDynamicConfigurationDefault ); - + // - adding to order only at this point + // - if header contains content, generated content will not be added + registerAndOrderNamedHeaderResource( + HeaderResource.HEADER_SECTION_DOJO_INIT, + HeaderResource.HEADER_TYPE_SCRIPT_TAG, dojoEnableName, + headerDynamicConfigurationDefault); + // dojo requires - core libraries - List dojoRequiresCore = (List)dojoConfigMap.get( HeaderResource.HEADER_CONFIG_DOJO_REQUIRES_CORE ); - if ( dojoRequiresCore != null && dojoRequiresCore.size() > 0 ) + List dojoRequiresCore = (List) dojoConfigMap + .get(HeaderResource.HEADER_CONFIG_DOJO_REQUIRES_CORE); + if (dojoRequiresCore != null && dojoRequiresCore.size() > 0) { StringBuffer dojoRequiresContent = new StringBuffer(); Iterator dojoRequiresCoreIter = dojoRequiresCore.iterator(); - while ( dojoRequiresCoreIter.hasNext() ) + while (dojoRequiresCoreIter.hasNext()) { - String dojoReq = (String)dojoRequiresCoreIter.next(); - if ( dojoReq != null && dojoReq.length() > 0 ) + String dojoReq = (String) dojoRequiresCoreIter.next(); + if (dojoReq != null && dojoReq.length() > 0) { - if ( canAddHeaderNamedResourceFragment( dojoReq, namedResourcesAddedFragmentsDefault, registryContent ) ) + if (canAddHeaderNamedResourceFragment(dojoReq, + namedResourcesAddedFragmentsDefault, + registryContent)) { - if ( registryContent[0] != null ) + if (registryContent[0] != null) { - String dojoReqFromRegistry = HeaderResourceLib.makeJavascriptStatement( registryContent[0], " ", true ); - if ( dojoReqFromRegistry.length() > 0 ) + String dojoReqFromRegistry = HeaderResourceLib + .makeJavascriptStatement( + registryContent[0], " ", true); + if (dojoReqFromRegistry.length() > 0) { - dojoRequiresContent.append( registryContent[0] ); + dojoRequiresContent.append(registryContent[0]); } } else { - dojoRequiresContent.append( " dojo.require(\"").append( dojoReq ).append( "\");" ).append( EOL ); + dojoRequiresContent.append(" dojo.require(\"") + .append(dojoReq).append("\");").append(EOL); } } } } - namedResourcesDefault.put( HeaderResource.HEADER_SECTION_DOJO_REQUIRES_CORE, dojoRequiresContent.toString() ); - registerAndOrderNamedHeaderResource( HeaderResource.HEADER_SECTION_DOJO_REQUIRES_CORE, null, dojoEnableName, headerDynamicConfigurationDefault ); + namedResourcesDefault.put( + HeaderResource.HEADER_SECTION_DOJO_REQUIRES_CORE, + dojoRequiresContent.toString()); + registerAndOrderNamedHeaderResource( + HeaderResource.HEADER_SECTION_DOJO_REQUIRES_CORE, null, + dojoEnableName, headerDynamicConfigurationDefault); } - + // dojo modules path definition - List dojoModulesPath = (List)dojoConfigMap.get( HeaderResource.HEADER_CONFIG_DOJO_MODULES_PATH ); - if ( dojoModulesPath != null && dojoModulesPath.size() > 0 ) + List dojoModulesPath = (List) dojoConfigMap + .get(HeaderResource.HEADER_CONFIG_DOJO_MODULES_PATH); + if (dojoModulesPath != null && dojoModulesPath.size() > 0) { StringBuffer dojoModulesPathContent = new StringBuffer(); boolean addedContent = false; Iterator dojoModulesPathIter = dojoModulesPath.iterator(); - while ( dojoModulesPathIter.hasNext() ) + while (dojoModulesPathIter.hasNext()) { - String dojoModule = (String)dojoModulesPathIter.next(); - if ( dojoModule != null && dojoModule.length() > 0 ) + String dojoModule = (String) dojoModulesPathIter.next(); + if (dojoModule != null && dojoModule.length() > 0) { - if ( canAddHeaderNamedResourceFragment( dojoModule, namedResourcesAddedFragmentsDefault, registryContent ) ) + if (canAddHeaderNamedResourceFragment(dojoModule, + namedResourcesAddedFragmentsDefault, + registryContent)) { String dojoModuleContent = null; - if ( registryContent[0] != null ) + if (registryContent[0] != null) { dojoModuleContent = registryContent[0]; } @@ -852,38 +1214,48 @@ { dojoModuleContent = dojoModule; } - dojoModuleContent = HeaderResourceLib.makeJavascriptStatement( dojoModuleContent, " ", true ); - if ( dojoModuleContent.length() > 0 ) + dojoModuleContent = HeaderResourceLib + .makeJavascriptStatement(dojoModuleContent, + " ", true); + if (dojoModuleContent.length() > 0) { - dojoModulesPathContent.append( dojoModuleContent ); + dojoModulesPathContent.append(dojoModuleContent); addedContent = true; } } } } - if ( addedContent ) + if (addedContent) { - namedResourcesDefault.put( HeaderResource.HEADER_SECTION_DOJO_MODULES_PATH, dojoModulesPathContent.toString() ); - registerAndOrderNamedHeaderResource( HeaderResource.HEADER_SECTION_DOJO_MODULES_PATH, null, dojoEnableName, headerDynamicConfigurationDefault ); + namedResourcesDefault.put( + HeaderResource.HEADER_SECTION_DOJO_MODULES_PATH, + dojoModulesPathContent.toString()); + registerAndOrderNamedHeaderResource( + HeaderResource.HEADER_SECTION_DOJO_MODULES_PATH, null, + dojoEnableName, headerDynamicConfigurationDefault); } } - + // dojo modules namespace definition - List dojoModulesNamespace = (List)dojoConfigMap.get( HeaderResource.HEADER_CONFIG_DOJO_MODULES_NAMESPACE ); - if ( dojoModulesNamespace != null && dojoModulesNamespace.size() > 0 ) + List dojoModulesNamespace = (List) dojoConfigMap + .get(HeaderResource.HEADER_CONFIG_DOJO_MODULES_NAMESPACE); + if (dojoModulesNamespace != null && dojoModulesNamespace.size() > 0) { StringBuffer dojoModulesNamespaceContent = new StringBuffer(); boolean addedContent = false; Iterator dojoModulesNamespaceIter = dojoModulesNamespace.iterator(); - while ( dojoModulesNamespaceIter.hasNext() ) + while (dojoModulesNamespaceIter.hasNext()) { - String dojoModuleWidget = (String)dojoModulesNamespaceIter.next(); - if ( dojoModuleWidget != null && dojoModuleWidget.length() > 0 ) + String dojoModuleWidget = (String) dojoModulesNamespaceIter + .next(); + if (dojoModuleWidget != null && dojoModuleWidget.length() > 0) { - if ( canAddHeaderNamedResourceFragment( dojoModuleWidget, namedResourcesAddedFragmentsDefault, registryContent ) ) + if (canAddHeaderNamedResourceFragment(dojoModuleWidget, + namedResourcesAddedFragmentsDefault, + registryContent)) { String dojoModuleContent = null; - if ( registryContent[0] != null ) + if (registryContent[0] != null) { dojoModuleContent = registryContent[0]; } @@ -891,289 +1263,370 @@ { dojoModuleContent = dojoModuleWidget; } - dojoModuleContent = HeaderResourceLib.makeJavascriptStatement( dojoModuleContent, " ", true ); - if ( dojoModuleContent.length() > 0 ) + dojoModuleContent = HeaderResourceLib + .makeJavascriptStatement(dojoModuleContent, + " ", true); + if (dojoModuleContent.length() > 0) { - dojoModulesNamespaceContent.append( dojoModuleContent ); + dojoModulesNamespaceContent + .append(dojoModuleContent); addedContent = true; } } } } - if ( addedContent ) + if (addedContent) { - namedResourcesDefault.put( HeaderResource.HEADER_SECTION_DOJO_MODULES_NAMESPACE, dojoModulesNamespaceContent.toString() ); + namedResourcesDefault.put( + HeaderResource.HEADER_SECTION_DOJO_MODULES_NAMESPACE, + dojoModulesNamespaceContent.toString()); // registerAndOrderNamedHeaderResource called below } } - + // dojo requires - module libraries (from add-on modules) - List dojoRequiresModules = (List)dojoConfigMap.get( HeaderResource.HEADER_CONFIG_DOJO_REQUIRES_MODULES ); - if ( dojoRequiresModules != null && dojoRequiresModules.size() > 0 ) + List dojoRequiresModules = (List) dojoConfigMap + .get(HeaderResource.HEADER_CONFIG_DOJO_REQUIRES_MODULES); + if (dojoRequiresModules != null && dojoRequiresModules.size() > 0) { - HashMap addedReqs = null; - if ( dojoDebugEnabled ) - addedReqs = new HashMap(); + HashMap addedReqs = null; + if (dojoDebugEnabled) addedReqs = new HashMap(); StringBuffer dojoRequiresContent = new StringBuffer(); Iterator dojoRequiresModulesIter = dojoRequiresModules.iterator(); - while ( dojoRequiresModulesIter.hasNext() ) + while (dojoRequiresModulesIter.hasNext()) { - String dojoReq = (String)dojoRequiresModulesIter.next(); - if ( dojoReq != null && dojoReq.length() > 0 ) + String dojoReq = (String) dojoRequiresModulesIter.next(); + if (dojoReq != null && dojoReq.length() > 0) { - if ( canAddHeaderNamedResourceFragment( dojoReq, namedResourcesAddedFragmentsDefault, registryContent ) ) + if (canAddHeaderNamedResourceFragment(dojoReq, + namedResourcesAddedFragmentsDefault, + registryContent)) { - if ( registryContent[0] != null ) + if (registryContent[0] != null) { - String dojoReqFromRegistry = HeaderResourceLib.makeJavascriptStatement( registryContent[0], " ", true ); - if ( dojoReqFromRegistry.length() > 0 ) + String dojoReqFromRegistry = HeaderResourceLib + .makeJavascriptStatement( + registryContent[0], " ", true); + if (dojoReqFromRegistry.length() > 0) { - dojoRequiresContent.append( registryContent[0] ); + dojoRequiresContent.append(registryContent[0]); } } else { - dojoRequiresContent.append( " dojo.require(\"").append( dojoReq ).append( "\");" ).append( EOL ); - if ( dojoDebugEnabled ) - addedReqs.put( dojoReq, dojoReq ); + dojoRequiresContent.append(" dojo.require(\"") + .append(dojoReq).append("\");").append(EOL); + if (dojoDebugEnabled) + addedReqs.put(dojoReq, dojoReq); } } } } - if ( dojoDebugEnabled ) + if (dojoDebugEnabled) { - if ( addedReqs.get( HeaderResource.HEADER_DEBUG_REQUIRES ) == null ) - { - dojoRequiresContent.append( " dojo.require(\"").append( HeaderResource.HEADER_DEBUG_REQUIRES ).append( "\");" ).append( EOL ); - } - } - namedResourcesDefault.put( HeaderResource.HEADER_SECTION_DOJO_REQUIRES_MODULES, dojoRequiresContent.toString() ); - registerAndOrderNamedHeaderResource( HeaderResource.HEADER_SECTION_DOJO_REQUIRES_MODULES, null, dojoEnableName, headerDynamicConfigurationDefault ); + if (addedReqs.get(HeaderResource.HEADER_DEBUG_REQUIRES) == null) + { + dojoRequiresContent.append(" dojo.require(\"").append( + HeaderResource.HEADER_DEBUG_REQUIRES) + .append("\");").append(EOL); + } + } + namedResourcesDefault.put( + HeaderResource.HEADER_SECTION_DOJO_REQUIRES_MODULES, + dojoRequiresContent.toString()); + registerAndOrderNamedHeaderResource( + HeaderResource.HEADER_SECTION_DOJO_REQUIRES_MODULES, null, + dojoEnableName, headerDynamicConfigurationDefault); } - + // dojo writeincludes - // - adding to order only at this point - // - if header contains content, generated content will not be added - registerAndOrderNamedHeaderResource( HeaderResource.HEADER_SECTION_DOJO_WRITEINCLUDES, HeaderResource.HEADER_TYPE_SCRIPT_BLOCK_START, dojoEnableName, headerDynamicConfigurationDefault ); - - // dojo widget module - register widget packages (eg. dojo.widget.manager.registerWidgetPackage('jetspeed.ui.widget')) - // - default resource added above - registerAndOrderNamedHeaderResource( HeaderResource.HEADER_SECTION_DOJO_MODULES_NAMESPACE, HeaderResource.HEADER_TYPE_SCRIPT_BLOCK_START, dojoEnableName, headerDynamicConfigurationDefault ); - + // - adding to order only at this point + // - if header contains content, generated content will not be added + registerAndOrderNamedHeaderResource( + HeaderResource.HEADER_SECTION_DOJO_WRITEINCLUDES, + HeaderResource.HEADER_TYPE_SCRIPT_BLOCK_START, dojoEnableName, + headerDynamicConfigurationDefault); + + // dojo widget module - register widget packages (eg. + // dojo.widget.manager.registerWidgetPackage('jetspeed.ui.widget')) + // - default resource added above + registerAndOrderNamedHeaderResource( + HeaderResource.HEADER_SECTION_DOJO_MODULES_NAMESPACE, + HeaderResource.HEADER_TYPE_SCRIPT_BLOCK_START, dojoEnableName, + headerDynamicConfigurationDefault); + // dojo style bodyexpand - setNamedHeaderResourceProperties( HeaderResource.HEADER_SECTION_DOJO_STYLE_BODYEXPAND, HeaderResource.HEADER_TYPE_STYLE_BLOCK, dojoEnableName, headerDynamicConfigurationDefault ); - + setNamedHeaderResourceProperties( + HeaderResource.HEADER_SECTION_DOJO_STYLE_BODYEXPAND, + HeaderResource.HEADER_TYPE_STYLE_BLOCK, dojoEnableName, + headerDynamicConfigurationDefault); + // dojo style bodyexpand noscroll - setNamedHeaderResourceProperties( HeaderResource.HEADER_SECTION_DOJO_STYLE_BODYEXPAND_NOSCROLL, HeaderResource.HEADER_TYPE_STYLE_BLOCK, dojoEnableName, headerDynamicConfigurationDefault ); + setNamedHeaderResourceProperties( + HeaderResource.HEADER_SECTION_DOJO_STYLE_BODYEXPAND_NOSCROLL, + HeaderResource.HEADER_TYPE_STYLE_BLOCK, dojoEnableName, + headerDynamicConfigurationDefault); } - /** * Builds the portlet set defined in the context into a portlet tree. * * @return Unique Portlet Entity ID */ - public void build( RequestContext context ) throws JetspeedException, IOException + public void build(RequestContext context) throws JetspeedException, + IOException { ContentPage page = context.getPage(); - if ( null == page ) - { - throw new JetspeedException( "Failed to find PSML Pin ContentPageAggregator.build" ); - } + if (null == page) { throw new JetspeedException( + "Failed to find PSML Pin ContentPageAggregator.build"); } ContentFragment root = page.getRootContentFragment(); - if ( root == null ) - { - throw new JetspeedException( "No root ContentFragment found in ContentPage" ); - } + if (root == null) { throw new JetspeedException( + "No root ContentFragment found in ContentPage"); } - // add named-resources and named-resources-added maps as request attributes + // add named-resources and named-resources-added maps as request + // attributes Map dynamicConfigDefault = getHeaderDynamicConfigurationDefault(); Map namedResourcesDefault = getHeaderNamedResourcesDefault(); Map namedResourcesAddedFragmentsDefault = getHeaderNamedResourcesAddedFragmentsDefault(); - - /*if ( log.isDebugEnabled() && namedResourcesDefault != null ) + + /* + * if ( log.isDebugEnabled() && namedResourcesDefault != null ) { + * Iterator namedResourcesDefaultIter = + * namedResourcesDefault.entrySet().iterator(); while ( + * namedResourcesDefaultIter.hasNext() ) { Map.Entry rsrcEntry = + * (Map.Entry)namedResourcesDefaultIter.next(); Object rsrcVal = + * rsrcEntry.getValue(); log.debug( rsrcEntry.getKey().toString() + ": " + + * EOL + ( rsrcVal != null ? rsrcVal.toString() : "null" ) ); } } + */ + + if (dynamicConfigDefault != null || namedResourcesDefault != null + || namedResourcesAddedFragmentsDefault != null) { - Iterator namedResourcesDefaultIter = namedResourcesDefault.entrySet().iterator(); - while ( namedResourcesDefaultIter.hasNext() ) + Map existingNamedResources = (Map) context + .getAttribute(PortalReservedParameters.HEADER_NAMED_RESOURCE_ATTRIBUTE); + if (existingNamedResources == null) { - Map.Entry rsrcEntry = (Map.Entry)namedResourcesDefaultIter.next(); - Object rsrcVal = rsrcEntry.getValue(); - log.debug( rsrcEntry.getKey().toString() + ": " + EOL + ( rsrcVal != null ? rsrcVal.toString() : "null" ) ); - } - }*/ - - if ( dynamicConfigDefault != null || namedResourcesDefault != null || namedResourcesAddedFragmentsDefault != null ) - { - Map existingNamedResources = (Map)context.getAttribute( PortalReservedParameters.HEADER_NAMED_RESOURCE_ATTRIBUTE ); - if ( existingNamedResources == null ) - { - if ( dynamicConfigDefault == null ) + if (dynamicConfigDefault == null) { - context.setAttribute( PortalReservedParameters.HEADER_CONFIGURATION_ATTRIBUTE, new HashMap() ); + context + .setAttribute( + PortalReservedParameters.HEADER_CONFIGURATION_ATTRIBUTE, + new HashMap()); } else { HashMap dynamicConfig = new HashMap(); - Iterator hConfigEntryIter = dynamicConfigDefault.entrySet().iterator(); - while ( hConfigEntryIter.hasNext() ) + Iterator hConfigEntryIter = dynamicConfigDefault.entrySet() + .iterator(); + while (hConfigEntryIter.hasNext()) { - Map.Entry hConfigEntry = (Map.Entry)hConfigEntryIter.next(); + Map.Entry hConfigEntry = (Map.Entry) hConfigEntryIter + .next(); Object hConfigKey = hConfigEntry.getKey(); Object hConfigVal = hConfigEntry.getValue(); - if ( hConfigVal instanceof Map ) + if (hConfigVal instanceof Map) { - dynamicConfig.put( hConfigKey, new HashMap( (Map)hConfigVal ) ); + dynamicConfig.put(hConfigKey, new HashMap( + (Map) hConfigVal)); } - else if ( hConfigVal instanceof List ) + else if (hConfigVal instanceof List) { - dynamicConfig.put( hConfigKey, new ArrayList( (List)hConfigVal ) ); + dynamicConfig.put(hConfigKey, new ArrayList( + (List) hConfigVal)); } else { - dynamicConfig.put( hConfigKey, hConfigVal ); + dynamicConfig.put(hConfigKey, hConfigVal); } } - context.setAttribute( PortalReservedParameters.HEADER_CONFIGURATION_ATTRIBUTE, dynamicConfig ); + context + .setAttribute( + PortalReservedParameters.HEADER_CONFIGURATION_ATTRIBUTE, + dynamicConfig); } - - if ( namedResourcesDefault != null ) + + if (namedResourcesDefault != null) { - context.setAttribute( PortalReservedParameters.HEADER_NAMED_RESOURCE_ATTRIBUTE, new HashMap( namedResourcesDefault ) ); + context + .setAttribute( + PortalReservedParameters.HEADER_NAMED_RESOURCE_ATTRIBUTE, + new HashMap(namedResourcesDefault)); } - if ( namedResourcesAddedFragmentsDefault != null ) + if (namedResourcesAddedFragmentsDefault != null) { - context.setAttribute( PortalReservedParameters.HEADER_NAMED_RESOURCE_ADDED_FRAGMENTS_ATTRIBUTE, new HashMap( namedResourcesAddedFragmentsDefault ) ); + context + .setAttribute( + PortalReservedParameters.HEADER_NAMED_RESOURCE_ADDED_FRAGMENTS_ATTRIBUTE, + new HashMap( + namedResourcesAddedFragmentsDefault)); } } } - if ( getHeaderResourceRegistry() != null ) + if (getHeaderResourceRegistry() != null) { - context.setAttribute( PortalReservedParameters.HEADER_NAMED_RESOURCE_REGISTRY_ATTRIBUTE, getHeaderResourceRegistry() ); + context + .setAttribute( + PortalReservedParameters.HEADER_NAMED_RESOURCE_REGISTRY_ATTRIBUTE, + getHeaderResourceRegistry()); } - + // handle maximized state boolean atLeastOneHasHeaderPhase = false; NavigationalState nav = context.getPortalURL().getNavigationalState(); PortletWindow window = nav.getMaximizedWindow(); - if ( null != window ) + if (null != window) { - ContentFragment maxedContentFragment = page.getContentFragmentById( window.getId().toString() ); - if ( maxedContentFragment != null ) + ContentFragment maxedContentFragment = page + .getContentFragmentById(window.getId().toString()); + if (maxedContentFragment != null) { - atLeastOneHasHeaderPhase = renderHeaderFragment( context, maxedContentFragment ); + atLeastOneHasHeaderPhase = renderHeaderFragment(context, + maxedContentFragment); } } else { - atLeastOneHasHeaderPhase = aggregateAndRender( root, context, page ); + atLeastOneHasHeaderPhase = aggregateAndRender(root, context, page); } - - if ( atLeastOneHasHeaderPhase ) + + if (atLeastOneHasHeaderPhase) { - + } } - protected boolean aggregateAndRender( ContentFragment fragment, RequestContext context, ContentPage page ) + protected boolean aggregateAndRender(ContentFragment fragment, + RequestContext context, ContentPage page) throws FailedToRenderFragmentException { boolean atLeastOneHasHeaderPhase = false; boolean hasHeaderPhase = false; - if ( fragment.getContentFragments() != null && fragment.getContentFragments().size() > 0 ) + if (fragment.getContentFragments() != null + && fragment.getContentFragments().size() > 0) { Iterator children = fragment.getContentFragments().iterator(); while (children.hasNext()) { ContentFragment child = (ContentFragment) children.next(); - if ( ! "hidden".equals( fragment.getState() ) ) + if (!"hidden".equals(fragment.getState())) { - hasHeaderPhase = aggregateAndRender( child, context, page ); - if ( hasHeaderPhase ) + hasHeaderPhase = aggregateAndRender(child, context, page); + if (hasHeaderPhase) { atLeastOneHasHeaderPhase = true; } } } } - hasHeaderPhase = renderHeaderFragment( context, fragment ); - if ( hasHeaderPhase ) + hasHeaderPhase = renderHeaderFragment(context, fragment); + if (hasHeaderPhase) { atLeastOneHasHeaderPhase = true; } return atLeastOneHasHeaderPhase; } - - protected boolean renderHeaderFragment( RequestContext context, ContentFragment fragment ) + + protected boolean renderHeaderFragment(RequestContext context, + ContentFragment fragment) { try { - if ( !fragment.getType().equals( ContentFragment.LAYOUT ) ) + if (!fragment.getType().equals(ContentFragment.LAYOUT)) { - PortletWindow portletWindow = getPortletWindowAccessor().getPortletWindow( fragment ); - PortletDefinition pd = portletWindow.getPortletEntity().getPortletDefinition(); - if ( pd != null && getPortletFactory().isPortletApplicationRegistered((PortletApplication)pd.getPortletApplicationDefinition() ) ) + PortletWindow portletWindow = getPortletWindowAccessor() + .getPortletWindow(fragment); + PortletDefinition pd = portletWindow.getPortletEntity() + .getPortletDefinition(); + if (pd != null + && getPortletFactory().isPortletApplicationRegistered( + (PortletApplication) pd + .getPortletApplicationDefinition())) { - String portletApplicationContextPath = pd.getPortletApplicationDefinition().getWebApplicationDefinition().getContextRoot(); - Portlet portlet = getPortletFactory().getPortletInstance( context.getConfig().getServletContext().getContext( portletApplicationContextPath ), pd ).getRealPortlet(); - if ( portlet != null && portlet instanceof SupportsHeaderPhase ) + String portletApplicationContextPath = pd + .getPortletApplicationDefinition() + .getWebApplicationDefinition().getContextRoot(); + Portlet portlet = getPortletFactory().getPortletInstance( + context.getConfig().getServletContext().getContext( + portletApplicationContextPath), pd) + .getRealPortlet(); + if (portlet != null + && portlet instanceof SupportsHeaderPhase) { - log.debug( "renderHeaderFragment: " + pd.getName() + " supports header phase" ); - - HeaderResource hr = getHeaderResourceFactory().getHeaderResource( context, this.baseUrlAccess, isDesktop(), getHeaderConfiguration() ); - PortletHeaderRequest headerRequest = new PortletHeaderRequestImpl( context, portletWindow, portletApplicationContextPath ); - PortletHeaderResponse headerResponse = new PortletHeaderResponseImpl( context, hr, isDesktop(), getHeaderConfiguration(), getHeaderResourceRegistry() ); - ((SupportsHeaderPhase)portlet).doHeader( headerRequest, headerResponse ); + log.debug("renderHeaderFragment: " + pd.getName() + + " supports header phase"); + + HeaderResource hr = getHeaderResourceFactory() + .getHeaderResource(context, this.baseUrlAccess, + isDesktop(), getHeaderConfiguration()); + PortletHeaderRequest headerRequest = new PortletHeaderRequestImpl( + context, portletWindow, + portletApplicationContextPath); + PortletHeaderResponse headerResponse = new PortletHeaderResponseImpl( + context, hr, isDesktop(), + getHeaderConfiguration(), + getHeaderResourceRegistry()); + ((SupportsHeaderPhase) portlet).doHeader(headerRequest, + headerResponse); return true; } } } return false; } - catch ( Exception e ) + catch (Exception e) { - log.error( "renderHeaderFragment failed", e ); + log.error("renderHeaderFragment failed", e); } return false; } - + protected PortletFactory getPortletFactory() { return this.factory; } + protected PortletWindowAccessor getPortletWindowAccessor() { return this.windowAccessor; } + protected HeaderResourceFactory getHeaderResourceFactory() { return this.headerResourceFactory; } + protected boolean isDesktop() { return this.isDesktop; } + protected Map getHeaderConfiguration() { return this.headerConfiguration; } + protected Map getHeaderResourceRegistry() { return this.headerResourceRegistry; } + protected Map getHeaderDynamicConfigurationDefault() { return this.headerDynamicConfigurationDefault; } + protected Map getHeaderNamedResourcesDefault() { return this.headerNamedResourcesDefault; } + protected Map getHeaderNamedResourcesAddedFragmentsDefault() { return this.headerNamedResourcesAddedFragmentsDefault; } + protected BasePortalURL getBaseUrlAccess() { return this.baseUrlAccess; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/HttpBufferedResponse.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/HttpBufferedResponse.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/HttpBufferedResponse.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,40 +20,46 @@ import java.io.PrintWriter; import java.io.UnsupportedEncodingException; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletResponse; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletResponse; import org.apache.pluto.util.PrintWriterServletOutputStream; -public class HttpBufferedResponse extends javax.servlet.http.HttpServletResponseWrapper +public class HttpBufferedResponse extends + javax.servlet.http.HttpServletResponseWrapper { + private boolean usingWriter; + private boolean usingStream; /** Commons logging */ - protected final static Log log = LogFactory.getLog(HttpBufferedResponse.class); + protected final static Log log = LogFactory + .getLog(HttpBufferedResponse.class); private ServletOutputStream wrappedStream; + private PrintWriter writer; public HttpBufferedResponse(HttpServletResponse servletResponse, - PrintWriter writer) + PrintWriter writer) { super(servletResponse); this.writer = writer; } - public ServletOutputStream getOutputStream() throws IllegalStateException, IOException + public ServletOutputStream getOutputStream() throws IllegalStateException, + IOException { - if (usingWriter) - { - throw new IllegalStateException("getOutputStream can't be used after getWriter was invoked"); - } + if (usingWriter) { throw new IllegalStateException( + "getOutputStream can't be used after getWriter was invoked"); } if (wrappedStream == null) - { - wrappedStream = new PrintWriterServletOutputStream(writer, getResponse().getCharacterEncoding()); + { + wrappedStream = new PrintWriterServletOutputStream(writer, + getResponse().getCharacterEncoding()); } usingStream = true; @@ -61,19 +67,18 @@ return wrappedStream; } - public PrintWriter getWriter() throws UnsupportedEncodingException, IllegalStateException, IOException { + public PrintWriter getWriter() throws UnsupportedEncodingException, + IllegalStateException, IOException + { - if (usingStream) - { - throw new IllegalStateException("getWriter can't be used after getOutputStream was invoked"); - } + if (usingStream) { throw new IllegalStateException( + "getWriter can't be used after getOutputStream was invoked"); } usingWriter = true; return writer; } - public void setBufferSize(int size) { // ignore Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PageAggregatorImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PageAggregatorImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PageAggregatorImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,18 +33,22 @@ import org.apache.pluto.om.window.PortletWindow; /** - * ContentPageAggregator builds the content required to render a page of portlets. + * ContentPageAggregator builds the content required to render a page of + * portlets. * * @author Rapha?l Luta * @author David Sean Taylor * @version $Id: PageAggregatorImpl.java 648465 2008-04-16 00:23:47Z taylor $ */ -public class PageAggregatorImpl extends BaseAggregatorImpl implements PageAggregator +public class PageAggregatorImpl extends BaseAggregatorImpl implements + PageAggregator { + private final static Log log = LogFactory.getLog(PageAggregatorImpl.class); + private PortletRenderer renderer; - public PageAggregatorImpl( PortletRenderer renderer) + public PageAggregatorImpl(PortletRenderer renderer) { this.renderer = renderer; } @@ -54,18 +58,15 @@ * * @return Unique Portlet Entity ID */ - public void build( RequestContext context ) throws JetspeedException, IOException + public void build(RequestContext context) throws JetspeedException, + IOException { ContentPage page = context.getPage(); - if (null == page) - { - throw new JetspeedException("Failed to find PSML Pin ContentPageAggregator.build"); - } + if (null == page) { throw new JetspeedException( + "Failed to find PSML Pin ContentPageAggregator.build"); } ContentFragment root = page.getRootContentFragment(); - if (root == null) - { - throw new JetspeedException("No root ContentFragment found in ContentPage"); - } + if (root == null) { throw new JetspeedException( + "No root ContentFragment found in ContentPage"); } // handle maximized state NavigationalState nav = context.getPortalURL().getNavigationalState(); PortletWindow window = nav.getMaximizedWindow(); @@ -76,14 +77,16 @@ else { aggregateAndRender(root, context, page); - } + } context.getResponse().getWriter().write(root.getRenderedContent()); if (null != window) { - context.getRequest().removeAttribute(PortalReservedParameters.MAXIMIZED_FRAGMENT_ATTRIBUTE); - context.getRequest().removeAttribute(PortalReservedParameters.MAXIMIZED_LAYOUT_ATTRIBUTE); + context.getRequest().removeAttribute( + PortalReservedParameters.MAXIMIZED_FRAGMENT_ATTRIBUTE); + context.getRequest().removeAttribute( + PortalReservedParameters.MAXIMIZED_LAYOUT_ATTRIBUTE); } - releaseBuffers(root, context); + releaseBuffers(root, context); } /** @@ -99,41 +102,55 @@ * @param window * @throws FailedToRenderContentFragmentException */ - protected void renderMaximizedWindow( RequestContext context, ContentPage page, ContentFragment layoutContentFragment, - PortletWindow window ) throws FailedToRenderFragmentException + protected void renderMaximizedWindow(RequestContext context, + ContentPage page, ContentFragment layoutContentFragment, + PortletWindow window) throws FailedToRenderFragmentException { - ContentFragment maxedContentFragment = page.getContentFragmentById(window.getId().toString()); + ContentFragment maxedContentFragment = page + .getContentFragmentById(window.getId().toString()); if (maxedContentFragment != null) { - context.getRequest().setAttribute(PortalReservedParameters.MAXIMIZED_FRAGMENT_ATTRIBUTE, maxedContentFragment); - context.getRequest().setAttribute(PortalReservedParameters.FRAGMENT_ATTRIBUTE, maxedContentFragment); - context.getRequest().setAttribute(PortalReservedParameters.MAXIMIZED_LAYOUT_ATTRIBUTE, page.getRootContentFragment()); + context.getRequest().setAttribute( + PortalReservedParameters.MAXIMIZED_FRAGMENT_ATTRIBUTE, + maxedContentFragment); + context.getRequest().setAttribute( + PortalReservedParameters.FRAGMENT_ATTRIBUTE, + maxedContentFragment); + context.getRequest().setAttribute( + PortalReservedParameters.MAXIMIZED_LAYOUT_ATTRIBUTE, + page.getRootContentFragment()); try { renderer.renderNow(maxedContentFragment, context); - renderer.renderNow(layoutContentFragment, context); - + renderer.renderNow(layoutContentFragment, context); + } catch (Exception e) { log.error(e.getMessage(), e); - maxedContentFragment.overrideRenderedContent("Sorry, but we were unable access the requested portlet. Send the following message to your portal admin: "+ e.getMessage()); + maxedContentFragment + .overrideRenderedContent("Sorry, but we were unable access the requested portlet. Send the following message to your portal admin: " + + e.getMessage()); } } else { - String message = "Maximized fragment not found."; + String message = "Maximized fragment not found."; log.error(message); if (maxedContentFragment != null) - maxedContentFragment.overrideRenderedContent("Sorry, but we were unable access the requested portlet. Send the following message to your portal admin: "+ message); + maxedContentFragment + .overrideRenderedContent("Sorry, but we were unable access the requested portlet. Send the following message to your portal admin: " + + message); } } - protected void aggregateAndRender( ContentFragment f, RequestContext context, ContentPage page ) + protected void aggregateAndRender(ContentFragment f, + RequestContext context, ContentPage page) throws FailedToRenderFragmentException { - if (f.getContentFragments() != null && f.getContentFragments().size() > 0) + if (f.getContentFragments() != null + && f.getContentFragments().size() > 0) { Iterator children = f.getContentFragments().iterator(); while (children.hasNext()) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletAggregatorFragmentImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletAggregatorFragmentImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletAggregatorFragmentImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,394 +27,498 @@ /** * PortletAggregator Fragment implementation for rendering. - * + * * @author Randy Watler * @version $Id$ */ public class PortletAggregatorFragmentImpl implements Fragment { + private String id; + private String name; + private String type; + private String decorator; + private String state; + private String mode; - + public PortletAggregatorFragmentImpl(String id) { this.id = id; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getConstraintsEnabled() */ public boolean getConstraintsEnabled() { return false; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getSecurityConstraints() */ public SecurityConstraints getSecurityConstraints() { return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#setSecurityConstraints(org.apache.jetspeed.om.common.SecurityConstraints) */ public void setSecurityConstraints(SecurityConstraints constraints) { } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#newSecurityConstraints() */ public SecurityConstraints newSecurityConstraints() { return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#newSecurityConstraint() */ public SecurityConstraint newSecurityConstraint() { return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#checkConstraints(java.lang.String) */ public void checkConstraints(String actions) throws SecurityException { } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#getPermissionsEnabled() */ public boolean getPermissionsEnabled() { return false; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#checkPermissions(int) */ public void checkPermissions(int mask) throws SecurityException { } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.SecuredResource#checkAccess(java.lang.String) */ public void checkAccess(String actions) throws SecurityException { } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#getId() */ public String getId() { return id; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#getTitle() */ public String getTitle() { return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#setTitle(java.lang.String) */ public void setTitle(String title) { } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#getShortTitle() */ public String getShortTitle() { return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.BaseElement#setShortTitle(java.lang.String) */ public void setShortTitle(String title) { } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getName() */ public String getName() { return name; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setName(java.lang.String) */ - public void setName( String name ) + public void setName(String name) { this.name = name; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getType() */ public String getType() { return type; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setType(java.lang.String) */ public void setType(String type) { this.type = type; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getSkin() */ public String getSkin() { return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setSkin(java.lang.String) */ public void setSkin(String skinName) { } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getDecorator() */ public String getDecorator() { return decorator; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setDecorator(java.lang.String) */ public void setDecorator(String decoratorName) { this.decorator = decoratorName; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getState() */ public String getState() { return state; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setState(java.lang.String) */ public void setState(String state) { this.state = state; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getMode() */ public String getMode() { return mode; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setMode(java.lang.String) */ public void setMode(String mode) { this.mode = mode; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getFragments() */ public List getFragments() { return new ArrayList(0); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getProperties() */ public Map getProperties() { return new HashMap(0); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getProperty(java.lang.String) */ public String getProperty(String propName) { return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getIntProperty(java.lang.String) */ public int getIntProperty(String propName) { return -1; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getFloatProperty(java.lang.String) */ public float getFloatProperty(String propName) { return -1.0F; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutRow() */ public int getLayoutRow() { return -1; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutColumn() */ public int getLayoutColumn() { return -1; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutSizes() */ public String getLayoutSizes() { return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutX() */ public float getLayoutX() { return -1.0F; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutY() */ public float getLayoutY() { return -1.0F; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutZ() */ public float getLayoutZ() { return -1.0F; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutWidth() */ public float getLayoutWidth() { return -1.0F; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getLayoutHeight() */ public float getLayoutHeight() { return -1.0F; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutRow(int) */ public void setLayoutRow(int row) { } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutColumn(int) */ public void setLayoutColumn(int column) { } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutSizes(java.lang.String) */ public void setLayoutSizes(String sizes) { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutX(float) */ public void setLayoutX(float x) { } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutY(float) */ public void setLayoutY(float y) { } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutZ(float) */ public void setLayoutZ(float z) { } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutWidth(float) */ public void setLayoutWidth(float width) { } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setLayoutHeight(float) */ public void setLayoutHeight(float height) { } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#isReference() */ public boolean isReference() { return false; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#clone() */ public Object clone() throws CloneNotSupportedException @@ -422,15 +526,19 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#getPreferences() */ public List getPreferences() { return null; - } + } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.Fragment#setPreferences(java.util.List) */ public void setPreferences(List preferences) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletAggregatorImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletAggregatorImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletAggregatorImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,59 +31,63 @@ /** * PortletAggregator builds the content required to render a single portlet. - * + * * @author David Sean Taylor * @version $Id: PortletAggregatorImpl.java 648465 2008-04-16 00:23:47Z taylor $ */ public class PortletAggregatorImpl implements PortletAggregator { + private PortletRenderer renderer; - public PortletAggregatorImpl(PortletRenderer renderer) + public PortletAggregatorImpl(PortletRenderer renderer) { this.renderer = renderer; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.aggregator.Aggregator#build(org.apache.jetspeed.request.RequestContext) */ - public void build(RequestContext context) throws JetspeedException, IOException + public void build(RequestContext context) throws JetspeedException, + IOException { // construct Fragment for rendering use with // appropriate id to match portlet entity - String entity = context.getRequestParameter(PortalReservedParameters.PORTLET_ENTITY); + String entity = context + .getRequestParameter(PortalReservedParameters.PORTLET_ENTITY); if (entity == null) { - entity = (String)context.getAttribute(PortalReservedParameters.PORTLET_ENTITY); + entity = (String) context + .getAttribute(PortalReservedParameters.PORTLET_ENTITY); } - if (entity == null) + if (entity == null) { return; } + Fragment fragment = context.getPage().getFragmentById(entity); + if (fragment == null) { - return; - } - Fragment fragment = context.getPage().getFragmentById(entity); - if (fragment == null) - { - String name = context.getRequestParameter(PortalReservedParameters.PORTLET); + String name = context + .getRequestParameter(PortalReservedParameters.PORTLET); if (name == null) { - name = (String)context.getAttribute(PortalReservedParameters.PORTLET); + name = (String) context + .getAttribute(PortalReservedParameters.PORTLET); } - if (name == null) - { - return; - } - fragment = new PortletAggregatorFragmentImpl(entity); + if (name == null) { return; } + fragment = new PortletAggregatorFragmentImpl(entity); fragment.setType(Fragment.PORTLET); fragment.setName(name); } - ContentFragment contentFragment = new ContentFragmentImpl(fragment, new HashMap()); + ContentFragment contentFragment = new ContentFragmentImpl(fragment, + new HashMap()); renderer.renderNow(contentFragment, context); - context.getResponse().getWriter().write(contentFragment.getRenderedContent()); + context.getResponse().getWriter().write( + contentFragment.getRenderedContent()); PortletContent content = contentFragment.getPortletContent(); if (content.getExpiration() == 0) { contentFragment.getPortletContent().release(); - } + } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletContentImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletContentImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletContentImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,23 +23,30 @@ import org.apache.jetspeed.aggregator.PortletRenderer; import org.apache.jetspeed.cache.ContentCacheKey; - public class PortletContentImpl implements PortletContent { + private CharArrayWriter cw; + private PrintWriter writer; + private boolean complete = false; + private ContentCacheKey cacheKey; + private int expiration = 0; + private String title; + private PortletRenderer renderer = null; - + PortletContentImpl() { init(); } - - PortletContentImpl(PortletRenderer renderer, ContentCacheKey cacheKey, int expiration, String title) + + PortletContentImpl(PortletRenderer renderer, ContentCacheKey cacheKey, + int expiration, String title) { this.renderer = renderer; this.cacheKey = cacheKey; @@ -48,11 +55,12 @@ init(); } - PortletContentImpl(PortletRenderer renderer, ContentCacheKey cacheKey, int expiration) + PortletContentImpl(PortletRenderer renderer, ContentCacheKey cacheKey, + int expiration) { - this(renderer, cacheKey, expiration,"no title"); + this(renderer, cacheKey, expiration, "no title"); } - + public PrintWriter getWriter() { return writer; @@ -81,7 +89,7 @@ return cw.toString(); } - public void writeTo( java.io.Writer out ) throws java.io.IOException + public void writeTo(java.io.Writer out) throws java.io.IOException { writer.flush(); cw.writeTo(out); @@ -100,57 +108,57 @@ void setComplete(boolean state, boolean notify) { - if (renderer != null && notify) - renderer.notifyContentComplete(this); + if (renderer != null && notify) renderer.notifyContentComplete(this); this.complete = state; } - + public String getContent() { return toString(); } + /** *

        * complete *

        - * + * * @see org.apache.jetspeed.aggregator.PortletContent#complete() * */ public void complete() { - setComplete(true, true); + setComplete(true, true); } - - // error case, don't notify + + // error case, don't notify public void completeWithError() { setComplete(true, false); } - + public ContentCacheKey getCacheKey() { return cacheKey; } - + public int getExpiration() { return expiration; } - + public void setExpiration(int expiration) { this.expiration = expiration; } - + public String getTitle() { return title; } - + public void setTitle(String title) { this.title = title; } - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletHeaderRequestImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletHeaderRequestImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletHeaderRequestImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,54 +21,58 @@ import org.apache.jetspeed.portlet.PortletHeaderRequest; import org.apache.jetspeed.request.RequestContext; import org.apache.pluto.core.impl.PortletPreferencesImpl; +import org.apache.pluto.om.common.Parameter; import org.apache.pluto.om.common.ParameterSet; -import org.apache.pluto.om.common.Parameter; import org.apache.pluto.om.window.PortletWindow; - public class PortletHeaderRequestImpl implements PortletHeaderRequest { + private RequestContext requestContext; + private String portletApplicationContextPath; + private PortletWindow portletWindow; + private ParameterSet initParamSet; - - public PortletHeaderRequestImpl( RequestContext requestContext, PortletWindow portletWindow, String portletApplicationContextPath ) + + public PortletHeaderRequestImpl(RequestContext requestContext, + PortletWindow portletWindow, String portletApplicationContextPath) { this.requestContext = requestContext; this.portletApplicationContextPath = portletApplicationContextPath; this.portletWindow = portletWindow; } - + public String getPortalContextPath() { return requestContext.getRequest().getContextPath(); - } - + } + public PortletPreferences getPreferences() { - return new PortletPreferencesImpl(org.apache.pluto.Constants.METHOD_NOOP, this.portletWindow.getPortletEntity()); + return new PortletPreferencesImpl( + org.apache.pluto.Constants.METHOD_NOOP, this.portletWindow + .getPortletEntity()); } - - public String getInitParameter( String name ) + + public String getInitParameter(String name) { ParameterSet iParamSet = this.initParamSet; - if ( iParamSet == null ) + if (iParamSet == null) { - iParamSet = this.portletWindow.getPortletEntity().getPortletDefinition().getInitParameterSet(); + iParamSet = this.portletWindow.getPortletEntity() + .getPortletDefinition().getInitParameterSet(); this.initParamSet = iParamSet; } - if ( iParamSet != null ) + if (iParamSet != null) { - Parameter initParam = iParamSet.get( name ); - if ( initParam != null ) - { - return initParam.getValue(); - } + Parameter initParam = iParamSet.get(name); + if (initParam != null) { return initParam.getValue(); } } return null; } - + /** * @return Returns the portletApplicationContextPath. */ @@ -76,5 +80,5 @@ { return portletApplicationContextPath; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletHeaderResponseImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletHeaderResponseImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletHeaderResponseImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,85 +32,95 @@ import org.apache.jetspeed.portlet.PortletHeaderResponse; import org.apache.jetspeed.request.RequestContext; - public class PortletHeaderResponseImpl implements PortletHeaderResponse { + private RequestContext requestContext; + private HeaderResource hr; + private String tempContent; - + private boolean isDesktop; - + private Map headerConfiguration; + private Map headerResourceRegistry; - - public PortletHeaderResponseImpl( RequestContext requestContext, HeaderResource hr, boolean isDesktop, Map headerConfiguration, Map headerResourceRegistry ) + + public PortletHeaderResponseImpl(RequestContext requestContext, + HeaderResource hr, boolean isDesktop, Map headerConfiguration, + Map headerResourceRegistry) { this.requestContext = requestContext; this.hr = hr; this.isDesktop = isDesktop; - + this.headerConfiguration = headerConfiguration; this.headerResourceRegistry = headerResourceRegistry; - } + } - public void include(PortletHeaderRequest request, PortletHeaderResponse response, String headerResource) - throws PortletException + public void include(PortletHeaderRequest request, + PortletHeaderResponse response, String headerResource) + throws PortletException { try { HttpServletRequest servletRequest = requestContext.getRequest(); HttpServletResponse servletResponse = requestContext.getResponse(); PortletContent content = new PortletContentImpl(); - HttpBufferedResponse bufferedResponse = - new HttpBufferedResponse(servletResponse, content.getWriter()); - ServletContext crossContext = requestContext.getConfig().getServletContext().getContext(request.getPortletApplicationContextPath()); - RequestDispatcher dispatcher = crossContext.getRequestDispatcher(headerResource); + HttpBufferedResponse bufferedResponse = new HttpBufferedResponse( + servletResponse, content.getWriter()); + ServletContext crossContext = requestContext.getConfig() + .getServletContext().getContext( + request.getPortletApplicationContextPath()); + RequestDispatcher dispatcher = crossContext + .getRequestDispatcher(headerResource); if (dispatcher != null) - dispatcher.include(servletRequest, bufferedResponse); + dispatcher.include(servletRequest, bufferedResponse); bufferedResponse.flushBuffer(); - BufferedReader reader = new BufferedReader(new StringReader(content.getContent())); + BufferedReader reader = new BufferedReader(new StringReader(content + .getContent())); String buffer; StringBuffer headerText = new StringBuffer(); while ((buffer = reader.readLine()) != null) { - headerText.append( buffer ).append( "\r\n" ); + headerText.append(buffer).append("\r\n"); } - tempContent = headerText.toString(); + tempContent = headerText.toString(); } catch (Exception e) { throw new PortletException(e); } } - + protected RequestContext getRequestContext() { return this.requestContext; } - + public HeaderResource getHeaderResource() { return this.hr; } - + public boolean isDesktop() { return this.isDesktop; } - + public Map getHeaderConfiguration() { return this.headerConfiguration; } - + public Map getHeaderResourceRegistry() { return this.headerResourceRegistry; } - + public String getContent() { - return tempContent; + return tempContent; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletRendererImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletRendererImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletRendererImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,8 +19,8 @@ import java.util.Collection; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Map; -import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -74,47 +74,53 @@ */ public class PortletRendererImpl implements PortletRenderer { - protected final static Log log = LogFactory.getLog(PortletRendererImpl.class); + protected final static Log log = LogFactory + .getLog(PortletRendererImpl.class); + protected WorkerMonitor workMonitor; + protected PortletContainer container; + protected PortletWindowAccessor windowAccessor; + protected PortalStatistics statistics; + protected DynamicTitleService addTitleService; protected PortletTrackingManager portletTracking; - + /** - * flag indicating whether to check jetspeed-portlet.xml security constraints - * before rendering a portlet. If security check fails, do not display portlet content + * flag indicating whether to check jetspeed-portlet.xml security + * constraints before rendering a portlet. If security check fails, do not + * display portlet content */ - protected boolean checkSecurityConstraints; + protected boolean checkSecurityConstraints; + /** * For security constraint checks */ protected SecurityAccessController accessController; - + /** * JSR 168 Portlet Content Cache */ protected JetspeedCache portletContentCache; - + /** * OutOfService Cache */ protected boolean overrideTitles = false; + public static final String OUT_OF_SERVICE_MESSAGE = "Portlet is not responding and has been taken out of service."; - - public PortletRendererImpl(PortletContainer container, - PortletWindowAccessor windowAccessor, - WorkerMonitor workMonitor, - PortalStatistics statistics, - DynamicTitleService addTitleService, - PortletTrackingManager portletTracking, - boolean checkSecurityConstraints, - SecurityAccessController accessController, - JetspeedCache portletContentCache, - boolean overrideTitles) + + public PortletRendererImpl(PortletContainer container, + PortletWindowAccessor windowAccessor, WorkerMonitor workMonitor, + PortalStatistics statistics, DynamicTitleService addTitleService, + PortletTrackingManager portletTracking, + boolean checkSecurityConstraints, + SecurityAccessController accessController, + JetspeedCache portletContentCache, boolean overrideTitles) { this.container = container; this.windowAccessor = windowAccessor; @@ -128,45 +134,40 @@ this.overrideTitles = overrideTitles; } - public PortletRendererImpl(PortletContainer container, - PortletWindowAccessor windowAccessor, - WorkerMonitor workMonitor, - PortalStatistics statistics, - DynamicTitleService addTitleService, + public PortletRendererImpl(PortletContainer container, + PortletWindowAccessor windowAccessor, WorkerMonitor workMonitor, + PortalStatistics statistics, DynamicTitleService addTitleService, PortletTrackingManager portletTracking, boolean checkSecurityConstraints, SecurityAccessController accessController, JetspeedCache portletContentCache) { - this(container, windowAccessor, workMonitor, statistics, - addTitleService, portletTracking, checkSecurityConstraints, - accessController, portletContentCache, false); + this(container, windowAccessor, workMonitor, statistics, + addTitleService, portletTracking, checkSecurityConstraints, + accessController, portletContentCache, false); } - - public PortletRendererImpl(PortletContainer container, - PortletWindowAccessor windowAccessor, - WorkerMonitor workMonitor, - PortalStatistics statistics, - DynamicTitleService addTitleService) + + public PortletRendererImpl(PortletContainer container, + PortletWindowAccessor windowAccessor, WorkerMonitor workMonitor, + PortalStatistics statistics, DynamicTitleService addTitleService) { - this(container, windowAccessor, workMonitor, statistics, null, null, false, null, null, true); + this(container, windowAccessor, workMonitor, statistics, null, null, + false, null, null, true); } - public PortletRendererImpl(PortletContainer container, - PortletWindowAccessor windowAccessor, - WorkerMonitor workMonitor, - PortalStatistics statistics) + public PortletRendererImpl(PortletContainer container, + PortletWindowAccessor windowAccessor, WorkerMonitor workMonitor, + PortalStatistics statistics) { - this( container, windowAccessor, workMonitor, statistics, null ); + this(container, windowAccessor, workMonitor, statistics, null); } - - public PortletRendererImpl(PortletContainer container, - PortletWindowAccessor windowAccessor, - WorkerMonitor workMonitor) + + public PortletRendererImpl(PortletContainer container, + PortletWindowAccessor windowAccessor, WorkerMonitor workMonitor) { - this( container, windowAccessor, workMonitor, null ); + this(container, windowAccessor, workMonitor, null); } - + public void start() { // workMonitor.start(); @@ -185,53 +186,59 @@ * @throws FailedToRetrievePortletWindow * @throws UnknownPortletDefinitionException */ - public void renderNow( ContentFragment fragment, RequestContext requestContext ) + public void renderNow(ContentFragment fragment, + RequestContext requestContext) { - HttpServletRequest servletRequest =null; + HttpServletRequest servletRequest = null; HttpServletResponse servletResponse = null; - ContentDispatcherCtrl dispatcher = null; + ContentDispatcherCtrl dispatcher = null; boolean contentIsCached = false; try { PortletWindow portletWindow = getPortletWindow(fragment); - PortletDefinitionComposite portletDefinition = - (PortletDefinitionComposite) portletWindow.getPortletEntity().getPortletDefinition(); - if (checkSecurityConstraints && !checkSecurityConstraint(portletDefinition, fragment)) - { - throw new PortletAccessDeniedException("Access Denied."); - } + PortletDefinitionComposite portletDefinition = (PortletDefinitionComposite) portletWindow + .getPortletEntity().getPortletDefinition(); + if (checkSecurityConstraints + && !checkSecurityConstraint(portletDefinition, fragment)) { throw new PortletAccessDeniedException( + "Access Denied."); } if (portletTracking.isOutOfService(portletWindow)) { - log.info("Taking portlet out of service: " + portletDefinition.getUniqueName() + " for window " + fragment.getId()); + log.info("Taking portlet out of service: " + + portletDefinition.getUniqueName() + " for window " + + fragment.getId()); fragment.overrideRenderedContent(OUT_OF_SERVICE_MESSAGE); return; } long timeoutMetadata = this.getTimeoutOnJob(portletDefinition); - portletTracking.setExpiration(portletWindow, timeoutMetadata); + portletTracking.setExpiration(portletWindow, timeoutMetadata); int expirationCache = getExpirationCache(portletDefinition); if (expirationCache != 0) { - if (retrieveCachedContent(requestContext, fragment, portletWindow, expirationCache, portletDefinition)) + if (retrieveCachedContent(requestContext, fragment, + portletWindow, expirationCache, portletDefinition)) return; contentIsCached = true; } if (dispatcher == null) { - dispatcher = createDispatcher(requestContext, fragment, expirationCache); + dispatcher = createDispatcher(requestContext, fragment, + expirationCache); } servletRequest = requestContext.getRequestForWindow(portletWindow); - servletResponse = dispatcher.getResponseForWindow(portletWindow, requestContext); - RenderingJob rJob = - buildRenderingJob(portletWindow, fragment, servletRequest, servletResponse, - requestContext, false, portletDefinition, dispatcher, null, - expirationCache, contentIsCached, timeoutMetadata); + servletResponse = dispatcher.getResponseForWindow(portletWindow, + requestContext); + RenderingJob rJob = buildRenderingJob(portletWindow, fragment, + servletRequest, servletResponse, requestContext, false, + portletDefinition, dispatcher, null, expirationCache, + contentIsCached, timeoutMetadata); rJob.execute(); - addTitleToHeader( portletWindow, fragment, servletRequest, servletResponse, dispatcher, contentIsCached); + addTitleToHeader(portletWindow, fragment, servletRequest, + servletResponse, dispatcher, contentIsCached); } catch (PortletAccessDeniedException e) { - fragment.overrideRenderedContent(e.getLocalizedMessage()); - } + fragment.overrideRenderedContent(e.getLocalizedMessage()); + } catch (Exception e) { fragment.overrideRenderedContent(e.getLocalizedMessage()); @@ -248,30 +255,32 @@ * @throws UnknownPortletDefinitionException * @throws PortletAccessDeniedException */ - public void renderNow( ContentFragment fragment, HttpServletRequest request, HttpServletResponse response ) + public void renderNow(ContentFragment fragment, HttpServletRequest request, + HttpServletResponse response) { RequestContext requestContext = (RequestContext) request .getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); renderNow(fragment, requestContext); } - - protected int getExpirationCache(PortletDefinitionComposite portletDefinition) + + protected int getExpirationCache( + PortletDefinitionComposite portletDefinition) { - if (portletDefinition == null) - return 0; + if (portletDefinition == null) return 0; String expiration = portletDefinition.getExpirationCache(); - if (expiration == null) - return 0; + if (expiration == null) return 0; return Integer.parseInt(expiration); } - + /** * Render the specified Page fragment. The method returns before rendering - * is complete, rendered content can be accessed through the Content Dispatcher + * is complete, rendered content can be accessed through the Content + * Dispatcher * * @return the asynchronous portlet rendering job to synchronize */ - public RenderingJob render( ContentFragment fragment, RequestContext requestContext ) + public RenderingJob render(ContentFragment fragment, + RequestContext requestContext) { RenderingJob job = null; @@ -282,7 +291,7 @@ catch (Exception e) { log.error("render() failed: " + e.toString(), e); - fragment.overrideRenderedContent(e.getLocalizedMessage()); + fragment.overrideRenderedContent(e.getLocalizedMessage()); } if (job != null) @@ -291,34 +300,36 @@ } return job; - } - - /** + } + + /** * - * Create a rendering job for the specified Page fragment. - * The method returns a rendering job which should be passed to 'processRenderingJob(RenderingJob job)' method. + * Create a rendering job for the specified Page fragment. The method + * returns a rendering job which should be passed to + * 'processRenderingJob(RenderingJob job)' method. + * * @return portlet rendering job to pass to render(RenderingJob job) method * @throws FailedToRetrievePortletWindow * @throws UnknownPortletDefinitionException * @throws PortletAccessDeniedException */ - public RenderingJob createRenderingJob(ContentFragment fragment, RequestContext requestContext) + public RenderingJob createRenderingJob(ContentFragment fragment, + RequestContext requestContext) { RenderingJob job = null; - boolean contentIsCached = false; + boolean contentIsCached = false; try { PortletWindow portletWindow = getPortletWindow(fragment); - PortletDefinitionComposite portletDefinition = - (PortletDefinitionComposite) portletWindow.getPortletEntity().getPortletDefinition(); + PortletDefinitionComposite portletDefinition = (PortletDefinitionComposite) portletWindow + .getPortletEntity().getPortletDefinition(); long timeoutMetadata = this.getTimeoutOnJob(portletDefinition); - portletTracking.setExpiration(portletWindow, timeoutMetadata); - - if (checkSecurityConstraints && !checkSecurityConstraint(portletDefinition, fragment)) - { - throw new PortletAccessDeniedException("Access Denied."); - } + portletTracking.setExpiration(portletWindow, timeoutMetadata); + + if (checkSecurityConstraints + && !checkSecurityConstraint(portletDefinition, fragment)) { throw new PortletAccessDeniedException( + "Access Denied."); } if (portletTracking.isOutOfService(portletWindow)) { fragment.overrideRenderedContent(OUT_OF_SERVICE_MESSAGE); @@ -328,15 +339,14 @@ if (expirationCache != 0) { portletTracking.setExpiration(portletWindow, expirationCache); - contentIsCached = retrieveCachedContent(requestContext, fragment, portletWindow, - expirationCache, portletDefinition); - if (contentIsCached) - { - return null; - } + contentIsCached = retrieveCachedContent(requestContext, + fragment, portletWindow, expirationCache, + portletDefinition); + if (contentIsCached) { return null; } } - job = buildRenderingJob( portletWindow, fragment, requestContext, true, - portletDefinition, null, contentIsCached, timeoutMetadata ); + job = buildRenderingJob(portletWindow, fragment, requestContext, + true, portletDefinition, null, contentIsCached, + timeoutMetadata); } catch (Exception e) { @@ -345,12 +355,13 @@ return job; } - - /** + + /** * - * Render the specified rendering job. - * The method returns before rendering is complete when the job is processed in parallel mode. - * When it is not parallel mode, it returns after rendering is complete. + * Render the specified rendering job. The method returns before rendering + * is complete when the job is processed in parallel mode. When it is not + * parallel mode, it returns after rendering is complete. + * * @throws FailedToRenderFragmentException */ public void processRenderingJob(RenderingJob job) @@ -371,21 +382,24 @@ else { job.execute(); - addTitleToHeader(job.getWindow(), job.getFragment(), - job.getRequest(), job.getResponse(), job.getDispatcher(), - job.isContentCached()); + addTitleToHeader(job.getWindow(), job.getFragment(), job + .getRequest(), job.getResponse(), job.getDispatcher(), + job.isContentCached()); } } catch (Exception e1) { log.error("render() failed: " + e1.toString(), e1); - fragment.overrideRenderedContent(e1.getLocalizedMessage()); + fragment.overrideRenderedContent(e1.getLocalizedMessage()); } } - + /** - * Wait for all rendering jobs in the collection to finish successfully or otherwise. - * @param renderingJobs the Collection of rendering job objects to wait for. + * Wait for all rendering jobs in the collection to finish successfully or + * otherwise. + * + * @param renderingJobs + * the Collection of rendering job objects to wait for. */ public void waitForRenderingJobs(List renderingJobs) { @@ -393,146 +407,188 @@ } /** - * Retrieve cached content, if content retrieved successfully return true, if no content found return false + * Retrieve cached content, if content retrieved successfully return true, + * if no content found return false + * * @param requestContext * @param fragment * @param portletWindow * @return true when content found, otherwise false */ - protected boolean retrieveCachedContent(RequestContext requestContext, ContentFragment fragment, - PortletWindow portletWindow, int expiration, - PortletDefinitionComposite portletDefinition) - throws Exception + protected boolean retrieveCachedContent(RequestContext requestContext, + ContentFragment fragment, PortletWindow portletWindow, + int expiration, PortletDefinitionComposite portletDefinition) + throws Exception { - ContentCacheKey cacheKey = portletContentCache.createCacheKey(requestContext, fragment.getId()); + ContentCacheKey cacheKey = portletContentCache.createCacheKey( + requestContext, fragment.getId()); CacheElement cachedElement = portletContentCache.get(cacheKey); if (cachedElement != null) { - PortletContent portletContent = (PortletContent)cachedElement.getContent(); + PortletContent portletContent = (PortletContent) cachedElement + .getContent(); fragment.setPortletContent(portletContent); - ContentDispatcherCtrl dispatcher = new ContentDispatcherImpl(portletContent); - HttpServletRequest servletRequest = requestContext.getRequestForWindow(portletWindow); + ContentDispatcherCtrl dispatcher = new ContentDispatcherImpl( + portletContent); + HttpServletRequest servletRequest = requestContext + .getRequestForWindow(portletWindow); - this.addTitleService.setDynamicTitle(portletWindow, servletRequest, dispatcher.getPortletContent(fragment).getTitle()); + this.addTitleService.setDynamicTitle(portletWindow, servletRequest, + dispatcher.getPortletContent(fragment).getTitle()); return true; - } + } return false; } - - public ContentDispatcherCtrl createDispatcher(RequestContext request, ContentFragment fragment, int expirationCache) + + public ContentDispatcherCtrl createDispatcher(RequestContext request, + ContentFragment fragment, int expirationCache) { - ContentCacheKey cacheKey = portletContentCache.createCacheKey(request, fragment.getId()); - PortletContent content = new PortletContentImpl(this, cacheKey, expirationCache); - ContentDispatcherCtrl dispatcher = new ContentDispatcherImpl(content); + ContentCacheKey cacheKey = portletContentCache.createCacheKey(request, + fragment.getId()); + PortletContent content = new PortletContentImpl(this, cacheKey, + expirationCache); + ContentDispatcherCtrl dispatcher = new ContentDispatcherImpl(content); return dispatcher; } - + /** * Retrieve the ContentDispatcher for the specified request */ - public ContentDispatcher getDispatcher( RequestContext request, boolean isParallel ) + public ContentDispatcher getDispatcher(RequestContext request, + boolean isParallel) { return request.getContentDispatcher(); } - - protected PortletWindow getPortletWindow( ContentFragment fragment ) throws FailedToRetrievePortletWindow, PortletEntityNotStoredException + protected PortletWindow getPortletWindow(ContentFragment fragment) + throws FailedToRetrievePortletWindow, + PortletEntityNotStoredException { // ObjectID oid = JetspeedObjectID.createFromString(fragment.getId()); PortletWindow portletWindow = windowAccessor.getPortletWindow(fragment); - if (portletWindow == null) - { - throw new FailedToRetrievePortletWindow("Portlet Window creation failed for fragment: " - + fragment.getId() + ", " + fragment.getName()); - } + if (portletWindow == null) { throw new FailedToRetrievePortletWindow( + "Portlet Window creation failed for fragment: " + + fragment.getId() + ", " + fragment.getName()); } PortletEntity portletEntity = portletWindow.getPortletEntity(); - ((MutablePortletEntity)portletEntity).setFragment(fragment); - - ((PortletWindowImpl) portletWindow).setInstantlyRendered(fragment.isInstantlyRendered()); + ((MutablePortletEntity) portletEntity).setFragment(fragment); + ((PortletWindowImpl) portletWindow).setInstantlyRendered(fragment + .isInstantlyRendered()); + return portletWindow; } - - protected RenderingJob buildRenderingJob( PortletWindow portletWindow, ContentFragment fragment, - RequestContext requestContext, boolean isParallel, - PortletDefinitionComposite portletDefinition, - PortletContent portletContent, boolean contentIsCached, long timeoutMetadata) - throws PortletAccessDeniedException, FailedToRetrievePortletWindow, PortletEntityNotStoredException + + protected RenderingJob buildRenderingJob(PortletWindow portletWindow, + ContentFragment fragment, RequestContext requestContext, + boolean isParallel, PortletDefinitionComposite portletDefinition, + PortletContent portletContent, boolean contentIsCached, + long timeoutMetadata) throws PortletAccessDeniedException, + FailedToRetrievePortletWindow, PortletEntityNotStoredException { int expirationCache = getExpirationCache(portletDefinition); - ContentDispatcherCtrl dispatcher = createDispatcher(requestContext, fragment, expirationCache); - HttpServletRequest request = requestContext.getRequestForWindow(portletWindow); - HttpServletResponse response = dispatcher.getResponseForWindow(portletWindow, requestContext); + ContentDispatcherCtrl dispatcher = createDispatcher(requestContext, + fragment, expirationCache); + HttpServletRequest request = requestContext + .getRequestForWindow(portletWindow); + HttpServletResponse response = dispatcher.getResponseForWindow( + portletWindow, requestContext); - return buildRenderingJob( portletWindow, fragment, request, response, - requestContext, isParallel, - portletDefinition, dispatcher, - portletContent, expirationCache, contentIsCached, timeoutMetadata ); + return buildRenderingJob(portletWindow, fragment, request, response, + requestContext, isParallel, portletDefinition, dispatcher, + portletContent, expirationCache, contentIsCached, + timeoutMetadata); } - protected RenderingJob buildRenderingJob( PortletWindow portletWindow, ContentFragment fragment, - HttpServletRequest request, HttpServletResponse response, - RequestContext requestContext, boolean isParallel, - PortletDefinitionComposite portletDefinition, - ContentDispatcherCtrl dispatcher, - PortletContent portletContent, - int expirationCache, boolean contentIsCached, long timeoutMetadata) - throws PortletAccessDeniedException, FailedToRetrievePortletWindow, PortletEntityNotStoredException - { + protected RenderingJob buildRenderingJob(PortletWindow portletWindow, + ContentFragment fragment, HttpServletRequest request, + HttpServletResponse response, RequestContext requestContext, + boolean isParallel, PortletDefinitionComposite portletDefinition, + ContentDispatcherCtrl dispatcher, PortletContent portletContent, + int expirationCache, boolean contentIsCached, long timeoutMetadata) + throws PortletAccessDeniedException, FailedToRetrievePortletWindow, + PortletEntityNotStoredException + { RenderingJob rJob = null; - - request.setAttribute(PortalReservedParameters.PAGE_ATTRIBUTE, requestContext.getPage()); - request.setAttribute(PortalReservedParameters.FRAGMENT_ATTRIBUTE, fragment); - request.setAttribute(PortalReservedParameters.CONTENT_DISPATCHER_ATTRIBUTE, dispatcher); - request.setAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE, requestContext); - request.setAttribute(PortalReservedParameters.REQUEST_CONTEXT_OBJECTS, requestContext.getObjects()); - request.setAttribute(PortalReservedParameters.PATH_ATTRIBUTE, requestContext.getAttribute(PortalReservedParameters.PATH_ATTRIBUTE)); - request.setAttribute(PortalReservedParameters.PORTLET_WINDOW_ATTRIBUTE, portletWindow); - + + request.setAttribute(PortalReservedParameters.PAGE_ATTRIBUTE, + requestContext.getPage()); + request.setAttribute(PortalReservedParameters.FRAGMENT_ATTRIBUTE, + fragment); + request.setAttribute( + PortalReservedParameters.CONTENT_DISPATCHER_ATTRIBUTE, + dispatcher); + request.setAttribute( + PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE, + requestContext); + request.setAttribute(PortalReservedParameters.REQUEST_CONTEXT_OBJECTS, + requestContext.getObjects()); + request.setAttribute(PortalReservedParameters.PATH_ATTRIBUTE, + requestContext + .getAttribute(PortalReservedParameters.PATH_ATTRIBUTE)); + request.setAttribute(PortalReservedParameters.PORTLET_WINDOW_ATTRIBUTE, + portletWindow); + if (portletContent == null) { portletContent = dispatcher.getPortletContent(fragment); fragment.setPortletContent(portletContent); } - // In case of parallel mode, store attributes in a map to be refered by worker. + // In case of parallel mode, store attributes in a map to be refered by + // worker. if (isParallel) { Map workerAttrs = new HashMap(); - workerAttrs.put(PortalReservedParameters.PAGE_ATTRIBUTE, requestContext.getPage()); - workerAttrs.put(PortalReservedParameters.FRAGMENT_ATTRIBUTE, fragment); - workerAttrs.put(PortalReservedParameters.CONTENT_DISPATCHER_ATTRIBUTE, dispatcher); - workerAttrs.put(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE, requestContext); - workerAttrs.put(PortalReservedParameters.REQUEST_CONTEXT_OBJECTS, requestContext.getObjects()); - workerAttrs.put(PortalReservedParameters.PATH_ATTRIBUTE, requestContext.getAttribute(PortalReservedParameters.PATH_ATTRIBUTE)); - workerAttrs.put(PortalReservedParameters.PORTLET_WINDOW_ATTRIBUTE, portletWindow); + workerAttrs.put(PortalReservedParameters.PAGE_ATTRIBUTE, + requestContext.getPage()); + workerAttrs.put(PortalReservedParameters.FRAGMENT_ATTRIBUTE, + fragment); + workerAttrs.put( + PortalReservedParameters.CONTENT_DISPATCHER_ATTRIBUTE, + dispatcher); + workerAttrs.put(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE, + requestContext); + workerAttrs.put(PortalReservedParameters.REQUEST_CONTEXT_OBJECTS, + requestContext.getObjects()); + workerAttrs + .put( + PortalReservedParameters.PATH_ATTRIBUTE, + requestContext + .getAttribute(PortalReservedParameters.PATH_ATTRIBUTE)); + workerAttrs.put(PortalReservedParameters.PORTLET_WINDOW_ATTRIBUTE, + portletWindow); - // the portlet invoker is not thread safe; it stores current portlet definition as a member variable. + // the portlet invoker is not thread safe; it stores current portlet + // definition as a member variable. // so, store portlet definition as an attribute of worker - workerAttrs.put(PortalReservedParameters.PORTLET_DEFINITION_ATTRIBUTE, portletDefinition); + workerAttrs.put( + PortalReservedParameters.PORTLET_DEFINITION_ATTRIBUTE, + portletDefinition); - rJob = new RenderingJobImpl(container, this, portletDefinition, portletContent, fragment, dispatcher, - request, response, requestContext, portletWindow, - statistics, expirationCache, contentIsCached, workerAttrs); - + rJob = new RenderingJobImpl(container, this, portletDefinition, + portletContent, fragment, dispatcher, request, response, + requestContext, portletWindow, statistics, expirationCache, + contentIsCached, workerAttrs); + } else { - rJob = new RenderingJobImpl(container, this, portletDefinition, portletContent, fragment, dispatcher, - request, response, requestContext, portletWindow, - statistics, expirationCache, contentIsCached ); - + rJob = new RenderingJobImpl(container, this, portletDefinition, + portletContent, fragment, dispatcher, request, response, + requestContext, portletWindow, statistics, expirationCache, + contentIsCached); + } - + if (isParallel) { setTimeoutOnJob(timeoutMetadata, rJob); } - + return rJob; } - + protected long getTimeoutOnJob(PortletDefinitionComposite portletDefinition) { long timeoutMetadata = 0; @@ -540,46 +596,51 @@ if (portletDefinition != null) { - timeoutFields = portletDefinition.getMetadata().getFields(PortalReservedParameters.PORTLET_EXTENDED_DESCRIPTOR_RENDER_TIMEOUT); + timeoutFields = portletDefinition + .getMetadata() + .getFields( + PortalReservedParameters.PORTLET_EXTENDED_DESCRIPTOR_RENDER_TIMEOUT); } - if (timeoutFields != null) + if (timeoutFields != null) { Iterator it = timeoutFields.iterator(); - if (it.hasNext()) + if (it.hasNext()) { - LocalizedField timeoutField = (LocalizedField) timeoutFields.iterator().next(); + LocalizedField timeoutField = (LocalizedField) timeoutFields + .iterator().next(); - try + try { timeoutMetadata = Long.parseLong(timeoutField.getValue()); } - catch (NumberFormatException nfe) + catch (NumberFormatException nfe) { log.warn("Invalid timeout metadata: " + nfe.getMessage()); } } - } + } return timeoutMetadata; } - + protected void setTimeoutOnJob(long timeoutMetadata, RenderingJob rJob) { - - if (timeoutMetadata > 0) + + if (timeoutMetadata > 0) { rJob.setTimeout(timeoutMetadata); } - else if (this.portletTracking.getDefaultPortletTimeout() > 0) + else if (this.portletTracking.getDefaultPortletTimeout() > 0) { rJob.setTimeout(this.portletTracking.getDefaultPortletTimeout()); - } + } } - - public void addTitleToHeader( PortletWindow portletWindow, ContentFragment fragment, - HttpServletRequest request, HttpServletResponse response, - ContentDispatcherCtrl dispatcher, boolean isCacheTitle ) + + public void addTitleToHeader(PortletWindow portletWindow, + ContentFragment fragment, HttpServletRequest request, + HttpServletResponse response, ContentDispatcherCtrl dispatcher, + boolean isCacheTitle) { if (overrideTitles) { @@ -587,17 +648,20 @@ { String title = fragment.getTitle(); - if ( title == null ) + if (title == null) { - title = addTitleService.getDynamicTitle( portletWindow, request ); + title = addTitleService.getDynamicTitle(portletWindow, + request); } - response.setHeader( "JS_PORTLET_TITLE", StringEscapeUtils.escapeHtml( title ) ); - dispatcher.getPortletContent(fragment).setTitle(title); + response.setHeader("JS_PORTLET_TITLE", StringEscapeUtils + .escapeHtml(title)); + dispatcher.getPortletContent(fragment).setTitle(title); } catch (Exception e) { - log.error("Unable to reteive portlet title: " + e.getMessage(), e); + log.error("Unable to reteive portlet title: " + e.getMessage(), + e); } } else @@ -608,9 +672,10 @@ { title = fragment.getTitle(); - if ( title == null ) + if (title == null) { - title = addTitleService.getDynamicTitle(portletWindow, request); + title = addTitleService.getDynamicTitle(portletWindow, + request); } dispatcher.getPortletContent(fragment).setTitle(title); @@ -619,45 +684,46 @@ if (title == null) { title = addTitleService.getDynamicTitle(portletWindow, request); - dispatcher.getPortletContent(fragment).setTitle(title); + dispatcher.getPortletContent(fragment).setTitle(title); } } } - - protected boolean checkSecurityConstraint(PortletDefinitionComposite portlet, ContentFragment fragment) + + protected boolean checkSecurityConstraint( + PortletDefinitionComposite portlet, ContentFragment fragment) { if (fragment.getType().equals(ContentFragment.PORTLET)) { - if (accessController != null) - { - return accessController.checkPortletAccess(portlet, JetspeedActions.MASK_VIEW); - } + if (accessController != null) { return accessController + .checkPortletAccess(portlet, JetspeedActions.MASK_VIEW); } } return true; } - + protected void addToCache(PortletContent content) { - CacheElement cachedElement = portletContentCache.createElement(content.getCacheKey(), content); + CacheElement cachedElement = portletContentCache.createElement(content + .getCacheKey(), content); if (content.getExpiration() == -1) { - cachedElement.setTimeToIdleSeconds(portletContentCache.getTimeToIdleSeconds()); - cachedElement.setTimeToLiveSeconds(portletContentCache.getTimeToLiveSeconds()); + cachedElement.setTimeToIdleSeconds(portletContentCache + .getTimeToIdleSeconds()); + cachedElement.setTimeToLiveSeconds(portletContentCache + .getTimeToLiveSeconds()); } else - { + { cachedElement.setTimeToIdleSeconds(content.getExpiration()); cachedElement.setTimeToLiveSeconds(content.getExpiration()); } - portletContentCache.put(cachedElement); - } - + portletContentCache.put(cachedElement); + } + public void notifyContentComplete(PortletContent content) { - if (content.getExpiration() != 0) - addToCache(content); + if (content.getExpiration() != 0) addToCache(content); } - + public PortletTrackingManager getPortletTrackingManager() { return this.portletTracking; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletTrackingManagerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletTrackingManagerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/PortletTrackingManagerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,36 +31,38 @@ /** * Tracks out of service status for portlets - * + * * @author David Sean Taylor * @version $Id: $ */ public class PortletTrackingManagerImpl implements PortletTrackingManager { + protected Map outOfService = Collections.synchronizedMap(new HashMap()); /** * when rendering a portlet, the default timeout period in milliseconds * setting to zero will disable (no timeout) the timeout - * + * */ - protected long defaultPortletTimeout; - + protected long defaultPortletTimeout; + /** - * Out of service limit, if a portlet entity times out past its limit (or default limit) n consecutive times, - * it is taken out of service + * Out of service limit, if a portlet entity times out past its limit (or + * default limit) n consecutive times, it is taken out of service */ protected int outOfServiceLimit; - + protected PortletWindowAccessor windowAccessor; - - public PortletTrackingManagerImpl(PortletWindowAccessor windowAccessor, long defaultPortletTimeout, int outOfServiceLimit) + + public PortletTrackingManagerImpl(PortletWindowAccessor windowAccessor, + long defaultPortletTimeout, int outOfServiceLimit) { this.windowAccessor = windowAccessor; this.defaultPortletTimeout = defaultPortletTimeout; this.outOfServiceLimit = outOfServiceLimit; } - + public long getDefaultPortletTimeout() { return this.defaultPortletTimeout; @@ -68,71 +70,66 @@ public boolean exceededTimeout(long renderTime, PortletWindow window) { - RenderTrackable trackInfo = (RenderTrackable)window.getPortletEntity(); + RenderTrackable trackInfo = (RenderTrackable) window.getPortletEntity(); long defaultTimeout = this.getDefaultPortletTimeout(); if (trackInfo.getExpiration() > 0) { return (renderTime > trackInfo.getExpiration()); } - else if (defaultTimeout > 0) - { - return (renderTime > defaultTimeout); - } + else if (defaultTimeout > 0) { return (renderTime > defaultTimeout); } return false; } - + public boolean isOutOfService(PortletWindow window) { - RenderTrackable trackable = (RenderTrackable)window.getPortletEntity(); - if (trackable.getRenderTimeoutCount() > this.outOfServiceLimit) - { - return true; - } + RenderTrackable trackable = (RenderTrackable) window.getPortletEntity(); + if (trackable.getRenderTimeoutCount() > this.outOfServiceLimit) { return true; } return false; } - + public int getOutOfServiceLimit() { return this.outOfServiceLimit; } - + public void incrementRenderTimeoutCount(PortletWindow window) { - RenderTrackable trackable = (RenderTrackable)window.getPortletEntity(); - trackable.incrementRenderTimeoutCount(); + RenderTrackable trackable = (RenderTrackable) window.getPortletEntity(); + trackable.incrementRenderTimeoutCount(); } - + public void success(PortletWindow window) { - RenderTrackable trackable = (RenderTrackable)window.getPortletEntity(); + RenderTrackable trackable = (RenderTrackable) window.getPortletEntity(); trackable.success(); } - + public void setExpiration(PortletWindow window, long expiration) { - RenderTrackable trackable = (RenderTrackable)window.getPortletEntity(); - trackable.setExpiration(expiration); // * 1000); + RenderTrackable trackable = (RenderTrackable) window.getPortletEntity(); + trackable.setExpiration(expiration); // * 1000); } - + public void takeOutOfService(PortletWindow window) { - RenderTrackable trackable = (RenderTrackable)window.getPortletEntity(); - trackable.setRenderTimeoutCount((int)this.defaultPortletTimeout + 1); + RenderTrackable trackable = (RenderTrackable) window.getPortletEntity(); + trackable.setRenderTimeoutCount((int) this.defaultPortletTimeout + 1); } - + public void putIntoService(PortletWindow window) { - RenderTrackable trackable = (RenderTrackable)window.getPortletEntity(); - trackable.setRenderTimeoutCount(0); + RenderTrackable trackable = (RenderTrackable) window.getPortletEntity(); + trackable.setRenderTimeoutCount(0); } - + public void putIntoService(List fullPortletNames) { Iterator windows = this.windowAccessor.getPortletWindows().iterator(); while (windows.hasNext()) { - PortletWindow window = (PortletWindow)windows.next(); - PortletDefinitionComposite pd = (PortletDefinitionComposite)window.getPortletEntity().getPortletDefinition(); + PortletWindow window = (PortletWindow) windows.next(); + PortletDefinitionComposite pd = (PortletDefinitionComposite) window + .getPortletEntity().getPortletDefinition(); for (int ix = 0; ix < fullPortletNames.size(); ix++) { if (pd.getUniqueName().equals(fullPortletNames.get(ix))) @@ -140,35 +137,37 @@ putIntoService(window); } } - } + } } - + public List getOutOfServiceList(String fullPortletName) { List outs = new ArrayList(); Iterator windows = this.windowAccessor.getPortletWindows().iterator(); while (windows.hasNext()) { - PortletWindow window = (PortletWindow)windows.next(); - PortletDefinitionComposite pd = (PortletDefinitionComposite)window.getPortletEntity().getPortletDefinition(); - if (pd.getUniqueName().equals(fullPortletName) && isOutOfService(window)) + PortletWindow window = (PortletWindow) windows.next(); + PortletDefinitionComposite pd = (PortletDefinitionComposite) window + .getPortletEntity().getPortletDefinition(); + if (pd.getUniqueName().equals(fullPortletName) + && isOutOfService(window)) { outs.add(window); } } return outs; } - + public List getOutOfServiceList() { List outs = new ArrayList(); Iterator windows = this.windowAccessor.getPortletWindows().iterator(); while (windows.hasNext()) { - PortletWindow window = (PortletWindow)windows.next(); + PortletWindow window = (PortletWindow) windows.next(); if (isOutOfService(window)) { - outs.add(window); + outs.add(window); } } return outs; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/RenderingJobImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/RenderingJobImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/RenderingJobImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,18 +17,18 @@ package org.apache.jetspeed.aggregator.impl; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; import java.util.Iterator; import java.util.Map; -import java.util.HashMap; -import java.util.Collection; -import java.util.Collections; -import java.util.Arrays; import javax.portlet.UnavailableException; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletRequestWrapper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -50,9 +50,9 @@ /** * The RenderingJob is responsible for storing all necessary objets for - * asynchronous portlet rendering as well as implementing the rendering logic - * in its Runnable method. - * + * asynchronous portlet rendering as well as implementing the rendering logic in + * its Runnable method. + * * @author Rapha?l Luta * @author David Sean Taylor * @author Woonsan Ko @@ -60,82 +60,83 @@ */ public class RenderingJobImpl implements RenderingJob { + /** Commons logging */ protected final static Log log = LogFactory.getLog(RenderingJobImpl.class); /** WorkerMonitor used to flush the queue */ protected PortletWindow window = null; + protected HttpServletRequest request = null; + protected HttpServletResponse response = null; - + protected PortletContainer container = null; + protected PortletRenderer renderer = null; + protected ContentFragment fragment = null; + protected RequestContext requestContext = null; + protected PortletTrackingManager portletTracking = null; protected PortletDefinition portletDefinition; + protected PortletContent portletContent; + protected PortalStatistics statistics; + protected ContentDispatcherCtrl dispatcher; + protected boolean contentIsCached; - + protected int expirationCache = 0; protected Map workerAttributes; protected long startTimeMillis = 0; + protected long timeout; - + public RenderingJobImpl(PortletContainer container, - PortletRenderer renderer, - PortletDefinition portletDefinition, - PortletContent portletContent, - ContentFragment fragment, - ContentDispatcherCtrl dispatcher, - HttpServletRequest request, - HttpServletResponse response, - RequestContext requestContext, - PortletWindow window, - PortalStatistics statistics, - int expirationCache, - boolean contentIsCached) + PortletRenderer renderer, PortletDefinition portletDefinition, + PortletContent portletContent, ContentFragment fragment, + ContentDispatcherCtrl dispatcher, HttpServletRequest request, + HttpServletResponse response, RequestContext requestContext, + PortletWindow window, PortalStatistics statistics, + int expirationCache, boolean contentIsCached) { this.container = container; this.renderer = renderer; - this.portletTracking = renderer.getPortletTrackingManager(); + this.portletTracking = renderer.getPortletTrackingManager(); this.statistics = statistics; this.portletDefinition = portletDefinition; this.fragment = fragment; this.dispatcher = dispatcher; this.request = request; this.response = response; - this.requestContext = requestContext; + this.requestContext = requestContext; this.window = window; - this.portletContent = portletContent; - ((MutablePortletEntity)window.getPortletEntity()).setFragment(fragment); + this.portletContent = portletContent; + ((MutablePortletEntity) window.getPortletEntity()) + .setFragment(fragment); this.expirationCache = expirationCache; this.contentIsCached = contentIsCached; } - public RenderingJobImpl(PortletContainer container, - PortletRenderer renderer, - PortletDefinition portletDefinition, - PortletContent portletContent, - ContentFragment fragment, - ContentDispatcherCtrl dispatcher, - HttpServletRequest request, - HttpServletResponse response, - RequestContext requestContext, - PortletWindow window, - PortalStatistics statistics, - int expirationCache, - boolean contentIsCached, - Map workerAttrs) + public RenderingJobImpl(PortletContainer container, + PortletRenderer renderer, PortletDefinition portletDefinition, + PortletContent portletContent, ContentFragment fragment, + ContentDispatcherCtrl dispatcher, HttpServletRequest request, + HttpServletResponse response, RequestContext requestContext, + PortletWindow window, PortalStatistics statistics, + int expirationCache, boolean contentIsCached, Map workerAttrs) { - this(container, renderer, portletDefinition, portletContent, fragment, dispatcher, - request, response, requestContext, window, statistics, expirationCache, contentIsCached); - + this(container, renderer, portletDefinition, portletContent, fragment, + dispatcher, request, response, requestContext, window, + statistics, expirationCache, contentIsCached); + if (workerAttrs != null) { this.workerAttributes = Collections.synchronizedMap(workerAttrs); @@ -145,62 +146,69 @@ /** * Sets portlet timout in milliseconds. */ - public void setTimeout(long timeout) { + public void setTimeout(long timeout) + { this.timeout = timeout; } /** * Gets portlet timout in milliseconds. */ - public long getTimeout() { + public long getTimeout() + { return this.timeout; } /** * Checks if the portlet rendering is timeout */ - public boolean isTimeout() { - if ((this.timeout > 0) && (this.startTimeMillis > 0)) { - return (System.currentTimeMillis() - this.startTimeMillis > this.timeout); - } + public boolean isTimeout() + { + if ((this.timeout > 0) && (this.startTimeMillis > 0)) { return (System + .currentTimeMillis() + - this.startTimeMillis > this.timeout); } return false; } /** - * Checks if queue is empty, if not try to empty it by calling - * the WorkerMonitor. When done, pause until next scheduled scan. + * Checks if queue is empty, if not try to empty it by calling the + * WorkerMonitor. When done, pause until next scheduled scan. */ public void run() - { + { try { - if (this.timeout > 0) + if (this.timeout > 0) { CurrentWorkerContext.setParallelRenderingMode(true); this.startTimeMillis = System.currentTimeMillis(); } - // A little baby hack to make sure the worker thread has PortletContent to write too. + // A little baby hack to make sure the worker thread has + // PortletContent to write too. fragment.setPortletContent(portletContent); - execute(); + execute(); } finally { synchronized (portletContent) { - if (log.isDebugEnabled()) log.debug("Notifying completion of rendering job for fragment " + fragment.getId()); - portletContent.notifyAll(); + if (log.isDebugEnabled()) + log + .debug("Notifying completion of rendering job for fragment " + + fragment.getId()); + portletContent.notifyAll(); } } } - + /** *

        * execute *

        - * * + * */ public void execute() { @@ -209,78 +217,111 @@ PortletWindow curWindow = this.window; try { - if (log.isDebugEnabled()) log.debug("Rendering OID "+this.window.getId()+" "+ this.request +" "+this.response); + if (log.isDebugEnabled()) + log.debug("Rendering OID " + this.window.getId() + " " + + this.request + " " + this.response); // if the current thread is worker, then store attribues in that. if (this.workerAttributes != null) { - isParallelMode = CurrentWorkerContext.getParallelRenderingMode(); + isParallelMode = CurrentWorkerContext + .getParallelRenderingMode(); if (isParallelMode) { - Collection attrNames = Arrays.asList(this.workerAttributes.keySet().toArray()); - + Collection attrNames = Arrays.asList(this.workerAttributes + .keySet().toArray()); + Iterator itAttrNames = attrNames.iterator(); - while (itAttrNames.hasNext()) + while (itAttrNames.hasNext()) { String name = (String) itAttrNames.next(); - CurrentWorkerContext.setAttribute(name, this.workerAttributes.get(name)); + CurrentWorkerContext.setAttribute(name, + this.workerAttributes.get(name)); } - - // The portletEntity stores its portletDefinition into the ThreadLocal member, + + // The portletEntity stores its portletDefinition into the + // ThreadLocal member, // before the worker starts doing a rendering job. // So the thread contexts are different from each other. - // Therefore, in parallel mode, we have to clear threadlocal fragmentPortletDefinition cache - // of portletEntity and to replace the portletDefinition with one of current worker context. - // Refer to org.apache.jetspeed.components.portletentity.PortletEntityImpl class - - curWindow = (PortletWindow) - CurrentWorkerContext.getAttribute(PortalReservedParameters.PORTLET_WINDOW_ATTRIBUTE); - PortletEntityImpl curEntity = (PortletEntityImpl) curWindow.getPortletEntity(); - PortletDefinition oldPortletDefinition = curEntity.getPortletDefinition(); - PortletDefinition curPortletDefinition = (PortletDefinition) - CurrentWorkerContext.getAttribute(PortalReservedParameters.PORTLET_DEFINITION_ATTRIBUTE); - - if (!oldPortletDefinition.getId().equals(curPortletDefinition.getId())) { + // Therefore, in parallel mode, we have to clear threadlocal + // fragmentPortletDefinition cache + // of portletEntity and to replace the portletDefinition + // with one of current worker context. + // Refer to + // org.apache.jetspeed.components.portletentity.PortletEntityImpl + // class + + curWindow = (PortletWindow) CurrentWorkerContext + .getAttribute(PortalReservedParameters.PORTLET_WINDOW_ATTRIBUTE); + PortletEntityImpl curEntity = (PortletEntityImpl) curWindow + .getPortletEntity(); + PortletDefinition oldPortletDefinition = curEntity + .getPortletDefinition(); + PortletDefinition curPortletDefinition = (PortletDefinition) CurrentWorkerContext + .getAttribute(PortalReservedParameters.PORTLET_DEFINITION_ATTRIBUTE); + + if (!oldPortletDefinition.getId().equals( + curPortletDefinition.getId())) + { curEntity.setPortletDefinition(curPortletDefinition); } } } - + if (isParallelMode) { - ServletRequest servletRequest = ((HttpServletRequestWrapper)((HttpServletRequestWrapper) this.request).getRequest()).getRequest(); - + ServletRequest servletRequest = ((HttpServletRequestWrapper) ((HttpServletRequestWrapper) this.request) + .getRequest()).getRequest(); + synchronized (servletRequest) { - this.request.setAttribute(PortalReservedParameters.FRAGMENT_ATTRIBUTE, fragment); - this.request.setAttribute(PortalReservedParameters.PAGE_ATTRIBUTE, requestContext.getPage()); - this.request.setAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE, requestContext); - this.request.setAttribute(PortalReservedParameters.REQUEST_CONTEXT_OBJECTS, requestContext.getObjects()); - // this.request.setAttribute(PortalReservedParameters.CONTENT_DISPATCHER_ATTRIBUTE,dispatcher); + this.request.setAttribute( + PortalReservedParameters.FRAGMENT_ATTRIBUTE, + fragment); + this.request.setAttribute( + PortalReservedParameters.PAGE_ATTRIBUTE, + requestContext.getPage()); + this.request.setAttribute( + PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE, + requestContext); + this.request.setAttribute( + PortalReservedParameters.REQUEST_CONTEXT_OBJECTS, + requestContext.getObjects()); + // this.request.setAttribute(PortalReservedParameters.CONTENT_DISPATCHER_ATTRIBUTE,dispatcher); } } else { - this.request.setAttribute(PortalReservedParameters.FRAGMENT_ATTRIBUTE, fragment); - this.request.setAttribute(PortalReservedParameters.PAGE_ATTRIBUTE, requestContext.getPage()); - this.request.setAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE, requestContext); - this.request.setAttribute(PortalReservedParameters.REQUEST_CONTEXT_OBJECTS, requestContext.getObjects()); - // this.request.setAttribute(PortalReservedParameters.CONTENT_DISPATCHER_ATTRIBUTE,dispatcher); + this.request.setAttribute( + PortalReservedParameters.FRAGMENT_ATTRIBUTE, fragment); + this.request.setAttribute( + PortalReservedParameters.PAGE_ATTRIBUTE, requestContext + .getPage()); + this.request.setAttribute( + PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE, + requestContext); + this.request.setAttribute( + PortalReservedParameters.REQUEST_CONTEXT_OBJECTS, + requestContext.getObjects()); + // this.request.setAttribute(PortalReservedParameters.CONTENT_DISPATCHER_ATTRIBUTE,dispatcher); } - - container.renderPortlet(this.window, this.request, this.response); - this.response.flushBuffer(); + + container.renderPortlet(this.window, this.request, this.response); + this.response.flushBuffer(); } catch (Throwable t) { if (t instanceof UnavailableException) { // no need to dump a full stack trace to the log - log.error("Error rendering portlet OID " + curWindow.getId() + ": " + t.toString()); + log.error("Error rendering portlet OID " + curWindow.getId() + + ": " + t.toString()); } else { - log.error("Error rendering portlet OID " + curWindow.getId(), t); + log + .error("Error rendering portlet OID " + + curWindow.getId(), t); } fragment.overrideRenderedContent(t.getMessage()); } @@ -291,25 +332,31 @@ if (isParallelMode) { this.renderer.addTitleToHeader(curWindow, fragment, - this.request, this.response, - this.dispatcher, this.contentIsCached); - + this.request, this.response, this.dispatcher, + this.contentIsCached); + CurrentWorkerContext.removeAllAttributes(); } - + if (fragment.getType().equals(ContentFragment.PORTLET)) { long end = System.currentTimeMillis(); - boolean exceededTimeout = portletTracking.exceededTimeout(end - start, window); - + boolean exceededTimeout = portletTracking.exceededTimeout( + end - start, window); + if (statistics != null) { - statistics.logPortletAccess(requestContext, fragment.getName(), PortalStatistics.HTTP_OK, end - start); + statistics.logPortletAccess(requestContext, fragment + .getName(), PortalStatistics.HTTP_OK, end + - start); } if (exceededTimeout) { // took too long to render - log.info("Portlet Exceeded timeout: " + curWindow.getPortletEntity().getPortletDefinition().getName() + " for window " + curWindow.getId()); + log.info("Portlet Exceeded timeout: " + + curWindow.getPortletEntity() + .getPortletDefinition().getName() + + " for window " + curWindow.getId()); portletTracking.incrementRenderTimeoutCount(curWindow); } else @@ -334,13 +381,13 @@ } } } - + /** * *

        * getWindow *

        - * + * * @return The window this job is in charge of rendering */ public PortletWindow getWindow() @@ -353,7 +400,7 @@ *

        * getPortletContent *

        - * + * * @return The portlet content this job is in charge of rendering */ public PortletContent getPortletContent() @@ -396,18 +443,18 @@ return this.dispatcher; } - public boolean isContentCached() + public boolean isContentCached() { return this.contentIsCached; } - + public void setWorkerAttribute(String name, Object value) { if (this.workerAttributes == null) { this.workerAttributes = Collections.synchronizedMap(new HashMap()); } - + if (value != null) { this.workerAttributes.put(name, value); @@ -417,19 +464,19 @@ this.workerAttributes.remove(name); } } - + public Object getWorkerAttribute(String name) { Object value = null; - + if (this.workerAttributes != null) { value = this.workerAttributes.get(name); } - + return value; } - + public void removeWorkerAttribute(String name) { if (this.workerAttributes != null) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/WorkerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/WorkerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/WorkerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,21 +33,24 @@ * Worker thread processes jobs and notify its WorkerMonitor when completed. * When no work is available, the worker simply sets itself in a waiting mode * pending reactivation by the WorkerMonitor - * + * * @author Raphael Luta * @author Woonsan Ko * @version $Id: WorkerImpl.java 587064 2007-10-22 11:54:11Z woonsan $ */ public class WorkerImpl extends Thread implements Worker { + /** Commons logging */ protected final static Log log = LogFactory.getLog(WorkerImpl.class); /** Running status of this worker */ private boolean running = true; - /** Counter of consecutive jobs that can be processed before the - worker being actually put back on the idle queue */ + /** + * Counter of consecutive jobs that can be processed before the worker being + * actually put back on the idle queue + */ private int jobCount = 0; /** Job to process */ @@ -87,7 +90,7 @@ */ public void resetJobCount() { - this.jobCount=0; + this.jobCount = 0; } /** @@ -134,8 +137,8 @@ } /** - * Process the job assigned, then notify Monitor. If no job available, - * go into sleep mode + * Process the job assigned, then notify Monitor. If no job available, go + * into sleep mode */ public void run() { @@ -160,7 +163,8 @@ // process it if (this.job != null) { - log.debug("Processing job for window :" + ((RenderingJob)job).getWindow().getId()); + log.debug("Processing job for window :" + + ((RenderingJob) job).getWindow().getId()); Subject subject = null; if (this.context != null) { @@ -169,20 +173,21 @@ if (subject != null) { JSSubject.doAsPrivileged(subject, new PrivilegedAction() + { + + public Object run() { - public Object run() + try { - try - { - WorkerImpl.this.job.run(); - } - catch (Throwable t) - { - log.error("Thread error", t); - } - return null; + WorkerImpl.this.job.run(); } - }, this.context); + catch (Throwable t) + { + log.error("Thread error", t); + } + return null; + } + }, this.context); } else { @@ -203,5 +208,5 @@ ((WorkerMonitorImpl) monitor).release(this); } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/WorkerMonitorImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/WorkerMonitorImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/aggregator/impl/WorkerMonitorImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,57 +19,58 @@ import java.security.AccessControlContext; import java.security.AccessController; +import java.util.ArrayList; +import java.util.Collections; import java.util.Iterator; -import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; import java.util.Stack; -import java.util.LinkedList; -import java.util.Collections; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.jetspeed.aggregator.PortletContent; import org.apache.jetspeed.aggregator.RenderingJob; import org.apache.jetspeed.aggregator.Worker; import org.apache.jetspeed.aggregator.WorkerMonitor; -import org.apache.jetspeed.aggregator.PortletContent; +import org.apache.jetspeed.util.FIFOQueue; import org.apache.jetspeed.util.Queue; -import org.apache.jetspeed.util.FIFOQueue; - +import org.apache.pluto.om.common.ObjectID; import org.apache.pluto.om.window.PortletWindow; -import org.apache.pluto.om.common.ObjectID; /** - * The WorkerMonitor is responsible for dispatching jobs to workers - * It uses an Apache HTTPd configuration style of min/max/spare workers - * threads to throttle the rendering work. - * If jobs come in faster that processing, they are stored in a queue - * which is flushed periodically by a QueueMonitor. - * + * The WorkerMonitor is responsible for dispatching jobs to workers It uses an + * Apache HTTPd configuration style of min/max/spare workers threads to throttle + * the rendering work. If jobs come in faster that processing, they are stored + * in a queue which is flushed periodically by a QueueMonitor. + * * @author Rapha\u00ebl Luta * @author David Sean Taylor * @version $Id: WorkerMonitorImpl.java 591867 2007-11-05 02:20:06Z woonsan $ */ public class WorkerMonitorImpl implements WorkerMonitor { - public static final String ACCESS_CONTROL_CONTEXT_WORKER_ATTR = AccessControlContext.class.getName(); - public WorkerMonitorImpl(int minWorkers, int maxWorkers, int spareWorkers, int maxJobsPerWorker) + public static final String ACCESS_CONTROL_CONTEXT_WORKER_ATTR = AccessControlContext.class + .getName(); + + public WorkerMonitorImpl(int minWorkers, int maxWorkers, int spareWorkers, + int maxJobsPerWorker) { this.minWorkers = minWorkers; this.maxWorkers = maxWorkers; this.spareWorkers = spareWorkers; this.maxJobsPerWorker = maxJobsPerWorker; } - + /** Commons logging */ protected final static Log log = LogFactory.getLog(WorkerMonitorImpl.class); /** Static counters for identifying workers */ protected static long sCount = 0; - /** Count of running jobs **/ + /** Count of running jobs * */ protected int runningJobs = 0; - + /** Minimum number of wokers to create */ protected int minWorkers = 5; @@ -92,7 +93,8 @@ protected Queue queue; /** Workers to be monitored for timeout checking */ - protected List workersMonitored = Collections.synchronizedList(new LinkedList()); + protected List workersMonitored = Collections + .synchronizedList(new LinkedList()); /** Renering Job Timeout monitor */ protected RenderingJobTimeoutMonitor jobMonitor = null; @@ -107,18 +109,18 @@ } public void stop() - { - if (jobMonitor != null) - jobMonitor.endThread(); - jobMonitor = null; - + { + if (jobMonitor != null) jobMonitor.endThread(); + jobMonitor = null; + } /** - * Create the request number of workers and add them to - * list of available workers. - * - * @param wCount the number of workers to create + * Create the request number of workers and add them to list of available + * workers. + * + * @param wCount + * the number of workers to create */ protected synchronized void addWorkers(int wCount) { @@ -131,11 +133,13 @@ wCount = maxWorkers - wCurrent; } - log.info("Creating "+ wCount +" workers -> "+ (wCurrent + wCount)); + log.info("Creating " + wCount + " workers -> " + + (wCurrent + wCount)); for (int i = 0; i < wCount; ++i) { - Worker worker = new WorkerImpl(this, this.tg, "WORKER_" + (++sCount)); + Worker worker = new WorkerImpl(this, this.tg, "WORKER_" + + (++sCount)); worker.start(); workers.push(worker); } @@ -144,32 +148,30 @@ /** * Retrieves an idle worker - * + * * @return a Worker from the idle pool or null if non available */ protected Worker getWorker() { - synchronized(this.workers) + synchronized (this.workers) { if (this.workers.size() < spareWorkers) { addWorkers(spareWorkers); } - if (this.workers.size() == 0) - { - return null; - } + if (this.workers.size() == 0) { return null; } - return (Worker)workers.pop(); + return (Worker) workers.pop(); } } /** - * Assign a job to a worker and execute it or queue the job if no - * worker is available. - * - * @param job the Job to process + * Assign a job to a worker and execute it or queue the job if no worker is + * available. + * + * @param job + * the Job to process */ public void process(RenderingJob job) { @@ -177,8 +179,8 @@ AccessControlContext context = AccessController.getContext(); job.setWorkerAttribute(ACCESS_CONTROL_CONTEXT_WORKER_ATTR, context); - - if (worker==null) + + if (worker == null) { queue.push(job); } @@ -190,7 +192,8 @@ { worker.setJob(job, context); - if (job.getTimeout() > 0) { + if (job.getTimeout() > 0) + { workersMonitored.add(worker); } @@ -204,23 +207,26 @@ } } } - + /** - * Wait for all rendering jobs in the collection to finish successfully or otherwise. - * @param renderingJobs the Collection of rendering job objects to wait for. + * Wait for all rendering jobs in the collection to finish successfully or + * otherwise. + * + * @param renderingJobs + * the Collection of rendering job objects to wait for. */ public void waitForRenderingJobs(List renderingJobs) { - try + try { - for (Iterator iter = renderingJobs.iterator(); iter.hasNext(); ) + for (Iterator iter = renderingJobs.iterator(); iter.hasNext();) { RenderingJob job = (RenderingJob) iter.next(); PortletContent portletContent = job.getPortletContent(); - - synchronized (portletContent) + + synchronized (portletContent) { - if (!portletContent.isComplete()) + if (!portletContent.isComplete()) { portletContent.wait(); } @@ -229,7 +235,10 @@ } catch (Exception e) { - log.error("Exception during synchronizing all portlet rendering jobs.", e); + log + .error( + "Exception during synchronizing all portlet rendering jobs.", + e); } } @@ -254,20 +263,21 @@ synchronized (worker) { RenderingJob job = null; - + if (worker.getJobCount() < this.maxJobsPerWorker) { job = (RenderingJob) queue.pop(); - + if (job != null) { - AccessControlContext context = (AccessControlContext) job.getWorkerAttribute(ACCESS_CONTROL_CONTEXT_WORKER_ATTR); + AccessControlContext context = (AccessControlContext) job + .getWorkerAttribute(ACCESS_CONTROL_CONTEXT_WORKER_ATTR); worker.setJob(job, context); runningJobs--; return; } } - + if (job == null) { worker.setJob(null); @@ -276,7 +286,8 @@ } } - if (jobTimeout > 0) { + if (jobTimeout > 0) + { workersMonitored.remove(worker); } @@ -290,62 +301,72 @@ { return queue.size(); } - + /** * Returns a snapshot of the available jobs + * * @return available jobs */ public int getAvailableJobsCount() { return workers.size(); } - + public int getRunningJobsCount() { return this.tg.activeCount(); } - - class RenderingJobTimeoutMonitor extends Thread { + class RenderingJobTimeoutMonitor extends Thread + { + long interval = 1000; + boolean shouldRun = true; - - RenderingJobTimeoutMonitor(long interval) { + + RenderingJobTimeoutMonitor(long interval) + { super("RenderingJobTimeoutMonitor"); - if (interval > 0) { + if (interval > 0) + { this.interval = interval; } } + /** - * Thread.stop() is deprecated. - * This method achieves the same by setting the run varaible "shouldRun" to false and interrupting the Thread, + * Thread.stop() is deprecated. This method achieves the same by setting + * the run varaible "shouldRun" to false and interrupting the Thread, * effectively causing the thread to shutdown correctly. - * + * */ public void endThread() { - shouldRun = false; - this.interrupt(); + shouldRun = false; + this.interrupt(); } - - public void run() { - while (shouldRun) { - try + + public void run() + { + while (shouldRun) + { + try { - // Because a timeout worker can be removed + // Because a timeout worker can be removed // in the workersMonitored collection during iterating, - // copy timeout workers in the following collection to kill later. + // copy timeout workers in the following collection to kill + // later. List timeoutWorkers = new ArrayList(); - synchronized (workersMonitored) + synchronized (workersMonitored) { - for (Iterator it = workersMonitored.iterator(); it.hasNext(); ) + for (Iterator it = workersMonitored.iterator(); it + .hasNext();) { WorkerImpl worker = (WorkerImpl) it.next(); RenderingJob job = (RenderingJob) worker.getJob(); - + if ((null != job) && (job.isTimeout())) { timeoutWorkers.add(worker); @@ -354,56 +375,65 @@ } // Now, we can kill the timeout worker(s). - for (Iterator it = timeoutWorkers.iterator(); it.hasNext(); ) + for (Iterator it = timeoutWorkers.iterator(); it.hasNext();) { WorkerImpl worker = (WorkerImpl) it.next(); RenderingJob job = (RenderingJob) worker.getJob(); - // If the job is just completed, then do not kill the worker. + // If the job is just completed, then do not kill the + // worker. if ((null != job) && (job.isTimeout())) { killJob(worker, job); } } - } - catch (Exception e) + } + catch (Exception e) { log.error("Exception during job monitoring.", e); } - - try + + try { - synchronized (this) + synchronized (this) { wait(this.interval); } - } - catch (InterruptedException e) + } + catch (InterruptedException e) { ; } } } - public void killJob(WorkerImpl worker, RenderingJob job) { - try { - if (log.isWarnEnabled()) { + public void killJob(WorkerImpl worker, RenderingJob job) + { + try + { + if (log.isWarnEnabled()) + { PortletWindow window = job.getWindow(); ObjectID windowId = (null != window ? window.getId() : null); - log.warn("Portlet Rendering job to be interrupted by timeout (" + job.getTimeout() + "ms): " + windowId); + log + .warn("Portlet Rendering job to be interrupted by timeout (" + + job.getTimeout() + "ms): " + windowId); } PortletContent content = job.getPortletContent(); - + synchronized (content) { - if (!content.isComplete()) { + if (!content.isComplete()) + { worker.interrupt(); content.wait(); } } - - } catch (Exception e) { + + } + catch (Exception e) + { log.error("Exceptiong during job killing.", e); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXFilter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXFilter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXFilter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -35,14 +35,17 @@ * * * @author Scott T. Weaver - * + * */ public class AJAXFilter implements Filter { + private ApplicationContext ctx; + private AJAXService ajaxService; + private FilterConfig config; - + public void init(FilterConfig config) throws ServletException { this.config = config; @@ -50,25 +53,30 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterChain arg2) throws IOException, ServletException - { + { try { response.setContentType("text/xml"); - if(ctx == null) + if (ctx == null) { - ctx = (ApplicationContext)config.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); + ctx = (ApplicationContext) config + .getServletContext() + .getAttribute( + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); ajaxService = (AJAXService) ctx.getBean("AJAXService"); } - - AJAXRequest ajaxRequest = new AJAXRequestImpl((HttpServletRequest) request, (HttpServletResponse) response, config.getServletContext()); + + AJAXRequest ajaxRequest = new AJAXRequestImpl( + (HttpServletRequest) request, + (HttpServletResponse) response, config.getServletContext()); AJAXResponse ajaxReponse = ajaxService.processRequest(ajaxRequest); ajaxReponse.complete(); } catch (AJAXException e) { - ((HttpServletResponse) response).sendError(500, e.getMessage()); + ((HttpServletResponse) response).sendError(500, e.getMessage()); } - catch(Exception e) + catch (Exception e) { throw new ServletException(e.getMessage(), e); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXRequestImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXRequestImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXRequestImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,39 +29,50 @@ * Request used for AJAX services. * * @author Scott T. Weaver - * + * */ public class AJAXRequestImpl implements AJAXRequest { + public static final String AJAX_SERVICE = "ajax_service"; + public static final String AJAX_PARAM_PREFIX = "ajax_param_"; - + private final HttpServletRequest request; + private List ajaxParams; + private final String serviceName; + private final String methodName; + private HttpServletResponse response; + private ServletContext context; - public AJAXRequestImpl(HttpServletRequest request, HttpServletResponse response, ServletContext context) throws AJAXException + public AJAXRequestImpl(HttpServletRequest request, + HttpServletResponse response, ServletContext context) + throws AJAXException { this.request = request; this.response = response; this.context = context; - String serviceRequest = request.getParameter(AJAX_SERVICE); - if(serviceRequest == null ) - { - throw new AJAXException("No '"+AJAX_SERVICE+"' parameter could be found in the request or it was not in the '{service_name}.{method_name}' format."); - } + String serviceRequest = request.getParameter(AJAX_SERVICE); + if (serviceRequest == null) { throw new AJAXException( + "No '" + + AJAX_SERVICE + + "' parameter could be found in the request or it was not in the '{service_name}.{method_name}' format."); } final String split = serviceRequest.split("\\.")[0]; serviceName = split; methodName = serviceRequest.split("\\.")[1]; - + parseRequestArguments(); - + } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.ajax.AJAXRequest#getParameters() */ public List getParameters() @@ -69,7 +80,9 @@ return ajaxParams; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.ajax.AJAXRequest#getServiceName() */ public String getServiceName() @@ -84,17 +97,18 @@ ajaxParams = new ArrayList(); Map rawParams = request.getParameterMap(); Iterator entryItr = rawParams.entrySet().iterator(); - while(entryItr.hasNext()) + while (entryItr.hasNext()) { Map.Entry entry = (Map.Entry) entryItr.next(); String key = entry.getKey().toString(); - - if(key.startsWith(AJAX_PARAM_PREFIX)) + + if (key.startsWith(AJAX_PARAM_PREFIX)) { String[] paramInfo = key.split("_"); int index = Integer.parseInt(paramInfo[2]); - String type = paramInfo[3]; - AJAXParameter ajaxParam = new AJAXParameter(type, (String[])entry.getValue()); + String type = paramInfo[3]; + AJAXParameter ajaxParam = new AJAXParameter(type, + (String[]) entry.getValue()); ajaxParams.add(index, ajaxParam); } } @@ -102,22 +116,25 @@ } catch (Throwable e) { - throw new AJAXException("Errors were encountered parsing request parameters for the AJAX service "+serviceName+": "+e.getMessage(), e); + throw new AJAXException( + "Errors were encountered parsing request parameters for the AJAX service " + + serviceName + ": " + e.getMessage(), e); } } - + public class AJAXParameter { + private Object value; - + public AJAXParameter(String typeName, String[] paramValues) { - if(typeName.equals("int")) - { - if(paramValues.length > 1) + if (typeName.equals("int")) + { + if (paramValues.length > 1) { int[] intValues = new int[paramValues.length]; - for(int i=0; i 1) - { - value = paramValues; - } - else - { - value = paramValues[0]; - } + if (paramValues.length > 1) + { + value = paramValues; + } + else + { + value = paramValues[0]; + } } } - + public Object getValue() { return value; } } - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.ajax.AJAXRequest#getMethodName() */ public String getMethodName() @@ -155,7 +173,9 @@ return methodName; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.ajax.AJAXRequest#getContext() */ public ServletContext getContext() @@ -163,7 +183,9 @@ return context; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.ajax.AJAXRequest#getServletRequest() */ public HttpServletRequest getServletRequest() @@ -171,7 +193,9 @@ return request; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.ajax.AJAXRequest#getServletResponse() */ public HttpServletResponse getServletResponse() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXResponseImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXResponseImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXResponseImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,17 +26,21 @@ * Response object used for AJAX services. * * @author Scott T. Weaver - * + * */ public class AJAXResponseImpl implements AJAXResponse -{ +{ private Context context; + private VelocityEngine engine; + private Reader template; + private Writer output; - public AJAXResponseImpl(Context context, VelocityEngine engine, Reader template, Writer output) + public AJAXResponseImpl(Context context, VelocityEngine engine, + Reader template, Writer output) { this.context = context; this.engine = engine; @@ -44,7 +48,9 @@ this.output = output; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.ajax.AJAXResponse#complete() */ public void complete() throws AJAXException @@ -55,11 +61,10 @@ } catch (Exception e) { - throw new AJAXException("Failed to render velocity xml template: "+e.getMessage(), e); + throw new AJAXException("Failed to render velocity xml template: " + + e.getMessage(), e); } - + } - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXServiceImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXServiceImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXServiceImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -38,28 +38,32 @@ import org.springframework.beans.factory.BeanFactoryAware; /** - * Performs invocation of the actual AJAX request and returns - * a result object to converted into XML. + * Performs invocation of the actual AJAX request and returns a result object to + * converted into XML. * * @author Scott T. Weaver - * + * */ public class AJAXServiceImpl implements AJAXService, BeanFactoryAware { + private Map serviceToBeans; + private Map serviceToTemplates; private BeanFactory beanFactory; + private VelocityEngine engine; public AJAXServiceImpl(Map serviceToBeans) { - this.serviceToBeans = serviceToBeans; + this.serviceToBeans = serviceToBeans; } - public AJAXServiceImpl(Map serviceToBeans, VelocityEngine engine, Map serviceToTemplates) + public AJAXServiceImpl(Map serviceToBeans, VelocityEngine engine, + Map serviceToTemplates) { - this.serviceToBeans = serviceToBeans; + this.serviceToBeans = serviceToBeans; this.engine = engine; this.serviceToTemplates = serviceToTemplates; } @@ -69,67 +73,77 @@ { final String serviceName = request.getServiceName(); final String methodName = request.getMethodName(); - // final String templateName = request.getServletRequest().getServletPath(); + // final String templateName = + // request.getServletRequest().getServletPath(); - final String mappedServiceName = (serviceName+"."+methodName).trim(); + final String mappedServiceName = (serviceName + "." + methodName) + .trim(); try { - if(engine == null) + if (engine == null) { engine = new VelocityEngine(); Properties props = new Properties(); - props.load(request.getContext().getResourceAsStream("/WEB-INF/velocity.properties")); - props.setProperty("file.resource.loader.path", request.getContext().getRealPath("/")); + props.load(request.getContext().getResourceAsStream( + "/WEB-INF/velocity.properties")); + props.setProperty("file.resource.loader.path", request + .getContext().getRealPath("/")); engine.init(); } - - - if(!serviceToBeans.containsKey(mappedServiceName)) - { - throw new AJAXException("There is no AJAX service named '"+mappedServiceName+"' defined. "+ - "Please make sure that your ajax.xml is set up correctly."); - } - - String beanId = ((String)serviceToBeans.get(mappedServiceName)).trim(); + + if (!serviceToBeans.containsKey(mappedServiceName)) { throw new AJAXException( + "There is no AJAX service named '" + + mappedServiceName + + "' defined. " + + "Please make sure that your ajax.xml is set up correctly."); } + + String beanId = ((String) serviceToBeans.get(mappedServiceName)) + .trim(); Object targetService = beanFactory.getBean(beanId); final List parameters = request.getParameters(); - Method method = targetService.getClass().getMethod(methodName, getTypes(parameters)); + Method method = targetService.getClass().getMethod(methodName, + getTypes(parameters)); Object result = method.invoke(targetService, getValues(parameters)); Context context = new VelocityContext(); context.put("ajaxRequest", request); - context.put("result", result); - - String templateName = ((String)serviceToTemplates.get(mappedServiceName)).trim(); - final InputStream templateResource = request.getContext().getResourceAsStream(templateName); - - if(templateResource == null) + context.put("result", result); + + String templateName = ((String) serviceToTemplates + .get(mappedServiceName)).trim(); + final InputStream templateResource = request.getContext() + .getResourceAsStream(templateName); + + if (templateResource == null) { - request.getServletResponse().sendError(404, templateName+" ajax template could not be found."); - throw new IOException(templateName+" does not exist"); + request.getServletResponse().sendError(404, + templateName + " ajax template could not be found."); + throw new IOException(templateName + " does not exist"); } Reader template = new InputStreamReader(templateResource); - + StringWriter stringWriter = new StringWriter(); - AJAXResponse ajaxResponse = new AJAXResponseImpl(context, engine, template, stringWriter); + AJAXResponse ajaxResponse = new AJAXResponseImpl(context, engine, + template, stringWriter); ajaxResponse.complete(); - + String buffer = stringWriter.getBuffer().toString(); - // Put the response XML on the response object + // Put the response XML on the response object HttpServletResponse response = request.getServletResponse(); ServletOutputStream sos = response.getOutputStream(); sos.print(buffer); sos.flush(); return ajaxResponse; } - catch(AJAXException ae) + catch (AJAXException ae) { throw ae; } catch (Exception e) { - throw new AJAXException("Unable to process service" + mappedServiceName + ": " + e.getMessage(), e); + throw new AJAXException("Unable to process service" + + mappedServiceName + ": " + e.getMessage(), e); } } @@ -151,12 +165,13 @@ int i = 0; while (itr.hasNext()) { - args[i] = ((AJAXRequestImpl.AJAXParameter)itr.next()).getValue().getClass(); + args[i] = ((AJAXRequestImpl.AJAXParameter) itr.next()).getValue() + .getClass(); i++; } return args; } - + protected Object[] getValues(List objects) { Object[] args = new Object[objects.size()]; @@ -164,7 +179,7 @@ int i = 0; while (itr.hasNext()) { - args[i] = ((AJAXRequestImpl.AJAXParameter)itr.next()).getValue(); + args[i] = ((AJAXRequestImpl.AJAXParameter) itr.next()).getValue(); i++; } return args; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AJAXValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,28 +32,30 @@ */ public class AJAXValve extends AbstractValve { + private AJAXService ajaxService; + private PortletActionSecurityBehavior securityBehavior; - - public AJAXValve(AJAXService service, PortletActionSecurityBehavior securityBehavior) + + public AJAXValve(AJAXService service, + PortletActionSecurityBehavior securityBehavior) { super(); this.ajaxService = service; this.securityBehavior = securityBehavior; } - - public void invoke( RequestContext request, ValveContext context ) - throws PipelineException + + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { - HttpServletResponse response = request.getResponse(); + HttpServletResponse response = request.getResponse(); try { - response.setContentType("text/xml"); - if (!securityBehavior.checkAccess(request, "edit")) - { - throw new AJAXException("Access Denied."); - } - AJAXRequest ajaxRequest = new AJAXRequestImpl(request.getRequest(), response, request.getConfig().getServletContext()); + response.setContentType("text/xml"); + if (!securityBehavior.checkAccess(request, "edit")) { throw new AJAXException( + "Access Denied."); } + AJAXRequest ajaxRequest = new AJAXRequestImpl(request.getRequest(), + response, request.getConfig().getServletContext()); ajaxService.processRequest(ajaxRequest); } catch (AJAXException e) @@ -67,11 +69,11 @@ throw new PipelineException(e2.getMessage(), e2); } } - catch(Exception e) + catch (Exception e) { throw new PipelineException(e.getMessage(), e); } - + // Pass control to the next Valve in the Pipeline context.invokeNext(request); } @@ -81,6 +83,4 @@ return "AJAXValve"; } - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AjaxRequestServiceImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AjaxRequestServiceImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/ajax/AjaxRequestServiceImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,10 +19,10 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.io.OutputStreamWriter; import java.io.Reader; +import java.io.StringWriter; import java.io.Writer; -import java.io.OutputStreamWriter; -import java.io.StringWriter; import java.util.HashMap; import java.util.Map; @@ -40,8 +40,8 @@ /** * - * Provides a generic way to handle a Ajax request/response. Useful for AJAX since - * the processing can be broken down into actions and builders + * Provides a generic way to handle a Ajax request/response. Useful for AJAX + * since the processing can be broken down into actions and builders */ public class AjaxRequestServiceImpl implements AjaxRequestService { @@ -81,10 +81,10 @@ // Default Action if no action specified protected String defaultAction = "getpage"; - + // Handy Velocity Escape Tool (is threadsafe) protected EscapeTool velocityEscTool = null; - + // Spring can be used to inject this information public AjaxRequestServiceImpl(Map objects, VelocityEngine velocityEngine) { @@ -102,12 +102,12 @@ this.urlParameterName = urlParameterName; this.velocityEscTool = new EscapeTool(); } - + // This is the entry point for this service public void process(RequestContext requestContext) throws AJAXException - { + { // Lookup the object that is to be used - String objectKey = requestContext.getRequestParameter(urlParameterName); + String objectKey = requestContext.getRequestParameter(urlParameterName); if (objectKey == null) { objectKey = defaultAction; @@ -128,7 +128,8 @@ success = processAction((AjaxAction) object, requestContext, resultMap); } - } catch (Exception e) + } + catch (Exception e) { success = false; } @@ -142,12 +143,14 @@ processBuilder((AjaxBuilder) object, resultMap, requestContext, success); } - } catch (Exception e) + } + catch (Exception e) { // The builder failed, return an error response buildError(requestContext); } - } else + } + else { // Log an informational message log.debug("could not find the object named:" + objectKey); @@ -159,8 +162,7 @@ // Process the action if provided protected boolean processAction(AjaxAction action, - RequestContext requestContext, Map resultMap) - throws Exception + RequestContext requestContext, Map resultMap) throws Exception { return action.run(requestContext, resultMap); } @@ -187,7 +189,7 @@ { // Ask the builder to construct the context // Add the input map to the velocity context - + boolean result = true; if (actionSuccessFlag == true) @@ -198,10 +200,10 @@ { result = builder.buildErrorContext(requestContext, inputMap); } - + Context context = new VelocityContext(inputMap); context.put("esc", this.velocityEscTool); - + // Check to see if we have a valid context if (result) { @@ -211,7 +213,7 @@ if (actionSuccessFlag == true) { templateName = builder.getTemplate(); - } + } else { templateName = builder.getErrorTemplate(); @@ -227,52 +229,54 @@ StringWriter stringWriter = new StringWriter(); // Run the velocity template - velocityEngine.evaluate(context, stringWriter, - AJAX_PROCESSOR, template); + velocityEngine.evaluate(context, stringWriter, AJAX_PROCESSOR, + template); // Get the results from the velocity processing String buffer = stringWriter.getBuffer().toString(); - //log.debug("output from AjaxService:" + buffer); + // log.debug("output from AjaxService:" + buffer); // Put the response XML on the response object HttpServletResponse response = requestContext.getResponse(); ServletOutputStream sos = response.getOutputStream(); - + Writer writer = new OutputStreamWriter(sos, "UTF-8"); writer.write(buffer); writer.flush(); - } + } else { log.error("could not create builder context"); buildError(requestContext); } - } catch (Exception e) + } + catch (Exception e) { log.error("builder failed", e); inputMap.put(Constants.REASON, e.toString()); - + buildError(requestContext); } } // This is the last chance to handle an error to send back to the client - // Send back a generic response. Subclasses may want to override this + // Send back a generic response. Subclasses may want to override this // method protected void buildError(RequestContext requestContext) { try { requestContext.getResponse().getOutputStream().print(DEFAULT_ERROR); - } + } catch (IOException e) { - // Not much can be done here, an exception while handling an exception + // Not much can be done here, an exception while handling an + // exception log.error("exception while trying to build an error message", e); } } - + /** * @return Returns the objects. */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/capabilities/impl/CapabilityCustomizerValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/capabilities/impl/CapabilityCustomizerValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/capabilities/impl/CapabilityCustomizerValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,11 +21,10 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.apache.jetspeed.capabilities.Capabilities; import org.apache.jetspeed.capabilities.CapabilityMap; +import org.apache.jetspeed.capabilities.Client; import org.apache.jetspeed.capabilities.MediaType; -import org.apache.jetspeed.capabilities.Client; import org.apache.jetspeed.pipeline.PipelineException; import org.apache.jetspeed.pipeline.valve.AbstractValve; import org.apache.jetspeed.pipeline.valve.ValveContext; @@ -35,17 +34,21 @@ * Invokes the capability customizer in the request pipeline * * @author Woonsan Ko - * @version $Id: CapabilityCustomizerValveImpl.java 517719 2007-03-13 15:05:48Z ate $ + * @version $Id: CapabilityCustomizerValveImpl.java 517719 2007-03-13 15:05:48Z + * ate $ */ public class CapabilityCustomizerValveImpl extends AbstractValve { - private static final Log log = LogFactory.getLog(CapabilityCustomizerValveImpl.class); + private static final Log log = LogFactory + .getLog(CapabilityCustomizerValveImpl.class); private Capabilities capabilities; + private Map clientToMediaTypeMap; - public CapabilityCustomizerValveImpl( Capabilities capabilities, Map clientToMediaTypeMap ) + public CapabilityCustomizerValveImpl(Capabilities capabilities, + Map clientToMediaTypeMap) { this.capabilities = capabilities; this.clientToMediaTypeMap = clientToMediaTypeMap; @@ -59,18 +62,21 @@ } - public void invoke( RequestContext request, ValveContext context ) throws PipelineException + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { CapabilityMap cm = request.getCapabilityMap(); if (cm != null && this.clientToMediaTypeMap != null) { Client client = cm.getClient(); - String mediaTypeName = (String) this.clientToMediaTypeMap.get(client.getName()); - + String mediaTypeName = (String) this.clientToMediaTypeMap + .get(client.getName()); + if (mediaTypeName != null) { - MediaType mediaType = this.capabilities.getMediaType(mediaTypeName); + MediaType mediaType = this.capabilities + .getMediaType(mediaTypeName); cm.setPreferredMediaType(mediaType); request.setMediaType(mediaTypeName); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/capabilities/impl/CapabilityValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/capabilities/impl/CapabilityValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/capabilities/impl/CapabilityValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,11 +37,14 @@ */ public class CapabilityValveImpl implements CapabilityValve { + private static final Log log = LogFactory.getLog(CapabilityValveImpl.class); + String resourceDefault; // the default name for a resource + private Capabilities capabilities; - public CapabilityValveImpl( Capabilities capabilities ) + public CapabilityValveImpl(Capabilities capabilities) { this.capabilities = capabilities; } @@ -54,7 +57,8 @@ } - public void invoke( RequestContext request, ValveContext context ) throws PipelineException + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { String agent = request.getRequest().getHeader("User-Agent"); @@ -66,22 +70,25 @@ } catch (UnableToBuildCapabilityMapException e) { - throw new PipelineException("Falied to create capabilitied: "+e.getMessage(), e); + throw new PipelineException("Falied to create capabilitied: " + + e.getMessage(), e); } - + MediaType mediaType = cm.getPreferredMediaType(); MimeType mimeType = cm.getPreferredType(); if (mediaType == null) { log.error("CapabilityMap returned a null media type"); - throw new PipelineException("CapabilityMap returned a null media type"); + throw new PipelineException( + "CapabilityMap returned a null media type"); } if (mimeType == null) { log.error("CapabilityMap returned a null mime type"); - throw new PipelineException("CapabilityMap returned a null mime type"); + throw new PipelineException( + "CapabilityMap returned a null mime type"); } String encoding = request.getRequest().getCharacterEncoding(); @@ -119,7 +126,8 @@ { contentType.append("; charset=" + encoding); } - String type = contentType.toString(); //mapContentType(request, contentType.toString()); + String type = contentType.toString(); // mapContentType(request, + // contentType.toString()); request.getResponse().setContentType(type); // Pass control to the next Valve in the Pipeline @@ -127,10 +135,9 @@ } static String[][] MIME_MAP = - { - {".pdf", "application/pdf"} - }; - + { + {".pdf", "application/pdf"}}; + protected String mapContentType(RequestContext request, String contentType) { // TODO: get path from servlet request @@ -139,17 +146,14 @@ String path = request.getPath(); if (path != null) { - for (int ix=0; ix < MIME_MAP.length; ix++) + for (int ix = 0; ix < MIME_MAP.length; ix++) { - if (path.endsWith(MIME_MAP[ix][0])) - { - return MIME_MAP[ix][1]; - } - } + if (path.endsWith(MIME_MAP[ix][0])) { return MIME_MAP[ix][1]; } + } } return contentType; } - + public String toString() { return "CapabilityValveImpl"; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/cluster/NodeInformationImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/cluster/NodeInformationImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/cluster/NodeInformationImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,152 +31,155 @@ * @author Hajo Birthelmer * @version */ -public class NodeInformationImpl implements NodeInformation, Serializable +public class NodeInformationImpl implements NodeInformation, Serializable { - static final long serialVersionUID = -598265530537353219L; - private Long id; - private String contextName; - private Date lastDeployDate = null; - private static final int CompressVersion = 1; + static final long serialVersionUID = -598265530537353219L; - /** - * default class construtor required for bean management - * - */ - public NodeInformationImpl() - {} - - /** - * extensible serialization routine - indicates the version written to allow for later structural updates - * - */ - private void writeObject(ObjectOutputStream out) throws IOException - { - out.writeByte(CompressVersion); - out.writeLong(id.longValue()); - out.writeUTF(contextName); - if (lastDeployDate == null) - out.writeByte(0); - else - { - out.writeByte(1); - out.writeLong(lastDeployDate.getTime()); - } - } - /** - * extensible serialization routine - * using the version byte code can identify older versions and handle updates correctly - * - */ - private void readObject(ObjectInputStream in) throws IOException, - ClassNotFoundException - { - int version = in.readByte(); - // do changes here if version dependant + private Long id; - id = new Long(in.readLong()); - contextName = in.readUTF(); - int dateSet = in.readByte(); - - if (dateSet == 1) - lastDeployDate = new Date(in.readLong()); - else - lastDeployDate = null; - } + private String contextName; - public boolean equals(Object object) - { - if (object == this) - return true; - if (!(object instanceof NodeInformation)) - return false; - return equals((NodeInformation) object); - } + private Date lastDeployDate = null; - public int compareTo(Object object) - { - if (object == null) - return 1; - if (object == this) - return 0; - if (!(object instanceof NodeInformation)) - return 1; - return compareTo((NodeInformation) object); - } + private static final int CompressVersion = 1; - public final boolean equals(NodeInformation object) - { - if (object == null) - return false; - return object.getContextName().equalsIgnoreCase(contextName); - } + /** + * default class construtor required for bean management + * + */ + public NodeInformationImpl() + { + } - public final int compareTo(NodeInformation object) - { - return getContextName().compareToIgnoreCase(contextName); - } + /** + * extensible serialization routine - indicates the version written to allow + * for later structural updates + * + */ + private void writeObject(ObjectOutputStream out) throws IOException + { + out.writeByte(CompressVersion); + out.writeLong(id.longValue()); + out.writeUTF(contextName); + if (lastDeployDate == null) + out.writeByte(0); + else + { + out.writeByte(1); + out.writeLong(lastDeployDate.getTime()); + } + } - public String toString() - { - StringBuffer buffer = new StringBuffer(); - buffer.append("id= " + this.id.longValue()); - buffer.append("; contextName= " + this.getContextName()); - buffer.append("; lastDeployDate= " + this.getContextName()); - if (this.lastDeployDate != null) - { - DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT); - try - { - buffer.append(format.format(this.lastDeployDate)); - } catch (Exception e) - { - buffer.append(""); - } - } else - buffer.append(""); + /** + * extensible serialization routine using the version byte code can identify + * older versions and handle updates correctly + * + */ + private void readObject(ObjectInputStream in) throws IOException, + ClassNotFoundException + { + int version = in.readByte(); + // do changes here if version dependant - return buffer.toString(); - } + id = new Long(in.readLong()); + contextName = in.readUTF(); + int dateSet = in.readByte(); - public String getContextName() - { - return contextName; - } + if (dateSet == 1) + lastDeployDate = new Date(in.readLong()); + else + lastDeployDate = null; + } - public void setContextName(String contextName) - { - this.contextName = contextName; - } + public boolean equals(Object object) + { + if (object == this) return true; + if (!(object instanceof NodeInformation)) return false; + return equals((NodeInformation) object); + } - public Long getId() - { - return id; - } + public int compareTo(Object object) + { + if (object == null) return 1; + if (object == this) return 0; + if (!(object instanceof NodeInformation)) return 1; + return compareTo((NodeInformation) object); + } - public void setId(ObjectID id) - { - this.id = new Long(id.toString()); - } + public final boolean equals(NodeInformation object) + { + if (object == null) return false; + return object.getContextName().equalsIgnoreCase(contextName); + } - public void setId(Long id) - { - this.id = id; - } + public final int compareTo(NodeInformation object) + { + return getContextName().compareToIgnoreCase(contextName); + } - public void setId(long id) - { - this.id = new Long(id); - } + public String toString() + { + StringBuffer buffer = new StringBuffer(); + buffer.append("id= " + this.id.longValue()); + buffer.append("; contextName= " + this.getContextName()); + buffer.append("; lastDeployDate= " + this.getContextName()); + if (this.lastDeployDate != null) + { + DateFormat format = DateFormat.getTimeInstance(DateFormat.SHORT); + try + { + buffer.append(format.format(this.lastDeployDate)); + } + catch (Exception e) + { + buffer.append(""); + } + } + else + buffer.append(""); - public Date getLastDeployDate() - { - return lastDeployDate; - } + return buffer.toString(); + } - public void setLastDeployDate(Date lastDeployDate) - { - this.lastDeployDate = lastDeployDate; - } + public String getContextName() + { + return contextName; + } + public void setContextName(String contextName) + { + this.contextName = contextName; + } + + public Long getId() + { + return id; + } + + public void setId(ObjectID id) + { + this.id = new Long(id.toString()); + } + + public void setId(Long id) + { + this.id = id; + } + + public void setId(long id) + { + this.id = new Long(id); + } + + public Date getLastDeployDate() + { + return lastDeployDate; + } + + public void setLastDeployDate(Date lastDeployDate) + { + this.lastDeployDate = lastDeployDate; + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/cluster/NodeManagerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/cluster/NodeManagerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/cluster/NodeManagerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,145 +30,153 @@ import org.springframework.beans.factory.BeanFactoryAware; /** - * Node Manager - * + * Node Manager + * * @author Hajo Birthelmer - * @version + * @version */ -public class NodeManagerImpl implements NodeManager,BeanFactoryAware +public class NodeManagerImpl implements NodeManager, BeanFactoryAware { - protected final static Log log = LogFactory.getLog(NodeManagerImpl.class); + protected final static Log log = LogFactory.getLog(NodeManagerImpl.class); + /** * added support for bean factory to create profile rules */ private BeanFactory beanFactory; - private HashMap nodes = null; - private File rootIndexDir = null; - + private HashMap nodes = null; + + private File rootIndexDir = null; + /** the default criterion bean name */ private String nodeInformationBean = "NodeInformation"; - - public NodeManagerImpl(String indexRoot, String nodeInformationBean) - throws Exception + public NodeManagerImpl(String indexRoot, String nodeInformationBean) + throws Exception { - - //assume it's full path for now + + // assume it's full path for now rootIndexDir = new File(indexRoot); this.nodeInformationBean = nodeInformationBean; - if (!(rootIndexDir.exists())) - rootIndexDir.mkdirs(); + if (!(rootIndexDir.exists())) rootIndexDir.mkdirs(); load(); } - - protected void save() - { - try { - FileOutputStream fout = new FileOutputStream(rootIndexDir.getAbsolutePath()+ "/nodeInfo.ser"); - ObjectOutputStream oos = new ObjectOutputStream(fout); - oos.writeObject(nodes); - oos.close(); - } - catch (Exception e) - { - log.error("Failed to write nodes data file to " + rootIndexDir.getAbsolutePath()+ "/nodeInfo.ser" + " - error : " + e.getLocalizedMessage()); - e.printStackTrace(); - } - } - - protected void load() - { - File data = new File( rootIndexDir.getAbsolutePath()+ "/nodeInfo.ser"); - if (data.exists()) - { - try { - FileInputStream fin = new FileInputStream(data.getAbsolutePath()); - ObjectInputStream ois = new ObjectInputStream(fin); - nodes = (HashMap) ois.readObject(); - ois.close(); - } - catch (Exception e) - { - log.error("Failed to read nodes data file from " + data.getAbsolutePath() + " - error : " + e.getLocalizedMessage()); - nodes = new HashMap(); - } - } - else - { - try - { - data.createNewFile(); - } - catch (Exception e) - { - log.error("Failed to create new nodes data file error : " + e.getLocalizedMessage()); - e.printStackTrace(); - } - nodes = new HashMap(); - } - -// NodeInformationImpl temp = new NodeInformationImpl(); -// temp.setContextName("tttt"); - } - public int checkNode(Long id, String contextName) - { - if ((contextName == null) || (id == null)) - return NodeManager.INVALID_NODE_REQUEST; - NodeInformation info = (NodeInformation)nodes.get(contextName); - if (info == null) - return NodeManager.NODE_NEW; - if (info.getId().longValue() < id.longValue()) - return NodeManager.NODE_OUTDATED; - return NodeManager.NODE_SAVED; - } - - public void addNode(Long id, String contextName) throws Exception - { - if ((contextName == null) || (id == null)) - return; - NodeInformation info = (NodeInformation)nodes.get(contextName); - if (info == null) - { - info = createNodeInformation(); - info.setContextName(contextName); - } - info.setId(id); - nodes.put(contextName, info); - save(); - } + protected void save() + { + try + { + FileOutputStream fout = new FileOutputStream(rootIndexDir + .getAbsolutePath() + + "/nodeInfo.ser"); + ObjectOutputStream oos = new ObjectOutputStream(fout); + oos.writeObject(nodes); + oos.close(); + } + catch (Exception e) + { + log.error("Failed to write nodes data file to " + + rootIndexDir.getAbsolutePath() + "/nodeInfo.ser" + + " - error : " + e.getLocalizedMessage()); + e.printStackTrace(); + } + } - public void removeNode(String contextName) throws Exception - { - if (contextName == null) - return; - NodeInformation info = (NodeInformation)nodes.get(contextName); - if (info == null) - return; - nodes.remove(contextName); - save(); - } + protected void load() + { + File data = new File(rootIndexDir.getAbsolutePath() + "/nodeInfo.ser"); + if (data.exists()) + { + try + { + FileInputStream fin = new FileInputStream(data + .getAbsolutePath()); + ObjectInputStream ois = new ObjectInputStream(fin); + nodes = (HashMap) ois.readObject(); + ois.close(); + } + catch (Exception e) + { + log.error("Failed to read nodes data file from " + + data.getAbsolutePath() + " - error : " + + e.getLocalizedMessage()); + nodes = new HashMap(); + } + } + else + { + try + { + data.createNewFile(); + } + catch (Exception e) + { + log.error("Failed to create new nodes data file error : " + + e.getLocalizedMessage()); + e.printStackTrace(); + } + nodes = new HashMap(); + } - + // NodeInformationImpl temp = new NodeInformationImpl(); + // temp.setContextName("tttt"); + } + + public int checkNode(Long id, String contextName) + { + if ((contextName == null) || (id == null)) + return NodeManager.INVALID_NODE_REQUEST; + NodeInformation info = (NodeInformation) nodes.get(contextName); + if (info == null) return NodeManager.NODE_NEW; + if (info.getId().longValue() < id.longValue()) + return NodeManager.NODE_OUTDATED; + return NodeManager.NODE_SAVED; + } + + public void addNode(Long id, String contextName) throws Exception + { + if ((contextName == null) || (id == null)) return; + NodeInformation info = (NodeInformation) nodes.get(contextName); + if (info == null) + { + info = createNodeInformation(); + info.setContextName(contextName); + } + info.setId(id); + nodes.put(contextName, info); + save(); + } + + public void removeNode(String contextName) throws Exception + { + if (contextName == null) return; + NodeInformation info = (NodeInformation) nodes.get(contextName); + if (info == null) return; + nodes.remove(contextName); + save(); + } + /* * (non-Javadoc) * * @see org.apache.jetspeed.profiler.Profiler#createRuleCriterion() */ - protected NodeInformation createNodeInformation() throws ClassNotFoundException + protected NodeInformation createNodeInformation() + throws ClassNotFoundException { try { - NodeInformation nodeInformation = (NodeInformation) beanFactory.getBean( - this.nodeInformationBean, NodeInformation.class); + NodeInformation nodeInformation = (NodeInformation) beanFactory + .getBean(this.nodeInformationBean, NodeInformation.class); return nodeInformation; - } catch (Exception e) + } + catch (Exception e) { - log.error("Failed to create nodeInformation for " + nodeInformationBean - + " error : " + e.getLocalizedMessage()); + log.error("Failed to create nodeInformation for " + + nodeInformationBean + " error : " + + e.getLocalizedMessage()); throw new ClassNotFoundException("Spring failed to create the " + " nodeInformation bean.", e); } @@ -186,12 +194,9 @@ this.beanFactory = beanFactory; } - public int getNumberOfNodes() - { - return nodes.size(); - } + public int getNumberOfNodes() + { + return nodes.size(); + } - - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/ContainerValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/ContainerValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/ContainerValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,13 +18,13 @@ import javax.servlet.http.HttpServletResponse; -import org.apache.jetspeed.request.RequestContext; import org.apache.jetspeed.container.state.MutableNavigationalState; import org.apache.jetspeed.om.page.Page; import org.apache.jetspeed.om.window.impl.PortletWindowImpl; import org.apache.jetspeed.pipeline.PipelineException; import org.apache.jetspeed.pipeline.valve.AbstractValve; import org.apache.jetspeed.pipeline.valve.ValveContext; +import org.apache.jetspeed.request.RequestContext; import org.apache.pluto.om.window.PortletWindow; /** @@ -38,7 +38,9 @@ */ public class ContainerValve extends AbstractValve { - public void invoke(RequestContext request, ValveContext context) throws PipelineException + + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { try { @@ -46,44 +48,58 @@ request.getRequest().getSession(true); // PortletContainerServices.prepare(); - MutableNavigationalState state = (MutableNavigationalState)request.getPortalURL().getNavigationalState(); + MutableNavigationalState state = (MutableNavigationalState) request + .getPortalURL().getNavigationalState(); if (state != null) { boolean redirect = false; Page page = request.getPage(); PortletWindow window = state.getPortletWindowOfResource(); - if (window != null && page.getFragmentById(window.getId().toString()) == null) + if (window != null + && page.getFragmentById(window.getId().toString()) == null) { - // target window doesn't exists anymore or the target page is not accessible (anymore) - request.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND); + // target window doesn't exists anymore or the target page + // is not accessible (anymore) + request.getResponse().sendError( + HttpServletResponse.SC_NOT_FOUND); return; } window = state.getPortletWindowOfAction(); - if (window != null && page.getFragmentById(window.getId().toString()) == null) + if (window != null + && page.getFragmentById(window.getId().toString()) == null) { if (!((PortletWindowImpl) window).isInstantlyRendered()) { - // target window doesn't exists anymore or the target page is not accessible (anymore) + // target window doesn't exists anymore or the target + // page is not accessible (anymore) // remove any navigational state for the window state.removeState(window); - // as this is an action request which cannot be handled, perform a direct redirect after sync state (for the other windows) + // as this is an action request which cannot be handled, + // perform a direct redirect after sync state (for the + // other windows) redirect = true; } } window = state.getMaximizedWindow(); - if (window != null && page.getFragmentById(window.getId().toString()) == null) + if (window != null + && page.getFragmentById(window.getId().toString()) == null) { - // target window doesn't exists anymore or the target page is not accessible (anymore) + // target window doesn't exists anymore or the target page + // is not accessible (anymore) // remove any navigational state for the window state.removeState(window); } state.sync(request); if (redirect) { - // target page doesn't contain (anymore) the targeted windowOfAction - // this can also occur when a session is expired and the target page isn't accessible for the anonymous user - // Redirect the user back to the target page (with possibly retaining the other windows navigational state). - request.getResponse().sendRedirect(request.getPortalURL().getPortalURL()); + // target page doesn't contain (anymore) the targeted + // windowOfAction + // this can also occur when a session is expired and the + // target page isn't accessible for the anonymous user + // Redirect the user back to the target page (with possibly + // retaining the other windows navigational state). + request.getResponse().sendRedirect( + request.getPortalURL().getPortalURL()); return; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/DesktopPortletContainerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/DesktopPortletContainerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/DesktopPortletContainerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,6 +24,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.jetspeed.desktop.JetspeedDesktop; import org.apache.pluto.PortletContainer; import org.apache.pluto.PortletContainerImpl; import org.apache.pluto.core.InternalActionResponse; @@ -32,73 +33,86 @@ import org.apache.pluto.services.information.InformationProviderAccess; import org.apache.pluto.services.information.PortletURLProvider; -import org.apache.jetspeed.desktop.JetspeedDesktop; - /** - * Desktop Portlet Container implementation. This implementation - * redirects only if the query paramater encoder=desktop is NOT specified. - * When the encoder=desktop parameter is specified, the 'redirect' URL - * is returned in the response body for use by desktop javascript code. + * Desktop Portlet Container implementation. This implementation redirects only + * if the query paramater encoder=desktop is NOT specified. When the + * encoder=desktop parameter is specified, the 'redirect' URL is returned in the + * response body for use by desktop javascript code. * * @author David Sean Taylor * @version $Id: $ */ -public class DesktopPortletContainerImpl extends PortletContainerImpl implements PortletContainer +public class DesktopPortletContainerImpl extends PortletContainerImpl implements + PortletContainer { + private String desktopPipelinePath = null; + private String desktopActionPipelinePath = null; + private String desktopRenderPipelinePath = null; - - public DesktopPortletContainerImpl( String desktopPipelinePath, String desktopActionPipelinePath, String desktopRenderPipelinePath ) + + public DesktopPortletContainerImpl(String desktopPipelinePath, + String desktopActionPipelinePath, String desktopRenderPipelinePath) { - if ( desktopPipelinePath == null || desktopPipelinePath.length() == 0 ) + if (desktopPipelinePath == null || desktopPipelinePath.length() == 0) desktopPipelinePath = JetspeedDesktop.DEFAULT_DESKTOP_PIPELINE_PATH; - if ( desktopPipelinePath.charAt( 0 ) != '/' ) + if (desktopPipelinePath.charAt(0) != '/') desktopPipelinePath = "/" + desktopPipelinePath; - if ( desktopPipelinePath.charAt( desktopPipelinePath.length() -1 ) != '/' ) + if (desktopPipelinePath.charAt(desktopPipelinePath.length() - 1) != '/') desktopPipelinePath = desktopPipelinePath + "/"; - - if ( desktopActionPipelinePath == null || desktopActionPipelinePath.length() == 0 ) + + if (desktopActionPipelinePath == null + || desktopActionPipelinePath.length() == 0) desktopActionPipelinePath = JetspeedDesktop.DEFAULT_DESKTOP_ACTION_PIPELINE_PATH; - if ( desktopActionPipelinePath.charAt( 0 ) != '/' ) + if (desktopActionPipelinePath.charAt(0) != '/') desktopActionPipelinePath = "/" + desktopActionPipelinePath; - if ( desktopActionPipelinePath.charAt( desktopActionPipelinePath.length() -1 ) != '/' ) + if (desktopActionPipelinePath + .charAt(desktopActionPipelinePath.length() - 1) != '/') desktopActionPipelinePath = desktopActionPipelinePath + "/"; - if ( desktopRenderPipelinePath == null || desktopRenderPipelinePath.length() == 0 ) + if (desktopRenderPipelinePath == null + || desktopRenderPipelinePath.length() == 0) desktopRenderPipelinePath = JetspeedDesktop.DEFAULT_DESKTOP_RENDER_PIPELINE_PATH; - if ( desktopRenderPipelinePath.charAt( 0 ) != '/' ) + if (desktopRenderPipelinePath.charAt(0) != '/') desktopRenderPipelinePath = "/" + desktopRenderPipelinePath; - if ( desktopRenderPipelinePath.charAt( desktopRenderPipelinePath.length() -1 ) != '/' ) + if (desktopRenderPipelinePath + .charAt(desktopRenderPipelinePath.length() - 1) != '/') desktopRenderPipelinePath = desktopRenderPipelinePath + "/"; - + this.desktopPipelinePath = desktopPipelinePath; this.desktopActionPipelinePath = desktopActionPipelinePath; this.desktopRenderPipelinePath = desktopRenderPipelinePath; } /** - * This redirect does not redirect, instead returns the redirect URL in the response + * This redirect does not redirect, instead returns the redirect URL in the + * response */ protected void redirect(String location, PortletWindow portletWindow, HttpServletRequest servletRequest, HttpServletResponse servletResponse, InternalActionResponse _actionResponse) throws IOException { - String encoding = servletRequest.getParameter( JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER ); + String encoding = servletRequest + .getParameter(JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER); boolean requestHasDesktopEncoding = false; - boolean requestIsDesktopAjax = false; - if ( encoding != null && encoding.equals( JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER_VALUE ) ) - { // used in cases where action request cannot be made via ajax (e.g. form has element) - requestHasDesktopEncoding = true; - requestIsDesktopAjax = true; - String ajaxOverride = servletRequest.getParameter( JetspeedDesktop.DESKTOP_AJAX_REQUEST_PARAMETER ); - if ( ajaxOverride != null && ajaxOverride.equals( "false" ) ) - { - requestIsDesktopAjax = false; - } + boolean requestIsDesktopAjax = false; + if (encoding != null + && encoding + .equals(JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER_VALUE)) + { // used in cases where action request cannot be made via ajax (e.g. + // form has element) + requestHasDesktopEncoding = true; + requestIsDesktopAjax = true; + String ajaxOverride = servletRequest + .getParameter(JetspeedDesktop.DESKTOP_AJAX_REQUEST_PARAMETER); + if (ajaxOverride != null && ajaxOverride.equals("false")) + { + requestIsDesktopAjax = false; + } } - + if (location == null && _actionResponse != null) { DynamicInformationProvider provider = InformationProviderAccess @@ -145,15 +159,18 @@ { redirectURL.setSecure(); // TBD } - - if ( requestHasDesktopEncoding && ! requestIsDesktopAjax ) - { // add parameter to tell DesktopEncodingPortalURL that it should not add extra desktop parameters (e.g. entity and portlet) - renderParameter.put( JetspeedDesktop.DESKTOP_REQUEST_NOT_AJAX_PARAMETER, Boolean.TRUE ); + + if (requestHasDesktopEncoding && !requestIsDesktopAjax) + { // add parameter to tell DesktopEncodingPortalURL that it should + // not add extra desktop parameters (e.g. entity and portlet) + renderParameter.put( + JetspeedDesktop.DESKTOP_REQUEST_NOT_AJAX_PARAMETER, + Boolean.TRUE); } redirectURL.clearParameters(); redirectURL.setParameters(renderParameter); - + location = servletResponse .encodeRedirectURL(redirectURL.toString()); } @@ -165,19 +182,23 @@ .getResponse(); } - if ( requestIsDesktopAjax ) - { // no real redirect will occur; instead, return the redirect URL in the response body - location = location.replaceAll( this.desktopActionPipelinePath, this.desktopRenderPipelinePath ); - redirectResponse.getWriter().print( location ); + if (requestIsDesktopAjax) + { // no real redirect will occur; instead, return the redirect URL in + // the response body + location = location.replaceAll(this.desktopActionPipelinePath, + this.desktopRenderPipelinePath); + redirectResponse.getWriter().print(location); } else - { // do real redirect - location = location.replaceAll( this.desktopActionPipelinePath, this.desktopPipelinePath ); - location = location.replaceAll( this.desktopRenderPipelinePath, this.desktopPipelinePath); + { // do real redirect + location = location.replaceAll(this.desktopActionPipelinePath, + this.desktopPipelinePath); + location = location.replaceAll(this.desktopRenderPipelinePath, + this.desktopPipelinePath); redirectResponse.sendRedirect(location); } // System.out.println("+++ >>>> location is " + location); - + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/JetspeedPortletContainerWrapper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/JetspeedPortletContainerWrapper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/JetspeedPortletContainerWrapper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -35,25 +35,36 @@ /** * Portlet Container Wrapper to secure access to portlet container. - * + * * @author David Sean Taylor - * @version $Id: JetspeedPortletContainerWrapper.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: JetspeedPortletContainerWrapper.java 516448 2007-03-09 + * 16:25:47Z ate $ */ public class JetspeedPortletContainerWrapper implements PortletContainerWrapper { + private boolean initialized = false; - private static final Log log = LogFactory.getLog(JetspeedPortletContainerWrapper.class); + + private static final Log log = LogFactory + .getLog(JetspeedPortletContainerWrapper.class); + private final PortletContainer pluto; + private final String containerId; + private final Properties properties; + private final PortletContainerEnvironment environment; + private final ServletConfig servletConfig; - + private ServletRequestFactory requestFactory; + private ServletResponseFactory responseFactory; - public JetspeedPortletContainerWrapper(PortletContainer pluto, String containerId, - ServletConfig servletConfig, PortletContainerEnvironment env, Properties properties) + public JetspeedPortletContainerWrapper(PortletContainer pluto, + String containerId, ServletConfig servletConfig, + PortletContainerEnvironment env, Properties properties) { this.pluto = pluto; this.containerId = containerId; @@ -61,15 +72,16 @@ this.properties = properties; this.servletConfig = servletConfig; } - - public JetspeedPortletContainerWrapper(PortletContainer pluto, String containerId, - ServletConfig servletConfig, PortletContainerEnvironment env) + + public JetspeedPortletContainerWrapper(PortletContainer pluto, + String containerId, ServletConfig servletConfig, + PortletContainerEnvironment env) { this(pluto, containerId, servletConfig, env, new Properties()); } - + /** - * Allows starting of the container without providing calling the + * Allows starting of the container without providing calling the * init() method without all of the arguments as the * arguments have already been provided in the constructor. * @@ -81,16 +93,15 @@ this.init(containerId, servletConfig, environment, properties); log.info("Pluto portlet container successfully started."); } - + /** - * initialization is still handled outside component architecture, since Pluto is not a component + * initialization is still handled outside component architecture, since + * Pluto is not a component */ - public synchronized void init( - String uniqueContainerId, - ServletConfig servletConfig, - PortletContainerEnvironment environment, - Properties props) - throws PortletContainerException + public synchronized void init(String uniqueContainerId, + ServletConfig servletConfig, + PortletContainerEnvironment environment, Properties props) + throws PortletContainerException { pluto.init(uniqueContainerId, servletConfig, environment, props); @@ -103,52 +114,58 @@ pluto.shutdown(); } - public void renderPortlet(PortletWindow portletWindow, HttpServletRequest servletRequest, HttpServletResponse servletResponse) - throws PortletException, IOException, PortletContainerException + public void renderPortlet(PortletWindow portletWindow, + HttpServletRequest servletRequest, + HttpServletResponse servletResponse) throws PortletException, + IOException, PortletContainerException { - - if(portletWindow.getPortletEntity() == null) + + if (portletWindow.getPortletEntity() == null) { - log.warn("Could not render PortletWindow "+ portletWindow.getId() + " as it has no PortletEntity defined."); + log.warn("Could not render PortletWindow " + portletWindow.getId() + + " as it has no PortletEntity defined."); return; - } - - if(portletWindow.getPortletEntity().getPortletDefinition() == null) + } + + if (portletWindow.getPortletEntity().getPortletDefinition() == null) { - log.warn("Could not render PortletWindow"+ portletWindow.getId() + " as it has no PortletDefintion defined."); + log.warn("Could not render PortletWindow" + portletWindow.getId() + + " as it has no PortletDefintion defined."); return; } pluto.renderPortlet(portletWindow, servletRequest, servletResponse); - // TODO: figure out how to access pluto-services before container kicks in - // ServletObjectAccess.getServletRequest(servletRequest), - // ServletObjectAccess.getServletResponse(servletResponse)); + // TODO: figure out how to access pluto-services before container kicks + // in + // ServletObjectAccess.getServletRequest(servletRequest), + // ServletObjectAccess.getServletResponse(servletResponse)); } - public void processPortletAction( - PortletWindow portletWindow, - HttpServletRequest servletRequest, - HttpServletResponse servletResponse) - throws PortletException, IOException, PortletContainerException + public void processPortletAction(PortletWindow portletWindow, + HttpServletRequest servletRequest, + HttpServletResponse servletResponse) throws PortletException, + IOException, PortletContainerException { - pluto.processPortletAction(portletWindow, servletRequest, servletResponse); - // ServletObjectAccess.getServletRequest(servletRequest), - // ServletObjectAccess.getServletResponse(servletResponse)); + pluto.processPortletAction(portletWindow, servletRequest, + servletResponse); + // ServletObjectAccess.getServletRequest(servletRequest), + // ServletObjectAccess.getServletResponse(servletResponse)); } - public void portletLoad(PortletWindow portletWindow, HttpServletRequest servletRequest, HttpServletResponse servletResponse) - throws PortletException, PortletContainerException + public void portletLoad(PortletWindow portletWindow, + HttpServletRequest servletRequest, + HttpServletResponse servletResponse) throws PortletException, + PortletContainerException { - pluto.portletLoad( - portletWindow, - requestFactory.getServletRequest(servletRequest, portletWindow), - responseFactory.getServletResponse(servletResponse)); + pluto.portletLoad(portletWindow, requestFactory.getServletRequest( + servletRequest, portletWindow), responseFactory + .getServletResponse(servletResponse)); } /** *

        * isInitialized *

        - * + * * @see org.apache.pluto.PortletContainer#isInitialized() * @return */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/PageHistoryValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/PageHistoryValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/PageHistoryValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,11 +24,10 @@ import org.apache.jetspeed.pipeline.valve.ValveContext; import org.apache.jetspeed.request.RequestContext; - /** *

        - * Valve basically mantains the page navigation history by maintaining a previous page id in the session. - * Required by JS2-806 + * Valve basically mantains the page navigation history by maintaining a + * previous page id in the session. Required by JS2-806 *

        * * @author Mohan Kannapareddy @@ -36,18 +35,24 @@ */ public class PageHistoryValve extends AbstractValve { + protected final Log log = LogFactory.getLog(getClass()); - + // SessionFullExtendedNavigationalState object needs this. public static final String REQUEST_CLEAR_PORTLETS_MODE_AND_WINDOWSTATE_KEY = "clearPortletsModeAndWindowState"; - + private final String SESSION_PREVIOUS_PAGEID_KEY = "PreviousPageId"; + private boolean valveDisabled = false; - - /* (non-Javadoc) - * @see org.apache.jetspeed.pipeline.valve.AbstractValve#invoke(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.pipeline.valve.ValveContext) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.pipeline.valve.AbstractValve#invoke(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.pipeline.valve.ValveContext) */ - public void invoke(RequestContext request, ValveContext context) throws PipelineException + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { if (valveDisabled) { @@ -57,45 +62,56 @@ } } else - { //OK, the valve is enabled check and see if are a inter-page nav. + { // OK, the valve is enabled check and see if are a inter-page nav. try { - // create a session if not already created, necessary for Tomcat 5 + // create a session if not already created, necessary for Tomcat + // 5 request.getRequest().getSession(true); - + Page page = request.getPage(); String curPageId = page.getId(); - - String prevPageId = (String) request.getSessionAttribute(SESSION_PREVIOUS_PAGEID_KEY); + + String prevPageId = (String) request + .getSessionAttribute(SESSION_PREVIOUS_PAGEID_KEY); if (prevPageId == null) { - //First time, lets set it - request.setSessionAttribute(SESSION_PREVIOUS_PAGEID_KEY, curPageId); + // First time, lets set it + request.setSessionAttribute(SESSION_PREVIOUS_PAGEID_KEY, + curPageId); if (log.isDebugEnabled()) { - log.debug("No previous page Id found in session, setting it for the first time"); + log + .debug("No previous page Id found in session, setting it for the first time"); } } else { - + if (prevPageId.equalsIgnoreCase(curPageId)) { if (log.isDebugEnabled()) { - log.debug("Previous page id is same as current page id, not clearing page state"); + log + .debug("Previous page id is same as current page id, not clearing page state"); } } else { if (log.isDebugEnabled()) { - log.debug("Page Change encountered Current Page:" + curPageId + " Prev Page:" + prevPageId); + log.debug("Page Change encountered Current Page:" + + curPageId + " Prev Page:" + prevPageId); } // Make sure we set the prevPageId in session - request.setSessionAttribute(SESSION_PREVIOUS_PAGEID_KEY, curPageId); - // inform NavigationalState object we want to clear all Modes - request.setAttribute(REQUEST_CLEAR_PORTLETS_MODE_AND_WINDOWSTATE_KEY, Boolean.TRUE); + request.setSessionAttribute( + SESSION_PREVIOUS_PAGEID_KEY, curPageId); + // inform NavigationalState object we want to clear all + // Modes + request + .setAttribute( + REQUEST_CLEAR_PORTLETS_MODE_AND_WINDOWSTATE_KEY, + Boolean.TRUE); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/PortletContainerWrapper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/PortletContainerWrapper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/PortletContainerWrapper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,7 +20,7 @@ /** * Portlet Container Wrapper inteface - * + * * @author David Sean Taylor * @version $Id: PortletContainerWrapper.java 516448 2007-03-09 16:25:47Z ate $ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/DefaultPortletRequestResponseUnwrapper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/DefaultPortletRequestResponseUnwrapper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/DefaultPortletRequestResponseUnwrapper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,23 +24,28 @@ import javax.servlet.http.HttpServletResponseWrapper; /** - * DefaultPortletRequestResponseUnwrapper implements PortletRequestResponseUnwrapper - * and finds servlet request or servlet response by simple unwrapping. - * + * DefaultPortletRequestResponseUnwrapper implements + * PortletRequestResponseUnwrapper and finds servlet request or servlet response + * by simple unwrapping. + * * @author Woonsan Ko * @version $Id: $ */ -public class DefaultPortletRequestResponseUnwrapper implements PortletRequestResponseUnwrapper +public class DefaultPortletRequestResponseUnwrapper implements + PortletRequestResponseUnwrapper { + public ServletRequest unwrapPortletRequest(PortletRequest portletRequest) { - ServletRequest servletRequest = ((HttpServletRequestWrapper)((HttpServletRequestWrapper)((HttpServletRequestWrapper)portletRequest).getRequest()).getRequest()).getRequest(); + ServletRequest servletRequest = ((HttpServletRequestWrapper) ((HttpServletRequestWrapper) ((HttpServletRequestWrapper) portletRequest) + .getRequest()).getRequest()).getRequest(); return servletRequest; } - + public ServletResponse unwrapPortletResponse(PortletResponse portletResponse) { - ServletResponse servletResponse = ((HttpServletResponseWrapper) portletResponse).getResponse(); + ServletResponse servletResponse = ((HttpServletResponseWrapper) portletResponse) + .getResponse(); return servletResponse; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/JetspeedPortletInvoker.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/JetspeedPortletInvoker.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/JetspeedPortletInvoker.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,48 +23,62 @@ import org.apache.pluto.om.portlet.PortletDefinition; /** - * JetspeedPortletInvoker extends Pluto's portlet invoker and extends it - * with lifecycle management. Portlet Invokers can be pooled, and activated - * and passivated per request cycle. - * + * JetspeedPortletInvoker extends Pluto's portlet invoker and extends it with + * lifecycle management. Portlet Invokers can be pooled, and activated and + * passivated per request cycle. + * * @author David Sean Taylor * @version $Id: JetspeedPortletInvoker.java 516448 2007-03-09 16:25:47Z ate $ */ public interface JetspeedPortletInvoker extends PortletInvoker { + /** - * Activating an invoker makes it ready to invoke portlets. - * If an invoker's state is not activated, it can not invoke. + * Activating an invoker makes it ready to invoke portlets. If an invoker's + * state is not activated, it can not invoke. * - * @param portletFactory The factory to get access to the portlet being invoked. - * @param portletDefinition The portlet's definition that is being invoked. - * @param servletConfig The servlet configuration of the portal. + * @param portletFactory + * The factory to get access to the portlet being invoked. + * @param portletDefinition + * The portlet's definition that is being invoked. + * @param servletConfig + * The servlet configuration of the portal. * @param containerServlet */ - void activate(PortletFactory portletFactory, PortletDefinition portletDefinition, ServletConfig servletConfig); + void activate(PortletFactory portletFactory, + PortletDefinition portletDefinition, ServletConfig servletConfig); /** - * Activating an invoker makes it ready to invoke portlets. - * If an invoker's state is not activated, it can not invoke. - * This second signature allows for activating with an extra property. + * Activating an invoker makes it ready to invoke portlets. If an invoker's + * state is not activated, it can not invoke. This second signature allows + * for activating with an extra property. * - * @param portletFactory The factory to get access to the portlet being invoked. - * @param portletDefinition The portlet's definition that is being invoked. - * @param servletConfig The servlet configuration of the portal. - * @param property Implementation specific property + * @param portletFactory + * The factory to get access to the portlet being invoked. + * @param portletDefinition + * The portlet's definition that is being invoked. + * @param servletConfig + * The servlet configuration of the portal. + * @param property + * Implementation specific property * @param containerServlet */ - void activate(PortletFactory portletFactory, PortletDefinition portletDefinition, ServletConfig servletConfig, String property); - + void activate(PortletFactory portletFactory, + PortletDefinition portletDefinition, ServletConfig servletConfig, + String property); + /** - * Passivates an invoker, freeing it back to the invoker pool. - * If an invoker's state is passivated, it cannot be used to invoke portlets. + * Passivates an invoker, freeing it back to the invoker pool. If an + * invoker's state is passivated, it cannot be used to invoke portlets. */ void passivate(); - + /** - * Returns true if the state of this invoke is 'activated', and false if it is 'passivated'. - * @return True if the current state of the invoker is 'activated' otherwise false. + * Returns true if the state of this invoke is 'activated', and false if it + * is 'passivated'. + * + * @return True if the current state of the invoker is 'activated' otherwise + * false. */ boolean isActivated(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/LocalPortletInvoker.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/LocalPortletInvoker.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/LocalPortletInvoker.java 2008-05-16 01:54:54 UTC (rev 940) @@ -42,86 +42,110 @@ import org.apache.pluto.om.portlet.PortletDefinition; /** - * LocalPortletInvoker invokes local (internal) portlet applications. - * Local portlet applications are stored within the Jetspeed Portlet application. - * They are not separate web applications; but are stored under Jetspeed's + * LocalPortletInvoker invokes local (internal) portlet applications. Local + * portlet applications are stored within the Jetspeed Portlet application. They + * are not separate web applications; but are stored under Jetspeed's * WEB-INF/apps directory. *

        Sample Configuration

        + * *
          * 
          * factory.invoker.local = org.apache.jetspeed.container.invoker.LocalPortletInvoker
          * factory.invoker.local.pool.size = 50
          *  
          * 
        + * * @author David Sean Taylor * @version $Id: LocalPortletInvoker.java 565870 2007-08-14 19:40:03Z taylor $ */ public class LocalPortletInvoker implements JetspeedPortletInvoker { + private final static Log log = LogFactory.getLog(LocalPortletInvoker.class); protected PortletFactory portletFactory; + protected ServletContext jetspeedContext; + protected ServletConfig jetspeedConfig; + protected PortletDefinition portletDefinition; + protected boolean activated = false; - - /* (non-Javadoc) - * @see org.apache.jetspeed.container.invoker.JetspeedPortletInvoker#activate(PortletFactory,org.apache.pluto.om.portlet.PortletDefinition, javax.servlet.ServletConfig) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.container.invoker.JetspeedPortletInvoker#activate(PortletFactory,org.apache.pluto.om.portlet.PortletDefinition, + * javax.servlet.ServletConfig) */ - public void activate(PortletFactory portletFactory, PortletDefinition portletDefinition, ServletConfig servletConfig) + public void activate(PortletFactory portletFactory, + PortletDefinition portletDefinition, ServletConfig servletConfig) { this.portletFactory = portletFactory; this.jetspeedConfig = servletConfig; jetspeedContext = servletConfig.getServletContext(); this.portletDefinition = portletDefinition; - activated = true; + activated = true; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.invoker.JetspeedPortletInvoker#passivate() */ public void passivate() { - activated = false; + activated = false; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.invoker.JetspeedPortletInvoker#isActivated() */ public boolean isActivated() { return activated; } - + public LocalPortletInvoker() { activated = false; } - - /* (non-Javadoc) - * @see org.apache.pluto.invoker.PortletInvoker#action(javax.portlet.ActionRequest, javax.portlet.ActionResponse) + + /* + * (non-Javadoc) + * + * @see org.apache.pluto.invoker.PortletInvoker#action(javax.portlet.ActionRequest, + * javax.portlet.ActionResponse) */ public void action(ActionRequest request, ActionResponse response) - throws PortletException, IOException + throws PortletException, IOException { invoke(request, response, ContainerConstants.METHOD_ACTION); } - - /* (non-Javadoc) - * @see org.apache.pluto.invoker.PortletInvoker#render(javax.portlet.RenderRequest, javax.portlet.RenderResponse) + + /* + * (non-Javadoc) + * + * @see org.apache.pluto.invoker.PortletInvoker#render(javax.portlet.RenderRequest, + * javax.portlet.RenderResponse) */ public void render(RenderRequest request, RenderResponse response) - throws PortletException, IOException + throws PortletException, IOException { invoke(request, response, ContainerConstants.METHOD_RENDER); } - - /* (non-Javadoc) - * @see org.apache.pluto.invoker.PortletInvoker#load(javax.portlet.PortletRequest, javax.portlet.RenderResponse) + + /* + * (non-Javadoc) + * + * @see org.apache.pluto.invoker.PortletInvoker#load(javax.portlet.PortletRequest, + * javax.portlet.RenderResponse) */ public void load(PortletRequest request, RenderResponse response) - throws PortletException + throws PortletException { try { @@ -129,16 +153,19 @@ } catch (IOException e) { - log.error("LocalPortletInvokerImpl.load() - Error while dispatching portlet.", e); + log + .error( + "LocalPortletInvokerImpl.load() - Error while dispatching portlet.", + e); throw new PortletException(e); } } - - + /** - * Invokes the specific request denoted by the method parameter on a portlet. - * The portlet is invoked with a direct method call on the portlet. It is not invoked in another web application. - * This requires manipulation of the current thread's classpath. + * Invokes the specific request denoted by the method + * parameter on a portlet. The portlet is invoked with a direct method call + * on the portlet. It is not invoked in another web application. This + * requires manipulation of the current thread's classpath. * * @param portletRequest * @param portletResponse @@ -146,34 +173,38 @@ * @throws PortletException * @throws IOException */ - protected void invoke(PortletRequest portletRequest, PortletResponse portletResponse, Integer method) + protected void invoke(PortletRequest portletRequest, + PortletResponse portletResponse, Integer method) throws PortletException, IOException { ClassLoader paClassLoader = portletFactory .getPortletApplicationClassLoader((PortletApplication) portletDefinition .getPortletApplicationDefinition()); - PortletInstance portletInstance = portletFactory.getPortletInstance(jetspeedContext, portletDefinition); + PortletInstance portletInstance = portletFactory.getPortletInstance( + jetspeedContext, portletDefinition); - if (method == ContainerConstants.METHOD_NOOP) - { - return; - } + if (method == ContainerConstants.METHOD_NOOP) { return; } // gather all required data from request and response - ServletRequest servletRequest = ((javax.servlet.http.HttpServletRequestWrapper) portletRequest).getRequest(); + ServletRequest servletRequest = ((javax.servlet.http.HttpServletRequestWrapper) portletRequest) + .getRequest(); ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); try { - PortletRequestContext.createContext(portletDefinition, portletInstance, portletRequest, portletResponse); + PortletRequestContext.createContext(portletDefinition, + portletInstance, portletRequest, portletResponse); - servletRequest.setAttribute(ContainerConstants.PORTLET_CONFIG, portletInstance.getConfig()); - servletRequest.setAttribute(ContainerConstants.PORTLET_REQUEST, portletRequest); - servletRequest.setAttribute(ContainerConstants.PORTLET_RESPONSE, portletResponse); + servletRequest.setAttribute(ContainerConstants.PORTLET_CONFIG, + portletInstance.getConfig()); + servletRequest.setAttribute(ContainerConstants.PORTLET_REQUEST, + portletRequest); + servletRequest.setAttribute(ContainerConstants.PORTLET_RESPONSE, + portletResponse); RequestContext requestContext = (RequestContext) servletRequest .getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); - servletRequest - .setAttribute(ContainerConstants.PORTAL_CONTEXT, requestContext.getRequest().getContextPath()); + servletRequest.setAttribute(ContainerConstants.PORTAL_CONTEXT, + requestContext.getRequest().getContextPath()); Thread.currentThread().setContextClassLoader(paClassLoader); @@ -194,7 +225,7 @@ } catch (Throwable t) { - if ( t instanceof UnavailableException ) + if (t instanceof UnavailableException) { // take it out of service try @@ -206,14 +237,11 @@ // never mind, it won't be used anymore } } - if ( t instanceof PortletException ) + if (t instanceof PortletException) { throw (PortletException) t; } + if (t instanceof IOException) { - throw (PortletException)t; + throw (IOException) t; } - if ( t instanceof IOException ) - { - throw (IOException)t; - } else { throw new PortletException(t); @@ -231,12 +259,17 @@ } } - /* (non-Javadoc) - * @see org.apache.jetspeed.container.invoker.JetspeedPortletInvoker#activate(PortletFactory,org.apache.pluto.om.portlet.PortletDefinition, javax.servlet.ServletConfig, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.container.invoker.JetspeedPortletInvoker#activate(PortletFactory,org.apache.pluto.om.portlet.PortletDefinition, + * javax.servlet.ServletConfig, java.lang.String) */ - public void activate(PortletFactory portletFactory, PortletDefinition portletDefinition, ServletConfig servletConfig, String servletMappingName) + public void activate(PortletFactory portletFactory, + PortletDefinition portletDefinition, ServletConfig servletConfig, + String servletMappingName) { activate(portletFactory, portletDefinition, servletConfig); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/LocalPortletInvokerFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/LocalPortletInvokerFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/LocalPortletInvokerFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,28 +19,30 @@ /** * @author David Sean Taylor * @version $Id: $ - * + * */ -public class LocalPortletInvokerFactory +public class LocalPortletInvokerFactory { + /** *

        * createInstance *

        - * + * * @see org.springframework.beans.factory.config.AbstractFactoryBean#createInstance() * @return * @throws Exception */ - public LocalPortletInvoker createInstance() - { - return new LocalPortletInvoker(); + public LocalPortletInvoker createInstance() + { + return new LocalPortletInvoker(); } /** *

        * getObjectType *

        + * * @see org.springframework.beans.factory.FactoryBean#getObjectType() * @return */ @@ -48,5 +50,5 @@ { return LocalPortletInvoker.class; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/LocalServletRequest.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/LocalServletRequest.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/LocalServletRequest.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,21 +23,21 @@ import javax.servlet.http.HttpServletRequestWrapper; /** - * Local servlet request wrapper. The purpose of this wrapper is to hold - * attribute information that is need for each request. In a threaded environment, - * each thread needs to have its own copy of this information so that there is - * not a timing issue with the original request object. - * Also, since the original request is no longer "holding" the attributes, - * there is no reason to remove them in the finally block. - * The LocalServletRequest object is automatically garbage collected at then - * end of this method. - * + * Local servlet request wrapper. The purpose of this wrapper is to hold + * attribute information that is need for each request. In a threaded + * environment, each thread needs to have its own copy of this information so + * that there is not a timing issue with the original request object. Also, + * since the original request is no longer "holding" the attributes, there is no + * reason to remove them in the finally block. The LocalServletRequest object is + * automatically garbage collected at then end of this method. + * * @author David Sean Taylor * @author David Gurney * @version $Id: $ */ public class LocalServletRequest extends HttpServletRequestWrapper { + private Map attributeMap = new HashMap(); private HttpServletRequest originalRequest = null; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/PortletInvokerFactoryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/PortletInvokerFactoryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/PortletInvokerFactoryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,124 +29,142 @@ /** *

        - * Portlet Invoker Factory creates portlet invokers based on the servlet context. - * This class is part of the contract between Pluto and the Jetspeed Portal as defined - * in the interfaces under org.apache.pluto.factory - * The Pluto container uses portlet invokers to abstract access to portlets. - * An invoker interfaces defines which actions are performed between the portal and container, - * namely action, render and optionally load. Portlet invoker factories are implemented by - * the portal implementation. The Pluto container uses pluggable portlet invoker factories - * in order to get portlet invokers, and then invoke methods on portlets (render, action, load). + * Portlet Invoker Factory creates portlet invokers based on the servlet + * context. This class is part of the contract between Pluto and the Jetspeed + * Portal as defined in the interfaces under + * org.apache.pluto.factory The Pluto container uses portlet + * invokers to abstract access to portlets. An invoker interfaces defines which + * actions are performed between the portal and container, namely action, render + * and optionally load. Portlet invoker factories are implemented by the portal + * implementation. The Pluto container uses pluggable portlet invoker factories + * in order to get portlet invokers, and then invoke methods on portlets + * (render, action, load). *

        *

        - * The Portlet Invoker Factory is a Pluto factory. Pluto defines a basic lifecycle for Pluto - * factory services in the org.apach.pluto.factory.Factory interface with - * standard init and destroy methods. + * The Portlet Invoker Factory is a Pluto factory. Pluto defines a basic + * lifecycle for Pluto factory services in the + * org.apach.pluto.factory.Factory interface with standard + * init and destroy methods. *

        *

        - * The Jetspeed portlet invoker factory supports two kinds of invokers: local and servlet. - * Local portlet invokers call portlets located in the same web applications. - * With local invokers, a simple java method invocation is called on the portlet. - * Servlet portlet invokers call portlets located in another web application. - * With servlet invokers, the servlet request dispatcher is used to call methods on the portlet. + * The Jetspeed portlet invoker factory supports two kinds of invokers: local + * and servlet. Local portlet invokers call portlets located in the same web + * applications. With local invokers, a simple java method invocation is called + * on the portlet. Servlet portlet invokers call portlets located in another web + * application. With servlet invokers, the servlet request dispatcher is used to + * call methods on the portlet. *

        * * @author David Sean Taylor * @version $Id: PortletInvokerFactoryImpl.java 517124 2007-03-12 08:10:25Z ate $ */ -public class PortletInvokerFactoryImpl - implements PortletInvokerFactory +public class PortletInvokerFactoryImpl implements PortletInvokerFactory { - + public final static String INVOKER_SERVLET_MAPPING_NAME = "factory.invoker.servlet.mapping.name"; + public final static String DEFAULT_MAPPING_NAME = "/container"; - + /** The servlet configuration for the Jetspeed portal */ private final ServletConfig servletConfig; private final PortalContext portalContext; - + private final PortletFactory portletFactory; - + private final ServletPortletInvokerFactory servletPortletInvokerFactory; - + private final LocalPortletInvokerFactory localPortletInvokerFactory; - - public PortletInvokerFactoryImpl(ServletConfig servletConfig, PortalContext portalContext, - PortletFactory portletFactory, ServletPortletInvokerFactory servletPortletInvokerFactory, LocalPortletInvokerFactory localPortletInvokerFactory) + + public PortletInvokerFactoryImpl(ServletConfig servletConfig, + PortalContext portalContext, PortletFactory portletFactory, + ServletPortletInvokerFactory servletPortletInvokerFactory, + LocalPortletInvokerFactory localPortletInvokerFactory) { - this.servletConfig = servletConfig; - this.portalContext = portalContext; + this.servletConfig = servletConfig; + this.portalContext = portalContext; this.portletFactory = portletFactory; this.servletPortletInvokerFactory = servletPortletInvokerFactory; - this.localPortletInvokerFactory = localPortletInvokerFactory; + this.localPortletInvokerFactory = localPortletInvokerFactory; } - - /* (non-Javadoc) - * @see org.apache.pluto.factory.Factory#init(javax.servlet.ServletConfig, java.util.Map) + + /* + * (non-Javadoc) + * + * @see org.apache.pluto.factory.Factory#init(javax.servlet.ServletConfig, + * java.util.Map) */ - public void init(ServletConfig config, Map properties) - throws Exception + public void init(ServletConfig config, Map properties) throws Exception { // does absolutely nothing } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.pluto.factory.Factory#destroy() */ - public void destroy() - throws Exception + public void destroy() throws Exception { } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.pluto.factory.PortletInvokerFactory#getPortletInvoker(org.apache.pluto.om.portlet.PortletDefinition) */ public PortletInvoker getPortletInvoker(PortletDefinition portletDefinition) { - MutablePortletApplication app = (MutablePortletApplication)portletDefinition.getPortletApplicationDefinition(); - if(app == null) - { - throw new IllegalStateException("Portlet definition \""+portletDefinition.getName()+"\" is not assigned to a portlet application."); - } - + MutablePortletApplication app = (MutablePortletApplication) portletDefinition + .getPortletApplicationDefinition(); + if (app == null) { throw new IllegalStateException( + "Portlet definition \"" + portletDefinition.getName() + + "\" is not assigned to a portlet application."); } + if (app.getApplicationType() == MutablePortletApplication.LOCAL) { - LocalPortletInvoker localPortletInvoker = localPortletInvokerFactory.createInstance(); - localPortletInvoker.activate(portletFactory, portletDefinition, servletConfig); - return localPortletInvoker; + LocalPortletInvoker localPortletInvoker = localPortletInvokerFactory + .createInstance(); + localPortletInvoker.activate(portletFactory, portletDefinition, + servletConfig); + return localPortletInvoker; } else - { - ServletPortletInvoker servletPortletInvoker = servletPortletInvokerFactory.createInstance(); - String servletMappingName = portalContext.getConfigurationProperty(INVOKER_SERVLET_MAPPING_NAME, DEFAULT_MAPPING_NAME); - servletPortletInvoker.activate(portletFactory, portletDefinition, servletConfig, servletMappingName); + { + ServletPortletInvoker servletPortletInvoker = servletPortletInvokerFactory + .createInstance(); + String servletMappingName = portalContext.getConfigurationProperty( + INVOKER_SERVLET_MAPPING_NAME, DEFAULT_MAPPING_NAME); + servletPortletInvoker.activate(portletFactory, portletDefinition, + servletConfig, servletMappingName); return servletPortletInvoker; } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.pluto.factory.PortletInvokerFactory#releasePortletInvoker(org.apache.pluto.invoker.PortletInvoker) */ public void releasePortletInvoker(PortletInvoker invoker) { // this is now taken care off by Spring's CommonsPoolingTargetSource -// try -// { -// if (invoker instanceof ServletPortletInvoker) -// { -// servletInvokerFactory.releaseObject(invoker); -// } -// else -// { -// localInvokerFactory.releaseObject(invoker); -// } -// } -// catch (Exception e) -// { -// log.error(e); -// } + // try + // { + // if (invoker instanceof ServletPortletInvoker) + // { + // servletInvokerFactory.releaseObject(invoker); + // } + // else + // { + // localInvokerFactory.releaseObject(invoker); + // } + // } + // catch (Exception e) + // { + // log.error(e); + // } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/ServletPortletInvoker.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/ServletPortletInvoker.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/ServletPortletInvoker.java 2008-05-16 01:54:54 UTC (rev 940) @@ -35,26 +35,27 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jetspeed.PortalReservedParameters; +import org.apache.jetspeed.aggregator.CurrentWorkerContext; import org.apache.jetspeed.container.ContainerConstants; import org.apache.jetspeed.container.PortletRequestContext; import org.apache.jetspeed.factory.PortletFactory; import org.apache.jetspeed.factory.PortletInstance; import org.apache.jetspeed.om.common.portlet.MutablePortletApplication; import org.apache.jetspeed.request.RequestContext; -import org.apache.jetspeed.aggregator.CurrentWorkerContext; import org.apache.pluto.om.portlet.PortletDefinition; import org.apache.pluto.om.servlet.WebApplicationDefinition; /** - * ServletPortletInvoker invokes portlets in another web application, calling a - * portlet's render or action method via a cross context request dispatcher. - * In order for this class to work, a servlet must be special servlet must be - * infused into the web (portlet) application. This servlet knows how to delegate - * to portlets and package their response back into a servlet response. - * The context name of the servlet should be configurable. The default context name is "/container" - * ServletPortletInvokerFactory is the factory for creating portlet invokers that - * use Jetspeed Container servlet. + * ServletPortletInvoker invokes portlets in another web application, calling a + * portlet's render or action method via a cross context request dispatcher. In + * order for this class to work, a servlet must be special servlet must be + * infused into the web (portlet) application. This servlet knows how to + * delegate to portlets and package their response back into a servlet response. + * The context name of the servlet should be configurable. The default context + * name is "/container" ServletPortletInvokerFactory is the factory for creating + * portlet invokers that use Jetspeed Container servlet. *

        Sample Factory Configuration

        + * *
          * 
          * factory.invoker.servlet = org.apache.jetspeed.container.invoker.ServletPortletInvoker
        @@ -62,23 +63,31 @@
          * factory.invoker.servlet.mapping.name = /container
          *  
          * 
        + * * @author David Sean Taylor * @version $Id: ServletPortletInvoker.java 598155 2007-11-26 07:41:26Z woonsan $ */ public class ServletPortletInvoker implements JetspeedPortletInvoker { - private final static Log log = LogFactory.getLog(ServletPortletInvoker.class); + private final static Log log = LogFactory + .getLog(ServletPortletInvoker.class); + protected PortletFactory portletFactory; + protected ServletContext jetspeedContext; + protected ServletConfig jetspeedConfig; + protected PortletDefinition portletDefinition; + protected boolean activated = false; + protected String servletMappingName; - + /** - * requestResponseUnwrapper used to unwrap portlet request or portlet response - * to find the real servlet request or servlet response. + * requestResponseUnwrapper used to unwrap portlet request or portlet + * response to find the real servlet request or servlet response. */ protected PortletRequestResponseUnwrapper requestResponseUnwrapper; @@ -86,13 +95,16 @@ { this(new DefaultPortletRequestResponseUnwrapper()); } - - public ServletPortletInvoker(PortletRequestResponseUnwrapper requestResponseUnwrapper) + + public ServletPortletInvoker( + PortletRequestResponseUnwrapper requestResponseUnwrapper) { this.requestResponseUnwrapper = requestResponseUnwrapper; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.invoker.JetspeedPortletInvoker#passivate() */ public void passivate() @@ -100,7 +112,9 @@ activated = false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.invoker.JetspeedPortletInvoker#isActivated() */ public boolean isActivated() @@ -108,10 +122,14 @@ return activated; } - /* (non-Javadoc) - * @see org.apache.jetspeed.container.invoker.JetspeedPortletInvoker#activate(PortletFactory,org.apache.pluto.om.portlet.PortletDefinition, javax.servlet.ServletConfig) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.container.invoker.JetspeedPortletInvoker#activate(PortletFactory,org.apache.pluto.om.portlet.PortletDefinition, + * javax.servlet.ServletConfig) */ - public void activate(PortletFactory portletFactory, PortletDefinition portletDefinition, ServletConfig servletConfig) + public void activate(PortletFactory portletFactory, + PortletDefinition portletDefinition, ServletConfig servletConfig) { this.portletFactory = portletFactory; this.jetspeedConfig = servletConfig; @@ -120,38 +138,46 @@ activated = true; } - /* (non-Javadoc) - * @see org.apache.jetspeed.container.invoker.JetspeedPortletInvoker#activate(PortletFactory,org.apache.pluto.om.portlet.PortletDefinition, javax.servlet.ServletConfig, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.container.invoker.JetspeedPortletInvoker#activate(PortletFactory,org.apache.pluto.om.portlet.PortletDefinition, + * javax.servlet.ServletConfig, java.lang.String) */ - public void activate(PortletFactory portletFactory, PortletDefinition portletDefinition, ServletConfig servletConfig, String servletMappingName) + public void activate(PortletFactory portletFactory, + PortletDefinition portletDefinition, ServletConfig servletConfig, + String servletMappingName) { this.servletMappingName = servletMappingName; activate(portletFactory, portletDefinition, servletConfig); } /** - * + * * @param request * @param response * @throws PortletException */ - public void render(RenderRequest request, RenderResponse response) throws PortletException, IOException + public void render(RenderRequest request, RenderResponse response) + throws PortletException, IOException { invoke(request, response, ContainerConstants.METHOD_RENDER); } /** - * + * */ - public void action(ActionRequest request, ActionResponse response) throws PortletException, IOException + public void action(ActionRequest request, ActionResponse response) + throws PortletException, IOException { invoke(request, response, ContainerConstants.METHOD_ACTION); } /** - * + * */ - public void load(PortletRequest request, RenderResponse response) throws PortletException + public void load(PortletRequest request, RenderResponse response) + throws PortletException { try { @@ -159,65 +185,79 @@ } catch (IOException e) { - log.error("ServletPortletInvokerImpl.load() - Error while dispatching portlet.", e); + log + .error( + "ServletPortletInvokerImpl.load() - Error while dispatching portlet.", + e); throw new PortletException(e); } } /** - * Creates a servlet request dispatcher to dispatch to another web application to render the portlet. - * NOTE: this method requires that your container supports cross-context dispatching. - * Cross-context dispatching is known to work on Tomcat, Catalina, Tomcat-5. - * + * Creates a servlet request dispatcher to dispatch to another web + * application to render the portlet. NOTE: this method requires that your + * container supports cross-context dispatching. Cross-context dispatching + * is known to work on Tomcat, Catalina, Tomcat-5. + * * @param portletRequest * @param portletResponse * @param methodID * @throws PortletException * @throws IOException */ - protected void invoke(PortletRequest portletRequest, PortletResponse portletResponse, Integer methodID) - throws PortletException, IOException + protected void invoke(PortletRequest portletRequest, + PortletResponse portletResponse, Integer methodID) + throws PortletException, IOException { - // In case of parallel mode, the portletDefinition member is not thread-safe. + // In case of parallel mode, the portletDefinition member is not + // thread-safe. // So, hide the member variable by the following local variable. PortletDefinition portletDefinition = null; - // In case of parallel mode, get portlet definition object from the worker thread context. + // In case of parallel mode, get portlet definition object from the + // worker thread context. // Otherwise, refer the member variable. - boolean isParallelMode = CurrentWorkerContext.getParallelRenderingMode(); + boolean isParallelMode = CurrentWorkerContext + .getParallelRenderingMode(); if (isParallelMode) { - portletDefinition = (PortletDefinition) CurrentWorkerContext.getAttribute(PortalReservedParameters.PORTLET_DEFINITION_ATTRIBUTE); + portletDefinition = (PortletDefinition) CurrentWorkerContext + .getAttribute(PortalReservedParameters.PORTLET_DEFINITION_ATTRIBUTE); } - + if (portletDefinition == null) { portletDefinition = this.portletDefinition; } - - MutablePortletApplication app = (MutablePortletApplication)portletDefinition.getPortletApplicationDefinition(); - WebApplicationDefinition webApplicationDefinition = app.getWebApplicationDefinition(); - if(webApplicationDefinition == null) - { - throw new IllegalStateException("Portlet application "+app.getName()+ " has no associated web application."); - } - String portletApplicationName = webApplicationDefinition.getContextRoot(); + MutablePortletApplication app = (MutablePortletApplication) portletDefinition + .getPortletApplicationDefinition(); - ServletContext appContext = jetspeedContext.getContext(portletApplicationName); + WebApplicationDefinition webApplicationDefinition = app + .getWebApplicationDefinition(); + if (webApplicationDefinition == null) { throw new IllegalStateException( + "Portlet application " + app.getName() + + " has no associated web application."); } + String portletApplicationName = webApplicationDefinition + .getContextRoot(); + + ServletContext appContext = jetspeedContext + .getContext(portletApplicationName); if (null == appContext) { - String message = "Failed to find Servlet context for Portlet Application: " + portletApplicationName; + String message = "Failed to find Servlet context for Portlet Application: " + + portletApplicationName; log.error(message); throw new PortletException(message); } - PortletInstance portletInstance = portletFactory.getPortletInstance(appContext, portletDefinition); - RequestDispatcher dispatcher = appContext.getRequestDispatcher(servletMappingName); + PortletInstance portletInstance = portletFactory.getPortletInstance( + appContext, portletDefinition); + RequestDispatcher dispatcher = appContext + .getRequestDispatcher(servletMappingName); if (null == dispatcher) { - String message = - "Failed to get Request Dispatcher for Portlet Application: " + String message = "Failed to get Request Dispatcher for Portlet Application: " + portletApplicationName + ", servlet: " + servletMappingName; @@ -226,57 +266,92 @@ } // gather all required data from request and response - ServletRequest servletRequest = this.requestResponseUnwrapper.unwrapPortletRequest(portletRequest); - ServletResponse servletResponse = this.requestResponseUnwrapper.unwrapPortletResponse(portletResponse); + ServletRequest servletRequest = this.requestResponseUnwrapper + .unwrapPortletRequest(portletRequest); + ServletResponse servletResponse = this.requestResponseUnwrapper + .unwrapPortletResponse(portletResponse); try { - RequestContext requestContext = (RequestContext) servletRequest.getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); - + RequestContext requestContext = (RequestContext) servletRequest + .getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); + if (isParallelMode) { synchronized (servletRequest) { - servletRequest.setAttribute(ContainerConstants.PORTLET, portletInstance); - servletRequest.setAttribute(ContainerConstants.PORTLET_CONFIG, portletInstance.getConfig()); - servletRequest.setAttribute(ContainerConstants.PORTLET_REQUEST, portletRequest); - servletRequest.setAttribute(ContainerConstants.PORTLET_RESPONSE, portletResponse); - servletRequest.setAttribute(ContainerConstants.METHOD_ID, methodID); - servletRequest.setAttribute(ContainerConstants.PORTLET_NAME, app.getName()+"::"+portletDefinition.getName()); - servletRequest.setAttribute(ContainerConstants.PORTAL_CONTEXT, ((HttpServletRequest) servletRequest).getContextPath()); + servletRequest.setAttribute(ContainerConstants.PORTLET, + portletInstance); + servletRequest.setAttribute( + ContainerConstants.PORTLET_CONFIG, portletInstance + .getConfig()); + servletRequest.setAttribute( + ContainerConstants.PORTLET_REQUEST, portletRequest); + servletRequest.setAttribute( + ContainerConstants.PORTLET_RESPONSE, + portletResponse); + servletRequest.setAttribute(ContainerConstants.METHOD_ID, + methodID); + servletRequest.setAttribute( + ContainerConstants.PORTLET_NAME, app.getName() + + "::" + portletDefinition.getName()); + servletRequest.setAttribute( + ContainerConstants.PORTAL_CONTEXT, + ((HttpServletRequest) servletRequest) + .getContextPath()); } } else { - servletRequest.setAttribute(ContainerConstants.PORTLET, portletInstance); - servletRequest.setAttribute(ContainerConstants.PORTLET_CONFIG, portletInstance.getConfig()); - servletRequest.setAttribute(ContainerConstants.PORTLET_REQUEST, portletRequest); - servletRequest.setAttribute(ContainerConstants.PORTLET_RESPONSE, portletResponse); - servletRequest.setAttribute(ContainerConstants.METHOD_ID, methodID); - servletRequest.setAttribute(ContainerConstants.PORTLET_NAME, app.getName()+"::"+portletDefinition.getName()); - servletRequest.setAttribute(ContainerConstants.PORTAL_CONTEXT, requestContext.getRequest().getContextPath()); + servletRequest.setAttribute(ContainerConstants.PORTLET, + portletInstance); + servletRequest.setAttribute(ContainerConstants.PORTLET_CONFIG, + portletInstance.getConfig()); + servletRequest.setAttribute(ContainerConstants.PORTLET_REQUEST, + portletRequest); + servletRequest.setAttribute( + ContainerConstants.PORTLET_RESPONSE, portletResponse); + servletRequest.setAttribute(ContainerConstants.METHOD_ID, + methodID); + servletRequest.setAttribute(ContainerConstants.PORTLET_NAME, + app.getName() + "::" + portletDefinition.getName()); + servletRequest.setAttribute(ContainerConstants.PORTAL_CONTEXT, + requestContext.getRequest().getContextPath()); } // Store same request attributes into the worker in parallel mode. if (isParallelMode) { - CurrentWorkerContext.setAttribute(ContainerConstants.PORTLET, portletInstance); - CurrentWorkerContext.setAttribute(ContainerConstants.PORTLET_CONFIG, portletInstance.getConfig()); - CurrentWorkerContext.setAttribute(ContainerConstants.PORTLET_REQUEST, portletRequest); - CurrentWorkerContext.setAttribute(ContainerConstants.PORTLET_RESPONSE, portletResponse); - CurrentWorkerContext.setAttribute(ContainerConstants.METHOD_ID, methodID); - CurrentWorkerContext.setAttribute(ContainerConstants.PORTLET_NAME, app.getName()+"::"+portletDefinition.getName()); - CurrentWorkerContext.setAttribute(ContainerConstants.PORTAL_CONTEXT, ((HttpServletRequest) servletRequest).getContextPath()); + CurrentWorkerContext.setAttribute(ContainerConstants.PORTLET, + portletInstance); + CurrentWorkerContext.setAttribute( + ContainerConstants.PORTLET_CONFIG, portletInstance + .getConfig()); + CurrentWorkerContext.setAttribute( + ContainerConstants.PORTLET_REQUEST, portletRequest); + CurrentWorkerContext.setAttribute( + ContainerConstants.PORTLET_RESPONSE, portletResponse); + CurrentWorkerContext.setAttribute(ContainerConstants.METHOD_ID, + methodID); + CurrentWorkerContext.setAttribute( + ContainerConstants.PORTLET_NAME, app.getName() + "::" + + portletDefinition.getName()); + CurrentWorkerContext.setAttribute( + ContainerConstants.PORTAL_CONTEXT, + ((HttpServletRequest) servletRequest).getContextPath()); } - PortletRequestContext.createContext(portletDefinition, portletInstance, portletRequest, portletResponse); + PortletRequestContext.createContext(portletDefinition, + portletInstance, portletRequest, portletResponse); dispatcher.include(servletRequest, servletResponse); - + } catch (Exception e) { - String message = - "Failed to dispatch.include for Portlet Application: " + portletApplicationName + ", servlet: " + servletMappingName; + String message = "Failed to dispatch.include for Portlet Application: " + + portletApplicationName + + ", servlet: " + + servletMappingName; log.error(message, e); throw new PortletException(message, e); } @@ -287,13 +362,20 @@ // In parallel mode, remove all attributes of worker context. if (isParallelMode) { - CurrentWorkerContext.removeAttribute(ContainerConstants.PORTLET); - CurrentWorkerContext.removeAttribute(ContainerConstants.PORTLET_CONFIG); - CurrentWorkerContext.removeAttribute(ContainerConstants.PORTLET_REQUEST); - CurrentWorkerContext.removeAttribute(ContainerConstants.PORTLET_RESPONSE); - CurrentWorkerContext.removeAttribute(ContainerConstants.METHOD_ID); - CurrentWorkerContext.removeAttribute(ContainerConstants.PORTLET_NAME); - CurrentWorkerContext.removeAttribute(ContainerConstants.PORTAL_CONTEXT); + CurrentWorkerContext + .removeAttribute(ContainerConstants.PORTLET); + CurrentWorkerContext + .removeAttribute(ContainerConstants.PORTLET_CONFIG); + CurrentWorkerContext + .removeAttribute(ContainerConstants.PORTLET_REQUEST); + CurrentWorkerContext + .removeAttribute(ContainerConstants.PORTLET_RESPONSE); + CurrentWorkerContext + .removeAttribute(ContainerConstants.METHOD_ID); + CurrentWorkerContext + .removeAttribute(ContainerConstants.PORTLET_NAME); + CurrentWorkerContext + .removeAttribute(ContainerConstants.PORTAL_CONTEXT); } servletRequest.removeAttribute(ContainerConstants.PORTLET); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/ServletPortletInvokerFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/ServletPortletInvokerFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/invoker/ServletPortletInvokerFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,23 +19,24 @@ /** * @author David Sean Taylor * @version $Id: $ - * + * */ -public class ServletPortletInvokerFactory +public class ServletPortletInvokerFactory { /** - * requestResponseUnwrapper used to unwrap portlet request or portlet response - * to find the real servlet request or servlet response. + * requestResponseUnwrapper used to unwrap portlet request or portlet + * response to find the real servlet request or servlet response. */ protected PortletRequestResponseUnwrapper requestResponseUnwrapper; - + public ServletPortletInvokerFactory() { this(null); } - public ServletPortletInvokerFactory(PortletRequestResponseUnwrapper requestResponseUnwrapper) + public ServletPortletInvokerFactory( + PortletRequestResponseUnwrapper requestResponseUnwrapper) { this.requestResponseUnwrapper = requestResponseUnwrapper; } @@ -44,20 +45,21 @@ *

        * createInstance *

        - * + * * @see org.springframework.beans.factory.config.AbstractFactoryBean#createInstance() * @return * @throws Exception */ - public ServletPortletInvoker createInstance() - { - return new ServletPortletInvoker(this.requestResponseUnwrapper); + public ServletPortletInvoker createInstance() + { + return new ServletPortletInvoker(this.requestResponseUnwrapper); } /** *

        * getObjectType *

        + * * @see org.springframework.beans.factory.FactoryBean#getObjectType() * @return */ @@ -65,5 +67,5 @@ { return ServletPortletInvoker.class; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,13 +20,14 @@ /** * Jetspeed NamespaceMapper interface extension - * + * * @author Ate Douma * @version $Id: JetspeedNamespaceMapper.java 516448 2007-03-09 16:25:47Z ate $ */ public interface JetspeedNamespaceMapper extends NamespaceMapper { + static final String DEFAULT_PREFIX = "js_"; - + String getPrefix(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapperFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapperFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapperFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,11 +20,13 @@ /** * Jetspeed extension of the NamespaceMapperFactory interface - * + * * @author Ate Douma - * @version $Id: JetspeedNamespaceMapperFactory.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: JetspeedNamespaceMapperFactory.java 516448 2007-03-09 16:25:47Z + * ate $ */ public interface JetspeedNamespaceMapperFactory extends NamespaceMapperFactory { + JetspeedNamespaceMapper getJetspeedNamespaceMapper(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapperFactoryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapperFactoryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapperFactoryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,19 +20,24 @@ /** * Jetspeed version of the Factory implementation for the NamespaceMapper - * + * * @author Ate Douma - * @version $Id: JetspeedNamespaceMapperFactoryImpl.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: JetspeedNamespaceMapperFactoryImpl.java 516448 2007-03-09 + * 16:25:47Z ate $ */ -public class JetspeedNamespaceMapperFactoryImpl implements JetspeedNamespaceMapperFactory +public class JetspeedNamespaceMapperFactoryImpl implements + JetspeedNamespaceMapperFactory { + private JetspeedNamespaceMapper namespaceMapper; - - public void init(javax.servlet.ServletConfig config, java.util.Map properties) throws Exception + + public void init(javax.servlet.ServletConfig config, + java.util.Map properties) throws Exception { - namespaceMapper = (JetspeedNamespaceMapper)properties.get("JetspeedNamespaceMapper"); + namespaceMapper = (JetspeedNamespaceMapper) properties + .get("JetspeedNamespaceMapper"); } - + public void destroy() throws Exception { } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapperImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapperImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/namespace/JetspeedNamespaceMapperImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,105 +18,116 @@ import org.apache.pluto.om.common.ObjectID; - /** * Jetspeed implementation of Name space mapping for creating named attributes. - * + * * @author David Sean Taylor * @author Ate Douma - * @version $Id: JetspeedNamespaceMapperImpl.java 551860 2007-06-29 11:56:23Z ate $ + * @version $Id: JetspeedNamespaceMapperImpl.java 551860 2007-06-29 11:56:23Z + * ate $ */ public class JetspeedNamespaceMapperImpl implements JetspeedNamespaceMapper { + private String prefix; - + public JetspeedNamespaceMapperImpl(String prefix) { this.prefix = prefix; - if ( this.prefix == null ) + if (this.prefix == null) { this.prefix = DEFAULT_PREFIX; - } + } } - + public JetspeedNamespaceMapperImpl() { this(null); } - + public String getPrefix() { return prefix; } - + public String encode(String ns, String name) { - return join(prefix,ns,"_",name,null,null); + return join(prefix, ns, "_", name, null, null); } public String encode(String ns1, String ns2, String name) { - return join(prefix,ns1,"_",ns2,"_",name); + return join(prefix, ns1, "_", ns2, "_", name); } public String decode(String ns, String name) { if (!name.startsWith(prefix)) return null; - String tmp = join(prefix,ns,"_",null,null,null); + String tmp = join(prefix, ns, "_", null, null, null); if (!name.startsWith(tmp)) return null; return name.substring(tmp.length()); } public String encode(long id, String name) { - return encode(new Long(id).toString(),name); + return encode(new Long(id).toString(), name); } - /* (non-Javadoc) - * @see org.apache.pluto.util.NamespaceMapper#encode(org.apache.pluto.om.common.ObjectID, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.pluto.util.NamespaceMapper#encode(org.apache.pluto.om.common.ObjectID, + * java.lang.String) */ public String encode(ObjectID ns, String name) { - return encode(ns.toString(),name); + return encode(ns.toString(), name); } - /* (non-Javadoc) - * @see org.apache.pluto.util.NamespaceMapper#encode(org.apache.pluto.om.common.ObjectID, org.apache.pluto.om.common.ObjectID, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.pluto.util.NamespaceMapper#encode(org.apache.pluto.om.common.ObjectID, + * org.apache.pluto.om.common.ObjectID, java.lang.String) */ public String encode(ObjectID ns1, ObjectID ns2, String name) { - return encode(ns1.toString(),ns2.toString(),name); + return encode(ns1.toString(), ns2.toString(), name); } - /* (non-Javadoc) - * @see org.apache.pluto.util.NamespaceMapper#decode(org.apache.pluto.om.common.ObjectID, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.pluto.util.NamespaceMapper#decode(org.apache.pluto.om.common.ObjectID, + * java.lang.String) */ public String decode(ObjectID ns, String name) { - return decode(ns.toString(),name); + return decode(ns.toString(), name); } - - private static String join(String s1, String s2, String s3, String s4, String s5, String s6) + + private static String join(String s1, String s2, String s3, String s4, + String s5, String s6) { int len = 0; if (s1 != null) { - len+=s1.length(); + len += s1.length(); if (s2 != null) { - len+=s2.length(); + len += s2.length(); if (s3 != null) { - len+=s3.length(); + len += s3.length(); if (s4 != null) { - len+=s4.length(); + len += s4.length(); if (s5 != null) { - len+=s5.length(); + len += s5.length(); if (s6 != null) { - len+=s6.length(); + len += s6.length(); } } } @@ -125,35 +136,35 @@ } char[] buffer = new char[len]; int index = 0; - if (s1 != null) + if (s1 != null) { len = s1.length(); - s1.getChars(0,len,buffer,index); - index+= len; - if (s2 != null) + s1.getChars(0, len, buffer, index); + index += len; + if (s2 != null) { len = s2.length(); - s2.getChars(0,len,buffer,index); - index+= len; - if (s3 != null) + s2.getChars(0, len, buffer, index); + index += len; + if (s3 != null) { len = s3.length(); - s3.getChars(0,len,buffer,index); - index+= len; - if (s4 != null) + s3.getChars(0, len, buffer, index); + index += len; + if (s4 != null) { len = s4.length(); - s4.getChars(0,len,buffer,index); - index+= len; - if (s5 != null) + s4.getChars(0, len, buffer, index); + index += len; + if (s5 != null) { len = s5.length(); - s5.getChars(0,len,buffer,index); - index+= len; - if (s6 != null) + s5.getChars(0, len, buffer, index); + index += len; + if (s6 != null) { len = s6.length(); - s6.getChars(0,len,buffer,index); + s6.getChars(0, len, buffer, index); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/services/log/ContainerLoggerAdaptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/services/log/ContainerLoggerAdaptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/services/log/ContainerLoggerAdaptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,110 +16,135 @@ */ package org.apache.jetspeed.container.services.log; +import org.apache.commons.logging.Log; import org.apache.pluto.services.log.Logger; -import org.apache.commons.logging.Log; /** * ContainerLoggerAdaptor - * + * * @author David Sean Taylor * @version $Id: ContainerLoggerAdaptor.java 516448 2007-03-09 16:25:47Z ate $ */ public class ContainerLoggerAdaptor implements Logger { + private Log log = null; - public ContainerLoggerAdaptor(Log log) + public ContainerLoggerAdaptor(Log log) { this.log = log; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.pluto.services.log.Logger#isDebugEnabled() */ public boolean isDebugEnabled() { return log.isDebugEnabled(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.pluto.services.log.Logger#isInfoEnabled() */ public boolean isInfoEnabled() { return log.isInfoEnabled(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.pluto.services.log.Logger#isWarnEnabled() */ public boolean isWarnEnabled() { return log.isWarnEnabled(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.pluto.services.log.Logger#isErrorEnabled() */ public boolean isErrorEnabled() { return log.isErrorEnabled(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.pluto.services.log.Logger#debug(java.lang.String) */ public void debug(String aMessage) { - log.debug(aMessage); + log.debug(aMessage); } - - /* (non-Javadoc) - * @see org.apache.pluto.services.log.Logger#debug(java.lang.String, java.lang.Throwable) + + /* + * (non-Javadoc) + * + * @see org.apache.pluto.services.log.Logger#debug(java.lang.String, + * java.lang.Throwable) */ public void debug(String aMessage, Throwable aThrowable) { log.debug(aMessage, aThrowable); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.pluto.services.log.Logger#info(java.lang.String) */ public void info(String aMessage) { log.info(aMessage); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.pluto.services.log.Logger#warn(java.lang.String) */ public void warn(String aMessage) { log.warn(aMessage); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.pluto.services.log.Logger#error(java.lang.String) */ public void error(String aMessage) { log.error(aMessage); } - - /* (non-Javadoc) - * @see org.apache.pluto.services.log.Logger#error(java.lang.String, java.lang.Throwable) + + /* + * (non-Javadoc) + * + * @see org.apache.pluto.services.log.Logger#error(java.lang.String, + * java.lang.Throwable) */ public void error(String aMessage, Throwable aThrowable) { log.error(aMessage, aThrowable); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.pluto.services.log.Logger#error(java.lang.Throwable) */ public void error(Throwable aThrowable) { log.error(aThrowable); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/services/log/PlutoLogService.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/services/log/PlutoLogService.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/services/log/PlutoLogService.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,27 +22,27 @@ import org.apache.pluto.services.log.LogService; import org.apache.pluto.services.log.Logger; - /** - * Implements the logging service adaptor for the Pluto container - * adapting Jetspeed logging service implemented in Commons to Pluto + * Implements the logging service adaptor for the Pluto container adapting + * Jetspeed logging service implemented in Commons to Pluto * - * NOTE: this implementation may have performance issues - * since everytime we call isSomethingEnabled, we must get a logger - * I recommend deprecated Pluto's logging container service and - * this adaptor once we get the Pluto source in Apache's CVS + * NOTE: this implementation may have performance issues since everytime we call + * isSomethingEnabled, we must get a logger I recommend deprecated Pluto's + * logging container service and this adaptor once we get the Pluto source in + * Apache's CVS * * @author David Sean Taylor - * @version $Id: PlutoLogService.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: PlutoLogService.java 516448 2007-03-09 16:25:47Z ate $ */ -public class PlutoLogService - implements LogService +public class PlutoLogService implements LogService { - private final static Log defaultLog = LogFactory.getLog(PlutoLogService.class); - + private final static Log defaultLog = LogFactory + .getLog(PlutoLogService.class); - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.pluto.services.log.LogService#getLogger(java.lang.String) */ public Logger getLogger(String component) @@ -50,29 +50,33 @@ return new ContainerLoggerAdaptor(getConfiguredLogger(component)); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.pluto.services.log.LogService#getLogger(java.lang.Class) */ public Logger getLogger(Class klass) { - + return new ContainerLoggerAdaptor(getConfiguredLogger(klass)); } /** - * Given a string class name returns a logger for that class, or if we can't find a logger for the class - * the it returns the default logger for this class + * Given a string class name returns a logger for that class, or if we can't + * find a logger for the class the it returns the default logger for this + * class * * @param className - * @return Log The logger configured for the given class name or the default logger if failed to load class + * @return Log The logger configured for the given class name or the default + * logger if failed to load class */ private Log getConfiguredLogger(String className) { Class classe = null; Log log = defaultLog; - + try - { + { classe = Class.forName(className); log = LogFactory.getLog(classe); } @@ -82,31 +86,34 @@ } catch (LogConfigurationException e) { - // use the default logger + // use the default logger } - return log; + return log; } /** - * Given a string class name returns a logger for that class, or if we can't find a logger for the class - * the it returns the default logger for this class + * Given a string class name returns a logger for that class, or if we can't + * find a logger for the class the it returns the default logger for this + * class * - * @param classe the class to get a logger for - * @return Log The logger configured for the given class name or the default logger if failed to load class + * @param classe + * the class to get a logger for + * @return Log The logger configured for the given class name or the default + * logger if failed to load class */ private Log getConfiguredLogger(Class classe) { Log log = defaultLog; - + try - { + { log = LogFactory.getLog(classe); } catch (LogConfigurationException e) { - // use the default logger + // use the default logger } - return log; + return log; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionMonitorImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionMonitorImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionMonitorImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,31 +25,37 @@ /** * PortalSessionMonitorImpl - * + * * @author Ate Douma * @version $Id: $ */ public class PortalSessionMonitorImpl implements PortalSessionMonitor { + private static final long serialVersionUID = 1239564779524373742L; private long sessionKey; + private transient String sessionId; + private transient HttpSession session; + private boolean forceInvalidate; - + public PortalSessionMonitorImpl(long sessionKey) { - this(sessionKey,true); + this(sessionKey, true); } - + public PortalSessionMonitorImpl(long sessionKey, boolean forceInvalidate) { this.sessionKey = sessionKey; this.forceInvalidate = forceInvalidate; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.session.PortalSessionMonitor#getSessionId() */ public String getSessionId() @@ -57,27 +63,30 @@ return sessionId; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.session.PortalSessionMonitor#getSessionKey() */ public long getSessionKey() { return sessionKey; } - + public HttpSession getSession() { return session; } - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.session.PortalSessionMonitor#invalidateSession() */ public void invalidateSession() { HttpSession thisSession = session; - if ( thisSession != null ) + if (thisSession != null) { session = null; if (forceInvalidate) @@ -94,7 +103,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpSessionBindingListener#valueBound(javax.servlet.http.HttpSessionBindingEvent) */ public void valueBound(HttpSessionBindingEvent event) @@ -103,19 +114,22 @@ this.sessionId = session.getId(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpSessionBindingListener#valueUnbound(javax.servlet.http.HttpSessionBindingEvent) */ public void valueUnbound(HttpSessionBindingEvent event) { - if ( session != null ) + if (session != null) { - try { - if (session.getAttribute(SESSION_KEY) != null) { - return; - } - } catch (Exception e) { + try + { + if (session.getAttribute(SESSION_KEY) != null) { return; } } + catch (Exception e) + { + } PortalSessionsManager manager = getManager(); if (manager != null) { @@ -125,7 +139,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpSessionActivationListener#sessionDidActivate(javax.servlet.http.HttpSessionEvent) */ public void sessionDidActivate(HttpSessionEvent event) @@ -139,7 +155,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpSessionActivationListener#sessionWillPassivate(javax.servlet.http.HttpSessionEvent) */ public void sessionWillPassivate(HttpSessionEvent event) @@ -155,10 +173,8 @@ private PortalSessionsManager getManager() { PortletServices services = JetspeedPortletServices.getSingleton(); - if (services != null) - { - return (PortalSessionsManager)services.getService(PortalSessionsManager.SERVICE_NAME); - } + if (services != null) { return (PortalSessionsManager) services + .getService(PortalSessionsManager.SERVICE_NAME); } return null; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionsManagerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionsManagerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/session/PortalSessionsManagerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,7 +30,7 @@ /** * PortalSessionsManagerImpl - * + * * @author Ate Douma * @version $Id: $ */ @@ -38,53 +38,63 @@ { private static Log log = LogFactory.getLog(PortalSessionsManagerImpl.class); - + private static final class PortalSessionRegistry { + long portalSessionKey; + PortalSessionMonitor psm; + Map sessionMonitors; - + PortalSessionRegistry() { sessionMonitors = Collections.synchronizedMap(new HashMap()); } } - + private long portalSessionKeySequence; + private Map portalSessionsRegistry; + private boolean forceInvalidate; - + public PortalSessionsManagerImpl() { - this(true); + this(true); } - + public PortalSessionsManagerImpl(boolean forceInvalidate) { portalSessionKeySequence = System.currentTimeMillis(); portalSessionsRegistry = Collections.synchronizedMap(new HashMap()); this.forceInvalidate = forceInvalidate; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.session.PortalSessionsManager#portalSessionCreated(javax.servlet.http.HttpSession) */ public void portalSessionCreated(HttpSession portalSession) { PortalSessionMonitor psm = null; - - synchronized (this) + + synchronized (this) { - psm = new PortalSessionMonitorImpl(++portalSessionKeySequence, forceInvalidate); + psm = new PortalSessionMonitorImpl(++portalSessionKeySequence, + forceInvalidate); } - + portalSession.setAttribute(PortalSessionMonitor.SESSION_KEY, psm); // register it as if activated portalSessionDidActivate(psm); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.session.PortalSessionsManager#portalSessionWillPassivate(org.apache.jetspeed.container.session.PortalSessionMonitor) */ public void portalSessionWillPassivate(PortalSessionMonitor psm) @@ -92,20 +102,26 @@ portalSessionsRegistry.remove(psm.getSessionId()); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.session.PortalSessionsManager#portalSessionDidActivate(org.apache.jetspeed.container.session.PortalSessionMonitor) */ public void portalSessionDidActivate(PortalSessionMonitor restoredPsm) { - PortalSessionRegistry psr = (PortalSessionRegistry)portalSessionsRegistry.get(restoredPsm.getSessionId()); - if ( psr != null && psr.portalSessionKey != -1 && psr.portalSessionKey != restoredPsm.getSessionKey() ) + PortalSessionRegistry psr = (PortalSessionRegistry) portalSessionsRegistry + .get(restoredPsm.getSessionId()); + if (psr != null && psr.portalSessionKey != -1 + && psr.portalSessionKey != restoredPsm.getSessionKey()) { - // looks like Client didn't join the previous portal session while the sessionId is reused (cookies disabled?) - // destroy the "old" portal Session and any (probably also not-joined) registered paSessions + // looks like Client didn't join the previous portal session while + // the sessionId is reused (cookies disabled?) + // destroy the "old" portal Session and any (probably also + // not-joined) registered paSessions portalSessionDestroyed(psr.psm); psr = null; } - if ( psr == null ) + if (psr == null) { psr = new PortalSessionRegistry(); portalSessionsRegistry.put(restoredPsm.getSessionId(), psr); @@ -114,13 +130,15 @@ psr.psm = restoredPsm; psr.portalSessionKey = restoredPsm.getSessionKey(); // validate registered paSessions are in sync - // we iterate with shallow copy of paSessions to avoid conflicts with concurrent updates of paSessions - Iterator iter = valuesShallowCopy(psr.sessionMonitors.values()).iterator(); + // we iterate with shallow copy of paSessions to avoid conflicts with + // concurrent updates of paSessions + Iterator iter = valuesShallowCopy(psr.sessionMonitors.values()) + .iterator(); PortletApplicationSessionMonitor pasm; while (iter.hasNext()) { - pasm = (PortletApplicationSessionMonitor)iter.next(); - if ( pasm.getPortalSessionKey() != psr.portalSessionKey ) + pasm = (PortletApplicationSessionMonitor) iter.next(); + if (pasm.getPortalSessionKey() != psr.portalSessionKey) { pasm.invalidateSession(); // remove from original map ! @@ -129,25 +147,32 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.session.PortalSessionsManager#portalSessionDestroyed(org.apache.jetspeed.container.session.PortalSessionMonitor) */ public void portalSessionDestroyed(PortalSessionMonitor psm) { - PortalSessionRegistry psr = (PortalSessionRegistry)portalSessionsRegistry.remove(psm.getSessionId()); - if ( psr != null ) + PortalSessionRegistry psr = (PortalSessionRegistry) portalSessionsRegistry + .remove(psm.getSessionId()); + if (psr != null) { - // we iterate with shallow copy of paSessions to avoid conflicts with concurrent updates of paSessions - Iterator iter = valuesShallowCopy(psr.sessionMonitors.values()).iterator(); + // we iterate with shallow copy of paSessions to avoid conflicts + // with concurrent updates of paSessions + Iterator iter = valuesShallowCopy(psr.sessionMonitors.values()) + .iterator(); while (iter.hasNext()) { - ((PortletApplicationSessionMonitor) iter.next()).invalidateSession(); + ((PortletApplicationSessionMonitor) iter.next()) + .invalidateSession(); } - + try { // To make sure its gone. - // You better not remove the psm from the portal session yourself ;) + // You better not remove the psm from the portal session + // yourself ;) psm.invalidateSession(); } catch (IllegalStateException ise) @@ -157,58 +182,75 @@ } } - /* (non-Javadoc) - * @see org.apache.jetspeed.container.session.PortalSessionsManager#checkMonitorSession(java.lang.String, javax.servlet.http.HttpSession, javax.servlet.http.HttpSession) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.container.session.PortalSessionsManager#checkMonitorSession(java.lang.String, + * javax.servlet.http.HttpSession, javax.servlet.http.HttpSession) */ - public void checkMonitorSession(String contextPath, HttpSession portalSession, HttpSession paSession) + public void checkMonitorSession(String contextPath, + HttpSession portalSession, HttpSession paSession) { - if ( portalSession != null && paSession != null ) + if (portalSession != null && paSession != null) { if (portalSession == paSession) { // On WebSphere 6.1.0.11, strange symptoms like this occur... - log.warn("servlet context name of paSession(" + paSession.getId() + "): " + paSession.getServletContext().getServletContextName()); + log + .warn("servlet context name of paSession(" + + paSession.getId() + + "): " + + paSession.getServletContext() + .getServletContextName()); return; } - PortalSessionRegistry psr = (PortalSessionRegistry)portalSessionsRegistry.get(portalSession.getId()); + PortalSessionRegistry psr = (PortalSessionRegistry) portalSessionsRegistry + .get(portalSession.getId()); if (psr == null) { - // yet unexplained condition: the HttpSessionListener on the portal application *should* have registered the session!!! + // yet unexplained condition: the HttpSessionListener on the + // portal application *should* have registered the session!!! // Alas, it has been reported to happen... // Now trying to do some recovering here - PortalSessionMonitor psm = (PortalSessionMonitor)portalSession.getAttribute(PortalSessionMonitor.SESSION_KEY); - // the psm better be null here, otherwise something really is corrupt or not playing by the listeners contracts - if ( psm == null ) + PortalSessionMonitor psm = (PortalSessionMonitor) portalSession + .getAttribute(PortalSessionMonitor.SESSION_KEY); + // the psm better be null here, otherwise something really is + // corrupt or not playing by the listeners contracts + if (psm == null) { portalSessionCreated(portalSession); } else { // Now we have discovered a really strange situation here - // Only explanation I can see is that a passivation of the portalSession occurred, - // but that the activation again didn't trigger the sessionDidActivate event handler??? - // Lets just try to accomodate this situation for now: + // Only explanation I can see is that a passivation of the + // portalSession occurred, + // but that the activation again didn't trigger the + // sessionDidActivate event handler??? + // Lets just try to accomodate this situation for now: portalSessionDidActivate(psm); } // now retrieve the just created psr again - psr = (PortalSessionRegistry)portalSessionsRegistry.get(portalSession.getId()); + psr = (PortalSessionRegistry) portalSessionsRegistry + .get(portalSession.getId()); } - if (psr == null) { - return; - } - PortletApplicationSessionMonitor pasm = (PortletApplicationSessionMonitor)psr.sessionMonitors.get(contextPath); - if ( pasm != null ) + if (psr == null) { return; } + PortletApplicationSessionMonitor pasm = (PortletApplicationSessionMonitor) psr.sessionMonitors + .get(contextPath); + if (pasm != null) { try { - if ( paSession.getAttribute(PortletApplicationSessionMonitor.SESSION_KEY) == null ) + if (paSession + .getAttribute(PortletApplicationSessionMonitor.SESSION_KEY) == null) { // looks like Client didn't join the previous pa session // destroy the "old" paSession - pasm.invalidateSession(); + pasm.invalidateSession(); pasm = null; - // no need to remove the "old" pasm from the sessionMonitors as it will be replaced right below + // no need to remove the "old" pasm from the + // sessionMonitors as it will be replaced right below } } catch (IllegalStateException ise) @@ -216,12 +258,15 @@ // paSession already invalid, ignore } } - if ( pasm == null ) + if (pasm == null) { - pasm = new PortletApplicationSessionMonitorImpl(contextPath,portalSession.getId(),psr.portalSessionKey, forceInvalidate); + pasm = new PortletApplicationSessionMonitorImpl(contextPath, + portalSession.getId(), psr.portalSessionKey, + forceInvalidate); try { - paSession.setAttribute(PortletApplicationSessionMonitor.SESSION_KEY, pasm); + paSession.setAttribute( + PortletApplicationSessionMonitor.SESSION_KEY, pasm); psr.sessionMonitors.put(contextPath, pasm); } catch (IllegalStateException ise) @@ -231,48 +276,63 @@ } } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.session.PortalSessionsManager#sessionWillPassivate(org.apache.jetspeed.container.session.PortletApplicationSessionMonitor) */ public void sessionWillPassivate(PortletApplicationSessionMonitor pasm) { - PortalSessionRegistry psr = (PortalSessionRegistry)portalSessionsRegistry.get(pasm.getPortalSessionId()); - if (psr != null ) + PortalSessionRegistry psr = (PortalSessionRegistry) portalSessionsRegistry + .get(pasm.getPortalSessionId()); + if (psr != null) { psr.sessionMonitors.remove(pasm.getContextPath()); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.session.PortalSessionsManager#sessionDidActivate(org.apache.jetspeed.container.session.PortletApplicationSessionMonitor) */ public void sessionDidActivate(PortletApplicationSessionMonitor restoredPasm) { - PortalSessionRegistry psr = (PortalSessionRegistry)portalSessionsRegistry.get(restoredPasm.getPortalSessionId()); - if ( psr == null ) + PortalSessionRegistry psr = (PortalSessionRegistry) portalSessionsRegistry + .get(restoredPasm.getPortalSessionId()); + if (psr == null) { - // looks like the portalSession was passivated or the paSession was replicated to another JVM while its related portalSession wasn't (yet) - // so, we're gonna anticipate future activation of the portalSession: - // create a temporary psr with an "empty" psm for now (portalSessionKey == -1) - // once the portalSession is replicated/Activated, it will validate registered paSessions having the correct portalSessionKey + // looks like the portalSession was passivated or the paSession was + // replicated to another JVM while its related portalSession wasn't + // (yet) + // so, we're gonna anticipate future activation of the + // portalSession: + // create a temporary psr with an "empty" psm for now + // (portalSessionKey == -1) + // once the portalSession is replicated/Activated, it will validate + // registered paSessions having the correct portalSessionKey psr = new PortalSessionRegistry(); psr.psm = new PortalSessionMonitorImpl(-1); portalSessionsRegistry.put(restoredPasm.getPortalSessionId(), psr); } - + // save the restored instance - restoredPasm.getSession().setAttribute(PortletApplicationSessionMonitor.SESSION_KEY, restoredPasm); + restoredPasm.getSession().setAttribute( + PortletApplicationSessionMonitor.SESSION_KEY, restoredPasm); psr.sessionMonitors.put(restoredPasm.getContextPath(), restoredPasm); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.container.session.PortalSessionsManager#sessionDestroyed(org.apache.jetspeed.container.session.PortletApplicationSessionMonitor) */ public void sessionDestroyed(PortletApplicationSessionMonitor pasm) { - PortalSessionRegistry psr = (PortalSessionRegistry)portalSessionsRegistry.get(pasm.getPortalSessionId()); - if ( psr != null ) + PortalSessionRegistry psr = (PortalSessionRegistry) portalSessionsRegistry + .get(pasm.getPortalSessionId()); + if (psr != null) { psr.sessionMonitors.remove(pasm.getContextPath()); @@ -289,20 +349,25 @@ } } - /* (non-Javadoc) - * @see org.apache.jetspeed.container.session.PortalSessionsManager#sessionCount() - */ - public int sessionCount() { - - return portalSessionsRegistry.size(); - } + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.container.session.PortalSessionsManager#sessionCount() + */ + public int sessionCount() + { + return portalSessionsRegistry.size(); + } + /** * Returns a shallow copy of the given Collection. + * * @param inValues * @return shallow copy */ - private Collection valuesShallowCopy(Collection inValues) { + private Collection valuesShallowCopy(Collection inValues) + { return Arrays.asList(inValues.toArray()); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/AbstractNavigationalState.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/AbstractNavigationalState.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/AbstractNavigationalState.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,62 +32,76 @@ /** * BaseNavigationalState - * + * * @author David Sean Taylor * @version $Id: AbstractNavigationalState.java 554926 2007-07-10 13:12:26Z ate $ */ -public abstract class AbstractNavigationalState implements MutableNavigationalState +public abstract class AbstractNavigationalState implements + MutableNavigationalState { + private NavigationalStateCodec codec; + private PortletWindowRequestNavigationalStates requestStates; + protected JetspeedContentCache cache; + protected JetspeedContentCache decorationCache; - - public AbstractNavigationalState(NavigationalStateCodec codec, JetspeedContentCache cache) + + public AbstractNavigationalState(NavigationalStateCodec codec, + JetspeedContentCache cache) { this(codec, cache, null); } - public AbstractNavigationalState(NavigationalStateCodec codec, JetspeedContentCache cache, JetspeedContentCache decorationCache) + public AbstractNavigationalState(NavigationalStateCodec codec, + JetspeedContentCache cache, JetspeedContentCache decorationCache) { this.codec = codec; this.cache = cache; this.decorationCache = decorationCache; } - + public void init(String encodedState, String characterEncoding) - throws UnsupportedEncodingException + throws UnsupportedEncodingException { - if ( requestStates == null ) + if (requestStates == null) { requestStates = codec.decode(encodedState, characterEncoding); } } - + protected PortletWindowRequestNavigationalStates getPortletWindowRequestNavigationalStates() { return requestStates; } - + public void setState(PortletWindow window, WindowState windowState) { - if ( windowState != null ) + if (windowState != null) { - if (!JetspeedActions.getStandardWindowStates().contains(windowState)) + if (!JetspeedActions.getStandardWindowStates() + .contains(windowState)) { - PortletApplication pa = (PortletApplication)window.getPortletEntity().getPortletDefinition().getPortletApplicationDefinition(); + PortletApplication pa = (PortletApplication) window + .getPortletEntity().getPortletDefinition() + .getPortletApplicationDefinition(); windowState = pa.getMappedWindowState(windowState); } String windowId = window.getId().toString(); - PortletWindowRequestNavigationalState state = requestStates.getPortletWindowNavigationalState(windowId); - if (state != null && (state.getWindowState() == null || !state.getWindowState().equals(windowState))) + PortletWindowRequestNavigationalState state = requestStates + .getPortletWindowNavigationalState(windowId); + if (state != null + && (state.getWindowState() == null || !state + .getWindowState().equals(windowState))) { state.setWindowState(windowState); } else { state = new PortletWindowRequestNavigationalState(windowId); - requestStates.addPortletWindowNavigationalState(windowId, state); + requestStates + .addPortletWindowNavigationalState(windowId, state); state.setWindowState(windowState); } if (windowState.equals(WindowState.MAXIMIZED)) @@ -99,23 +113,30 @@ public void setMode(PortletWindow window, PortletMode portletMode) { - if ( portletMode != null ) + if (portletMode != null) { - if (!JetspeedActions.getStandardPortletModes().contains(portletMode)) + if (!JetspeedActions.getStandardPortletModes() + .contains(portletMode)) { - PortletApplication pa = (PortletApplication)window.getPortletEntity().getPortletDefinition().getPortletApplicationDefinition(); + PortletApplication pa = (PortletApplication) window + .getPortletEntity().getPortletDefinition() + .getPortletApplicationDefinition(); portletMode = pa.getMappedPortletMode(portletMode); } String windowId = window.getId().toString(); - PortletWindowRequestNavigationalState state = requestStates.getPortletWindowNavigationalState(windowId); - if (state != null && (state.getPortletMode() == null || !state.getPortletMode().equals(portletMode))) + PortletWindowRequestNavigationalState state = requestStates + .getPortletWindowNavigationalState(windowId); + if (state != null + && (state.getPortletMode() == null || !state + .getPortletMode().equals(portletMode))) { state.setPortletMode(portletMode); } else { state = new PortletWindowRequestNavigationalState(windowId); - requestStates.addPortletWindowNavigationalState(windowId, state); + requestStates + .addPortletWindowNavigationalState(windowId, state); state.setPortletMode(portletMode); } } @@ -124,7 +145,8 @@ public WindowState getMappedState(String windowId) { WindowState windowState = null; - PortletWindowRequestNavigationalState state = requestStates.getPortletWindowNavigationalState(windowId); + PortletWindowRequestNavigationalState state = requestStates + .getPortletWindowNavigationalState(windowId); if (state != null) { windowState = state.getWindowState(); @@ -143,9 +165,12 @@ public WindowState getState(PortletWindow window) { WindowState state = getMappedState(window.getId().toString()); - if (state != null && !JetspeedActions.getStandardWindowStates().contains(state)) + if (state != null + && !JetspeedActions.getStandardWindowStates().contains(state)) { - PortletApplication pa = (PortletApplication)window.getPortletEntity().getPortletDefinition().getPortletApplicationDefinition(); + PortletApplication pa = (PortletApplication) window + .getPortletEntity().getPortletDefinition() + .getPortletApplicationDefinition(); state = pa.getCustomWindowState(state); } return state; @@ -159,14 +184,15 @@ public PortletMode getMappedMode(String windowId) { PortletMode portletMode = null; - PortletWindowRequestNavigationalState state = requestStates.getPortletWindowNavigationalState(windowId); + PortletWindowRequestNavigationalState state = requestStates + .getPortletWindowNavigationalState(windowId); if (state != null) { portletMode = state.getPortletMode(); } return portletMode != null ? portletMode : PortletMode.VIEW; } - + /** * @deprecated */ @@ -174,13 +200,16 @@ { return getMappedMode(windowId); } - + public PortletMode getMode(PortletWindow window) { PortletMode mode = getMappedMode(window.getId().toString()); - if (mode != null && !JetspeedActions.getStandardPortletModes().contains(mode)) + if (mode != null + && !JetspeedActions.getStandardPortletModes().contains(mode)) { - PortletApplication pa = (PortletApplication)window.getPortletEntity().getPortletDefinition().getPortletApplicationDefinition(); + PortletApplication pa = (PortletApplication) window + .getPortletEntity().getPortletDefinition() + .getPortletApplicationDefinition(); mode = pa.getCustomPortletMode(mode); } return mode; @@ -198,8 +227,9 @@ public Iterator getParameterNames(PortletWindow window) { - PortletWindowRequestNavigationalState state = requestStates.getPortletWindowNavigationalState(window.getId().toString()); - if ( state != null && state.getParametersMap() != null ) + PortletWindowRequestNavigationalState state = requestStates + .getPortletWindowNavigationalState(window.getId().toString()); + if (state != null && state.getParametersMap() != null) { return state.getParametersMap().keySet().iterator(); } @@ -209,12 +239,14 @@ } } - public String[] getParameterValues(PortletWindow window, String parameterName) + public String[] getParameterValues(PortletWindow window, + String parameterName) { - PortletWindowRequestNavigationalState state = requestStates.getPortletWindowNavigationalState(window.getId().toString()); - if ( state != null && state.getParametersMap() != null ) + PortletWindowRequestNavigationalState state = requestStates + .getPortletWindowNavigationalState(window.getId().toString()); + if (state != null && state.getParametersMap() != null) { - return (String[])state.getParametersMap().get(parameterName); + return (String[]) state.getParametersMap().get(parameterName); } else { @@ -226,52 +258,70 @@ { return requestStates.getActionWindow(); } - + public PortletWindow getPortletWindowOfResource() { return requestStates.getResourceWindow(); } - public String encode(PortletWindow window, Map parameters, PortletMode mode, WindowState state, boolean action) - throws UnsupportedEncodingException + public String encode(PortletWindow window, Map parameters, + PortletMode mode, WindowState state, boolean action) + throws UnsupportedEncodingException { - if ( mode != null || state != null ) + if (mode != null || state != null) { PortletApplication pa = null; - if (mode != null && !JetspeedActions.getStandardPortletModes().contains(mode)) + if (mode != null + && !JetspeedActions.getStandardPortletModes() + .contains(mode)) { - pa = (PortletApplication)window.getPortletEntity().getPortletDefinition().getPortletApplicationDefinition(); + pa = (PortletApplication) window.getPortletEntity() + .getPortletDefinition() + .getPortletApplicationDefinition(); mode = pa.getMappedPortletMode(mode); } - if (state != null && !JetspeedActions.getStandardWindowStates().contains(state)) + if (state != null + && !JetspeedActions.getStandardWindowStates().contains( + state)) { - if ( pa == null ) + if (pa == null) { - pa = (PortletApplication)window.getPortletEntity().getPortletDefinition().getPortletApplicationDefinition(); + pa = (PortletApplication) window.getPortletEntity() + .getPortletDefinition() + .getPortletApplicationDefinition(); } state = pa.getMappedWindowState(state); } } - return codec.encode(requestStates, window, parameters, mode, state, action, isNavigationalParameterStateFull(), + return codec.encode(requestStates, window, parameters, mode, state, + action, isNavigationalParameterStateFull(), isRenderParameterStateFull()); } - public String encode(PortletWindow window, PortletMode mode, WindowState state) - throws UnsupportedEncodingException + public String encode(PortletWindow window, PortletMode mode, + WindowState state) throws UnsupportedEncodingException { - if ( mode != null || state != null ) + if (mode != null || state != null) { PortletApplication pa = null; - if (mode != null && !JetspeedActions.getStandardPortletModes().contains(mode)) + if (mode != null + && !JetspeedActions.getStandardPortletModes() + .contains(mode)) { - pa = (PortletApplication)window.getPortletEntity().getPortletDefinition().getPortletApplicationDefinition(); + pa = (PortletApplication) window.getPortletEntity() + .getPortletDefinition() + .getPortletApplicationDefinition(); mode = pa.getMappedPortletMode(mode); } - if (state != null && !JetspeedActions.getStandardWindowStates().contains(state)) + if (state != null + && !JetspeedActions.getStandardWindowStates().contains( + state)) { - if ( pa == null ) + if (pa == null) { - pa = (PortletApplication)window.getPortletEntity().getPortletDefinition().getPortletApplicationDefinition(); + pa = (PortletApplication) window.getPortletEntity() + .getPortletDefinition() + .getPortletApplicationDefinition(); } state = pa.getMappedWindowState(state); } @@ -283,10 +333,12 @@ WindowState targetState = state; if (this instanceof SessionNavigationalState) { - currentWindowStates = ((SessionNavigationalState)this).getCurrentPageWindowStates(); + currentWindowStates = ((SessionNavigationalState) this) + .getCurrentPageWindowStates(); if (currentWindowStates != null) { - windowNavState = (PortletWindowExtendedNavigationalState)currentWindowStates.get(window.getId().toString()); + windowNavState = (PortletWindowExtendedNavigationalState) currentWindowStates + .get(window.getId().toString()); if (windowNavState != null) { if (targetMode == null) @@ -297,39 +349,46 @@ { targetState = windowNavState.getWindowState(); } - encodedState = windowNavState.getDecoratorActionEncoding(targetMode, targetState); + encodedState = windowNavState.getDecoratorActionEncoding( + targetMode, targetState); } } } if (encodedState == null) { - encodedState = codec.encode(requestStates, window, mode, state, isNavigationalParameterStateFull(), isRenderParameterStateFull()); + encodedState = codec.encode(requestStates, window, mode, state, + isNavigationalParameterStateFull(), + isRenderParameterStateFull()); if (currentWindowStates != null) { if (windowNavState == null) { windowNavState = new PortletWindowExtendedNavigationalState(); - currentWindowStates.put(window.getId().toString(), windowNavState); + currentWindowStates.put(window.getId().toString(), + windowNavState); } - windowNavState.setDecoratorActionEncoding(targetMode, targetState, encodedState); + windowNavState.setDecoratorActionEncoding(targetMode, + targetState, encodedState); } } return encodedState; } - + public String encode() throws UnsupportedEncodingException { - return codec.encode(requestStates, isNavigationalParameterStateFull(), isRenderParameterStateFull()); + return codec.encode(requestStates, isNavigationalParameterStateFull(), + isRenderParameterStateFull()); } public Iterator getWindowIdIterator() { return requestStates.getWindowIdIterator(); } - + public void clearParameters(PortletWindow window) { - PortletWindowRequestNavigationalState state = requestStates.getPortletWindowNavigationalState(window.getId().toString()); + PortletWindowRequestNavigationalState state = requestStates + .getPortletWindowNavigationalState(window.getId().toString()); if (state != null) { Map map = state.getParametersMap(); @@ -340,9 +399,10 @@ } } } - + public void removeState(PortletWindow window) { - requestStates.removePortletWindowNavigationalState(window.getId().toString()); + requestStates.removePortletWindowNavigationalState(window.getId() + .toString()); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/HybridNavigationalState.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/HybridNavigationalState.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/HybridNavigationalState.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.container.state.impl; import java.io.UnsupportedEncodingException; @@ -31,28 +31,32 @@ * HybridNavigationalState * * Only encodes render parameters that start with a given prefix - * + * * @author David Sean Taylor - * @version $Id: AbstractNavigationalState.java 333093 2005-11-13 18:42:42Z taylor $ + * @version $Id: AbstractNavigationalState.java 333093 2005-11-13 18:42:42Z + * taylor $ */ public class HybridNavigationalState extends SessionNavigationalState { + protected String prefix; - - public HybridNavigationalState(NavigationalStateCodec codec, String prefix, JetspeedContentCache cache) + + public HybridNavigationalState(NavigationalStateCodec codec, String prefix, + JetspeedContentCache cache) { super(codec, cache); this.prefix = prefix; } - - public String encode(PortletWindow window, Map parameters, PortletMode mode, WindowState state, boolean action) - throws UnsupportedEncodingException + + public String encode(PortletWindow window, Map parameters, + PortletMode mode, WindowState state, boolean action) + throws UnsupportedEncodingException { Map subset = new HashMap(); Iterator params = parameters.keySet().iterator(); while (params.hasNext()) { - String key = (String)params.next(); + String key = (String) params.next(); if (key.startsWith(prefix)) { // only encode params that start with prefix @@ -71,6 +75,5 @@ { return false; } - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/JetspeedNavigationalStateCodec.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/JetspeedNavigationalStateCodec.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/JetspeedNavigationalStateCodec.java 2008-05-16 01:54:54 UTC (rev 940) @@ -35,103 +35,126 @@ /** * JetspeedNavigationalStateCodec - * + * * @author Ate Douma - * @version $Id: JetspeedNavigationalStateCodec.java 554926 2007-07-10 13:12:26Z ate $ + * @version $Id: JetspeedNavigationalStateCodec.java 554926 2007-07-10 13:12:26Z + * ate $ */ public class JetspeedNavigationalStateCodec implements NavigationalStateCodec { + /** Commons logging */ - protected final static Log log = LogFactory.getLog(JetspeedNavigationalStateCodec.class); + protected final static Log log = LogFactory + .getLog(JetspeedNavigationalStateCodec.class); protected static final char PARAMETER_SEPARATOR = '|'; - protected static final char PARAMETER_ELEMENT_SEPARATOR = '='; + + protected static final char PARAMETER_ELEMENT_SEPARATOR = '='; + protected static final char RENDER_WINDOW_ID_KEY = 'a'; + protected static final char ACTION_WINDOW_ID_KEY = 'b'; + protected static final char MODE_KEY = 'c'; + protected static final char STATE_KEY = 'd'; + protected static final char PARAM_KEY = 'e'; + protected static final char CLEAR_PARAMS_KEY = 'f'; + protected static final char RESOURCE_WINDOW_ID_KEY = 'g'; - + protected static final String keytable = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + protected final PortletMode[] portletModes; + protected final WindowState[] windowStates; + private final PortletWindowAccessor windowAccessor; - - public JetspeedNavigationalStateCodec(PortalContext portalContext, PortletWindowAccessor windowAccessor) + + public JetspeedNavigationalStateCodec(PortalContext portalContext, + PortletWindowAccessor windowAccessor) { ArrayList list = new ArrayList(); this.windowAccessor = windowAccessor; - + // ensure standard modes will be first in the portletModeNames array - // this ensures those modes are never lost from a bookmarked url when new modes are added somewhere in the + // this ensures those modes are never lost from a bookmarked url when + // new modes are added somewhere in the // middle list.addAll(JetspeedActions.getStandardPortletModes()); list.addAll(JetspeedActions.getExtendedPortletModes()); - - portletModes = (PortletMode[])list.toArray(new PortletMode[list.size()]); - if (portletModes.length > keytable.length()) - { - throw new UnsupportedOperationException("Too many supported PortletModes found. Can only handle max: "+keytable.length()); - } - + + portletModes = (PortletMode[]) list + .toArray(new PortletMode[list.size()]); + if (portletModes.length > keytable.length()) { throw new UnsupportedOperationException( + "Too many supported PortletModes found. Can only handle max: " + + keytable.length()); } + list.clear(); - + // ensure standard states will be first in the windowStateNames array - // this ensures those states are never lost from a bookmarked url when new states are added somewhere in the + // this ensures those states are never lost from a bookmarked url when + // new states are added somewhere in the // middle list.addAll(JetspeedActions.getStandardWindowStates()); list.addAll(JetspeedActions.getExtendedWindowStates()); - - windowStates = (WindowState[])list.toArray(new WindowState[list.size()]); - if (windowStates.length > keytable.length()) - { - throw new UnsupportedOperationException("Too many supported WindowModes found. Can only handle max: "+keytable.length()); - } + + windowStates = (WindowState[]) list + .toArray(new WindowState[list.size()]); + if (windowStates.length > keytable.length()) { throw new UnsupportedOperationException( + "Too many supported WindowModes found. Can only handle max: " + + keytable.length()); } } - - public PortletWindowRequestNavigationalStates decode(String parameters, String characterEncoding) - throws UnsupportedEncodingException + + public PortletWindowRequestNavigationalStates decode(String parameters, + String characterEncoding) throws UnsupportedEncodingException { - PortletWindowRequestNavigationalStates states = new PortletWindowRequestNavigationalStates(characterEncoding); - if ( parameters != null && parameters.length() > 0 ) + PortletWindowRequestNavigationalStates states = new PortletWindowRequestNavigationalStates( + characterEncoding); + if (parameters != null && parameters.length() > 0) { - String decodedParameters = decodeParameters(parameters, characterEncoding); - + String decodedParameters = decodeParameters(parameters, + characterEncoding); + int position = 0; StringBuffer buffer = new StringBuffer(); - + PortletWindowRequestNavigationalState currentState = null; String parameter; - while ( (position = decodeArgument(position, decodedParameters, buffer, PARAMETER_SEPARATOR )) != -1 ) + while ((position = decodeArgument(position, decodedParameters, + buffer, PARAMETER_SEPARATOR)) != -1) { parameter = buffer.toString(); - currentState = decodeParameter( windowAccessor, states, currentState, parameter); + currentState = decodeParameter(windowAccessor, states, + currentState, parameter); } - - if ( log.isDebugEnabled() ) + + if (log.isDebugEnabled()) { logDecode(states, buffer); - if ( buffer.length() > 0 ) + if (buffer.length() > 0) { buffer.append("]"); - log.debug("navstate decoded="+buffer.toString()); + log.debug("navstate decoded=" + buffer.toString()); } } } return states; } - private void logDecode(PortletWindowRequestNavigationalStates states, StringBuffer buffer) + private void logDecode(PortletWindowRequestNavigationalStates states, + StringBuffer buffer) { PortletWindowRequestNavigationalState currentState; buffer.setLength(0); - String actionWindowId = states.getActionWindow() != null ? states.getActionWindow().getId().toString() : ""; + String actionWindowId = states.getActionWindow() != null ? states + .getActionWindow().getId().toString() : ""; Iterator iter = states.getWindowIdIterator(); - while ( iter.hasNext() ) + while (iter.hasNext()) { - if ( buffer.length() == 0 ) + if (buffer.length() == 0) { buffer.append("[["); } @@ -139,20 +162,21 @@ { buffer.append(",["); } - currentState = states.getPortletWindowNavigationalState((String)iter.next()); - buffer.append("window:"+currentState.getWindowId()); - - if ( currentState.getWindowId().equals(actionWindowId)) + currentState = states + .getPortletWindowNavigationalState((String) iter.next()); + buffer.append("window:" + currentState.getWindowId()); + + if (currentState.getWindowId().equals(actionWindowId)) { buffer.append(",action:true"); } - if (currentState.getPortletMode() != null) + if (currentState.getPortletMode() != null) { - buffer.append(",mode:"+currentState.getPortletMode()); + buffer.append(",mode:" + currentState.getPortletMode()); } - if (currentState.getWindowState() != null ) + if (currentState.getWindowState() != null) { - buffer.append(",state:"+currentState.getWindowState()); + buffer.append(",state:" + currentState.getWindowState()); } if (!currentState.isClearParameters()) { @@ -160,10 +184,11 @@ { buffer.append(",parameters:["); boolean first = true; - Iterator parIter = currentState.getParametersMap().keySet().iterator(); - while ( parIter.hasNext() ) + Iterator parIter = currentState.getParametersMap().keySet() + .iterator(); + while (parIter.hasNext()) { - if ( first ) + if (first) { first = false; } @@ -171,15 +196,16 @@ { buffer.append(","); } - String name = (String)parIter.next(); - buffer.append(name+":["); - String[] values = (String[])currentState.getParametersMap().get(name); - for ( int i = 0; i < values.length; i++ ) + String name = (String) parIter.next(); + buffer.append(name + ":["); + String[] values = (String[]) currentState + .getParametersMap().get(name); + for (int i = 0; i < values.length; i++) { - if ( i > 0 ) + if (i > 0) { buffer.append(","); - } + } buffer.append(values[i]); } buffer.append("]"); @@ -189,59 +215,76 @@ buffer.append("]"); } } - - public String encode(PortletWindowRequestNavigationalStates states, PortletWindow window, PortletMode portletMode, - WindowState windowState, boolean navParamsStateFull, boolean renderParamsStateFull) - throws UnsupportedEncodingException + + public String encode(PortletWindowRequestNavigationalStates states, + PortletWindow window, PortletMode portletMode, + WindowState windowState, boolean navParamsStateFull, + boolean renderParamsStateFull) throws UnsupportedEncodingException { String windowId = window.getId().toString(); - PortletWindowRequestNavigationalState currentState = states.getPortletWindowNavigationalState(windowId); - PortletWindowRequestNavigationalState targetState = new PortletWindowRequestNavigationalState(windowId); - targetState.setPortletMode(portletMode != null ? portletMode : currentState != null ? currentState.getPortletMode() : null); - targetState.setWindowState(windowState != null ? windowState : currentState != null ? currentState.getWindowState() : null); + PortletWindowRequestNavigationalState currentState = states + .getPortletWindowNavigationalState(windowId); + PortletWindowRequestNavigationalState targetState = new PortletWindowRequestNavigationalState( + windowId); + targetState.setPortletMode(portletMode != null ? portletMode + : currentState != null ? currentState.getPortletMode() : null); + targetState.setWindowState(windowState != null ? windowState + : currentState != null ? currentState.getWindowState() : null); - // never retain actionRequest parameters nor session stored renderParameters - if ( currentState != null && !renderParamsStateFull ) + // never retain actionRequest parameters nor session stored + // renderParameters + if (currentState != null && !renderParamsStateFull) { // retain current request parameters if any - if ( currentState.getParametersMap() != null ) + if (currentState.getParametersMap() != null) { - Iterator parametersIter = currentState.getParametersMap().entrySet().iterator(); + Iterator parametersIter = currentState.getParametersMap() + .entrySet().iterator(); Map.Entry entry; - while ( parametersIter.hasNext()) + while (parametersIter.hasNext()) { - entry = (Map.Entry)parametersIter.next(); - targetState.setParameters((String)entry.getKey(), (String[])entry.getValue()); + entry = (Map.Entry) parametersIter.next(); + targetState.setParameters((String) entry.getKey(), + (String[]) entry.getValue()); } } } // encode as requestURL parameters - return encode(states, windowId, targetState, false, false, navParamsStateFull, renderParamsStateFull); + return encode(states, windowId, targetState, false, false, + navParamsStateFull, renderParamsStateFull); } - public String encode(PortletWindowRequestNavigationalStates states, PortletWindow window, Map parameters, - PortletMode portletMode, WindowState windowState, boolean action, boolean navParamsStateFull, - boolean renderParamsStateFull) - throws UnsupportedEncodingException + public String encode(PortletWindowRequestNavigationalStates states, + PortletWindow window, Map parameters, PortletMode portletMode, + WindowState windowState, boolean action, + boolean navParamsStateFull, boolean renderParamsStateFull) + throws UnsupportedEncodingException { String windowId = window.getId().toString(); - PortletWindowRequestNavigationalState currentState = states.getPortletWindowNavigationalState(windowId); - PortletWindowRequestNavigationalState targetState = new PortletWindowRequestNavigationalState(windowId); - targetState.setPortletMode(portletMode != null ? portletMode : currentState != null ? currentState.getPortletMode() : null); - targetState.setWindowState(windowState != null ? windowState : currentState != null ? currentState.getWindowState() : null); - + PortletWindowRequestNavigationalState currentState = states + .getPortletWindowNavigationalState(windowId); + PortletWindowRequestNavigationalState targetState = new PortletWindowRequestNavigationalState( + windowId); + targetState.setPortletMode(portletMode != null ? portletMode + : currentState != null ? currentState.getPortletMode() : null); + targetState.setWindowState(windowState != null ? windowState + : currentState != null ? currentState.getWindowState() : null); + Iterator parametersIter = parameters.entrySet().iterator(); - + boolean resource = false; Map.Entry entry; String parameter; // fill in the new parameters - while ( parametersIter.hasNext()) + while (parametersIter.hasNext()) { - entry = (Map.Entry)parametersIter.next(); - parameter = (String)entry.getKey(); - if (!resource && !action && PortalReservedParameters.PORTLET_RESOURCE_URL_REQUEST_PARAMETER.equals(parameter)) + entry = (Map.Entry) parametersIter.next(); + parameter = (String) entry.getKey(); + if (!resource + && !action + && PortalReservedParameters.PORTLET_RESOURCE_URL_REQUEST_PARAMETER + .equals(parameter)) { resource = true; navParamsStateFull = true; @@ -249,53 +292,63 @@ } else { - targetState.setParameters(parameter, (String[])entry.getValue()); + targetState.setParameters(parameter, (String[]) entry + .getValue()); } } - if ( renderParamsStateFull && targetState.getParametersMap() == null ) + if (renderParamsStateFull && targetState.getParametersMap() == null) { - // Indicate that the saved (in the session) render parameters for this PortletWindow must be cleared - // and not copied when synchronizing the state (encoded as CLEAR_PARAMS_KEY) + // Indicate that the saved (in the session) render parameters for + // this PortletWindow must be cleared + // and not copied when synchronizing the state (encoded as + // CLEAR_PARAMS_KEY) targetState.setClearParameters(true); } - return encode(states, windowId, targetState, action, resource, navParamsStateFull, renderParamsStateFull); + return encode(states, windowId, targetState, action, resource, + navParamsStateFull, renderParamsStateFull); } - public String encode(PortletWindowRequestNavigationalStates states, boolean navParamsStateFull, boolean renderParamsStateFull) - throws UnsupportedEncodingException + public String encode(PortletWindowRequestNavigationalStates states, + boolean navParamsStateFull, boolean renderParamsStateFull) + throws UnsupportedEncodingException { - return encode(states, null, null, false, false, navParamsStateFull, renderParamsStateFull); + return encode(states, null, null, false, false, navParamsStateFull, + renderParamsStateFull); } - protected String encode(PortletWindowRequestNavigationalStates states, String targetWindowId, - PortletWindowRequestNavigationalState targetState, boolean action, boolean resource, boolean navParamsStateFull, - boolean renderParamsStateFull) - throws UnsupportedEncodingException + + protected String encode(PortletWindowRequestNavigationalStates states, + String targetWindowId, + PortletWindowRequestNavigationalState targetState, boolean action, + boolean resource, boolean navParamsStateFull, + boolean renderParamsStateFull) throws UnsupportedEncodingException { StringBuffer buffer = new StringBuffer(); String encodedState; boolean haveState = false; - - // skip other states if all non-targeted PortletWindow states are kept in the session - if ( !navParamsStateFull || !renderParamsStateFull ) + + // skip other states if all non-targeted PortletWindow states are kept + // in the session + if (!navParamsStateFull || !renderParamsStateFull) { PortletWindowRequestNavigationalState pwfns; String windowId; Iterator iter = states.getWindowIdIterator(); - while ( iter.hasNext() ) + while (iter.hasNext()) { - windowId = (String)iter.next(); + windowId = (String) iter.next(); pwfns = states.getPortletWindowNavigationalState(windowId); - if ( targetWindowId != null && windowId.equals(targetWindowId)) + if (targetWindowId != null && windowId.equals(targetWindowId)) { // skip it for now, it will be encoded as the last one below } else { - encodedState = encodePortletWindowNavigationalState(windowId, pwfns, false, false, navParamsStateFull, + encodedState = encodePortletWindowNavigationalState( + windowId, pwfns, false, false, navParamsStateFull, renderParamsStateFull); - if ( encodedState.length() > 0 ) + if (encodedState.length() > 0) { - if ( !haveState ) + if (!haveState) { haveState = true; } @@ -310,10 +363,11 @@ } if (targetWindowId != null) { - encodedState = encodePortletWindowNavigationalState(targetWindowId, targetState, action, resource, false, false); - if ( encodedState.length() > 0 ) + encodedState = encodePortletWindowNavigationalState(targetWindowId, + targetState, action, resource, false, false); + if (encodedState.length() > 0) { - if ( !haveState ) + if (!haveState) { haveState = true; } @@ -325,22 +379,26 @@ } } String encodedNavState = null; - if ( haveState ) + if (haveState) { - encodedNavState = encodeParameters(buffer.toString(), states.getCharacterEncoding()); + encodedNavState = encodeParameters(buffer.toString(), states + .getCharacterEncoding()); } return encodedNavState; } - - protected String encodePortletWindowNavigationalState(String windowId, PortletWindowRequestNavigationalState state, - boolean action, boolean resource, boolean navParamsStateFull, boolean renderParamsStateFull) + + protected String encodePortletWindowNavigationalState(String windowId, + PortletWindowRequestNavigationalState state, boolean action, + boolean resource, boolean navParamsStateFull, + boolean renderParamsStateFull) { StringBuffer buffer = new StringBuffer(); - buffer.append(action ? ACTION_WINDOW_ID_KEY : resource? RESOURCE_WINDOW_ID_KEY: RENDER_WINDOW_ID_KEY); + buffer.append(action ? ACTION_WINDOW_ID_KEY + : resource ? RESOURCE_WINDOW_ID_KEY : RENDER_WINDOW_ID_KEY); buffer.append(windowId); boolean encoded = action || resource; - - if ( action || !navParamsStateFull ) + + if (action || !navParamsStateFull) { if (state.getPortletMode() != null) { @@ -359,151 +417,170 @@ } } - if (state.getParametersMap() != null && (action || !renderParamsStateFull) ) + if (state.getParametersMap() != null + && (action || !renderParamsStateFull)) { Map.Entry entry; - String parameterName; + String parameterName; String[] parameterValues; StringBuffer paramBuffer = new StringBuffer(); Iterator iter = state.getParametersMap().entrySet().iterator(); - while ( iter.hasNext() ) + while (iter.hasNext()) { encoded = true; - entry = (Map.Entry)iter.next(); - parameterName = (String)entry.getKey(); - parameterValues = (String[])entry.getValue(); - + entry = (Map.Entry) iter.next(); + parameterName = (String) entry.getKey(); + parameterValues = (String[]) entry.getValue(); + buffer.append(PARAMETER_SEPARATOR); buffer.append(PARAM_KEY); - + paramBuffer.setLength(0); - paramBuffer.append(encodeArgument(parameterName, PARAMETER_ELEMENT_SEPARATOR)); + paramBuffer.append(encodeArgument(parameterName, + PARAMETER_ELEMENT_SEPARATOR)); paramBuffer.append(PARAMETER_ELEMENT_SEPARATOR); paramBuffer.append(Integer.toHexString(parameterValues.length)); - for ( int i = 0; i < parameterValues.length; i++ ) + for (int i = 0; i < parameterValues.length; i++) { paramBuffer.append(PARAMETER_ELEMENT_SEPARATOR); - paramBuffer.append(encodeArgument(parameterValues[i], PARAMETER_ELEMENT_SEPARATOR)); + paramBuffer.append(encodeArgument(parameterValues[i], + PARAMETER_ELEMENT_SEPARATOR)); } - - buffer.append(encodeArgument(paramBuffer.toString(),PARAMETER_SEPARATOR)); + + buffer.append(encodeArgument(paramBuffer.toString(), + PARAMETER_SEPARATOR)); } } - else if ( state.isClearParameters() ) + else if (state.isClearParameters()) { - // Special case: for a targeted PortletWindow for which no parameters are specified - // indicate its saved (in the session) request parameters must be cleared instead of copying them when + // Special case: for a targeted PortletWindow for which no + // parameters are specified + // indicate its saved (in the session) request parameters must be + // cleared instead of copying them when // synchronizing the state. - // During decoding this CLEAR_PARAMS_KEY will set the clearParameters flag of the PortletWindowRequestNavigationalState. + // During decoding this CLEAR_PARAMS_KEY will set the + // clearParameters flag of the + // PortletWindowRequestNavigationalState. buffer.append(PARAMETER_SEPARATOR); - buffer.append(CLEAR_PARAMS_KEY); + buffer.append(CLEAR_PARAMS_KEY); encoded = true; } return encoded ? buffer.toString() : ""; } - - protected PortletWindowRequestNavigationalState decodeParameter(PortletWindowAccessor accessor, PortletWindowRequestNavigationalStates states, PortletWindowRequestNavigationalState currentState, String parameter) + + protected PortletWindowRequestNavigationalState decodeParameter( + PortletWindowAccessor accessor, + PortletWindowRequestNavigationalStates states, + PortletWindowRequestNavigationalState currentState, String parameter) { char parameterType = parameter.charAt(0); - if (parameterType == RENDER_WINDOW_ID_KEY || parameterType == ACTION_WINDOW_ID_KEY || parameterType == RESOURCE_WINDOW_ID_KEY ) - { + if (parameterType == RENDER_WINDOW_ID_KEY + || parameterType == ACTION_WINDOW_ID_KEY + || parameterType == RESOURCE_WINDOW_ID_KEY) + { String windowId = parameter.substring(1); currentState = states.getPortletWindowNavigationalState(windowId); - if ( currentState == null ) + if (currentState == null) { PortletWindow window = accessor.getPortletWindow(windowId); - if ( window == null ) + if (window == null) { window = accessor.createPortletWindow(windowId); } - currentState = new PortletWindowRequestNavigationalState(windowId); - states.addPortletWindowNavigationalState(windowId, currentState); - if ( parameterType == ACTION_WINDOW_ID_KEY ) + currentState = new PortletWindowRequestNavigationalState( + windowId); + states + .addPortletWindowNavigationalState(windowId, + currentState); + if (parameterType == ACTION_WINDOW_ID_KEY) { states.setActionWindow(window); } - else if (parameterType == RESOURCE_WINDOW_ID_KEY ) + else if (parameterType == RESOURCE_WINDOW_ID_KEY) { states.setResourceWindow(window); } } } - else if ( currentState != null ) + else if (currentState != null) { - switch ( parameterType ) + switch (parameterType) { - case MODE_KEY: + case MODE_KEY: { + PortletMode portletMode = decodePortletMode(parameter.charAt(1)); + if (portletMode != null) { - PortletMode portletMode = decodePortletMode(parameter.charAt(1)); - if ( portletMode != null ) - { - currentState.setPortletMode(portletMode); - } - break; + currentState.setPortletMode(portletMode); } - case STATE_KEY: + break; + } + case STATE_KEY: { + WindowState windowState = decodeWindowState(parameter.charAt(1)); + if (windowState != null) { - WindowState windowState = decodeWindowState(parameter.charAt(1)); - if ( windowState != null ) + currentState.setWindowState(windowState); + if (windowState.equals(WindowState.MAXIMIZED) + || windowState.equals(JetspeedActions.SOLO_STATE)) { - currentState.setWindowState(windowState); - if (windowState.equals(WindowState.MAXIMIZED) || windowState.equals(JetspeedActions.SOLO_STATE)) + PortletWindow window = accessor + .getPortletWindow(currentState.getWindowId()); + if (window == null) { - PortletWindow window = accessor.getPortletWindow(currentState.getWindowId()); - if ( window == null ) - { - window = accessor.createPortletWindow(currentState.getWindowId()); - } - states.setMaximizedWindow(window); + window = accessor.createPortletWindow(currentState + .getWindowId()); } + states.setMaximizedWindow(window); } - break; } - case PARAM_KEY: + break; + } + case PARAM_KEY: { + int position = 1; + StringBuffer buffer = new StringBuffer(); + String parameterName = null; + int parameterValueCount = -1; + String parameterValues[] = null; + int parameterValueIndex = -1; + while ((position = decodeArgument(position, parameter, buffer, + PARAMETER_ELEMENT_SEPARATOR)) != -1) { - int position = 1; - StringBuffer buffer = new StringBuffer(); - String parameterName = null; - int parameterValueCount = -1; - String parameterValues[] = null; - int parameterValueIndex = -1; - while ( (position = decodeArgument(position, parameter, buffer, PARAMETER_ELEMENT_SEPARATOR)) != -1 ) + if (parameterName == null) { - if ( parameterName == null ) + parameterName = buffer.toString(); + parameterValueCount = -1; + } + else if (parameterValueCount == -1) + { + parameterValueCount = Integer.parseInt(buffer + .toString(), 16); + parameterValues = new String[parameterValueCount]; + parameterValueIndex = 0; + } + else + { + parameterValues[parameterValueIndex++] = buffer + .toString(); + parameterValueCount--; + if (parameterValueCount == 0) { - parameterName = buffer.toString(); - parameterValueCount = -1; + currentState.setParameters(parameterName, + parameterValues); + break; } - else if ( parameterValueCount == -1 ) - { - parameterValueCount = Integer.parseInt(buffer.toString(), 16); - parameterValues = new String[parameterValueCount]; - parameterValueIndex = 0; - } - else - { - parameterValues[parameterValueIndex++] = buffer.toString(); - parameterValueCount--; - if ( parameterValueCount == 0 ) - { - currentState.setParameters(parameterName, parameterValues); - break; - } - } } - break; } - case CLEAR_PARAMS_KEY: - { - currentState.setClearParameters(true); - } + break; } + case CLEAR_PARAMS_KEY: { + currentState.setClearParameters(true); + } + } } return currentState; - + } - + protected PortletMode decodePortletMode(char mode) { PortletMode portletMode = null; @@ -514,17 +591,17 @@ } return portletMode; } - + protected char encodePortletMode(PortletMode portletMode) { - for ( int i = 0; i < portletModes.length; i++ ) + for (int i = 0; i < portletModes.length; i++) { - if (portletModes[i].equals(portletMode)) - return keytable.charAt(i); + if (portletModes[i].equals(portletMode)) return keytable.charAt(i); } - throw new IllegalArgumentException("Unsupported PortletMode: "+portletMode); + throw new IllegalArgumentException("Unsupported PortletMode: " + + portletMode); } - + protected WindowState decodeWindowState(char state) { WindowState windowState = null; @@ -535,35 +612,37 @@ } return windowState; } - + protected char encodeWindowState(WindowState windowState) { - for ( int i = 0; i < windowStates.length; i++ ) + for (int i = 0; i < windowStates.length; i++) { - if (windowStates[i].equals(windowState)) - return keytable.charAt(i); + if (windowStates[i].equals(windowState)) return keytable.charAt(i); } - throw new IllegalArgumentException("Unsupported WindowState: "+windowState); + throw new IllegalArgumentException("Unsupported WindowState: " + + windowState); } - - /** + + /** * Decodes a Base64 encoded string. * - * Because the encoded string is used in an URL - * the two '/' and '=' which has some significance in an URL - * are encoded on top of the Base64 encoding and are first translated back before decoding. + * Because the encoded string is used in an URL the two '/' and '=' which + * has some significance in an URL are encoded on top of the Base64 encoding + * and are first translated back before decoding. * * @param value - * @param characterEncoding String containing the name of the chararacter encoding + * @param characterEncoding + * String containing the name of the chararacter encoding * @return decoded string */ protected String decodeParameters(String value, String characterEncoding) - throws UnsupportedEncodingException + throws UnsupportedEncodingException { - value = value.replace('-','/').replace('_','='); - if ( characterEncoding != null ) + value = value.replace('-', '/').replace('_', '='); + if (characterEncoding != null) { - return new String(Base64.decodeBase64(value.getBytes(characterEncoding)), characterEncoding); + return new String(Base64.decodeBase64(value + .getBytes(characterEncoding)), characterEncoding); } else { @@ -571,63 +650,66 @@ } } - /** + /** * Encodes a string with Base64. * - * Because the encoded string is used in an URL - * the two '/' and '=' which has some significance in an URL - * are encoded on top of/after the Base64 encoding - * + * Because the encoded string is used in an URL the two '/' and '=' which + * has some significance in an URL are encoded on top of/after the Base64 + * encoding + * * @param value * @return encoded string */ protected String encodeParameters(String value, String characterEncoding) - throws UnsupportedEncodingException + throws UnsupportedEncodingException { - if ( characterEncoding != null ) + if (characterEncoding != null) { - value = new String(Base64.encodeBase64(value.getBytes(characterEncoding))); + value = new String(Base64.encodeBase64(value + .getBytes(characterEncoding))); } else { value = new String(Base64.encodeBase64(value.getBytes())); } - return value.replace('/','-').replace('=','_'); + return value.replace('/', '-').replace('=', '_'); } - protected String encodeArgument( String argument, char escape ) + protected String encodeArgument(String argument, char escape) { int length = argument.length(); StringBuffer buffer = new StringBuffer(length); buffer.setLength(0); char c; - for ( int i = 0; i < length; i++ ) + for (int i = 0; i < length; i++) { c = argument.charAt(i); buffer.append(c); - if ( c == escape ) + if (c == escape) { buffer.append(c); } } return buffer.toString(); } - - protected int decodeArgument(int position, String arguments, StringBuffer buffer, char escape) + + protected int decodeArgument(int position, String arguments, + StringBuffer buffer, char escape) { int maxLength = arguments.length(); buffer.setLength(0); char c; - for ( ; position < maxLength; position++ ) + for (; position < maxLength; position++) { c = arguments.charAt(position); - if ( c != escape ) + if (c != escape) { buffer.append(c); } - else + else { - if ( c == escape && position < maxLength-1 && arguments.charAt(position+1) == escape ) + if (c == escape && position < maxLength - 1 + && arguments.charAt(position + 1) == escape) { buffer.append(c); position++; @@ -639,6 +721,6 @@ } } } - return buffer.length() > 0 ? position : -1; + return buffer.length() > 0 ? position : -1; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/JetspeedNavigationalStateComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/JetspeedNavigationalStateComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/JetspeedNavigationalStateComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,23 +37,32 @@ /** * JetspeedNavigationalStateComponent - * + * * @author David Sean Taylor - * @version $Id: JetspeedNavigationalStateComponent.java 517124 2007-03-12 08:10:25Z ate $ + * @version $Id: JetspeedNavigationalStateComponent.java 517124 2007-03-12 + * 08:10:25Z ate $ */ -public class JetspeedNavigationalStateComponent implements NavigationalStateComponent, BeanFactoryAware +public class JetspeedNavigationalStateComponent implements + NavigationalStateComponent, BeanFactoryAware { + private final String navBeanName; - private final String urlBeanName; + + private final String urlBeanName; + private final String desktopUrlBeanName; - - // maps containing allowed PortletMode and WindowState objects on their lowercase name - // ensuring only allowed, and always the same objects are returned and allowing comparision by value - private final Map supportedPortletModes = Collections.synchronizedMap(new HashMap()); - private final Map supportedWindowStates = Collections.synchronizedMap(new HashMap()); + // maps containing allowed PortletMode and WindowState objects on their + // lowercase name + // ensuring only allowed, and always the same objects are returned and + // allowing comparision by value + private final Map supportedPortletModes = Collections + .synchronizedMap(new HashMap()); + + private final Map supportedWindowStates = Collections + .synchronizedMap(new HashMap()); + private BeanFactory beanFactory; - /** * @param navBeanName @@ -61,97 +70,106 @@ * @param urlBeanName * name of the bean implementing Portal URL instances * @param navCodecBeanName - * name of the bean implementing Navigational State Codec instance + * name of the bean implementing Navigational State Codec + * instance * @throws ClassNotFoundException * if navClassName or urlClassName * do not exist. */ - public JetspeedNavigationalStateComponent(String navBeanName, String urlBeanName, PortalContext portalContext, String desktopUrlBeanName) - throws ClassNotFoundException + public JetspeedNavigationalStateComponent(String navBeanName, + String urlBeanName, PortalContext portalContext, + String desktopUrlBeanName) throws ClassNotFoundException { ArgUtil.assertNotNull(String.class, navBeanName, this); - ArgUtil.assertNotNull(String.class, urlBeanName, this); + ArgUtil.assertNotNull(String.class, urlBeanName, this); this.navBeanName = navBeanName; this.urlBeanName = urlBeanName; this.desktopUrlBeanName = desktopUrlBeanName; Enumeration portletModesEnum = portalContext.getSupportedPortletModes(); PortletMode portletMode; - while ( portletModesEnum.hasMoreElements() ) + while (portletModesEnum.hasMoreElements()) { - portletMode = (PortletMode)portletModesEnum.nextElement(); + portletMode = (PortletMode) portletModesEnum.nextElement(); supportedPortletModes.put(portletMode.toString(), portletMode); } Enumeration windowStatesEnum = portalContext.getSupportedWindowStates(); WindowState windowState; - while ( windowStatesEnum.hasMoreElements() ) + while (windowStatesEnum.hasMoreElements()) { - windowState = (WindowState)windowStatesEnum.nextElement(); + windowState = (WindowState) windowStatesEnum.nextElement(); supportedWindowStates.put(windowState.toString(), windowState); } } /** - * + * *

        * create *

        - * + * * @see org.apache.jetspeed.container.state.NavigationalStateComponent#create(org.apache.jetspeed.request.RequestContext) - * @return @throws - * FailedToCreateNavStateException if the nav state could not be - * created. Under normal circumstances, this should not happen. + * @return + * @throws FailedToCreateNavStateException + * if the nav state could not be created. Under normal + * circumstances, this should not happen. */ public NavigationalState create() throws FailedToCreateNavStateException { try { - return (NavigationalState) beanFactory.getBean(navBeanName, NavigationalState.class); + return (NavigationalState) beanFactory.getBean(navBeanName, + NavigationalState.class); } catch (BeansException e) - { - throw new FailedToCreateNavStateException("Spring failed to create the NavigationalState bean.", e); + { + throw new FailedToCreateNavStateException( + "Spring failed to create the NavigationalState bean.", e); } } - /** - * - *

        - * createURL - *

        - * - * @see org.apache.jetspeed.container.state.NavigationalStateComponent#createURL(org.apache.jetspeed.request.RequestContext) - * @param context - * @return - */ - public PortalURL createURL( HttpServletRequest request, String characterEncoding ) + /** + * + *

        + * createURL + *

        + * + * @see org.apache.jetspeed.container.state.NavigationalStateComponent#createURL(org.apache.jetspeed.request.RequestContext) + * @param context + * @return + */ + public PortalURL createURL(HttpServletRequest request, + String characterEncoding) { - PortalURL url = (PortalURL) beanFactory.getBean(urlBeanName, PortalURL.class); + PortalURL url = (PortalURL) beanFactory.getBean(urlBeanName, + PortalURL.class); url.setRequest(request); url.setCharacterEncoding(characterEncoding); return url; } - public WindowState lookupWindowState( String name ) + public WindowState lookupWindowState(String name) { - return (WindowState)supportedWindowStates.get(name.toLowerCase()); + return (WindowState) supportedWindowStates.get(name.toLowerCase()); } - public PortletMode lookupPortletMode( String name ) + public PortletMode lookupPortletMode(String name) { - return (PortletMode)supportedPortletModes.get(name.toLowerCase()); + return (PortletMode) supportedPortletModes.get(name.toLowerCase()); } public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.beanFactory = beanFactory; + this.beanFactory = beanFactory; } - - public PortalURL createDesktopURL(HttpServletRequest request, String characterEncoding) + + public PortalURL createDesktopURL(HttpServletRequest request, + String characterEncoding) { - PortalURL url = (PortalURL) beanFactory.getBean(desktopUrlBeanName, PortalURL.class); + PortalURL url = (PortalURL) beanFactory.getBean(desktopUrlBeanName, + PortalURL.class); url.setRequest(request); url.setCharacterEncoding(characterEncoding); - return url; + return url; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/NavigationalStateCodec.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/NavigationalStateCodec.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/NavigationalStateCodec.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,15 +26,22 @@ public interface NavigationalStateCodec { - PortletWindowRequestNavigationalStates decode(String parameters, String characterEncoding) throws UnsupportedEncodingException; - String encode(PortletWindowRequestNavigationalStates states, PortletWindow window, PortletMode portletMode, - WindowState windowState, boolean navParamsStateFull, boolean renderParamsStateFull) throws UnsupportedEncodingException; + PortletWindowRequestNavigationalStates decode(String parameters, + String characterEncoding) throws UnsupportedEncodingException; - String encode(PortletWindowRequestNavigationalStates states, PortletWindow window, Map parameters, - PortletMode portletMode, WindowState windowState, boolean action, boolean navParamsStateFull, + String encode(PortletWindowRequestNavigationalStates states, + PortletWindow window, PortletMode portletMode, + WindowState windowState, boolean navParamsStateFull, boolean renderParamsStateFull) throws UnsupportedEncodingException; - String encode(PortletWindowRequestNavigationalStates states, boolean navParamsStateFull, boolean renderParamsStateFull) + String encode(PortletWindowRequestNavigationalStates states, + PortletWindow window, Map parameters, PortletMode portletMode, + WindowState windowState, boolean action, + boolean navParamsStateFull, boolean renderParamsStateFull) throws UnsupportedEncodingException; + + String encode(PortletWindowRequestNavigationalStates states, + boolean navParamsStateFull, boolean renderParamsStateFull) + throws UnsupportedEncodingException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PathNavigationalState.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PathNavigationalState.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PathNavigationalState.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,22 +20,23 @@ import org.apache.jetspeed.request.RequestContext; /** - * PathNavigationalStateContext stores all navigational state in the URL. - * This implementation does not currently support persisting navigational state. - * + * PathNavigationalStateContext stores all navigational state in the URL. This + * implementation does not currently support persisting navigational state. + * * @author David Sean Taylor * @version $Id: PathNavigationalState.java 550655 2007-06-26 01:41:35Z taylor $ */ -public class PathNavigationalState extends AbstractNavigationalState +public class PathNavigationalState extends AbstractNavigationalState { - public PathNavigationalState(NavigationalStateCodec codec, JetspeedContentCache cache) + public PathNavigationalState(NavigationalStateCodec codec, + JetspeedContentCache cache) { super(codec, cache); } public void sync(RequestContext context) - { + { } public boolean isNavigationalParameterStateFull() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowBaseNavigationalState.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowBaseNavigationalState.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowBaseNavigationalState.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,42 +23,46 @@ /** * PortletWindowBaseNavigationalState - * + * * @author Ate Douma - * @version $Id: PortletWindowBaseNavigationalState.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: PortletWindowBaseNavigationalState.java 516448 2007-03-09 + * 16:25:47Z ate $ */ public class PortletWindowBaseNavigationalState implements Serializable { + private String modeName; + private String stateName; - + private transient PortletMode portletMode; + private transient WindowState windowState; - + public PortletMode getPortletMode() { - if ( portletMode == null && modeName != null ) + if (portletMode == null && modeName != null) { portletMode = new PortletMode(modeName); } - return portletMode ; + return portletMode; } - + public void setPortletMode(PortletMode portletMode) { this.portletMode = portletMode; this.modeName = portletMode == null ? null : portletMode.toString(); } - + public WindowState getWindowState() { - if ( windowState == null && stateName != null ) + if (windowState == null && stateName != null) { windowState = new WindowState(stateName); } return windowState; } - + public void setWindowState(WindowState windowState) { this.windowState = windowState; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowExtendedNavigationalState.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowExtendedNavigationalState.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowExtendedNavigationalState.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,30 +25,38 @@ /** * PortletWindowExtendedNavigationalState - * + * * @author Ate Douma - * @version $Id: PortletWindowExtendedNavigationalState.java 551865 2007-06-29 12:13:10Z ate $ + * @version $Id: PortletWindowExtendedNavigationalState.java 551865 2007-06-29 + * 12:13:10Z ate $ */ -public class PortletWindowExtendedNavigationalState extends PortletWindowBaseNavigationalState +public class PortletWindowExtendedNavigationalState extends + PortletWindowBaseNavigationalState { + private static final class ModeStateKey implements Serializable { + private final String mode; + private final String state; + private final int hashCode; - + public ModeStateKey(PortletMode mode, WindowState state) { - this.mode = (mode != null ? mode.toString() : PortletMode.VIEW.toString()).intern() ; - this.state = (state != null ? state.toString() : WindowState.NORMAL.toString()).intern(); - hashCode = this.mode.hashCode()+this.state.hashCode(); + this.mode = (mode != null ? mode.toString() : PortletMode.VIEW + .toString()).intern(); + this.state = (state != null ? state.toString() : WindowState.NORMAL + .toString()).intern(); + hashCode = this.mode.hashCode() + this.state.hashCode(); } - + public boolean equals(Object obj) { if (obj != null && obj instanceof ModeStateKey) { - ModeStateKey key = (ModeStateKey)obj; + ModeStateKey key = (ModeStateKey) obj; return mode.equals(key.mode) && state.equals(key.state); } return false; @@ -59,11 +67,11 @@ return hashCode; } } - + private Map parametersMap; - + private Map decoratorActionEncodings; - + public Map getParametersMap() { return parametersMap; @@ -71,18 +79,18 @@ public void setParameters(String name, String[] values) { - if ( parametersMap == null ) + if (parametersMap == null) { parametersMap = new HashMap(); } parametersMap.put(name, values); - } - + } + public void setParametersMap(Map parametersMap) { this.parametersMap = parametersMap; } - + public void resetDecoratorActionEncodings() { if (decoratorActionEncodings != null) @@ -90,22 +98,21 @@ decoratorActionEncodings.clear(); } } - - public void setDecoratorActionEncoding(PortletMode mode, WindowState state, String encoding) + + public void setDecoratorActionEncoding(PortletMode mode, WindowState state, + String encoding) { if (decoratorActionEncodings == null) { decoratorActionEncodings = new HashMap(4); } - decoratorActionEncodings.put(new ModeStateKey(mode,state), encoding); + decoratorActionEncodings.put(new ModeStateKey(mode, state), encoding); } - + public String getDecoratorActionEncoding(PortletMode mode, WindowState state) { - if (decoratorActionEncodings != null) - { - return (String)decoratorActionEncodings.get(new ModeStateKey(mode,state)); - } + if (decoratorActionEncodings != null) { return (String) decoratorActionEncodings + .get(new ModeStateKey(mode, state)); } return null; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowRequestNavigationalState.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowRequestNavigationalState.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowRequestNavigationalState.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,20 +18,24 @@ /** * PortletWindowRequestNavigationalState - * + * * @author Ate Douma - * @version $Id: PortletWindowRequestNavigationalState.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: PortletWindowRequestNavigationalState.java 516448 2007-03-09 + * 16:25:47Z ate $ */ -public class PortletWindowRequestNavigationalState extends PortletWindowExtendedNavigationalState +public class PortletWindowRequestNavigationalState extends + PortletWindowExtendedNavigationalState { - private String windowId; - + + private String windowId; + /** - * true if for a targeted PortletWindow using StateFullParameters the saved (in the session) render parameters - * must be cleared when synchronizing the states. - * Prevents the default behavior when using StateFullParameters to copy the parameters from the session - * when no parameters are specified in the PortletURL. - * Used if for the targeted PortletWindow no render parameters are specified. + * true if for a targeted PortletWindow using StateFullParameters the saved + * (in the session) render parameters must be cleared when synchronizing the + * states. Prevents the default behavior when using StateFullParameters to + * copy the parameters from the session when no parameters are specified in + * the PortletURL. Used if for the targeted PortletWindow no render + * parameters are specified. */ private boolean clearParameters; @@ -44,12 +48,12 @@ { return windowId; } - + public boolean isClearParameters() { return clearParameters; } - + public void setClearParameters(boolean ignoreParameters) { this.clearParameters = ignoreParameters; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowRequestNavigationalStates.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowRequestNavigationalStates.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowRequestNavigationalStates.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,62 +24,72 @@ public class PortletWindowRequestNavigationalStates { + private String characterEncoding; + private Map pwnStates = new HashMap(); + private PortletWindow maximizedWindow; + private PortletWindow actionWindow; + private PortletWindow resourceWindow; - + public PortletWindowRequestNavigationalStates(String characterEncoding) { this.characterEncoding = characterEncoding; } - + public String getCharacterEncoding() { return characterEncoding; } - + public Iterator getWindowIdIterator() { return pwnStates.keySet().iterator(); } - + public void removePortletWindowNavigationalState(String windowId) - { + { boolean removed = pwnStates.remove(windowId) != null; if (removed) { - if (maximizedWindow != null && windowId.equals(maximizedWindow.getId().toString())) + if (maximizedWindow != null + && windowId.equals(maximizedWindow.getId().toString())) { maximizedWindow = null; } - if (actionWindow != null && windowId.equals(actionWindow.getId().toString())) + if (actionWindow != null + && windowId.equals(actionWindow.getId().toString())) { actionWindow = null; } - if (resourceWindow != null && windowId.equals(actionWindow.getId().toString())) + if (resourceWindow != null + && windowId.equals(actionWindow.getId().toString())) { resourceWindow = null; } } } - - public PortletWindowRequestNavigationalState getPortletWindowNavigationalState(String windowId) + + public PortletWindowRequestNavigationalState getPortletWindowNavigationalState( + String windowId) { - return (PortletWindowRequestNavigationalState)pwnStates.get(windowId); + return (PortletWindowRequestNavigationalState) pwnStates.get(windowId); } - - public void addPortletWindowNavigationalState(String windowId, PortletWindowRequestNavigationalState pwnState) + + public void addPortletWindowNavigationalState(String windowId, + PortletWindowRequestNavigationalState pwnState) { pwnStates.put(windowId, pwnState); } - + public PortletWindow getMaximizedWindow() { return maximizedWindow; } - + public void setMaximizedWindow(PortletWindow maximizedWindow) { this.maximizedWindow = maximizedWindow; @@ -89,14 +99,17 @@ { return actionWindow; } + public void setActionWindow(PortletWindow actionWindow) { this.actionWindow = actionWindow; } + public void setResourceWindow(PortletWindow resourceWindow) { this.resourceWindow = resourceWindow; } + public PortletWindow getResourceWindow() { return resourceWindow; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowSessionNavigationalStates.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowSessionNavigationalStates.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/PortletWindowSessionNavigationalStates.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,68 +34,78 @@ public class PortletWindowSessionNavigationalStates implements Serializable { + private static final class PageState implements Serializable { + public Map windowStates = new HashMap(); + public String maximizedWindowId; } - + private final boolean storeParameters; + private Map pageStates = new HashMap(); public PortletWindowSessionNavigationalStates(boolean storeParameters) { this.storeParameters = storeParameters; } + /* - * JS2-806 patch - *

        - * reset all portlets on page to mode VIEW and window state NORMAL in the case of page navigation. - *

        + * JS2-806 patch

        reset all portlets on page to mode VIEW and window + * state NORMAL in the case of page navigation.

        */ - public void changeAllPortletsToViewModeAndNormalWindowState(RequestContext context, Page page, PortletWindowRequestNavigationalStates requestStates, JetspeedContentCache cache, JetspeedContentCache decorationCache) + public void changeAllPortletsToViewModeAndNormalWindowState( + RequestContext context, Page page, + PortletWindowRequestNavigationalStates requestStates, + JetspeedContentCache cache, JetspeedContentCache decorationCache) { final PortletMode viewMode = PortletMode.VIEW; final WindowState normalWindowState = WindowState.NORMAL; - - PageState pageState = (PageState)pageStates.get(page.getId()); - if ( pageState == null ) + + PageState pageState = (PageState) pageStates.get(page.getId()); + if (pageState == null) { pageState = new PageState(); pageStates.put(page.getId(), pageState); } - + PortletWindowRequestNavigationalState requestState = null; PortletWindowBaseNavigationalState sessionState = null; - //remove any maximized windows + // remove any maximized windows if (null != pageState.maximizedWindowId) { pageState.windowStates.remove(pageState.maximizedWindowId); removeFromCache(context, pageState.maximizedWindowId, cache); - removeFromCache(context, pageState.maximizedWindowId, decorationCache); + removeFromCache(context, pageState.maximizedWindowId, + decorationCache); pageState.maximizedWindowId = null; } Iterator iter = requestStates.getWindowIdIterator(); iter = pageState.windowStates.keySet().iterator(); String windowId; - while ( iter.hasNext() ) + while (iter.hasNext()) { - windowId = (String)iter.next(); - requestState = requestStates.getPortletWindowNavigationalState(windowId); - if ( requestState == null ) + windowId = (String) iter.next(); + requestState = requestStates + .getPortletWindowNavigationalState(windowId); + if (requestState == null) { - requestState = new PortletWindowRequestNavigationalState(windowId); + requestState = new PortletWindowRequestNavigationalState( + windowId); } - //regardless, reset portlet mode and window state + // regardless, reset portlet mode and window state requestState.setPortletMode(viewMode); requestState.setWindowState(normalWindowState); // get the session case just in case and create a new one - sessionState = (PortletWindowBaseNavigationalState)pageState.windowStates.get(requestState.getWindowId()); - if ( sessionState == null ) + sessionState = (PortletWindowBaseNavigationalState) pageState.windowStates + .get(requestState.getWindowId()); + if (sessionState == null) { - if ( storeParameters ) + if (storeParameters) { sessionState = new PortletWindowExtendedNavigationalState(); } @@ -103,68 +113,80 @@ { sessionState = new PortletWindowBaseNavigationalState(); } - pageState.windowStates.put(requestState.getWindowId(),sessionState); + pageState.windowStates.put(requestState.getWindowId(), + sessionState); } - //Now, sync up. NOTE we should not be in this method if there is an portlet action request. - boolean changed = syncStates(false, requestState,(PortletWindowBaseNavigationalState)pageState.windowStates.get(windowId)); + // Now, sync up. NOTE we should not be in this method if there is an + // portlet action request. + boolean changed = syncStates(false, requestState, + (PortletWindowBaseNavigationalState) pageState.windowStates + .get(windowId)); if (changed) { removeFromCache(context, requestState.getWindowId(), cache); - removeFromCache(context, page.getId(), decorationCache); + removeFromCache(context, page.getId(), decorationCache); if (storeParameters) { - ((PortletWindowExtendedNavigationalState)sessionState).resetDecoratorActionEncodings(); + ((PortletWindowExtendedNavigationalState) sessionState) + .resetDecoratorActionEncodings(); } } - - } + + } } - - public void sync(RequestContext context, Page page, PortletWindowRequestNavigationalStates requestStates, JetspeedContentCache cache, JetspeedContentCache decorationCache) + + public void sync(RequestContext context, Page page, + PortletWindowRequestNavigationalStates requestStates, + JetspeedContentCache cache, JetspeedContentCache decorationCache) { - PageState pageState = (PageState)pageStates.get(page.getId()); - if ( pageState == null ) + PageState pageState = (PageState) pageStates.get(page.getId()); + if (pageState == null) { pageState = new PageState(); pageStates.put(page.getId(), pageState); } - + PortletWindowRequestNavigationalState requestState = null; PortletWindowBaseNavigationalState sessionState = null; // first synchronize MAXIMIZED window - if ( pageState.maximizedWindowId != null ) + if (pageState.maximizedWindowId != null) { String requestMaximizedWindowId = null; - - if ( requestStates.getMaximizedWindow() != null ) + + if (requestStates.getMaximizedWindow() != null) { - requestMaximizedWindowId = requestStates.getMaximizedWindow().getId().toString(); + requestMaximizedWindowId = requestStates.getMaximizedWindow() + .getId().toString(); } - - if ( requestMaximizedWindowId == null ) + + if (requestMaximizedWindowId == null) { // check clearing MAXIMIZED window - requestState = requestStates.getPortletWindowNavigationalState(pageState.maximizedWindowId); - if ( requestState != null ) + requestState = requestStates + .getPortletWindowNavigationalState(pageState.maximizedWindowId); + if (requestState != null) { if (requestState.getWindowState() != null) { pageState.maximizedWindowId = null; // syncState will reset the sessionState.WindowState - } + } } else { // check PortletWindow still exists... // depends on PortletWindowAccessor cache to be active - PortletWindowAccessor accessor = - (PortletWindowAccessor)Jetspeed.getComponentManager().getComponent(PortletWindowAccessor.class); - PortletWindow maximizedWindow = accessor.getPortletWindow(pageState.maximizedWindowId); - if ( maximizedWindow == null ) + PortletWindowAccessor accessor = (PortletWindowAccessor) Jetspeed + .getComponentManager().getComponent( + PortletWindowAccessor.class); + PortletWindow maximizedWindow = accessor + .getPortletWindow(pageState.maximizedWindowId); + if (maximizedWindow == null) { // gone: remove sessionState - pageState.windowStates.remove(pageState.maximizedWindowId); + pageState.windowStates + .remove(pageState.maximizedWindowId); pageState.maximizedWindowId = null; } else @@ -173,37 +195,48 @@ } } } - else if ( !requestMaximizedWindowId.equals( pageState.maximizedWindowId )) + else if (!requestMaximizedWindowId + .equals(pageState.maximizedWindowId)) { - // When can a non-maximized window request maximized state while another already has it? - // Maybe from a decoration portlet which always needs to be viewable? - requestState = requestStates.getPortletWindowNavigationalState(pageState.maximizedWindowId); - sessionState = (PortletWindowBaseNavigationalState)pageState.windowStates.get(pageState.maximizedWindowId); - if ( requestState == null || requestState.getWindowState() == null ) + // When can a non-maximized window request maximized state while + // another already has it? + // Maybe from a decoration portlet which always needs to be + // viewable? + requestState = requestStates + .getPortletWindowNavigationalState(pageState.maximizedWindowId); + sessionState = (PortletWindowBaseNavigationalState) pageState.windowStates + .get(pageState.maximizedWindowId); + if (requestState == null + || requestState.getWindowState() == null) { // need to clear it ourselves first sessionState.setWindowState(null); } } } - - if ( requestStates.getMaximizedWindow() != null ) + + if (requestStates.getMaximizedWindow() != null) { // store the new MAXIMIZED window - pageState.maximizedWindowId = requestStates.getMaximizedWindow().getId().toString(); + pageState.maximizedWindowId = requestStates.getMaximizedWindow() + .getId().toString(); } - + Iterator iter = requestStates.getWindowIdIterator(); - String actionWindowId = requestStates.getActionWindow() != null ? requestStates.getActionWindow().getId().toString() : null; + String actionWindowId = requestStates.getActionWindow() != null ? requestStates + .getActionWindow().getId().toString() + : null; boolean actionRequestState = false; // now synchronize requestStates and sessionStates - while ( iter.hasNext() ) + while (iter.hasNext()) { - requestState = requestStates.getPortletWindowNavigationalState((String)iter.next()); - sessionState = (PortletWindowBaseNavigationalState)pageState.windowStates.get(requestState.getWindowId()); - if ( sessionState == null ) + requestState = requestStates + .getPortletWindowNavigationalState((String) iter.next()); + sessionState = (PortletWindowBaseNavigationalState) pageState.windowStates + .get(requestState.getWindowId()); + if (sessionState == null) { - if ( storeParameters ) + if (storeParameters) { sessionState = new PortletWindowExtendedNavigationalState(); } @@ -211,99 +244,111 @@ { sessionState = new PortletWindowBaseNavigationalState(); } - pageState.windowStates.put(requestState.getWindowId(),sessionState); + pageState.windowStates.put(requestState.getWindowId(), + sessionState); } - actionRequestState = actionWindowId != null && actionWindowId.equals(requestState.getWindowId()); - boolean changed = syncStates(actionRequestState, requestState, sessionState); + actionRequestState = actionWindowId != null + && actionWindowId.equals(requestState.getWindowId()); + boolean changed = syncStates(actionRequestState, requestState, + sessionState); if (changed) { removeFromCache(context, requestState.getWindowId(), cache); removeFromCache(context, page.getId(), decorationCache); if (storeParameters) { - ((PortletWindowExtendedNavigationalState)sessionState).resetDecoratorActionEncodings(); + ((PortletWindowExtendedNavigationalState) sessionState) + .resetDecoratorActionEncodings(); } } } - + // now copy missing requestStates from the pageState iter = pageState.windowStates.keySet().iterator(); String windowId; - while ( iter.hasNext() ) + while (iter.hasNext()) { - windowId = (String)iter.next(); - requestState = requestStates.getPortletWindowNavigationalState(windowId); - if ( requestState == null ) + windowId = (String) iter.next(); + requestState = requestStates + .getPortletWindowNavigationalState(windowId); + if (requestState == null) { - requestState = new PortletWindowRequestNavigationalState(windowId); - boolean changed = syncStates(false, requestState,(PortletWindowBaseNavigationalState)pageState.windowStates.get(windowId)); - requestStates.addPortletWindowNavigationalState(windowId, requestState); + requestState = new PortletWindowRequestNavigationalState( + windowId); + boolean changed = syncStates( + false, + requestState, + (PortletWindowBaseNavigationalState) pageState.windowStates + .get(windowId)); + requestStates.addPortletWindowNavigationalState(windowId, + requestState); if (changed) { removeFromCache(context, requestState.getWindowId(), cache); - removeFromCache(context, page.getId(), decorationCache); + removeFromCache(context, page.getId(), decorationCache); if (storeParameters) { - ((PortletWindowExtendedNavigationalState)sessionState).resetDecoratorActionEncodings(); + ((PortletWindowExtendedNavigationalState) sessionState) + .resetDecoratorActionEncodings(); } } } - } + } } - + private boolean modeChanged(PortletMode req, PortletMode ses) { if (req == null) { - //if (ses != null && !ses.equals(PortletMode.VIEW)) - // return true; + // if (ses != null && !ses.equals(PortletMode.VIEW)) + // return true; return false; } else { if (ses == null) { - if (req.equals(PortletMode.VIEW)) - return false; + if (req.equals(PortletMode.VIEW)) return false; return true; } } return !req.equals(ses); } - + private boolean stateChanged(WindowState req, WindowState ses) { if (req == null) { - //if (ses != null && !ses.equals(WindowState.NORMAL)) - // return true; + // if (ses != null && !ses.equals(WindowState.NORMAL)) + // return true; return false; } else { if (ses == null) { - if (req.equals(WindowState.NORMAL)) - return false; + if (req.equals(WindowState.NORMAL)) return false; return true; } } return !req.equals(ses); } - - private boolean syncStates(boolean actionRequestState, PortletWindowRequestNavigationalState requestState, PortletWindowBaseNavigationalState sessionState) + private boolean syncStates(boolean actionRequestState, + PortletWindowRequestNavigationalState requestState, + PortletWindowBaseNavigationalState sessionState) { boolean changed = false; - - if (modeChanged(requestState.getPortletMode(), sessionState.getPortletMode()) - || stateChanged(requestState.getWindowState(), sessionState.getWindowState())) - changed = true; - - if ( requestState.getPortletMode() != null ) + + if (modeChanged(requestState.getPortletMode(), sessionState + .getPortletMode()) + || stateChanged(requestState.getWindowState(), sessionState + .getWindowState())) changed = true; + + if (requestState.getPortletMode() != null) { - if ( requestState.getPortletMode().equals(PortletMode.VIEW) ) + if (requestState.getPortletMode().equals(PortletMode.VIEW)) { sessionState.setPortletMode(null); } @@ -312,7 +357,7 @@ sessionState.setPortletMode(requestState.getPortletMode()); } } - else if ( sessionState.getPortletMode() == null ) + else if (sessionState.getPortletMode() == null) { requestState.setPortletMode(PortletMode.VIEW); } @@ -320,10 +365,10 @@ { requestState.setPortletMode(sessionState.getPortletMode()); } - - if ( requestState.getWindowState() != null ) + + if (requestState.getWindowState() != null) { - if ( requestState.getWindowState().equals(WindowState.NORMAL) ) + if (requestState.getWindowState().equals(WindowState.NORMAL)) { sessionState.setWindowState(null); } @@ -332,77 +377,76 @@ sessionState.setWindowState(requestState.getWindowState()); } } - else if ( sessionState.getWindowState() == null ) + else if (sessionState.getWindowState() == null) { requestState.setWindowState(WindowState.NORMAL); } - else + else { requestState.setWindowState(sessionState.getWindowState()); } - + if (storeParameters) { - PortletWindowExtendedNavigationalState extendedSessionState = (PortletWindowExtendedNavigationalState)sessionState; - if ( requestState.getParametersMap() != null ) + PortletWindowExtendedNavigationalState extendedSessionState = (PortletWindowExtendedNavigationalState) sessionState; + if (requestState.getParametersMap() != null) { - if ( actionRequestState ) + if (actionRequestState) { // never store ActionRequest parameters in session extendedSessionState.setParametersMap(null); } - else + else { - if (changedParameters(requestState.getParametersMap(), extendedSessionState.getParametersMap())) + if (changedParameters(requestState.getParametersMap(), + extendedSessionState.getParametersMap())) { changed = true; } - extendedSessionState.setParametersMap(new HashMap(requestState.getParametersMap())); + extendedSessionState.setParametersMap(new HashMap( + requestState.getParametersMap())); } } - else if ( requestState.isClearParameters() ) + else if (requestState.isClearParameters()) { extendedSessionState.setParametersMap(null); requestState.setClearParameters(false); - //changed = true; - } - else if ( extendedSessionState.getParametersMap() != null ) + // changed = true; + } + else if (extendedSessionState.getParametersMap() != null) { - requestState.setParametersMap(new HashMap(extendedSessionState.getParametersMap())); + requestState.setParametersMap(new HashMap(extendedSessionState + .getParametersMap())); } } return changed; - } + } protected boolean changedParameters(Map requestMap, Map sessionMap) { - if (sessionMap == null || requestMap == null) - return true; - if (requestMap.size() != sessionMap.size()) - return true; + if (sessionMap == null || requestMap == null) return true; + if (requestMap.size() != sessionMap.size()) return true; Iterator ri = requestMap.entrySet().iterator(); Iterator si = sessionMap.entrySet().iterator(); while (ri.hasNext() && si.hasNext()) { - Map.Entry r = (Map.Entry)ri.next(); - Map.Entry s = (Map.Entry)si.next(); - if (!r.getKey().equals(s.getKey())) - return true; - String[] rvals = (String[])r.getValue(); - String[] svals = (String[])s.getValue(); + Map.Entry r = (Map.Entry) ri.next(); + Map.Entry s = (Map.Entry) si.next(); + if (!r.getKey().equals(s.getKey())) return true; + String[] rvals = (String[]) r.getValue(); + String[] svals = (String[]) s.getValue(); for (int ix = 0; ix < rvals.length; ix++) { - if (!rvals[ix].equals(svals[ix])) - return true; + if (!rvals[ix].equals(svals[ix])) return true; } } return false; } - - protected void removeFromCache(RequestContext context, String id, JetspeedContentCache cache) + + protected void removeFromCache(RequestContext context, String id, + JetspeedContentCache cache) { - if (cache == null) - return; + if (cache == null) return; ContentCacheKey cacheKey = cache.createCacheKey(context, id); if (cache.isKeyInCache(cacheKey)) { @@ -410,10 +454,10 @@ } cache.invalidate(context); } - + protected Map getWindowStates(Page page) { - PageState pageState = (PageState)pageStates.get(page.getId()); + PageState pageState = (PageState) pageStates.get(page.getId()); return pageState != null ? pageState.windowStates : null; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/SessionFullExtendedNavigationalState.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/SessionFullExtendedNavigationalState.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/SessionFullExtendedNavigationalState.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,50 +21,58 @@ import org.apache.jetspeed.request.RequestContext; /** - * SessionFullClearOnChangePageNavigationalState, stores all nav parameters in the session, including render parameters - * + * SessionFullClearOnChangePageNavigationalState, stores all nav parameters in + * the session, including render parameters + * * @author Mohan Kannapareddy * @version $Id$ */ -public class SessionFullExtendedNavigationalState extends SessionFullNavigationalState +public class SessionFullExtendedNavigationalState extends + SessionFullNavigationalState { - private boolean clearStateOnPageChangeEnabled = false; - - public SessionFullExtendedNavigationalState(NavigationalStateCodec codec,JetspeedContentCache cache) - { - super(codec, cache); - } - public SessionFullExtendedNavigationalState(NavigationalStateCodec codec, JetspeedContentCache cache, JetspeedContentCache decorationCache) + private boolean clearStateOnPageChangeEnabled = false; + + public SessionFullExtendedNavigationalState(NavigationalStateCodec codec, + JetspeedContentCache cache) { + super(codec, cache); + } + + public SessionFullExtendedNavigationalState(NavigationalStateCodec codec, + JetspeedContentCache cache, JetspeedContentCache decorationCache) + { super(codec, cache, decorationCache); } - public SessionFullExtendedNavigationalState(NavigationalStateCodec codec, JetspeedContentCache cache, JetspeedContentCache decorationCache, boolean clearStateOnPageChangeEnabled) + public SessionFullExtendedNavigationalState(NavigationalStateCodec codec, + JetspeedContentCache cache, JetspeedContentCache decorationCache, + boolean clearStateOnPageChangeEnabled) { super(codec, cache, decorationCache); this.clearStateOnPageChangeEnabled = clearStateOnPageChangeEnabled; } - + protected boolean clearPagePortletsModeAndWindowState(RequestContext context) { String contextKey = PageHistoryValve.REQUEST_CLEAR_PORTLETS_MODE_AND_WINDOWSTATE_KEY; boolean result = false; if (clearStateOnPageChangeEnabled) { - Boolean pageNavigationEvent = (Boolean) context.getAttribute(contextKey); + Boolean pageNavigationEvent = (Boolean) context + .getAttribute(contextKey); if ((pageNavigationEvent != null)) { result = pageNavigationEvent.booleanValue(); } } - //Just to be safe make it false + // Just to be safe make it false context.setAttribute(contextKey, Boolean.FALSE); - - return result; + + return result; } - + public synchronized void sync(RequestContext context) { // JS2-806, check the session for a psuedo inter page navigation. @@ -78,9 +86,10 @@ } } - // push the informaion up to SessionNavigationalState, so that we can handle it appropriately there + // push the informaion up to SessionNavigationalState, so that we can + // handle it appropriately there setClearPortletsModeAndWindowStateEnabled(resetPagePortlets); - //Inform the super + // Inform the super super.sync(context); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/SessionFullNavigationalState.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/SessionFullNavigationalState.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/SessionFullNavigationalState.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,21 +18,25 @@ import org.apache.jetspeed.cache.JetspeedContentCache; - /** - * SessionFullNavigationalState, stores all nav parameters in the session, including render parameters - * + * SessionFullNavigationalState, stores all nav parameters in the session, + * including render parameters + * * @author Ate Douma - * @version $Id: SessionFullNavigationalState.java 553340 2007-07-04 22:00:09Z taylor $ + * @version $Id: SessionFullNavigationalState.java 553340 2007-07-04 22:00:09Z + * taylor $ */ public class SessionFullNavigationalState extends SessionNavigationalState -{ - public SessionFullNavigationalState(NavigationalStateCodec codec, JetspeedContentCache cache) +{ + + public SessionFullNavigationalState(NavigationalStateCodec codec, + JetspeedContentCache cache) { super(codec, cache); } - - public SessionFullNavigationalState(NavigationalStateCodec codec, JetspeedContentCache cache, JetspeedContentCache decorationCache) + + public SessionFullNavigationalState(NavigationalStateCodec codec, + JetspeedContentCache cache, JetspeedContentCache decorationCache) { super(codec, cache, decorationCache); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/SessionNavigationalState.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/SessionNavigationalState.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/state/impl/SessionNavigationalState.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,71 +32,84 @@ /** * SessionNavigationalState, stores nav parameters in the session, not on URL - * + * *

        - * Added the ability to reset portlet mode and window states to VIEW and NORMAL in the case - * of page navigation. JS2-806 + * Added the ability to reset portlet mode and window states to VIEW and NORMAL + * in the case of page navigation. JS2-806 *

        - * + * * @author David Sean Taylor - * @version $Id: SessionNavigationalState.java 593807 2007-11-10 19:22:03Z taylor $ + * @version $Id: SessionNavigationalState.java 593807 2007-11-10 19:22:03Z + * taylor $ */ public class SessionNavigationalState extends AbstractNavigationalState -{ - protected final Log log = LogFactory.getLog(getClass()); +{ + + protected final Log log = LogFactory.getLog(getClass()); + private Map currentPageWindowStates; + private boolean clearPortletsModeAndWindowStateEnabled = false; - - public SessionNavigationalState(NavigationalStateCodec codec, JetspeedContentCache cache) + + public SessionNavigationalState(NavigationalStateCodec codec, + JetspeedContentCache cache) { super(codec, cache); } - - public SessionNavigationalState(NavigationalStateCodec codec, JetspeedContentCache cache, JetspeedContentCache decorationCache) + + public SessionNavigationalState(NavigationalStateCodec codec, + JetspeedContentCache cache, JetspeedContentCache decorationCache) { super(codec, cache, decorationCache); - } + } public synchronized void sync(RequestContext context) { PortletWindowRequestNavigationalStates requestStates = getPortletWindowRequestNavigationalStates(); - - // for Resource (PortletURL) requests, session state is never synchronized + + // for Resource (PortletURL) requests, session state is never + // synchronized boolean transientNavState = requestStates.getResourceWindow() != null; - + String clearCacheWindowId = null; - + if (!transientNavState) { // Check if a maximized window is set in the request. // This can mean a window with state MAXIMIZED *or* SOLO. // With a SOLO state, also skip all synchroniziations! String requestMaximizedWindowId = null; - - if ( requestStates.getMaximizedWindow() != null ) + + if (requestStates.getMaximizedWindow() != null) { - requestMaximizedWindowId = requestStates.getMaximizedWindow().getId().toString(); - WindowState state = requestStates.getPortletWindowNavigationalState(requestMaximizedWindowId).getWindowState(); + requestMaximizedWindowId = requestStates.getMaximizedWindow() + .getId().toString(); + WindowState state = requestStates + .getPortletWindowNavigationalState( + requestMaximizedWindowId).getWindowState(); transientNavState = JetspeedActions.SOLO_STATE.equals(state); clearCacheWindowId = requestMaximizedWindowId; } - + } if (transientNavState) { // no navState synchronizations - + if (clearCacheWindowId != null) { HttpSession session = context.getRequest().getSession(); - if ( session != null ) + if (session != null) { - PortletWindowSessionNavigationalStates sessionStates = (PortletWindowSessionNavigationalStates)session.getAttribute(NavigationalState.NAVSTATE_SESSION_KEY); - if ( sessionStates != null ) + PortletWindowSessionNavigationalStates sessionStates = (PortletWindowSessionNavigationalStates) session + .getAttribute(NavigationalState.NAVSTATE_SESSION_KEY); + if (sessionStates != null) { - sessionStates.removeFromCache(context, clearCacheWindowId, cache); + sessionStates.removeFromCache(context, + clearCacheWindowId, cache); ContentPage page = context.getPage(); - sessionStates.removeFromCache(context, page.getId(), decorationCache); + sessionStates.removeFromCache(context, page.getId(), + decorationCache); } } } @@ -104,37 +117,47 @@ else { HttpSession session = context.getRequest().getSession(); - if ( session != null ) + if (session != null) { - PortletWindowSessionNavigationalStates sessionStates = (PortletWindowSessionNavigationalStates)session.getAttribute(NavigationalState.NAVSTATE_SESSION_KEY); - if ( sessionStates == null ) + PortletWindowSessionNavigationalStates sessionStates = (PortletWindowSessionNavigationalStates) session + .getAttribute(NavigationalState.NAVSTATE_SESSION_KEY); + if (sessionStates == null) { - sessionStates = new PortletWindowSessionNavigationalStates(isRenderParameterStateFull()); - session.setAttribute(NavigationalState.NAVSTATE_SESSION_KEY, sessionStates); + sessionStates = new PortletWindowSessionNavigationalStates( + isRenderParameterStateFull()); + session.setAttribute( + NavigationalState.NAVSTATE_SESSION_KEY, + sessionStates); } Page page = context.getPage(); // JS2-806 if (isClearPortletsModeAndWindowStateEnabled()) { - sessionStates.changeAllPortletsToViewModeAndNormalWindowState(context, page, requestStates, cache, decorationCache); + sessionStates + .changeAllPortletsToViewModeAndNormalWindowState( + context, page, requestStates, cache, + decorationCache); } else { - sessionStates.sync(context, (Page) context.getPage(), requestStates, cache, decorationCache); + sessionStates.sync(context, (Page) context.getPage(), + requestStates, cache, decorationCache); } - if (isNavigationalParameterStateFull() && isRenderParameterStateFull()) + if (isNavigationalParameterStateFull() + && isRenderParameterStateFull()) { - currentPageWindowStates = sessionStates.getWindowStates(page); + currentPageWindowStates = sessionStates + .getWindowStates(page); } } } } - + public Map getCurrentPageWindowStates() { return currentPageWindowStates; } - + public boolean isNavigationalParameterStateFull() { return true; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/AbstractPortalURL.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/AbstractPortalURL.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/AbstractPortalURL.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,102 +32,123 @@ import org.apache.pluto.om.window.PortletWindow; /** - * AbstractPortalURL delivers the base implemention for parsing Jetspeed Portal URLs and creating new Portlet URLs. - * Not implemented is the encoding and decoding of the NavigationState parameter in the URL, allowing concrete - * implementations to supply different algorithms for it like encoding it as pathInfo or as query string parameter. - * + * AbstractPortalURL delivers the base implemention for parsing Jetspeed Portal + * URLs and creating new Portlet URLs. Not implemented is the encoding and + * decoding of the NavigationState parameter in the URL, allowing concrete + * implementations to supply different algorithms for it like encoding it as + * pathInfo or as query string parameter. + * * @author Ate Douma * @version $Id: AbstractPortalURL.java 605989 2007-12-20 18:26:54Z ate $ */ public abstract class AbstractPortalURL implements PortalURL { + public static final String DEFAULT_NAV_STATE_PARAMETER = "_ns"; - + protected static String navStateParameter; - + protected NavigationalState navState; + protected BasePortalURL base = null; - + protected static Boolean relativeOnly; + protected String contextPath; + protected String basePath; + protected String path; + protected String encodedNavState; + protected String secureBaseURL; + protected String nonSecureBaseURL; + protected String characterEncoding = "UTF-8"; - - public AbstractPortalURL(NavigationalState navState, PortalContext portalContext, BasePortalURL base) + public AbstractPortalURL(NavigationalState navState, + PortalContext portalContext, BasePortalURL base) { - this(navState, portalContext); + this(navState, portalContext); this.base = base; } - - public AbstractPortalURL(NavigationalState navState, PortalContext portalContext) + + public AbstractPortalURL(NavigationalState navState, + PortalContext portalContext) { - if ( navStateParameter == null ) + if (navStateParameter == null) { - navStateParameter = - portalContext.getConfigurationProperty("portalurl.navigationalstate.parameter.name", - DEFAULT_NAV_STATE_PARAMETER); + navStateParameter = portalContext.getConfigurationProperty( + "portalurl.navigationalstate.parameter.name", + DEFAULT_NAV_STATE_PARAMETER); } this.navState = navState; - if ( relativeOnly == null ) + if (relativeOnly == null) { - relativeOnly = new Boolean(portalContext.getConfiguration().getBoolean("portalurl.relative.only", false)); + relativeOnly = new Boolean(portalContext.getConfiguration() + .getBoolean("portalurl.relative.only", false)); } } - - - public AbstractPortalURL(String characterEncoding, NavigationalState navState, PortalContext portalContext) + + public AbstractPortalURL(String characterEncoding, + NavigationalState navState, PortalContext portalContext) { this(navState, portalContext); this.characterEncoding = characterEncoding; } - - public AbstractPortalURL(HttpServletRequest request, String characterEncoding, NavigationalState navState, PortalContext portalContext) + + public AbstractPortalURL(HttpServletRequest request, + String characterEncoding, NavigationalState navState, + PortalContext portalContext) { this(characterEncoding, navState, portalContext); setRequest(request); } - + public boolean isRelativeOnly() { return relativeOnly.booleanValue(); } - + public static String getNavigationalStateParameterName() { return navStateParameter; } - - public String createNavigationalEncoding(PortletWindow window, Map parameters, PortletMode mode, WindowState state, boolean action) + + public String createNavigationalEncoding(PortletWindow window, + Map parameters, PortletMode mode, WindowState state, boolean action) { try { - return getNavigationalStateParameterName() + ":" + getNavigationalState().encode(window, parameters, mode, state, action); + return getNavigationalStateParameterName() + + ":" + + getNavigationalState().encode(window, parameters, mode, + state, action); } catch (UnsupportedEncodingException e) { e.printStackTrace(); - return ""; - } + return ""; + } } - - public String createNavigationalEncoding(PortletWindow window, PortletMode mode, WindowState state) + + public String createNavigationalEncoding(PortletWindow window, + PortletMode mode, WindowState state) { try { - return getNavigationalStateParameterName() + ":" + getNavigationalState().encode(window, mode, state); + return getNavigationalStateParameterName() + ":" + + getNavigationalState().encode(window, mode, state); } catch (UnsupportedEncodingException e) { e.printStackTrace(); - return ""; - } + return ""; + } } - + protected void decodeBaseURL(HttpServletRequest request) { if (base == null) @@ -136,16 +157,16 @@ base.setServerScheme(request.getScheme()); base.setServerName(request.getServerName()); base.setServerPort(request.getServerPort()); - base.setSecure(request.isSecure()); + base.setSecure(request.isSecure()); } - if ( relativeOnly.booleanValue() ) + if (relativeOnly.booleanValue()) { this.secureBaseURL = this.nonSecureBaseURL = ""; } else { StringBuffer buffer; - + buffer = new StringBuffer(HTTPS); buffer.append("://").append(base.getServerName()); if (base.getServerPort() != 443 && base.getServerPort() != 80) @@ -153,20 +174,21 @@ buffer.append(":").append(base.getServerPort()); } this.secureBaseURL = buffer.toString(); - + buffer = new StringBuffer(HTTP); buffer.append("://").append(base.getServerName()); if (base.getServerPort() != 443 && base.getServerPort() != 80) { - buffer.append(":").append(base.getServerPort()); + buffer.append(":").append(base.getServerPort()); } this.nonSecureBaseURL = buffer.toString(); } } - + protected void decodeBasePath(HttpServletRequest request) { - this.contextPath = (String) request.getAttribute(ContainerConstants.PORTAL_CONTEXT); + this.contextPath = (String) request + .getAttribute(ContainerConstants.PORTAL_CONTEXT); if (contextPath == null) { contextPath = request.getContextPath(); @@ -185,14 +207,15 @@ protected void setEncodedNavigationalState(String encodedNavigationalState) { - this.encodedNavState = encodedNavigationalState; + this.encodedNavState = encodedNavigationalState; try { navState.init(encodedNavState, characterEncoding); } catch (UnsupportedEncodingException e) { - IllegalStateException ise = new IllegalStateException("An unsupported encoding was defined for this NavigationalState."); + IllegalStateException ise = new IllegalStateException( + "An unsupported encoding was defined for this NavigationalState."); ise.initCause(e); throw ise; } @@ -207,56 +230,59 @@ { return getBaseURL(base.isSecure()); } - + public String getBaseURL(boolean secure) { // TODO: delivering both secure and non-secure baseURL for PLT.7.1.2 - // currently only the baseURL as decoded (secure or non-secure) is returned - // and the secure parameter is ignored + // currently only the baseURL as decoded (secure or non-secure) is + // returned + // and the secure parameter is ignored return secure ? secureBaseURL : nonSecureBaseURL; } - + public String getBasePath() { return basePath; } - + public String getPath() { return path; - } + } public String getPageBasePath() { - if ( null == path || (1 == path.length() && '/' == path.charAt(0)) ) + if (null == path || (1 == path.length() && '/' == path.charAt(0))) { return basePath; } - else if ( -1 != path.indexOf('/') && !path.endsWith("/") ) + else if (-1 != path.indexOf('/') && !path.endsWith("/")) { - return basePath + path.substring(0, path.lastIndexOf('/') ); + return basePath + path.substring(0, path.lastIndexOf('/')); } else { return basePath + path; } } - + public boolean isSecure() { return base.isSecure(); } - + public NavigationalState getNavigationalState() { return navState; } - public String createPortletURL(PortletWindow window, Map parameters, PortletMode mode, WindowState state, boolean action, boolean secure) + public String createPortletURL(PortletWindow window, Map parameters, + PortletMode mode, WindowState state, boolean action, boolean secure) { try { - return createPortletURL(navState.encode(window,parameters,mode,state,action), secure); + return createPortletURL(navState.encode(window, parameters, mode, + state, action), secure); } catch (UnsupportedEncodingException e) { @@ -267,11 +293,13 @@ } } - public String createPortletURL(PortletWindow window, PortletMode mode, WindowState state, boolean secure) + public String createPortletURL(PortletWindow window, PortletMode mode, + WindowState state, boolean secure) { try { - return createPortletURL(navState.encode(window,mode,state), secure); + return createPortletURL(navState.encode(window, mode, state), + secure); } catch (UnsupportedEncodingException e) { @@ -280,25 +308,28 @@ // to keep the compiler happy return null; } - } + } - protected abstract void decodePathAndNavigationalState(HttpServletRequest request); - - protected abstract String createPortletURL(String encodedNavState, boolean secure); + protected abstract void decodePathAndNavigationalState( + HttpServletRequest request); + protected abstract String createPortletURL(String encodedNavState, + boolean secure); + public void setRequest(HttpServletRequest request) { - ArgUtil.assertNotNull(HttpServletRequest.class, request, this, "setRequest"); - decodeBaseURL(request); - decodeBasePath(request); - decodePathAndNavigationalState(request); + ArgUtil.assertNotNull(HttpServletRequest.class, request, this, + "setRequest"); + decodeBaseURL(request); + decodeBasePath(request); + decodePathAndNavigationalState(request); } public void setCharacterEncoding(String characterEncoding) { this.characterEncoding = characterEncoding; } - + public String getPortalURL() { try Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/BasePortalURLImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/BasePortalURLImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/BasePortalURLImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,58 +24,62 @@ /** *

        * BasePortalURL defines the interface for manipulating Base URLs in a portal. - * Base URLs contain the isSecure flag, server name, server port, and server scheme. - * This abstraction was necessary for wiring the entire portal's base URL via another - * mechanism than retrieving from the servlet request. + * Base URLs contain the isSecure flag, server name, server port, and server + * scheme. This abstraction was necessary for wiring the entire portal's base + * URL via another mechanism than retrieving from the servlet request. *

        * * @author David Sean Taylor * @version $Id: $ - * + * */ public class BasePortalURLImpl implements BasePortalURL { - private String serverName; + + private String serverName; + private String serverScheme; - private int serverPort; + + private int serverPort; + private boolean secure; - + public BasePortalURLImpl() - { + { } - + /** * This constructor takes a string that represents the name of an - * environment variable. The environment variable will be the full - * path of a properties file to be loaded. Information from the - * properties file will populate this object + * environment variable. The environment variable will be the full path of a + * properties file to be loaded. Information from the properties file will + * populate this object */ - public BasePortalURLImpl(String environmentPath) throws ConfigurationException + public BasePortalURLImpl(String environmentPath) + throws ConfigurationException { String propertyFilePath = null; - if (environmentPath != null) + if (environmentPath != null) { propertyFilePath = System.getProperty(environmentPath); } - + PropertiesConfiguration config = null; - + // Load the file if the path is provided - if (propertyFilePath != null) + if (propertyFilePath != null) { config = new PropertiesConfiguration(propertyFilePath); } - if (config != null) + if (config != null) { this.serverName = config.getString("portal.url.name"); this.serverScheme = config.getString("portal.url.scheme"); this.serverPort = config.getInt("portal.url.port"); - this.secure = config.getBoolean("portal.url.secure"); + this.secure = config.getBoolean("portal.url.secure"); } } - - + public BasePortalURLImpl(Configuration config) { this.serverName = config.getString("portal.url.name"); @@ -83,50 +87,51 @@ this.serverPort = config.getInt("portal.url.port"); this.secure = config.getBoolean("portal.url.secure"); } - - public BasePortalURLImpl(String serverScheme, String serverName, int serverPort, boolean secure) + + public BasePortalURLImpl(String serverScheme, String serverName, + int serverPort, boolean secure) { this.serverName = serverName; this.serverScheme = serverScheme; this.serverPort = serverPort; this.secure = secure; } - + public boolean isSecure() { return secure; } - + public void setSecure(boolean secure) { this.secure = secure; } - + public String getServerName() { return serverName; } - + public void setServerName(String serverName) { this.serverName = serverName; } - + public int getServerPort() { return serverPort; } - + public void setServerPort(int serverPort) { this.serverPort = serverPort; } - + public String getServerScheme() { return serverScheme; } - + public void setServerScheme(String serverScheme) { this.serverScheme = serverScheme; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/CleanPathInfoEncodedNavStateFromPortalURLValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/CleanPathInfoEncodedNavStateFromPortalURLValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/CleanPathInfoEncodedNavStateFromPortalURLValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,48 +27,62 @@ import org.apache.jetspeed.request.RequestContext; /** - * This Valve will clean encoded navstate from the browser url by sending a client side redirect - * to the same url with the navstate removed. + * This Valve will clean encoded navstate from the browser url by sending a + * client side redirect to the same url with the navstate removed. *

        * This Valve will only do this: *

          - *
        • on a GET Render request (not for Resource or Action requests)
        • - *
        • the request is not served by the Desktop
        • - *
        • the navstate is encoded as PathInfo
        • - *
        • all the navstate is maintained in the session (portlet mode, window state and render parameters)
        • + *
        • on a GET Render request (not for Resource or Action requests)
        • + *
        • the request is not served by the Desktop
        • + *
        • the navstate is encoded as PathInfo
        • + *
        • all the navstate is maintained in the session (portlet mode, window + * state and render parameters)
        • *
        *

        *

        - * This valve needs to be added to the portal pipeline *after* the ContainerValve to ensure navstate is properly synchronized with the session. + * This valve needs to be added to the portal pipeline *after* the + * ContainerValve to ensure navstate is properly synchronized with the session. *

        *

        * Caveats:
        *

          - *
        • bookmarking browser url will no longer retain nav state, but with SessionFullNavigationState this wasn't really reliable anyway.
        • - *
        • back button history is no longer maintained by browsers for GET render urls, somewhat similar to Ajax based requests (e.g. Desktop)
        • + *
        • bookmarking browser url will no longer retain nav state, but with + * SessionFullNavigationState this wasn't really reliable anyway.
        • + *
        • back button history is no longer maintained by browsers for GET render + * urls, somewhat similar to Ajax based requests (e.g. Desktop)
        • *
        + * * @author Ate Douma - * @version $Id: CleanPathInfoEncodedNavStateFromPortalURLValve.java 605989 2007-12-20 18:26:54Z ate $ + * @version $Id: CleanPathInfoEncodedNavStateFromPortalURLValve.java 605989 + * 2007-12-20 18:26:54Z ate $ * */ -public class CleanPathInfoEncodedNavStateFromPortalURLValve extends AbstractValve +public class CleanPathInfoEncodedNavStateFromPortalURLValve extends + AbstractValve { - public void invoke(RequestContext request, ValveContext context) throws PipelineException + + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { NavigationalState state = request.getPortalURL().getNavigationalState(); PortalURL portalURL = request.getPortalURL(); - Boolean desktopEnabled = (Boolean) request.getAttribute(JetspeedDesktop.DESKTOP_ENABLED_REQUEST_ATTRIBUTE); + Boolean desktopEnabled = (Boolean) request + .getAttribute(JetspeedDesktop.DESKTOP_ENABLED_REQUEST_ATTRIBUTE); - if (request.getRequest().getMethod().equals("GET") && portalURL.hasEncodedNavState() - && portalURL.isPathInfoEncodingNavState() && state.isNavigationalParameterStateFull() - && state.isRenderParameterStateFull() && state.getPortletWindowOfAction() == null + if (request.getRequest().getMethod().equals("GET") + && portalURL.hasEncodedNavState() + && portalURL.isPathInfoEncodingNavState() + && state.isNavigationalParameterStateFull() + && state.isRenderParameterStateFull() + && state.getPortletWindowOfAction() == null && state.getPortletWindowOfResource() == null && (desktopEnabled == null || desktopEnabled.booleanValue() == false)) { try { - StringBuffer location = new StringBuffer(request.getPortalURL().getBasePath()); + StringBuffer location = new StringBuffer(request.getPortalURL() + .getBasePath()); String str = request.getPortalURL().getPath(); if (str != null) { @@ -77,9 +91,12 @@ str = request.getRequest().getQueryString(); if (str != null && str.length() > 0) { - location.append('?').append(request.getRequest().getQueryString()); + location.append('?').append( + request.getRequest().getQueryString()); } - request.getResponse().sendRedirect(request.getResponse().encodeRedirectURL(location.toString())); + request.getResponse().sendRedirect( + request.getResponse().encodeRedirectURL( + location.toString())); } catch (IOException e) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/DesktopEncodingPortalURL.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/DesktopEncodingPortalURL.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/DesktopEncodingPortalURL.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,83 +30,105 @@ import org.apache.jetspeed.container.url.BasePortalURL; import org.apache.jetspeed.desktop.JetspeedDesktop; import org.apache.jetspeed.om.common.portlet.MutablePortletApplication; -import org.apache.pluto.om.window.PortletWindow; import org.apache.pluto.om.entity.PortletEntity; import org.apache.pluto.om.portlet.PortletDefinition; +import org.apache.pluto.om.window.PortletWindow; /** - * DesktopEncodingPortalURL encodes action URLs to target desktop specific /action pipeline, - * and render URLs to target desktop specific /render pipeline + * DesktopEncodingPortalURL encodes action URLs to target desktop specific + * /action pipeline, and render URLs to target desktop specific /render pipeline * - * The query parameters "entity" and "portlet" are added to each url. These parameters are needed in a /render - * request and are used by the desktop javascript code for both /render and /action requests. + * The query parameters "entity" and "portlet" are added to each url. These + * parameters are needed in a /render request and are used by the desktop + * javascript code for both /render and /action requests. * * @author Ate Douma - * @version $Id: PathInfoEncodingPortalURL.java 367856 2006-01-11 01:04:09Z taylor $ + * @version $Id: PathInfoEncodingPortalURL.java 367856 2006-01-11 01:04:09Z + * taylor $ */ public class DesktopEncodingPortalURL extends AbstractPortalURL { + private String baseActionPath = null; + private String baseRenderPath = null; - + private String desktopActionPipelinePath = null; + private String desktopRenderPipelinePath = null; - - - public DesktopEncodingPortalURL(NavigationalState navState, PortalContext portalContext, String desktopRenderPipelinePath, String desktopActionPipelinePath) + + public DesktopEncodingPortalURL(NavigationalState navState, + PortalContext portalContext, String desktopRenderPipelinePath, + String desktopActionPipelinePath) { super(navState, portalContext); - initializePipelinePaths( desktopRenderPipelinePath, desktopActionPipelinePath ); + initializePipelinePaths(desktopRenderPipelinePath, + desktopActionPipelinePath); } - - public DesktopEncodingPortalURL(NavigationalState navState, PortalContext portalContext, String desktopRenderPipelinePath, String desktopActionPipelinePath, BasePortalURL base) + + public DesktopEncodingPortalURL(NavigationalState navState, + PortalContext portalContext, String desktopRenderPipelinePath, + String desktopActionPipelinePath, BasePortalURL base) { super(navState, portalContext, base); - initializePipelinePaths( desktopRenderPipelinePath, desktopActionPipelinePath ); + initializePipelinePaths(desktopRenderPipelinePath, + desktopActionPipelinePath); } - public DesktopEncodingPortalURL(String characterEncoding, NavigationalState navState, PortalContext portalContext) + public DesktopEncodingPortalURL(String characterEncoding, + NavigationalState navState, PortalContext portalContext) { super(characterEncoding, navState, portalContext); - initializePipelinePaths( null, null ); + initializePipelinePaths(null, null); } - public DesktopEncodingPortalURL(HttpServletRequest request, String characterEncoding, NavigationalState navState, PortalContext portalContext) + public DesktopEncodingPortalURL(HttpServletRequest request, + String characterEncoding, NavigationalState navState, + PortalContext portalContext) { super(request, characterEncoding, navState, portalContext); - initializePipelinePaths( null, null ); + initializePipelinePaths(null, null); } - - private void initializePipelinePaths( String desktopRenderPipelinePath, String desktopActionPipelinePath ) + + private void initializePipelinePaths(String desktopRenderPipelinePath, + String desktopActionPipelinePath) { - if ( desktopActionPipelinePath == null || desktopActionPipelinePath.length() == 0 ) + if (desktopActionPipelinePath == null + || desktopActionPipelinePath.length() == 0) desktopActionPipelinePath = JetspeedDesktop.DEFAULT_DESKTOP_ACTION_PIPELINE_PATH; - if ( desktopActionPipelinePath.charAt( 0 ) != '/' ) + if (desktopActionPipelinePath.charAt(0) != '/') desktopActionPipelinePath = "/" + desktopActionPipelinePath; - if ( desktopActionPipelinePath.length() > 1 && desktopActionPipelinePath.charAt( desktopActionPipelinePath.length() -1 ) == '/' ) - desktopActionPipelinePath = desktopActionPipelinePath.substring( 0, desktopActionPipelinePath.length() -1 ); + if (desktopActionPipelinePath.length() > 1 + && desktopActionPipelinePath.charAt(desktopActionPipelinePath + .length() - 1) == '/') + desktopActionPipelinePath = desktopActionPipelinePath.substring(0, + desktopActionPipelinePath.length() - 1); - if ( desktopRenderPipelinePath == null || desktopRenderPipelinePath.length() == 0 ) + if (desktopRenderPipelinePath == null + || desktopRenderPipelinePath.length() == 0) desktopRenderPipelinePath = JetspeedDesktop.DEFAULT_DESKTOP_RENDER_PIPELINE_PATH; - if ( desktopRenderPipelinePath.charAt( 0 ) != '/' ) + if (desktopRenderPipelinePath.charAt(0) != '/') desktopRenderPipelinePath = "/" + desktopRenderPipelinePath; - if ( desktopRenderPipelinePath.length() > 1 && desktopRenderPipelinePath.charAt( desktopRenderPipelinePath.length() -1 ) == '/' ) - desktopRenderPipelinePath = desktopRenderPipelinePath.substring( 0, desktopRenderPipelinePath.length() -1 ); - + if (desktopRenderPipelinePath.length() > 1 + && desktopRenderPipelinePath.charAt(desktopRenderPipelinePath + .length() - 1) == '/') + desktopRenderPipelinePath = desktopRenderPipelinePath.substring(0, + desktopRenderPipelinePath.length() - 1); + this.desktopRenderPipelinePath = desktopRenderPipelinePath; - this.desktopActionPipelinePath = desktopActionPipelinePath; + this.desktopActionPipelinePath = desktopActionPipelinePath; } protected void decodeBasePath(HttpServletRequest request) { super.decodeBasePath(request); - if ( this.baseActionPath == null ) + if (this.baseActionPath == null) { this.baseActionPath = contextPath + this.desktopActionPipelinePath; this.baseRenderPath = contextPath + this.desktopRenderPipelinePath; } } - + protected void decodePathAndNavigationalState(HttpServletRequest request) { String path = null; @@ -115,20 +137,22 @@ String pathInfo = request.getPathInfo(); if (pathInfo != null) { - StringTokenizer tokenizer = new StringTokenizer(request.getPathInfo(),"/"); + StringTokenizer tokenizer = new StringTokenizer(request + .getPathInfo(), "/"); StringBuffer buffer = new StringBuffer(); String token; boolean foundNavState = false; - String navStatePrefix = getNavigationalStateParameterName() +":"; + String navStatePrefix = getNavigationalStateParameterName() + ":"; while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); if (!foundNavState && token.startsWith(navStatePrefix)) { foundNavState = true; - if ( token.length() > navStatePrefix.length() ) + if (token.length() > navStatePrefix.length()) { - encodedNavState = token.substring(navStatePrefix.length()); + encodedNavState = token.substring(navStatePrefix + .length()); } } else @@ -137,7 +161,7 @@ buffer.append(token); } } - if ( buffer.length() > 0 ) + if (buffer.length() > 0) { path = buffer.toString(); } @@ -154,14 +178,18 @@ { return createPortletURL(encodedNavState, secure, null, false); } - - protected String createPortletURL(String encodedNavState, boolean secure, PortletWindow window, boolean action) - { - return createPortletURL(encodedNavState, secure, window, action, false, false); + + protected String createPortletURL(String encodedNavState, boolean secure, + PortletWindow window, boolean action) + { + return createPortletURL(encodedNavState, secure, window, action, false, + false); } - - protected String createPortletURL(String encodedNavState, boolean secure, PortletWindow window, boolean action, boolean resource, boolean desktopRequestNotAjax) - { + + protected String createPortletURL(String encodedNavState, boolean secure, + PortletWindow window, boolean action, boolean resource, + boolean desktopRequestNotAjax) + { StringBuffer buffer = new StringBuffer(""); buffer.append(getBaseURL(secure)); if (action) @@ -170,31 +198,32 @@ } else { - buffer.append(this.baseRenderPath); - } - if ( encodedNavState != null ) + buffer.append(this.baseRenderPath); + } + if (encodedNavState != null) { buffer.append("/"); buffer.append(getNavigationalStateParameterName()); buffer.append(":"); buffer.append(encodedNavState); } - if ( getPath() != null ) + if (getPath() != null) { buffer.append(getPath()); } - - if ( !resource ) + + if (!resource) { - if ( ! desktopRequestNotAjax ) + if (!desktopRequestNotAjax) { - PortletEntity pe = window.getPortletEntity(); - buffer.append( "?entity=" ).append( pe.getId() ); - - PortletDefinition portlet = pe.getPortletDefinition(); - MutablePortletApplication app = (MutablePortletApplication)portlet.getPortletApplicationDefinition(); - String uniqueName = app.getName() + "::" + portlet.getName(); - buffer.append( "&portlet=" ).append( uniqueName ); + PortletEntity pe = window.getPortletEntity(); + buffer.append("?entity=").append(pe.getId()); + + PortletDefinition portlet = pe.getPortletDefinition(); + MutablePortletApplication app = (MutablePortletApplication) portlet + .getPortletApplicationDefinition(); + String uniqueName = app.getName() + "::" + portlet.getName(); + buffer.append("&portlet=").append(uniqueName); } } else @@ -203,20 +232,27 @@ } return buffer.toString(); - } - - public String createPortletURL(PortletWindow window, Map parameters, PortletMode mode, WindowState state, boolean action, boolean secure) + } + + public String createPortletURL(PortletWindow window, Map parameters, + PortletMode mode, WindowState state, boolean action, boolean secure) { try { - boolean resource = !action && parameters.containsKey(PortalReservedParameters.PORTLET_RESOURCE_URL_REQUEST_PARAMETER); + boolean resource = !action + && parameters + .containsKey(PortalReservedParameters.PORTLET_RESOURCE_URL_REQUEST_PARAMETER); boolean desktopRequestNotAjax = false; - if ( parameters.containsKey(JetspeedDesktop.DESKTOP_REQUEST_NOT_AJAX_PARAMETER) ) + if (parameters + .containsKey(JetspeedDesktop.DESKTOP_REQUEST_NOT_AJAX_PARAMETER)) { - desktopRequestNotAjax = true; - parameters.remove(JetspeedDesktop.DESKTOP_REQUEST_NOT_AJAX_PARAMETER); + desktopRequestNotAjax = true; + parameters + .remove(JetspeedDesktop.DESKTOP_REQUEST_NOT_AJAX_PARAMETER); } - return createPortletURL(this.getNavigationalState().encode(window,parameters,mode,state,action), secure, window, action, resource, desktopRequestNotAjax); + return createPortletURL(this.getNavigationalState().encode(window, + parameters, mode, state, action), secure, window, action, + resource, desktopRequestNotAjax); } catch (UnsupportedEncodingException e) { @@ -225,5 +261,5 @@ // to keep the compiler happy return null; } - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/GlassFishPathInfoEncodingPortalURL.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/GlassFishPathInfoEncodingPortalURL.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/GlassFishPathInfoEncodingPortalURL.java 2008-05-16 01:54:54 UTC (rev 940) @@ -13,63 +13,80 @@ import org.apache.jetspeed.container.url.BasePortalURL; import org.apache.pluto.om.window.PortletWindow; -public class GlassFishPathInfoEncodingPortalURL extends AbstractPortalURL { +public class GlassFishPathInfoEncodingPortalURL extends AbstractPortalURL +{ + public GlassFishPathInfoEncodingPortalURL(NavigationalState navState, - PortalContext portalContext, BasePortalURL base) { + PortalContext portalContext, BasePortalURL base) + { super(navState, portalContext, base); } public GlassFishPathInfoEncodingPortalURL(NavigationalState navState, - PortalContext portalContext) { + PortalContext portalContext) + { super(navState, portalContext); } public GlassFishPathInfoEncodingPortalURL(String characterEncoding, - NavigationalState navState, PortalContext portalContext) { + NavigationalState navState, PortalContext portalContext) + { super(characterEncoding, navState, portalContext); } public GlassFishPathInfoEncodingPortalURL(HttpServletRequest request, String characterEncoding, NavigationalState navState, - PortalContext portalContext) { + PortalContext portalContext) + { super(request, characterEncoding, navState, portalContext); } - protected String getNavigationalStateParameterSeparator() { + protected String getNavigationalStateParameterSeparator() + { return "-"; } public String createNavigationalEncoding(PortletWindow window, - Map parameters, PortletMode mode, WindowState state, boolean action) { - try { + Map parameters, PortletMode mode, WindowState state, boolean action) + { + try + { return getNavigationalStateParameterName() + getNavigationalStateParameterSeparator() + getNavigationalState().encode(window, parameters, mode, state, action); - } catch (UnsupportedEncodingException e) { + } + catch (UnsupportedEncodingException e) + { e.printStackTrace(); return ""; } } public String createNavigationalEncoding(PortletWindow window, - PortletMode mode, WindowState state) { - try { + PortletMode mode, WindowState state) + { + try + { return getNavigationalStateParameterName() + getNavigationalStateParameterSeparator() + getNavigationalState().encode(window, mode, state); - } catch (UnsupportedEncodingException e) { + } + catch (UnsupportedEncodingException e) + { e.printStackTrace(); return ""; } } - protected void decodePathAndNavigationalState(HttpServletRequest request) { + protected void decodePathAndNavigationalState(HttpServletRequest request) + { String path = null; String encodedNavState = null; String pathInfo = request.getPathInfo(); - if (pathInfo != null) { + if (pathInfo != null) + { StringTokenizer tokenizer = new StringTokenizer(request .getPathInfo(), "/"); StringBuffer buffer = new StringBuffer(); @@ -77,22 +94,30 @@ boolean foundNavState = false; String navStatePrefix = getNavigationalStateParameterName() + getNavigationalStateParameterSeparator(); - while (tokenizer.hasMoreTokens()) { + while (tokenizer.hasMoreTokens()) + { token = tokenizer.nextToken(); - if (!foundNavState && token.startsWith(navStatePrefix)) { + if (!foundNavState && token.startsWith(navStatePrefix)) + { foundNavState = true; - if (token.length() > navStatePrefix.length()) { + if (token.length() > navStatePrefix.length()) + { encodedNavState = token.substring(navStatePrefix .length()); } - } else { + } + else + { buffer.append("/"); buffer.append(token); } } - if (buffer.length() > 0) { + if (buffer.length() > 0) + { path = buffer.toString(); - } else { + } + else + { path = "/"; } } @@ -100,22 +125,26 @@ setEncodedNavigationalState(encodedNavState); } - protected String createPortletURL(String encodedNavState, boolean secure) { + protected String createPortletURL(String encodedNavState, boolean secure) + { StringBuffer buffer = new StringBuffer(getBaseURL(secure)); buffer.append(getBasePath()); - if (encodedNavState != null) { + if (encodedNavState != null) + { buffer.append("/"); buffer.append(getNavigationalStateParameterName()); buffer.append(getNavigationalStateParameterSeparator()); buffer.append(encodedNavState); } - if (getPath() != null) { + if (getPath() != null) + { buffer.append(getPath()); } return buffer.toString(); } - public boolean isPathInfoEncodingNavState() { + public boolean isPathInfoEncodingNavState() + { return true; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/JetspeedPortletURL.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/JetspeedPortletURL.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/JetspeedPortletURL.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,15 +23,18 @@ import org.apache.pluto.om.window.PortletWindow; /** - * Jetspeed extension of the Pluto PortalURLImpl providing support for session url rewriting - * when cookies are disabled. - * + * Jetspeed extension of the Pluto PortalURLImpl providing support for session + * url rewriting when cookies are disabled. + * * @author Ate Douma * @version $Id: JetspeedPortletURL.java 516448 2007-03-09 16:25:47Z ate $ */ public class JetspeedPortletURL extends PortletURLImpl { - public JetspeedPortletURL(PortletWindow portletWindow, HttpServletRequest servletRequest, HttpServletResponse servletResponse, boolean isAction) + + public JetspeedPortletURL(PortletWindow portletWindow, + HttpServletRequest servletRequest, + HttpServletResponse servletResponse, boolean isAction) { super(portletWindow, servletRequest, servletResponse, isAction); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/PathInfoEncodingPortalURL.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/PathInfoEncodingPortalURL.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/PathInfoEncodingPortalURL.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,29 +25,35 @@ import org.apache.jetspeed.container.url.BasePortalURL; /** - * PathInfoEncodingPortalURL encodes the NavigationalState as PathInfo element - * * + * PathInfoEncodingPortalURL encodes the NavigationalState as PathInfo element * + * * @author Ate Douma * @version $Id: PathInfoEncodingPortalURL.java 605989 2007-12-20 18:26:54Z ate $ */ public class PathInfoEncodingPortalURL extends AbstractPortalURL { - public PathInfoEncodingPortalURL(NavigationalState navState, PortalContext portalContext, BasePortalURL base) + + public PathInfoEncodingPortalURL(NavigationalState navState, + PortalContext portalContext, BasePortalURL base) { super(navState, portalContext, base); } - public PathInfoEncodingPortalURL(NavigationalState navState, PortalContext portalContext) + public PathInfoEncodingPortalURL(NavigationalState navState, + PortalContext portalContext) { super(navState, portalContext); } - public PathInfoEncodingPortalURL(String characterEncoding, NavigationalState navState, PortalContext portalContext) + public PathInfoEncodingPortalURL(String characterEncoding, + NavigationalState navState, PortalContext portalContext) { super(characterEncoding, navState, portalContext); } - public PathInfoEncodingPortalURL(HttpServletRequest request, String characterEncoding, NavigationalState navState, PortalContext portalContext) + public PathInfoEncodingPortalURL(HttpServletRequest request, + String characterEncoding, NavigationalState navState, + PortalContext portalContext) { super(request, characterEncoding, navState, portalContext); } @@ -60,20 +66,22 @@ String pathInfo = request.getPathInfo(); if (pathInfo != null) { - StringTokenizer tokenizer = new StringTokenizer(request.getPathInfo(),"/"); + StringTokenizer tokenizer = new StringTokenizer(request + .getPathInfo(), "/"); StringBuffer buffer = new StringBuffer(); String token; boolean foundNavState = false; - String navStatePrefix = getNavigationalStateParameterName() +":"; + String navStatePrefix = getNavigationalStateParameterName() + ":"; while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); if (!foundNavState && token.startsWith(navStatePrefix)) { foundNavState = true; - if ( token.length() > navStatePrefix.length() ) + if (token.length() > navStatePrefix.length()) { - encodedNavState = token.substring(navStatePrefix.length()); + encodedNavState = token.substring(navStatePrefix + .length()); } } else @@ -82,7 +90,7 @@ buffer.append(token); } } - if ( buffer.length() > 0 ) + if (buffer.length() > 0) { path = buffer.toString(); } @@ -99,14 +107,14 @@ { StringBuffer buffer = new StringBuffer(getBaseURL(secure)); buffer.append(getBasePath()); - if ( encodedNavState != null ) + if (encodedNavState != null) { buffer.append("/"); buffer.append(getNavigationalStateParameterName()); buffer.append(":"); buffer.append(encodedNavState); } - if ( getPath() != null ) + if (getPath() != null) { buffer.append(getPath()); } @@ -116,5 +124,5 @@ public boolean isPathInfoEncodingNavState() { return true; - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/PortalURLValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/PortalURLValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/PortalURLValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,45 +18,53 @@ package org.apache.jetspeed.container.url.impl; import org.apache.jetspeed.container.state.NavigationalStateComponent; +import org.apache.jetspeed.desktop.JetspeedDesktop; import org.apache.jetspeed.pipeline.PipelineException; import org.apache.jetspeed.pipeline.valve.AbstractValve; import org.apache.jetspeed.pipeline.valve.ValveContext; import org.apache.jetspeed.request.RequestContext; -import org.apache.jetspeed.desktop.JetspeedDesktop; /** * Creates the PortalURL for the current Request - * + * * @author Ate Douma * @version $Id: PortalURLValveImpl.java 588430 2007-10-26 00:08:07Z smilek $ */ public class PortalURLValveImpl extends AbstractValve { + private NavigationalStateComponent navComponent; public PortalURLValveImpl(NavigationalStateComponent navComponent) { this.navComponent = navComponent; } - + public void invoke(RequestContext request, ValveContext context) - throws PipelineException + throws PipelineException { try - { - if ( request.getPortalURL() == null ) + { + if (request.getPortalURL() == null) { - String encoding = request.getRequestParameter(JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER); - if (encoding != null && encoding.equals(JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER_VALUE)) + String encoding = request + .getRequestParameter(JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER); + if (encoding != null + && encoding + .equals(JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER_VALUE)) { - request.setPortalURL(navComponent.createDesktopURL(request.getRequest(), request.getCharacterEncoding())); - request.setAttribute( JetspeedDesktop.DESKTOP_ENABLED_REQUEST_ATTRIBUTE, Boolean.TRUE ); + request.setPortalURL(navComponent.createDesktopURL(request + .getRequest(), request.getCharacterEncoding())); + request.setAttribute( + JetspeedDesktop.DESKTOP_ENABLED_REQUEST_ATTRIBUTE, + Boolean.TRUE); } else { - request.setPortalURL(navComponent.createURL(request.getRequest(), request.getCharacterEncoding())); + request.setPortalURL(navComponent.createURL(request + .getRequest(), request.getCharacterEncoding())); } - + } } catch (Exception e) @@ -64,7 +72,7 @@ throw new PipelineException(e); } // Pass control to the next Valve in the Pipeline - context.invokeNext( request ); + context.invokeNext(request); } public String toString() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/PortletURLFactoryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/PortletURLFactoryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/PortletURLFactoryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,29 +23,33 @@ /** * Jetspeed implementation of the Pluto PortalURLFactory - * + * * @author Ate Douma * @version $Id: PortletURLFactoryImpl.java 516448 2007-03-09 16:25:47Z ate $ */ -public class PortletURLFactoryImpl implements PortletURLFactory { +public class PortletURLFactoryImpl implements PortletURLFactory +{ - public void init(javax.servlet.ServletConfig config, java.util.Map properties) throws Exception + public void init(javax.servlet.ServletConfig config, + java.util.Map properties) throws Exception { } public PortletURL getPortletURL(PortletWindow portletWindow, - javax.servlet.http.HttpServletRequest servletRequest, - javax.servlet.http.HttpServletResponse servletResponse) + javax.servlet.http.HttpServletRequest servletRequest, + javax.servlet.http.HttpServletResponse servletResponse) { - return getPortletURL(portletWindow, servletRequest, servletResponse, false); + return getPortletURL(portletWindow, servletRequest, servletResponse, + false); } public PortletURL getPortletURL(PortletWindow portletWindow, - javax.servlet.http.HttpServletRequest servletRequest, - javax.servlet.http.HttpServletResponse servletResponse, - boolean isAction) + javax.servlet.http.HttpServletRequest servletRequest, + javax.servlet.http.HttpServletResponse servletResponse, + boolean isAction) { - return new JetspeedPortletURL(portletWindow, servletRequest, servletResponse, isAction); + return new JetspeedPortletURL(portletWindow, servletRequest, + servletResponse, isAction); } public void destroy() throws Exception Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/QueryStringEncodingPortalURL.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/QueryStringEncodingPortalURL.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/url/impl/QueryStringEncodingPortalURL.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,58 +23,67 @@ import org.apache.jetspeed.container.url.BasePortalURL; /** - * QueryStringEncodingPortalURL encodes the NavigationalState as query parameter - * * + * QueryStringEncodingPortalURL encodes the NavigationalState as query parameter * + * * @author Ate Douma - * @version $Id: QueryStringEncodingPortalURL.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: QueryStringEncodingPortalURL.java 516448 2007-03-09 16:25:47Z + * ate $ */ public class QueryStringEncodingPortalURL extends AbstractPortalURL { - public QueryStringEncodingPortalURL(NavigationalState navState, PortalContext portalContext, BasePortalURL base) + + public QueryStringEncodingPortalURL(NavigationalState navState, + PortalContext portalContext, BasePortalURL base) { super(navState, portalContext, base); } - public QueryStringEncodingPortalURL(NavigationalState navState, PortalContext portalContext) + public QueryStringEncodingPortalURL(NavigationalState navState, + PortalContext portalContext) { super(navState, portalContext); } - public QueryStringEncodingPortalURL(String characterEncoding, NavigationalState navState, PortalContext portalContext) + public QueryStringEncodingPortalURL(String characterEncoding, + NavigationalState navState, PortalContext portalContext) { super(characterEncoding, navState, portalContext); } - public QueryStringEncodingPortalURL(HttpServletRequest request, String characterEncoding, NavigationalState navState, PortalContext portalContext) + public QueryStringEncodingPortalURL(HttpServletRequest request, + String characterEncoding, NavigationalState navState, + PortalContext portalContext) { super(request, characterEncoding, navState, portalContext); } protected void decodePathAndNavigationalState(HttpServletRequest request) { - setEncodedNavigationalState(request.getParameter(getNavigationalStateParameterName())); + setEncodedNavigationalState(request + .getParameter(getNavigationalStateParameterName())); String path = null; if (request.getPathInfo() != null) { path = request.getPathInfo(); int length = path.length(); - if ( length > 1 && path.endsWith("/") ) + if (length > 1 && path.endsWith("/")) { - path = path.substring(0, length-1); + path = path.substring(0, length - 1); } } setPath(path); } - - protected String createPortletURL(String encodedNavigationalState, boolean secure) + + protected String createPortletURL(String encodedNavigationalState, + boolean secure) { StringBuffer buffer = new StringBuffer(getBaseURL(secure)); buffer.append(getBasePath()); - if ( getPath() != null ) + if (getPath() != null) { buffer.append(getPath()); } - if ( encodedNavigationalState != null ) + if (encodedNavigationalState != null) { buffer.append("?"); buffer.append(getNavigationalStateParameterName()); @@ -82,5 +91,5 @@ buffer.append(encodedNavigationalState); } return buffer.toString(); - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/window/impl/PortletWindowAccessorImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/window/impl/PortletWindowAccessorImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/container/window/impl/PortletWindowAccessorImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -44,23 +44,31 @@ /** * Portlet Window Accessor Implementation - * + * * @author David Sean Taylor - * @version $Id: PortletWindowAccessorImpl.java,v 1.12 2005/04/29 14:01:57 weaver Exp $ + * @version $Id: PortletWindowAccessorImpl.java,v 1.12 2005/04/29 14:01:57 + * weaver Exp $ */ -public class PortletWindowAccessorImpl implements PortletWindowAccessor, RegistryEventListener +public class PortletWindowAccessorImpl implements PortletWindowAccessor, + RegistryEventListener { - protected final static Log log = LogFactory.getLog(PortletWindowAccessorImpl.class); - - //private Map windows = Collections.synchronizedMap(new HashMap()); + + protected final static Log log = LogFactory + .getLog(PortletWindowAccessorImpl.class); + + // private Map windows = Collections.synchronizedMap(new HashMap()); private PortletEntityAccessComponent entityAccessor; + private PortletFactory portletFactory; + private boolean validateWindows = false; + private PortletWindowCache portletWindowCache; - - - public PortletWindowAccessorImpl(PortletEntityAccessComponent entityAccessor, PortletFactory portletFactory, PortletWindowCache portletWindowCache, boolean validateWindows) + public PortletWindowAccessorImpl( + PortletEntityAccessComponent entityAccessor, + PortletFactory portletFactory, + PortletWindowCache portletWindowCache, boolean validateWindows) { this.entityAccessor = entityAccessor; this.portletFactory = portletFactory; @@ -69,11 +77,10 @@ } - public PortletWindowAccessorImpl(PortletEntityAccessComponent entityAccessor, - PortletFactory portletFactory, - PortletRegistry registry, - PortletWindowCache portletWindowCache, - boolean validateWindows) + public PortletWindowAccessorImpl( + PortletEntityAccessComponent entityAccessor, + PortletFactory portletFactory, PortletRegistry registry, + PortletWindowCache portletWindowCache, boolean validateWindows) { this.entityAccessor = entityAccessor; this.portletFactory = portletFactory; @@ -81,31 +88,30 @@ this.portletWindowCache = portletWindowCache; registry.addRegistryListener(this); } - - public PortletWindow createPortletWindow(PortletEntity entity, String windowId) + + public PortletWindow createPortletWindow(PortletEntity entity, + String windowId) { - if(entity == null) - { - throw new IllegalArgumentException("cratePortletWindow requires a non-null PortletEntity"); - } - + if (entity == null) { throw new IllegalArgumentException( + "cratePortletWindow requires a non-null PortletEntity"); } + PortletWindow found = getWindowFromCache(windowId); if (found != null) { // remove from cache if invalid entity checkPortletWindowEntity(found); - ((PortletWindowCtrl)found).setPortletEntity(entity); + ((PortletWindowCtrl) found).setPortletEntity(entity); return found; } - + PortletWindowImpl window = new PortletWindowImpl(windowId); window.setPortletEntity(entity); - if ( isValidPortletEntity(entity)) + if (isValidPortletEntity(entity)) { // windows.put(windowId, window); - portletWindowCache.putPortletWindow(window); + portletWindowCache.putPortletWindow(window); } - return window; + return window; } public PortletWindow createPortletWindow(String windowId) @@ -116,11 +122,11 @@ // remove from cache if invalid entity checkPortletWindowEntity(found); return found; - } + } PortletWindowImpl window = new PortletWindowImpl(windowId); - return window; + return window; } - + public PortletWindow getPortletWindow(String windowId) { PortletWindow window = getWindowFromCache(windowId); @@ -128,14 +134,17 @@ { // remove from cache if invalid entity checkPortletWindowEntity(window); - } + } return window; } - - public PortletWindow getPortletWindow(ContentFragment fragment) throws FailedToRetrievePortletWindow, PortletEntityNotStoredException + + public PortletWindow getPortletWindow(ContentFragment fragment) + throws FailedToRetrievePortletWindow, + PortletEntityNotStoredException { - ArgUtil.assertNotNull(ContentFragment.class, fragment, this, "getPortletWindow(Fragment fragment)"); - PortletWindow portletWindow = getWindowFromCache(fragment); + ArgUtil.assertNotNull(ContentFragment.class, fragment, this, + "getPortletWindow(Fragment fragment)"); + PortletWindow portletWindow = getWindowFromCache(fragment); if (portletWindow == null || !checkPortletWindowEntity(portletWindow)) { try @@ -154,25 +163,28 @@ validateWindow(fragment, portletWindow); } } - + return portletWindow; } - + /** *

        * validateWindow *

        - * + * * @param fragment * @param portletWindow - * @throws PortletEntityNotStoredException + * @throws PortletEntityNotStoredException * @throws InconsistentWindowStateException */ - protected void validateWindow( ContentFragment fragment, PortletWindow portletWindow ) throws FailedToRetrievePortletWindow, PortletEntityNotStoredException + protected void validateWindow(ContentFragment fragment, + PortletWindow portletWindow) throws FailedToRetrievePortletWindow, + PortletEntityNotStoredException { // make sure the window has the most up-to-date portlet entity - PortletEntity portletEntity = entityAccessor.getPortletEntityForFragment(fragment); - if(portletEntity != null) + PortletEntity portletEntity = entityAccessor + .getPortletEntityForFragment(fragment); + if (portletEntity != null) { ((PortletWindowCtrl) portletWindow).setPortletEntity(portletEntity); // if not a valid entity, remove window from cache @@ -180,20 +192,26 @@ } else { - removeWindow(portletWindow); - throw new FailedToRetrievePortletWindow("No PortletEntity exists for for id "+fragment.getId()+" removing window from cache."); + removeWindow(portletWindow); + throw new FailedToRetrievePortletWindow( + "No PortletEntity exists for for id " + fragment.getId() + + " removing window from cache."); } } - public PortletWindow getPortletWindow(ContentFragment fragment, String principal) throws FailedToRetrievePortletWindow, FailedToCreateWindowException, PortletEntityNotStoredException + public PortletWindow getPortletWindow(ContentFragment fragment, + String principal) throws FailedToRetrievePortletWindow, + FailedToCreateWindowException, PortletEntityNotStoredException { - ArgUtil.assertNotNull(ContentFragment.class, fragment, this, "getPortletWindow(Fragment fragment, String principal)"); - ArgUtil.assertNotNull(String.class, principal, this, "getPortletWindow(Fragment fragment, String principal)"); + ArgUtil.assertNotNull(ContentFragment.class, fragment, this, + "getPortletWindow(Fragment fragment, String principal)"); + ArgUtil.assertNotNull(String.class, principal, this, + "getPortletWindow(Fragment fragment, String principal)"); PortletWindow portletWindow = getWindowFromCache(fragment); if (portletWindow == null) { return createPortletWindow(fragment, principal); - } + } else { // make sure the window has the most up-to-date portlet entity @@ -202,25 +220,33 @@ return portletWindow; } - private PortletWindow createPortletWindow(ContentFragment fragment) throws FailedToCreateWindowException, PortletEntityNotStoredException + private PortletWindow createPortletWindow(ContentFragment fragment) + throws FailedToCreateWindowException, + PortletEntityNotStoredException { return createPortletWindow(fragment, null); } - - private PortletWindow createPortletWindow(ContentFragment fragment, String principal) throws FailedToCreateWindowException, PortletEntityNotStoredException - { + + private PortletWindow createPortletWindow(ContentFragment fragment, + String principal) throws FailedToCreateWindowException, + PortletEntityNotStoredException + { PortletWindow portletWindow = new PortletWindowImpl(fragment.getId()); boolean temporaryWindow = false; - - MutablePortletEntity portletEntity = entityAccessor.getPortletEntityForFragment(fragment, principal); + + MutablePortletEntity portletEntity = entityAccessor + .getPortletEntityForFragment(fragment, principal); if (portletEntity == null) { - log.info("No portlet entity defined for fragment ID "+fragment.getId()+" attempting to auto-generate..."); + log.info("No portlet entity defined for fragment ID " + + fragment.getId() + " attempting to auto-generate..."); try { - portletEntity = entityAccessor.generateEntityFromFragment(fragment, principal); - // not portlet definition most likely means that the portlet has not been deployed so dont worry about storing off the entity - if(isValidPortletEntity(portletEntity)) + portletEntity = entityAccessor.generateEntityFromFragment( + fragment, principal); + // not portlet definition most likely means that the portlet has + // not been deployed so dont worry about storing off the entity + if (isValidPortletEntity(portletEntity)) { entityAccessor.storePortletEntity(portletEntity); } @@ -232,58 +258,60 @@ } catch (PortletEntityNotGeneratedException e) { - throw new FailedToCreateWindowException("Error generating new PortletEntity: "+e.toString(), e); + throw new FailedToCreateWindowException( + "Error generating new PortletEntity: " + e.toString(), + e); } catch (PortletEntityNotStoredException e) { - throw new FailedToCreateWindowException("Error storing new PortletEntity: "+e.toString(), e); + throw new FailedToCreateWindowException( + "Error storing new PortletEntity: " + e.toString(), e); } - - if(portletEntity == null) - { - throw new FailedToCreateWindowException("Unable to generate portlet entity."); - } - + + if (portletEntity == null) { throw new FailedToCreateWindowException( + "Unable to generate portlet entity."); } + } ((PortletWindowCtrl) portletWindow).setPortletEntity(portletEntity); - - if ( !temporaryWindow ) + + if (!temporaryWindow) { portletWindowCache.putPortletWindow(portletWindow); } - + return portletWindow; } - public void removeWindows(PortletEntity portletEntity) { -// List tmpWindows = new ArrayList(windows.entrySet()); -// for(int i = 0; i < tmpWindows.size(); i++) -// { -// PortletWindow window = (PortletWindow)((Map.Entry)tmpWindows.get(i)).getValue(); -// if (portletEntity.getId().equals(window.getPortletEntity().getId())) -// { -// removeWindow(window); -// } -// } -// tmpWindows.clear(); -// - portletWindowCache.removePortletWindowByPortletEntityId(portletEntity.getId().toString()); + // List tmpWindows = new ArrayList(windows.entrySet()); + // for(int i = 0; i < tmpWindows.size(); i++) + // { + // PortletWindow window = + // (PortletWindow)((Map.Entry)tmpWindows.get(i)).getValue(); + // if (portletEntity.getId().equals(window.getPortletEntity().getId())) + // { + // removeWindow(window); + // } + // } + // tmpWindows.clear(); + // + portletWindowCache.removePortletWindowByPortletEntityId(portletEntity + .getId().toString()); } - + public void removeWindow(PortletWindow window) { - // windows.remove(window.getId().toString()); - portletWindowCache.removePortletWindow(window.getId().toString()); + // windows.remove(window.getId().toString()); + portletWindowCache.removePortletWindow(window.getId().toString()); } - + private PortletWindow getWindowFromCache(ContentFragment fragment) { return portletWindowCache.getPortletWindow(fragment.getId()); } - + private PortletWindow getWindowFromCache(String id) { return portletWindowCache.getPortletWindow(id); @@ -298,16 +326,18 @@ } return true; } - + private boolean isValidPortletEntity(PortletEntity pe) { return pe != null && pe.getPortletDefinition() != null && pe.getPortletDefinition().getPortletApplicationDefinition() != null - && portletFactory.isPortletApplicationRegistered((PortletApplication) pe.getPortletDefinition() - .getPortletApplicationDefinition()); + && portletFactory + .isPortletApplicationRegistered((PortletApplication) pe + .getPortletDefinition() + .getPortletApplicationDefinition()); } - + public Set getPortletWindows() { return portletWindowCache.getAllPortletWindows(); @@ -315,93 +345,102 @@ protected void removeForPortletDefinition(PortletDefinitionComposite def) { -// List tmpWindows = new ArrayList(windows.entrySet()); -// for (int i = 0; i < tmpWindows.size(); i++) -// { -// PortletWindow window = (PortletWindow)((Map.Entry)tmpWindows.get(i)).getValue(); -// PortletDefinitionComposite windowDef = (PortletDefinitionComposite)window.getPortletEntity().getPortletDefinition(); -// if(def != null && windowDef != null && def.getUniqueName() != null && def.getUniqueName().equals(windowDef.getUniqueName())) -// { -// removeWindow(window); -// } -// } -// tmpWindows.clear(); -// if (def != null) -// portletFactory.updatePortletConfig(def); - - - Iterator windows = getPortletWindows().iterator(); - while(windows.hasNext()) + // List tmpWindows = new ArrayList(windows.entrySet()); + // for (int i = 0; i < tmpWindows.size(); i++) + // { + // PortletWindow window = + // (PortletWindow)((Map.Entry)tmpWindows.get(i)).getValue(); + // PortletDefinitionComposite windowDef = + // (PortletDefinitionComposite)window.getPortletEntity().getPortletDefinition(); + // if(def != null && windowDef != null && def.getUniqueName() != null && + // def.getUniqueName().equals(windowDef.getUniqueName())) + // { + // removeWindow(window); + // } + // } + // tmpWindows.clear(); + // if (def != null) + // portletFactory.updatePortletConfig(def); + + Iterator windows = getPortletWindows().iterator(); + while (windows.hasNext()) { - PortletWindow window = (PortletWindow) windows.next(); - PortletDefinitionComposite windowDef = (PortletDefinitionComposite)window.getPortletEntity().getPortletDefinition(); - if(def != null && windowDef != null && def.getUniqueName() != null && def.getUniqueName().equals(windowDef.getUniqueName())) + PortletWindow window = (PortletWindow) windows.next(); + PortletDefinitionComposite windowDef = (PortletDefinitionComposite) window + .getPortletEntity().getPortletDefinition(); + if (def != null && windowDef != null && def.getUniqueName() != null + && def.getUniqueName().equals(windowDef.getUniqueName())) { removeWindow(window); } } - - if (def != null) - portletFactory.updatePortletConfig(def); + + if (def != null) portletFactory.updatePortletConfig(def); } protected void removeForPortletApplication(MutablePortletApplication app) { -// List tmpWindows = new ArrayList(windows.entrySet()); -// for (int i = 0; i < tmpWindows.size(); i++) -// { -// PortletWindow window = (PortletWindow)((Map.Entry)tmpWindows.get(i)).getValue(); -// PortletDefinitionComposite pd = (PortletDefinitionComposite)window.getPortletEntity().getPortletDefinition(); -// if (pd != null) -// { -// MutablePortletApplication windowApp = (MutablePortletApplication)pd.getPortletApplicationDefinition(); -// if (app.getName().equals(windowApp.getName())) -// { -// removeWindow(window); -// } -// } -// } -// tmpWindows.clear(); - - Iterator windows = getPortletWindows().iterator(); - while(windows.hasNext()) + // List tmpWindows = new ArrayList(windows.entrySet()); + // for (int i = 0; i < tmpWindows.size(); i++) + // { + // PortletWindow window = + // (PortletWindow)((Map.Entry)tmpWindows.get(i)).getValue(); + // PortletDefinitionComposite pd = + // (PortletDefinitionComposite)window.getPortletEntity().getPortletDefinition(); + // if (pd != null) + // { + // MutablePortletApplication windowApp = + // (MutablePortletApplication)pd.getPortletApplicationDefinition(); + // if (app.getName().equals(windowApp.getName())) + // { + // removeWindow(window); + // } + // } + // } + // tmpWindows.clear(); + + Iterator windows = getPortletWindows().iterator(); + while (windows.hasNext()) { - PortletWindow window = (PortletWindow) windows.next(); - PortletDefinitionComposite pd = (PortletDefinitionComposite)window.getPortletEntity().getPortletDefinition(); - if (pd != null) - { - MutablePortletApplication windowApp = (MutablePortletApplication)pd.getPortletApplicationDefinition(); - if (app.getName().equals(windowApp.getName())) - { - removeWindow(window); - } - } + PortletWindow window = (PortletWindow) windows.next(); + PortletDefinitionComposite pd = (PortletDefinitionComposite) window + .getPortletEntity().getPortletDefinition(); + if (pd != null) + { + MutablePortletApplication windowApp = (MutablePortletApplication) pd + .getPortletApplicationDefinition(); + if (app.getName().equals(windowApp.getName())) + { + removeWindow(window); + } + } } - - - + } - + public void applicationRemoved(MutablePortletApplication app) { if (app == null) { - //System.out.println("@@@ receiving APP REMOVED message with NULL"); + // System.out.println("@@@ receiving APP REMOVED message with + // NULL"); return; } - //System.out.println("@@@ receiving APP REMOVED message: " + app.getName()); + // System.out.println("@@@ receiving APP REMOVED message: " + + // app.getName()); removeForPortletApplication(app); } - public void applicationUpdated(MutablePortletApplication app) { if (app == null) { - //System.out.println("@@@ receiving APP UPDATED message with NULL"); + // System.out.println("@@@ receiving APP UPDATED message with + // NULL"); return; } - //System.out.println("@@@ receiving APP UPDATED message: " + app.getName()); + // System.out.println("@@@ receiving APP UPDATED message: " + + // app.getName()); removeForPortletApplication(app); } @@ -409,21 +448,25 @@ { if (def == null) { - //System.out.println("@@@ receiving DEF REMOVED message with NULL"); + // System.out.println("@@@ receiving DEF REMOVED message with + // NULL"); return; } - //System.out.println("@@@ receiving DEF REMOVED message: " + def.getName()); + // System.out.println("@@@ receiving DEF REMOVED message: " + + // def.getName()); removeForPortletDefinition(def); } - + public void portletUpdated(PortletDefinitionComposite def) { if (def == null) { - //System.out.println("@@@ receiving DEF UPDATED message with NULL"); + // System.out.println("@@@ receiving DEF UPDATED message with + // NULL"); return; } - //System.out.println("@@@ receiving DEF UPDATED message: " + def.getName()); + // System.out.println("@@@ receiving DEF UPDATED message: " + + // def.getName()); removeForPortletDefinition(def); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/AbstractDecoratorActionsFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/AbstractDecoratorActionsFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/AbstractDecoratorActionsFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.decoration; import java.util.ArrayList; @@ -34,13 +34,18 @@ import org.apache.jetspeed.security.SecurityAccessController; import org.apache.pluto.om.window.PortletWindow; -public abstract class AbstractDecoratorActionsFactory implements DecoratorActionsFactory +public abstract class AbstractDecoratorActionsFactory implements + DecoratorActionsFactory { + private static ThreadLocal actionResourcesMap = new ThreadLocal(); + private boolean editMaximizesOption = false; + private boolean configMaximizesOption = false; + private boolean editDefaultsMaximizesOption = false; - + /** * When Edit is clicked, also maximize the window state * @@ -49,62 +54,71 @@ public AbstractDecoratorActionsFactory() { } - - public List getDecoratorActions(RequestContext rc, PortletApplication pa, PortletWindow pw, PortletMode pm, - WindowState ws, Decoration decoration, List actionTemplates,PortletDefinitionComposite portlet, - ContentFragment fragment,SecurityAccessController accessController) + + public List getDecoratorActions(RequestContext rc, PortletApplication pa, + PortletWindow pw, PortletMode pm, WindowState ws, + Decoration decoration, List actionTemplates, + PortletDefinitionComposite portlet, ContentFragment fragment, + SecurityAccessController accessController) { DecoratorAction action; - boolean checkConstraints=false; + boolean checkConstraints = false; ArrayList actions = new ArrayList(); - + Iterator iter = actionTemplates.iterator(); while (iter.hasNext()) { checkConstraints = false; - DecoratorActionTemplate template = (DecoratorActionTemplate)iter.next(); - //checking the constraints only on EDIT and HELP Action, as VIEW will taken care with portlet view. - if (template.getAction().equals(JetspeedActions.EDIT) || template.getAction().equals(JetspeedActions.HELP)) - checkConstraints = true; - if (checkConstraints && checkSecurityConstraint(portlet,fragment,accessController,template.getAction())) + DecoratorActionTemplate template = (DecoratorActionTemplate) iter + .next(); + // checking the constraints only on EDIT and HELP Action, as VIEW + // will taken care with portlet view. + if (template.getAction().equals(JetspeedActions.EDIT) + || template.getAction().equals(JetspeedActions.HELP)) + checkConstraints = true; + if (checkConstraints + && checkSecurityConstraint(portlet, fragment, + accessController, template.getAction())) { - action = createAction(rc, pw, decoration,template ); - if ( action != null) + action = createAction(rc, pw, decoration, template); + if (action != null) { actions.add(action); } } else if (!checkConstraints) { - action = createAction(rc, pw, decoration,template ); - if ( action != null) + action = createAction(rc, pw, decoration, template); + if (action != null) { actions.add(action); } - } + } } return actions; } - - public List getDecoratorActions(RequestContext rc, PortletApplication pa, PortletWindow pw, PortletMode pm, - WindowState ws, Decoration decoration, List actionTemplates) + + public List getDecoratorActions(RequestContext rc, PortletApplication pa, + PortletWindow pw, PortletMode pm, WindowState ws, + Decoration decoration, List actionTemplates) { DecoratorAction action; ArrayList actions = new ArrayList(); Iterator iter = actionTemplates.iterator(); while (iter.hasNext()) { - action = createAction(rc, pw, decoration,(DecoratorActionTemplate)iter.next() ); - if ( action != null) + action = createAction(rc, pw, decoration, + (DecoratorActionTemplate) iter.next()); + if (action != null) { actions.add(action); } } return actions; - } + } - protected DecoratorAction createAction(RequestContext rc, PortletWindow pw, Decoration decoration, - DecoratorActionTemplate template) + protected DecoratorAction createAction(RequestContext rc, PortletWindow pw, + Decoration decoration, DecoratorActionTemplate template) { String actionName = template.getAction(); @@ -114,19 +128,24 @@ WindowState ws; PortletMode pm; - if (editMaximizesOption || configMaximizesOption || editDefaultsMaximizesOption) + if (editMaximizesOption || configMaximizesOption + || editDefaultsMaximizesOption) { - if (editMaximizesOption && template.getAction().equals(JetspeedActions.EDIT)) + if (editMaximizesOption + && template.getAction().equals(JetspeedActions.EDIT)) { ws = WindowState.MAXIMIZED; pm = template.getCustomMode(); } - else if (configMaximizesOption && template.getAction().equals(JetspeedActions.CONFIG)) + else if (configMaximizesOption + && template.getAction().equals(JetspeedActions.CONFIG)) { ws = WindowState.MAXIMIZED; pm = template.getCustomMode(); } - else if (editDefaultsMaximizesOption && template.getAction().equals(JetspeedActions.EDIT_DEFAULTS)) + else if (editDefaultsMaximizesOption + && template.getAction().equals( + JetspeedActions.EDIT_DEFAULTS)) { ws = WindowState.MAXIMIZED; pm = template.getCustomMode(); @@ -134,12 +153,12 @@ else if (template.getAction().equals(JetspeedActions.VIEW)) { ws = WindowState.NORMAL; - pm = template.getCustomMode(); + pm = template.getCustomMode(); } else if (template.getAction().equals(JetspeedActions.NORMAL)) { - pm = PortletMode.VIEW; - ws = template.getCustomState(); + pm = PortletMode.VIEW; + ws = template.getCustomState(); } else { @@ -150,13 +169,14 @@ else { ws = template.getCustomState(); - pm = template.getCustomMode(); + pm = template.getCustomMode(); } - ///////////////////////////////////// - + // /////////////////////////////////// + String actionURL = rc.getResponse().encodeURL( - (isAjaxRequest == null) ? portalURL.createPortletURL(pw, pm, ws, portalURL.isSecure()).toString() - : portalURL.createNavigationalEncoding(pw, pm, ws)); + (isAjaxRequest == null) ? portalURL.createPortletURL(pw, pm, + ws, portalURL.isSecure()).toString() : portalURL + .createNavigationalEncoding(pw, pm, ws)); String linkURL = decoration .getResource("images/" + actionName + ".gif"); @@ -166,72 +186,73 @@ || (template.getState() != null && !template.getState().equals( template.getCustomState())); - HashMap resourcesMap = (HashMap)actionResourcesMap.get(); - ResourceBundle bundle = DecoratorAction.getResourceBundle(rc.getLocale()); + HashMap resourcesMap = (HashMap) actionResourcesMap.get(); + ResourceBundle bundle = DecoratorAction.getResourceBundle(rc + .getLocale()); String localizedName = null; - + if (resourcesMap == null) { resourcesMap = new HashMap(); actionResourcesMap.set(resourcesMap); resourcesMap.put(DecoratorAction.RESOURCE_BUNDLE, bundle); - localizedName = DecoratorAction.getResourceString(bundle, actionName, actionName); - resourcesMap.put(actionName,localizedName); + localizedName = DecoratorAction.getResourceString(bundle, + actionName, actionName); + resourcesMap.put(actionName, localizedName); } else { - localizedName = (String)resourcesMap.get(actionName); + localizedName = (String) resourcesMap.get(actionName); if (localizedName == null) { - localizedName = DecoratorAction.getResourceString(bundle, actionName, actionName); - resourcesMap.put(actionName,localizedName); + localizedName = DecoratorAction.getResourceString(bundle, + actionName, actionName); + resourcesMap.put(actionName, localizedName); } } - return new DecoratorAction(actionName, localizedName, localizedName, linkURL, actionURL, customAction, template.getActionType()); + return new DecoratorAction(actionName, localizedName, localizedName, + linkURL, actionURL, customAction, template.getActionType()); } - - //added for checkin the constraints on actions + + // added for checkin the constraints on actions protected boolean checkSecurityConstraint( PortletDefinitionComposite portlet, ContentFragment fragment, SecurityAccessController accessController, String action) { if (fragment.getType().equals(ContentFragment.PORTLET)) { - if (accessController != null) - { - return accessController + if (accessController != null) { return accessController .checkPortletAccess(portlet, JetspeedActions - .getContainerActionMask(action)); - } + .getContainerActionMask(action)); } } return true; - } - + } + public void setMaximizeOnEdit(boolean maxOnEdit) { this.editMaximizesOption = maxOnEdit; } - + public boolean getMaximizeOnEdit() { return this.editMaximizesOption; } - + public void setMaximizeOnConfig(boolean maxOnConfig) { this.configMaximizesOption = maxOnConfig; } - + public boolean getMaximizeOnConfig() { return this.configMaximizesOption; } - + public void setMaximizeOnEditDefaults(boolean maxOnEditDefaults) { this.editDefaultsMaximizesOption = maxOnEditDefaults; } - + public boolean getMaximizeOnEditDefaults() { return this.editDefaultsMaximizesOption; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/BaseDecoration.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/BaseDecoration.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/BaseDecoration.java 2008-05-16 01:54:54 UTC (rev 940) @@ -47,136 +47,161 @@ */ public class BaseDecoration implements Decoration, Serializable { + private static final Log log = LogFactory.getLog(BaseDecoration.class); - + protected static final String NO_SUCH_RESOURCE = "no_such_resource"; + protected transient Properties config; - private transient ResourceValidator validator; + + private transient ResourceValidator validator; + private final String name; + private final Path basePath; + private final Path baseClientPath; + private transient PathResolverCache cache; + private final String commonStylesheet; + private final String portalStylesheet; + private final String desktopStylesheet; + private List actions; + private String currentModeAction; + private String currentStateAction; + private boolean supportsDesktop; - + /** * - * @param config java.util.Properties object containing configuration infomation - * for this Decoration. - * @param validator The ResourceValidator to be used in looking up fully-qualified resource pathes - * @param baseClientPath The "root" of the decroation hierarchy. + * @param config + * java.util.Properties object containing + * configuration infomation for this Decoration. + * @param validator + * The ResourceValidator to be used in looking up fully-qualified + * resource pathes + * @param baseClientPath + * The "root" of the decroation hierarchy. * * @throws InvalidDecorationConfigurationException */ - public BaseDecoration( Properties config, ResourceValidator validator, Path basePath, Path baseClientPath, PathResolverCache cache ) - { + public BaseDecoration(Properties config, ResourceValidator validator, + Path basePath, Path baseClientPath, PathResolverCache cache) + { this.config = config; this.validator = validator; this.basePath = basePath; - this.baseClientPath= baseClientPath; + this.baseClientPath = baseClientPath; this.cache = cache; - - this.name = config.getProperty( "name" ); - - this.commonStylesheet = config.getProperty( "stylesheet", DEFAULT_COMMON_STYLE_SHEET ); - - this.supportsDesktop = "true".equalsIgnoreCase( config.getProperty( Decoration.DESKTOP_SUPPORTED_PROPERTY ) ); - if ( this.supportsDesktop ) + + this.name = config.getProperty("name"); + + this.commonStylesheet = config.getProperty("stylesheet", + DEFAULT_COMMON_STYLE_SHEET); + + this.supportsDesktop = "true".equalsIgnoreCase(config + .getProperty(Decoration.DESKTOP_SUPPORTED_PROPERTY)); + if (this.supportsDesktop) { - this.portalStylesheet = config.getProperty( "stylesheet.portal", DEFAULT_PORTAL_STYLE_SHEET ); - this.desktopStylesheet = config.getProperty( "stylesheet.desktop", DEFAULT_DESKTOP_STYLE_SHEET ); + this.portalStylesheet = config.getProperty("stylesheet.portal", + DEFAULT_PORTAL_STYLE_SHEET); + this.desktopStylesheet = config.getProperty("stylesheet.desktop", + DEFAULT_DESKTOP_STYLE_SHEET); } else { this.portalStylesheet = null; this.desktopStylesheet = null; } - + if (log.isDebugEnabled()) { - log.debug( "BaseDecoration basePath: " + basePath.toString() ); - log.debug( "BaseDecoration baseClientPath: " + baseClientPath.toString() ); + log.debug("BaseDecoration basePath: " + basePath.toString()); + log.debug("BaseDecoration baseClientPath: " + + baseClientPath.toString()); } } - - public void init(Properties config, ResourceValidator validator, PathResolverCache cache) + + public void init(Properties config, ResourceValidator validator, + PathResolverCache cache) { this.config = config; this.validator = validator; this.cache = cache; - } + } public String getName() - { + { return name; } - + public String getBasePath() { return basePath.toString(); } - - public String getBasePath( String relativePath ) + + public String getBasePath(String relativePath) { - if ( relativePath == null ) - { - return basePath.toString(); - } - return basePath.addSegment( relativePath ).toString(); + if (relativePath == null) { return basePath.toString(); } + return basePath.addSegment(relativePath).toString(); } - - public String getResource( String path ) - { - Path workingPath = baseClientPath.getChild( path ); - - String hit = cache.getPath( workingPath.toString()); - if( hit != null ) + + public String getResource(String path) + { + Path workingPath = baseClientPath.getChild(path); + + String hit = cache.getPath(workingPath.toString()); + if (hit != null) { return hit; } else { - String locatedPath = getResource( baseClientPath, new Path( path ) ); - if( ! locatedPath.startsWith( NO_SUCH_RESOURCE ) ) + String locatedPath = getResource(baseClientPath, new Path(path)); + if (!locatedPath.startsWith(NO_SUCH_RESOURCE)) { - if( ! path.startsWith( "/" ) ) + if (!path.startsWith("/")) { - locatedPath = locatedPath.substring( 1 ); + locatedPath = locatedPath.substring(1); } - cache.addPath( workingPath.toString(), locatedPath ); + cache.addPath(workingPath.toString(), locatedPath); return locatedPath; } } - return null; + return null; } - + /** * Recursively tries to locate a resource. * - * @param rootPath initial path to start looking for the searchPath. - * The "pruning" of the rootPath of subsequest recursive calls follows the logic - * detailed in the {@link Decoration#getResource(String)} method. - * @param searchPath relative path to the resource we wish to locate. + * @param rootPath + * initial path to start looking for the searchPath. + * The "pruning" of the rootPath of subsequest recursive calls + * follows the logic detailed in the + * {@link Decoration#getResource(String)} method. + * @param searchPath + * relative path to the resource we wish to locate. * @return * * @see Decoration */ - protected String getResource( Path rootPath, Path searchPath ) + protected String getResource(Path rootPath, Path searchPath) { - String pathString = rootPath.getChild( searchPath ).toString(); - if( validator.resourceExists( pathString ) ) + String pathString = rootPath.getChild(searchPath).toString(); + if (validator.resourceExists(pathString)) { return pathString; } - else if( rootPath.length() > 0 ) + else if (rootPath.length() > 0) { - - return getResource( rootPath.removeLastPathSegment(), searchPath ); + + return getResource(rootPath.removeLastPathSegment(), searchPath); } else { @@ -186,61 +211,55 @@ public String getStyleSheet() { - if ( this.commonStylesheet != null ) - { - return getResource( this.commonStylesheet ); - } + if (this.commonStylesheet != null) { return getResource(this.commonStylesheet); } return null; } + public String getStyleSheetPortal() { - if ( this.portalStylesheet != null ) - { - return getResource( this.portalStylesheet ); - } + if (this.portalStylesheet != null) { return getResource(this.portalStylesheet); } return null; } + public String getStyleSheetDesktop() { - if ( this.desktopStylesheet != null ) - { - return getResource( this.desktopStylesheet ); - } + if (this.desktopStylesheet != null) { return getResource(this.desktopStylesheet); } return null; } public List getActions() { - if(actions != null) - { - return actions; - } - else - { - return Collections.EMPTY_LIST; - } + if (actions != null) + { + return actions; + } + else + { + return Collections.EMPTY_LIST; + } } - public void setActions( List actions ) + public void setActions(List actions) { this.actions = actions; } - public String getProperty( String name ) + public String getProperty(String name) { - return config.getProperty( name ); + return config.getProperty(name); } public String getBaseCSSClass() { - return config.getProperty( Decoration.BASE_CSS_CLASS_PROP, getName() ); + return config.getProperty(Decoration.BASE_CSS_CLASS_PROP, getName()); } public String getCurrentModeAction() { return this.currentModeAction; } - public void setCurrentModeAction( String currentModeAction ) + + public void setCurrentModeAction(String currentModeAction) { this.currentModeAction = currentModeAction; } @@ -249,46 +268,45 @@ { return this.currentStateAction; } - public void setCurrentStateAction( String currentStateAction ) + + public void setCurrentStateAction(String currentStateAction) { this.currentStateAction = currentStateAction; } - + public String getResourceBundleName() { - return config.getProperty( Decoration.RESOURCE_BUNDLE_PROP ); + return config.getProperty(Decoration.RESOURCE_BUNDLE_PROP); } - - public ResourceBundle getResourceBundle( Locale locale, org.apache.jetspeed.request.RequestContext context ) + + public ResourceBundle getResourceBundle(Locale locale, + org.apache.jetspeed.request.RequestContext context) { String resourceDirName = context.getConfig().getServletContext() - .getRealPath( getResource( RESOURCES_DIRECTORY_NAME ) ); - File resourceDir = new File( resourceDirName ); + .getRealPath(getResource(RESOURCES_DIRECTORY_NAME)); + File resourceDir = new File(resourceDirName); String resourceName = getResourceBundleName(); - if ( resourceName == null ) - { - throw new NullPointerException( "Decoration cannot get ResourceBundle due to null value for decoration property " + Decoration.RESOURCE_BUNDLE_PROP + "." ); - } - if ( !resourceDir.isDirectory() ) - { - throw new MissingResourceException( - "Can't find the resource directory: " + resourceDirName, - resourceName + "_" + locale, "" ); - } + if (resourceName == null) { throw new NullPointerException( + "Decoration cannot get ResourceBundle due to null value for decoration property " + + Decoration.RESOURCE_BUNDLE_PROP + "."); } + if (!resourceDir.isDirectory()) { throw new MissingResourceException( + "Can't find the resource directory: " + resourceDirName, + resourceName + "_" + locale, ""); } URL[] urls = new URL[1]; try { urls[0] = resourceDir.toURL(); } - catch ( MalformedURLException e ) + catch (MalformedURLException e) { throw new MissingResourceException( "The resource directory cannot be parsed as a URL: " + resourceDirName, resourceName + "_" + locale, ""); } - return ResourceBundle.getBundle( resourceName, locale, new URLClassLoader( urls ) ); + return ResourceBundle.getBundle(resourceName, locale, + new URLClassLoader(urls)); } - + public boolean supportsDesktop() { return this.supportsDesktop; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/CustomDecoratorActionsFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/CustomDecoratorActionsFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/CustomDecoratorActionsFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.decoration; import java.util.ArrayList; @@ -26,71 +26,93 @@ import org.apache.jetspeed.JetspeedActions; import org.apache.jetspeed.om.common.portlet.PortletApplication; import org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite; +import org.apache.jetspeed.om.page.ContentFragment; import org.apache.jetspeed.om.page.ContentPage; -import org.apache.jetspeed.om.page.ContentFragment; import org.apache.jetspeed.request.RequestContext; import org.apache.jetspeed.security.SecurityAccessController; import org.apache.pluto.om.window.PortletWindow; -public class CustomDecoratorActionsFactory extends AbstractDecoratorActionsFactory +public class CustomDecoratorActionsFactory extends + AbstractDecoratorActionsFactory { - private static final DecoratorActionTemplate ABOUT_MODE_TEMPLATE = new DecoratorActionTemplate(JetspeedActions.ABOUT_MODE); - private static final DecoratorActionTemplate CONFIG_MODE_TEMPLATE = new DecoratorActionTemplate(JetspeedActions.CONFIG_MODE); - private static final DecoratorActionTemplate EDIT_DEFAULTS_MODE_TEMPLATE = new DecoratorActionTemplate(JetspeedActions.EDIT_DEFAULTS_MODE); - //private static final DecoratorActionTemplate PREVIEW_MODE_TEMPLATE = new DecoratorActionTemplate(JetspeedActions.PREVIEW_MODE); - private static final DecoratorActionTemplate PRINT_MODE_TEMPLATE = new DecoratorActionTemplate(JetspeedActions.PRINT_MODE); - private static final DecoratorActionTemplate SOLO_ACTION_TEMPLATE = new DecoratorActionTemplate(JetspeedActions.SOLO_STATE); - + + private static final DecoratorActionTemplate ABOUT_MODE_TEMPLATE = new DecoratorActionTemplate( + JetspeedActions.ABOUT_MODE); + + private static final DecoratorActionTemplate CONFIG_MODE_TEMPLATE = new DecoratorActionTemplate( + JetspeedActions.CONFIG_MODE); + + private static final DecoratorActionTemplate EDIT_DEFAULTS_MODE_TEMPLATE = new DecoratorActionTemplate( + JetspeedActions.EDIT_DEFAULTS_MODE); + + // private static final DecoratorActionTemplate PREVIEW_MODE_TEMPLATE = new + // DecoratorActionTemplate(JetspeedActions.PREVIEW_MODE); + private static final DecoratorActionTemplate PRINT_MODE_TEMPLATE = new DecoratorActionTemplate( + JetspeedActions.PRINT_MODE); + + private static final DecoratorActionTemplate SOLO_ACTION_TEMPLATE = new DecoratorActionTemplate( + JetspeedActions.SOLO_STATE); + private final List supportedActions; + private final List supportedSoloActions; - + public CustomDecoratorActionsFactory() { - ArrayList list = new ArrayList(JetspeedActions.getStandardPortletModes()); + ArrayList list = new ArrayList(JetspeedActions + .getStandardPortletModes()); list.add(JetspeedActions.ABOUT_MODE); list.add(JetspeedActions.CONFIG_MODE); list.add(JetspeedActions.EDIT_DEFAULTS_MODE); - //list.add(JetspeedActions.PREVIEW_MODE); + // list.add(JetspeedActions.PREVIEW_MODE); list.add(JetspeedActions.PRINT_MODE); list.addAll(JetspeedActions.getStandardWindowStates()); list.add(JetspeedActions.SOLO_STATE); supportedActions = Collections.unmodifiableList(list); - + list = new ArrayList(JetspeedActions.getStandardPortletModes()); list.add(JetspeedActions.PRINT_MODE); supportedSoloActions = Collections.unmodifiableList(list); } - public List getSupportedActions(RequestContext rc, PortletApplication pa, PortletWindow pw, PortletMode cm, - WindowState ws, Decoration decoration) + public List getSupportedActions(RequestContext rc, PortletApplication pa, + PortletWindow pw, PortletMode cm, WindowState ws, + Decoration decoration) { // don't support any window state actions when in "solo" state - return JetspeedActions.SOLO_STATE.equals(ws) ? supportedSoloActions : supportedActions; + return JetspeedActions.SOLO_STATE.equals(ws) ? supportedSoloActions + : supportedActions; } - - public List getDecoratorActions(RequestContext rc, PortletApplication pa, PortletWindow pw, PortletMode pm, - WindowState ws, Decoration decoration, List actionTemplates, - PortletDefinitionComposite portlet, ContentFragment fragment, SecurityAccessController accessController) + + public List getDecoratorActions(RequestContext rc, PortletApplication pa, + PortletWindow pw, PortletMode pm, WindowState ws, + Decoration decoration, List actionTemplates, + PortletDefinitionComposite portlet, ContentFragment fragment, + SecurityAccessController accessController) { int printModeIndex = actionTemplates.indexOf(PRINT_MODE_TEMPLATE); int soloStateIndex = actionTemplates.indexOf(SOLO_ACTION_TEMPLATE); - - if ( printModeIndex != -1 && soloStateIndex != -1 ) + + if (printModeIndex != -1 && soloStateIndex != -1) { // merge "solo" state with "print" mode - DecoratorActionTemplate soloStateTemplate = (DecoratorActionTemplate)actionTemplates.remove(soloStateIndex); - DecoratorActionTemplate printActionTemplate = (DecoratorActionTemplate)actionTemplates.get(printModeIndex); + DecoratorActionTemplate soloStateTemplate = (DecoratorActionTemplate) actionTemplates + .remove(soloStateIndex); + DecoratorActionTemplate printActionTemplate = (DecoratorActionTemplate) actionTemplates + .get(printModeIndex); printActionTemplate.setState(soloStateTemplate.getState()); - printActionTemplate.setCustomState((soloStateTemplate.getCustomState())); + printActionTemplate.setCustomState((soloStateTemplate + .getCustomState())); } - else if ( soloStateIndex != -1 ) + else if (soloStateIndex != -1) { // don't provide "solo" action separately without "print" mode actionTemplates.remove(soloStateIndex); } // else if (printModeIndex != -1) - // support switching to different modes once in "solo" state, even back to "print" - + // support switching to different modes once in "solo" state, even back + // to "print" + int configModeIndex = actionTemplates.indexOf(CONFIG_MODE_TEMPLATE); if (configModeIndex != -1) { @@ -104,8 +126,9 @@ actionTemplates.remove(configModeIndex); } } - - int editDefaultsModeIndex = actionTemplates.indexOf(EDIT_DEFAULTS_MODE_TEMPLATE); + + int editDefaultsModeIndex = actionTemplates + .indexOf(EDIT_DEFAULTS_MODE_TEMPLATE); if (editDefaultsModeIndex != -1) { try @@ -118,15 +141,18 @@ actionTemplates.remove(editDefaultsModeIndex); } } - - return super.getDecoratorActions(rc,pa,pw,pm,ws,decoration,actionTemplates, portlet, fragment, accessController); + + return super.getDecoratorActions(rc, pa, pw, pm, ws, decoration, + actionTemplates, portlet, fragment, accessController); } - - protected DecoratorAction createAction(RequestContext rc, PortletWindow pw, Decoration decoration, - DecoratorActionTemplate template) + + protected DecoratorAction createAction(RequestContext rc, PortletWindow pw, + Decoration decoration, DecoratorActionTemplate template) { - DecoratorAction action = super.createAction(rc,pw,decoration,template); - if ( template.getState() != null && JetspeedActions.SOLO_STATE.equals(template.getState())) + DecoratorAction action = super.createAction(rc, pw, decoration, + template); + if (template.getState() != null + && JetspeedActions.SOLO_STATE.equals(template.getState())) { // "solo" opens in a new popup winodw action.setTarget("_blank"); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecorationFactoryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecorationFactoryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecorationFactoryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,166 +37,204 @@ import org.apache.jetspeed.cache.JetspeedCache; import org.apache.jetspeed.components.portletregistry.PortletRegistry; import org.apache.jetspeed.decoration.caches.SessionPathResolverCache; +import org.apache.jetspeed.desktop.JetspeedDesktop; import org.apache.jetspeed.om.common.portlet.MutablePortletApplication; import org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite; import org.apache.jetspeed.om.page.Fragment; import org.apache.jetspeed.om.page.Page; import org.apache.jetspeed.request.RequestContext; import org.apache.jetspeed.util.Path; -import org.apache.jetspeed.desktop.JetspeedDesktop; import org.springframework.web.context.ServletContextAware; /** - * + * * @author Scott T. Weaver * @author Steve Milek * @see org.apache.jetspeed.decoration.DecorationFactory */ -public class DecorationFactoryImpl implements DecorationFactory, ServletContextAware +public class DecorationFactoryImpl implements DecorationFactory, + ServletContextAware { - private static final Log log = LogFactory.getLog(DecorationFactoryImpl.class); + private static final Log log = LogFactory + .getLog(DecorationFactoryImpl.class); + private final Path decorationsPath; + private final Path portletDecorationsPath; + private final Path layoutDecorationsPath; + private final String portletDecorationsPathStr; + private final String layoutDecorationsPathStr; - + private final ResourceValidator validator; + private final PortletRegistry registry; - - /** cache to hold decoration Properties objects **/ + + /** cache to hold decoration Properties objects * */ private JetspeedCache decorationConfigurationCache; - + private ServletContext servletContext; private String defaultDesktopLayoutDecoration = null; + private String defaultDesktopPortletDecoration = null; - + private Set layoutDecorationsDir = Collections.EMPTY_SET; + private Set portletDecorationsDir = Collections.EMPTY_SET; + private Set desktopLayoutDecorationsDir = Collections.EMPTY_SET; + private Set desktopPortletDecorationsDir = Collections.EMPTY_SET; - + private Set layoutDecorationsList = Collections.EMPTY_SET; + private Set portletDecorationsList = Collections.EMPTY_SET; + private Set desktopLayoutDecorationsList = Collections.EMPTY_SET; + private Set desktopPortletDecorationsList = Collections.EMPTY_SET; - + private Map portletDecoratorProperties = new HashMap(); + private Map layoutDecoratorProperties = new HashMap(); - public DecorationFactoryImpl( String decorationsPath, - ResourceValidator validator ) + public DecorationFactoryImpl(String decorationsPath, + ResourceValidator validator) { - this( null, decorationsPath, validator, null ); + this(null, decorationsPath, validator, null); } - - public DecorationFactoryImpl( String decorationsPath, - ResourceValidator validator, - JetspeedCache decorationConfigurationCache ) + + public DecorationFactoryImpl(String decorationsPath, + ResourceValidator validator, + JetspeedCache decorationConfigurationCache) { - this( null, decorationsPath, validator, decorationConfigurationCache ); + this(null, decorationsPath, validator, decorationConfigurationCache); } - public DecorationFactoryImpl( PortletRegistry registry, - String decorationsPath, - ResourceValidator validator, - JetspeedCache decorationConfigurationCache ) + public DecorationFactoryImpl(PortletRegistry registry, + String decorationsPath, ResourceValidator validator, + JetspeedCache decorationConfigurationCache) { - this.registry = registry; - this.decorationsPath = new Path( decorationsPath ); - this.layoutDecorationsPath = getBasePath( Fragment.LAYOUT ); + this.registry = registry; + this.decorationsPath = new Path(decorationsPath); + this.layoutDecorationsPath = getBasePath(Fragment.LAYOUT); this.layoutDecorationsPathStr = this.layoutDecorationsPath.toString(); - this.portletDecorationsPath = getBasePath( Fragment.PORTLET ); + this.portletDecorationsPath = getBasePath(Fragment.PORTLET); this.portletDecorationsPathStr = this.portletDecorationsPath.toString(); this.validator = validator; this.decorationConfigurationCache = decorationConfigurationCache; } - + public ResourceValidator getResourceValidator() { return validator; } - + protected JetspeedCache getDecorationConfigurationCache() { - return decorationConfigurationCache; + return decorationConfigurationCache; } - public Theme getTheme( Page page, RequestContext requestContext ) + public Theme getTheme(Page page, RequestContext requestContext) { return new PageTheme(page, this, requestContext); } - - public Decoration getDecoration( Page page, Fragment fragment, RequestContext requestContext ) + + public Decoration getDecoration(Page page, Fragment fragment, + RequestContext requestContext) { - String decorationName = getDefaultDecorationName( fragment, page ); + String decorationName = getDefaultDecorationName(fragment, page); Decoration decoration; // use layout decoration for top level layout root fragments - // and use portlet decoration for all other fragments - boolean isLayout = fragment.getType().equals( Fragment.LAYOUT ); - if ( isLayout ) + // and use portlet decoration for all other fragments + boolean isLayout = fragment.getType().equals(Fragment.LAYOUT); + if (isLayout) { - decoration = getLayoutDecoration( decorationName, requestContext ); + decoration = getLayoutDecoration(decorationName, requestContext); } else { - decoration = getPortletDecoration( decorationName, requestContext ); + decoration = getPortletDecoration(decorationName, requestContext); } - if ( isDesktopEnabled( requestContext ) ) - { // assure that selected decoration supports /desktop - // otherwise get default desktop decoration for fragment type - if ( decoration == null || ! decoration.supportsDesktop() ) + if (isDesktopEnabled(requestContext)) + { // assure that selected decoration supports /desktop + // otherwise get default desktop decoration for fragment type + if (decoration == null || !decoration.supportsDesktop()) { String defaultDecoration = null; - if ( isLayout ) + if (isLayout) { - if ( decoration == null || fragment.equals( page.getRootFragment() ) ) - { - defaultDecoration = getDefaultDesktopLayoutDecoration(); - decoration = getLayoutDecoration( defaultDecoration, requestContext ); - } + if (decoration == null + || fragment.equals(page.getRootFragment())) + { + defaultDecoration = getDefaultDesktopLayoutDecoration(); + decoration = getLayoutDecoration(defaultDecoration, + requestContext); + } } else { defaultDecoration = getDefaultDesktopPortletDecoration(); - decoration = getPortletDecoration( defaultDecoration, requestContext ); + decoration = getPortletDecoration(defaultDecoration, + requestContext); } - if ( decoration == null ) + if (decoration == null) { - String errMsg = "Cannot locate default desktop " + fragment.getType() + " decoration " + ( defaultDecoration == null ? "null" : ("\"" + defaultDecoration + "\"") ) + " (decoration " + ( defaultDecoration == null ? "null" : ("\"" + decorationName + "\"") ) + " specified for page could either not be located or does not support desktop). No desktop compatible " + fragment.getType() + " decoration is available."; - log.error( errMsg ); + String errMsg = "Cannot locate default desktop " + + fragment.getType() + + " decoration " + + (defaultDecoration == null ? "null" : ("\"" + + defaultDecoration + "\"")) + + " (decoration " + + (defaultDecoration == null ? "null" : ("\"" + + decorationName + "\"")) + + " specified for page could either not be located or does not support desktop). No desktop compatible " + + fragment.getType() + " decoration is available."; + log.error(errMsg); } } } return decoration; } - public PortletDecoration getPortletDecoration( String name, RequestContext requestContext ) + public PortletDecoration getPortletDecoration(String name, + RequestContext requestContext) { - Path basePath = getPortletDecorationBasePath( name ); - Path baseClientPath = createClientPath( name, basePath, requestContext, Fragment.PORTLET ); - Properties configuration = getConfiguration( name, Fragment.PORTLET ); - SessionPathResolverCache sessionPathResolver = new SessionPathResolverCache( requestContext.getRequest().getSession() ); - return new PortletDecorationImpl( configuration, validator, basePath, baseClientPath, sessionPathResolver ); + Path basePath = getPortletDecorationBasePath(name); + Path baseClientPath = createClientPath(name, basePath, requestContext, + Fragment.PORTLET); + Properties configuration = getConfiguration(name, Fragment.PORTLET); + SessionPathResolverCache sessionPathResolver = new SessionPathResolverCache( + requestContext.getRequest().getSession()); + return new PortletDecorationImpl(configuration, validator, basePath, + baseClientPath, sessionPathResolver); } - public LayoutDecoration getLayoutDecoration( String name, RequestContext requestContext ) + public LayoutDecoration getLayoutDecoration(String name, + RequestContext requestContext) { - Path basePath = getLayoutDecorationBasePath( name ); - Path baseClientPath = createClientPath( name, basePath, requestContext, Fragment.LAYOUT ); - Properties configuration = getConfiguration( name, Fragment.LAYOUT ); - SessionPathResolverCache sessionPathResolver = new SessionPathResolverCache( requestContext.getRequest().getSession() ); - return new LayoutDecorationImpl( configuration, validator, basePath, baseClientPath, sessionPathResolver ); - } - - public boolean isDesktopEnabled( RequestContext requestContext ) + Path basePath = getLayoutDecorationBasePath(name); + Path baseClientPath = createClientPath(name, basePath, requestContext, + Fragment.LAYOUT); + Properties configuration = getConfiguration(name, Fragment.LAYOUT); + SessionPathResolverCache sessionPathResolver = new SessionPathResolverCache( + requestContext.getRequest().getSession()); + return new LayoutDecorationImpl(configuration, validator, basePath, + baseClientPath, sessionPathResolver); + } + + public boolean isDesktopEnabled(RequestContext requestContext) { - Boolean desktopEnabled = (Boolean)requestContext.getAttribute( JetspeedDesktop.DESKTOP_ENABLED_REQUEST_ATTRIBUTE ); - return ( desktopEnabled != null && desktopEnabled.booleanValue() ? true : false ); + Boolean desktopEnabled = (Boolean) requestContext + .getAttribute(JetspeedDesktop.DESKTOP_ENABLED_REQUEST_ATTRIBUTE); + return (desktopEnabled != null && desktopEnabled.booleanValue() ? true + : false); } public void setServletContext(ServletContext servletContext) @@ -205,91 +243,103 @@ } - protected Properties getCachedConfiguration( String name, String type ) + protected Properties getCachedConfiguration(String name, String type) { - if ( decorationConfigurationCache == null ) - { - if ( type.equals( Fragment.PORTLET ) ) - { - return (Properties)this.portletDecoratorProperties.get( name ); - } - else - { - return (Properties)this.layoutDecoratorProperties.get( name ); - } - } - CacheElement cachedElement = decorationConfigurationCache.get( getCachedConfigurationKey( type, name ) ); + if (decorationConfigurationCache == null) + { + if (type.equals(Fragment.PORTLET)) + { + return (Properties) this.portletDecoratorProperties.get(name); + } + else + { + return (Properties) this.layoutDecoratorProperties.get(name); + } + } + CacheElement cachedElement = decorationConfigurationCache + .get(getCachedConfigurationKey(type, name)); if (cachedElement != null) - return (Properties)cachedElement.getContent(); + return (Properties) cachedElement.getContent(); return null; } - protected void setCachedConfiguration( String name, String type, Properties props ) + + protected void setCachedConfiguration(String name, String type, + Properties props) { - if ( decorationConfigurationCache == null ) - { - if ( type.equals( Fragment.PORTLET ) ) - { - this.portletDecoratorProperties.put( name, props ); - } - else - { - this.layoutDecoratorProperties.put( name, props ); - } - } - else - { - CacheElement cachedElement = decorationConfigurationCache.createElement( getCachedConfigurationKey( type, name ), props ); - cachedElement.setTimeToIdleSeconds(decorationConfigurationCache.getTimeToIdleSeconds()); - cachedElement.setTimeToLiveSeconds(decorationConfigurationCache.getTimeToLiveSeconds()); - decorationConfigurationCache.put( cachedElement ); - } + if (decorationConfigurationCache == null) + { + if (type.equals(Fragment.PORTLET)) + { + this.portletDecoratorProperties.put(name, props); + } + else + { + this.layoutDecoratorProperties.put(name, props); + } + } + else + { + CacheElement cachedElement = decorationConfigurationCache + .createElement(getCachedConfigurationKey(type, name), props); + cachedElement.setTimeToIdleSeconds(decorationConfigurationCache + .getTimeToIdleSeconds()); + cachedElement.setTimeToLiveSeconds(decorationConfigurationCache + .getTimeToLiveSeconds()); + decorationConfigurationCache.put(cachedElement); + } } - protected String getCachedConfigurationKey( String type, String name ) + + protected String getCachedConfigurationKey(String type, String name) { - return type + "." + name; + return type + "." + name; } - + /** * Gets the configuration (decorator.properties) object for the decoration. - * @param name Name of the Decoration. - * @return java.util.Properties representing the configuration - * object. + * + * @param name + * Name of the Decoration. + * @return java.util.Properties representing the + * configuration object. */ - public Properties getConfiguration( String name, String type ) + public Properties getConfiguration(String name, String type) { - Properties props = getCachedConfiguration( name, type ); - if ( props != null ) - { - return props; - } - + Properties props = getCachedConfiguration(name, type); + if (props != null) { return props; } + props = new Properties(); InputStream is = null; - + // load Decoration.CONFIG_FILE_NAME (decorator.properties) try { - is = servletContext.getResourceAsStream( decorationsPath + "/" + type + "/" + name + "/" + Decoration.CONFIG_FILE_NAME ); + is = servletContext.getResourceAsStream(decorationsPath + "/" + + type + "/" + name + "/" + Decoration.CONFIG_FILE_NAME); if (is != null) - { - props.load( is ); + { + props.load(is); } else { - log.warn( "Could not locate the " + Decoration.CONFIG_FILE_NAME + " configuration file for decoration \"" + name + "\". This decoration may not exist." ); - props.setProperty( "id", name ); - props.setProperty( "name", name ); + log.warn("Could not locate the " + Decoration.CONFIG_FILE_NAME + + " configuration file for decoration \"" + name + + "\". This decoration may not exist."); + props.setProperty("id", name); + props.setProperty("name", name); } } - catch ( Exception e ) + catch (Exception e) { - log.warn( "Failed to load the " + Decoration.CONFIG_FILE_NAME + " configuration file for decoration \"" + name + "\".", e ); - props.setProperty( "id", name ); - props.setProperty( "name", name ); + log + .warn("Failed to load the " + Decoration.CONFIG_FILE_NAME + + " configuration file for decoration \"" + name + + "\".", e); + props.setProperty("id", name); + props.setProperty("name", name); } finally { - if ( is != null ) + if (is != null) { try { @@ -300,11 +350,11 @@ log.warn("Failed to close decoration configuration.", e); } } - String decorationIdPropVal = props.getProperty( "id" ); - String decorationNamePropVal = props.getProperty( "name" ); - if ( decorationIdPropVal == null ) + String decorationIdPropVal = props.getProperty("id"); + String decorationNamePropVal = props.getProperty("name"); + if (decorationIdPropVal == null) { - if ( decorationNamePropVal != null ) + if (decorationNamePropVal != null) { decorationIdPropVal = decorationNamePropVal; } @@ -312,109 +362,130 @@ { decorationIdPropVal = name; } - props.setProperty( "id", decorationIdPropVal ); + props.setProperty("id", decorationIdPropVal); } - - if ( decorationNamePropVal == null ) + + if (decorationNamePropVal == null) { - props.setProperty( "name", decorationIdPropVal ); + props.setProperty("name", decorationIdPropVal); } } - - // load Decoration.CONFIG_DESKTOP_FILE_NAME (decoratordesktop.properties) + + // load Decoration.CONFIG_DESKTOP_FILE_NAME + // (decoratordesktop.properties) try { - is = servletContext.getResourceAsStream( decorationsPath + "/" + type + "/" + name + "/" + Decoration.CONFIG_DESKTOP_FILE_NAME ); - if ( is != null ) - { - props.load( is ); - if ( props.getProperty( Decoration.DESKTOP_SUPPORTED_PROPERTY ) == null ) + is = servletContext.getResourceAsStream(decorationsPath + "/" + + type + "/" + name + "/" + + Decoration.CONFIG_DESKTOP_FILE_NAME); + if (is != null) + { + props.load(is); + if (props.getProperty(Decoration.DESKTOP_SUPPORTED_PROPERTY) == null) { - props.setProperty( Decoration.DESKTOP_SUPPORTED_PROPERTY, "true" ); + props.setProperty(Decoration.DESKTOP_SUPPORTED_PROPERTY, + "true"); } } else { - log.debug( "Could not locate the " + Decoration.CONFIG_DESKTOP_FILE_NAME + " configuration file for decoration \"" + name + "\". This decoration may not exist." ); + log.debug("Could not locate the " + + Decoration.CONFIG_DESKTOP_FILE_NAME + + " configuration file for decoration \"" + name + + "\". This decoration may not exist."); } } - catch ( Exception e ) + catch (Exception e) { - log.warn( "Failed to load the " + Decoration.CONFIG_DESKTOP_FILE_NAME + " configuration file for decoration \"" + name + "\".", e ); + log + .warn("Failed to load the " + + Decoration.CONFIG_DESKTOP_FILE_NAME + + " configuration file for decoration \"" + name + + "\".", e); } finally { - if ( is != null ) + if (is != null) { try { is.close(); } - catch ( IOException e ) + catch (IOException e) { - log.warn( "Failed to close decoration desktop configuration.", e ); + log + .warn( + "Failed to close decoration desktop configuration.", + e); } } - if ( props.getProperty( Decoration.DESKTOP_SUPPORTED_PROPERTY ) == null ) + if (props.getProperty(Decoration.DESKTOP_SUPPORTED_PROPERTY) == null) { - props.setProperty( Decoration.DESKTOP_SUPPORTED_PROPERTY, "false" ); + props.setProperty(Decoration.DESKTOP_SUPPORTED_PROPERTY, + "false"); } } - - setCachedConfiguration( name, type, props ); - + + setCachedConfiguration(name, type, props); + return props; } - + /** - * Creates a org.apache.jetspeed.util.Path object based - * off of the user's client browser and locale. - * - * @param name Decroator's name - * @param requestContext Current portal request. - * @param decorationType Type of decoration, either layout - * or portlet + * Creates a org.apache.jetspeed.util.Path object based off + * of the user's client browser and locale. + * + * @param name + * Decroator's name + * @param requestContext + * Current portal request. + * @param decorationType + * Type of decoration, either layout or + * portlet * @return - * + * * @see Path * @see RequestContext */ - protected Path createClientPath( String name, RequestContext requestContext, String decorationType ) + protected Path createClientPath(String name, RequestContext requestContext, + String decorationType) { - return createClientPath( name, null, requestContext, decorationType ); - } - - private Path createClientPath( String name, Path basePath, RequestContext requestContext, String decorationType ) + return createClientPath(name, null, requestContext, decorationType); + } + + private Path createClientPath(String name, Path basePath, + RequestContext requestContext, String decorationType) { - if ( basePath == null ) - basePath = getBasePath( name, decorationType ); + if (basePath == null) basePath = getBasePath(name, decorationType); String mediaType = requestContext.getMediaType(); Locale locale = requestContext.getLocale(); String language = locale.getLanguage(); String country = locale.getCountry(); String variant = locale.getVariant(); - basePath = basePath.addSegment( mediaType ).addSegment( language ); + basePath = basePath.addSegment(mediaType).addSegment(language); - if ( country != null ) + if (country != null) { - basePath = basePath.addSegment( country ); + basePath = basePath.addSegment(country); } if (variant != null) { - basePath = basePath.addSegment( variant ); + basePath = basePath.addSegment(variant); } return basePath; } /** * Returns a the default decoration name for the specific Fragment type. - * - * @param fragment Fragment whose default decroation has been requested - * @param page Page this fragment belongs to. + * + * @param fragment + * Fragment whose default decroation has been requested + * @param page + * Page this fragment belongs to. * @return Default decorator name. - * + * * @see Page * @see Fragment */ @@ -429,7 +500,8 @@ if (fragment.equals(page.getRootFragment())) { // use page specified layout decorator name - decoration = page.getEffectiveDefaultDecorator(Fragment.LAYOUT); + decoration = page + .getEffectiveDefaultDecorator(Fragment.LAYOUT); } else { @@ -440,7 +512,8 @@ else { // use page specified default portlet decorator name - decoration = page.getEffectiveDefaultDecorator(Fragment.PORTLET); + decoration = page + .getEffectiveDefaultDecorator(Fragment.PORTLET); } } @@ -449,33 +522,35 @@ public void clearCache(RequestContext requestContext) { - new SessionPathResolverCache(requestContext.getRequest().getSession()).clear(); + new SessionPathResolverCache(requestContext.getRequest().getSession()) + .clear(); } - protected Path getBasePath( String decorationType ) + protected Path getBasePath(String decorationType) { return decorationsPath.addSegment(decorationType); } - - protected Path getBasePath( String name, String decorationType ) + + protected Path getBasePath(String name, String decorationType) { return decorationsPath.addSegment(decorationType).addSegment(name); } - - protected Path getLayoutDecorationBasePath( String name ) + + protected Path getLayoutDecorationBasePath(String name) { return layoutDecorationsPath.addSegment(name); } - protected Path getPortletDecorationBasePath( String name ) + + protected Path getPortletDecorationBasePath(String name) { return portletDecorationsPath.addSegment(name); } - + public String getLayoutDecorationsBasePath() { return this.layoutDecorationsPathStr; } - + public String getPortletDecorationsBasePath() { return this.portletDecorationsPathStr; @@ -483,108 +558,122 @@ /** * Get the portal-wide list of page decorations. - * + * * @return A list of page decorations of type Decoration */ - public Set getPageDecorations( RequestContext request ) + public Set getPageDecorations(RequestContext request) { - Set decorations = servletContext.getResourcePaths( decorationsPath.toString() + "/layout" ); - if( ! layoutDecorationsDir.equals( decorations ) ) + Set decorations = servletContext.getResourcePaths(decorationsPath + .toString() + + "/layout"); + if (!layoutDecorationsDir.equals(decorations)) { - layoutDecorationsList = getListing( decorations, Decoration.CONFIG_FILE_NAME ); + layoutDecorationsList = getListing(decorations, + Decoration.CONFIG_FILE_NAME); layoutDecorationsDir = decorations; - + } return layoutDecorationsList; } - + /** * Get the portal-wide list of available desktop page decorations. * * @return A list of desktop skins of type String - */ - public Set getDesktopPageDecorations( RequestContext request ) + */ + public Set getDesktopPageDecorations(RequestContext request) { - Set decorations = servletContext.getResourcePaths( decorationsPath.toString() + "/layout" ); - if( ! desktopLayoutDecorationsDir.equals( decorations ) ) + Set decorations = servletContext.getResourcePaths(decorationsPath + .toString() + + "/layout"); + if (!desktopLayoutDecorationsDir.equals(decorations)) { - desktopLayoutDecorationsList = getListing( decorations, Decoration.CONFIG_DESKTOP_FILE_NAME ); + desktopLayoutDecorationsList = getListing(decorations, + Decoration.CONFIG_DESKTOP_FILE_NAME); desktopLayoutDecorationsDir = decorations; - + } return desktopLayoutDecorationsList; } /** * Get the portal-wide list of portlet decorations. - * + * * @return A list of portlet decorations of type String */ - public Set getPortletDecorations( RequestContext request ) + public Set getPortletDecorations(RequestContext request) { - Set decorations = servletContext.getResourcePaths( decorationsPath.toString() + "/portlet" ); - if( ! portletDecorationsDir.equals( decorations ) ) + Set decorations = servletContext.getResourcePaths(decorationsPath + .toString() + + "/portlet"); + if (!portletDecorationsDir.equals(decorations)) { - portletDecorationsList = getListing( decorations, Decoration.CONFIG_FILE_NAME ); + portletDecorationsList = getListing(decorations, + Decoration.CONFIG_FILE_NAME); portletDecorationsDir = decorations; - + } return portletDecorationsList; } - + /** * Get the portal-wide list of desktop portlet decorations. - * + * * @return A list of portlet decorations of type String */ - public Set getDesktopPortletDecorations( RequestContext request ) + public Set getDesktopPortletDecorations(RequestContext request) { - Set decorations = servletContext.getResourcePaths( decorationsPath.toString() + "/portlet" ); - if( ! desktopPortletDecorationsDir.equals( decorations ) ) + Set decorations = servletContext.getResourcePaths(decorationsPath + .toString() + + "/portlet"); + if (!desktopPortletDecorationsDir.equals(decorations)) { - desktopPortletDecorationsList = getListing( decorations, Decoration.CONFIG_DESKTOP_FILE_NAME ); + desktopPortletDecorationsList = getListing(decorations, + Decoration.CONFIG_DESKTOP_FILE_NAME); desktopPortletDecorationsDir = decorations; - + } return desktopPortletDecorationsList; } - + /** * Get the portal-wide list of available layouts. - * - * @return A list of layout portlets of type PortletDefinitionComposite + * + * @return A list of layout portlets of type + * PortletDefinitionComposite */ - public List getLayouts( RequestContext request ) + public List getLayouts(RequestContext request) { List list = new LinkedList(); Iterator portlets = registry.getAllPortletDefinitions().iterator(); - while ( portlets.hasNext() ) + while (portlets.hasNext()) { - PortletDefinitionComposite portlet = (PortletDefinitionComposite)portlets.next(); - MutablePortletApplication muta = (MutablePortletApplication)portlet.getPortletApplicationDefinition(); + PortletDefinitionComposite portlet = (PortletDefinitionComposite) portlets + .next(); + MutablePortletApplication muta = (MutablePortletApplication) portlet + .getPortletApplicationDefinition(); String appName = muta.getName(); - if ( appName == null ) - continue; - if ( ! appName.equals( "jetspeed-layouts" ) ) - continue; + if (appName == null) continue; + if (!appName.equals("jetspeed-layouts")) continue; String uniqueName = appName + "::" + portlet.getName(); - list.add( new LayoutInfoImpl( uniqueName, - portlet.getDisplayNameText( request.getLocale() ), - portlet.getDescriptionText( request.getLocale() ) ) ); + list.add(new LayoutInfoImpl(uniqueName, portlet + .getDisplayNameText(request.getLocale()), portlet + .getDescriptionText(request.getLocale()))); } return list; } - + protected Set getListing(Set rawList, String propsFile) { Iterator itr = rawList.iterator(); Set filteredList = new HashSet(); - while(itr.hasNext()) + while (itr.hasNext()) { Path path = new Path((String) itr.next()); - if(path.getFileName() == null && validator.resourceExists(path.toString() + propsFile)) + if (path.getFileName() == null + && validator.resourceExists(path.toString() + propsFile)) { int offset = path.length() - 1; filteredList.add(path.getSegment(offset)); @@ -595,28 +684,31 @@ public String getDefaultDesktopLayoutDecoration() { - synchronized ( this ) + synchronized (this) { return this.defaultDesktopLayoutDecoration; } } - public void setDefaultDesktopLayoutDecoration( String newOne ) + + public void setDefaultDesktopLayoutDecoration(String newOne) { - synchronized ( this ) + synchronized (this) { this.defaultDesktopLayoutDecoration = newOne; } } + public String getDefaultDesktopPortletDecoration() { - synchronized ( this ) + synchronized (this) { return this.defaultDesktopPortletDecoration; } } - public void setDefaultDesktopPortletDecoration( String newOne ) + + public void setDefaultDesktopPortletDecoration(String newOne) { - synchronized ( this ) + synchronized (this) { this.defaultDesktopPortletDecoration = newOne; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecorationValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecorationValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecorationValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -54,9 +54,9 @@ /** * Assigns decorations and page actions to all of the portlet Fragments within - * the current request. + * the current request. * - * @see org.apache.jetspeed.om.page.Fragment + * @see org.apache.jetspeed.om.page.Fragment * @see org.apache.jetspeed.om.page.Page * @see org.apache.jetspeed.decoration.Decoration * @see org.apache.jetspeed.decoration.LayoutDecoration @@ -65,96 +65,109 @@ * * @author Scott T. Weaver * @author Vivek Kumar - * + * */ public class DecorationValve extends AbstractValve implements Valve { + public static final String ACTION_IMAGE_EXTENSION_ATTR = "actionImageExtension"; + public static final String IS_AJAX_DECORATION_REQUEST = "org.apache.jetspeed.decoration.ajax"; - + protected final static Log log = LogFactory.getLog(DecorationValve.class); - + private final DecorationFactory decorationFactory; private final PortletWindowAccessor windowAccessor; - + private HashMap decoratorActionsAdapterCache = new HashMap(); - + private DecoratorActionsFactory defaultDecoratorActionsFactory; private JetspeedContentCache cache = null; - + private boolean useSessionForThemeCaching = false; - + private boolean maxOnEdit = false; - + private boolean maxOnConfig = false; - + private boolean maxOnEditDefaults = false; - + /** - * When edit_defaults mode is not supported by a portlet, support the mode automatically. + * When edit_defaults mode is not supported by a portlet, support the mode + * automatically. */ private boolean autoSwitchingForConfigMode = false; /** - * When edit_defaults mode is not supported by a portlet, support the mode automatically. + * When edit_defaults mode is not supported by a portlet, support the mode + * automatically. */ private boolean autoSwitchingToEditDefaultsModes = true; - - /** - * For security constraint checks - */ - protected SecurityAccessController accessController; - public DecorationValve(DecorationFactory decorationFactory, PortletWindowAccessor windowAccessor,SecurityAccessController accessController) - { - this(decorationFactory, windowAccessor, accessController, null); - } - - public DecorationValve(DecorationFactory decorationFactory, PortletWindowAccessor windowAccessor, - SecurityAccessController accessController, JetspeedContentCache cache) - { - this(decorationFactory, windowAccessor, accessController, cache, false); - } - - public DecorationValve(DecorationFactory decorationFactory, PortletWindowAccessor windowAccessor, - SecurityAccessController accessController, JetspeedContentCache cache, - boolean useSessionForThemeCaching) - { + /** + * For security constraint checks + */ + protected SecurityAccessController accessController; + + public DecorationValve(DecorationFactory decorationFactory, + PortletWindowAccessor windowAccessor, + SecurityAccessController accessController) + { + this(decorationFactory, windowAccessor, accessController, null); + } + + public DecorationValve(DecorationFactory decorationFactory, + PortletWindowAccessor windowAccessor, + SecurityAccessController accessController, + JetspeedContentCache cache) + { + this(decorationFactory, windowAccessor, accessController, cache, false); + } + + public DecorationValve(DecorationFactory decorationFactory, + PortletWindowAccessor windowAccessor, + SecurityAccessController accessController, + JetspeedContentCache cache, boolean useSessionForThemeCaching) + { this.decorationFactory = decorationFactory; this.windowAccessor = windowAccessor; - this.defaultDecoratorActionsFactory = new DefaultDecoratorActionsFactory(); - //added the accessController in portlet decorater for checking the actions - this.accessController = accessController; + this.defaultDecoratorActionsFactory = new DefaultDecoratorActionsFactory(); + // added the accessController in portlet decorater for checking the + // actions + this.accessController = accessController; this.cache = cache; this.useSessionForThemeCaching = useSessionForThemeCaching; } - - public void invoke(RequestContext requestContext, ValveContext context) throws PipelineException + + public void invoke(RequestContext requestContext, ValveContext context) + throws PipelineException { - //long start = System.currentTimeMillis(); - boolean isAjaxRequest = (context == null); - initFragments( requestContext, isAjaxRequest, null ); - //long end = System.currentTimeMillis(); - //System.out.println(end - start); + // long start = System.currentTimeMillis(); + boolean isAjaxRequest = (context == null); + initFragments(requestContext, isAjaxRequest, null); + // long end = System.currentTimeMillis(); + // System.out.println(end - start); if (!isAjaxRequest) { context.invokeNext(requestContext); } } - - public void initFragments( RequestContext requestContext, boolean isAjaxRequest, List fragments ) + public void initFragments(RequestContext requestContext, + boolean isAjaxRequest, List fragments) { if (isAjaxRequest) { - requestContext.setAttribute(IS_AJAX_DECORATION_REQUEST, new Boolean(true)); + requestContext.setAttribute(IS_AJAX_DECORATION_REQUEST, + new Boolean(true)); } ContentPage page = requestContext.getPage(); - // Globaly override all psml themes if override session attribute has been set + // Globaly override all psml themes if override session attribute has + // been set if (requestContext .getSessionAttribute(PortalReservedParameters.PAGE_THEME_OVERRIDE_ATTRIBUTE) != null) { @@ -162,27 +175,32 @@ .getSessionAttribute(PortalReservedParameters.PAGE_THEME_OVERRIDE_ATTRIBUTE); page.setDefaultDecorator(decoratorName, Fragment.LAYOUT); } - - PageActionAccess pageActionAccess = (PageActionAccess)requestContext.getAttribute(PortalReservedParameters.PAGE_EDIT_ACCESS_ATTRIBUTE); + + PageActionAccess pageActionAccess = (PageActionAccess) requestContext + .getAttribute(PortalReservedParameters.PAGE_EDIT_ACCESS_ATTRIBUTE); String themeCacheKey = null; ContentCacheKey themeContentCacheKey = null; Theme theme = null; - + if (useCache()) { if (pageActionAccess.isEditing() == false) { - // user helps us with the funky way jetspeed doesn't create a new session on login + // user helps us with the funky way jetspeed doesn't create a + // new session on login if (this.useSessionForThemeCaching) { themeCacheKey = cache.createSessionKey(requestContext); - theme = (Theme) requestContext.getSessionAttribute(themeCacheKey); + theme = (Theme) requestContext + .getSessionAttribute(themeCacheKey); } else { - themeContentCacheKey = cache.createCacheKey(requestContext, page.getId()); - CacheElement themeCacheElem = cache.get(themeContentCacheKey); - + themeContentCacheKey = cache.createCacheKey(requestContext, + page.getId()); + CacheElement themeCacheElem = cache + .get(themeContentCacheKey); + if (themeCacheElem != null) { theme = (Theme) themeCacheElem.getContent(); @@ -194,14 +212,17 @@ if (theme != null) { theme.init(page, decorationFactory, requestContext); - requestContext.setAttribute(PortalReservedParameters.PAGE_THEME_ATTRIBUTE, theme); - boolean solo = isSoloMode(requestContext); - SessionPathResolverCache sessionPathResolver = new SessionPathResolverCache( requestContext.getRequest().getSession() ); - initDepthFragmentDecorations(requestContext, theme, page.getRootContentFragment(), - pageActionAccess, isAjaxRequest, - ((DecorationFactoryImpl) decorationFactory).getResourceValidator(), - sessionPathResolver, (theme.isInvalidated() && !solo)); - + requestContext.setAttribute( + PortalReservedParameters.PAGE_THEME_ATTRIBUTE, theme); + boolean solo = isSoloMode(requestContext); + SessionPathResolverCache sessionPathResolver = new SessionPathResolverCache( + requestContext.getRequest().getSession()); + initDepthFragmentDecorations(requestContext, theme, page + .getRootContentFragment(), pageActionAccess, isAjaxRequest, + ((DecorationFactoryImpl) decorationFactory) + .getResourceValidator(), sessionPathResolver, + (theme.isInvalidated() && !solo)); + if (theme.isInvalidated() && !solo) { if (this.useSessionForThemeCaching) @@ -209,247 +230,294 @@ requestContext.setSessionAttribute(themeCacheKey, theme); } else - { - CacheElement themeCacheElem = cache.createElement(themeContentCacheKey, theme); + { + CacheElement themeCacheElem = cache.createElement( + themeContentCacheKey, theme); cache.put(themeCacheElem); } - theme.setInvalidated(false); - } + theme.setInvalidated(false); + } return; } - theme = decorationFactory.getTheme(page, requestContext); - requestContext.setAttribute(PortalReservedParameters.PAGE_THEME_ATTRIBUTE, theme); - if ( fragments == null || fragments.size() == 0 ) + theme = decorationFactory.getTheme(page, requestContext); + requestContext.setAttribute( + PortalReservedParameters.PAGE_THEME_ATTRIBUTE, theme); + if (fragments == null || fragments.size() == 0) { ContentFragment rootFragment = page.getRootContentFragment(); - initDepthFragments(requestContext, theme, rootFragment, pageActionAccess, isAjaxRequest, fragments); + initDepthFragments(requestContext, theme, rootFragment, + pageActionAccess, isAjaxRequest, fragments); } else { Iterator fragmentsIter = fragments.iterator(); - while ( fragmentsIter.hasNext() ) + while (fragmentsIter.hasNext()) { - ContentFragment fragment = (ContentFragment)fragmentsIter.next(); - initFragment(requestContext, theme, fragment, pageActionAccess, isAjaxRequest); + ContentFragment fragment = (ContentFragment) fragmentsIter + .next(); + initFragment(requestContext, theme, fragment, pageActionAccess, + isAjaxRequest); } } - + if (useCache() && !isSoloMode(requestContext)) { if (themeContentCacheKey == null && themeCacheKey == null) { if (this.useSessionForThemeCaching) { - themeCacheKey = cache.createSessionKey(requestContext); - requestContext.getRequest().getSession().removeAttribute(themeCacheKey); + themeCacheKey = cache.createSessionKey(requestContext); + requestContext.getRequest().getSession().removeAttribute( + themeCacheKey); } else { - themeContentCacheKey = cache.createCacheKey(requestContext, page.getId()); + themeContentCacheKey = cache.createCacheKey(requestContext, + page.getId()); cache.remove(themeContentCacheKey); - } + } } else { if (this.useSessionForThemeCaching) { - themeContentCacheKey = cache.createCacheKey(requestContext, page.getId()); + themeContentCacheKey = cache.createCacheKey(requestContext, + page.getId()); requestContext.setSessionAttribute(themeCacheKey, theme); } else { - CacheElement themeCacheElem = cache.createElement(themeContentCacheKey, theme); + CacheElement themeCacheElem = cache.createElement( + themeContentCacheKey, theme); cache.put(themeCacheElem); } } - } + } } protected boolean isSoloMode(RequestContext requestContext) { boolean solo = false; - PortletWindow window = requestContext.getPortalURL().getNavigationalState().getMaximizedWindow(); + PortletWindow window = requestContext.getPortalURL() + .getNavigationalState().getMaximizedWindow(); boolean maximized = (window != null); if (maximized) { - solo = JetspeedActions.SOLO_STATE.equals(requestContext.getPortalURL().getNavigationalState().getMappedState(window)); + solo = JetspeedActions.SOLO_STATE.equals(requestContext + .getPortalURL().getNavigationalState().getMappedState( + window)); } return solo; } - + protected boolean useCache() { return this.cache != null; } - + public String toString() { return "DecorationValve"; } - - public DecoratorActionsFactory getDecoratorActionsAdapter(Decoration decoration) + + public DecoratorActionsFactory getDecoratorActionsAdapter( + Decoration decoration) { // FIXME: why always get this property - String decoratorActionsAdapterClassName = decoration.getProperty("actions.factory"); - if ( decoratorActionsAdapterClassName == null ) + String decoratorActionsAdapterClassName = decoration + .getProperty("actions.factory"); + if (decoratorActionsAdapterClassName == null) { - decoratorActionsAdapterClassName = defaultDecoratorActionsFactory.getClass().getName(); + decoratorActionsAdapterClassName = defaultDecoratorActionsFactory + .getClass().getName(); } synchronized (decoratorActionsAdapterCache) { - DecoratorActionsFactory adapter = (DecoratorActionsFactory)decoratorActionsAdapterCache.get(decoratorActionsAdapterClassName); - if ( adapter == null ) + DecoratorActionsFactory adapter = (DecoratorActionsFactory) decoratorActionsAdapterCache + .get(decoratorActionsAdapterClassName); + if (adapter == null) { try { - adapter = (DecoratorActionsFactory)Class.forName(decoratorActionsAdapterClassName).newInstance(); + adapter = (DecoratorActionsFactory) Class.forName( + decoratorActionsAdapterClassName).newInstance(); adapter.setMaximizeOnEdit(this.maxOnEdit); adapter.setMaximizeOnConfig(this.maxOnConfig); adapter.setMaximizeOnEditDefaults(this.maxOnEditDefaults); } catch (Exception e) { - log.error("Failed to instantiate custom DecoratorActionsAdaptor "+decoratorActionsAdapterClassName+", falling back to default.",e); - adapter = (DecoratorActionsFactory)decoratorActionsAdapterCache.get(defaultDecoratorActionsFactory.getClass().getName()); - if ( adapter == null ) + log.error( + "Failed to instantiate custom DecoratorActionsAdaptor " + + decoratorActionsAdapterClassName + + ", falling back to default.", e); + adapter = (DecoratorActionsFactory) decoratorActionsAdapterCache + .get(defaultDecoratorActionsFactory.getClass() + .getName()); + if (adapter == null) { adapter = defaultDecoratorActionsFactory; } } - decoratorActionsAdapterCache.put(decoratorActionsAdapterClassName,adapter); + decoratorActionsAdapterCache.put( + decoratorActionsAdapterClassName, adapter); } return adapter; } } - + /** - * Builds and assigns a list of available portlet modes and window states for - * the target Fragment. + * Builds and assigns a list of available portlet modes and window states + * for the target Fragment. * - * @param requestContext RequestContext of the current portal request. - * @param fragment Fragment to initialize modes and states for. + * @param requestContext + * RequestContext of the current portal request. + * @param fragment + * Fragment to initialize modes and states for. * @return - * @throws PortletEntityNotStoredException - * @throws FailedToRetrievePortletWindow + * @throws PortletEntityNotStoredException + * @throws FailedToRetrievePortletWindow */ - protected boolean initActionsForFragment(RequestContext requestContext, - ContentFragment fragment, - PageActionAccess pageActionAccess, - Decoration decoration, - boolean isAjaxRequest) throws FailedToRetrievePortletWindow, PortletEntityNotStoredException + protected boolean initActionsForFragment(RequestContext requestContext, + ContentFragment fragment, PageActionAccess pageActionAccess, + Decoration decoration, boolean isAjaxRequest) + throws FailedToRetrievePortletWindow, + PortletEntityNotStoredException { boolean fragmentSupportsActions = false; - PortletWindow window = windowAccessor.getPortletWindow(fragment); - PortletDefinitionComposite portlet = (PortletDefinitionComposite) window.getPortletEntity().getPortletDefinition(); - - if (null == portlet) - { - return fragmentSupportsActions; // allow nothing + PortletWindow window = windowAccessor.getPortletWindow(fragment); + PortletDefinitionComposite portlet = (PortletDefinitionComposite) window + .getPortletEntity().getPortletDefinition(); + + if (null == portlet) { return fragmentSupportsActions; // allow nothing } List actions = Collections.EMPTY_LIST; - - PortletMode currentMode = requestContext.getPortalURL().getNavigationalState().getMode(window); - WindowState currentState = requestContext.getPortalURL().getNavigationalState().getState(window); + + PortletMode currentMode = requestContext.getPortalURL() + .getNavigationalState().getMode(window); + WindowState currentState = requestContext.getPortalURL() + .getNavigationalState().getState(window); ContentTypeSet content = portlet.getContentTypeSet(); - - if ( fragment.equals(requestContext.getPage().getRootFragment()) ) + + if (fragment.equals(requestContext.getPage().getRootFragment())) { fragmentSupportsActions = true; - actions = getPageModes(requestContext, window, content, currentMode, currentState, pageActionAccess, decoration, isAjaxRequest); + actions = getPageModes(requestContext, window, content, + currentMode, currentState, pageActionAccess, decoration, + isAjaxRequest); } - else if ( !Fragment.LAYOUT.equals(fragment.getType()) ) + else if (!Fragment.LAYOUT.equals(fragment.getType())) { fragmentSupportsActions = true; String fragmentId = fragment.getId(); - PortletApplication pa = (PortletApplication)window.getPortletEntity().getPortletDefinition().getPortletApplicationDefinition(); + PortletApplication pa = (PortletApplication) window + .getPortletEntity().getPortletDefinition() + .getPortletApplicationDefinition(); String portletName = portlet.getUniqueName(); - PortletMode currentMappedMode = pa.getMappedPortletMode(currentMode); - WindowState currentMappedState = pa.getMappedWindowState(currentState); + PortletMode currentMappedMode = pa + .getMappedPortletMode(currentMode); + WindowState currentMappedState = pa + .getMappedWindowState(currentState); Object action; PortletMode mappedMode; PortletMode customMode; WindowState mappedState; WindowState customState; - + ArrayList actionTemplates = new ArrayList(); - + DecoratorActionsFactory actionsAdapter = getDecoratorActionsAdapter(decoration); - - List supportedActions = actionsAdapter.getSupportedActions(requestContext, pa, window, currentMappedMode, currentMappedState, decoration); + + List supportedActions = actionsAdapter.getSupportedActions( + requestContext, pa, window, currentMappedMode, + currentMappedState, decoration); Iterator iter = supportedActions.iterator(); - + String currentModeAction = null; String currentStateAction = null; - while ( iter.hasNext() ) + while (iter.hasNext()) { action = iter.next(); - if ( action instanceof PortletMode ) + if (action instanceof PortletMode) { - mappedMode = (PortletMode)action; + mappedMode = (PortletMode) action; customMode = pa.getCustomPortletMode(mappedMode); - - if ( customMode != null ) + + if (customMode != null) { - boolean equalsCurrentMode = customMode.equals(currentMode); - if ( equalsCurrentMode ) + boolean equalsCurrentMode = customMode + .equals(currentMode); + if (equalsCurrentMode) { currentModeAction = mappedMode.toString(); } - if ( ! equalsCurrentMode || isAjaxRequest ) + if (!equalsCurrentMode || isAjaxRequest) { - if ( (content.supportsPortletMode(customMode) || isAutoSwitchableCustomMode(content, customMode)) - && (!PortletMode.EDIT.equals(customMode) || pageActionAccess.isEditAllowed()) - && pageActionAccess.checkPortletMode(fragmentId, portletName, mappedMode) - ) + if ((content.supportsPortletMode(customMode) || isAutoSwitchableCustomMode( + content, customMode)) + && (!PortletMode.EDIT.equals(customMode) || pageActionAccess + .isEditAllowed()) + && pageActionAccess + .checkPortletMode(fragmentId, + portletName, mappedMode)) { - actionTemplates.add(new DecoratorActionTemplate(mappedMode, customMode)); + actionTemplates + .add(new DecoratorActionTemplate( + mappedMode, customMode)); } } } } - else if ( action instanceof WindowState ) + else if (action instanceof WindowState) { - mappedState = (WindowState)action; + mappedState = (WindowState) action; customState = pa.getCustomWindowState(mappedState); - if ( customState != null ) + if (customState != null) { - boolean equalsCurrentState = customState.equals(currentState); - if ( equalsCurrentState ) + boolean equalsCurrentState = customState + .equals(currentState); + if (equalsCurrentState) { currentStateAction = mappedState.toString(); } - if ( ! equalsCurrentState || isAjaxRequest ) + if (!equalsCurrentState || isAjaxRequest) { - if ( pageActionAccess.checkWindowState(fragmentId, portletName, mappedState ) ) + if (pageActionAccess.checkWindowState(fragmentId, + portletName, mappedState)) { - actionTemplates.add(new DecoratorActionTemplate(mappedState, customState)); + actionTemplates + .add(new DecoratorActionTemplate( + mappedState, customState)); } } } } } - actions = actionsAdapter.getDecoratorActions(requestContext, pa, window, currentMode, currentState, decoration, actionTemplates,portlet,fragment,accessController); - - decoration.setCurrentModeAction( currentModeAction ); - decoration.setCurrentStateAction( currentStateAction ); + actions = actionsAdapter.getDecoratorActions(requestContext, pa, + window, currentMode, currentState, decoration, + actionTemplates, portlet, fragment, accessController); + + decoration.setCurrentModeAction(currentModeAction); + decoration.setCurrentStateAction(currentStateAction); } - - decoration.setActions( actions ); - + + decoration.setActions(actions); + return fragmentSupportsActions; } - + /** * Builds a list of portlet modes that can be executed on the current * fragment excluding the portlet's current mode. * - * @param requestContext RequestContext of the current portal request. + * @param requestContext + * RequestContext of the current portal request. * @param pageActionAccess * @param mode * @param content @@ -457,62 +525,100 @@ * @param window * @param fragment * @return java.util.List of modes excluding the current one. - * @throws PortletEntityNotStoredException + * @throws PortletEntityNotStoredException */ - protected List getPageModes(RequestContext requestContext, PortletWindow window, ContentTypeSet content, - PortletMode mode, WindowState state, PageActionAccess pageActionAccess, Decoration decoration, - boolean isAjaxRequest) + protected List getPageModes(RequestContext requestContext, + PortletWindow window, ContentTypeSet content, PortletMode mode, + WindowState state, PageActionAccess pageActionAccess, + Decoration decoration, boolean isAjaxRequest) { List pageModes = new ArrayList(); - - + try { - if (mode.equals(PortletMode.HELP) || !state.equals(WindowState.NORMAL)) + if (mode.equals(PortletMode.HELP) + || !state.equals(WindowState.NORMAL)) { // switch back to VIEW mode and NORMAL state. PortalURL portalURL = requestContext.getPortalURL(); - String action = requestContext.getResponse().encodeURL( (isAjaxRequest) - ? portalURL.createNavigationalEncoding(window, PortletMode.VIEW, WindowState.NORMAL) - : portalURL.createPortletURL(window, PortletMode.VIEW, WindowState.NORMAL, portalURL.isSecure()).toString() ); + String action = requestContext.getResponse().encodeURL( + (isAjaxRequest) ? portalURL.createNavigationalEncoding( + window, PortletMode.VIEW, WindowState.NORMAL) + : portalURL.createPortletURL(window, + PortletMode.VIEW, WindowState.NORMAL, + portalURL.isSecure()).toString()); String actionName = PortletMode.VIEW.toString(); - pageModes.add(new DecoratorAction(actionName, requestContext.getLocale(), decoration.getResource("images/" + actionName + ".gif"),action,DecoratorActionTemplate.ACTION_TYPE_MODE)); + pageModes.add(new DecoratorAction(actionName, requestContext + .getLocale(), decoration.getResource("images/" + + actionName + ".gif"), action, + DecoratorActionTemplate.ACTION_TYPE_MODE)); } - else if ( pageActionAccess.isEditAllowed() ) + else if (pageActionAccess.isEditAllowed()) { - String targetMode = pageActionAccess.isEditing() ? PortletMode.VIEW.toString() : PortletMode.EDIT.toString(); + String targetMode = pageActionAccess.isEditing() ? PortletMode.VIEW + .toString() + : PortletMode.EDIT.toString(); PortalURL portalURL = requestContext.getPortalURL(); HashMap parameters = new HashMap(); - String[] paramValues = new String[]{targetMode}; - parameters.put("pageMode",paramValues); + String[] paramValues = new String[] + {targetMode}; + parameters.put("pageMode", paramValues); - // Use an ActionURL to set the oposite pageMode and always set VIEW mode and state NORMAL - String action = requestContext.getResponse().encodeURL( (isAjaxRequest) - ? portalURL.createNavigationalEncoding(window, parameters, PortletMode.VIEW, WindowState.NORMAL, true) - : portalURL.createPortletURL(window, parameters, PortletMode.VIEW, WindowState.NORMAL, true, portalURL.isSecure()).toString() ); - pageModes.add(new DecoratorAction(targetMode, requestContext.getLocale(), decoration.getResource("images/" + targetMode + ".gif"), action,DecoratorActionTemplate.ACTION_TYPE_MODE)); - - //window.getPortletEntity().getPortletDefinition().getInitParameterSet().get( "xxxx" ); - + // Use an ActionURL to set the oposite pageMode and always set + // VIEW mode and state NORMAL + String action = requestContext.getResponse().encodeURL( + (isAjaxRequest) ? portalURL.createNavigationalEncoding( + window, parameters, PortletMode.VIEW, + WindowState.NORMAL, true) : portalURL + .createPortletURL(window, parameters, + PortletMode.VIEW, WindowState.NORMAL, + true, portalURL.isSecure()).toString()); + pageModes.add(new DecoratorAction(targetMode, requestContext + .getLocale(), decoration.getResource("images/" + + targetMode + ".gif"), action, + DecoratorActionTemplate.ACTION_TYPE_MODE)); + + // window.getPortletEntity().getPortletDefinition().getInitParameterSet().get( + // "xxxx" ); + if (content.supportsPortletMode(PortletMode.HELP)) { - if ( pageActionAccess.isEditing() ) + if (pageActionAccess.isEditing()) { - // force it back to VIEW mode first with an ActionURL, as well as setting HELP mode and MAXIMIZED state + // force it back to VIEW mode first with an ActionURL, + // as well as setting HELP mode and MAXIMIZED state paramValues[0] = PortletMode.VIEW.toString(); - action = requestContext.getResponse().encodeURL( (isAjaxRequest) - ? portalURL.createNavigationalEncoding(window, parameters, PortletMode.HELP, WindowState.MAXIMIZED, true) - : portalURL.createPortletURL(window, parameters, PortletMode.HELP, WindowState.MAXIMIZED, true, portalURL.isSecure()).toString() ); + action = requestContext.getResponse().encodeURL( + (isAjaxRequest) ? portalURL + .createNavigationalEncoding(window, + parameters, PortletMode.HELP, + WindowState.MAXIMIZED, true) + : portalURL.createPortletURL(window, + parameters, PortletMode.HELP, + WindowState.MAXIMIZED, true, + portalURL.isSecure()) + .toString()); } else { // switch to mode HELP and state MAXIMIZED - action = requestContext.getResponse().encodeURL( (isAjaxRequest) - ? portalURL.createNavigationalEncoding(window, PortletMode.HELP, WindowState.MAXIMIZED) - : portalURL.createPortletURL(window,PortletMode.HELP, WindowState.MAXIMIZED, portalURL.isSecure()).toString() ); + action = requestContext.getResponse().encodeURL( + (isAjaxRequest) ? portalURL + .createNavigationalEncoding(window, + PortletMode.HELP, + WindowState.MAXIMIZED) + : portalURL.createPortletURL(window, + PortletMode.HELP, + WindowState.MAXIMIZED, + portalURL.isSecure()) + .toString()); } String actionName = PortletMode.HELP.toString(); - pageModes.add(new DecoratorAction(actionName, requestContext.getLocale(), decoration.getResource("images/" + actionName + ".gif"), action,DecoratorActionTemplate.ACTION_TYPE_MODE)); + pageModes.add(new DecoratorAction(actionName, + requestContext.getLocale(), decoration + .getResource("images/" + actionName + + ".gif"), action, + DecoratorActionTemplate.ACTION_TYPE_MODE)); } } } @@ -521,73 +627,75 @@ log.warn("Unable to initalize PageLayout actions", e); pageModes = null; } - + return pageModes; - } - + } + /** - * Intializes all fragments with there decorations and portlet modes - * and winodw states. + * Intializes all fragments with there decorations and portlet modes and + * winodw states. * * - * @param requestContext RequestContext of the current portal request. + * @param requestContext + * RequestContext of the current portal request. * @param theme * @param fragment * @param pageActionAccess */ - protected void initDepthFragments(RequestContext requestContext, - Theme theme, - ContentFragment fragment, - PageActionAccess pageActionAccess, - boolean isAjaxRequest, - List collectFragments ) + protected void initDepthFragments(RequestContext requestContext, + Theme theme, ContentFragment fragment, + PageActionAccess pageActionAccess, boolean isAjaxRequest, + List collectFragments) { final List contentFragments = fragment.getContentFragments(); - - if(contentFragments != null && contentFragments.size() > 0) + + if (contentFragments != null && contentFragments.size() > 0) { Iterator itr = contentFragments.iterator(); - while(itr.hasNext()) + while (itr.hasNext()) { ContentFragment aFragment = (ContentFragment) itr.next(); - initDepthFragments(requestContext, theme, aFragment, pageActionAccess, isAjaxRequest, collectFragments); + initDepthFragments(requestContext, theme, aFragment, + pageActionAccess, isAjaxRequest, collectFragments); } } - - if ( initFragment(requestContext, theme, fragment, pageActionAccess, isAjaxRequest) ) + + if (initFragment(requestContext, theme, fragment, pageActionAccess, + isAjaxRequest)) { - if ( collectFragments != null ) + if (collectFragments != null) { - collectFragments.add( fragment ); + collectFragments.add(fragment); } } } - protected boolean initFragment(RequestContext requestContext, - Theme theme, - ContentFragment fragment, - PageActionAccess pageActionAccess, - boolean isAjaxRequest) + protected boolean initFragment(RequestContext requestContext, Theme theme, + ContentFragment fragment, PageActionAccess pageActionAccess, + boolean isAjaxRequest) { boolean fragmentSupportsActions = false; try { Decoration decoration = theme.getDecoration(fragment); fragment.setDecoration(decoration); - fragmentSupportsActions = initActionsForFragment(requestContext, fragment, pageActionAccess, decoration, isAjaxRequest); + fragmentSupportsActions = initActionsForFragment(requestContext, + fragment, pageActionAccess, decoration, isAjaxRequest); } catch (Exception e) { - log.warn("Unable to initalize actions for fragment "+fragment.getId(), e); + log.warn("Unable to initalize actions for fragment " + + fragment.getId(), e); } return fragmentSupportsActions; } /** - * Reintializes all fragments with there decorations and portlet modes - * and winodw states after theme is restored from cache. + * Reintializes all fragments with there decorations and portlet modes and + * winodw states after theme is restored from cache. * - * @param requestContext RequestContext of the current portal request. + * @param requestContext + * RequestContext of the current portal request. * @param theme * @param fragment * @param pageActionAccess @@ -596,117 +704,118 @@ * @param pathResolverCache */ protected void initDepthFragmentDecorations(RequestContext requestContext, - Theme theme, - ContentFragment fragment, - PageActionAccess pageActionAccess, - boolean isAjaxRequest, - ResourceValidator validator, - PathResolverCache pathResolverCache, - boolean reloadActionList) + Theme theme, ContentFragment fragment, + PageActionAccess pageActionAccess, boolean isAjaxRequest, + ResourceValidator validator, PathResolverCache pathResolverCache, + boolean reloadActionList) { final List contentFragments = fragment.getContentFragments(); - - if(contentFragments != null && contentFragments.size() > 0) + + if (contentFragments != null && contentFragments.size() > 0) { Iterator itr = contentFragments.iterator(); - while(itr.hasNext()) + while (itr.hasNext()) { ContentFragment aFragment = (ContentFragment) itr.next(); initDepthFragmentDecorations(requestContext, theme, aFragment, - pageActionAccess, isAjaxRequest, - validator, pathResolverCache, reloadActionList); + pageActionAccess, isAjaxRequest, validator, + pathResolverCache, reloadActionList); } } - try + try { // PageTheme::getDecoration retrieves cached decoration only. Decoration decoration = theme.getDecoration(fragment); // re-init to set transient memebers. - Properties config = ((DecorationFactoryImpl) decorationFactory).getConfiguration(decoration.getName(), fragment.getType()); - ((BaseDecoration) decoration).init(config, validator, pathResolverCache); - // fragment is newly created on every request, so reset decoration for fragment. + Properties config = ((DecorationFactoryImpl) decorationFactory) + .getConfiguration(decoration.getName(), fragment.getType()); + ((BaseDecoration) decoration).init(config, validator, + pathResolverCache); + // fragment is newly created on every request, so reset decoration + // for fragment. fragment.setDecoration(decoration); - + if (reloadActionList) { - initActionsForFragment(requestContext, fragment, pageActionAccess, decoration, isAjaxRequest); + initActionsForFragment(requestContext, fragment, + pageActionAccess, decoration, isAjaxRequest); } } catch (Exception e) { - log.warn("Unable to initalize actions for fragment "+fragment.getId(), e); + log.warn("Unable to initalize actions for fragment " + + fragment.getId(), e); } } - + public void setMaximizeOnEdit(boolean maxOnEdit) { this.maxOnEdit = maxOnEdit; this.defaultDecoratorActionsFactory.setMaximizeOnEdit(maxOnEdit); } - + public boolean getMaximizeOnEdit() { return this.maxOnEdit; } - + public void setMaximizeOnConfig(boolean maxOnConfig) { this.maxOnConfig = maxOnConfig; this.defaultDecoratorActionsFactory.setMaximizeOnConfig(maxOnConfig); } - + public boolean getMaximizeOnConfig() { return this.maxOnConfig; } - + public void setMaximizeOnEditDefaults(boolean maxOnEditDefaults) { this.maxOnEditDefaults = maxOnEditDefaults; - this.defaultDecoratorActionsFactory.setMaximizeOnEditDefaults(maxOnEditDefaults); + this.defaultDecoratorActionsFactory + .setMaximizeOnEditDefaults(maxOnEditDefaults); } - + public boolean getMaximizeOnEditDefaults() { return this.maxOnEditDefaults; } - - public void setAutoSwitchingToEditDefaultsModes(boolean autoSwitchingToEditDefaultsModes) + + public void setAutoSwitchingToEditDefaultsModes( + boolean autoSwitchingToEditDefaultsModes) { this.autoSwitchingToEditDefaultsModes = autoSwitchingToEditDefaultsModes; } - + public boolean getAutoSwitchingToEditDefaultsModes() { return this.autoSwitchingToEditDefaultsModes; } - + public void setAutoSwitchingForConfigMode(boolean autoSwitchingForConfigMode) { this.autoSwitchingForConfigMode = autoSwitchingForConfigMode; } - + public boolean getAutoSwitchingForConfigMode() { return this.autoSwitchingForConfigMode; } - - private boolean isAutoSwitchableCustomMode(ContentTypeSet content, PortletMode customMode) + + private boolean isAutoSwitchableCustomMode(ContentTypeSet content, + PortletMode customMode) { - if (this.autoSwitchingForConfigMode && JetspeedActions.CONFIG_MODE.equals(customMode)) - { - return true; - } - + if (this.autoSwitchingForConfigMode + && JetspeedActions.CONFIG_MODE.equals(customMode)) { return true; } + if (this.autoSwitchingToEditDefaultsModes) { - if (content.supportsPortletMode(PortletMode.EDIT) && JetspeedActions.EDIT_DEFAULTS_MODE.equals(customMode)) - { - return true; - } + if (content.supportsPortletMode(PortletMode.EDIT) + && JetspeedActions.EDIT_DEFAULTS_MODE.equals(customMode)) { return true; } } - + return false; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecoratorAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecoratorAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecoratorAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,76 +23,87 @@ /** * DecoratorAction - * + * * @author David Sean Taylor * @version $Id: DecoratorAction.java 554461 2007-07-08 22:45:49Z ate $ */ public class DecoratorAction implements Serializable { + public static final String RESOURCE_BUNDLE = "org.apache.jetspeed.decoration.resources.DecoratorActions"; String actionName = null; + String actionType = null; + String name = null; + String link = null; + String alt = null; + String action = null; + String target; + boolean custom; - + public static ResourceBundle getResourceBundle(Locale locale) { return getBundle(RESOURCE_BUNDLE, locale); } - + private static ResourceBundle getBundle(String base, Locale locale) { ResourceBundle bundle = null; try { - if ( locale != null ) + if (locale != null) { bundle = ResourceBundle.getBundle(base, locale); } else { bundle = ResourceBundle.getBundle(base); - } + } } catch (MissingResourceException mre) - { + { } return bundle; } - - public static String getResourceString(ResourceBundle bundle, String key, String defaultValue) + + public static String getResourceString(ResourceBundle bundle, String key, + String defaultValue) { String value = defaultValue; - - if ( key != null && bundle != null ) - try + + if (key != null && bundle != null) try { value = bundle.getString(key); } catch (MissingResourceException mre) - { + { } return value; } - public DecoratorAction(String actionName, String name, String alt, Locale locale, String link, String action, boolean custom, String actionType) + public DecoratorAction(String actionName, String name, String alt, + Locale locale, String link, String action, boolean custom, + String actionType) { ResourceBundle bundle = getBundle(RESOURCE_BUNDLE, locale); this.actionName = actionName; this.actionType = actionType; - this.name = getResourceString(bundle,name,name); - this.alt = getResourceString(bundle,alt,alt); + this.name = getResourceString(bundle, name, name); + this.alt = getResourceString(bundle, alt, alt); this.link = link; this.action = action; this.custom = custom; } - - public DecoratorAction(String actionName, String name, String alt, String link, String action, boolean custom, String actionType) + + public DecoratorAction(String actionName, String name, String alt, + String link, String action, boolean custom, String actionType) { this.actionName = actionName; this.actionType = actionType; @@ -102,27 +113,31 @@ this.action = action; this.custom = custom; } - - public DecoratorAction(String name, Locale locale, String link, String action, boolean custom, String actionType) + + public DecoratorAction(String name, Locale locale, String link, + String action, boolean custom, String actionType) { - this(name,name,name,locale,link,action,custom,actionType); + this(name, name, name, locale, link, action, custom, actionType); } - - public DecoratorAction(String name, Locale locale, String link, String action, String actionType) + + public DecoratorAction(String name, Locale locale, String link, + String action, String actionType) { - this(name,name,name,locale,link,action,false,actionType); + this(name, name, name, locale, link, action, false, actionType); } - - public DecoratorAction(String actionName, String name, String alt, String link, String actionType) + + public DecoratorAction(String actionName, String name, String alt, + String link, String actionType) { - this(actionName, name,alt,null,link,null,false,actionType); + this(actionName, name, alt, null, link, null, false, actionType); } public String getActionName() { return this.actionName; } - public void setActionName( String actionName ) + + public void setActionName(String actionName) { this.actionName = actionName; } @@ -131,26 +146,27 @@ { return this.actionType; } - public void setActionType( String actionType ) + + public void setActionType(String actionType) { this.actionType = actionType; } - + public String getName() { return this.name; } - + public void setName(String name) { this.name = name; } - + public String getLink() { return this.link; } - + public void setLink(String link) { this.link = link; @@ -160,7 +176,7 @@ { return this.alt; } - + public void setAlt(String alt) { this.alt = alt; @@ -170,22 +186,22 @@ { return this.action; } - + public void setAction(String action) { this.action = action; } - + public String getTarget() { return this.target; } - + public void setTarget(String target) { this.target = target; } - + public boolean isCustom() { return custom; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecoratorActionTemplate.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecoratorActionTemplate.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecoratorActionTemplate.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.decoration; import javax.portlet.PortletMode; @@ -21,38 +21,48 @@ public class DecoratorActionTemplate { + protected static final String ACTION_TYPE_MODE = "mode"; + protected static final String ACTION_TYPE_STATE = "state"; + protected static final String ACTION_TYPE_BOTH = "both"; private String action; + private PortletMode mode; + private PortletMode customMode; + private WindowState state; + private WindowState customState; private String actionType; - public DecoratorActionTemplate(String action, PortletMode mode, PortletMode customMode, WindowState state, WindowState customState) + public DecoratorActionTemplate(String action, PortletMode mode, + PortletMode customMode, WindowState state, WindowState customState) { this.action = action; this.mode = mode; this.customMode = customMode; this.state = state; this.customState = customState; - if ( mode != null ) + if (mode != null) { - this.actionType = ( state != null ) ? ACTION_TYPE_BOTH : ACTION_TYPE_MODE; + this.actionType = (state != null) ? ACTION_TYPE_BOTH + : ACTION_TYPE_MODE; } - else if ( state != null ) + else if (state != null) { this.actionType = ACTION_TYPE_STATE; } } - public DecoratorActionTemplate(String action, PortletMode mode, WindowState state) + public DecoratorActionTemplate(String action, PortletMode mode, + WindowState state) { - this(action,mode,mode,state,state); + this(action, mode, mode, state, state); } public DecoratorActionTemplate(PortletMode mode, PortletMode customMode) @@ -62,7 +72,7 @@ public DecoratorActionTemplate(PortletMode mode) { - this(mode,mode); + this(mode, mode); } public DecoratorActionTemplate(WindowState state, WindowState customState) @@ -72,7 +82,7 @@ public DecoratorActionTemplate(WindowState state) { - this(state,state); + this(state, state); } public String getAction() @@ -104,18 +114,16 @@ { return state; } - + public int hashCode() { return action.hashCode(); } - + public boolean equals(Object o) { - if ( o != null && o instanceof DecoratorActionTemplate) - { - return action.equals(((DecoratorActionTemplate)o).action); - } + if (o != null && o instanceof DecoratorActionTemplate) { return action + .equals(((DecoratorActionTemplate) o).action); } return false; } @@ -124,7 +132,7 @@ this.action = action; } - public void setActionType( String actionType ) + public void setActionType(String actionType) { this.actionType = actionType; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecoratorActionsFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecoratorActionsFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DecoratorActionsFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.decoration; import java.util.List; @@ -30,44 +30,52 @@ public interface DecoratorActionsFactory { - List getSupportedActions(RequestContext rc, PortletApplication pa, PortletWindow pw, PortletMode pm, - WindowState ws, Decoration decoration); - List getDecoratorActions(RequestContext rc, PortletApplication pa, PortletWindow pw, PortletMode pm, - WindowState ws, Decoration decoration, List allowedActions, PortletDefinitionComposite portlet, ContentFragment fragment, SecurityAccessController accessController); - + List getSupportedActions(RequestContext rc, PortletApplication pa, + PortletWindow pw, PortletMode pm, WindowState ws, + Decoration decoration); + + List getDecoratorActions(RequestContext rc, PortletApplication pa, + PortletWindow pw, PortletMode pm, WindowState ws, + Decoration decoration, List allowedActions, + PortletDefinitionComposite portlet, ContentFragment fragment, + SecurityAccessController accessController); + /** * Maximize portlet window when going into edit mode + * * @param maxOnEdit */ void setMaximizeOnEdit(boolean maxOnEdit); - + /** * Maximize portlet window when going into edit mode * * @return */ public boolean getMaximizeOnEdit(); - + /** * Maximize portlet window when going into config mode + * * @param maxOnConfig */ void setMaximizeOnConfig(boolean maxOnConfig); - + /** * Maximize portlet window when going into edit_defaults mode * * @return */ public boolean getMaximizeOnConfig(); - + /** * Maximize portlet window when going into edit_defaults mode + * * @param maxOnEditDefaults */ void setMaximizeOnEditDefaults(boolean maxOnEditDefaults); - + /** * Maximize portlet window when going into edit_defaults mode * Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DefaultDecoratorActionsFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DefaultDecoratorActionsFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/DefaultDecoratorActionsFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.decoration; import java.util.ArrayList; @@ -28,19 +28,23 @@ import org.apache.jetspeed.request.RequestContext; import org.apache.pluto.om.window.PortletWindow; -public class DefaultDecoratorActionsFactory extends AbstractDecoratorActionsFactory +public class DefaultDecoratorActionsFactory extends + AbstractDecoratorActionsFactory { + private final List supportedActions; public DefaultDecoratorActionsFactory() { - ArrayList list = new ArrayList(JetspeedActions.getStandardPortletModes()); + ArrayList list = new ArrayList(JetspeedActions + .getStandardPortletModes()); list.addAll(JetspeedActions.getStandardWindowStates()); supportedActions = Collections.unmodifiableList(list); } - public List getSupportedActions(RequestContext rc, PortletApplication pa, PortletWindow pw, PortletMode pm, - WindowState ws, Decoration decoration) + public List getSupportedActions(RequestContext rc, PortletApplication pa, + PortletWindow pw, PortletMode pm, WindowState ws, + Decoration decoration) { return supportedActions; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/LayoutDecorationImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/LayoutDecorationImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/LayoutDecorationImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,24 +21,28 @@ import org.apache.jetspeed.util.Path; /** - * Default implementation of org.apache.jetspeed.decoration.LayoutDecoration + * Default implementation of + * org.apache.jetspeed.decoration.LayoutDecoration * * @author Scott T. Weaver * * @see org.apache.jetspeed.decoration.LayoutDecoration - * + * */ -public class LayoutDecorationImpl extends BaseDecoration implements LayoutDecoration +public class LayoutDecorationImpl extends BaseDecoration implements + LayoutDecoration { - public LayoutDecorationImpl(Properties config, ResourceValidator validator, Path basePath, Path baseClientPath, PathResolverCache cache) + + public LayoutDecorationImpl(Properties config, ResourceValidator validator, + Path basePath, Path baseClientPath, PathResolverCache cache) { super(config, validator, basePath, baseClientPath, cache); } - + public void setDecorationFactory(DecorationFactory decorationFactory) { // TODO Ate: this seems like an obsolete constructor to me, no? - } + } public String getHeader() { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/LayoutInfoImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/LayoutInfoImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/LayoutInfoImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,33 +19,36 @@ /** * * @author Scott T. Weaver - * + * */ public class LayoutInfoImpl implements LayoutInfo { + private String name; + private String displayName; + private String description; - + public LayoutInfoImpl(String name, String displayName, String description) { this.name = name; this.displayName = displayName; this.description = description; } - + public String getName() { return this.name; } - + public String getDescription() { return this.description; } - + public String getDisplayName() { return this.displayName; - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PageActionAccess.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PageActionAccess.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PageActionAccess.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,32 +29,38 @@ /** * PageActionAccess - * + * * @author Ate Douma * @version $Id: PageActionAccess.java 516448 2007-03-09 16:25:47Z ate $ */ public class PageActionAccess implements PageEditAccess, Serializable { + protected static final Log log = LogFactory.getLog(PageActionAccess.class); private static final class ActionAccess implements Serializable { + int checkedFlags; + int actionFlags; } - + private boolean anonymous; + private boolean editAllowed; + private boolean editing; + private HashMap fragmentActionAccess; - + public PageActionAccess(boolean anonymous, Page page) { - this.anonymous = anonymous; + this.anonymous = anonymous; this.editAllowed = checkEditPage(page); this.fragmentActionAccess = new HashMap(); } - + public void checkReset(boolean anonymous, Page page) { if (this.anonymous != anonymous) @@ -65,73 +71,74 @@ this.editing = false; } } - + public boolean isAnonymous() { return anonymous; } - + public boolean isEditAllowed() { return editAllowed; } - + public boolean isEditing() { return editing; } - + public void setEditing(boolean editing) { - if ( editing && ! editAllowed ) - { - throw new SecurityException(); - } + if (editing && !editAllowed) { throw new SecurityException(); } this.editing = editing; } - - public boolean checkPortletMode(String fragmentId, String portletName, PortletMode mode) + + public boolean checkPortletMode(String fragmentId, String portletName, + PortletMode mode) { return checkActionAccess(fragmentId, portletName, mode.toString()); } - public boolean checkWindowState(String fragmentId, String portletName, WindowState state) + public boolean checkWindowState(String fragmentId, String portletName, + WindowState state) { return checkActionAccess(fragmentId, portletName, state.toString()); } - - protected synchronized boolean checkActionAccess(String fragmentId, String portletName, String action) + + protected synchronized boolean checkActionAccess(String fragmentId, + String portletName, String action) { try { int actionIndex = JetspeedActions.getContainerActionMask(action); - ActionAccess actionAccess = (ActionAccess)fragmentActionAccess.get(fragmentId); - if ( actionAccess == null ) + ActionAccess actionAccess = (ActionAccess) fragmentActionAccess + .get(fragmentId); + if (actionAccess == null) { actionAccess = new ActionAccess(); fragmentActionAccess.put(fragmentId, actionAccess); } - if ( (actionAccess.checkedFlags & actionIndex) != actionIndex ) + if ((actionAccess.checkedFlags & actionIndex) != actionIndex) { - // TODO: not handling PortletPermission checks yet + // TODO: not handling PortletPermission checks yet // boolean access = checkPermission(portletName, action); boolean access = true; - if ( access ) + if (access) { actionAccess.actionFlags |= actionIndex; } - actionAccess.checkedFlags |= actionIndex; + actionAccess.checkedFlags |= actionIndex; } return ((actionAccess.actionFlags & actionIndex) == actionIndex); } catch (IndexOutOfBoundsException e) { - log.error("Unknown action: "+action, e); + log.error("Unknown action: " + action, e); return false; } } - + protected boolean checkEditPage(Page page) { boolean allowed = false; @@ -139,8 +146,10 @@ { page.checkAccess(JetspeedActions.EDIT); allowed = true; - } - catch (SecurityException se) {} + } + catch (SecurityException se) + { + } return allowed; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PageTheme.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PageTheme.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PageTheme.java 2008-05-16 01:54:54 UTC (rev 940) @@ -36,101 +36,125 @@ * Default implementation of org.apache.jetspeed.decoration.Theme * * @author Scott T. Weaver - * + * * @see org.apache.jetspeed.decoration.Theme */ public class PageTheme implements Theme, Serializable { + private transient Page page; + private transient DecorationFactory decorationFactory; + private transient RequestContext requestContext; + private final Set styleSheets; + private final LayoutDecoration layoutDecoration; + private final Map fragmentDecorations; + private final Collection portletDecorationNames; + private boolean invalidated = false; - - public PageTheme(Page page, DecorationFactory decorationFactory, RequestContext requestContext) + + public PageTheme(Page page, DecorationFactory decorationFactory, + RequestContext requestContext) { this.page = page; this.decorationFactory = decorationFactory; this.requestContext = requestContext; this.styleSheets = new LinkedHashSet(); this.fragmentDecorations = new HashMap(); - - boolean isDesktopEnabled = decorationFactory.isDesktopEnabled( requestContext ); + + boolean isDesktopEnabled = decorationFactory + .isDesktopEnabled(requestContext); HashMap portletDecorationNames = new HashMap(); - this.layoutDecoration = (LayoutDecoration)setupFragmentDecorations( page.getRootFragment(), true, portletDecorationNames, isDesktopEnabled ); - - if ( isDesktopEnabled ) + this.layoutDecoration = (LayoutDecoration) setupFragmentDecorations( + page.getRootFragment(), true, portletDecorationNames, + isDesktopEnabled); + + if (isDesktopEnabled) { - String defaultDesktopPortletDecoration = decorationFactory.getDefaultDesktopPortletDecoration(); - if ( defaultDesktopPortletDecoration != null && defaultDesktopPortletDecoration.length() > 0 ) + String defaultDesktopPortletDecoration = decorationFactory + .getDefaultDesktopPortletDecoration(); + if (defaultDesktopPortletDecoration != null + && defaultDesktopPortletDecoration.length() > 0) { - if ( portletDecorationNames.get( defaultDesktopPortletDecoration ) == null ) + if (portletDecorationNames.get(defaultDesktopPortletDecoration) == null) { - portletDecorationNames.put( defaultDesktopPortletDecoration, defaultDesktopPortletDecoration ); + portletDecorationNames.put(defaultDesktopPortletDecoration, + defaultDesktopPortletDecoration); } } } - this.portletDecorationNames = Collections.unmodifiableCollection( new ArrayList( portletDecorationNames.keySet() ) ); + this.portletDecorationNames = Collections + .unmodifiableCollection(new ArrayList(portletDecorationNames + .keySet())); } /** * setupFragmentDecorations - * - * Setup styleSheets and fragmentDecorations from all fragments - * in page, including nested fragments. - * - * @param fragment page fragment + * + * Setup styleSheets and fragmentDecorations from all fragments in page, + * including nested fragments. + * + * @param fragment + * page fragment * @return fragment decoration */ - private Decoration setupFragmentDecorations( Fragment fragment, boolean isRootLayout, HashMap portletDecorationNames, boolean isDesktopEnabled ) + private Decoration setupFragmentDecorations(Fragment fragment, + boolean isRootLayout, HashMap portletDecorationNames, + boolean isDesktopEnabled) { // setup fragment decorations - Decoration decoration = decorationFactory.getDecoration( page, fragment, requestContext ); - - fragmentDecorations.put( fragment.getId(), decoration ); - boolean isPortlet = ( ! isRootLayout && fragment.getType().equals( Fragment.PORTLET ) ); - - if ( isPortlet || isRootLayout ) + Decoration decoration = decorationFactory.getDecoration(page, fragment, + requestContext); + + fragmentDecorations.put(fragment.getId(), decoration); + boolean isPortlet = (!isRootLayout && fragment.getType().equals( + Fragment.PORTLET)); + + if (isPortlet || isRootLayout) { - String commonStyleSheet = decoration.getStyleSheet(); - if ( commonStyleSheet != null ) + String commonStyleSheet = decoration.getStyleSheet(); + if (commonStyleSheet != null) { - styleSheets.add( commonStyleSheet ); + styleSheets.add(commonStyleSheet); } - if ( isDesktopEnabled ) + if (isDesktopEnabled) { String desktopStyleSheet = decoration.getStyleSheetDesktop(); - if ( desktopStyleSheet != null ) + if (desktopStyleSheet != null) { - styleSheets.add( desktopStyleSheet ); + styleSheets.add(desktopStyleSheet); } } else { String portalStyleSheet = decoration.getStyleSheetPortal(); - if ( portalStyleSheet != null ) + if (portalStyleSheet != null) { - styleSheets.add( portalStyleSheet ); + styleSheets.add(portalStyleSheet); } } - - if ( isPortlet ) - { - portletDecorationNames.put( decoration.getName(), decoration.getName() ); - } + + if (isPortlet) + { + portletDecorationNames.put(decoration.getName(), decoration + .getName()); + } } - + // setup nested fragment decorations List fragments = fragment.getFragments(); - if ( ( fragments != null ) && ! fragments.isEmpty() ) + if ((fragments != null) && !fragments.isEmpty()) { Iterator fragmentsIter = fragments.iterator(); - while ( fragmentsIter.hasNext() ) + while (fragmentsIter.hasNext()) { - setupFragmentDecorations( (Fragment)fragmentsIter.next(), false, portletDecorationNames, isDesktopEnabled ); + setupFragmentDecorations((Fragment) fragmentsIter.next(), + false, portletDecorationNames, isDesktopEnabled); } } @@ -143,43 +167,44 @@ return styleSheets; } - public Decoration getDecoration( Fragment fragment ) + public Decoration getDecoration(Fragment fragment) { - return (Decoration) fragmentDecorations.get( fragment.getId() ); + return (Decoration) fragmentDecorations.get(fragment.getId()); } - + public Collection getPortletDecorationNames() { - return portletDecorationNames; // is unmodifiable + return portletDecorationNames; // is unmodifiable } - + public LayoutDecoration getPageLayoutDecoration() { return layoutDecoration; } - public void init(Page page, DecorationFactory decoration, RequestContext context) + public void init(Page page, DecorationFactory decoration, + RequestContext context) { this.page = page; this.decorationFactory = decoration; - this.requestContext = context; + this.requestContext = context; } - + public Page getPage() { return page; - } + } public ContentPage getContentPage() { - return (ContentPage)page; + return (ContentPage) page; } public boolean isInvalidated() { return this.invalidated; } - + public void setInvalidated(boolean flag) { this.invalidated = flag; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PortletDecorationImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PortletDecorationImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PortletDecorationImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,16 +21,21 @@ import org.apache.jetspeed.util.Path; /** - * Default implementation of org.apache.jetspeed.decoration.PortletDecoration - * + * Default implementation of + * org.apache.jetspeed.decoration.PortletDecoration + * * @author Scott T. Weaver * @see org.apache.jetspeed.decoration.PortletDecoration */ -public class PortletDecorationImpl extends BaseDecoration implements PortletDecoration +public class PortletDecorationImpl extends BaseDecoration implements + PortletDecoration { - public PortletDecorationImpl(Properties config, ResourceValidator validator, Path basePath, Path baseClientPath, PathResolverCache cache) + + public PortletDecorationImpl(Properties config, + ResourceValidator validator, Path basePath, Path baseClientPath, + PathResolverCache cache) { - super(config, validator, basePath, baseClientPath, cache); + super(config, validator, basePath, baseClientPath, cache); } public String getTemplate() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PrintSoloDecoratorActionsFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PrintSoloDecoratorActionsFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/PrintSoloDecoratorActionsFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.decoration; import java.util.ArrayList; @@ -31,17 +31,24 @@ import org.apache.jetspeed.security.SecurityAccessController; import org.apache.pluto.om.window.PortletWindow; -public class PrintSoloDecoratorActionsFactory extends AbstractDecoratorActionsFactory +public class PrintSoloDecoratorActionsFactory extends + AbstractDecoratorActionsFactory { - private static final DecoratorActionTemplate PRINT_MODE_TEMPLATE = new DecoratorActionTemplate(JetspeedActions.PRINT_MODE); - private static final DecoratorActionTemplate SOLO_ACTION_TEMPLATE = new DecoratorActionTemplate(JetspeedActions.SOLO_STATE); - + + private static final DecoratorActionTemplate PRINT_MODE_TEMPLATE = new DecoratorActionTemplate( + JetspeedActions.PRINT_MODE); + + private static final DecoratorActionTemplate SOLO_ACTION_TEMPLATE = new DecoratorActionTemplate( + JetspeedActions.SOLO_STATE); + private final List supportedActions; + private final List supportedSoloActions; - + public PrintSoloDecoratorActionsFactory() { - ArrayList list = new ArrayList(JetspeedActions.getStandardPortletModes()); + ArrayList list = new ArrayList(JetspeedActions + .getStandardPortletModes()); list.add(JetspeedActions.PRINT_MODE); list.addAll(JetspeedActions.getStandardWindowStates()); list.add(JetspeedActions.SOLO_STATE); @@ -51,43 +58,54 @@ supportedSoloActions = Collections.unmodifiableList(list); } - public List getSupportedActions(RequestContext rc, PortletApplication pa, PortletWindow pw, PortletMode cm, - WindowState ws, Decoration decoration) + public List getSupportedActions(RequestContext rc, PortletApplication pa, + PortletWindow pw, PortletMode cm, WindowState ws, + Decoration decoration) { // don't support any window state actions when in "solo" state - return JetspeedActions.SOLO_STATE.equals(ws) ? supportedSoloActions : supportedActions; + return JetspeedActions.SOLO_STATE.equals(ws) ? supportedSoloActions + : supportedActions; } - - public List getDecoratorActions(RequestContext rc, PortletApplication pa, PortletWindow pw, PortletMode pm, - WindowState ws, Decoration decoration, List actionTemplates, - PortletDefinitionComposite portlet, ContentFragment fragment, SecurityAccessController accessController) + + public List getDecoratorActions(RequestContext rc, PortletApplication pa, + PortletWindow pw, PortletMode pm, WindowState ws, + Decoration decoration, List actionTemplates, + PortletDefinitionComposite portlet, ContentFragment fragment, + SecurityAccessController accessController) { int printModeIndex = actionTemplates.indexOf(PRINT_MODE_TEMPLATE); int soloStateIndex = actionTemplates.indexOf(SOLO_ACTION_TEMPLATE); - - if ( printModeIndex != -1 && soloStateIndex != -1 ) + + if (printModeIndex != -1 && soloStateIndex != -1) { // merge "solo" state with "print" mode - DecoratorActionTemplate soloStateTemplate = (DecoratorActionTemplate)actionTemplates.remove(soloStateIndex); - DecoratorActionTemplate printActionTemplate = (DecoratorActionTemplate)actionTemplates.get(printModeIndex); + DecoratorActionTemplate soloStateTemplate = (DecoratorActionTemplate) actionTemplates + .remove(soloStateIndex); + DecoratorActionTemplate printActionTemplate = (DecoratorActionTemplate) actionTemplates + .get(printModeIndex); printActionTemplate.setState(soloStateTemplate.getState()); - printActionTemplate.setCustomState((soloStateTemplate.getCustomState())); + printActionTemplate.setCustomState((soloStateTemplate + .getCustomState())); } - else if ( soloStateIndex != -1 ) + else if (soloStateIndex != -1) { // don't provide "solo" action separately without "print" mode actionTemplates.remove(soloStateIndex); } // else if (printModeIndex != -1) - // support switching to different modes once in "solo" state, even back to "print" - return super.getDecoratorActions(rc,pa,pw,pm,ws,decoration,actionTemplates, portlet, fragment, accessController); + // support switching to different modes once in "solo" state, even back + // to "print" + return super.getDecoratorActions(rc, pa, pw, pm, ws, decoration, + actionTemplates, portlet, fragment, accessController); } - - protected DecoratorAction createAction(RequestContext rc, PortletWindow pw, Decoration decoration, - DecoratorActionTemplate template) + + protected DecoratorAction createAction(RequestContext rc, PortletWindow pw, + Decoration decoration, DecoratorActionTemplate template) { - DecoratorAction action = super.createAction(rc,pw,decoration,template); - if ( template.getState() != null && JetspeedActions.SOLO_STATE.equals(template.getState())) + DecoratorAction action = super.createAction(rc, pw, decoration, + template); + if (template.getState() != null + && JetspeedActions.SOLO_STATE.equals(template.getState())) { // "solo" opens in a new popup winodw action.setTarget("_blank"); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/caches/HashMapPathResolverCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/caches/HashMapPathResolverCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/caches/HashMapPathResolverCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,18 +21,18 @@ import org.apache.jetspeed.decoration.PathResolverCache; - /** - * Uses a java.util.HashMap to cache previously located - * resources pathes. + * Uses a java.util.HashMap to cache previously located resources + * pathes. * * @author Scott T. Weaver - * + * */ public class HashMapPathResolverCache implements PathResolverCache { + protected Map cache; - + public HashMapPathResolverCache() { this.cache = new HashMap(); @@ -55,7 +55,7 @@ public void clear() { - cache.clear(); + cache.clear(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/caches/NoCachePathResolverCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/caches/NoCachePathResolverCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/caches/NoCachePathResolverCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,7 +22,7 @@ * A non-caching cache :) * * @author Scott T. Weaver - * + * */ public class NoCachePathResolverCache implements PathResolverCache { @@ -46,7 +46,7 @@ public void clear() { - // Does nothing + // Does nothing } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/caches/SessionPathResolverCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/caches/SessionPathResolverCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/caches/SessionPathResolverCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,24 +25,28 @@ import org.apache.jetspeed.decoration.PathResolverCache; /** - * Extends the + * Extends the * * @author Scott T. Weaver - * + * */ -public class SessionPathResolverCache extends HashMapPathResolverCache implements PathResolverCache +public class SessionPathResolverCache extends HashMapPathResolverCache + implements PathResolverCache { + public SessionPathResolverCache(HttpSession session) { - cache = (Map) session.getAttribute(PortalReservedParameters.RESOVLER_CACHE_ATTR); - - if(cache == null) + cache = (Map) session + .getAttribute(PortalReservedParameters.RESOVLER_CACHE_ATTR); + + if (cache == null) { cache = new HashMap(); - session.setAttribute(PortalReservedParameters.RESOVLER_CACHE_ATTR, cache); + session.setAttribute(PortalReservedParameters.RESOVLER_CACHE_ATTR, + cache); } } - + public void clear() { cache.clear(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/validators/ClasspathResourceValidator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/validators/ClasspathResourceValidator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/validators/ClasspathResourceValidator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,21 +19,22 @@ import org.apache.jetspeed.decoration.ResourceValidator; /** - * This implementation uses ClassLoader.getResource() to - * validate the existence of a resource. + * This implementation uses ClassLoader.getResource() to validate + * the existence of a resource. * * @author Scott T. Weaver - * + * */ public class ClasspathResourceValidator implements ResourceValidator { + private ClassLoader classLoader; - + public ClasspathResourceValidator(ClassLoader classLoader) { this.classLoader = classLoader; } - + public ClasspathResourceValidator() { this(ClasspathResourceValidator.class.getClassLoader()); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/validators/WebApplicationResourceValidator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/validators/WebApplicationResourceValidator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/decoration/validators/WebApplicationResourceValidator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,16 +24,17 @@ import org.springframework.web.context.ServletContextAware; /** - * This implementation uses ServletContext.getResource() - * to verify the existence of a resource. + * This implementation uses ServletContext.getResource() to + * verify the existence of a resource. * * @author Scott T. Weaver - * + * */ -public class WebApplicationResourceValidator implements ResourceValidator, ServletContextAware +public class WebApplicationResourceValidator implements ResourceValidator, + ServletContextAware { + private ServletContext servletContext; - public boolean resourceExists(String path) { @@ -43,17 +44,17 @@ } catch (MalformedURLException e) { - IllegalArgumentException iae = new IllegalArgumentException(path+" is not a valid path."); + IllegalArgumentException iae = new IllegalArgumentException(path + + " is not a valid path."); iae.initCause(e); - throw iae; + throw iae; } } - public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; - + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/DeployDecoratorEventListener.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/DeployDecoratorEventListener.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/DeployDecoratorEventListener.java 2008-05-16 01:54:54 UTC (rev 940) @@ -40,14 +40,18 @@ *

        * * @author Scott T. Weaver - * @version $Id: DeployDecoratorEventListener.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: DeployDecoratorEventListener.java 516448 2007-03-09 16:25:47Z + * ate $ */ public class DeployDecoratorEventListener implements DeploymentEventListener { + protected static final Log log = LogFactory.getLog("deployment"); - protected String deployToDir; - public DeployDecoratorEventListener(String deployToDir) throws FileNotFoundException + protected String deployToDir; + + public DeployDecoratorEventListener(String deployToDir) + throws FileNotFoundException { File checkFile = new File(deployToDir); if (checkFile.exists()) @@ -56,18 +60,20 @@ { this.deployToDir = checkFile.getCanonicalPath(); } - catch (IOException e) {} + catch (IOException e) + { + } } else { - throw new FileNotFoundException("The deployment directory, " + checkFile.getAbsolutePath() - + ", does not exist"); + throw new FileNotFoundException("The deployment directory, " + + checkFile.getAbsolutePath() + ", does not exist"); } } public void initialize() { - // nothing to do + // nothing to do } /** @@ -82,27 +88,19 @@ public void invokeDeploy(DeploymentEvent event) throws DeploymentException { String fileName = event.getName(); - if (!fileName.endsWith(".jar") && !fileName.endsWith(".zip")) - { - return; - } + if (!fileName.endsWith(".jar") && !fileName.endsWith(".zip")) { return; } // get decorator configuration if available PropertiesConfiguration conf = getDecoratorConfiguration(event); // silently return if configuration not available, (assumes // probably not a decorator) - if (conf == null) - { - return; - } + if (conf == null) { return; } // process decorator by id String id = conf.getString("id"); - if (id == null) - { - throw new DeploymentException("Unable to deploy decorator, \"id\" attribute not defined in configuration"); - } - + if (id == null) { throw new DeploymentException( + "Unable to deploy decorator, \"id\" attribute not defined in configuration"); } + log.info("Found decorator deployment archive " + id); try @@ -121,7 +119,8 @@ // redeploy/deploy decorator w/o META_INF jar metadata log.info("Deploying decorator " + id + " to " + deployPath); - JarExpander.expand(event.getDeploymentObject().getFile(), deployPathFile); + JarExpander.expand(event.getDeploymentObject().getFile(), + deployPathFile); File metaInf = new File(deployPathFile, "META-INF"); if (metaInf.exists()) { @@ -141,33 +140,41 @@ // deploy to locale specific location File deployToPathFile = new File(baseDeployPath - + localeDeployPathFile.getPath().substring(deployPath.length()) - + File.separator + id); - log.info("Deploying locale specific decorator component to " + deployToPathFile.getPath()); + + localeDeployPathFile.getPath().substring( + deployPath.length()) + File.separator + id); + log.info("Deploying locale specific decorator component to " + + deployToPathFile.getPath()); deployToPathFile.mkdirs(); // deploy decorator components by moving from deployed decorator - File[] filesToDeploy = localeDeployPathFile.listFiles(new FileFilter() - { - public boolean accept(File pathname) - { - return !localeSpecificDeployPathsList.contains(pathname); - } - }); + File[] filesToDeploy = localeDeployPathFile + .listFiles(new FileFilter() + { + + public boolean accept(File pathname) + { + return !localeSpecificDeployPathsList + .contains(pathname); + } + }); for (int i = 0; (i < filesToDeploy.length); i++) { - filesToDeploy[i].renameTo(new File(deployToPathFile, filesToDeploy[i].getName())); + filesToDeploy[i].renameTo(new File(deployToPathFile, + filesToDeploy[i].getName())); } } // cleanup locale specific deployment directories - Iterator cleanupDeployPathsIter = localeSpecificDeployPathsList.iterator(); + Iterator cleanupDeployPathsIter = localeSpecificDeployPathsList + .iterator(); while (cleanupDeployPathsIter.hasNext()) { - File cleanupLocaleDeployPathFile = (File) cleanupDeployPathsIter.next(); + File cleanupLocaleDeployPathFile = (File) cleanupDeployPathsIter + .next(); if (cleanupLocaleDeployPathFile.exists()) { - DirectoryHelper cleanup = new DirectoryHelper(cleanupLocaleDeployPathFile); + DirectoryHelper cleanup = new DirectoryHelper( + cleanupLocaleDeployPathFile); cleanup.remove(); cleanup.close(); } @@ -196,31 +203,40 @@ public void invokeUndeploy(File deployPathFile) throws DeploymentException { - if (deployPathFile == null || !deployPathFile.exists() || - !deployPathFile.isDirectory() || deployPathFile.getParentFile() == null || - !deployToDir.equals(deployPathFile.getParentFile().getParent())) - { - throw new DeploymentException("Cannot undeploy decorator at " + deployPathFile + ": invalid decorator path"); - } + if (deployPathFile == null + || !deployPathFile.exists() + || !deployPathFile.isDirectory() + || deployPathFile.getParentFile() == null + || !deployToDir.equals(deployPathFile.getParentFile() + .getParent())) { throw new DeploymentException( + "Cannot undeploy decorator at " + deployPathFile + + ": invalid decorator path"); } String id = deployPathFile.getName(); try { // undeploy decorator - log.info("Undeploying decorator " + id + " at " + deployPathFile.getAbsolutePath()); + log.info("Undeploying decorator " + id + " at " + + deployPathFile.getAbsolutePath()); // detect language/country localized decorator components - final List localeSpecificDeployPathsList = getLocaleSpecificDeployPaths(deployPathFile.getParentFile()); + final List localeSpecificDeployPathsList = getLocaleSpecificDeployPaths(deployPathFile + .getParentFile()); - // undeploy individual locale specific decorator components depth first + // undeploy individual locale specific decorator components depth + // first for (int i = localeSpecificDeployPathsList.size() - 1; i > -1; i--) { - File localeDeployPathFile = new File((File) localeSpecificDeployPathsList.get(i), id); + File localeDeployPathFile = new File( + (File) localeSpecificDeployPathsList.get(i), id); if (localeDeployPathFile.exists()) { - log.info("Undeploying locale specific decorator component at " + localeDeployPathFile.getPath()); - DirectoryHelper cleanup = new DirectoryHelper(localeDeployPathFile); + log + .info("Undeploying locale specific decorator component at " + + localeDeployPathFile.getPath()); + DirectoryHelper cleanup = new DirectoryHelper( + localeDeployPathFile); cleanup.remove(); cleanup.close(); localeDeployPathFile.getParentFile().delete(); @@ -236,7 +252,8 @@ } catch (Exception e) { - throw new DeploymentException("Error undeploying decorator " + id, e); + throw new DeploymentException("Error undeploying decorator " + id, + e); } } @@ -249,16 +266,15 @@ * @return configuration * @throws DeploymentException */ - private PropertiesConfiguration getDecoratorConfiguration(DeploymentEvent event) throws DeploymentException + private PropertiesConfiguration getDecoratorConfiguration( + DeploymentEvent event) throws DeploymentException { InputStream stream = null; try { - if (event.getDeploymentObject() == null) - { - return null; - } - stream = event.getDeploymentObject().getConfiguration("decorator.properties"); + if (event.getDeploymentObject() == null) { return null; } + stream = event.getDeploymentObject().getConfiguration( + "decorator.properties"); if (stream == null) { return null; @@ -272,7 +288,9 @@ } catch (Exception e1) { - throw new DeploymentException("Error reading decorator.properties from " + event.getPath(), e1); + throw new DeploymentException( + "Error reading decorator.properties from " + + event.getPath(), e1); } finally { @@ -306,7 +324,7 @@ { layoutType = "generic"; } - return deployToDir + File.separator + layoutType ; + return deployToDir + File.separator + layoutType; } /** @@ -321,28 +339,37 @@ { // detect language/country localized deploy paths List localeSpecificDeployPathsList = new ArrayList(); - File[] localeLanguageSpecificRoots = rootPath.listFiles(new FileFilter() - { - public boolean accept(File pathname) - { - // filter language code dirs, (assume length test is accurate enough) - return (pathname.isDirectory() && (pathname.getName().length() == 2)); - } - }); + File[] localeLanguageSpecificRoots = rootPath + .listFiles(new FileFilter() + { + + public boolean accept(File pathname) + { + // filter language code dirs, (assume length test is + // accurate enough) + return (pathname.isDirectory() && (pathname.getName() + .length() == 2)); + } + }); for (int i = 0; (i < localeLanguageSpecificRoots.length); i++) { localeSpecificDeployPathsList.add(localeLanguageSpecificRoots[i]); - File[] localeCountrySpecificPaths = localeLanguageSpecificRoots[i].listFiles(new FileFilter() - { - public boolean accept(File pathname) - { - // filter country code dirs, (assume length test is accurate enough) - return (pathname.isDirectory() && (pathname.getName().length() == 2)); - } - }); + File[] localeCountrySpecificPaths = localeLanguageSpecificRoots[i] + .listFiles(new FileFilter() + { + + public boolean accept(File pathname) + { + // filter country code dirs, (assume length test is + // accurate enough) + return (pathname.isDirectory() && (pathname + .getName().length() == 2)); + } + }); for (int j = 0; (j < localeCountrySpecificPaths.length); j++) { - localeSpecificDeployPathsList.add(localeCountrySpecificPaths[j]); + localeSpecificDeployPathsList + .add(localeCountrySpecificPaths[j]); } } return localeSpecificDeployPathsList; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/DeployPortletAppEventListener.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/DeployPortletAppEventListener.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/DeployPortletAppEventListener.java 2008-05-16 01:54:54 UTC (rev 940) @@ -41,46 +41,61 @@ *

        * * @author Scott T. Weaver - * @version $Id: DeployPortletAppEventListener.java 548891 2007-06-20 02:24:37Z ate $ + * @version $Id: DeployPortletAppEventListener.java 548891 2007-06-20 02:24:37Z + * ate $ */ public class DeployPortletAppEventListener implements DeploymentEventListener { - protected static final Log log = LogFactory.getLog("deployment"); - private String webAppDir; - private int localPAPrefixLength; - private String localAppDir; - private String localAppStagingDir; - private boolean stripLoggers; + protected static final Log log = LogFactory.getLog("deployment"); + + private String webAppDir; + + private int localPAPrefixLength; + + private String localAppDir; + + private String localAppStagingDir; + + private boolean stripLoggers; + private PortletApplicationManagement pam; + /** * @param pam * @param webAppDir * @param localAppDir * @param stripLoggers - * @throws FileNotFoundException the webAppDir or localAppDir directory does not - * exist. + * @throws FileNotFoundException + * the webAppDir or localAppDir + * directory does not exist. */ - public DeployPortletAppEventListener(PortletApplicationManagement pam, PortletRegistry registry, String webAppDir, - String localAppDir, boolean stripLoggers) throws FileNotFoundException + public DeployPortletAppEventListener(PortletApplicationManagement pam, + PortletRegistry registry, String webAppDir, String localAppDir, + boolean stripLoggers) throws FileNotFoundException { - this(pam,registry,webAppDir,localAppDir,null,stripLoggers); + this(pam, registry, webAppDir, localAppDir, null, stripLoggers); } + /** * @param pam * @param webAppDir * @param localAppDir * @param localAppStagingDir * @param stripLoggers - * @throws FileNotFoundException the webAppDir or localAppDir directory does not - * exist. + * @throws FileNotFoundException + * the webAppDir or localAppDir + * directory does not exist. */ - public DeployPortletAppEventListener(PortletApplicationManagement pam, PortletRegistry registry, String webAppDir, - String localAppDir, String localAppStagingDir, boolean stripLoggers) throws FileNotFoundException + public DeployPortletAppEventListener(PortletApplicationManagement pam, + PortletRegistry registry, String webAppDir, String localAppDir, + String localAppStagingDir, boolean stripLoggers) + throws FileNotFoundException { this.pam = pam; this.stripLoggers = stripLoggers; - localPAPrefixLength = PortletApplicationManagement.LOCAL_PA_PREFIX.length(); + localPAPrefixLength = PortletApplicationManagement.LOCAL_PA_PREFIX + .length(); File webAppDirFile = new File(webAppDir); @@ -90,12 +105,16 @@ { this.webAppDir = webAppDirFile.getCanonicalPath(); } - catch (IOException e) {} + catch (IOException e) + { + } } else { - throw new FileNotFoundException("The depoyment directory for portlet applications \"" - + webAppDirFile.getAbsolutePath() + "\" does not exist."); + throw new FileNotFoundException( + "The depoyment directory for portlet applications \"" + + webAppDirFile.getAbsolutePath() + + "\" does not exist."); } File localAppDirFile = new File(localAppDir); @@ -103,33 +122,34 @@ { localAppDirFile.mkdirs(); } - else if (!localAppDirFile.isDirectory()) - { - throw new FileNotFoundException("Invalid depoyment directory for local portlet applications: \"" - + localAppDirFile.getAbsolutePath()); - } + else if (!localAppDirFile.isDirectory()) { throw new FileNotFoundException( + "Invalid depoyment directory for local portlet applications: \"" + + localAppDirFile.getAbsolutePath()); } try { this.localAppDir = localAppDirFile.getCanonicalPath(); } - catch (IOException e) {} - if ( localAppStagingDir != null ) + catch (IOException e) { + } + if (localAppStagingDir != null) + { File localAppStagingDirFile = new File(localAppStagingDir); - if ( !localAppStagingDirFile.exists() ) + if (!localAppStagingDirFile.exists()) { localAppStagingDirFile.mkdirs(); } - else if (!localAppStagingDirFile.isDirectory()) + else if (!localAppStagingDirFile.isDirectory()) { throw new FileNotFoundException( + "Invalid staging directory for local portlet applications: \"" + + localAppStagingDirFile.getAbsolutePath()); } + try { - throw new FileNotFoundException("Invalid staging directory for local portlet applications: \"" - + localAppStagingDirFile.getAbsolutePath()); + this.localAppStagingDir = localAppStagingDirFile + .getCanonicalPath(); } - try + catch (IOException e) { - this.localAppStagingDir = localAppStagingDirFile.getCanonicalPath(); } - catch (IOException e) {} } } @@ -137,12 +157,13 @@ { return webAppDir; } - + public void initialize() { // start deployed local pa File[] localApps = new File(localAppDir).listFiles(new FileFilter() { + public boolean accept(File pathname) { return pathname.isDirectory(); @@ -153,7 +174,7 @@ // Check for at least WEB-INF/portlet.xml // This will also prevent the src/webapps/WEB-INF/apps/CVS folder // to be seen as local app from testcases resulting in an exception - if ( ! new File(localApps[i],"WEB-INF/portlet.xml").exists() ) + if (!new File(localApps[i], "WEB-INF/portlet.xml").exists()) { log.warn("Not a local application " + localApps[i].getName()); } @@ -162,22 +183,26 @@ DirectoryHelper paDirHelper = new DirectoryHelper(localApps[i]); try { - pam.startLocalPortletApplication(localApps[i].getName(), paDirHelper, - createLocalPAClassLoader(localApps[i])); + pam + .startLocalPortletApplication(localApps[i] + .getName(), paDirHelper, + createLocalPAClassLoader(localApps[i])); } catch (Exception e) { - log.error("Failed to start Local Portlet Application " + localApps[i], e); + log.error("Failed to start Local Portlet Application " + + localApps[i], e); } } } } - + private String getEventParentPath(DeploymentEvent event) { try { - return event.getDeploymentObject().getFile().getParentFile().getCanonicalPath(); + return event.getDeploymentObject().getFile().getParentFile() + .getCanonicalPath(); } catch (IOException io) { @@ -198,9 +223,12 @@ String fileName = event.getName(); if (fileName.endsWith(".war")) { - if ((localAppStagingDir != null && getEventParentPath(event).equals(localAppStagingDir)) - || (fileName.length() > localPAPrefixLength && fileName.substring(0, localPAPrefixLength) - .equalsIgnoreCase(PortletApplicationManagement.LOCAL_PA_PREFIX))) + if ((localAppStagingDir != null && getEventParentPath(event) + .equals(localAppStagingDir)) + || (fileName.length() > localPAPrefixLength && fileName + .substring(0, localPAPrefixLength) + .equalsIgnoreCase( + PortletApplicationManagement.LOCAL_PA_PREFIX))) { deployLocalPortletApplication(event); } @@ -211,12 +239,14 @@ } } - protected void deployPortletApplication(DeploymentEvent event) throws DeploymentException + protected void deployPortletApplication(DeploymentEvent event) + throws DeploymentException { try { File toFile = new File(webAppDir, event.getName()); - new JetspeedDeploy(event.getPath(), toFile.getAbsolutePath(), stripLoggers); + new JetspeedDeploy(event.getPath(), toFile.getAbsolutePath(), + stripLoggers); event.setStatus(DeploymentStatus.STATUS_OKAY); } catch (Exception e) @@ -225,7 +255,8 @@ } } - protected void deployLocalPortletApplication(DeploymentEvent event) throws DeploymentException + protected void deployLocalPortletApplication(DeploymentEvent event) + throws DeploymentException { try { @@ -233,9 +264,11 @@ String appName = fileName.substring(0, fileName.length() - 4); pam.stopLocalPortletApplication(appName); File targetDir = new File(localAppDir, appName); - JarExpander.expand(event.getDeploymentObject().getFile(), targetDir); + JarExpander + .expand(event.getDeploymentObject().getFile(), targetDir); DirectoryHelper paDirHelper = new DirectoryHelper(targetDir); - pam.startLocalPortletApplication(appName, paDirHelper, createLocalPAClassLoader(targetDir)); + pam.startLocalPortletApplication(appName, paDirHelper, + createLocalPAClassLoader(targetDir)); event.setStatus(DeploymentStatus.STATUS_OKAY); } catch (Exception e) @@ -244,7 +277,8 @@ } } - protected ClassLoader createLocalPAClassLoader(File paDir) throws IOException + protected ClassLoader createLocalPAClassLoader(File paDir) + throws IOException { ArrayList urls = new ArrayList(); File webInfClasses = null; @@ -252,7 +286,8 @@ webInfClasses = new File(paDir, ("WEB-INF/classes/")); if (webInfClasses.exists()) { - log.info("Adding " + webInfClasses.toURL() + " to class path for Local PA " + paDir.getName()); + log.info("Adding " + webInfClasses.toURL() + + " to class path for Local PA " + paDir.getName()); urls.add(webInfClasses.toURL()); } @@ -265,11 +300,13 @@ for (int i = 0; i < jars.length; i++) { File jar = jars[i]; - log.info("Adding " + jar.toURL() + " to class path for Local PA " + paDir.getName()); + log.info("Adding " + jar.toURL() + + " to class path for Local PA " + paDir.getName()); urls.add(jar.toURL()); } } - return new URLClassLoader((URL[]) urls.toArray(new URL[urls.size()]), getClass().getClassLoader()); + return new URLClassLoader((URL[]) urls.toArray(new URL[urls.size()]), + getClass().getClassLoader()); } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/DeploymentEventImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/DeploymentEventImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/DeploymentEventImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,7 +19,6 @@ import org.apache.jetspeed.deployment.DeploymentEvent; import org.apache.jetspeed.deployment.DeploymentObject; - /** *

        * DeploymentEventImpl @@ -27,36 +26,39 @@ * * @author Scott T. Weaver * @version $Id: DeploymentEventImpl.java 517124 2007-03-12 08:10:25Z ate $ - * + * */ public class DeploymentEventImpl implements DeploymentEvent { - private DeploymentObject handler; - private int status = STATUS_EVAL; - protected String name; - protected String path; - - public DeploymentEventImpl(DeploymentObject handler) - { - super(); - this.handler = handler; - this.name = handler.getName(); - this.path = handler.getPath(); - } - - public DeploymentEventImpl(String name, String path) - { - super(); - this.name = name; - this.path = path; - } + private DeploymentObject handler; + private int status = STATUS_EVAL; + + protected String name; + + protected String path; + + public DeploymentEventImpl(DeploymentObject handler) + { + super(); + this.handler = handler; + this.name = handler.getName(); + this.path = handler.getPath(); + } + + public DeploymentEventImpl(String name, String path) + { + super(); + this.name = name; + this.path = path; + } + /** * @see org.apache.jetspeed.deployment.DeploymentEvent#getDeploymentObject() */ public DeploymentObject getDeploymentObject() - { + { return handler; } @@ -80,7 +82,7 @@ *

        * getName *

        - * + * * @see org.apache.jetspeed.deployment.DeploymentEvent#getName() * @return */ @@ -88,11 +90,12 @@ { return name; } + /** *

        * getPath *

        - * + * * @see org.apache.jetspeed.deployment.DeploymentEvent#getPath() * @return */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/FileNotDeployableException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/FileNotDeployableException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/FileNotDeployableException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,10 +18,9 @@ import org.apache.jetspeed.deployment.DeploymentException; - /** * @author Scott T. Weaver - * + * * TODO To change the template for this generated type comment go to * * Thrown when attempting to deploy a file that cannot be deployed. @@ -41,7 +40,7 @@ /** * @param message */ - public FileNotDeployableException( String message ) + public FileNotDeployableException(String message) { super(message); // TODO Auto-generated constructor stub @@ -50,7 +49,7 @@ /** * @param nested */ - public FileNotDeployableException( Throwable nested ) + public FileNotDeployableException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -60,7 +59,7 @@ * @param msg * @param nested */ - public FileNotDeployableException( String msg, Throwable nested ) + public FileNotDeployableException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/JarExpander.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/JarExpander.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/JarExpander.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,18 +16,17 @@ */ package org.apache.jetspeed.deployment.impl; -import org.apache.jetspeed.util.DirectoryHelper; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; - import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; +import org.apache.jetspeed.util.DirectoryHelper; + /** * JarExpander * @@ -36,6 +35,7 @@ */ public class JarExpander { + public static void expand(File srcFile, File targetDir) throws IOException { if (targetDir.exists()) @@ -47,7 +47,7 @@ targetDir.mkdirs(); JarFile jarFile = new JarFile(srcFile); - + try { Enumeration entries = jarFile.entries(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/JettyDeployPortletAppEventListener.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/JettyDeployPortletAppEventListener.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/JettyDeployPortletAppEventListener.java 2008-05-16 01:54:54 UTC (rev 940) @@ -44,25 +44,36 @@ /** * @author Ate Douma - * @version $Id: JettyDeployPortletAppEventListener.java 549661 2007-06-22 01:24:32Z ate $ + * @version $Id: JettyDeployPortletAppEventListener.java 549661 2007-06-22 + * 01:24:32Z ate $ */ -public class JettyDeployPortletAppEventListener extends DeployPortletAppEventListener +public class JettyDeployPortletAppEventListener extends + DeployPortletAppEventListener { + private String jettyContextsDir; - - public JettyDeployPortletAppEventListener(PortletApplicationManagement pam, PortletRegistry registry, String webAppDir, String localAppDir, boolean stripLoggers, String jettyContextsDir) throws FileNotFoundException + + public JettyDeployPortletAppEventListener(PortletApplicationManagement pam, + PortletRegistry registry, String webAppDir, String localAppDir, + boolean stripLoggers, String jettyContextsDir) + throws FileNotFoundException { super(pam, registry, webAppDir, localAppDir, stripLoggers); initJettyContextsDir(jettyContextsDir); } - public JettyDeployPortletAppEventListener(PortletApplicationManagement pam, PortletRegistry registry, String webAppDir, String localAppDir, String localAppStagingDir, boolean stripLoggers, String jettyContextsDir) throws FileNotFoundException + public JettyDeployPortletAppEventListener(PortletApplicationManagement pam, + PortletRegistry registry, String webAppDir, String localAppDir, + String localAppStagingDir, boolean stripLoggers, + String jettyContextsDir) throws FileNotFoundException { - super(pam, registry, webAppDir, localAppDir, localAppStagingDir, stripLoggers); + super(pam, registry, webAppDir, localAppDir, localAppStagingDir, + stripLoggers); initJettyContextsDir(jettyContextsDir); } - - private void initJettyContextsDir(String jettyContextsDir) throws FileNotFoundException + + private void initJettyContextsDir(String jettyContextsDir) + throws FileNotFoundException { File jettyContextsDirFile = new File(jettyContextsDir); @@ -72,17 +83,21 @@ { this.jettyContextsDir = jettyContextsDirFile.getCanonicalPath(); } - catch (IOException e) {} + catch (IOException e) + { + } } else { throw new FileNotFoundException("The jetty contexts directory \"" - + jettyContextsDirFile.getAbsolutePath() + "\" does not exist."); + + jettyContextsDirFile.getAbsolutePath() + + "\" does not exist."); } } - protected void deployPortletApplication(DeploymentEvent event) throws DeploymentException - { + protected void deployPortletApplication(DeploymentEvent event) + throws DeploymentException + { try { String fileName = event.getName(); @@ -102,17 +117,18 @@ { context = getJettyContextTemplate(); } - updateJettyContext(appName, new File(getWebAppDir(), fileName).getAbsolutePath(), context); + updateJettyContext(appName, new File(getWebAppDir(), fileName) + .getAbsolutePath(), context); removeCurrentPA(appName); super.deployPortletApplication(event); - writeJettyContext(appName,context); + writeJettyContext(appName, context); } catch (Exception e) { throw new DeploymentException(e); } } - + protected void removeCurrentPA(String contextName) throws IOException { File warFile = new File(getWebAppDir(), contextName + ".war"); @@ -126,7 +142,7 @@ removeDir(warDir); } } - + protected boolean removeDir(File file) { if (file.isDirectory()) @@ -135,32 +151,31 @@ for (int i = 0; i < children.length; i++) { boolean success = removeDir(new File(file, children[i])); - if (!success) - { - return false; - } + if (!success) { return false; } } } // The directory is now empty so delete it OR it is a plain file - return file.delete(); + return file.delete(); } - - protected File getCurrentJettyContextFile(String contextName) throws IOException + + protected File getCurrentJettyContextFile(String contextName) + throws IOException { - File contextFile = new File(jettyContextsDir, contextName+".xml"); + File contextFile = new File(jettyContextsDir, contextName + ".xml"); if (contextFile.exists()) { - if (contextFile.isDirectory()) - { - throw new IOException("Cannot deploy application"+contextName+" as there already exists a directory in "+jettyContextsDir+" with the same name"); - } + if (contextFile.isDirectory()) { throw new IOException( + "Cannot deploy application" + contextName + + " as there already exists a directory in " + + jettyContextsDir + " with the same name"); } return contextFile; } return null; } - - protected Document getCurrentJettyContext(File contextFile) throws IOException + + protected Document getCurrentJettyContext(File contextFile) + throws IOException { InputStream source = null; try @@ -183,13 +198,14 @@ } } } - + protected Document getJettyContextTemplate() throws IOException { InputStream source = null; try { - source = getClass().getResourceAsStream("jetty/context-template.xml"); + source = getClass().getResourceAsStream( + "jetty/context-template.xml"); return parseJettyContext(source); } finally @@ -207,7 +223,7 @@ } } } - + protected Document getJettyContext(String fileName) throws IOException { JarFile jin = null; @@ -215,7 +231,7 @@ try { jin = new JarFile(fileName); - + ZipEntry src; Enumeration zipEntries = jin.entries(); while (zipEntries.hasMoreElements()) @@ -227,10 +243,10 @@ System.out.println("Found jetspeed-jetty-context.xml"); source = jin.getInputStream(src); return parseJettyContext(source); - } + } } return null; - } + } finally { if (source != null) @@ -258,22 +274,23 @@ } } } - - protected void updateJettyContext(String contextName, String warPath, Document context) + + protected void updateJettyContext(String contextName, String warPath, + Document context) { Element root = context.getRootElement(); Iterator iter = root.getChildren("Set").iterator(); boolean foundSetWar = false; boolean foundSetContextPath = false; boolean foundSetConfigurationClasses = false; - + while (iter.hasNext()) { - Element set = (Element)iter.next(); + Element set = (Element) iter.next(); String name = set.getAttribute("name").getName(); if (name.equals("contextPath")) { - set.setText("/"+contextName); + set.setText("/" + contextName); foundSetContextPath = true; } else if (name.equals("resourceBase")) @@ -289,39 +306,51 @@ { foundSetConfigurationClasses = true; } - } + } if (!foundSetContextPath) { - root.addContent(new Element("Set").setAttribute(new Attribute("name", "contextPath")).setText("/"+contextName)); + root.addContent(new Element("Set").setAttribute( + new Attribute("name", "contextPath")).setText( + "/" + contextName)); } if (!foundSetWar) { - root.addContent(new Element("Set").setAttribute(new Attribute("name", "war")).setText(warPath)); + root.addContent(new Element("Set").setAttribute( + new Attribute("name", "war")).setText(warPath)); } if (!foundSetConfigurationClasses) { - Element array = new Element("Array").setAttribute(new Attribute("type","java.lang.String")); - array.addContent(new Element("Item").setText("org.mortbay.jetty.webapp.WebInfConfiguration")); - array.addContent(new Element("Item").setText("org.mortbay.jetty.plus.webapp.EnvConfiguration")); - array.addContent(new Element("Item").setText("org.mortbay.jetty.plus.webapp.Configuration")); - array.addContent(new Element("Item").setText("org.mortbay.jetty.webapp.JettyWebXmlConfiguration")); - array.addContent(new Element("Item").setText("org.mortbay.jetty.webapp.TagLibConfiguration")); - root.addContent(new Element("Set").setAttribute(new Attribute("name", "configurationClasses")).setContent(array)); + Element array = new Element("Array").setAttribute(new Attribute( + "type", "java.lang.String")); + array.addContent(new Element("Item") + .setText("org.mortbay.jetty.webapp.WebInfConfiguration")); + array.addContent(new Element("Item") + .setText("org.mortbay.jetty.plus.webapp.EnvConfiguration")); + array.addContent(new Element("Item") + .setText("org.mortbay.jetty.plus.webapp.Configuration")); + array + .addContent(new Element("Item") + .setText("org.mortbay.jetty.webapp.JettyWebXmlConfiguration")); + array.addContent(new Element("Item") + .setText("org.mortbay.jetty.webapp.TagLibConfiguration")); + root.addContent(new Element("Set").setAttribute( + new Attribute("name", "configurationClasses")).setContent( + array)); } } - - protected void writeJettyContext(String contextName, Document context) throws IOException + + protected void writeJettyContext(String contextName, Document context) + throws IOException { - File contextFile = new File(jettyContextsDir, contextName+".xml"); - if (contextFile.exists()) - { - throw new IOException("Jetty context file "+contextFile.getAbsolutePath()+" found."); - } + File contextFile = new File(jettyContextsDir, contextName + ".xml"); + if (contextFile.exists()) { throw new IOException("Jetty context file " + + contextFile.getAbsolutePath() + " found."); } FileOutputStream output = null; try { output = new FileOutputStream(contextFile); - XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat()); + XMLOutputter xmlOutputter = new XMLOutputter(Format + .getPrettyFormat()); xmlOutputter.output(context, output); } finally @@ -340,20 +369,21 @@ } } - protected Document parseJettyContext(InputStream source) throws IOException + protected Document parseJettyContext(InputStream source) throws IOException { // Parse using the local dtds instead of remote dtds. This // allows to deploy the application offline SAXBuilder saxBuilder = new SAXBuilder(); saxBuilder.setEntityResolver(new EntityResolver() { - public InputSource resolveEntity(java.lang.String publicId, java.lang.String systemId) throws SAXException, - java.io.IOException + + public InputSource resolveEntity(java.lang.String publicId, + java.lang.String systemId) throws SAXException, + java.io.IOException { - if (systemId.equals("http://jetty.mortbay.org/configure.dtd")) - { - return new InputSource(getClass().getResourceAsStream("jetty/configure_6_0.dtd")); - } + if (systemId.equals("http://jetty.mortbay.org/configure.dtd")) { return new InputSource( + getClass().getResourceAsStream( + "jetty/configure_6_0.dtd")); } return null; } }); @@ -364,7 +394,8 @@ } catch (JDOMException e) { - IOException ioException = new IOException("Parse failure: "+e.getMessage()); + IOException ioException = new IOException("Parse failure: " + + e.getMessage()); ioException.fillInStackTrace(); throw ioException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/StandardDeploymentManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/StandardDeploymentManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/StandardDeploymentManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -48,38 +48,50 @@ */ public class StandardDeploymentManager implements DeploymentManager { + private static final FileFilter readmeIgnoringFileFilter = new FileFilter() { + public boolean accept(File file) { return !file.getName().equalsIgnoreCase("README.txt"); } }; - - protected Log log = LogFactory.getLog("deployment"); + + protected Log log = LogFactory.getLog("deployment"); + protected FileSystemScanner scanner; - protected PortletRegistry registry; - protected Collection deploymentListeners; - protected long scanningDelay; - protected String stagingDirectories; - protected File[] stagingDirectoriesAsFiles; - protected HashMap ignoredFiles; + protected PortletRegistry registry; + + protected Collection deploymentListeners; + + protected long scanningDelay; + + protected String stagingDirectories; + + protected File[] stagingDirectoriesAsFiles; + + protected HashMap ignoredFiles; + /** * @param stagingDirectories * @param scanningDelay * @param deploymentListeners */ - public StandardDeploymentManager(String stagingDirectories, long scanningDelay, Collection deploymentListeners) + public StandardDeploymentManager(String stagingDirectories, + long scanningDelay, Collection deploymentListeners) { this.scanningDelay = scanningDelay; this.stagingDirectories = stagingDirectories; - StringTokenizer dirTokenizer = new StringTokenizer(stagingDirectories, ","); + StringTokenizer dirTokenizer = new StringTokenizer(stagingDirectories, + ","); this.stagingDirectoriesAsFiles = new File[dirTokenizer.countTokens()]; int i = 0; while (dirTokenizer.hasMoreTokens()) { - this.stagingDirectoriesAsFiles[i] = new File(dirTokenizer.nextToken()); + this.stagingDirectoriesAsFiles[i] = new File(dirTokenizer + .nextToken()); i++; } @@ -107,9 +119,8 @@ { if (!stagingDirectoriesAsFiles[i].exists()) { - log - .error(stagingDirectoriesAsFiles[i].getAbsolutePath() - + " does not exist, auto deployment disabled."); + log.error(stagingDirectoriesAsFiles[i].getAbsolutePath() + + " does not exist, auto deployment disabled."); stop(); return; } @@ -126,8 +137,8 @@ { try { - scanner = new FileSystemScanner(Thread.currentThread().getThreadGroup(), - "Autodeployment File Scanner Thread"); + scanner = new FileSystemScanner(Thread.currentThread() + .getThreadGroup(), "Autodeployment File Scanner Thread"); scanner.setDaemon(true); // scanner.setContextClassLoader(Thread.currentThread().getContextClassLoader()); @@ -137,9 +148,10 @@ } catch (Exception e) { - log.warn( - "Unable to intialize Catalina Portlet Application Manager. Auto deployment will be disabled: " - + e.toString(), e); + log + .warn( + "Unable to intialize Catalina Portlet Application Manager. Auto deployment will be disabled: " + + e.toString(), e); stop(); return; @@ -148,7 +160,7 @@ else { log.info("Scanning delay set to " + scanningDelay - + " has disabled automatic scanning of staging directory."); + + " has disabled automatic scanning of staging directory."); } } @@ -167,8 +179,9 @@ scanner.safeStop(); } } - - public synchronized DeploymentStatus deploy(File aFile) throws DeploymentException + + public synchronized DeploymentStatus deploy(File aFile) + throws DeploymentException { DeploymentObject deploymentObject = new StandardDeploymentObject(aFile); DeploymentEvent event = null; @@ -179,14 +192,14 @@ } finally { - if ( deploymentObject != null ) + if (deploymentObject != null) { try { deploymentObject.close(); } catch (IOException e) - { + { } } } @@ -209,37 +222,45 @@ status = deploy(aFile); } catch (Exception e) - { + { de = e; } - - if ( status != null && status.getStatus() == DeploymentStatus.STATUS_OKAY ) + + if (status != null + && status.getStatus() == DeploymentStatus.STATUS_OKAY) { if (aFile.exists()) { - log.info("File: " + aFile.getAbsolutePath() + " deployed"); + log.info("File: " + aFile.getAbsolutePath() + + " deployed"); boolean result = aFile.delete(); if (!result) { - log.error("Failed to remove: " + aFile); + log.error("Failed to remove: " + aFile); } } } else { - if (status == null || status.getStatus() == DeploymentStatus.STATUS_EVAL) + if (status == null + || status.getStatus() == DeploymentStatus.STATUS_EVAL) { - log.warn("Unrecognized file " + aFile.getAbsolutePath()); + log + .warn("Unrecognized file " + + aFile.getAbsolutePath()); } - else if ( de != null ) + else if (de != null) { - log.error("Failure deploying " + aFile.getAbsolutePath(), de); + log.error("Failure deploying " + + aFile.getAbsolutePath(), de); } else { - log.error("Failure deploying " + aFile.getAbsolutePath()); + log.error("Failure deploying " + + aFile.getAbsolutePath()); } - ignoredFiles.put(aFile.getAbsolutePath(), new Long(aFile.lastModified())); + ignoredFiles.put(aFile.getAbsolutePath(), new Long(aFile + .lastModified())); } } } @@ -260,7 +281,8 @@ Iterator itr = deploymentListeners.iterator(); while (itr.hasNext()) { - DeploymentEventListener listener = (DeploymentEventListener) itr.next(); + DeploymentEventListener listener = (DeploymentEventListener) itr + .next(); listener.invokeDeploy(event); if (event.getStatus() != DeploymentStatus.STATUS_EVAL) { @@ -285,7 +307,8 @@ */ protected boolean ignoreFile(File aFile) { - Long previousModified = (Long) ignoredFiles.get(aFile.getAbsolutePath()); + Long previousModified = (Long) ignoredFiles + .get(aFile.getAbsolutePath()); if (previousModified != null) { if (previousModified.longValue() != aFile.lastModified()) @@ -312,7 +335,8 @@ ArrayList fileList = new ArrayList(); for (int i = 0; i < stagingDirectoriesAsFiles.length; i++) { - fileList.addAll(Arrays.asList(stagingDirectoriesAsFiles[i].listFiles(readmeIgnoringFileFilter))); + fileList.addAll(Arrays.asList(stagingDirectoriesAsFiles[i] + .listFiles(readmeIgnoringFileFilter))); } return (File[]) fileList.toArray(new File[fileList.size()]); @@ -323,7 +347,8 @@ private boolean started = true; - public FileSystemScanner(ThreadGroup threadGroup, String name) throws FileNotFoundException, IOException + public FileSystemScanner(ThreadGroup threadGroup, String name) + throws FileNotFoundException, IOException { super(threadGroup, name); setPriority(MIN_PRIORITY); @@ -334,7 +359,8 @@ */ public void run() { - // use a double scanningDelay at startup to give the App Server some time to wake up... + // use a double scanningDelay at startup to give the App Server some + // time to wake up... // see: http://issues.apache.org/jira/browse/JS2-261 try { @@ -346,7 +372,7 @@ // // autodeployment.delay=10000 // - //sleep(scanningDelay*2); + // sleep(scanningDelay*2); sleep(scanningDelay); } catch (InterruptedException e) @@ -368,7 +394,8 @@ } /** - * notifies a switch variable that exits the watcher's montior loop started in the run() method. + * notifies a switch variable that exits the watcher's montior loop + * started in the run() method. */ public void safeStop() { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/StandardDeploymentObject.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/StandardDeploymentObject.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/impl/StandardDeploymentObject.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,13 +34,16 @@ */ public class StandardDeploymentObject implements DeploymentObject { - protected File deploymentObject; + + protected File deploymentObject; + protected ZipFile zipFile; /** * @throws IOException */ - public StandardDeploymentObject(File deploymentObject) throws FileNotDeployableException + public StandardDeploymentObject(File deploymentObject) + throws FileNotDeployableException { if (verifyExtension(deploymentObject)) { @@ -48,8 +51,9 @@ } else { - throw new FileNotDeployableException("File type for " + deploymentObject.getName() - + " is not supported by StandardDeploymentObject."); + throw new FileNotDeployableException("File type for " + + deploymentObject.getName() + + " is not supported by StandardDeploymentObject."); } } @@ -85,10 +89,7 @@ { ZipFile zipFile = getZipFile(); ZipEntry entry = zipFile.getEntry(configPath); - if (entry != null) - { - return zipFile.getInputStream(entry); - } + if (entry != null) { return zipFile.getInputStream(entry); } return null; } @@ -139,7 +140,8 @@ if (dot != -1) { String ext = fileName.substring(dot); - return ext.equals(".war") || ext.equals(".jar") || ext.equals(".zip"); + return ext.equals(".war") || ext.equals(".jar") + || ext.equals(".zip"); } else { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/Entry.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/Entry.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/Entry.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * Created on Jan 13, 2004 * @@ -33,19 +33,21 @@ * * @author Scott T. Weaver * @version $Id: Entry.java 516881 2007-03-11 10:34:21Z ate $ - * + * */ public class Entry { - private String id; - private Map attributes; - - public Entry() - { - super(); - attributes = new HashMap(); - } + private String id; + + private Map attributes; + + public Entry() + { + super(); + attributes = new HashMap(); + } + /** * @return */ @@ -61,28 +63,29 @@ { id = string; } - + public Object getAttribute(String key) { - return attributes.get(key); + return attributes.get(key); } - + public void setAttribute(String key, Object value) { - attributes.put(key, value); + attributes.put(key, value); } /** * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) - { - if(obj != null && obj instanceof Entry) + { + if (obj != null && obj instanceof Entry) { - Entry entry = (Entry) obj; - return entry.getId() != null && getId() != null && getId().equals(entry.getId()); + Entry entry = (Entry) obj; + return entry.getId() != null && getId() != null + && getId().equals(entry.getId()); } - + return false; } @@ -90,15 +93,13 @@ * @see java.lang.Object#hashCode() */ public int hashCode() - { + { return toString().hashCode(); } public String toString() { - return getClass().toString().toString()+":"+getId(); + return getClass().toString().toString() + ":" + getId(); } - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/SimpleRegistry.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/SimpleRegistry.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/SimpleRegistry.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * Created on Jan 13, 2004 * @@ -29,50 +29,59 @@ * SimpleRegistry *

        *

        - * This is an interface for creating simple registry systems. A good example would be an - * in memory registry that gets populate at runtime and is lost on shutdown. + * This is an interface for creating simple registry systems. A good example + * would be an in memory registry that gets populate at runtime and is lost on + * shutdown. * * @author Scott T. Weaver * @version $Id: SimpleRegistry.java 516881 2007-03-11 10:34:21Z ate $ - * + * */ public interface SimpleRegistry { - /** - * Registers the entry. - * - * @throws java.lang.IllegalAgrumentException in entry is null or - * entry.getId() is null - * @throws org.apache.jetspeed.cps.simpleregistry if this entry is - * already registered. - * @param entry - */ - public void register(Entry entry) throws SimpleRegistryException; - - /** - * De-registers the entry - * @param entry - * @throws java.lang.IllegalAgrumentException in entry is null or - * entry.getId() is null - */ - public void deRegister(Entry entry); - - /** - * Verifies whether or not this entry is registered. - * @param entry - * - * @return boolean true is the entry is registered - * otherwise false. - * @throws java.lang.IllegalAgrumentException in entry is null or - * entry.getId() is null - */ - public boolean isRegistered(Entry entry); - - /** - * Provides a Cloolection of org.apache.jetspeed.cps.simpleregistry.Entry - * objects that are currently registered to this registery - * @return - */ - public Collection getRegistry(); + /** + * Registers the entry. + * + * @throws java.lang.IllegalAgrumentException + * in entry is null or entry.getId() + * is null + * @throws org.apache.jetspeed.cps.simpleregistry + * if this entry is already registered. + * @param entry + */ + public void register(Entry entry) throws SimpleRegistryException; + + /** + * De-registers the entry + * + * @param entry + * @throws java.lang.IllegalAgrumentException + * in entry is null or entry.getId() + * is null + */ + public void deRegister(Entry entry); + + /** + * Verifies whether or not this entry is registered. + * + * @param entry + * + * @return boolean true is the entry is + * registered otherwise false. + * @throws java.lang.IllegalAgrumentException + * in entry is null or entry.getId() + * is null + */ + public boolean isRegistered(Entry entry); + + /** + * Provides a Cloolection of + * org.apache.jetspeed.cps.simpleregistry.Entry objects that + * are currently registered to this registery + * + * @return + */ + public Collection getRegistry(); + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/SimpleRegistryException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/SimpleRegistryException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/SimpleRegistryException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * Created on Jan 13, 2004 * @@ -31,7 +31,7 @@ * * @author Scott T. Weaver * @version $Id: SimpleRegistryException.java 516881 2007-03-11 10:34:21Z ate $ - * + * */ public class SimpleRegistryException extends JetspeedException { @@ -41,7 +41,7 @@ */ public SimpleRegistryException() { - super(); + super(); } /** @@ -49,7 +49,7 @@ */ public SimpleRegistryException(String message) { - super(message); + super(message); } /** @@ -57,7 +57,7 @@ */ public SimpleRegistryException(Throwable nested) { - super(nested); + super(nested); } /** @@ -66,7 +66,7 @@ */ public SimpleRegistryException(String msg, Throwable nested) { - super(msg, nested); + super(msg, nested); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/impl/InMemoryRegistryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/impl/InMemoryRegistryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/deployment/simpleregistry/impl/InMemoryRegistryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * Created on Jan 13, 2004 * @@ -37,31 +37,33 @@ * * @author Scott T. Weaver * @version $Id: InMemoryRegistryImpl.java 516881 2007-03-11 10:34:21Z ate $ - * + * */ public class InMemoryRegistryImpl implements SimpleRegistry { - protected Map registry; - - public InMemoryRegistryImpl() - { - super(); - registry = new HashMap(); - } + protected Map registry; + + public InMemoryRegistryImpl() + { + super(); + registry = new HashMap(); + } + /** * @see org.apache.jetspeed.cps.simpleregistry.SimpleRegistry#register(org.apache.jetspeed.cps.simpleregistry.Entry) */ public void register(Entry entry) throws SimpleRegistryException { - checkArguments(entry); - if(!isRegistered(entry)) + checkArguments(entry); + if (!isRegistered(entry)) { - registry.put(entry.getId(), entry); + registry.put(entry.getId(), entry); } else { - throw new SimpleRegistryException(entry.getId()+" is already registered."); + throw new SimpleRegistryException(entry.getId() + + " is already registered."); } } @@ -80,8 +82,8 @@ * @see org.apache.jetspeed.cps.simpleregistry.SimpleRegistry#isRegistered(org.apache.jetspeed.cps.simpleregistry.Entry) */ public boolean isRegistered(Entry entry) - { - checkArguments(entry); + { + checkArguments(entry); return registry.containsKey(entry.getId()); } @@ -92,18 +94,14 @@ { return registry.values(); } - + protected void checkArguments(Entry entry) { - if(entry == null ) - { - throw new IllegalArgumentException("Entry cannot be null."); - } - - if(entry.getId() == null ) - { - throw new IllegalArgumentException("Entry.getId() cannot be null."); - } + if (entry == null) { throw new IllegalArgumentException( + "Entry cannot be null."); } + + if (entry.getId() == null) { throw new IllegalArgumentException( + "Entry.getId() cannot be null."); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/DesktopEncoderRedirectValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/DesktopEncoderRedirectValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/DesktopEncoderRedirectValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,72 +29,87 @@ /** * DesktopEncoderRedirect Valve * - * if request parameter encoder=desktop is NOT defined, - * redirect to same url with /desktop pipeline, - * otherwise, - * just invoke next valve + * if request parameter encoder=desktop is NOT defined, redirect to same url + * with /desktop pipeline, otherwise, just invoke next valve * - * Used by the /render pipeline (desktop-render-pipeline) to allow - * render requests that are not initiated via desktop javascript code to result - * in a page level navigation to the /desktop pipeline with the correct portlet rendering - * indicated in the original url. The encoder=desktop request parameter - * is used by desktop javascript code to indicate that the request is an "official" - * desktop ajax request. - * + * Used by the /render pipeline (desktop-render-pipeline) to allow render + * requests that are not initiated via desktop javascript code to result in a + * page level navigation to the /desktop pipeline with the correct portlet + * rendering indicated in the original url. The encoder=desktop request + * parameter is used by desktop javascript code to indicate that the request is + * an "official" desktop ajax request. + * * @author Steve Milek * @version $Id: $ */ public class DesktopEncoderRedirectValveImpl extends AbstractValve { - protected Log log = LogFactory.getLog(DesktopEncoderRedirectValveImpl.class); - + + protected Log log = LogFactory + .getLog(DesktopEncoderRedirectValveImpl.class); + private String desktopPipelinePath = null; + private String desktopRenderPipelinePath = null; - - public DesktopEncoderRedirectValveImpl( String desktopPipelinePath, String desktopRenderPipelinePath ) + + public DesktopEncoderRedirectValveImpl(String desktopPipelinePath, + String desktopRenderPipelinePath) { - if ( desktopPipelinePath == null || desktopPipelinePath.length() == 0 ) + if (desktopPipelinePath == null || desktopPipelinePath.length() == 0) desktopPipelinePath = JetspeedDesktop.DEFAULT_DESKTOP_PIPELINE_PATH; - if ( desktopPipelinePath.charAt( 0 ) != '/' ) + if (desktopPipelinePath.charAt(0) != '/') desktopPipelinePath = "/" + desktopPipelinePath; - if ( desktopPipelinePath.charAt( desktopPipelinePath.length() -1 ) != '/' ) + if (desktopPipelinePath.charAt(desktopPipelinePath.length() - 1) != '/') desktopPipelinePath = desktopPipelinePath + "/"; - if ( desktopRenderPipelinePath == null || desktopRenderPipelinePath.length() == 0 ) + if (desktopRenderPipelinePath == null + || desktopRenderPipelinePath.length() == 0) desktopRenderPipelinePath = JetspeedDesktop.DEFAULT_DESKTOP_RENDER_PIPELINE_PATH; - if ( desktopRenderPipelinePath.charAt( 0 ) != '/' ) + if (desktopRenderPipelinePath.charAt(0) != '/') desktopRenderPipelinePath = "/" + desktopRenderPipelinePath; - if ( desktopRenderPipelinePath.charAt( desktopRenderPipelinePath.length() -1 ) != '/' ) + if (desktopRenderPipelinePath + .charAt(desktopRenderPipelinePath.length() - 1) != '/') desktopRenderPipelinePath = desktopRenderPipelinePath + "/"; - + this.desktopPipelinePath = desktopPipelinePath; this.desktopRenderPipelinePath = desktopRenderPipelinePath; } - - public void invoke( RequestContext request, ValveContext context ) - throws PipelineException + + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { try - { - if ( request.getPortalURL() == null ) + { + if (request.getPortalURL() == null) { - String encoding = request.getRequestParameter(JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER); - if (encoding == null || ! encoding.equals(JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER_VALUE)) + String encoding = request + .getRequestParameter(JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER); + if (encoding == null + || !encoding + .equals(JetspeedDesktop.DESKTOP_ENCODER_REQUEST_PARAMETER_VALUE)) { // redirect to page url with render encoding - try + try { - String queryString = request.getRequest().getQueryString(); + String queryString = request.getRequest() + .getQueryString(); String location = request.getRequest().getRequestURI(); - if ( queryString != null && queryString.length() > 0 ) + if (queryString != null && queryString.length() > 0) location += "?" + queryString; - location = location.replaceAll( this.desktopRenderPipelinePath, this.desktopPipelinePath ); - //log.info( "DesktopEncoderRedirectValveImpl redirecting request-uri=" + request.getRequest().getRequestURI() + " location=" + location ); - request.getResponse().sendRedirect( location ); + location = location.replaceAll( + this.desktopRenderPipelinePath, + this.desktopPipelinePath); + // log.info( "DesktopEncoderRedirectValveImpl + // redirecting request-uri=" + + // request.getRequest().getRequestURI() + " location=" + + // location ); + request.getResponse().sendRedirect(location); } - catch (IOException ioe){} + catch (IOException ioe) + { + } return; - } + } } } catch (Exception e) @@ -102,7 +117,7 @@ throw new PipelineException(e); } // Pass control to the next Valve in the Pipeline - context.invokeNext( request ); + context.invokeNext(request); } public String toString() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/DesktopValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/DesktopValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/DesktopValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,21 +24,22 @@ /** * Desktop Valve - * + * * @author David Sean Taylor * @version $Id: $ */ public class DesktopValveImpl extends AbstractValve { + private JetspeedDesktop desktop; - + public DesktopValveImpl(JetspeedDesktop desktop) { this.desktop = desktop; } - - public void invoke( RequestContext request, ValveContext context ) - throws PipelineException + + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { try { @@ -48,7 +49,7 @@ { throw new PipelineException(e); } - context.invokeNext( request ); + context.invokeNext(request); } public String toString() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/JetspeedDesktopContextImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/JetspeedDesktopContextImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/JetspeedDesktopContextImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,45 +28,49 @@ import org.apache.jetspeed.request.RequestContext; /** - * Jetspeed Desktop - * + * Jetspeed Desktop + * * @author David Sean Taylor * @author Steve Milek * @version $Id: JetspeedDesktopContextImpl.java $ */ public class JetspeedDesktopContextImpl implements JetspeedDesktopContext { + // Jetspeed Request Context RequestContext context; - + // base portal url to override default url server info from servlet private BasePortalURL baseUrlAccess = null; - + private LayoutDecoration layoutDecoration; - + // default extension for layout templates private String defaultLayoutTemplateExtension; - - + // ... save generated portal urls to avoid duplicate effort private String portalBaseUrl; + private String portalUrl; - + private HeaderResource headerResource; - - public JetspeedDesktopContextImpl( RequestContext context, BasePortalURL baseUrlAccess, Theme theme, HeaderResource headerResource, String defaultLayoutTemplateExtension ) + + public JetspeedDesktopContextImpl(RequestContext context, + BasePortalURL baseUrlAccess, Theme theme, + HeaderResource headerResource, String defaultLayoutTemplateExtension) { - // String layoutDecorator, String layoutDecoratorRootPath, String resourceName + // String layoutDecorator, String layoutDecoratorRootPath, String + // resourceName this.context = context; this.baseUrlAccess = baseUrlAccess; this.layoutDecoration = theme.getPageLayoutDecoration(); this.headerResource = headerResource; this.defaultLayoutTemplateExtension = defaultLayoutTemplateExtension; } - - - // get portal urls - each of these methods is copied from HeaderResourceImpl.java - + + // get portal urls - each of these methods is copied from + // HeaderResourceImpl.java + /** * Portal base url ( e.g. http://localhost:8080/jetspeed ) * @@ -74,51 +78,55 @@ */ public String getPortalBaseUrl() { - if ( this.portalBaseUrl == null ) + if (this.portalBaseUrl == null) { - this.portalBaseUrl = HeaderResourceLib.getPortalBaseUrl( context, this.baseUrlAccess ); + this.portalBaseUrl = HeaderResourceLib.getPortalBaseUrl(context, + this.baseUrlAccess); } return this.portalBaseUrl; } - + /** * Portal base url ( e.g. http://localhost:8080/jetspeed ) * * @return portal base url */ - public String getPortalBaseUrl( boolean encode ) + public String getPortalBaseUrl(boolean encode) { String baseurl = getPortalBaseUrl(); - if ( ! encode ) + if (!encode) { return baseurl; } else { - return context.getResponse().encodeURL( baseurl ); + return context.getResponse().encodeURL(baseurl); } } - + /** - * Portal base url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/javascript/dojo/ ) + * Portal base url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/javascript/dojo/ ) * * @return portal base url with relativePath argument appended */ - public String getPortalResourceUrl( String relativePath ) + public String getPortalResourceUrl(String relativePath) { - return getPortalResourceUrl( relativePath, false ); + return getPortalResourceUrl(relativePath, false); } - + /** - * Portal base url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/javascript/dojo/ ) + * Portal base url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/javascript/dojo/ ) * * @return portal base url with relativePath argument appended */ - public String getPortalResourceUrl( String relativePath, boolean encode ) + public String getPortalResourceUrl(String relativePath, boolean encode) { - return HeaderResourceLib.getPortalResourceUrl( relativePath, getPortalBaseUrl(), encode, context ); + return HeaderResourceLib.getPortalResourceUrl(relativePath, + getPortalBaseUrl(), encode, context); } - + /** * Portal base servlet url ( e.g. http://localhost:8080/jetspeed/desktop/ ) * @@ -126,103 +134,111 @@ */ public String getPortalUrl() { - if ( this.portalUrl == null ) + if (this.portalUrl == null) { - this.portalUrl = HeaderResourceLib.getPortalUrl( getPortalBaseUrl(), context ); + this.portalUrl = HeaderResourceLib.getPortalUrl(getPortalBaseUrl(), + context); } return this.portalUrl; } - + /** * Portal base servlet url ( e.g. http://localhost:8080/jetspeed/desktop/ ) * * @return portal base servlet url */ - public String getPortalUrl( boolean encode ) + public String getPortalUrl(boolean encode) { - return getPortalUrl( null, encode ); + return getPortalUrl(null, encode); } - + /** - * Portal base servlet url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/desktop/default-page.psml ) + * Portal base servlet url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/desktop/default-page.psml ) * * @return portal base servlet url with relativePath argument appended */ - public String getPortalUrl( String relativePath ) + public String getPortalUrl(String relativePath) { - return getPortalUrl( relativePath, false ); + return getPortalUrl(relativePath, false); } - + /** - * Portal base servlet url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/desktop/default-page.psml ) + * Portal base servlet url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/desktop/default-page.psml ) * * @return portal base servlet url with relativePath argument appended */ - public String getPortalUrl( String relativePath, boolean encode ) + public String getPortalUrl(String relativePath, boolean encode) { - return HeaderResourceLib.getPortalResourceUrl( relativePath, getPortalUrl(), encode, context ); + return HeaderResourceLib.getPortalResourceUrl(relativePath, + getPortalUrl(), encode, context); } - + public String getLayoutDecorationName() { return layoutDecoration.getName(); } - + public String getLayoutTemplatePath() { - return getLayoutTemplatePath( null ); + return getLayoutTemplatePath(null); } - public String getLayoutTemplatePath( String layoutTemplateIdPropertyName ) + + public String getLayoutTemplatePath(String layoutTemplateIdPropertyName) { String id = null; - if ( layoutTemplateIdPropertyName != null ) + if (layoutTemplateIdPropertyName != null) { - id = layoutDecoration.getProperty( layoutTemplateIdPropertyName ); + id = layoutDecoration.getProperty(layoutTemplateIdPropertyName); } - - if ( id == null || id.length() == 0 ) + + if (id == null || id.length() == 0) { - id = layoutDecoration.getProperty( LAYOUT_TEMPLATE_ID_PROP ); + id = layoutDecoration.getProperty(LAYOUT_TEMPLATE_ID_PROP); } - - if ( id == null || id.length() == 0 ) + + if (id == null || id.length() == 0) { id = LAYOUT_TEMPLATE_ID_DEFAULT; } - - String ext = layoutDecoration.getProperty( LAYOUT_DESKTOP_TEMPLATE_EXTENSION_PROP ); - if ( ext == null ) - ext = layoutDecoration.getProperty( LAYOUT_TEMPLATE_EXTENSION_PROP ); - if ( ext == null ) + + String ext = layoutDecoration + .getProperty(LAYOUT_DESKTOP_TEMPLATE_EXTENSION_PROP); + if (ext == null) + ext = layoutDecoration.getProperty(LAYOUT_TEMPLATE_EXTENSION_PROP); + if (ext == null) { ext = this.defaultLayoutTemplateExtension; } - return layoutDecoration.getBasePath( id + ext ); + return layoutDecoration.getBasePath(id + ext); } - + public String getLayoutBasePath() { return layoutDecoration.getBasePath(); } - public String getLayoutBasePath( String relativePath ) + + public String getLayoutBasePath(String relativePath) { - return layoutDecoration.getBasePath( relativePath ); + return layoutDecoration.getBasePath(relativePath); } - + public String getLayoutBaseUrl() { - return getPortalResourceUrl( getLayoutBasePath(), false ); + return getPortalResourceUrl(getLayoutBasePath(), false); } - public String getLayoutBaseUrl( String relativePath ) + + public String getLayoutBaseUrl(String relativePath) { - return getPortalResourceUrl( getLayoutBasePath( relativePath ), false ); + return getPortalResourceUrl(getLayoutBasePath(relativePath), false); } - - public ResourceBundle getLayoutResourceBundle( Locale locale ) + + public ResourceBundle getLayoutResourceBundle(Locale locale) { - return layoutDecoration.getResourceBundle( locale, this.context ); + return layoutDecoration.getResourceBundle(locale, this.context); } - + public HeaderResource getHeaderResource() { return this.headerResource; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/JetspeedDesktopImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/JetspeedDesktopImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/desktop/impl/JetspeedDesktopImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,9 +18,9 @@ import java.io.IOException; import java.util.Iterator; +import java.util.Random; import java.util.ResourceBundle; import java.util.Set; -import java.util.Random; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; @@ -46,671 +46,1021 @@ /** * Desktop Valve - * + * * @author David Sean Taylor * @author Steve Milek * @version $Id: JetspeedDesktopImpl.java $ */ -public class JetspeedDesktopImpl implements JetspeedDesktop, ServletContextAware +public class JetspeedDesktopImpl implements JetspeedDesktop, + ServletContextAware { - private static final Log log = LogFactory.getLog( JetspeedDesktopImpl.class ); - - private final static String EOL = "\r\n"; // html eol - private final static String DOJO_CONFIG_LAYOUT_DECORATION_PATH_VAR_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + ".layoutDecorationPath"; - private final static String DOJO_CONFIG_LAYOUT_VAR_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + ".layoutName"; - private final static String DOJO_CONFIG_PORTLET_DECORATIONS_PATH_VAR_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + ".portletDecorationsPath"; - private final static String DOJO_CONFIG_PORTLET_DECORATIONS_ALLOWED_VAR_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + ".portletDecorationsAllowed"; - private final static String DOJO_CONFIG_PORTLET_DECORATIONS_CONFIG_VAR_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + ".portletDecorationsProperties"; - private final static String DOJO_CONFIG_ACTION_LABELS_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + ".desktopActionLabels"; - private final static String DOJO_CONFIG_LOADING_IMGPROPS_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + ".loadingImgProps"; - private final static String DOJO_CONFIG_PAGEEDITOR_LABELS_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + ".pageEditorLabels"; - private final static String DOJO_CONFIG_PAGEEDITOR_DIALOG_LABELS_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + ".pageEditorDialogLabels"; - private final static String DOJO_CONFIG_PAGEEDITOR_SETTINGS_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + ".pec"; - - private final static String[] DESKTOP_LOADING_PROPERTY_NAMES = new String[] - { "dir", "animated", "stepprefix", "stepextension", "steps" - }; - private final static String[] DESKTOP_LOADING_OUTPUT_PROPERTY_NAMES = new String[] - { "imgdir", "imganimated", "imgstepprefix", "imgstepextension", "imgsteps" - }; - private final static String[] DESKTOP_ACTION_RESOURCE_NAMES = new String[] - { "menu", "tile", "untile", "heightexpand", "heightnormal", - "restore", "removeportlet", "minimized", "maximized", "normal", - "help", "edit", "view", "print", "config", "edit_defaults", "about", - "addportlet", "editpage", - "movetiled", "moveuntiled", "loadpage", "loadpageeditor", - "loadportletrender", "loadportletaction", "loadportletupdate" - }; + + private static final Log log = LogFactory.getLog(JetspeedDesktopImpl.class); + + private final static String EOL = "\r\n"; // html eol + + private final static String DOJO_CONFIG_LAYOUT_DECORATION_PATH_VAR_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + + ".layoutDecorationPath"; + + private final static String DOJO_CONFIG_LAYOUT_VAR_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + + ".layoutName"; + + private final static String DOJO_CONFIG_PORTLET_DECORATIONS_PATH_VAR_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + + ".portletDecorationsPath"; + + private final static String DOJO_CONFIG_PORTLET_DECORATIONS_ALLOWED_VAR_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + + ".portletDecorationsAllowed"; + + private final static String DOJO_CONFIG_PORTLET_DECORATIONS_CONFIG_VAR_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + + ".portletDecorationsProperties"; + + private final static String DOJO_CONFIG_ACTION_LABELS_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + + ".desktopActionLabels"; + + private final static String DOJO_CONFIG_LOADING_IMGPROPS_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + + ".loadingImgProps"; + + private final static String DOJO_CONFIG_PAGEEDITOR_LABELS_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + + ".pageEditorLabels"; + + private final static String DOJO_CONFIG_PAGEEDITOR_DIALOG_LABELS_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + + ".pageEditorDialogLabels"; + + private final static String DOJO_CONFIG_PAGEEDITOR_SETTINGS_NAME = HeaderResource.HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + + ".pec"; + + private final static String[] DESKTOP_LOADING_PROPERTY_NAMES = new String[] + {"dir", "animated", "stepprefix", "stepextension", "steps"}; + + private final static String[] DESKTOP_LOADING_OUTPUT_PROPERTY_NAMES = new String[] + {"imgdir", "imganimated", "imgstepprefix", "imgstepextension", "imgsteps"}; + + private final static String[] DESKTOP_ACTION_RESOURCE_NAMES = new String[] + {"menu", "tile", "untile", "heightexpand", "heightnormal", "restore", + "removeportlet", "minimized", "maximized", "normal", "help", + "edit", "view", "print", "config", "edit_defaults", "about", + "addportlet", "editpage", "movetiled", "moveuntiled", "loadpage", + "loadpageeditor", "loadportletrender", "loadportletaction", + "loadportletupdate"}; + private final static String[] DESKTOP_PAGEEDITOR_RESOURCE_NAMES = new String[] - { "title", "changelayout", "changepagelayouttheme", "changepageportlettheme", - "newpage", "deletepage", "addlayout", "addportlet", "columnsizes", - "deletelayout", "movemode", "movemode_exit", "changeportlettheme" - }; + {"title", "changelayout", "changepagelayouttheme", + "changepageportlettheme", "newpage", "deletepage", "addlayout", + "addportlet", "columnsizes", "deletelayout", "movemode", + "movemode_exit", "changeportlettheme"}; + private final static String[] DESKTOP_PAGEEDITOR_DIALOG_RESOURCE_NAMES = new String[] - { "columnsizes", "columnsizes_column1", "columnsizes_column2", "columnsizes_column3", - "columnsizes_column4", "columnsizes_column5", "newpage", "newpage_name", - "newpage_title", "newpage_titleshort", "deletepage", "deletelayout", - "removeportlet", "ok", "cancel", "yes", "no" - }; - + {"columnsizes", "columnsizes_column1", "columnsizes_column2", + "columnsizes_column3", "columnsizes_column4", + "columnsizes_column5", "newpage", "newpage_name", "newpage_title", + "newpage_titleshort", "deletepage", "deletelayout", + "removeportlet", "ok", "cancel", "yes", "no"}; + private final static String DESKTOP_LOADING_NAME_PREFIX = "desktop.loading."; + private final static String DESKTOP_ACTION_NAME_PREFIX = "desktop.action."; + private final static String DESKTOP_PAGEEDITOR_NAME_PREFIX = "desktop.pageeditor."; - - private final static String DESKTOP_LOADING_IMG_NAME_PREFIX = DESKTOP_LOADING_NAME_PREFIX + "img."; - private final static String DESKTOP_ACTION_RESOURCE_NAME_PREFIX = DESKTOP_ACTION_NAME_PREFIX + "labels."; - private final static String DESKTOP_PAGEEDITOR_RESOURCE_NAME_PREFIX = DESKTOP_PAGEEDITOR_NAME_PREFIX + "labels."; - private final static String DESKTOP_PAGEEDITOR_DIALOG_RESOURCE_NAME_PREFIX = DESKTOP_PAGEEDITOR_NAME_PREFIX + "dialog.labels."; - - private final static String DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DECORATOR_EDITABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + "page.layout.decorator.editable"; + + private final static String DESKTOP_LOADING_IMG_NAME_PREFIX = DESKTOP_LOADING_NAME_PREFIX + + "img."; + + private final static String DESKTOP_ACTION_RESOURCE_NAME_PREFIX = DESKTOP_ACTION_NAME_PREFIX + + "labels."; + + private final static String DESKTOP_PAGEEDITOR_RESOURCE_NAME_PREFIX = DESKTOP_PAGEEDITOR_NAME_PREFIX + + "labels."; + + private final static String DESKTOP_PAGEEDITOR_DIALOG_RESOURCE_NAME_PREFIX = DESKTOP_PAGEEDITOR_NAME_PREFIX + + "dialog.labels."; + + private final static String DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DECORATOR_EDITABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + + "page.layout.decorator.editable"; + private final static String DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DECORATOR_EDITABLE_DEFAULT = "true"; - private final static String DESKTOP_PAGEEDITOR_LAYOUT_NAME_EDITABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + "layout.name.editable"; + + private final static String DESKTOP_PAGEEDITOR_LAYOUT_NAME_EDITABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + + "layout.name.editable"; + private final static String DESKTOP_PAGEEDITOR_LAYOUT_NAME_EDITABLE_DEFAULT = "true"; - - private final static String DESKTOP_PAGEEDITOR_LAYOUT_COLUMNSIZE_EDITABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + "layout.columnsize.editable"; + + private final static String DESKTOP_PAGEEDITOR_LAYOUT_COLUMNSIZE_EDITABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + + "layout.columnsize.editable"; + private final static String DESKTOP_PAGEEDITOR_LAYOUT_COLUMNSIZE_EDITABLE_DEFAULT = "true"; - - private final static String DESKTOP_PAGEEDITOR_PAGE_ADD_ENABLED = DESKTOP_PAGEEDITOR_NAME_PREFIX + "page.add.enabled"; + + private final static String DESKTOP_PAGEEDITOR_PAGE_ADD_ENABLED = DESKTOP_PAGEEDITOR_NAME_PREFIX + + "page.add.enabled"; + private final static String DESKTOP_PAGEEDITOR_PAGE_ADD_ENABLED_DEFAULT = "true"; - private final static String DESKTOP_PAGEEDITOR_PORTLET_ADD_ENABLED = DESKTOP_PAGEEDITOR_NAME_PREFIX + "portlet.add.enabled"; + + private final static String DESKTOP_PAGEEDITOR_PORTLET_ADD_ENABLED = DESKTOP_PAGEEDITOR_NAME_PREFIX + + "portlet.add.enabled"; + private final static String DESKTOP_PAGEEDITOR_PORTLET_ADD_ENABLED_DEFAULT = "true"; - private final static String DESKTOP_PAGEEDITOR_PAGE_PORTLET_DECORATOR_EDITABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + "page.portlet.decorator.editable"; + + private final static String DESKTOP_PAGEEDITOR_PAGE_PORTLET_DECORATOR_EDITABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + + "page.portlet.decorator.editable"; + private final static String DESKTOP_PAGEEDITOR_PAGE_PORTLET_DECORATOR_EDITABLE_DEFAULT = "true"; - private final static String DESKTOP_PAGEEDITOR_PORTLET_DECORATOR_EDITABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + "portlet.decorator.editable"; + + private final static String DESKTOP_PAGEEDITOR_PORTLET_DECORATOR_EDITABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + + "portlet.decorator.editable"; + private final static String DESKTOP_PAGEEDITOR_PORTLET_DECORATOR_EDITABLE_DEFAULT = "true"; - - private final static String DESKTOP_PAGEEDITOR_MOVEMODE_ISDEFAULT = DESKTOP_PAGEEDITOR_NAME_PREFIX + "movemode.isdefault"; + + private final static String DESKTOP_PAGEEDITOR_MOVEMODE_ISDEFAULT = DESKTOP_PAGEEDITOR_NAME_PREFIX + + "movemode.isdefault"; + private final static String DESKTOP_PAGEEDITOR_MOVEMODE_ISDEFAULT_DEFAULT = "true"; - private final static String DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + "layout.noactions.editable"; + + private final static String DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + + "layout.noactions.editable"; + private final static String DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITABLE_DEFAULT = "false"; - private final static String DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_TOPLEVEL_MOVEABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + "layout.noactions.toplevel.moveable"; + + private final static String DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_TOPLEVEL_MOVEABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + + "layout.noactions.toplevel.moveable"; + private final static String DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_TOPLEVEL_MOVEABLE_DEFAULT = "false"; - private final static String DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_COLUMNSIZE_EDITABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + "layout.noactions.columnsize.editable"; + + private final static String DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_COLUMNSIZE_EDITABLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + + "layout.noactions.columnsize.editable"; + private final static String DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_COLUMNSIZE_EDITABLE_DEFAULT = "false"; - - private final static String DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITOR_ROLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + "layout.noactions.editor.role"; + + private final static String DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITOR_ROLE = DESKTOP_PAGEEDITOR_NAME_PREFIX + + "layout.noactions.editor.role"; + private final static String DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITOR_ROLE_DEFAULT = null; - - private final static String DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DEPTH_MAX = DESKTOP_PAGEEDITOR_NAME_PREFIX + "page.layout.depth.max"; - private final static int DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DEPTH_MAX_DEFAULT = 2; // allowed range is 0-15 - private final static int DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DEPTH_MAX_RESERVED = 0x000F; // max layout depth (0-15) is first 4 bits - private final static int DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DECORATOR_EDITABLE_TRUE = 0x0010; - private final static int DESKTOP_PAGEEDITOR_LAYOUT_NAME_EDITABLE_TRUE = 0x0020; - private final static int DESKTOP_PAGEEDITOR_LAYOUT_COLUMNSIZE_EDITABLE_TRUE = 0x0040; - private final static int DESKTOP_PAGEEDITOR_PAGE_ADD_ENABLED_TRUE = 0x0080; - private final static int DESKTOP_PAGEEDITOR_PORTLET_ADD_ENABLED_TRUE = 0x0100; - private final static int DESKTOP_PAGEEDITOR_PAGE_PORTLET_DECORATOR_EDITABLE_TRUE = 0x0200; - private final static int DESKTOP_PAGEEDITOR_PORTLET_DECORATOR_EDITABLE_TRUE = 0x0400; - private final static int DESKTOP_PAGEEDITOR_MOVEMODE_ISDEFAULT_TRUE = 0x0800; - private final static int DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITABLE_TRUE = 0x1000; - private final static int DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_TOPLEVEL_MOVEABLE_TRUE = 0x2000; - private final static int DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_COLUMNSIZE_EDITABLE_TRUE = 0x4000; - // algorithm used below and on client-size doesn't allow for further expansion (i.e. allows for expansion up to 0x4000) - // (i.e. use of 0x8000 would break algorithm - because it would introduce the possibility of values close to 0xFFFF) - // - if needed, add another variable for a fresh set of flags (and adjust the dependencies) - + private final static String DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DEPTH_MAX = DESKTOP_PAGEEDITOR_NAME_PREFIX + + "page.layout.depth.max"; + + private final static int DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DEPTH_MAX_DEFAULT = 2; // allowed + + // range + // is + // 0-15 + + private final static int DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DEPTH_MAX_RESERVED = 0x000F; // max + + // layout + // depth + // (0-15) + // is + // first + // 4 + // bits + + private final static int DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DECORATOR_EDITABLE_TRUE = 0x0010; + + private final static int DESKTOP_PAGEEDITOR_LAYOUT_NAME_EDITABLE_TRUE = 0x0020; + + private final static int DESKTOP_PAGEEDITOR_LAYOUT_COLUMNSIZE_EDITABLE_TRUE = 0x0040; + + private final static int DESKTOP_PAGEEDITOR_PAGE_ADD_ENABLED_TRUE = 0x0080; + + private final static int DESKTOP_PAGEEDITOR_PORTLET_ADD_ENABLED_TRUE = 0x0100; + + private final static int DESKTOP_PAGEEDITOR_PAGE_PORTLET_DECORATOR_EDITABLE_TRUE = 0x0200; + + private final static int DESKTOP_PAGEEDITOR_PORTLET_DECORATOR_EDITABLE_TRUE = 0x0400; + + private final static int DESKTOP_PAGEEDITOR_MOVEMODE_ISDEFAULT_TRUE = 0x0800; + + private final static int DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITABLE_TRUE = 0x1000; + + private final static int DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_TOPLEVEL_MOVEABLE_TRUE = 0x2000; + + private final static int DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_COLUMNSIZE_EDITABLE_TRUE = 0x4000; + + // algorithm used below and on client-size doesn't allow for further + // expansion (i.e. allows for expansion up to 0x4000) + // (i.e. use of 0x8000 would break algorithm - because it would introduce + // the possibility of values close to 0xFFFF) + // - if needed, add another variable for a fresh set of flags (and adjust + // the dependencies) + private DecorationFactory decorationFactory; - + /** desktop pipeline servlet path */ private String desktopServletPath; - + /** default extension for layout templates */ private String defaultLayoutTemplateExtension; - + /** spring-fed servlet context property */ private ServletContext servletContext; - + /** tool for directing output to html <head> */ private HeaderResourceFactory headerResourceFactory; - - /** cache to minimize production of generated desktop configuration content **/ + + /** cache to minimize production of generated desktop configuration content * */ private JetspeedCache desktopContentCache; - + /** base portal URL to override default URL server info from servlet */ private BasePortalURL baseUrlAccess = null; - - public JetspeedDesktopImpl( DecorationFactory decorationFactory, - HeaderResourceFactory headerResourceFactory, - JetspeedCache desktopContentCache, - String desktopServletPath, - String defaultLayoutTemplateExtension ) + + public JetspeedDesktopImpl(DecorationFactory decorationFactory, + HeaderResourceFactory headerResourceFactory, + JetspeedCache desktopContentCache, String desktopServletPath, + String defaultLayoutTemplateExtension) { - this( decorationFactory, headerResourceFactory, desktopContentCache, desktopServletPath, defaultLayoutTemplateExtension, null, null, null ); + this(decorationFactory, headerResourceFactory, desktopContentCache, + desktopServletPath, defaultLayoutTemplateExtension, null, null, + null); } - public JetspeedDesktopImpl( DecorationFactory decorationFactory, - HeaderResourceFactory headerResourceFactory, - JetspeedCache desktopContentCache, - String desktopServletPath, - String defaultLayoutTemplateExtension, - String defaultDesktopLayoutDecoration, - String defaultDesktopPortletDecoration ) + + public JetspeedDesktopImpl(DecorationFactory decorationFactory, + HeaderResourceFactory headerResourceFactory, + JetspeedCache desktopContentCache, String desktopServletPath, + String defaultLayoutTemplateExtension, + String defaultDesktopLayoutDecoration, + String defaultDesktopPortletDecoration) { - this( decorationFactory, headerResourceFactory, desktopContentCache, desktopServletPath, defaultLayoutTemplateExtension, defaultDesktopLayoutDecoration, defaultDesktopPortletDecoration, null ); + this(decorationFactory, headerResourceFactory, desktopContentCache, + desktopServletPath, defaultLayoutTemplateExtension, + defaultDesktopLayoutDecoration, + defaultDesktopPortletDecoration, null); } - public JetspeedDesktopImpl( DecorationFactory decorationFactory, - HeaderResourceFactory headerResourceFactory, - JetspeedCache desktopContentCache, - String desktopServletPath, - String defaultLayoutTemplateExtension, - String defaultDesktopLayoutDecoration, - String defaultDesktopPortletDecoration, - BasePortalURL baseUrlAccess ) + + public JetspeedDesktopImpl(DecorationFactory decorationFactory, + HeaderResourceFactory headerResourceFactory, + JetspeedCache desktopContentCache, String desktopServletPath, + String defaultLayoutTemplateExtension, + String defaultDesktopLayoutDecoration, + String defaultDesktopPortletDecoration, BasePortalURL baseUrlAccess) { this.decorationFactory = decorationFactory; this.headerResourceFactory = headerResourceFactory; this.desktopContentCache = desktopContentCache; - - if ( desktopServletPath != null && desktopServletPath.length() > 0 ) + + if (desktopServletPath != null && desktopServletPath.length() > 0) { - if ( desktopServletPath.charAt( 0 ) != '/' ) + if (desktopServletPath.charAt(0) != '/') desktopServletPath = "/" + desktopServletPath; } this.desktopServletPath = desktopServletPath; - if ( this.desktopServletPath == null || this.desktopServletPath.length() == 0 ) + if (this.desktopServletPath == null + || this.desktopServletPath.length() == 0) { - log.warn( "JetspeedDesktopImpl initialization is incomplete due to undefined desktop servlet path." ); + log + .warn("JetspeedDesktopImpl initialization is incomplete due to undefined desktop servlet path."); this.desktopServletPath = null; } - + this.defaultLayoutTemplateExtension = defaultLayoutTemplateExtension; - - // set default layout and portlet decorations only if they are not currently undefined - if ( defaultDesktopLayoutDecoration != null && defaultDesktopLayoutDecoration.length() > 0 ) + + // set default layout and portlet decorations only if they are not + // currently undefined + if (defaultDesktopLayoutDecoration != null + && defaultDesktopLayoutDecoration.length() > 0) { - String existingDefaultDesktopLayoutDecoration = decorationFactory.getDefaultDesktopLayoutDecoration(); - if ( existingDefaultDesktopLayoutDecoration == null || existingDefaultDesktopLayoutDecoration.length() == 0 ) + String existingDefaultDesktopLayoutDecoration = decorationFactory + .getDefaultDesktopLayoutDecoration(); + if (existingDefaultDesktopLayoutDecoration == null + || existingDefaultDesktopLayoutDecoration.length() == 0) { - decorationFactory.setDefaultDesktopLayoutDecoration( defaultDesktopLayoutDecoration ); + decorationFactory + .setDefaultDesktopLayoutDecoration(defaultDesktopLayoutDecoration); } } - if ( defaultDesktopPortletDecoration != null && defaultDesktopPortletDecoration.length() > 0 ) + if (defaultDesktopPortletDecoration != null + && defaultDesktopPortletDecoration.length() > 0) { - String existingDefaultDesktopPortletDecoration = decorationFactory.getDefaultDesktopPortletDecoration(); - if ( existingDefaultDesktopPortletDecoration == null || existingDefaultDesktopPortletDecoration.length() == 0 ) + String existingDefaultDesktopPortletDecoration = decorationFactory + .getDefaultDesktopPortletDecoration(); + if (existingDefaultDesktopPortletDecoration == null + || existingDefaultDesktopPortletDecoration.length() == 0) { - decorationFactory.setDefaultDesktopPortletDecoration( defaultDesktopPortletDecoration ); + decorationFactory + .setDefaultDesktopPortletDecoration(defaultDesktopPortletDecoration); } } - + this.baseUrlAccess = baseUrlAccess; } - public void render( RequestContext request ) + public void render(RequestContext request) { String layoutDecorationTemplatePath = null; boolean layoutDecorationTemplatePathWasAssigned = false; try { Page page = request.getPage(); - + // enable desktop - request.setAttribute( JetspeedDesktop.DESKTOP_ENABLED_REQUEST_ATTRIBUTE, Boolean.TRUE ); - + request.setAttribute( + JetspeedDesktop.DESKTOP_ENABLED_REQUEST_ATTRIBUTE, + Boolean.TRUE); + // get decorations - Theme theme = decorationFactory.getTheme( page, request ); - - HeaderResource hr = getHeaderResourceFactory().getHeaderResouce( request ); - JetspeedDesktopContext desktopContext = new JetspeedDesktopContextImpl( request, this.baseUrlAccess, theme, hr, defaultLayoutTemplateExtension ); - + Theme theme = decorationFactory.getTheme(page, request); + + HeaderResource hr = getHeaderResourceFactory().getHeaderResouce( + request); + JetspeedDesktopContext desktopContext = new JetspeedDesktopContextImpl( + request, this.baseUrlAccess, theme, hr, + defaultLayoutTemplateExtension); + String layoutTemplateIdPropertyName = null; - if ( "true".equals( request.getRequest().getParameter( "jsprintmode" ) ) ) + if ("true".equals(request.getRequest().getParameter("jsprintmode"))) layoutTemplateIdPropertyName = JetspeedDesktopContext.LAYOUT_PRINT_TEMPLATE_ID_PROP; - - layoutDecorationTemplatePath = desktopContext.getLayoutTemplatePath( layoutTemplateIdPropertyName ); + + layoutDecorationTemplatePath = desktopContext + .getLayoutTemplatePath(layoutTemplateIdPropertyName); layoutDecorationTemplatePathWasAssigned = true; - - RequestDispatcher dispatcher = request.getRequest().getRequestDispatcher( layoutDecorationTemplatePath ); - + + RequestDispatcher dispatcher = request.getRequest() + .getRequestDispatcher(layoutDecorationTemplatePath); + hr.dojoEnable(); - - request.getRequest().setAttribute( JetspeedDesktopContext.DESKTOP_CONTEXT_ATTRIBUTE, desktopContext ); - request.getRequest().setAttribute( JetspeedDesktopContext.DESKTOP_REQUEST_CONTEXT_ATTRIBUTE, request ); - request.getRequest().setAttribute( JetspeedDesktopContext.DESKTOP_COMPONENT_MANAGER_ATTRIBUTE, Jetspeed.getComponentManager() ); - - String layoutDecorationName = desktopContext.getLayoutDecorationName(); - boolean inclStyleLayout = hr.isHeaderSectionIncluded( HeaderResource.HEADER_SECTION_DESKTOP_STYLE_LAYOUT ); - String dojoConfigContentCacheKey = DOJO_CONFIG_LAYOUT_VAR_NAME + "." + layoutDecorationName; - String dojoConfigContent = getCachedContent( dojoConfigContentCacheKey ); - - if ( dojoConfigContent == null ) + + request.getRequest().setAttribute( + JetspeedDesktopContext.DESKTOP_CONTEXT_ATTRIBUTE, + desktopContext); + request.getRequest().setAttribute( + JetspeedDesktopContext.DESKTOP_REQUEST_CONTEXT_ATTRIBUTE, + request); + request.getRequest().setAttribute( + JetspeedDesktopContext.DESKTOP_COMPONENT_MANAGER_ATTRIBUTE, + Jetspeed.getComponentManager()); + + String layoutDecorationName = desktopContext + .getLayoutDecorationName(); + boolean inclStyleLayout = hr + .isHeaderSectionIncluded(HeaderResource.HEADER_SECTION_DESKTOP_STYLE_LAYOUT); + String dojoConfigContentCacheKey = DOJO_CONFIG_LAYOUT_VAR_NAME + + "." + layoutDecorationName; + String dojoConfigContent = getCachedContent(dojoConfigContentCacheKey); + + if (dojoConfigContent == null) { - String portletDecorationsBasePath = decorationFactory.getPortletDecorationsBasePath(); - StringBuffer dojoConfigAddOn = new StringBuffer(); - dojoConfigAddOn.append( " " ).append( DOJO_CONFIG_LAYOUT_DECORATION_PATH_VAR_NAME ).append( " = \"" ).append( desktopContext.getLayoutBasePath() ).append( "\";" ).append( EOL ); - dojoConfigAddOn.append( " " ).append( DOJO_CONFIG_LAYOUT_VAR_NAME ).append( " = \"" ).append( layoutDecorationName ).append( "\";" ).append( EOL ); - dojoConfigAddOn.append( " " ).append( DOJO_CONFIG_PORTLET_DECORATIONS_PATH_VAR_NAME ).append( " = \"" ).append( portletDecorationsBasePath ).append( "\";" ).append( EOL ); + String portletDecorationsBasePath = decorationFactory + .getPortletDecorationsBasePath(); + StringBuffer dojoConfigAddOn = new StringBuffer(); + dojoConfigAddOn.append(" ").append( + DOJO_CONFIG_LAYOUT_DECORATION_PATH_VAR_NAME).append( + " = \"").append(desktopContext.getLayoutBasePath()) + .append("\";").append(EOL); + dojoConfigAddOn.append(" ").append( + DOJO_CONFIG_LAYOUT_VAR_NAME).append(" = \"").append( + layoutDecorationName).append("\";").append(EOL); + dojoConfigAddOn.append(" ").append( + DOJO_CONFIG_PORTLET_DECORATIONS_PATH_VAR_NAME).append( + " = \"").append(portletDecorationsBasePath).append( + "\";").append(EOL); - LayoutDecoration desktopLayoutDecoration = decorationFactory.getLayoutDecoration( layoutDecorationName, request ); - if ( desktopLayoutDecoration != null ) - { - boolean atLeastOneFound = false; - StringBuffer loadingPropsBuffer = new StringBuffer(); - loadingPropsBuffer.append( " " ).append( DOJO_CONFIG_LOADING_IMGPROPS_NAME ).append( " = { " ); - for ( int i = 0 ; i < DESKTOP_LOADING_PROPERTY_NAMES.length ; i++ ) - { - String propValue = desktopLayoutDecoration.getProperty( DESKTOP_LOADING_IMG_NAME_PREFIX + DESKTOP_LOADING_PROPERTY_NAMES[ i ] ); - if ( propValue != null ) - { - if ( atLeastOneFound ) - { - loadingPropsBuffer.append( ", " ); - } - else - { - atLeastOneFound = true; - } - String usePropertyName = DESKTOP_LOADING_PROPERTY_NAMES[ i ]; - if ( DESKTOP_LOADING_OUTPUT_PROPERTY_NAMES != null && DESKTOP_LOADING_OUTPUT_PROPERTY_NAMES.length > i && DESKTOP_LOADING_OUTPUT_PROPERTY_NAMES[i] != null ) - usePropertyName = DESKTOP_LOADING_OUTPUT_PROPERTY_NAMES[i]; - - loadingPropsBuffer.append( usePropertyName ).append( ": " ).append( propValue ); - } - } - loadingPropsBuffer.append( " };" ); - if ( atLeastOneFound ) - dojoConfigAddOn.append( loadingPropsBuffer.toString() ).append( EOL ); - - addPageEditorSettings( dojoConfigAddOn, desktopLayoutDecoration ); - } - else - { - log.error( "Failed to find desktop layout decoration " + layoutDecorationName + " - layout decoration properties cannot be added to content." ); - } - - Set desktopPortletDecorationsNames = decorationFactory.getDesktopPortletDecorations( request ); - String portletDecorationNamesContent = HeaderResourceLib.makeJSONStringArray( desktopPortletDecorationsNames ); - dojoConfigAddOn.append( " " ).append( DOJO_CONFIG_PORTLET_DECORATIONS_ALLOWED_VAR_NAME ).append( " = " ).append( portletDecorationNamesContent ).append( ";" ); + LayoutDecoration desktopLayoutDecoration = decorationFactory + .getLayoutDecoration(layoutDecorationName, request); + if (desktopLayoutDecoration != null) + { + boolean atLeastOneFound = false; + StringBuffer loadingPropsBuffer = new StringBuffer(); + loadingPropsBuffer.append(" ").append( + DOJO_CONFIG_LOADING_IMGPROPS_NAME).append(" = { "); + for (int i = 0; i < DESKTOP_LOADING_PROPERTY_NAMES.length; i++) + { + String propValue = desktopLayoutDecoration + .getProperty(DESKTOP_LOADING_IMG_NAME_PREFIX + + DESKTOP_LOADING_PROPERTY_NAMES[i]); + if (propValue != null) + { + if (atLeastOneFound) + { + loadingPropsBuffer.append(", "); + } + else + { + atLeastOneFound = true; + } + String usePropertyName = DESKTOP_LOADING_PROPERTY_NAMES[i]; + if (DESKTOP_LOADING_OUTPUT_PROPERTY_NAMES != null + && DESKTOP_LOADING_OUTPUT_PROPERTY_NAMES.length > i + && DESKTOP_LOADING_OUTPUT_PROPERTY_NAMES[i] != null) + usePropertyName = DESKTOP_LOADING_OUTPUT_PROPERTY_NAMES[i]; - StringBuffer pDecsOut = new StringBuffer(); - Iterator desktopPortletDecorationsNamesIter = desktopPortletDecorationsNames.iterator(); - while ( desktopPortletDecorationsNamesIter.hasNext() ) - { - String desktopPortletDecorationName = (String)desktopPortletDecorationsNamesIter.next(); - - PortletDecoration desktopPortletDecoration = decorationFactory.getPortletDecoration( desktopPortletDecorationName, request ); - - StringBuffer pOut = new StringBuffer(); - - String actionButtonOrderContent = desktopPortletDecoration.getProperty( HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ACTION_BUTTON_ORDER ); - if ( actionButtonOrderContent != null && actionButtonOrderContent.length() > 0 ) - { - pOut.append( ( pOut.length() > 0 ) ? ", " : "" ).append( HeaderResource.DESKTOP_JSON_WINDOW_ACTION_BUTTON_ORDER ).append( ": " ).append( actionButtonOrderContent ); - } - - String actionNoImageContent = desktopPortletDecoration.getProperty( HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ACTION_NOIMAGE ); - if ( actionNoImageContent != null && actionNoImageContent.length() > 0 ) - { - pOut.append( ( pOut.length() > 0 ) ? ", " : "" ).append( HeaderResource.DESKTOP_JSON_WINDOW_ACTION_NOIMAGE ).append( ": " ).append( actionNoImageContent ); - } - - String actionMenuOrderContent = desktopPortletDecoration.getProperty( HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ACTION_MENU_ORDER ); - if ( actionMenuOrderContent != null && actionMenuOrderContent.length() > 0 ) - { - pOut.append( ( pOut.length() > 0 ) ? ", " : "" ).append( HeaderResource.DESKTOP_JSON_WINDOW_ACTION_MENU_ORDER ).append( ": " ).append( actionMenuOrderContent ); - } - - String windowActionButtonTooltip = desktopPortletDecoration.getProperty( HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ACTION_BUTTON_TOOLTIP ); - if ( windowActionButtonTooltip != null && windowActionButtonTooltip.length() > 0 ) - { - pOut.append( ( pOut.length() > 0 ) ? ", " : "" ).append( HeaderResource.DESKTOP_JSON_WINDOW_ACTION_BUTTON_TOOLTIP ).append( ": " ).append( windowActionButtonTooltip ); - } + loadingPropsBuffer.append(usePropertyName).append( + ": ").append(propValue); + } + } + loadingPropsBuffer.append(" };"); + if (atLeastOneFound) + dojoConfigAddOn.append(loadingPropsBuffer.toString()) + .append(EOL); - String windowActionButtonMax = desktopPortletDecoration.getProperty( HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ACTION_BUTTON_MAX ); - if ( windowActionButtonMax != null && windowActionButtonMax.length() > 0 ) - { - pOut.append( ( pOut.length() > 0 ) ? ", " : "" ).append( HeaderResource.DESKTOP_JSON_WINDOW_ACTION_BUTTON_MAX ).append( ": " ).append( windowActionButtonMax ); - } - - String iconEnabledContent = desktopPortletDecoration.getProperty( HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ICON_ENABLED ); - if ( iconEnabledContent != null && iconEnabledContent.length() > 0 ) - { - pOut.append( ( pOut.length() > 0 ) ? ", " : "" ).append( HeaderResource.DESKTOP_JSON_WINDOW_ICON_ENABLED ).append( ": " ).append( iconEnabledContent ); - } - - String iconPathContent = desktopPortletDecoration.getProperty( HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ICON_PATH ); - if ( iconPathContent != null && iconPathContent.length() > 0 ) - { - pOut.append( ( pOut.length() > 0 ) ? ", " : "" ).append( HeaderResource.DESKTOP_JSON_WINDOW_ICON_PATH ).append( ": " ).append( iconPathContent ).append( ";" ).append( EOL ); - } - - String titlebarEnabledContent = desktopPortletDecoration.getProperty( HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_TITLEBAR_ENABLED ); - if ( titlebarEnabledContent != null && titlebarEnabledContent.length() > 0 ) - { - pOut.append( ( pOut.length() > 0 ) ? ", " : "" ).append( HeaderResource.DESKTOP_JSON_WINDOW_TITLEBAR_ENABLED ).append( ": " ).append( titlebarEnabledContent ); - } - - String resizebarEnabledContent = desktopPortletDecoration.getProperty( HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_RESIZEBAR_ENABLED ); - if ( resizebarEnabledContent != null && resizebarEnabledContent.length() > 0 ) - { - pOut.append( ( pOut.length() > 0 ) ? ", " : "" ).append( HeaderResource.DESKTOP_JSON_WINDOW_RESIZEBAR_ENABLED ).append( ": " ).append( resizebarEnabledContent ); - } - - if ( pOut.length() > 0 ) - { - if ( pDecsOut.length() == 0 ) - { - pDecsOut.append( DOJO_CONFIG_PORTLET_DECORATIONS_CONFIG_VAR_NAME ).append( " = { " ); - } - else - { - pDecsOut.append( ", " ); - } - pDecsOut.append( "\"" ).append( desktopPortletDecorationName ).append( "\": { " ).append( pOut.toString() ).append( " }" ).append( EOL ); - } - } // while ( desktopPortletDecorationsNamesIter.hasNext() ) - if ( pDecsOut.length() > 0 ) - { - pDecsOut.append( " }" ); - dojoConfigAddOn.append( EOL ).append( " " ).append( pDecsOut.toString() ).append( ";" ); - } - - dojoConfigContent = dojoConfigAddOn.toString(); - setCachedContent( dojoConfigContentCacheKey, dojoConfigContent ); - } - - if ( dojoConfigContent != null ) + addPageEditorSettings(dojoConfigAddOn, + desktopLayoutDecoration); + } + else + { + log + .error("Failed to find desktop layout decoration " + + layoutDecorationName + + " - layout decoration properties cannot be added to content."); + } + + Set desktopPortletDecorationsNames = decorationFactory + .getDesktopPortletDecorations(request); + String portletDecorationNamesContent = HeaderResourceLib + .makeJSONStringArray(desktopPortletDecorationsNames); + dojoConfigAddOn.append(" ").append( + DOJO_CONFIG_PORTLET_DECORATIONS_ALLOWED_VAR_NAME) + .append(" = ").append(portletDecorationNamesContent) + .append(";"); + + StringBuffer pDecsOut = new StringBuffer(); + Iterator desktopPortletDecorationsNamesIter = desktopPortletDecorationsNames + .iterator(); + while (desktopPortletDecorationsNamesIter.hasNext()) + { + String desktopPortletDecorationName = (String) desktopPortletDecorationsNamesIter + .next(); + + PortletDecoration desktopPortletDecoration = decorationFactory + .getPortletDecoration(desktopPortletDecorationName, + request); + + StringBuffer pOut = new StringBuffer(); + + String actionButtonOrderContent = desktopPortletDecoration + .getProperty(HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ACTION_BUTTON_ORDER); + if (actionButtonOrderContent != null + && actionButtonOrderContent.length() > 0) + { + pOut + .append((pOut.length() > 0) ? ", " : "") + .append( + HeaderResource.DESKTOP_JSON_WINDOW_ACTION_BUTTON_ORDER) + .append(": ").append(actionButtonOrderContent); + } + + String actionNoImageContent = desktopPortletDecoration + .getProperty(HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ACTION_NOIMAGE); + if (actionNoImageContent != null + && actionNoImageContent.length() > 0) + { + pOut + .append((pOut.length() > 0) ? ", " : "") + .append( + HeaderResource.DESKTOP_JSON_WINDOW_ACTION_NOIMAGE) + .append(": ").append(actionNoImageContent); + } + + String actionMenuOrderContent = desktopPortletDecoration + .getProperty(HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ACTION_MENU_ORDER); + if (actionMenuOrderContent != null + && actionMenuOrderContent.length() > 0) + { + pOut + .append((pOut.length() > 0) ? ", " : "") + .append( + HeaderResource.DESKTOP_JSON_WINDOW_ACTION_MENU_ORDER) + .append(": ").append(actionMenuOrderContent); + } + + String windowActionButtonTooltip = desktopPortletDecoration + .getProperty(HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ACTION_BUTTON_TOOLTIP); + if (windowActionButtonTooltip != null + && windowActionButtonTooltip.length() > 0) + { + pOut + .append((pOut.length() > 0) ? ", " : "") + .append( + HeaderResource.DESKTOP_JSON_WINDOW_ACTION_BUTTON_TOOLTIP) + .append(": ").append(windowActionButtonTooltip); + } + + String windowActionButtonMax = desktopPortletDecoration + .getProperty(HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ACTION_BUTTON_MAX); + if (windowActionButtonMax != null + && windowActionButtonMax.length() > 0) + { + pOut + .append((pOut.length() > 0) ? ", " : "") + .append( + HeaderResource.DESKTOP_JSON_WINDOW_ACTION_BUTTON_MAX) + .append(": ").append(windowActionButtonMax); + } + + String iconEnabledContent = desktopPortletDecoration + .getProperty(HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ICON_ENABLED); + if (iconEnabledContent != null + && iconEnabledContent.length() > 0) + { + pOut + .append((pOut.length() > 0) ? ", " : "") + .append( + HeaderResource.DESKTOP_JSON_WINDOW_ICON_ENABLED) + .append(": ").append(iconEnabledContent); + } + + String iconPathContent = desktopPortletDecoration + .getProperty(HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_ICON_PATH); + if (iconPathContent != null && iconPathContent.length() > 0) + { + pOut.append((pOut.length() > 0) ? ", " : "").append( + HeaderResource.DESKTOP_JSON_WINDOW_ICON_PATH) + .append(": ").append(iconPathContent).append( + ";").append(EOL); + } + + String titlebarEnabledContent = desktopPortletDecoration + .getProperty(HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_TITLEBAR_ENABLED); + if (titlebarEnabledContent != null + && titlebarEnabledContent.length() > 0) + { + pOut + .append((pOut.length() > 0) ? ", " : "") + .append( + HeaderResource.DESKTOP_JSON_WINDOW_TITLEBAR_ENABLED) + .append(": ").append(titlebarEnabledContent); + } + + String resizebarEnabledContent = desktopPortletDecoration + .getProperty(HeaderResource.HEADER_CONFIG_DESKTOP_WINDOW_RESIZEBAR_ENABLED); + if (resizebarEnabledContent != null + && resizebarEnabledContent.length() > 0) + { + pOut + .append((pOut.length() > 0) ? ", " : "") + .append( + HeaderResource.DESKTOP_JSON_WINDOW_RESIZEBAR_ENABLED) + .append(": ").append(resizebarEnabledContent); + } + + if (pOut.length() > 0) + { + if (pDecsOut.length() == 0) + { + pDecsOut + .append( + DOJO_CONFIG_PORTLET_DECORATIONS_CONFIG_VAR_NAME) + .append(" = { "); + } + else + { + pDecsOut.append(", "); + } + pDecsOut.append("\"").append( + desktopPortletDecorationName).append("\": { ") + .append(pOut.toString()).append(" }").append( + EOL); + } + } // while ( desktopPortletDecorationsNamesIter.hasNext() ) + if (pDecsOut.length() > 0) + { + pDecsOut.append(" }"); + dojoConfigAddOn.append(EOL).append(" ").append( + pDecsOut.toString()).append(";"); + } + + dojoConfigContent = dojoConfigAddOn.toString(); + setCachedContent(dojoConfigContentCacheKey, dojoConfigContent); + } + + if (dojoConfigContent != null) { - hr.addHeaderSectionFragment( DOJO_CONFIG_LAYOUT_VAR_NAME, HeaderResource.HEADER_SECTION_DOJO_CONFIG, dojoConfigContent ); + hr.addHeaderSectionFragment(DOJO_CONFIG_LAYOUT_VAR_NAME, + HeaderResource.HEADER_SECTION_DOJO_CONFIG, + dojoConfigContent); } - - if ( inclStyleLayout ) + + if (inclStyleLayout) { - String contextPath = request.getRequest().getContextPath(); - String styleLayoutContentCacheKey = (HeaderResource.HEADER_SECTION_DESKTOP_STYLE_LAYOUT + "." + layoutDecorationName + "." + contextPath); - String styleLayoutContent = getCachedContent( styleLayoutContentCacheKey ); - if ( styleLayoutContent == null ) + String contextPath = request.getRequest().getContextPath(); + String styleLayoutContentCacheKey = (HeaderResource.HEADER_SECTION_DESKTOP_STYLE_LAYOUT + + "." + layoutDecorationName + "." + contextPath); + String styleLayoutContent = getCachedContent(styleLayoutContentCacheKey); + if (styleLayoutContent == null) { - String portletDecorationsBasePath = decorationFactory.getPortletDecorationsBasePath(); - String portletDecorationsBaseRelative = portletDecorationsBasePath; - if ( portletDecorationsBaseRelative != null && portletDecorationsBaseRelative.length() > 1 && portletDecorationsBaseRelative.indexOf( '/' ) == 0 ) - { - portletDecorationsBaseRelative = portletDecorationsBaseRelative.substring( 1 ); - } - StringBuffer desktopThemeStyleLink = new StringBuffer(); - - int stylesheetCount = 0; - Iterator stylesheetIter = theme.getStyleSheets().iterator(); - while ( stylesheetIter.hasNext() ) - { - String stylesheetHref = (String)stylesheetIter.next(); - if ( stylesheetHref != null && stylesheetHref.length() > 0 ) - { - if ( ! stylesheetHref.startsWith( portletDecorationsBaseRelative ) ) - { // exclude portlet decorations - in desktop these are loaded via javascript - if ( stylesheetCount > 0 ) - { - desktopThemeStyleLink.append( EOL ); - } - - desktopThemeStyleLink.append( "" ); - desktopThemeStyleLink.append( contextPath + "/" + stylesheetHref ).append( "\"/>" ); - - stylesheetCount++; - } - } - } - styleLayoutContent = desktopThemeStyleLink.toString(); - setCachedContent( styleLayoutContentCacheKey, styleLayoutContent ); + String portletDecorationsBasePath = decorationFactory + .getPortletDecorationsBasePath(); + String portletDecorationsBaseRelative = portletDecorationsBasePath; + if (portletDecorationsBaseRelative != null + && portletDecorationsBaseRelative.length() > 1 + && portletDecorationsBaseRelative.indexOf('/') == 0) + { + portletDecorationsBaseRelative = portletDecorationsBaseRelative + .substring(1); + } + StringBuffer desktopThemeStyleLink = new StringBuffer(); + + int stylesheetCount = 0; + Iterator stylesheetIter = theme.getStyleSheets().iterator(); + while (stylesheetIter.hasNext()) + { + String stylesheetHref = (String) stylesheetIter.next(); + if (stylesheetHref != null + && stylesheetHref.length() > 0) + { + if (!stylesheetHref + .startsWith(portletDecorationsBaseRelative)) + { // exclude portlet decorations - in desktop + // these are loaded via javascript + if (stylesheetCount > 0) + { + desktopThemeStyleLink.append(EOL); + } + + desktopThemeStyleLink + .append("" ); + desktopThemeStyleLink.append( + contextPath + "/" + stylesheetHref) + .append("\"/>"); + + stylesheetCount++; + } + } + } + styleLayoutContent = desktopThemeStyleLink.toString(); + setCachedContent(styleLayoutContentCacheKey, + styleLayoutContent); } - if ( styleLayoutContent != null && styleLayoutContent.length() > 0 ) + if (styleLayoutContent != null + && styleLayoutContent.length() > 0) { - hr.setHeaderSectionType( HeaderResource.HEADER_SECTION_DESKTOP_STYLE_LAYOUT, HeaderResource.HEADER_TYPE_LINK_TAG ); - hr.addHeaderSectionFragment( "desktop.style.layout", HeaderResource.HEADER_SECTION_DESKTOP_STYLE_LAYOUT, styleLayoutContent ); + hr.setHeaderSectionType( + HeaderResource.HEADER_SECTION_DESKTOP_STYLE_LAYOUT, + HeaderResource.HEADER_TYPE_LINK_TAG); + hr.addHeaderSectionFragment("desktop.style.layout", + HeaderResource.HEADER_SECTION_DESKTOP_STYLE_LAYOUT, + styleLayoutContent); } } - - String layoutDecorationLocaleSuffix = "." + layoutDecorationName + "." + request.getLocale().toString(); - String desktopActionLabelsCacheKey = DOJO_CONFIG_ACTION_LABELS_NAME + layoutDecorationLocaleSuffix; - String pageEditorLabelsCacheKey = DOJO_CONFIG_PAGEEDITOR_LABELS_NAME + layoutDecorationLocaleSuffix; - String pageEditorDialogLabelsCacheKey = DOJO_CONFIG_PAGEEDITOR_DIALOG_LABELS_NAME + layoutDecorationLocaleSuffix; - - String desktopActionLabelsContent = getCachedContent( desktopActionLabelsCacheKey ); - String pageEditorLabelsContent = getCachedContent( pageEditorLabelsCacheKey ); - String pageEditorDialogLabelsContent = getCachedContent( pageEditorDialogLabelsCacheKey ); - if ( desktopActionLabelsContent == null || pageEditorLabelsContent == null || pageEditorDialogLabelsContent == null ) + + String layoutDecorationLocaleSuffix = "." + layoutDecorationName + + "." + request.getLocale().toString(); + String desktopActionLabelsCacheKey = DOJO_CONFIG_ACTION_LABELS_NAME + + layoutDecorationLocaleSuffix; + String pageEditorLabelsCacheKey = DOJO_CONFIG_PAGEEDITOR_LABELS_NAME + + layoutDecorationLocaleSuffix; + String pageEditorDialogLabelsCacheKey = DOJO_CONFIG_PAGEEDITOR_DIALOG_LABELS_NAME + + layoutDecorationLocaleSuffix; + + String desktopActionLabelsContent = getCachedContent(desktopActionLabelsCacheKey); + String pageEditorLabelsContent = getCachedContent(pageEditorLabelsCacheKey); + String pageEditorDialogLabelsContent = getCachedContent(pageEditorDialogLabelsCacheKey); + if (desktopActionLabelsContent == null + || pageEditorLabelsContent == null + || pageEditorDialogLabelsContent == null) { - ResourceBundle messages = desktopContext.getLayoutResourceBundle( request.getLocale() ); - if ( desktopActionLabelsContent == null ) - { - desktopActionLabelsContent = getResourcesAsJavascriptObject( DESKTOP_ACTION_RESOURCE_NAME_PREFIX, DESKTOP_ACTION_RESOURCE_NAMES, messages, DOJO_CONFIG_ACTION_LABELS_NAME, " ", true ); - setCachedContent( desktopActionLabelsCacheKey, desktopActionLabelsContent ); - } - if ( pageEditorLabelsContent == null ) - { - pageEditorLabelsContent = getResourcesAsJavascriptObject( DESKTOP_PAGEEDITOR_RESOURCE_NAME_PREFIX, DESKTOP_PAGEEDITOR_RESOURCE_NAMES, messages, DOJO_CONFIG_PAGEEDITOR_LABELS_NAME, " ", true ); - setCachedContent( pageEditorLabelsCacheKey, pageEditorLabelsContent ); - } - if ( pageEditorDialogLabelsContent == null ) - { - pageEditorDialogLabelsContent = getResourcesAsJavascriptObject( DESKTOP_PAGEEDITOR_DIALOG_RESOURCE_NAME_PREFIX, DESKTOP_PAGEEDITOR_DIALOG_RESOURCE_NAMES, messages, DOJO_CONFIG_PAGEEDITOR_DIALOG_LABELS_NAME, " ", true ); - setCachedContent( pageEditorDialogLabelsCacheKey, pageEditorDialogLabelsContent ); - } + ResourceBundle messages = desktopContext + .getLayoutResourceBundle(request.getLocale()); + if (desktopActionLabelsContent == null) + { + desktopActionLabelsContent = getResourcesAsJavascriptObject( + DESKTOP_ACTION_RESOURCE_NAME_PREFIX, + DESKTOP_ACTION_RESOURCE_NAMES, messages, + DOJO_CONFIG_ACTION_LABELS_NAME, " ", true); + setCachedContent(desktopActionLabelsCacheKey, + desktopActionLabelsContent); + } + if (pageEditorLabelsContent == null) + { + pageEditorLabelsContent = getResourcesAsJavascriptObject( + DESKTOP_PAGEEDITOR_RESOURCE_NAME_PREFIX, + DESKTOP_PAGEEDITOR_RESOURCE_NAMES, messages, + DOJO_CONFIG_PAGEEDITOR_LABELS_NAME, " ", true); + setCachedContent(pageEditorLabelsCacheKey, + pageEditorLabelsContent); + } + if (pageEditorDialogLabelsContent == null) + { + pageEditorDialogLabelsContent = getResourcesAsJavascriptObject( + DESKTOP_PAGEEDITOR_DIALOG_RESOURCE_NAME_PREFIX, + DESKTOP_PAGEEDITOR_DIALOG_RESOURCE_NAMES, messages, + DOJO_CONFIG_PAGEEDITOR_DIALOG_LABELS_NAME, " ", + true); + setCachedContent(pageEditorDialogLabelsCacheKey, + pageEditorDialogLabelsContent); + } } - if ( desktopActionLabelsContent != null && desktopActionLabelsContent.length() > 0 ) + if (desktopActionLabelsContent != null + && desktopActionLabelsContent.length() > 0) { - hr.addHeaderSectionFragment( DOJO_CONFIG_ACTION_LABELS_NAME, HeaderResource.HEADER_SECTION_DOJO_CONFIG, desktopActionLabelsContent ); + hr.addHeaderSectionFragment(DOJO_CONFIG_ACTION_LABELS_NAME, + HeaderResource.HEADER_SECTION_DOJO_CONFIG, + desktopActionLabelsContent); } - if ( pageEditorLabelsContent != null && pageEditorLabelsContent.length() > 0 ) + if (pageEditorLabelsContent != null + && pageEditorLabelsContent.length() > 0) { - hr.addHeaderSectionFragment( DOJO_CONFIG_PAGEEDITOR_LABELS_NAME, HeaderResource.HEADER_SECTION_DOJO_CONFIG, pageEditorLabelsContent ); + hr.addHeaderSectionFragment(DOJO_CONFIG_PAGEEDITOR_LABELS_NAME, + HeaderResource.HEADER_SECTION_DOJO_CONFIG, + pageEditorLabelsContent); } - if ( pageEditorDialogLabelsContent != null && pageEditorDialogLabelsContent.length() > 0 ) + if (pageEditorDialogLabelsContent != null + && pageEditorDialogLabelsContent.length() > 0) { - hr.addHeaderSectionFragment( DOJO_CONFIG_PAGEEDITOR_DIALOG_LABELS_NAME, HeaderResource.HEADER_SECTION_DOJO_CONFIG, pageEditorDialogLabelsContent ); + hr.addHeaderSectionFragment( + DOJO_CONFIG_PAGEEDITOR_DIALOG_LABELS_NAME, + HeaderResource.HEADER_SECTION_DOJO_CONFIG, + pageEditorDialogLabelsContent); } - - dispatcher.include( request.getRequest(), request.getResponse() ); + + dispatcher.include(request.getRequest(), request.getResponse()); } - catch ( Exception e ) + catch (Exception e) { try { - if ( layoutDecorationTemplatePathWasAssigned ) + if (layoutDecorationTemplatePathWasAssigned) { - layoutDecorationTemplatePath = ( layoutDecorationTemplatePath == null || layoutDecorationTemplatePath.length() == 0 ? "null" : layoutDecorationTemplatePath ); - log.error( "Failed to include desktop layout decoration at path " + layoutDecorationTemplatePath, e ); - request.getResponse().getWriter().println( "Desktop layout decoration " + layoutDecorationTemplatePath + " is not available" ); + layoutDecorationTemplatePath = (layoutDecorationTemplatePath == null + || layoutDecorationTemplatePath.length() == 0 ? "null" + : layoutDecorationTemplatePath); + log.error( + "Failed to include desktop layout decoration at path " + + layoutDecorationTemplatePath, e); + request.getResponse().getWriter().println( + "Desktop layout decoration " + + layoutDecorationTemplatePath + + " is not available"); } else { - log.error( "Failed to initialize for inclusion of desktop layout decoration", e ); - request.getResponse().getWriter().println( "Failed to initialize for inclusion of desktop layout decoration" ); + log + .error( + "Failed to initialize for inclusion of desktop layout decoration", + e); + request + .getResponse() + .getWriter() + .println( + "Failed to initialize for inclusion of desktop layout decoration"); } } - catch ( IOException ioe ) + catch (IOException ioe) { - log.error( "Failed to write desktop layout decoration exception information to servlet output writer", ioe ); + log + .error( + "Failed to write desktop layout decoration exception information to servlet output writer", + ioe); } } } - - private void addPageEditorSettings( StringBuffer dojoConfigAddOn, LayoutDecoration desktopLayoutDecoration ) + + private void addPageEditorSettings(StringBuffer dojoConfigAddOn, + LayoutDecoration desktopLayoutDecoration) { - int[] pageEditorConfigFlags = new int[] { 0 }; - String propValue; + int[] pageEditorConfigFlags = new int[] + {0}; + String propValue; - propValue = desktopLayoutDecoration.getProperty( DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DECORATOR_EDITABLE ); - processBooleanFlagProperty( pageEditorConfigFlags, propValue, DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DECORATOR_EDITABLE_DEFAULT, DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DECORATOR_EDITABLE_TRUE ); - - propValue = desktopLayoutDecoration.getProperty( DESKTOP_PAGEEDITOR_LAYOUT_NAME_EDITABLE ); - processBooleanFlagProperty( pageEditorConfigFlags, propValue, DESKTOP_PAGEEDITOR_LAYOUT_NAME_EDITABLE_DEFAULT, DESKTOP_PAGEEDITOR_LAYOUT_NAME_EDITABLE_TRUE ); - - propValue = desktopLayoutDecoration.getProperty( DESKTOP_PAGEEDITOR_LAYOUT_COLUMNSIZE_EDITABLE ); - processBooleanFlagProperty( pageEditorConfigFlags, propValue, DESKTOP_PAGEEDITOR_LAYOUT_COLUMNSIZE_EDITABLE_DEFAULT, DESKTOP_PAGEEDITOR_LAYOUT_COLUMNSIZE_EDITABLE_TRUE ); - - propValue = desktopLayoutDecoration.getProperty( DESKTOP_PAGEEDITOR_PAGE_ADD_ENABLED ); - processBooleanFlagProperty( pageEditorConfigFlags, propValue, DESKTOP_PAGEEDITOR_PAGE_ADD_ENABLED_DEFAULT, DESKTOP_PAGEEDITOR_PAGE_ADD_ENABLED_TRUE ); - - propValue = desktopLayoutDecoration.getProperty( DESKTOP_PAGEEDITOR_PORTLET_ADD_ENABLED ); - processBooleanFlagProperty( pageEditorConfigFlags, propValue, DESKTOP_PAGEEDITOR_PORTLET_ADD_ENABLED_DEFAULT, DESKTOP_PAGEEDITOR_PORTLET_ADD_ENABLED_TRUE ); - - propValue = desktopLayoutDecoration.getProperty( DESKTOP_PAGEEDITOR_PAGE_PORTLET_DECORATOR_EDITABLE ); - processBooleanFlagProperty( pageEditorConfigFlags, propValue, DESKTOP_PAGEEDITOR_PAGE_PORTLET_DECORATOR_EDITABLE_DEFAULT, DESKTOP_PAGEEDITOR_PAGE_PORTLET_DECORATOR_EDITABLE_TRUE ); + propValue = desktopLayoutDecoration + .getProperty(DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DECORATOR_EDITABLE); + processBooleanFlagProperty(pageEditorConfigFlags, propValue, + DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DECORATOR_EDITABLE_DEFAULT, + DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DECORATOR_EDITABLE_TRUE); - propValue = desktopLayoutDecoration.getProperty( DESKTOP_PAGEEDITOR_PORTLET_DECORATOR_EDITABLE ); - processBooleanFlagProperty( pageEditorConfigFlags, propValue, DESKTOP_PAGEEDITOR_PORTLET_DECORATOR_EDITABLE_DEFAULT, DESKTOP_PAGEEDITOR_PORTLET_DECORATOR_EDITABLE_TRUE ); + propValue = desktopLayoutDecoration + .getProperty(DESKTOP_PAGEEDITOR_LAYOUT_NAME_EDITABLE); + processBooleanFlagProperty(pageEditorConfigFlags, propValue, + DESKTOP_PAGEEDITOR_LAYOUT_NAME_EDITABLE_DEFAULT, + DESKTOP_PAGEEDITOR_LAYOUT_NAME_EDITABLE_TRUE); - propValue = desktopLayoutDecoration.getProperty( DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITABLE ); - processBooleanFlagProperty( pageEditorConfigFlags, propValue, DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITABLE_DEFAULT, DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITABLE_TRUE ); - - propValue = desktopLayoutDecoration.getProperty( DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_TOPLEVEL_MOVEABLE ); - processBooleanFlagProperty( pageEditorConfigFlags, propValue, DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_TOPLEVEL_MOVEABLE_DEFAULT, DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_TOPLEVEL_MOVEABLE_TRUE ); - - propValue = desktopLayoutDecoration.getProperty( DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_COLUMNSIZE_EDITABLE ); - processBooleanFlagProperty( pageEditorConfigFlags, propValue, DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_COLUMNSIZE_EDITABLE_DEFAULT, DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_COLUMNSIZE_EDITABLE_TRUE ); + propValue = desktopLayoutDecoration + .getProperty(DESKTOP_PAGEEDITOR_LAYOUT_COLUMNSIZE_EDITABLE); + processBooleanFlagProperty(pageEditorConfigFlags, propValue, + DESKTOP_PAGEEDITOR_LAYOUT_COLUMNSIZE_EDITABLE_DEFAULT, + DESKTOP_PAGEEDITOR_LAYOUT_COLUMNSIZE_EDITABLE_TRUE); - propValue = desktopLayoutDecoration.getProperty( DESKTOP_PAGEEDITOR_MOVEMODE_ISDEFAULT ); - processBooleanFlagProperty( pageEditorConfigFlags, propValue, DESKTOP_PAGEEDITOR_MOVEMODE_ISDEFAULT_DEFAULT, DESKTOP_PAGEEDITOR_MOVEMODE_ISDEFAULT_TRUE ); - - propValue = desktopLayoutDecoration.getProperty( DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DEPTH_MAX ); - Integer maxLayoutNestingObj = null; - try - { - maxLayoutNestingObj = new Integer( propValue ); - } - catch ( NumberFormatException ex ) - { - maxLayoutNestingObj = new Integer( DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DEPTH_MAX_DEFAULT ); - } - int maxLayoutNesting = maxLayoutNestingObj.intValue(); - if ( maxLayoutNesting < 0 ) - maxLayoutNesting = 0; - if ( maxLayoutNesting > DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DEPTH_MAX_RESERVED ) - maxLayoutNesting = DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DEPTH_MAX_RESERVED; - pageEditorConfigFlags[0] += maxLayoutNesting; - - String allowEditNoactionsRole = desktopLayoutDecoration.getProperty( DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITOR_ROLE ); - if ( allowEditNoactionsRole == null ) - allowEditNoactionsRole = DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITOR_ROLE_DEFAULT; - if ( allowEditNoactionsRole == null ) - allowEditNoactionsRole = ""; - char[] allowEditNoactionsRoleChars = allowEditNoactionsRole.toCharArray(); - int allowEditNoactionsRoleCharsLen = ( ( allowEditNoactionsRoleChars == null ) ? 0 : allowEditNoactionsRoleChars.length ); - Random rnd = new Random(); - int extrasCount = ( allowEditNoactionsRoleCharsLen > 0 ? getRandom( rnd, 2, 5 ) : getRandom( rnd, 5, 8 ) ); - int hexLen = 1 + extrasCount + allowEditNoactionsRoleCharsLen; - int addedExtras = 0; - int nextRoleChar = 0; - StringBuffer pageEditorSettings = new StringBuffer(); - for ( int i = 0 ; i < hexLen ; i++ ) - { // here we "mix-up" (obfuscate) the way this information is provided to the client-side - // this is done to avoid obvious display of certain strings in content, like "manager" or "admin" - int rndVal = getRandom( rnd, 0x1000, 0xFFFD ); - boolean isRndValEven = ( (rndVal % 2) == 0 ); - int rndValTens = (int)Math.floor( rndVal / 10 ); - int rndValTensEven = ( ( ( rndValTens % 2 ) == 1 ) ? Math.max( rndValTens - 1, 2 ) : rndValTens ); - int valToHex; - if ( i == 0 ) - { - valToHex = pageEditorConfigFlags[0]; - } - else if ( addedExtras < extrasCount && ( ( ( i % 2 ) == 1 ) || nextRoleChar >= allowEditNoactionsRoleCharsLen ) ) - { - if ( ! isRndValEven ) - rndVal++; - valToHex = getRandom( rnd, 0x0A00, 0xDFFF ); - if ( (valToHex % 2) == 1 ) - valToHex = valToHex + 1; - pageEditorSettings.append( ", " ); - addedExtras++; - } - else - { - //log.info( "char '" + allowEditNoactionsRoleChars[nextRoleChar] + "' numericval=" + (int)allowEditNoactionsRoleChars[nextRoleChar] + " hex=" + Integer.toHexString( (int)allowEditNoactionsRoleChars[nextRoleChar] ) + " hexLshift4=" + Integer.toHexString( (int)allowEditNoactionsRoleChars[nextRoleChar] << 4 ) + " hexLshift4+1=" + Integer.toHexString( ((int)allowEditNoactionsRoleChars[nextRoleChar] << 4 ) | 0x0001 ) ); - valToHex = ( ((int)allowEditNoactionsRoleChars[nextRoleChar] << 4 ) | 0x0001 ); - pageEditorSettings.append( ", " ); - nextRoleChar++; - } - String rndValHex = Integer.toHexString( 0x10000 | rndVal ).substring( 1 ); - - String realValHex = Integer.toHexString( 0x10000 | ( valToHex + rndValTensEven ) ).substring( 1 ); - if ( isRndValEven && i > 0 ) - pageEditorSettings.append( "0x" ).append( realValHex ).append( rndValHex ); - else - pageEditorSettings.append( "0x" ).append( rndValHex ).append( realValHex ); - } - dojoConfigAddOn.append( " " ).append( DOJO_CONFIG_PAGEEDITOR_SETTINGS_NAME ).append( " = [ " ).append( pageEditorSettings.toString() ).append( " ];" ).append( EOL ); + propValue = desktopLayoutDecoration + .getProperty(DESKTOP_PAGEEDITOR_PAGE_ADD_ENABLED); + processBooleanFlagProperty(pageEditorConfigFlags, propValue, + DESKTOP_PAGEEDITOR_PAGE_ADD_ENABLED_DEFAULT, + DESKTOP_PAGEEDITOR_PAGE_ADD_ENABLED_TRUE); + + propValue = desktopLayoutDecoration + .getProperty(DESKTOP_PAGEEDITOR_PORTLET_ADD_ENABLED); + processBooleanFlagProperty(pageEditorConfigFlags, propValue, + DESKTOP_PAGEEDITOR_PORTLET_ADD_ENABLED_DEFAULT, + DESKTOP_PAGEEDITOR_PORTLET_ADD_ENABLED_TRUE); + + propValue = desktopLayoutDecoration + .getProperty(DESKTOP_PAGEEDITOR_PAGE_PORTLET_DECORATOR_EDITABLE); + processBooleanFlagProperty(pageEditorConfigFlags, propValue, + DESKTOP_PAGEEDITOR_PAGE_PORTLET_DECORATOR_EDITABLE_DEFAULT, + DESKTOP_PAGEEDITOR_PAGE_PORTLET_DECORATOR_EDITABLE_TRUE); + + propValue = desktopLayoutDecoration + .getProperty(DESKTOP_PAGEEDITOR_PORTLET_DECORATOR_EDITABLE); + processBooleanFlagProperty(pageEditorConfigFlags, propValue, + DESKTOP_PAGEEDITOR_PORTLET_DECORATOR_EDITABLE_DEFAULT, + DESKTOP_PAGEEDITOR_PORTLET_DECORATOR_EDITABLE_TRUE); + + propValue = desktopLayoutDecoration + .getProperty(DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITABLE); + processBooleanFlagProperty(pageEditorConfigFlags, propValue, + DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITABLE_DEFAULT, + DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITABLE_TRUE); + + propValue = desktopLayoutDecoration + .getProperty(DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_TOPLEVEL_MOVEABLE); + processBooleanFlagProperty(pageEditorConfigFlags, propValue, + DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_TOPLEVEL_MOVEABLE_DEFAULT, + DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_TOPLEVEL_MOVEABLE_TRUE); + + propValue = desktopLayoutDecoration + .getProperty(DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_COLUMNSIZE_EDITABLE); + processBooleanFlagProperty( + pageEditorConfigFlags, + propValue, + DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_COLUMNSIZE_EDITABLE_DEFAULT, + DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_COLUMNSIZE_EDITABLE_TRUE); + + propValue = desktopLayoutDecoration + .getProperty(DESKTOP_PAGEEDITOR_MOVEMODE_ISDEFAULT); + processBooleanFlagProperty(pageEditorConfigFlags, propValue, + DESKTOP_PAGEEDITOR_MOVEMODE_ISDEFAULT_DEFAULT, + DESKTOP_PAGEEDITOR_MOVEMODE_ISDEFAULT_TRUE); + + propValue = desktopLayoutDecoration + .getProperty(DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DEPTH_MAX); + Integer maxLayoutNestingObj = null; + try + { + maxLayoutNestingObj = new Integer(propValue); + } + catch (NumberFormatException ex) + { + maxLayoutNestingObj = new Integer( + DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DEPTH_MAX_DEFAULT); + } + int maxLayoutNesting = maxLayoutNestingObj.intValue(); + if (maxLayoutNesting < 0) maxLayoutNesting = 0; + if (maxLayoutNesting > DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DEPTH_MAX_RESERVED) + maxLayoutNesting = DESKTOP_PAGEEDITOR_PAGE_LAYOUT_DEPTH_MAX_RESERVED; + pageEditorConfigFlags[0] += maxLayoutNesting; + + String allowEditNoactionsRole = desktopLayoutDecoration + .getProperty(DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITOR_ROLE); + if (allowEditNoactionsRole == null) + allowEditNoactionsRole = DESKTOP_PAGEEDITOR_LAYOUT_NOACTIONS_EDITOR_ROLE_DEFAULT; + if (allowEditNoactionsRole == null) allowEditNoactionsRole = ""; + char[] allowEditNoactionsRoleChars = allowEditNoactionsRole + .toCharArray(); + int allowEditNoactionsRoleCharsLen = ((allowEditNoactionsRoleChars == null) ? 0 + : allowEditNoactionsRoleChars.length); + Random rnd = new Random(); + int extrasCount = (allowEditNoactionsRoleCharsLen > 0 ? getRandom(rnd, + 2, 5) : getRandom(rnd, 5, 8)); + int hexLen = 1 + extrasCount + allowEditNoactionsRoleCharsLen; + int addedExtras = 0; + int nextRoleChar = 0; + StringBuffer pageEditorSettings = new StringBuffer(); + for (int i = 0; i < hexLen; i++) + { // here we "mix-up" (obfuscate) the way this information is provided + // to the client-side + // this is done to avoid obvious display of certain strings in + // content, like "manager" or "admin" + int rndVal = getRandom(rnd, 0x1000, 0xFFFD); + boolean isRndValEven = ((rndVal % 2) == 0); + int rndValTens = (int) Math.floor(rndVal / 10); + int rndValTensEven = (((rndValTens % 2) == 1) ? Math.max( + rndValTens - 1, 2) : rndValTens); + int valToHex; + if (i == 0) + { + valToHex = pageEditorConfigFlags[0]; + } + else if (addedExtras < extrasCount + && (((i % 2) == 1) || nextRoleChar >= allowEditNoactionsRoleCharsLen)) + { + if (!isRndValEven) rndVal++; + valToHex = getRandom(rnd, 0x0A00, 0xDFFF); + if ((valToHex % 2) == 1) valToHex = valToHex + 1; + pageEditorSettings.append(", "); + addedExtras++; + } + else + { + // log.info( "char '" + + // allowEditNoactionsRoleChars[nextRoleChar] + "' numericval=" + + // (int)allowEditNoactionsRoleChars[nextRoleChar] + " hex=" + + // Integer.toHexString( + // (int)allowEditNoactionsRoleChars[nextRoleChar] ) + " + // hexLshift4=" + Integer.toHexString( + // (int)allowEditNoactionsRoleChars[nextRoleChar] << 4 ) + " + // hexLshift4+1=" + Integer.toHexString( + // ((int)allowEditNoactionsRoleChars[nextRoleChar] << 4 ) | + // 0x0001 ) ); + valToHex = (((int) allowEditNoactionsRoleChars[nextRoleChar] << 4) | 0x0001); + pageEditorSettings.append(", "); + nextRoleChar++; + } + String rndValHex = Integer.toHexString(0x10000 | rndVal).substring( + 1); + + String realValHex = Integer.toHexString( + 0x10000 | (valToHex + rndValTensEven)).substring(1); + if (isRndValEven && i > 0) + pageEditorSettings.append("0x").append(realValHex).append( + rndValHex); + else + pageEditorSettings.append("0x").append(rndValHex).append( + realValHex); + } + dojoConfigAddOn.append(" ").append( + DOJO_CONFIG_PAGEEDITOR_SETTINGS_NAME).append(" = [ ").append( + pageEditorSettings.toString()).append(" ];").append(EOL); } - private int getRandom( Random rnd, int minValueInclusive, int maxValueExclusive ) + + private int getRandom(Random rnd, int minValueInclusive, + int maxValueExclusive) { - if ( minValueInclusive > maxValueExclusive ) - throw new IllegalArgumentException( "minValueInclusive (" + minValueInclusive + ") cannot be greater than maxValueExclusive (" + maxValueExclusive + ")" ); + if (minValueInclusive > maxValueExclusive) + throw new IllegalArgumentException("minValueInclusive (" + + minValueInclusive + + ") cannot be greater than maxValueExclusive (" + + maxValueExclusive + ")"); - int diff = (int)( maxValueExclusive - minValueInclusive ); - if ( diff == 0 ) - return minValueInclusive; + int diff = (int) (maxValueExclusive - minValueInclusive); + if (diff == 0) return minValueInclusive; - double sample = rnd.nextDouble(); - int result = (int)( sample * diff + minValueInclusive ); - result = ( ( result != maxValueExclusive ) ? result : ( result - 1 ) ); - return result; + double sample = rnd.nextDouble(); + int result = (int) (sample * diff + minValueInclusive); + result = ((result != maxValueExclusive) ? result : (result - 1)); + return result; } - - private void processBooleanFlagProperty( int[] flags, Object propVal, Object propValDefault, int propIsTrueBit ) + + private void processBooleanFlagProperty(int[] flags, Object propVal, + Object propValDefault, int propIsTrueBit) { - String boolStr = ( ( propVal == null ) ? ( ( propValDefault == null ) ? (String)null : propValDefault.toString() ) : propVal.toString() ); - if ( boolStr != null && boolStr.toLowerCase().equals( "true" ) ) - flags[0] |= propIsTrueBit; + String boolStr = ((propVal == null) ? ((propValDefault == null) ? (String) null + : propValDefault.toString()) + : propVal.toString()); + if (boolStr != null && boolStr.toLowerCase().equals("true")) + flags[0] |= propIsTrueBit; } - private String getCachedContent( String cacheKey ) + private String getCachedContent(String cacheKey) { - CacheElement cachedElement = desktopContentCache.get(cacheKey); - if (cachedElement != null) - return (String)cachedElement.getContent(); + CacheElement cachedElement = desktopContentCache.get(cacheKey); + if (cachedElement != null) return (String) cachedElement.getContent(); return null; } - private void setCachedContent( String cacheKey, String content ) + + private void setCachedContent(String cacheKey, String content) { - CacheElement cachedElement = desktopContentCache.createElement( cacheKey, content ); - cachedElement.setTimeToIdleSeconds(desktopContentCache.getTimeToIdleSeconds()); - cachedElement.setTimeToLiveSeconds(desktopContentCache.getTimeToLiveSeconds()); - desktopContentCache.put( cachedElement ); + CacheElement cachedElement = desktopContentCache.createElement( + cacheKey, content); + cachedElement.setTimeToIdleSeconds(desktopContentCache + .getTimeToIdleSeconds()); + cachedElement.setTimeToLiveSeconds(desktopContentCache + .getTimeToLiveSeconds()); + desktopContentCache.put(cachedElement); } - private String getResourcesAsJavascriptObject( String resourceNamePrefix, String[] resourceNames, ResourceBundle messages, String varName, String indent, boolean ifEmptyReturnEmptyString ) + private String getResourcesAsJavascriptObject(String resourceNamePrefix, + String[] resourceNames, ResourceBundle messages, String varName, + String indent, boolean ifEmptyReturnEmptyString) { - StringBuffer jsObjBuffer = new StringBuffer(); + StringBuffer jsObjBuffer = new StringBuffer(); boolean atLeastOneFound = false; - if ( indent != null ) - jsObjBuffer.append( indent ); - if ( varName != null ) - jsObjBuffer.append( varName ).append( " = " ); - jsObjBuffer.append( "{ " ); - for ( int i = 0 ; i < resourceNames.length ; i++ ) + if (indent != null) jsObjBuffer.append(indent); + if (varName != null) jsObjBuffer.append(varName).append(" = "); + jsObjBuffer.append("{ "); + for (int i = 0; i < resourceNames.length; i++) { String resourceValue = null; - try - { - resourceValue = messages.getString( resourceNamePrefix + resourceNames[ i ] ); - } - catch ( java.util.MissingResourceException ex ) { } - if ( resourceValue != null ) + try { - if ( atLeastOneFound ) + resourceValue = messages.getString(resourceNamePrefix + + resourceNames[i]); + } + catch (java.util.MissingResourceException ex) + { + } + if (resourceValue != null) + { + if (atLeastOneFound) { - jsObjBuffer.append( ", " ); + jsObjBuffer.append(", "); } else { - atLeastOneFound = true; + atLeastOneFound = true; } - jsObjBuffer.append( resourceNames[ i ] ).append( ": \"" ).append( resourceValue ).append( "\"" ); + jsObjBuffer.append(resourceNames[i]).append(": \"").append( + resourceValue).append("\""); } } - jsObjBuffer.append( " };" ); - if ( ! atLeastOneFound && ifEmptyReturnEmptyString ) - return ""; + jsObjBuffer.append(" };"); + if (!atLeastOneFound && ifEmptyReturnEmptyString) return ""; return jsObjBuffer.toString(); } - - public boolean isDesktopEnabled( RequestContext requestContext ) + + public boolean isDesktopEnabled(RequestContext requestContext) { - return this.decorationFactory.isDesktopEnabled( requestContext ); + return this.decorationFactory.isDesktopEnabled(requestContext); } - + public ServletContext getServletContext() { return servletContext; @@ -720,14 +1070,15 @@ { this.servletContext = servletContext; } - + public HeaderResourceFactory getHeaderResourceFactory() { return this.headerResourceFactory; } - - // get portal urls - each of these methods is copied from HeaderResourceImpl.java - + + // get portal urls - each of these methods is copied from + // HeaderResourceImpl.java + /** * Desktop servlet path ( e.g. /desktop ) * @@ -737,93 +1088,102 @@ { return this.desktopServletPath; } - + /** * Portal base url ( e.g. http://localhost:8080/jetspeed ) * * @return portal base url */ - public String getPortalBaseUrl( RequestContext context ) + public String getPortalBaseUrl(RequestContext context) { - return HeaderResourceLib.getPortalBaseUrl( context, this.baseUrlAccess ); + return HeaderResourceLib.getPortalBaseUrl(context, this.baseUrlAccess); } - + /** * Portal base url ( e.g. http://localhost:8080/jetspeed ) * * @return portal base url */ - public String getPortalBaseUrl( RequestContext context, boolean encode ) + public String getPortalBaseUrl(RequestContext context, boolean encode) { - String baseurl = getPortalBaseUrl( context ); - if ( ! encode ) + String baseurl = getPortalBaseUrl(context); + if (!encode) { return baseurl; } else { - return context.getResponse().encodeURL( baseurl ); + return context.getResponse().encodeURL(baseurl); } } - + /** - * Portal base url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/javascript/dojo/ ) + * Portal base url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/javascript/dojo/ ) * * @return portal base url with relativePath argument appended */ - public String getPortalResourceUrl( RequestContext context, String relativePath ) + public String getPortalResourceUrl(RequestContext context, + String relativePath) { - return getPortalResourceUrl( context, relativePath, false ); + return getPortalResourceUrl(context, relativePath, false); } - + /** - * Portal base url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/javascript/dojo/ ) + * Portal base url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/javascript/dojo/ ) * * @return portal base url with relativePath argument appended */ - public String getPortalResourceUrl( RequestContext context, String relativePath, boolean encode ) + public String getPortalResourceUrl(RequestContext context, + String relativePath, boolean encode) { - return HeaderResourceLib.getPortalResourceUrl( relativePath, getPortalBaseUrl( context ), encode, context ); + return HeaderResourceLib.getPortalResourceUrl(relativePath, + getPortalBaseUrl(context), encode, context); } - + /** * Portal base servlet url ( e.g. http://localhost:8080/jetspeed/desktop/ ) * * @return portal base servlet url */ - public String getPortalUrl( RequestContext context ) + public String getPortalUrl(RequestContext context) { - return HeaderResourceLib.getPortalUrl( getPortalBaseUrl( context ), context, getDesktopServletPath() ); + return HeaderResourceLib.getPortalUrl(getPortalBaseUrl(context), + context, getDesktopServletPath()); } - + /** * Portal base servlet url ( e.g. http://localhost:8080/jetspeed/desktop/ ) * * @return portal base servlet url */ - public String getPortalUrl( RequestContext context, boolean encode ) + public String getPortalUrl(RequestContext context, boolean encode) { - return getPortalUrl( context, null, encode ); + return getPortalUrl(context, null, encode); } - + /** - * Portal base servlet url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/desktop/default-page.psml ) + * Portal base servlet url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/desktop/default-page.psml ) * * @return portal base servlet url with relativePath argument appended */ - public String getPortalUrl( RequestContext context, String relativePath ) + public String getPortalUrl(RequestContext context, String relativePath) { - return getPortalUrl( context, relativePath, false ); + return getPortalUrl(context, relativePath, false); } - + /** - * Portal base servlet url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/desktop/default-page.psml ) + * Portal base servlet url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/desktop/default-page.psml ) * * @return portal base servlet url with relativePath argument appended */ - public String getPortalUrl( RequestContext context, String relativePath, boolean encode ) + public String getPortalUrl(RequestContext context, String relativePath, + boolean encode) { - return HeaderResourceLib.getPortalResourceUrl( relativePath, getPortalUrl( context ), encode, context ); + return HeaderResourceLib.getPortalResourceUrl(relativePath, + getPortalUrl(context), encode, context); } } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/JetspeedEngine.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/JetspeedEngine.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/JetspeedEngine.java 2008-05-16 01:54:54 UTC (rev 940) @@ -44,98 +44,117 @@ import org.apache.pluto.services.factory.FactoryManagerService; import org.springframework.beans.factory.NoSuchBeanDefinitionException; - /** *

        * AbstractEngine *

        *

        - * + * *

        + * * @author David Sean Taylor * @author Scott T. Weaver * @version $Id: AbstractEngine.java 188433 2005-03-23 22:50:44Z ate $ - * + * */ public class JetspeedEngine implements Engine -{ +{ + private final PortalContext context; + private final ServletConfig config; + private final ComponentManager componentManager; - private Map pipelineMapper ; + + private Map pipelineMapper; + private PortalStatistics statistics; - + protected static final Log log = LogFactory.getLog(JetspeedEngine.class); - protected String defaultPipelineName; - public JetspeedEngine(Configuration configuration, String applicationRoot, ServletConfig config, ComponentManager componentManager ) + protected String defaultPipelineName; + + public JetspeedEngine(Configuration configuration, String applicationRoot, + ServletConfig config, ComponentManager componentManager) { - this(new PortalConfigurationImpl(configuration), applicationRoot, config, componentManager); + this(new PortalConfigurationImpl(configuration), applicationRoot, + config, componentManager); } - - public JetspeedEngine(PortalConfiguration configuration, String applicationRoot, ServletConfig config, ComponentManager componentManager ) + + public JetspeedEngine(PortalConfiguration configuration, + String applicationRoot, ServletConfig config, + ComponentManager componentManager) { this.componentManager = componentManager; - this.context = new JetspeedPortalContext(this, configuration, applicationRoot); + this.context = new JetspeedPortalContext(this, configuration, + applicationRoot); this.config = config; context.setApplicationRoot(applicationRoot); - context.setConfiguration(configuration); + context.setConfiguration(configuration); - defaultPipelineName = configuration.getString(PIPELINE_DEFAULT, "jetspeed-pipeline"); - configuration.setString(JetspeedEngineConstants.APPLICATION_ROOT_KEY, applicationRoot); - + defaultPipelineName = configuration.getString(PIPELINE_DEFAULT, + "jetspeed-pipeline"); + configuration.setString(JetspeedEngineConstants.APPLICATION_ROOT_KEY, + applicationRoot); + // Make these availble as beans to Spring componentManager.addComponent("Engine", this); componentManager.addComponent("PortalContext", context); componentManager.addComponent("PortalConfiguration", configuration); - } - - + } /** * Initializes the engine with a commons configuration, starting all early * initable services. * * @param configuration - * a commons Configuration set + * a commons Configuration set * @param applicationRoot - * a String path to the application root for - * resources + * a String path to the application root for + * resources * @param * @throws JetspeedException - * when the engine fails to initilialize + * when the engine fails to initilialize */ public void start() throws JetspeedException - { + { DateFormat format = DateFormat.getInstance(); - Date startTime = new Date(); + Date startTime = new Date(); try - { - log.info("Starting Jetspeed Engine ("+getClass().getName()+") at "+format.format(startTime)); - + { + log.info("Starting Jetspeed Engine (" + getClass().getName() + + ") at " + format.format(startTime)); + // patch up OJB ClassLoader ploader2 = this.getClass().getClassLoader(); - //ClassLoader ploader2 = Thread.currentThread().getContextClassLoader(); + // ClassLoader ploader2 = + // Thread.currentThread().getContextClassLoader(); ClassHelper.setClassLoader(ploader2); - - //Start the ComponentManager - componentManager.start(); - pipelineMapper = (Map)componentManager.getComponent("pipeline-map"); + + // Start the ComponentManager + componentManager.start(); + pipelineMapper = (Map) componentManager + .getComponent("pipeline-map"); try { - statistics = (PortalStatistics)componentManager.getComponent("PortalStatistics"); + statistics = (PortalStatistics) componentManager + .getComponent("PortalStatistics"); } catch (Exception e) { // silenty ignore, its not configured // TODO: statistics as an AOP advice } - // TODO: complete this work for JSP (https://issues.apache.org/jira/browse/JS2-711) - // I think config.getServletName is incorrect, need to fix this and change this name to jetspeed-layouts:: when looking up in registry + // TODO: complete this work for JSP + // (https://issues.apache.org/jira/browse/JS2-711) + // I think config.getServletName is incorrect, need to fix this and + // change this name to jetspeed-layouts:: when looking up in + // registry // but not when dispatching, still trying to figure that out - //PortletApplicationManagement pam = (PortletApplicationManagement)componentManager.getComponent("PAM"); - //pam.startInternalApplication(config.getServletName()); - + // PortletApplicationManagement pam = + // (PortletApplicationManagement)componentManager.getComponent("PAM"); + // pam.startInternalApplication(config.getServletName()); + } catch (Throwable e) { @@ -144,11 +163,12 @@ throw new JetspeedException("Jetspeed Initialization exception!", e); } finally - { + { Date endTime = new Date(); long elapsedTime = (endTime.getTime() - startTime.getTime()) / 1000; - log.info("Finished starting Jetspeed Engine ("+getClass().getName()+") at "+format.format(endTime) - +". Elapsed time: "+elapsedTime+" seconds."); + log.info("Finished starting Jetspeed Engine (" + + getClass().getName() + ") at " + format.format(endTime) + + ". Elapsed time: " + elapsedTime + " seconds."); } } @@ -163,11 +183,9 @@ return this.config; } + public void shutdown() throws JetspeedException + { - - public void shutdown() throws JetspeedException - { - try { PortletContainer container = (PortletContainer) componentManager @@ -176,7 +194,7 @@ { container.shutdown(); } - + componentManager.stop(); } catch (PortletContainerException e) @@ -186,23 +204,25 @@ System.gc(); } - public void service( RequestContext context ) throws JetspeedException - { + public void service(RequestContext context) throws JetspeedException + { long start = System.currentTimeMillis(); String targetPipeline = context .getRequestParameter(PortalReservedParameters.PIPELINE); if (null == targetPipeline) { - targetPipeline = (String)context.getAttribute(PortalReservedParameters.PIPELINE); + targetPipeline = (String) context + .getAttribute(PortalReservedParameters.PIPELINE); if (null == targetPipeline) { - String pipelineKey = context.getRequest().getServletPath(); + String pipelineKey = context.getRequest().getServletPath(); if (null != pipelineKey) { if (pipelineKey.equals("/portal")) targetPipeline = this.defaultPipelineName; else - targetPipeline = (String)pipelineMapper.get(pipelineKey); + targetPipeline = (String) pipelineMapper + .get(pipelineKey); // System.out.println("pipeline = " + targetPipeline); } else @@ -222,13 +242,14 @@ } else pipeline = getPipeline(); - + context.setPipeline(pipeline); pipeline.invoke(context); - + long end = System.currentTimeMillis(); if (statistics != null) - statistics.logPageAccess(context, PortalStatistics.HTTP_OK, end - start); + statistics.logPageAccess(context, PortalStatistics.HTTP_OK, end + - start); } /** @@ -244,9 +265,9 @@ /** * Given a application relative path, returns the real path relative to the * application root - * + * */ - public String getRealPath( String path ) + public String getRealPath(String path) { String result = ""; String base = context.getApplicationRoot(); @@ -268,8 +289,8 @@ } return base.concat(path); } - - public Pipeline getPipeline( String pipelineName ) + + public Pipeline getPipeline(String pipelineName) { return (Pipeline) componentManager.getComponent(pipelineName); } @@ -285,7 +306,7 @@ public RequestContext getCurrentRequestContext() { RequestContextComponent contextComponent = (RequestContextComponent) getComponentManager() - .getComponent(RequestContextComponent.class); + .getComponent(RequestContextComponent.class); return contextComponent.getRequestContext(); } @@ -293,42 +314,42 @@ { return this.componentManager; } + /** *

        * getFactory *

        - * + * * @see org.apache.pluto.services.factory.FactoryManagerService#getFactory(java.lang.Class) * @param theClass * @return */ - public Factory getFactory( Class theClass ) - { + public Factory getFactory(Class theClass) + { return (Factory) getComponentManager().getComponent(theClass); } + /** *

        * getContainerService *

        - * + * * @see org.apache.pluto.services.PortletContainerEnvironment#getContainerService(java.lang.Class) * @param service * @return */ - public ContainerService getContainerService( Class service ) + public ContainerService getContainerService(Class service) { - if(service.equals(FactoryManagerService.class)) - { - return this; - } + if (service.equals(FactoryManagerService.class)) { return this; } try { - return (ContainerService) getComponentManager().getComponent(service); + return (ContainerService) getComponentManager().getComponent( + service); } catch (NoSuchBeanDefinitionException e) { - log.warn("No ContainerService defined for "+service.getName()); + log.warn("No ContainerService defined for " + service.getName()); return null; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/JetspeedServlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/JetspeedServlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/JetspeedServlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -59,11 +59,12 @@ * @author David Sean Taylor * @version $Id: JetspeedServlet.java 553340 2007-07-04 22:00:09Z taylor $ */ -public class JetspeedServlet -extends HttpServlet -implements JetspeedEngineConstants, HttpSessionListener +public class JetspeedServlet extends HttpServlet implements + JetspeedEngineConstants, HttpSessionListener { + private static Log log; + private static Log console; /** @@ -87,29 +88,31 @@ * The Jetspeed Engine */ private static Engine engine; + private static RequestContextComponent contextComponent; - + private static String webappRoot; // ------------------------------------------------------------------- // I N I T I A L I Z A T I O N // ------------------------------------------------------------------- private static final String INIT_START_MSG = "Jetspeed Starting Initialization..."; + private static final String INIT_DONE_MSG = "Jetspeed Initialization complete, Ready to service requests."; /** * Intialize Servlet. */ - public final void init( ServletConfig config ) throws ServletException + public final void init(ServletConfig config) throws ServletException { synchronized (this.getClass()) { - if ( log == null ) + if (log == null) { log = LogFactory.getLog(JetspeedServlet.class); - console = LogFactory.getLog(CONSOLE_LOGGER); + console = LogFactory.getLog(CONSOLE_LOGGER); } - + console.info(INIT_START_MSG); super.init(config); @@ -117,7 +120,8 @@ if (!firstInit) { log.info("Double initialization of Jetspeed was attempted!"); - console.info("Double initialization of Jetspeed was attempted!"); + console + .info("Double initialization of Jetspeed was attempted!"); return; } // executing init will trigger some static initializers, so we have @@ -129,42 +133,55 @@ ServletContext context = config.getServletContext(); - String propertiesFilename = ServletHelper.findInitParameter(context, config, JETSPEED_PROPERTIES_KEY, + String propertiesFilename = ServletHelper.findInitParameter( + context, config, JETSPEED_PROPERTIES_KEY, JETSPEED_PROPERTIES_DEFAULT); - String applicationRoot = ServletHelper.findInitParameter(context, config, APPLICATION_ROOT_KEY, + String applicationRoot = ServletHelper.findInitParameter( + context, config, APPLICATION_ROOT_KEY, APPLICATION_ROOT_DEFAULT); - console.info("JetspeedServlet identifying web application root..."); + console + .info("JetspeedServlet identifying web application root..."); webappRoot = config.getServletContext().getRealPath("/"); - console.info("JetspeedServlet identifed web application root as " + webappRoot); + console + .info("JetspeedServlet identifed web application root as " + + webappRoot); - if (applicationRoot == null || applicationRoot.equals(WEB_CONTEXT)) + if (applicationRoot == null + || applicationRoot.equals(WEB_CONTEXT)) { applicationRoot = webappRoot; } - Configuration properties = new PropertiesConfiguration(ServletHelper.getRealPath( - config, propertiesFilename)); + Configuration properties = new PropertiesConfiguration( + ServletHelper.getRealPath(config, propertiesFilename)); properties.setProperty(APPLICATION_ROOT_KEY, applicationRoot); properties.setProperty(WEBAPP_ROOT_KEY, webappRoot); - console.info("JetspeedServlet attempting to create the portlet engine..."); + console + .info("JetspeedServlet attempting to create the portlet engine..."); - engine = new JetspeedEngine(properties, applicationRoot, config, initializeComponentManager(config, applicationRoot, properties)); - - console.info("JetspeedServlet attempting to start the Jetspeed Portal Engine..."); + engine = new JetspeedEngine(properties, applicationRoot, + config, initializeComponentManager(config, + applicationRoot, properties)); + + console + .info("JetspeedServlet attempting to start the Jetspeed Portal Engine..."); Jetspeed.setEngine(engine); - engine.start(); - console.info("JetspeedServlet has successfuly started the Jetspeed Portal Engine...."); - contextComponent = (RequestContextComponent) Jetspeed.getComponentManager().getComponent(RequestContextComponent.class); + engine.start(); + console + .info("JetspeedServlet has successfuly started the Jetspeed Portal Engine...."); + contextComponent = (RequestContextComponent) Jetspeed + .getComponentManager().getComponent( + RequestContextComponent.class); } catch (Throwable e) { // save the exception to complain loudly later :-) final String msg = "Jetspeed: init() failed: "; - initFailure = e; + initFailure = e; log.fatal(msg, e); console.fatal(msg, e); } @@ -181,7 +198,8 @@ * @param data * The first GET request. */ - public final void init( HttpServletRequest request, HttpServletResponse response ) + public final void init(HttpServletRequest request, + HttpServletResponse response) { synchronized (JetspeedServlet.class) { @@ -209,15 +227,15 @@ * @exception ServletException * a servlet exception. */ - public final void doGet( HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException + public final void doGet(HttpServletRequest req, HttpServletResponse res) + throws IOException, ServletException { try { // Check to make sure that we started up properly. - if (initFailure != null) - { - throw new ServletException("Failed to initalize jetspeed. "+initFailure.toString(), initFailure); - } + if (initFailure != null) { throw new ServletException( + "Failed to initalize jetspeed. " + initFailure.toString(), + initFailure); } // If this is the first invocation, perform some late // initialization. @@ -226,19 +244,25 @@ init(req, res); } - //If we already passed though the content filter DON'T send it to the - // engine. This is a crappy hack until we find a better solution. - String wasFiltered = (String) req.getAttribute("org.apache.jetspeed.content.filtered"); + // If we already passed though the content filter DON'T send it to + // the + // engine. This is a crappy hack until we find a better solution. + String wasFiltered = (String) req + .getAttribute("org.apache.jetspeed.content.filtered"); if (wasFiltered == null || !wasFiltered.equals("true")) { // ensure that no proxy or brower caching is performed // on dynamic responses resulting from pipeline execution - res.setHeader("Cache-Control", "no-cache,no-store,private"); // HTTP/1.1 modern browser/proxy - res.setHeader("Pragma", "no-cache"); // HTTP/1.0 non-standard proxy - res.setHeader("Expires", "0"); // HTTP/1.0 browser/proxy + res.setHeader("Cache-Control", "no-cache,no-store,private"); // HTTP/1.1 + // modern + // browser/proxy + res.setHeader("Pragma", "no-cache"); // HTTP/1.0 non-standard + // proxy + res.setHeader("Expires", "0"); // HTTP/1.0 browser/proxy // send request through pipeline - RequestContext context = contextComponent.create(req, res, getServletConfig()); + RequestContext context = contextComponent.create(req, res, + getServletConfig()); engine.service(context); contextComponent.release(context); } @@ -246,7 +270,8 @@ } catch (JetspeedException e) { - final String msg = "Fatal error encountered while processing portal request: "+e.toString(); + final String msg = "Fatal error encountered while processing portal request: " + + e.toString(); log.fatal(msg, e); throw new ServletException(msg, e); } @@ -264,7 +289,8 @@ * @exception ServletException * a servlet exception. */ - public final void doPost( HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException + public final void doPost(HttpServletRequest req, HttpServletResponse res) + throws IOException, ServletException { doGet(req, res); } @@ -293,13 +319,13 @@ firstInit = true; log.info("Done shutting down!"); - } - + } + /** - * If you prefer to use a component manager other than Spring, you - * can override this method to do so. Do not explicitly call start() - * of the ComponentManager as the JetspeedEngine will do this within its - * own start() method. + * If you prefer to use a component manager other than Spring, you can + * override this method to do so. Do not explicitly call start() of the + * ComponentManager as the JetspeedEngine will do this within its own + * start() method. * * @param servletConfig * @param appRoot @@ -307,79 +333,102 @@ * @return * @throws IOException */ - protected ComponentManager initializeComponentManager(ServletConfig servletConfig, String appRoot, Configuration configuration) throws IOException + protected ComponentManager initializeComponentManager( + ServletConfig servletConfig, String appRoot, + Configuration configuration) throws IOException { ServletConfigFactoryBean.setServletConfig(servletConfig); - final String assemblyDir = configuration.getString("assembly.dir","/WEB-INF/assembly"); - final String assemblyFileExtension = configuration.getString("assembly.extension",".xml"); - - String[] bootConfigs = new String[] {"/WEB-INF/assembly/boot/*.xml"}; - String[] appConfigs = new String[] {assemblyDir+"/*"+assemblyFileExtension, assemblyDir+"/override/*"+assemblyFileExtension}; + final String assemblyDir = configuration.getString("assembly.dir", + "/WEB-INF/assembly"); + final String assemblyFileExtension = configuration.getString( + "assembly.extension", ".xml"); + + String[] bootConfigs = new String[] + {"/WEB-INF/assembly/boot/*.xml"}; + String[] appConfigs = new String[] + {assemblyDir + "/*" + assemblyFileExtension, + assemblyDir + "/override/*" + assemblyFileExtension}; ServletContext servletContext = servletConfig.getServletContext(); - SpringComponentManager cm = new SpringComponentManager(bootConfigs, appConfigs, servletContext, appRoot); - - return cm; + SpringComponentManager cm = new SpringComponentManager(bootConfigs, + appConfigs, servletContext, appRoot); + + return cm; } - + public void sessionCreated(HttpSessionEvent se) { PortletServices services = JetspeedPortletServices.getSingleton(); if (services != null) { - PortalSessionsManager psm = (PortalSessionsManager)services.getService(PortalSessionsManager.SERVICE_NAME); + PortalSessionsManager psm = (PortalSessionsManager) services + .getService(PortalSessionsManager.SERVICE_NAME); if (psm != null) { psm.portalSessionCreated(se.getSession()); } } } - + public void sessionDestroyed(HttpSessionEvent se) { - Subject subject = (Subject)se.getSession().getAttribute(PortalReservedParameters.SESSION_KEY_SUBJECT); - if (subject == null) - return; + Subject subject = (Subject) se.getSession().getAttribute( + PortalReservedParameters.SESSION_KEY_SUBJECT); + if (subject == null) return; if (firstInit) { - // Servlet already destroyed, + // Servlet already destroyed, // Can't reliably access ComponentManager (Spring) anymore - // as for instance WAS 6.0.2 has a bug invoking this method with a wrong classLoader (not the one for the WebApp) + // as for instance WAS 6.0.2 has a bug invoking this method with a + // wrong classLoader (not the one for the WebApp) return; - } - Principal subjectUserPrincipal = SecurityHelper.getPrincipal(subject, UserPrincipal.class); - PortalStatistics statistics = (PortalStatistics)engine.getComponentManager().getComponent("PortalStatistics"); - long sessionLength = System.currentTimeMillis() - se.getSession().getCreationTime(); - String ipAddress = (String)se.getSession().getAttribute(SecurityValve.IP_ADDRESS); - statistics.logUserLogout(ipAddress, subjectUserPrincipal.getName(), sessionLength); - JetspeedCache portletContentCache = (JetspeedCache)engine.getComponentManager().getComponent("portletContentCache"); + } + Principal subjectUserPrincipal = SecurityHelper.getPrincipal(subject, + UserPrincipal.class); + PortalStatistics statistics = (PortalStatistics) engine + .getComponentManager().getComponent("PortalStatistics"); + long sessionLength = System.currentTimeMillis() + - se.getSession().getCreationTime(); + String ipAddress = (String) se.getSession().getAttribute( + SecurityValve.IP_ADDRESS); + statistics.logUserLogout(ipAddress, subjectUserPrincipal.getName(), + sessionLength); + JetspeedCache portletContentCache = (JetspeedCache) engine + .getComponentManager().getComponent("portletContentCache"); JetspeedCache decorationContentCache = null; - + try { - decorationContentCache = (JetspeedCache)engine.getComponentManager().getComponent("decorationContentCache"); + decorationContentCache = (JetspeedCache) engine + .getComponentManager().getComponent( + "decorationContentCache"); } catch (Exception e) { } - - ContentCacheKeyGenerator generator = (ContentCacheKeyGenerator)engine.getComponentManager().getComponent("ContentCacheKeyGenerator"); - + + ContentCacheKeyGenerator generator = (ContentCacheKeyGenerator) engine + .getComponentManager().getComponent("ContentCacheKeyGenerator"); + if (generator.isCacheBySessionId()) { portletContentCache.evictContentForUser(se.getSession().getId()); - + if (decorationContentCache != null) { - decorationContentCache.evictContentForUser(se.getSession().getId()); + decorationContentCache.evictContentForUser(se.getSession() + .getId()); } } else { - portletContentCache.evictContentForUser(subjectUserPrincipal.getName()); - + portletContentCache.evictContentForUser(subjectUserPrincipal + .getName()); + if (decorationContentCache != null) { - decorationContentCache.evictContentForUser(subjectUserPrincipal.getName()); } + decorationContentCache.evictContentForUser(subjectUserPrincipal + .getName()); + } } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/core/PortalContextImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/core/PortalContextImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/core/PortalContextImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,61 +25,71 @@ /** * PortalContextImpl - * + * * @author David Sean Taylor * @version $Id: PortalContextImpl.java 516448 2007-03-09 16:25:47Z ate $ - * @deprecated Can't any references as it appears we always use JetpseedPortletContext + * @deprecated Can't any references as it appears we always use + * JetpseedPortletContext */ public class PortalContextImpl implements PortalContext { + PortalContextProvider provider = null; - public PortalContextImpl(PortalContextProvider provider) + public PortalContextImpl(PortalContextProvider provider) { this.provider = provider; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortalContext#getProperty(java.lang.String) */ public String getProperty(String name) { - if (name == null) - { - throw new IllegalArgumentException("Property name == null"); - } + if (name == null) { throw new IllegalArgumentException( + "Property name == null"); } return provider.getProperty(name); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortalContext#getPropertyNames() */ public Enumeration getPropertyNames() { - return(new Enumerator(provider.getPropertyNames())); + return (new Enumerator(provider.getPropertyNames())); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortalContext#getSupportedPortletModes() */ public Enumeration getSupportedPortletModes() { return new Enumerator(provider.getSupportedPortletModes()); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortalContext#getSupportedWindowStates() */ public Enumeration getSupportedWindowStates() { - return new Enumerator(provider.getSupportedWindowStates()); + return new Enumerator(provider.getSupportedWindowStates()); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortalContext#getPortalInfo() */ public String getPortalInfo() { - return provider.getPortalInfo(); + return provider.getPortalInfo(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/core/PortalContextProviderImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/core/PortalContextProviderImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/core/PortalContextProviderImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,50 +29,58 @@ * Provide information about the calling portal. * * @author David Sean Taylor - * @version $Id: PortalContextProviderImpl.java 553375 2007-07-05 05:37:00Z taylor $ + * @version $Id: PortalContextProviderImpl.java 553375 2007-07-05 05:37:00Z + * taylor $ */ -public class PortalContextProviderImpl - implements PortalContextProvider +public class PortalContextProviderImpl implements PortalContextProvider { - private final PortalContext portalContext; + + private final PortalContext portalContext; + /** Portal information */ private String info; + private final String portalName; + private final String portalVersion; - + /** supported portlet modes by this portal */ private Vector modes; /** supported window states by this portal */ private Vector states; - + public PortalContextProviderImpl(PortalContext portalContext) { this.portalContext = portalContext; - + modes = getDefaultModes(); // these are the minimum states that the portal needs to support - states = getDefaultStates(); + states = getDefaultStates(); // set info - portalName = this.portalContext.getConfiguration().getString("portal.name"); - portalVersion = this.portalContext.getConfiguration().getString("portal.version"); - info = portalName + "/" + portalVersion; - + portalName = this.portalContext.getConfiguration().getString( + "portal.name"); + portalVersion = this.portalContext.getConfiguration().getString( + "portal.version"); + info = portalName + "/" + portalVersion; + } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.pluto.services.information.PortalContextProvider#getPortalContext() */ - public PortalContext getPortalContext() + public PortalContext getPortalContext() { return portalContext; } - - /** + + /** *

        * getPortalInfo *

        @@ -85,7 +93,7 @@ return info; } - /** + /** *

        * getProperty *

        @@ -95,11 +103,11 @@ * @return */ public String getProperty(String name) - { - return portalContext.getProperty(name); + { + return portalContext.getProperty(name); } - /** + /** *

        * getPropertyNames *

        @@ -108,17 +116,17 @@ * @return */ public Collection getPropertyNames() - { - Iterator itr = portalContext.getConfiguration().getKeys(); - ArrayList names = new ArrayList(); - while(itr.hasNext()) - { - names.add(itr.next()); - } - return names; + { + Iterator itr = portalContext.getConfiguration().getKeys(); + ArrayList names = new ArrayList(); + while (itr.hasNext()) + { + names.add(itr.next()); + } + return names; } - /** + /** *

        * getSupportedPortletModes *

        @@ -131,7 +139,7 @@ return modes; } - /** + /** *

        * getSupportedWindowStates *

        @@ -140,15 +148,16 @@ * @return */ public Collection getSupportedWindowStates() - { + { return states; } private Vector getDefaultModes() - { + { Vector m = new Vector(); - Enumeration supportedPortletModes = portalContext.getSupportedPortletModes(); - while(supportedPortletModes.hasMoreElements()) + Enumeration supportedPortletModes = portalContext + .getSupportedPortletModes(); + while (supportedPortletModes.hasMoreElements()) { m.add(supportedPortletModes.nextElement()); } @@ -159,8 +168,9 @@ private Vector getDefaultStates() { Vector s = new Vector(); - Enumeration supportedWindowStates = portalContext.getSupportedWindowStates(); - while(supportedWindowStates.hasMoreElements()) + Enumeration supportedWindowStates = portalContext + .getSupportedWindowStates(); + while (supportedWindowStates.hasMoreElements()) { s.add(supportedWindowStates.nextElement()); } @@ -170,12 +180,10 @@ public void setProperty(String name, String value) { - if (name == null) - { - throw new IllegalArgumentException("Property name == null"); - } + if (name == null) { throw new IllegalArgumentException( + "Property name == null"); } portalContext.getConfiguration().setString(name, value); - } + } // expects enumeration of PortletMode objects @@ -183,7 +191,7 @@ { Vector v = new Vector(); - while (portletModes.hasMoreElements()) + while (portletModes.hasMoreElements()) { v.add(portletModes.nextElement()); } @@ -191,14 +199,12 @@ modes = v; } - - // expects enumeration of WindowState objects public void setSupportedWindowStates(Enumeration windowStates) { Vector v = new Vector(); - while (windowStates.hasMoreElements()) + while (windowStates.hasMoreElements()) { v.add(windowStates.nextElement()); } @@ -206,16 +212,14 @@ states = v; } - - /** - * reset all values to default portlet modes and window states; - * delete all properties and set the given portlet information - * as portlet info string. + * reset all values to default portlet modes and window states; delete all + * properties and set the given portlet information as portlet info string. * - * @param - * @param portalInfo portal information string that will be returned - * by the getPortalInfo call. + * @param + * @param portalInfo + * portal information string that will be returned by the + * getPortalInfo call. */ public void reset(String portalInfo) @@ -226,9 +230,9 @@ modes = getDefaultModes(); // these are the minimum states that the portal needs to support - states = getDefaultStates(); + states = getDefaultStates(); - //properties.clear(); + // properties.clear(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/core/PortletActionProviderImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/core/PortletActionProviderImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/core/PortletActionProviderImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,47 +19,56 @@ import javax.portlet.PortletMode; import javax.portlet.WindowState; +import org.apache.jetspeed.container.state.MutableNavigationalState; import org.apache.pluto.om.window.PortletWindow; import org.apache.pluto.services.information.PortletActionProvider; -import org.apache.jetspeed.container.state.MutableNavigationalState; /** - * Handle operations that the portlet may perform in an action method. - * This service is request based. - * + * Handle operations that the portlet may perform in an action method. This + * service is request based. + * * @author David Sean Taylor * @version $Id: PortletActionProviderImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class PortletActionProviderImpl implements PortletActionProvider { + private PortletWindow portletWindow; + private MutableNavigationalState navstate; - - public PortletActionProviderImpl(MutableNavigationalState navstate, PortletWindow portletWindow) + + public PortletActionProviderImpl(MutableNavigationalState navstate, + PortletWindow portletWindow) { this.portletWindow = portletWindow; - this.navstate = navstate; + this.navstate = navstate; } - /* (non-Javadoc) - * @see org.apache.pluto.services.information.PortletActionProvider#changePortletMode(PortletWindow, PortletMode) + /* + * (non-Javadoc) + * + * @see org.apache.pluto.services.information.PortletActionProvider#changePortletMode(PortletWindow, + * PortletMode) */ public void changePortletMode(PortletMode mode) - { + { if (mode != null) { navstate.setMode(portletWindow, mode); } } - /* (non-Javadoc) - * @see org.apache.pluto.services.information.PortletActionProvider#changePortletWindowState(PortletWindow, WindowState) + /* + * (non-Javadoc) + * + * @see org.apache.pluto.services.information.PortletActionProvider#changePortletWindowState(PortletWindow, + * WindowState) */ public void changePortletWindowState(WindowState state) { if (state != null) { - navstate.setState(portletWindow,state); + navstate.setState(portletWindow, state); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/HttpSessionWrapper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/HttpSessionWrapper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/HttpSessionWrapper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,25 +23,28 @@ /** * @author Scott T Weaver - * + * */ public class HttpSessionWrapper implements HttpSession { + private HttpSession session; - + public HttpSessionWrapper(HttpSession session) { this.session = session; } - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return session.equals(obj); } + /** * @param arg0 * @return @@ -50,6 +53,7 @@ { return session.getAttribute(arg0); } + /** * @return */ @@ -57,6 +61,7 @@ { return session.getAttributeNames(); } + /** * @return */ @@ -64,6 +69,7 @@ { return session.getCreationTime(); } + /** * @return */ @@ -71,6 +77,7 @@ { return session.getId(); } + /** * @return */ @@ -78,6 +85,7 @@ { return session.getLastAccessedTime(); } + /** * @return */ @@ -85,6 +93,7 @@ { return session.getMaxInactiveInterval(); } + /** * @return */ @@ -92,18 +101,20 @@ { return session.getServletContext(); } - + /** - * @deprecated As of Java(tm) Servlet API 2.1 - * for security reasons, with no replacement. + * @deprecated As of Java(tm) Servlet API 2.1 for security reasons, with no + * replacement. * @return */ public javax.servlet.http.HttpSessionContext getSessionContext() { return session.getSessionContext(); } + /** - * @deprecated @see javax.servlet.http.HttpSession#getValue(String) + * @deprecated + * @see javax.servlet.http.HttpSession#getValue(String) * @param arg0 * @return */ @@ -111,22 +122,27 @@ { return session.getValue(arg0); } - + /** - * @deprecated @see javax.servlet.http.HttpSession#getValueNames(String) + * @deprecated + * @see javax.servlet.http.HttpSession#getValueNames(String) * @return */ public String[] getValueNames() { return session.getValueNames(); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see java.lang.Object#hashCode() */ public int hashCode() { return session.hashCode(); } + /** * */ @@ -134,6 +150,7 @@ { session.invalidate(); } + /** * @return */ @@ -141,8 +158,10 @@ { return session.isNew(); } + /** - * @deprecated @see javax.servlet.http.HttpSession#putValue(String,Object) + * @deprecated + * @see javax.servlet.http.HttpSession#putValue(String,Object) * @param arg0 * @param arg1 */ @@ -150,6 +169,7 @@ { session.putValue(arg0, arg1); } + /** * @param arg0 */ @@ -157,14 +177,17 @@ { session.removeAttribute(arg0); } + /** - * @deprecated @see javax.servlet.http.HttpSession#removeValue(String) + * @deprecated + * @see javax.servlet.http.HttpSession#removeValue(String) * @param arg0 */ public void removeValue(String arg0) { session.removeValue(arg0); } + /** * @param arg0 * @param arg1 @@ -173,6 +196,7 @@ { session.setAttribute(arg0, arg1); } + /** * @param arg0 */ @@ -180,7 +204,10 @@ { session.setMaxInactiveInterval(arg0); } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see java.lang.Object#toString() */ public String toString() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/NamespaceEncodedSession.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/NamespaceEncodedSession.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/NamespaceEncodedSession.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,7 +29,7 @@ /** * @author Scott T Weaver - * + * */ public class NamespaceEncodedSession extends HttpSessionWrapper { @@ -46,8 +46,10 @@ public NamespaceEncodedSession(HttpSession session, ObjectID webAppId) { super(session); - this.nameSpaceMapper = ((JetspeedNamespaceMapperFactory) Jetspeed.getComponentManager().getComponent( - org.apache.pluto.util.NamespaceMapper.class)).getJetspeedNamespaceMapper(); + this.nameSpaceMapper = ((JetspeedNamespaceMapperFactory) Jetspeed + .getComponentManager().getComponent( + org.apache.pluto.util.NamespaceMapper.class)) + .getJetspeedNamespaceMapper(); this.webAppId = webAppId; } @@ -64,10 +66,8 @@ public void setAttribute(String name, Object value) { - if (name == null) - { - throw new IllegalArgumentException("Attribute name == null"); - } + if (name == null) { throw new IllegalArgumentException( + "Attribute name == null"); } if (skipEncode(name)) { @@ -99,7 +99,10 @@ private boolean skipEncode(String name) { - return name.startsWith(nameSpaceMapper.getPrefix()) || name.startsWith("javax.portlet") || name.startsWith("javax.servlet") || name.startsWith("org.apache.jetspeed"); + return name.startsWith(nameSpaceMapper.getPrefix()) + || name.startsWith("javax.portlet") + || name.startsWith("javax.servlet") + || name.startsWith("org.apache.jetspeed"); } /* Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,23 +26,25 @@ /** * Servlet Helper functions - * + * * @author David Sean Taylor * @version $Id: ServletHelper.java 516448 2007-03-09 16:25:47Z ate $ */ public class ServletHelper { + public static final String CONFIG_NAMESPACE = "org.apache.jetspeed"; /** Default Value for the Logging Directory, relative to the webroot */ public static final String LOGGING_ROOT_DEFAULT = "/logs"; + public static final String LOGGING_ROOT = "loggingRoot"; /** - * Used to get the real path of configuration and resource - * information. - * - * @param path path translated to the application root + * Used to get the real path of configuration and resource information. + * + * @param path + * path translated to the application root * @return the real path */ public static String getRealPath(ServletConfig config, String path) @@ -52,19 +54,17 @@ path = path.substring(1); } - return new File(config.getServletContext().getRealPath(""), path).getAbsolutePath(); + return new File(config.getServletContext().getRealPath(""), path) + .getAbsolutePath(); } /** - * Finds the specified servlet configuration/initialization - * parameter, looking first for a servlet-specific parameter, then - * for a global parameter, and using the provided default if not - * found. + * Finds the specified servlet configuration/initialization parameter, + * looking first for a servlet-specific parameter, then for a global + * parameter, and using the provided default if not found. */ public static final String findInitParameter(ServletContext context, - ServletConfig config, - String name, - String defaultValue) + ServletConfig config, String name, String defaultValue) { String path = null; @@ -100,21 +100,19 @@ /** * Create any directories that might be needed during - * + * */ public static void createRuntimeDirectories(ServletContext context, - ServletConfig config) - throws ServletException + ServletConfig config) throws ServletException { - String path = findInitParameter(context, config, LOGGING_ROOT, LOGGING_ROOT_DEFAULT); + String path = findInitParameter(context, config, LOGGING_ROOT, + LOGGING_ROOT_DEFAULT); File logDir = new File(getRealPath(config, path)); if (!logDir.exists()) { // Create the logging directory - if (!logDir.mkdirs()) - { - throw new ServletException("Cannot create directory for logs!"); - } + if (!logDir.mkdirs()) { throw new ServletException( + "Cannot create directory for logs!"); } } } - } \ No newline at end of file +} \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletObjectAccess.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletObjectAccess.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletObjectAccess.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,42 +31,51 @@ /** * Provides access to servlet request and response wrappers * - * + * * @deprecated Please use Spring to access request and response factories. * @author David Sean Taylor * @version $Id: ServletObjectAccess.java 516448 2007-03-09 16:25:47Z ate $ */ public abstract class ServletObjectAccess { - public static HttpServletRequest getServletRequest(HttpServletRequest request, PortletWindow window) + + public static HttpServletRequest getServletRequest( + HttpServletRequest request, PortletWindow window) { -// System.out.println("n"); + // System.out.println("n"); return requestFactory.getServletRequest(request, window); } - public static HttpServletResponse getServletResponse(HttpServletResponse response, PortletWindow window) + public static HttpServletResponse getServletResponse( + HttpServletResponse response, PortletWindow window) { return responseFactory.getServletResponse(response); } public static HttpServletRequest getServletRequest(PortletRequest request) { - InternalPortletRequest internalPortletRequest = CoreUtils.getInternalRequest(request); + InternalPortletRequest internalPortletRequest = CoreUtils + .getInternalRequest(request); - return (HttpServletRequest) ((javax.servlet.http.HttpServletRequestWrapper) internalPortletRequest).getRequest(); - + return (HttpServletRequest) ((javax.servlet.http.HttpServletRequestWrapper) internalPortletRequest) + .getRequest(); + } - public static HttpServletResponse getServletResponse(PortletResponse response) + public static HttpServletResponse getServletResponse( + PortletResponse response) { - InternalPortletResponse internalPortletResponse = CoreUtils.getInternalResponse(response); - return (HttpServletResponse) ((HttpServletResponseWrapper) internalPortletResponse).getResponse(); - + InternalPortletResponse internalPortletResponse = CoreUtils + .getInternalResponse(response); + return (HttpServletResponse) ((HttpServletResponseWrapper) internalPortletResponse) + .getResponse(); + } - private static ServletRequestFactory requestFactory = - (ServletRequestFactory) FactoryManager.getFactory(javax.servlet.http.HttpServletRequest.class); - private static ServletResponseFactory responseFactory = - (ServletResponseFactory) FactoryManager.getFactory(javax.servlet.http.HttpServletResponse.class); + private static ServletRequestFactory requestFactory = (ServletRequestFactory) FactoryManager + .getFactory(javax.servlet.http.HttpServletRequest.class); + private static ServletResponseFactory responseFactory = (ServletResponseFactory) FactoryManager + .getFactory(javax.servlet.http.HttpServletResponse.class); + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletRequestFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletRequestFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletRequestFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,16 +17,19 @@ package org.apache.jetspeed.engine.servlet; import javax.servlet.http.HttpServletRequest; + import org.apache.pluto.factory.Factory; import org.apache.pluto.om.window.PortletWindow; /** * Factory interface for creating HTTP Request Wrappers - * + * * @author David Sean Taylor * @version $Id: ServletRequestFactory.java 516448 2007-03-09 16:25:47Z ate $ */ public interface ServletRequestFactory extends Factory { - public HttpServletRequest getServletRequest(HttpServletRequest request, PortletWindow window); + + public HttpServletRequest getServletRequest(HttpServletRequest request, + PortletWindow window); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletRequestFactoryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletRequestFactoryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletRequestFactoryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,30 +24,30 @@ /** * Factory implementation for creating HTTP Request Wrappers - * + * * @author David Sean Taylor * @version $Id: ServletRequestFactoryImpl.java 517121 2007-03-12 07:45:49Z ate $ */ -public class ServletRequestFactoryImpl - implements ServletRequestFactory -{ - - public void init(javax.servlet.ServletConfig config, Map properties) - throws Exception - { +public class ServletRequestFactoryImpl implements ServletRequestFactory +{ + + public void init(javax.servlet.ServletConfig config, Map properties) + throws Exception + { } - - public void destroy() - throws Exception + + public void destroy() throws Exception { } - protected HttpServletRequest createRequest(HttpServletRequest request, PortletWindow window) + protected HttpServletRequest createRequest(HttpServletRequest request, + PortletWindow window) { - return new ServletRequestImpl(request, window); + return new ServletRequestImpl(request, window); } - - public HttpServletRequest getServletRequest(HttpServletRequest request, PortletWindow window) + + public HttpServletRequest getServletRequest(HttpServletRequest request, + PortletWindow window) { // May have already been wrapped, no need to re-wrap. if (!(request instanceof ServletRequestImpl)) @@ -59,7 +59,7 @@ else { return request; - } + } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletRequestImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletRequestImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletRequestImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -61,55 +61,71 @@ * @author David Sean Taylor * @version $Id: ServletRequestImpl.java 587064 2007-10-22 11:54:11Z woonsan $ */ -public class ServletRequestImpl extends HttpServletRequestWrapper implements PortletDispatcherIncludeAware +public class ServletRequestImpl extends HttpServletRequestWrapper implements + PortletDispatcherIncludeAware { + public static final String ACCEPT_LANGUAGE = "Accept-Language"; + /** Logger */ private static final Log log = LogFactory.getLog(ServletRequestImpl.class); PortletWindow portletWindow = null; + private JetspeedNamespaceMapper nameSpaceMapper = null; + private ServletRequest currentRequest = null; private Map portletParameters; - + private boolean included; private static Boolean mergePortalParametersWithPortletParameters; + private static Boolean mergePortalParametersBeforePortletParameters; - + private boolean portletMergePortalParametersWithPortletParameters; + private boolean portletMergePortalParametersBeforePortletParameters; - + private Map portalParameters; - - private String currentIncludeQueryString; - private String currentForwardQueryString; - + + private String currentIncludeQueryString; + + private String currentForwardQueryString; + // request attributes map which is cached for each paralleled worker. - // this should be re-created when it is called for the first time or when some attributes are added/modified/removed. + // this should be re-created when it is called for the first time or when + // some attributes are added/modified/removed. private Map cachedAttributes; - public ServletRequestImpl( HttpServletRequest servletRequest, PortletWindow window ) + public ServletRequestImpl(HttpServletRequest servletRequest, + PortletWindow window) { super(servletRequest); - nameSpaceMapper = ((JetspeedNamespaceMapperFactory) Jetspeed.getComponentManager().getComponent( - org.apache.pluto.util.NamespaceMapper.class)).getJetspeedNamespaceMapper(); - this.portletWindow = window; - - - String encoding = (String) servletRequest.getAttribute(PortalReservedParameters.PREFERED_CHARACTERENCODING_ATTRIBUTE); - boolean decode = servletRequest.getAttribute(PortalReservedParameters.PARAMETER_ALREADY_DECODED_ATTRIBUTE) == null + nameSpaceMapper = ((JetspeedNamespaceMapperFactory) Jetspeed + .getComponentManager().getComponent( + org.apache.pluto.util.NamespaceMapper.class)) + .getJetspeedNamespaceMapper(); + this.portletWindow = window; + + String encoding = (String) servletRequest + .getAttribute(PortalReservedParameters.PREFERED_CHARACTERENCODING_ATTRIBUTE); + boolean decode = servletRequest + .getAttribute(PortalReservedParameters.PARAMETER_ALREADY_DECODED_ATTRIBUTE) == null && encoding != null; if (decode) { - servletRequest.setAttribute(PortalReservedParameters.PARAMETER_ALREADY_DECODED_ATTRIBUTE, - new Boolean(true)); + servletRequest + .setAttribute( + PortalReservedParameters.PARAMETER_ALREADY_DECODED_ATTRIBUTE, + new Boolean(true)); } - //get portal servlet params + // get portal servlet params portalParameters = new HashMap(); - for (Enumeration parameters = servletRequest.getParameterNames(); parameters.hasMoreElements();) + for (Enumeration parameters = servletRequest.getParameterNames(); parameters + .hasMoreElements();) { String paramName = (String) parameters.nextElement(); String[] paramValues = servletRequest.getParameterValues(paramName); @@ -120,7 +136,8 @@ { try { - paramValues[i] = new String(paramValues[i].getBytes("ISO-8859-1"), encoding); + paramValues[i] = new String(paramValues[i] + .getBytes("ISO-8859-1"), encoding); } catch (UnsupportedEncodingException e) { @@ -130,60 +147,65 @@ } portalParameters.put(paramName, paramValues); } - - if (mergePortalParametersWithPortletParameters == null ) + + if (mergePortalParametersWithPortletParameters == null) { - mergePortalParametersWithPortletParameters = - new Boolean(Jetspeed.getContext().getConfiguration().getBoolean("merge.portal.parameters.with.portlet.parameters", false)); + mergePortalParametersWithPortletParameters = new Boolean(Jetspeed + .getContext().getConfiguration().getBoolean( + "merge.portal.parameters.with.portlet.parameters", + false)); } - + if (mergePortalParametersBeforePortletParameters == null) { - mergePortalParametersBeforePortletParameters = - new Boolean(Jetspeed.getContext().getConfiguration().getBoolean("merge.portal.parameters.before.portlet.parameters", false)); + mergePortalParametersBeforePortletParameters = new Boolean( + Jetspeed + .getContext() + .getConfiguration() + .getBoolean( + "merge.portal.parameters.before.portlet.parameters", + false)); } - - - PortletDefinitionComposite portletDef = (PortletDefinitionComposite)portletWindow.getPortletEntity().getPortletDefinition(); - if(portletDef != null) + + PortletDefinitionComposite portletDef = (PortletDefinitionComposite) portletWindow + .getPortletEntity().getPortletDefinition(); + if (portletDef != null) { GenericMetadata metaData = portletDef.getMetadata(); - portletMergePortalParametersWithPortletParameters = - getMetaDataBooleanValue( + portletMergePortalParametersWithPortletParameters = getMetaDataBooleanValue( metaData, PortalReservedParameters.PORTLET_EXTENDED_DESCRIPTOR_MERGE_PORTAL_PARAMETERS_WITH_PORTLET_PARAMETERS, mergePortalParametersWithPortletParameters.booleanValue()); - portletMergePortalParametersBeforePortletParameters = - getMetaDataBooleanValue( + portletMergePortalParametersBeforePortletParameters = getMetaDataBooleanValue( metaData, PortalReservedParameters.PORTLET_EXTENDED_DESCRIPTOR_MERGE_PORTAL_PARAMETERS_BEFORE_PORTLET_PARAMETERS, mergePortalParametersBeforePortletParameters.booleanValue()); - + } else { // This happens when an entity is referencing a non-existent portlet - portletMergePortalParametersWithPortletParameters = mergePortalParametersWithPortletParameters.booleanValue(); - portletMergePortalParametersBeforePortletParameters = mergePortalParametersBeforePortletParameters.booleanValue(); + portletMergePortalParametersWithPortletParameters = mergePortalParametersWithPortletParameters + .booleanValue(); + portletMergePortalParametersBeforePortletParameters = mergePortalParametersBeforePortletParameters + .booleanValue(); } } - - private boolean getMetaDataBooleanValue(GenericMetadata metaData, String fieldName, boolean defaultValue ) + + private boolean getMetaDataBooleanValue(GenericMetadata metaData, + String fieldName, boolean defaultValue) { String value = null; - if ( metaData != null ) + if (metaData != null) { Collection fields = metaData.getFields(fieldName); - if ( fields != null && !fields.isEmpty() ) + if (fields != null && !fields.isEmpty()) { - value = ((LocalizedField)fields.iterator().next()).getValue(); + value = ((LocalizedField) fields.iterator().next()).getValue(); } } - if ( value != null ) - { - return Boolean.valueOf(value).booleanValue(); - } + if (value != null) { return Boolean.valueOf(value).booleanValue(); } return defaultValue; } @@ -192,9 +214,9 @@ return (HttpServletRequest) super.getRequest(); } - // ServletRequestWrapper overlay + // ServletRequestWrapper overlay - public String getParameter( String name ) + public String getParameter(String name) { Object value = this.getParameterMap().get(name); if (value == null) @@ -214,76 +236,93 @@ return (value.toString()); } } - + private boolean isEqual(String one, String two) { - return (one == null && two == null) || (one != null && two != null && one.equals(two)); + return (one == null && two == null) + || (one != null && two != null && one.equals(two)); } - + private boolean checkQueryStringChanged() { boolean changed = false; ServletRequest request = getRequest(); - String includeQueryString = (String)request.getAttribute("javax.servlet.include.query_string"); - String forwardQueryString = (String)request.getAttribute("javax.servlet.forward.query_string"); - - if (!isEqual(currentIncludeQueryString,includeQueryString)) + String includeQueryString = (String) request + .getAttribute("javax.servlet.include.query_string"); + String forwardQueryString = (String) request + .getAttribute("javax.servlet.forward.query_string"); + + if (!isEqual(currentIncludeQueryString, includeQueryString)) { currentIncludeQueryString = includeQueryString; changed = true; } - if (!isEqual(currentForwardQueryString,forwardQueryString)) + if (!isEqual(currentForwardQueryString, forwardQueryString)) { currentForwardQueryString = forwardQueryString; changed = true; - } + } return changed; } public Map getParameterMap() { - // if included or forwarded with a query string, parameterMap might have changed - // this is/should be the only check needed, and the other "tricky" check below probably + // if included or forwarded with a query string, parameterMap might have + // changed + // this is/should be the only check needed, and the other "tricky" check + // below probably // can be removed. - // I'll keep it in for now though as it hasn't been tested enough on other app servers + // I'll keep it in for now though as it hasn't been tested enough on + // other app servers boolean queryStringChanged = checkQueryStringChanged(); - - if (queryStringChanged || currentRequest == null || currentRequest != getRequest() ) + + if (queryStringChanged || currentRequest == null + || currentRequest != getRequest()) { - // Cache the parameters for as long as the wrapped request stays the same. - // According to Servlet 2.3 SRV.6.2.2 the passed on ServletRequest object + // Cache the parameters for as long as the wrapped request stays the + // same. + // According to Servlet 2.3 SRV.6.2.2 the passed on ServletRequest + // object // to an dispatched Servlet must remain the same (this one). - // Tomcat solves this by injecting a new ServletRequest of its own above + // Tomcat solves this by injecting a new ServletRequest of its own + // above // this one (the getRequest() object). - // So, when that one has changed since the last time the parameters have + // So, when that one has changed since the last time the parameters + // have // been accessed, flush the cache and rebuild the map. currentRequest = getRequest(); boolean postAllowed = false; - - // determine the possible additional query string parameters provided on the RequestDispatcher include path - // per the specs, these are prepended to existing parameters or altogether new parameters - // as we save the original "portal" parameters, we can find those query string parameters by comparing against those + + // determine the possible additional query string parameters + // provided on the RequestDispatcher include path + // per the specs, these are prepended to existing parameters or + // altogether new parameters + // as we save the original "portal" parameters, we can find those + // query string parameters by comparing against those HashMap queryParameters = new HashMap(); - for ( Iterator iter = getRequest().getParameterMap().entrySet().iterator(); iter.hasNext(); ) + for (Iterator iter = getRequest().getParameterMap().entrySet() + .iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry)iter.next(); - String[] values = (String[])entry.getValue(); - String[] original = (String[])portalParameters.get(entry.getKey()); + Map.Entry entry = (Map.Entry) iter.next(); + String[] values = (String[]) entry.getValue(); + String[] original = (String[]) portalParameters.get(entry + .getKey()); String[] diff = null; - if ( original == null ) + if (original == null) { // a new parameter diff = new String[values.length]; - System.arraycopy(values,0,diff,0,values.length); + System.arraycopy(values, 0, diff, 0, values.length); } - else if ( values.length > original.length ) + else if (values.length > original.length) { // we've got some additional query string parameter value(s) diff = new String[values.length - original.length]; - System.arraycopy(values,0,diff,0,values.length-original.length); + System.arraycopy(values, 0, diff, 0, values.length + - original.length); } - if ( diff != null ) + if (diff != null) { queryParameters.put(entry.getKey(), diff); } @@ -294,57 +333,65 @@ JetspeedRequestContext context = (JetspeedRequestContext) getAttribute("org.apache.jetspeed.request.RequestContext"); if (context != null) { - NavigationalState ns = context.getPortalURL().getNavigationalState(); - postAllowed = ns.getPortletWindowOfAction() != null || ns.getPortletWindowOfResource() != null; + NavigationalState ns = context.getPortalURL() + .getNavigationalState(); + postAllowed = ns.getPortletWindowOfAction() != null + || ns.getPortletWindowOfResource() != null; Iterator iter = ns.getParameterNames(portletWindow); while (iter.hasNext()) { String name = (String) iter.next(); - String[] values = ns.getParameterValues(portletWindow, name); + String[] values = ns + .getParameterValues(portletWindow, name); navParameters.put(name, values); } } - + // now first merge the keys we have into one unique set HashSet keys = new HashSet(); keys.addAll(portalParameters.keySet()); keys.addAll(queryParameters.keySet()); keys.addAll(navParameters.keySet()); - + // now "merge" the parameters // there are three different options: // 1) query parameters + nav parameters: - // portletMergePortalParametersWithPortletParameters == false && !actionRequest + // portletMergePortalParametersWithPortletParameters == false && + // !actionRequest // 2) query parameters + nav parameters + portal parameters - // portletMergePortalParametersWithPortletParameters == true || actionRequest - // && portletMergePortalParametersBeforePortletParameters == false - // 3) query parameters + portal parameters + nav parameters (odd use-case but provided because this was the "old" pre-2.1 behavior - // portletMergePortalParametersWithPortletParameters == true || actionRequest - // && portletMergePortalParametersBeforePortletParameters == true + // portletMergePortalParametersWithPortletParameters == true || + // actionRequest + // && portletMergePortalParametersBeforePortletParameters == false + // 3) query parameters + portal parameters + nav parameters (odd + // use-case but provided because this was the "old" pre-2.1 behavior + // portletMergePortalParametersWithPortletParameters == true || + // actionRequest + // && portletMergePortalParametersBeforePortletParameters == true portletParameters = new HashMap(); - for ( Iterator iter = keys.iterator(); iter.hasNext(); ) + for (Iterator iter = keys.iterator(); iter.hasNext();) { - String key = (String)iter.next(); - String[] first = (String[])queryParameters.get(key); + String key = (String) iter.next(); + String[] first = (String[]) queryParameters.get(key); String[] next = null, last = null, result = null; - - if ( portletMergePortalParametersWithPortletParameters == false && !postAllowed ) + + if (portletMergePortalParametersWithPortletParameters == false + && !postAllowed) { - next = (String[])navParameters.get(key); + next = (String[]) navParameters.get(key); } - else if ( portletMergePortalParametersBeforePortletParameters ) + else if (portletMergePortalParametersBeforePortletParameters) { - next = (String[])portalParameters.get(key); - last = (String[])navParameters.get(key); + next = (String[]) portalParameters.get(key); + last = (String[]) navParameters.get(key); } else { - next = (String[])navParameters.get(key); - last = (String[])portalParameters.get(key); + next = (String[]) navParameters.get(key); + last = (String[]) portalParameters.get(key); } - if ( first == null ) + if (first == null) { - if ( next == null ) + if (next == null) { first = last; last = null; @@ -356,35 +403,40 @@ last = null; } } - else if ( next == null ) + else if (next == null) { next = last; last = null; } - - if ( last == null ) + + if (last == null) { - if ( next == null && first != null ) + if (next == null && first != null) { result = new String[first.length]; - System.arraycopy(first,0,result,0,first.length); + System.arraycopy(first, 0, result, 0, first.length); } - else if (next != null ) + else if (next != null) { result = new String[first.length + next.length]; - System.arraycopy(first,0,result,0,first.length); - System.arraycopy(next,0,result,first.length,next.length); + System.arraycopy(first, 0, result, 0, first.length); + System.arraycopy(next, 0, result, first.length, + next.length); } } else { - result = new String[first.length + next.length + last.length]; - System.arraycopy(first,0,result,0,first.length); - System.arraycopy(next,0,result,first.length,next.length); - System.arraycopy(last,0,result,first.length+next.length,last.length); - + result = new String[first.length + next.length + + last.length]; + System.arraycopy(first, 0, result, 0, first.length); + System + .arraycopy(next, 0, result, first.length, + next.length); + System.arraycopy(last, 0, result, first.length + + next.length, last.length); + } - if ( result != null ) + if (result != null) { portletParameters.put(key, result); } @@ -399,7 +451,7 @@ return Collections.enumeration(this.getParameterMap().keySet()); } - public String[] getParameterValues( String name ) + public String[] getParameterValues(String name) { return (String[]) this.getParameterMap().get(name); } @@ -410,70 +462,78 @@ public Enumeration getAttributeNames() { Enumeration attrNames = super.getAttributeNames(); - - // In parallel mode, adjust attributes by the values of the current thread + // In parallel mode, adjust attributes by the values of the current + // thread + if (CurrentWorkerContext.getParallelRenderingMode()) { // If cached attributes map is null, it should be re-created. - + if (cachedAttributes == null) { HashMap adjustedAttrMap = new HashMap(); - + // first, add all attributes of original request. - + while (attrNames.hasMoreElements()) { String key = (String) attrNames.nextElement(); adjustedAttrMap.put(key, super.getAttribute(key)); } - - // second, add or override all attributes by the current worker context. - - Enumeration cwAttrNames = CurrentWorkerContext.getAttributeNames(); - + + // second, add or override all attributes by the current worker + // context. + + Enumeration cwAttrNames = CurrentWorkerContext + .getAttributeNames(); + while (cwAttrNames.hasMoreElements()) { String key = (String) cwAttrNames.nextElement(); - adjustedAttrMap.put(key, CurrentWorkerContext.getAttribute(key)); + adjustedAttrMap.put(key, CurrentWorkerContext + .getAttribute(key)); } - + cachedAttributes = Collections.unmodifiableMap(adjustedAttrMap); } - + attrNames = Collections.enumeration(cachedAttributes.keySet()); } - + return attrNames; } - + /** * @see javax.servlet.http.HttpServletRequest#getAttribute(java.lang.String) */ - public Object getAttribute( String name ) + public Object getAttribute(String name) { Object value = null; // In parallel mode, first look up from the worker. if (CurrentWorkerContext.getParallelRenderingMode()) - { + { value = CurrentWorkerContext.getAttribute(name); - // Because PortletRequestImpl class of pluto encodes the name of attribute before calling setAttribute(), + // Because PortletRequestImpl class of pluto encodes the name of + // attribute before calling setAttribute(), // we have to check the encoded name also. if (null == value) { - // Extra code (2 lines) from Nicolas... not clear to me why this is needed, as "pr" is not used. Commenting out for now... - //PortletRequest pr = (PortletRequest) super.getAttribute("javax.portlet.request"); - //if (pr != null) - value = CurrentWorkerContext.getAttribute(nameSpaceMapper.encode(portletWindow.getId(), name)); + // Extra code (2 lines) from Nicolas... not clear to me why this + // is needed, as "pr" is not used. Commenting out for now... + // PortletRequest pr = (PortletRequest) + // super.getAttribute("javax.portlet.request"); + // if (pr != null) + value = CurrentWorkerContext.getAttribute(nameSpaceMapper + .encode(portletWindow.getId(), name)); } } // If no attribute found, then look up from the request - if (null == value) + if (null == value) { value = getAttributeInternal(name); } @@ -481,7 +541,7 @@ return value; } - private Object getAttributeInternal( String name ) + private Object getAttributeInternal(String name) { Object value = super.getAttribute(name); if (name.equals(PortletRequest.USER_INFO)) @@ -495,14 +555,16 @@ { entityID = entity.getId().toString(); } - PortletApplicationDefinition portletAppDef = entity.getPortletDefinition() + PortletApplicationDefinition portletAppDef = entity + .getPortletDefinition() .getPortletApplicationDefinition(); if (null != portletAppDef) { value = context.getUserInfoMap(portletAppDef.getId()); if (log.isDebugEnabled() && (null != value)) - log.debug(PortletRequest.USER_INFO + " map size: " + ((Map) value).size()); + log.debug(PortletRequest.USER_INFO + " map size: " + + ((Map) value).size()); } else { @@ -515,11 +577,12 @@ { if (null == value) { - PortletRequest pr = (PortletRequest) super.getAttribute("javax.portlet.request"); + PortletRequest pr = (PortletRequest) super + .getAttribute("javax.portlet.request"); if (pr != null) { - value = super.getAttribute(nameSpaceMapper.encode(portletWindow.getId(), - name)); + value = super.getAttribute(nameSpaceMapper.encode( + portletWindow.getId(), name)); } } } @@ -531,13 +594,13 @@ */ public Locale getLocale() { - //Locale preferedLocale = (Locale) getSession().getAttribute(RequestContext.PREFERED_LOCALE_SESSION_KEY); - RequestContext requestContext = (RequestContext) _getHttpServletRequest().getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); + // Locale preferedLocale = (Locale) + // getSession().getAttribute(RequestContext.PREFERED_LOCALE_SESSION_KEY); + RequestContext requestContext = (RequestContext) _getHttpServletRequest() + .getAttribute( + PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); Locale preferedLocale = requestContext.getLocale(); - if (preferedLocale != null) - { - return preferedLocale; - } + if (preferedLocale != null) { return preferedLocale; } return super.getLocale(); } @@ -547,12 +610,11 @@ */ public Enumeration getLocales() { - RequestContext requestContext = (RequestContext) _getHttpServletRequest().getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); + RequestContext requestContext = (RequestContext) _getHttpServletRequest() + .getAttribute( + PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); Locale preferedLocale = requestContext.getLocale(); - if (preferedLocale != null) - { - return getLocaleEnum(preferedLocale); - } + if (preferedLocale != null) { return getLocaleEnum(preferedLocale); } return super.getLocales(); } @@ -561,11 +623,11 @@ *

        * getLocaleEnum *

        - * + * * @param preferedLocale * @return */ - protected Enumeration getLocaleEnum( Locale preferedLocale ) + protected Enumeration getLocaleEnum(Locale preferedLocale) { ArrayList locales = new ArrayList(); locales.add(preferedLocale); @@ -580,11 +642,11 @@ /** * @see javax.servlet.http.HttpServletRequest#getHeader(java.lang.String) */ - public String getHeader( String name ) + public String getHeader(String name) { - if(name.equals(ACCEPT_LANGUAGE)) + if (name.equals(ACCEPT_LANGUAGE)) { - return getLocale().getLanguage(); + return getLocale().getLanguage(); } else { @@ -595,16 +657,16 @@ /** * @see javax.servlet.http.HttpServletRequest#getHeaders(java.lang.String) */ - public Enumeration getHeaders( String name ) + public Enumeration getHeaders(String name) { - if(name.equals(ACCEPT_LANGUAGE)) - { - return getLocaleEnum(getLocale()); + if (name.equals(ACCEPT_LANGUAGE)) + { + return getLocaleEnum(getLocale()); } else { return super.getHeaders(name); - } + } } @@ -618,25 +680,24 @@ * @param arg0 * @param arg1 */ - public void setAttribute( String name, Object value ) + public void setAttribute(String name, Object value) { - if (name == null) - { - throw new IllegalArgumentException("Attribute name == null"); - } - + if (name == null) { throw new IllegalArgumentException( + "Attribute name == null"); } + // In parallel mode, put attribute into worker. - if (CurrentWorkerContext.getParallelRenderingMode()) + if (CurrentWorkerContext.getParallelRenderingMode()) { - // when it is parallel rendering, the cached request attributes should be re-created later by setting it to null. + // when it is parallel rendering, the cached request attributes + // should be re-created later by setting it to null. cachedAttributes = null; - - if (null == value) + + if (null == value) { CurrentWorkerContext.removeAttribute(name); - } - else + } + else { CurrentWorkerContext.setAttribute(name, value); } @@ -653,7 +714,7 @@ } } - private void setAttributeInternal( String name, Object value ) + private void setAttributeInternal(String name, Object value) { // This allows us to make jetpseed objects avaiable to portlets // This makes the portlet non-portable but is a must admin portlets @@ -665,9 +726,9 @@ } else { - String encodedKey = nameSpaceMapper.encode(portletWindow.getId(), name); - this._getHttpServletRequest().setAttribute( - encodedKey, value); + String encodedKey = nameSpaceMapper.encode(portletWindow + .getId(), name); + this._getHttpServletRequest().setAttribute(encodedKey, value); } } super.setAttribute(name, value); @@ -681,23 +742,23 @@ * @see javax.servlet.ServletRequest#removeAttribute(java.lang.String) * @param arg0 */ - public void removeAttribute( String name ) + public void removeAttribute(String name) { - if (name == null) - { - throw new IllegalArgumentException("Attribute name == null"); - } - + if (name == null) { throw new IllegalArgumentException( + "Attribute name == null"); } + // In parallel mode, remove attribute from worker. - if (CurrentWorkerContext.getParallelRenderingMode()) + if (CurrentWorkerContext.getParallelRenderingMode()) { - // when it is parallel rendering, the cached request attributes should be re-created later by setting it to null. + // when it is parallel rendering, the cached request attributes + // should be re-created later by setting it to null. cachedAttributes = null; - + CurrentWorkerContext.removeAttribute(name); - - if (name.startsWith("org.apache.jetspeed")) { + + if (name.startsWith("org.apache.jetspeed")) + { super.removeAttribute(name); } } @@ -705,14 +766,14 @@ { // remove attribute from request. super.removeAttribute(name); - } + } } /** *

        * getHeaderNames *

        - * + * * @see javax.servlet.http.HttpServletRequest#getHeaderNames() * @return */ @@ -720,94 +781,105 @@ { return super.getHeaderNames(); } - + /** - * @param included when true, JSR-168 PLT.16.3.3 rules need to be enforced + * @param included + * when true, JSR-168 PLT.16.3.3 rules need to be enforced */ public void setPortletDispatcherIncluded(boolean included) { this.included = included; } - + /* * JSR-168 PLT.16.3.3 cxxix */ - public String getProtocol() - { - return (included ? null : super.getProtocol() ); - } + public String getProtocol() + { + return (included ? null : super.getProtocol()); + } /* * JSR-168 PLT.16.3.3 cxxix */ - public String getRemoteAddr() - { - return (included ? null : super.getRemoteAddr() ); - } + public String getRemoteAddr() + { + return (included ? null : super.getRemoteAddr()); + } /* * JSR-168 PLT.16.3.3 cxxix */ - public String getRemoteHost() - { - return (included ? null : super.getRemoteHost() ); - } + public String getRemoteHost() + { + return (included ? null : super.getRemoteHost()); + } /* * JSR-168 PLT.16.3.3 cxxix */ - public StringBuffer getRequestURL() - { + public StringBuffer getRequestURL() + { return (included ? null : super.getRequestURL()); - } + } /* * JSR-168 PLT.16.3.3 cxxx */ public String getPathInfo() - { - return (included ? (String)super.getAttribute("javax.servlet.include.path_info") : super.getPathInfo()); - } + { + return (included ? (String) super + .getAttribute("javax.servlet.include.path_info") : super + .getPathInfo()); + } /* * JSR-168 PLT.16.3.3 cxxx */ - public String getPathTranslated() - { + public String getPathTranslated() + { return (included ? null : super.getPathTranslated()); - } + } /* * JSR-168 PLT.16.3.3 cxxx */ - public String getQueryString() - { - return (included ? (String)super.getAttribute("javax.servlet.include.query_string") : super.getQueryString()); - } + public String getQueryString() + { + return (included ? (String) super + .getAttribute("javax.servlet.include.query_string") : super + .getQueryString()); + } /* * JSR-168 PLT.16.3.3 cxxx */ - public String getRequestURI() - { - return (included ? (String)super.getAttribute("javax.servlet.include.request_uri") : super.getRequestURI()); - } + public String getRequestURI() + { + return (included ? (String) super + .getAttribute("javax.servlet.include.request_uri") : super + .getRequestURI()); + } /* * JSR-168 PLT.16.3.3 cxxx */ - public String getServletPath() - { - return (included ? (String)super.getAttribute("javax.servlet.include.servlet_path") : super.getServletPath()); - } + public String getServletPath() + { + return (included ? (String) super + .getAttribute("javax.servlet.include.servlet_path") : super + .getServletPath()); + } /* * JSR-168 PLT.16.3.3 cxxxi */ - public String getContextPath() - { - return (included ? (String)super.getAttribute("javax.servlet.include.context_path") : super.getContextPath()); - } + public String getContextPath() + { + return (included ? (String) super + .getAttribute("javax.servlet.include.context_path") : super + .getContextPath()); + } /* * JSR-168 PLT.16.3.3 cxxxiv @@ -860,9 +932,10 @@ /* * JSR-168 PLT.16.3.3 cxxxii */ - public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException + public void setCharacterEncoding(String arg0) + throws UnsupportedEncodingException { - if ( !included ) + if (!included) { super.setCharacterEncoding(arg0); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletResponseFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletResponseFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletResponseFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,15 +17,17 @@ package org.apache.jetspeed.engine.servlet; import javax.servlet.http.HttpServletResponse; + import org.apache.pluto.factory.Factory; /** * Factory interface for creating HTTP Request Wrappers - * + * * @author David Sean Taylor * @version $Id: ServletResponseFactory.java 516448 2007-03-09 16:25:47Z ate $ */ public interface ServletResponseFactory extends Factory { + public HttpServletResponse getServletResponse(HttpServletResponse response); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletResponseFactoryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletResponseFactoryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletResponseFactoryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -44,7 +44,7 @@ if (!(response instanceof ServletResponseImpl)) { return new ServletResponseImpl(response); - + } else { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletResponseImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletResponseImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/ServletResponseImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,34 +27,38 @@ /** * Factory implementation for creating HTTP Response Wrappers - * + * * @author David Sean Taylor * @version $Id: ServletResponseImpl.java 516448 2007-03-09 16:25:47Z ate $ */ -public class ServletResponseImpl extends HttpServletResponseWrapper implements PortletDispatcherIncludeAware +public class ServletResponseImpl extends HttpServletResponseWrapper implements + PortletDispatcherIncludeAware { + private boolean included; - + public ServletResponseImpl(HttpServletResponse response) { super(response); } - public void setResponse(HttpServletResponse response) + public void setResponse(HttpServletResponse response) { super.setResponse(response); - } + } /** - * @param included when true, JSR-168 PLT.16.3.3 rules need to be enforced + * @param included + * when true, JSR-168 PLT.16.3.3 rules need to be enforced */ public void setPortletDispatcherIncluded(boolean included) { this.included = included; } - + /* * JSR-168 PLT.16.3.3 .cxxxviii + * * @deprecated use encodeRedirectURL instead */ public String encodeRedirectUrl(String url) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/StaticResourceCachingFilter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/StaticResourceCachingFilter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/StaticResourceCachingFilter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,74 +29,74 @@ public class StaticResourceCachingFilter implements Filter { + // constants - private static final String HTTP_HEADER_EXPIRES = "Expires" ; - private static final String HTTP_HEADER_CACHE_CONTROL = "Cache-Control" ; - private static final String HTTP_HEADER_CACHE_MAX_AGE = "max-age" ; - private static final String HTTP_HEADER_CACHE_MAX_AGE_EQ = "max-age=" ; + private static final String HTTP_HEADER_EXPIRES = "Expires"; + private static final String HTTP_HEADER_CACHE_CONTROL = "Cache-Control"; + + private static final String HTTP_HEADER_CACHE_MAX_AGE = "max-age"; + + private static final String HTTP_HEADER_CACHE_MAX_AGE_EQ = "max-age="; + private static String PARAM_EXPIRES_HOURS = "ExpireHours"; - private static final TimeZone GMT_TIME_ZONE = TimeZone.getTimeZone( "GMT" ); + private static final TimeZone GMT_TIME_ZONE = TimeZone.getTimeZone("GMT"); + // members - // members - private double expires_in_hours = 0.0; + private int max_age = 0; // constructor public StaticResourceCachingFilter() { - super() ; + super(); } - // protocol - public void init( FilterConfig config ) + public void init(FilterConfig config) { try { - expires_in_hours = Double.parseDouble( config.getInitParameter( PARAM_EXPIRES_HOURS ) ); + expires_in_hours = Double.parseDouble(config + .getInitParameter(PARAM_EXPIRES_HOURS)); } - catch ( NumberFormatException ex ) + catch (NumberFormatException ex) { expires_in_hours = 0; } - max_age = (int)(expires_in_hours * 60); + max_age = (int) (expires_in_hours * 60); } - - public void doFilter( ServletRequest aRequest, ServletResponse aResponse, FilterChain chain ) - throws java.io.IOException, ServletException + + public void doFilter(ServletRequest aRequest, ServletResponse aResponse, + FilterChain chain) throws java.io.IOException, ServletException { - HttpServletRequest request = (HttpServletRequest)aRequest; - HttpServletResponse response = (HttpServletResponse)aResponse; - if ( max_age > 0 ) + HttpServletRequest request = (HttpServletRequest) aRequest; + HttpServletResponse response = (HttpServletResponse) aResponse; + if (max_age > 0) { String cacheControlVal = HTTP_HEADER_CACHE_MAX_AGE_EQ + max_age; - response.setHeader( HTTP_HEADER_CACHE_CONTROL, cacheControlVal ); + response.setHeader(HTTP_HEADER_CACHE_CONTROL, cacheControlVal); } - chain.doFilter( request, response ); + chain.doFilter(request, response); } public void destroy() { } - - /* unused (we're only doing Cache-Control max-age), but works for generating Expires header - private String createExpiresHeader( int expiresInHours ) - { - SimpleDateFormat sdf = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US ); - sdf.setTimeZone( GMT_TIME_ZONE ); - Calendar cal = Calendar.getInstance(); - cal.add( Calendar.HOUR, expiresInHours ); - long millis = cal.getTimeInMillis(); - Date d = new Date( millis ); - return sdf.format( d ); - } + /* + * unused (we're only doing Cache-Control max-age), but works for generating + * Expires header private String createExpiresHeader( int expiresInHours ) { + * SimpleDateFormat sdf = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss + * zzz", Locale.US ); sdf.setTimeZone( GMT_TIME_ZONE ); Calendar cal = + * Calendar.getInstance(); cal.add( Calendar.HOUR, expiresInHours ); long + * millis = cal.getTimeInMillis(); Date d = new Date( millis ); return + * sdf.format( d ); } */ } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/XXSUrlAttackFilter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/XXSUrlAttackFilter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/engine/servlet/XXSUrlAttackFilter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,25 +28,30 @@ import javax.servlet.http.HttpServletResponse; /** - * Simple XXS Url attack protection blocking access whenever the request url contains a < or > character. + * Simple XXS Url attack protection blocking access whenever the request url + * contains a < or > character. + * * @version $Id: XXSUrlAttackFilter.java 516448 2007-03-09 16:25:47Z ate $ * */ public class XXSUrlAttackFilter implements Filter { + public void init(FilterConfig config) throws ServletException { } - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, - ServletException + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest hreq = (HttpServletRequest) request; - if (isInvalid(hreq.getQueryString()) || isInvalid(hreq.getRequestURI())) + if (isInvalid(hreq.getQueryString()) + || isInvalid(hreq.getRequestURI())) { - ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST); + ((HttpServletResponse) response) + .sendError(HttpServletResponse.SC_BAD_REQUEST); } } chain.doFilter(request, response); @@ -54,8 +59,10 @@ private boolean isInvalid(String value) { - return (value != null && (value.indexOf('<') != -1 || value.indexOf('>') != -1 || value.indexOf("%3e") != -1 - || value.indexOf("%3c") != -1 || value.indexOf("%3E") != -1 || value.indexOf("%3E") != -1)); + return (value != null && (value.indexOf('<') != -1 + || value.indexOf('>') != -1 || value.indexOf("%3e") != -1 + || value.indexOf("%3c") != -1 || value.indexOf("%3E") != -1 || value + .indexOf("%3E") != -1)); } public void destroy() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/AddPortletAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/AddPortletAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/AddPortletAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,176 +32,179 @@ import org.apache.jetspeed.page.PageManager; import org.apache.jetspeed.request.RequestContext; - /** * Add Portlet portlet placement action * - * AJAX Parameters: - * id = portlet full name (pa::portletName) to be added - * page = (implied in the URL) - * Optional Parameters: - * row = the new row to move to - * col = the new column to move to - * + * AJAX Parameters: id = portlet full name (pa::portletName) to be added page = + * (implied in the URL) Optional Parameters: row = the new row to move to col = + * the new column to move to + * * @author David Gurney * @author David Sean Taylor * @version $Id: $ */ -public class AddPortletAction - extends MovePortletAction - implements AjaxAction, AjaxBuilder, Constants +public class AddPortletAction extends MovePortletAction implements AjaxAction, + AjaxBuilder, Constants { + protected Log log = LogFactory.getLog(AddPortletAction.class); + protected GetPortletsAction getPortletsAction = null; + protected boolean allowDuplicatePortlets = true; - public AddPortletAction( String template, String errorTemplate, PortletRegistry registry, GetPortletsAction getPortletsAction ) - throws AJAXException + public AddPortletAction(String template, String errorTemplate, + PortletRegistry registry, GetPortletsAction getPortletsAction) + throws AJAXException { - this( template, errorTemplate, registry, null, null, getPortletsAction, true ); + this(template, errorTemplate, registry, null, null, getPortletsAction, + true); } - public AddPortletAction( String template, - String errorTemplate, - PortletRegistry registry, - PageManager pageManager, - PortletActionSecurityBehavior securityBehavior, - GetPortletsAction getPortletsAction ) - throws AJAXException + public AddPortletAction(String template, String errorTemplate, + PortletRegistry registry, PageManager pageManager, + PortletActionSecurityBehavior securityBehavior, + GetPortletsAction getPortletsAction) throws AJAXException { - this( template, errorTemplate, registry, pageManager, securityBehavior, getPortletsAction, true ); + this(template, errorTemplate, registry, pageManager, securityBehavior, + getPortletsAction, true); } - public AddPortletAction( String template, - String errorTemplate, - PortletRegistry registry, - PageManager pageManager, - PortletActionSecurityBehavior securityBehavior, - GetPortletsAction getPortletsAction, - boolean allowDuplicatePortlets ) - throws AJAXException + public AddPortletAction(String template, String errorTemplate, + PortletRegistry registry, PageManager pageManager, + PortletActionSecurityBehavior securityBehavior, + GetPortletsAction getPortletsAction, boolean allowDuplicatePortlets) + throws AJAXException { - super( template, errorTemplate, registry, pageManager, securityBehavior ); + super(template, errorTemplate, registry, pageManager, securityBehavior); this.getPortletsAction = getPortletsAction; this.allowDuplicatePortlets = allowDuplicatePortlets; } - - protected boolean runAction( RequestContext requestContext, Map resultMap, boolean batch ) throws AJAXException + + protected boolean runAction(RequestContext requestContext, Map resultMap, + boolean batch) throws AJAXException { boolean success = true; String status = "success"; try { - resultMap.put( ACTION, "add" ); + resultMap.put(ACTION, "add"); // Get the necessary parameters off of the request - String portletId = getActionParameter( requestContext, PORTLETID ); - if (portletId == null) - { - throw new RuntimeException( "portlet id not provided" ); - } - resultMap.put( PORTLETID, portletId ); - + String portletId = getActionParameter(requestContext, PORTLETID); + if (portletId == null) { throw new RuntimeException( + "portlet id not provided"); } + resultMap.put(PORTLETID, portletId); + // Verify that the specified portlet id is valid and accessible // If the portletid is not valid an exception will be thrown - verifyPortletId( requestContext, portletId ); - - if( allowDuplicatePortlets == false ) + verifyPortletId(requestContext, portletId); + + if (allowDuplicatePortlets == false) { - // Check to see if this portlet has already been added to the page - checkForDuplicatePortlet( requestContext, resultMap, portletId ); + // Check to see if this portlet has already been added to the + // page + checkForDuplicatePortlet(requestContext, resultMap, portletId); } - - String layoutId = getActionParameter( requestContext, LAYOUTID ); - - if ( false == checkAccess( requestContext, JetspeedActions.EDIT ) ) + + String layoutId = getActionParameter(requestContext, LAYOUTID); + + if (false == checkAccess(requestContext, JetspeedActions.EDIT)) { - NestedFragmentContext addToFragmentContext = null; - if ( layoutId != null && layoutId.length() > 0 ) - { - Page page = requestContext.getPage(); - Fragment fragment = page.getFragmentById( layoutId ); - if ( fragment == null ) - { - success = false; - resultMap.put( REASON, "Specified layout fragment not found: " + layoutId ); - return success; - } - - try - { - addToFragmentContext = new NestedFragmentContext( fragment, page, getPortletRegistry() ); - } - catch ( Exception ex ) - { - log.error( "Failure to construct nested context for fragment " + layoutId, ex ); - success = false; - resultMap.put( REASON, "Cannot construct nested context for specified layout fragment" ); - return success; - } - } - - if ( ! createNewPageOnEdit( requestContext ) ) + NestedFragmentContext addToFragmentContext = null; + if (layoutId != null && layoutId.length() > 0) { + Page page = requestContext.getPage(); + Fragment fragment = page.getFragmentById(layoutId); + if (fragment == null) + { + success = false; + resultMap.put(REASON, + "Specified layout fragment not found: " + + layoutId); + return success; + } + + try + { + addToFragmentContext = new NestedFragmentContext( + fragment, page, getPortletRegistry()); + } + catch (Exception ex) + { + log.error( + "Failure to construct nested context for fragment " + + layoutId, ex); + success = false; + resultMap + .put(REASON, + "Cannot construct nested context for specified layout fragment"); + return success; + } + } + + if (!createNewPageOnEdit(requestContext)) + { success = false; - resultMap.put( REASON, "Insufficient access to edit page" ); + resultMap.put(REASON, "Insufficient access to edit page"); return success; } status = "refresh"; - if ( addToFragmentContext != null ) + if (addToFragmentContext != null) { - Page newPage = requestContext.getPage(); + Page newPage = requestContext.getPage(); - // using NestedFragmentContext, find portlet id for copy of target portlet in the new page - Fragment newFragment = null; - try - { - newFragment = addToFragmentContext.getFragmentOnNewPage( newPage, getPortletRegistry() ); - } - catch ( Exception ex ) - { - log.error( "Failure to locate copy of fragment " + layoutId, ex ); - success = false; - resultMap.put( REASON, "Failed to find new fragment for specified layout id: " + layoutId ); - return success; - } - layoutId = newFragment.getId(); + // using NestedFragmentContext, find portlet id for copy of + // target portlet in the new page + Fragment newFragment = null; + try + { + newFragment = addToFragmentContext + .getFragmentOnNewPage(newPage, + getPortletRegistry()); + } + catch (Exception ex) + { + log.error("Failure to locate copy of fragment " + + layoutId, ex); + success = false; + resultMap.put(REASON, + "Failed to find new fragment for specified layout id: " + + layoutId); + return success; + } + layoutId = newFragment.getId(); } } - + Page page = requestContext.getPage(); - + Fragment fragment = pageManager.newFragment(); - fragment.setType( Fragment.PORTLET ); - fragment.setName( portletId ); - + fragment.setType(Fragment.PORTLET); + fragment.setName(portletId); + Fragment placeInLayoutFragment = null; - if ( layoutId != null && layoutId.length() > 0 ) + if (layoutId != null && layoutId.length() > 0) { - placeInLayoutFragment = page.getFragmentById( layoutId ); - if ( placeInLayoutFragment == null ) - { - throw new Exception( "layout id not found: " + layoutId ); - } + placeInLayoutFragment = page.getFragmentById(layoutId); + if (placeInLayoutFragment == null) { throw new Exception( + "layout id not found: " + layoutId); } } else { placeInLayoutFragment = page.getRootFragment(); } - success = placeFragment( requestContext, - batch, - resultMap, - fragment, - placeInLayoutFragment ) ; - - resultMap.put( PORTLETENTITY, fragment.getId() ); - if ( success ) + success = placeFragment(requestContext, batch, resultMap, fragment, + placeInLayoutFragment); + + resultMap.put(PORTLETENTITY, fragment.getId()); + if (success) { - resultMap.put( STATUS, status ); + resultMap.put(STATUS, status); } - } - catch ( Exception e ) + } + catch (Exception e) { // Log the exception log.error("exception while adding a portlet", e); @@ -213,62 +216,80 @@ return success; } - - protected void verifyPortletId(RequestContext requestContext, String portletId) throws Exception + + protected void verifyPortletId(RequestContext requestContext, + String portletId) throws Exception { - // Get the list of valid portlets from the getPortletAction - List portletList = getPortletsAction.retrievePortlets(requestContext, null); - if(portletList != null) { - for(int i = 0; i < portletList.size(); i++) { - PortletInfo portletInfo = (PortletInfo)portletList.get(i); - if(portletInfo != null) { - if(portletInfo.getName().equalsIgnoreCase(portletId)) { - // A match was found there is no need to continue - return; - } - } - } - } - // If we got here, then no match was found - throw new Exception(portletId + " is not a valid portlet or not allowed for this user"); + // Get the list of valid portlets from the getPortletAction + List portletList = getPortletsAction.retrievePortlets(requestContext, + null); + if (portletList != null) + { + for (int i = 0; i < portletList.size(); i++) + { + PortletInfo portletInfo = (PortletInfo) portletList.get(i); + if (portletInfo != null) + { + if (portletInfo.getName().equalsIgnoreCase(portletId)) + { + // A match was found there is no need to continue + return; + } + } + } + } + // If we got here, then no match was found + throw new Exception(portletId + + " is not a valid portlet or not allowed for this user"); } - - protected void checkForDuplicatePortlet(RequestContext requestContext, Map resultMap, String portletId) - throws AJAXException + + protected void checkForDuplicatePortlet(RequestContext requestContext, + Map resultMap, String portletId) throws AJAXException { - // Look at each portlet currently on the page - Page page = requestContext.getPage(); - - boolean duplicateFound = isDuplicateFragment(page.getRootFragment(), portletId); - - // Throw an exception if a duplicate is found - if(duplicateFound == true) { - throw new AJAXException(portletId + " is already on the page, duplicates are not allowed"); - } + // Look at each portlet currently on the page + Page page = requestContext.getPage(); + + boolean duplicateFound = isDuplicateFragment(page.getRootFragment(), + portletId); + + // Throw an exception if a duplicate is found + if (duplicateFound == true) { throw new AJAXException(portletId + + " is already on the page, duplicates are not allowed"); } } - protected boolean isDuplicateFragment(Fragment fragment, String portletId) { - if(fragment != null) { - // Get the name of this fragment - String fragmentName = fragment.getName(); - if(fragmentName.equals(portletId)) { - // Duplicate was found - return true; - } else { - // Process the child fragments if found - List childFragments = fragment.getFragments(); - if(childFragments != null) { - for(int i = 0; i < childFragments.size(); i++) { - // Recursively call this method again to process the child fragments - if(isDuplicateFragment((Fragment)childFragments.get(i),portletId) == true) { - // No need to continue to loop if a duplicate was found - return true; - } - } - } - } - } - // We will only get here if no duplicates were found - return false; + protected boolean isDuplicateFragment(Fragment fragment, String portletId) + { + if (fragment != null) + { + // Get the name of this fragment + String fragmentName = fragment.getName(); + if (fragmentName.equals(portletId)) + { + // Duplicate was found + return true; + } + else + { + // Process the child fragments if found + List childFragments = fragment.getFragments(); + if (childFragments != null) + { + for (int i = 0; i < childFragments.size(); i++) + { + // Recursively call this method again to process the + // child fragments + if (isDuplicateFragment((Fragment) childFragments + .get(i), portletId) == true) + { + // No need to continue to loop if a duplicate was + // found + return true; + } + } + } + } + } + // We will only get here if no duplicates were found + return false; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BaseGetResourceAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BaseGetResourceAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BaseGetResourceAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,45 +28,47 @@ /** * Abstract Get Resource aaction for folders, pages and links - * + * * @author David Sean Taylor * @version $Id: $ */ -public abstract class BaseGetResourceAction - extends BasePortletAction - implements AjaxAction, AjaxBuilder, Constants +public abstract class BaseGetResourceAction extends BasePortletAction implements + AjaxAction, AjaxBuilder, Constants { - protected static final Log log = LogFactory.getLog(BaseSiteUpdateAction.class); - - public BaseGetResourceAction(String template, - String errorTemplate, + + protected static final Log log = LogFactory + .getLog(BaseSiteUpdateAction.class); + + public BaseGetResourceAction(String template, String errorTemplate, PageManager pageManager) { super(template, errorTemplate, pageManager); } - - public BaseGetResourceAction(String template, - String errorTemplate, - PortletActionSecurityBehavior securityBehavior) + + public BaseGetResourceAction(String template, String errorTemplate, + PortletActionSecurityBehavior securityBehavior) { super(template, errorTemplate, securityBehavior); } - public BaseGetResourceAction(String template, - String errorTemplate, - PageManager pageManager, - PortletActionSecurityBehavior securityBehavior) + public BaseGetResourceAction(String template, String errorTemplate, + PageManager pageManager, + PortletActionSecurityBehavior securityBehavior) { - super(template, errorTemplate, pageManager, securityBehavior); + super(template, errorTemplate, pageManager, securityBehavior); } - protected void putSecurityInformation(Map resultMap, SecuredResource resource) + protected void putSecurityInformation(Map resultMap, + SecuredResource resource) { if (resource.getSecurityConstraints() != null) { - resultMap.put(SECURITY_REFS, resource.getSecurityConstraints().getSecurityConstraintsRefs()); - resultMap.put(SECURITY_DEFS, resource.getSecurityConstraints().getSecurityConstraints()); - resultMap.put(SECURITY_OWNER, resource.getSecurityConstraints().getOwner()); + resultMap.put(SECURITY_REFS, resource.getSecurityConstraints() + .getSecurityConstraintsRefs()); + resultMap.put(SECURITY_DEFS, resource.getSecurityConstraints() + .getSecurityConstraints()); + resultMap.put(SECURITY_OWNER, resource.getSecurityConstraints() + .getOwner()); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BasePortletAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BasePortletAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BasePortletAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,31 +32,34 @@ /** * Abstract portlet placement action - * + * * @author David Gurney * @author David Sean Taylor * @version $Id: $ */ -public abstract class BasePortletAction - implements AjaxAction, AjaxBuilder, Constants +public abstract class BasePortletAction implements AjaxAction, AjaxBuilder, + Constants { - protected static final Log log = LogFactory.getLog(BasePortletAction.class); - protected String template = null; + + protected static final Log log = LogFactory.getLog(BasePortletAction.class); + + protected String template = null; + protected PageManager pageManager = null; + protected String errorTemplate = null; + protected PortletActionSecurityBehavior securityBehavior; - - public BasePortletAction(String template, - String errorTemplate, - PortletActionSecurityBehavior securityBehavior) + + public BasePortletAction(String template, String errorTemplate, + PortletActionSecurityBehavior securityBehavior) { this.template = template; this.errorTemplate = errorTemplate; this.securityBehavior = securityBehavior; } - public BasePortletAction(String template, - String errorTemplate, + public BasePortletAction(String template, String errorTemplate, PageManager pageManager) { this.template = template; @@ -64,23 +67,23 @@ this.pageManager = pageManager; this.securityBehavior = null; } - - public BasePortletAction(String template, - String errorTemplate, - PageManager pageManager, - PortletActionSecurityBehavior securityBehavior) + + public BasePortletAction(String template, String errorTemplate, + PageManager pageManager, + PortletActionSecurityBehavior securityBehavior) { this(template, errorTemplate, securityBehavior); this.pageManager = pageManager; } - public boolean buildContext(RequestContext requestContext, Map responseContext) + public boolean buildContext(RequestContext requestContext, + Map responseContext) { return true; } public boolean buildErrorContext(RequestContext requestContext, - Map responseContext) + Map responseContext) { responseContext.put(STATUS, "failure"); @@ -117,50 +120,50 @@ } return access; } - + public boolean isCreateNewPageOnEditEnabled() { - if (securityBehavior == null) - return false; - return securityBehavior.isCreateNewPageOnEditEnabled(); + if (securityBehavior == null) return false; + return securityBehavior.isCreateNewPageOnEditEnabled(); } + public boolean isPageQualifiedForCreateNewPageOnEdit(RequestContext context) { - if (securityBehavior == null) - return false; - return securityBehavior.isPageQualifiedForCreateNewPageOnEdit(context); + if (securityBehavior == null) return false; + return securityBehavior.isPageQualifiedForCreateNewPageOnEdit(context); } + public boolean createNewPageOnEdit(RequestContext context) { - if (securityBehavior == null) - return false; - - return securityBehavior.createNewPageOnEdit(context); + if (securityBehavior == null) return false; + + return securityBehavior.createNewPageOnEdit(context); } - - public Fragment getFragmentIdFromLocation( int row, int column, Page page ) + + public Fragment getFragmentIdFromLocation(int row, int column, Page page) { - return getFragmentIdFromLocation( row, column, page.getRootFragment() ); + return getFragmentIdFromLocation(row, column, page.getRootFragment()); } - public Fragment getFragmentIdFromLocation( int row, int column, Fragment parentFragment ) + + public Fragment getFragmentIdFromLocation(int row, int column, + Fragment parentFragment) { Iterator fragments = parentFragment.getFragments().iterator(); - while ( fragments.hasNext() ) + while (fragments.hasNext()) { - Fragment fragment = (Fragment)fragments.next(); - if ( fragment.getLayoutColumn() == column && fragment.getLayoutRow() == row ) - { - return fragment; - } + Fragment fragment = (Fragment) fragments.next(); + if (fragment.getLayoutColumn() == column + && fragment.getLayoutRow() == row) { return fragment; } } return null; } - - public boolean runBatch(RequestContext requestContext, Map resultMap) throws AJAXException + + public boolean runBatch(RequestContext requestContext, Map resultMap) + throws AJAXException { return run(requestContext, resultMap); } - + public String getActionParameter(RequestContext requestContext, String name) { String parameter = requestContext.getRequestParameter(name); @@ -169,23 +172,22 @@ Object o = requestContext.getAttribute(name); if (o != null) { - if (o instanceof String) - return (String)o; + if (o instanceof String) return (String) o; } } return parameter; } - - public String getNonNullActionParameter(RequestContext requestContext, String name) + + public String getNonNullActionParameter(RequestContext requestContext, + String name) { String result = getActionParameter(requestContext, name); - if (result == null) - return ""; + if (result == null) return ""; return result; } - + public Fragment getParentFragmentById(String id, Fragment root) { - return NestedFragmentContext.getParentFragmentById( id, root ); - } + return NestedFragmentContext.getParentFragmentById(id, root); + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BaseSiteUpdateAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BaseSiteUpdateAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BaseSiteUpdateAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -36,56 +36,55 @@ /** * Abstract Site update action for folders, pages and links - * + * * @author David Sean Taylor * @version $Id: $ */ -public abstract class BaseSiteUpdateAction - extends BasePortletAction - implements AjaxAction, AjaxBuilder, Constants +public abstract class BaseSiteUpdateAction extends BasePortletAction implements + AjaxAction, AjaxBuilder, Constants { - protected static final Log log = LogFactory.getLog(BaseSiteUpdateAction.class); - - public BaseSiteUpdateAction(String template, - String errorTemplate, + + protected static final Log log = LogFactory + .getLog(BaseSiteUpdateAction.class); + + public BaseSiteUpdateAction(String template, String errorTemplate, PageManager pageManager) { super(template, errorTemplate, pageManager); } - - public BaseSiteUpdateAction(String template, - String errorTemplate, - PortletActionSecurityBehavior securityBehavior) + + public BaseSiteUpdateAction(String template, String errorTemplate, + PortletActionSecurityBehavior securityBehavior) { super(template, errorTemplate, securityBehavior); } - public BaseSiteUpdateAction(String template, - String errorTemplate, - PageManager pageManager, - PortletActionSecurityBehavior securityBehavior) + public BaseSiteUpdateAction(String template, String errorTemplate, + PageManager pageManager, + PortletActionSecurityBehavior securityBehavior) { - super(template, errorTemplate, pageManager, securityBehavior); + super(template, errorTemplate, pageManager, securityBehavior); } - protected abstract int updateInformation(RequestContext requestContext, Map resultMap, Node node, String path) - throws AJAXException; - - protected int insertMetadata(RequestContext requestContext, Map resultMap, Node node) - throws AJAXException + protected abstract int updateInformation(RequestContext requestContext, + Map resultMap, Node node, String path) throws AJAXException; + + protected int insertMetadata(RequestContext requestContext, Map resultMap, + Node node) throws AJAXException { String name = getActionParameter(requestContext, "name"); String language = getActionParameter(requestContext, "lang"); String value = getActionParameter(requestContext, "value"); if (isBlank(name) || isBlank(language)) - throw new AJAXException("Invalid Metadata: name, language invalid data."); + throw new AJAXException( + "Invalid Metadata: name, language invalid data."); Locale locale = new Locale(language); - node.getMetadata().addField(locale, name, value); + node.getMetadata().addField(locale, name, value); return 1; } - protected int updateMetadata(RequestContext requestContext, Map resultMap, Node node) - throws AJAXException + protected int updateMetadata(RequestContext requestContext, Map resultMap, + Node node) throws AJAXException { String name = getActionParameter(requestContext, "name"); String language = getActionParameter(requestContext, "lang"); @@ -93,21 +92,21 @@ String oldName = getActionParameter(requestContext, "oldname"); String oldLanguage = getActionParameter(requestContext, "oldlang"); - if (isBlank(name) || isBlank(language) || isBlank(oldName) || isBlank(oldLanguage)) - throw new AJAXException("Invalid Metadata: name, language invalid data."); - + if (isBlank(name) || isBlank(language) || isBlank(oldName) + || isBlank(oldLanguage)) + throw new AJAXException( + "Invalid Metadata: name, language invalid data."); + Collection cfields = node.getMetadata().getFields(oldName); - if (cfields == null || cfields.size() == 0) - { - return insertMetadata(requestContext, resultMap, node); - } + if (cfields == null || cfields.size() == 0) { return insertMetadata( + requestContext, resultMap, node); } boolean found = false; Iterator fields = cfields.iterator(); while (fields.hasNext()) { - LocalizedField field = (LocalizedField)fields.next(); - if (areFieldsSame(field.getName(), oldName) && - areFieldsSame(field.getLocale().toString(), oldLanguage)) + LocalizedField field = (LocalizedField) fields.next(); + if (areFieldsSame(field.getName(), oldName) + && areFieldsSame(field.getLocale().toString(), oldLanguage)) { field.setName(name); field.setLocale(new Locale(language)); @@ -116,31 +115,28 @@ break; } } - if (!found) - return insertMetadata(requestContext, resultMap, node); + if (!found) return insertMetadata(requestContext, resultMap, node); return 1; } - - protected int removeMetadata(RequestContext requestContext, Map resultMap, Node node) - throws AJAXException + + protected int removeMetadata(RequestContext requestContext, Map resultMap, + Node node) throws AJAXException { String name = getActionParameter(requestContext, "name"); String language = getActionParameter(requestContext, "lang"); if (isBlank(name) || isBlank(language)) - throw new AJAXException("Invalid Metadata: name, language invalid data."); + throw new AJAXException( + "Invalid Metadata: name, language invalid data."); Collection cfields = node.getMetadata().getFields(name); Collection allFields = node.getMetadata().getFields(); - if (cfields == null || cfields.size() == 0) - { - return 0; - } - boolean found = false; + if (cfields == null || cfields.size() == 0) { return 0; } + boolean found = false; Iterator fields = cfields.iterator(); while (fields.hasNext()) { - LocalizedField field = (LocalizedField)fields.next(); - if (areFieldsSame(field.getName(), name) && - areFieldsSame(field.getLocale().toString(), language)) + LocalizedField field = (LocalizedField) fields.next(); + if (areFieldsSame(field.getName(), name) + && areFieldsSame(field.getLocale().toString(), language)) { cfields.remove(field); if (allFields.remove(field)) @@ -150,13 +146,13 @@ found = true; break; } - } - + } + return (found) ? 1 : 0; } - protected int insertSecurityReference(RequestContext requestContext, Map resultMap, Node node) - throws AJAXException + protected int insertSecurityReference(RequestContext requestContext, + Map resultMap, Node node) throws AJAXException { String name = getActionParameter(requestContext, "name"); String kind = getActionParameter(requestContext, "kind"); @@ -165,7 +161,7 @@ if (node.getSecurityConstraints() == null) { SecurityConstraints cons = node.newSecurityConstraints(); - node.setSecurityConstraints(cons); + node.setSecurityConstraints(cons); } if (kind.equals("Owner")) { @@ -173,16 +169,16 @@ } else { - List refs = node.getSecurityConstraints().getSecurityConstraintsRefs(); - if (refs.contains(name)) - return 0; // do nothing + List refs = node.getSecurityConstraints() + .getSecurityConstraintsRefs(); + if (refs.contains(name)) return 0; // do nothing refs.add(name); } - return 1; + return 1; } - protected int updateSecurityReference(RequestContext requestContext, Map resultMap, Node node) - throws AJAXException + protected int updateSecurityReference(RequestContext requestContext, + Map resultMap, Node node) throws AJAXException { String name = getActionParameter(requestContext, "name"); String oldName = getActionParameter(requestContext, "oldname"); @@ -192,13 +188,11 @@ if (node.getSecurityConstraints() == null) { SecurityConstraints cons = node.newSecurityConstraints(); - node.setSecurityConstraints(cons); - } - List refs = node.getSecurityConstraints().getSecurityConstraintsRefs(); - if (refs == null || refs.size() == 0) - { - return insertSecurityReference(requestContext, resultMap, node); + node.setSecurityConstraints(cons); } + List refs = node.getSecurityConstraints().getSecurityConstraintsRefs(); + if (refs == null || refs.size() == 0) { return insertSecurityReference( + requestContext, resultMap, node); } boolean found = false; if (kind.equals("Owner")) { @@ -206,10 +200,10 @@ found = true; } else - { + { for (int ix = 0; ix < refs.size(); ix++) { - String ref = (String)refs.get(ix); + String ref = (String) refs.get(ix); if (areFieldsSame(ref, oldName)) { refs.set(ix, name); @@ -222,65 +216,52 @@ return insertSecurityReference(requestContext, resultMap, node); return 1; } - - protected int removeSecurityReference(RequestContext requestContext, Map resultMap, Node node) - throws AJAXException + + protected int removeSecurityReference(RequestContext requestContext, + Map resultMap, Node node) throws AJAXException { String name = getActionParameter(requestContext, "name"); String kind = getActionParameter(requestContext, "kind"); if (isBlank(name) || isBlank(kind)) throw new AJAXException("Invalid Security Ref: name invalid data."); - if (node.getSecurityConstraints() == null) - { - return 0; - } + if (node.getSecurityConstraints() == null) { return 0; } if (kind.equals("Owner")) { node.getSecurityConstraints().setOwner(null); } else { - List refs = node.getSecurityConstraints().getSecurityConstraintsRefs(); - if (!refs.contains(name)) - return 0; // nothing to do + List refs = node.getSecurityConstraints() + .getSecurityConstraintsRefs(); + if (!refs.contains(name)) return 0; // nothing to do refs.remove(name); } return 1; } - protected int removeSecurityDef(RequestContext requestContext, Map resultMap, Node node) - throws AJAXException + protected int removeSecurityDef(RequestContext requestContext, + Map resultMap, Node node) throws AJAXException { String id = getActionParameter(requestContext, "id"); if (isBlank(id)) throw new AJAXException("Invalid Security Ref: id invalid data."); - if (node.getSecurityConstraints() == null) - { - return 0; - } + if (node.getSecurityConstraints() == null) { return 0; } List defs = node.getSecurityConstraints().getSecurityConstraints(); - if (defs == null || defs.size() == 0) - { - return 0; - } - if (id.length() == 1) - return 0; + if (defs == null || defs.size() == 0) { return 0; } + if (id.length() == 1) return 0; id = id.substring(1); int index = Integer.parseInt(id) - 1; - if (index < 0) - { - return 0; - } + if (index < 0) { return 0; } defs.remove(index); return 1; } - + protected boolean isBlank(String field) { - if (field == null || field.trim().length() == 0) - return true; + if (field == null || field.trim().length() == 0) return true; return false; } + protected boolean isFieldModified(String paramValue, String prevValue) { if (paramValue == null) @@ -292,18 +273,19 @@ } else { - if (prevValue == null) - return true; + if (prevValue == null) return true; if (prevValue.equals(paramValue)) return false; else return true; } } + protected boolean areFieldsSame(String f1, String f2) { return !isFieldModified(f1, f2); } + protected boolean isBooleanModified(String paramValue, boolean prevValue) { if (paramValue == null) @@ -320,5 +302,5 @@ else return false; } - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BaseUserAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BaseUserAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/BaseUserAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,32 +32,35 @@ /** * Abstract portlet placement action - * + * * @author David Gurney * @author David Sean Taylor * @author Mikko Wuokko * @version $Id: $ */ -public abstract class BaseUserAction - implements AjaxAction, AjaxBuilder, Constants +public abstract class BaseUserAction implements AjaxAction, AjaxBuilder, + Constants { - protected Log log = LogFactory.getLog(BaseUserAction.class); - protected String template = null; + + protected Log log = LogFactory.getLog(BaseUserAction.class); + + protected String template = null; + protected UserManager userManager = null; + protected String errorTemplate = null; + protected RolesSecurityBehavior securityBehavior; - - public BaseUserAction(String template, - String errorTemplate, - RolesSecurityBehavior securityBehavior) + + public BaseUserAction(String template, String errorTemplate, + RolesSecurityBehavior securityBehavior) { this.template = template; this.errorTemplate = errorTemplate; this.securityBehavior = securityBehavior; } - public BaseUserAction(String template, - String errorTemplate, + public BaseUserAction(String template, String errorTemplate, UserManager userManager) { this.template = template; @@ -65,23 +68,22 @@ this.userManager = userManager; this.securityBehavior = null; } - - public BaseUserAction(String template, - String errorTemplate, - UserManager userManager, - RolesSecurityBehavior securityBehavior) + + public BaseUserAction(String template, String errorTemplate, + UserManager userManager, RolesSecurityBehavior securityBehavior) { this(template, errorTemplate, securityBehavior); this.userManager = userManager; } - public boolean buildContext(RequestContext requestContext, Map responseContext) + public boolean buildContext(RequestContext requestContext, + Map responseContext) { return true; } public boolean buildErrorContext(RequestContext requestContext, - Map responseContext) + Map responseContext) { responseContext.put(STATUS, "failure"); @@ -121,12 +123,11 @@ public boolean createNewPageOnEdit(RequestContext context) { - if (securityBehavior == null) - return false; - - return securityBehavior.createNewPageOnEdit(context); + if (securityBehavior == null) return false; + + return securityBehavior.createNewPageOnEdit(context); } - + // TODO: support nested fragments public Fragment getFragmentIdFromLocation(int row, int column, Page page) { @@ -134,21 +135,19 @@ Iterator fragments = root.getFragments().iterator(); while (fragments.hasNext()) { - Fragment fragment = (Fragment)fragments.next(); - if (fragment.getLayoutColumn() == column && - fragment.getLayoutRow() == row) - { - return fragment; - } + Fragment fragment = (Fragment) fragments.next(); + if (fragment.getLayoutColumn() == column + && fragment.getLayoutRow() == row) { return fragment; } } return null; } - - public boolean runBatch(RequestContext requestContext, Map resultMap) throws AJAXException + + public boolean runBatch(RequestContext requestContext, Map resultMap) + throws AJAXException { return run(requestContext, resultMap); } - + public String getActionParameter(RequestContext requestContext, String name) { String parameter = requestContext.getRequestParameter(name); @@ -157,44 +156,41 @@ Object o = requestContext.getAttribute(name); if (o != null) { - if (o instanceof String) - return (String)o; + if (o instanceof String) return (String) o; } } return parameter; } - + public Fragment getParentFragmentById(String id, Fragment root) { - if ( id == null ) - { - return null; - } - return searchForParentFragmentById( id, root ); + if (id == null) { return null; } + return searchForParentFragmentById(id, root); } - - protected Fragment searchForParentFragmentById( String id, Fragment parent ) - { + + protected Fragment searchForParentFragmentById(String id, Fragment parent) + { // find fragment by id, tracking fragment parent Fragment matchedParent = null; - if( parent != null ) + if (parent != null) { // process the children List children = parent.getFragments(); - for( int i = 0, cSize = children.size() ; i < cSize ; i++) + for (int i = 0, cSize = children.size(); i < cSize; i++) { - Fragment childFrag = (Fragment)children.get( i ); - if ( childFrag != null ) + Fragment childFrag = (Fragment) children.get(i); + if (childFrag != null) { - if ( id.equals( childFrag.getId() ) ) + if (id.equals(childFrag.getId())) { matchedParent = parent; break; } else { - matchedParent = searchForParentFragmentById( id, childFrag ); - if ( matchedParent != null ) + matchedParent = searchForParentFragmentById(id, + childFrag); + if (matchedParent != null) { break; } @@ -204,26 +200,27 @@ } return matchedParent; } - - + /** - * Helper method to determine if a parameter is true. Prevents - * accidental NullPointerExceptions when comparing or or using - * the parameter value. - * @param parameter The value to be determined as boolean true or false. - * @return boolean true or false according to the @param value. + * Helper method to determine if a parameter is true. Prevents accidental + * NullPointerExceptions when comparing or or using the parameter value. + * + * @param parameter + * The value to be determined as boolean true or false. + * @return boolean true or false according to the + * @param value. */ public boolean isTrue(String parameter) { - boolean isTrue = false; - if(parameter != null) - { - if(parameter.equalsIgnoreCase("true")) - { - isTrue = true; - } - } - return isTrue; + boolean isTrue = false; + if (parameter != null) + { + if (parameter.equalsIgnoreCase("true")) + { + isTrue = true; + } + } + return isTrue; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/ChangePortletAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/ChangePortletAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/ChangePortletAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -42,49 +42,47 @@ /** * Changes the window state or portlet mode for a given portlet window - * - * AJAX Parameters: - * id = the fragment id of the portlet to move - * page = (implied in the URL) - * state = the new window state - * mode = the new portlet mode - * + * + * AJAX Parameters: id = the fragment id of the portlet to move page = (implied + * in the URL) state = the new window state mode = the new portlet mode + * * @author David Sean Taylor * @version $Id: $ */ -public class ChangePortletAction - extends BasePortletAction - implements AjaxAction, AjaxBuilder, Constants +public class ChangePortletAction extends BasePortletAction implements + AjaxAction, AjaxBuilder, Constants { - protected static final Log log = LogFactory.getLog(ChangePortletAction.class); + + protected static final Log log = LogFactory + .getLog(ChangePortletAction.class); + protected String action; + protected Map validWindowStates = new HashMap(); + protected Map validPortletModes = new HashMap(); + protected PortletWindowAccessor windowAccessor; - - public ChangePortletAction(String template, - String errorTemplate, - String action, - PortletWindowAccessor windowAccessor) - throws AJAXException + + public ChangePortletAction(String template, String errorTemplate, + String action, PortletWindowAccessor windowAccessor) + throws AJAXException { this(template, errorTemplate, action, null, windowAccessor, null); } - - public ChangePortletAction(String template, - String errorTemplate, - String action, - PageManager pageManager, - PortletWindowAccessor windowAccessor, - PortletActionSecurityBehavior securityBehavior) - throws AJAXException + + public ChangePortletAction(String template, String errorTemplate, + String action, PageManager pageManager, + PortletWindowAccessor windowAccessor, + PortletActionSecurityBehavior securityBehavior) + throws AJAXException { super(template, errorTemplate, pageManager, securityBehavior); this.action = action; this.windowAccessor = windowAccessor; - + // Build the maps of allowed (internal) modes and states - Iterator modes = JetspeedActions.getStandardPortletModes().iterator(); + Iterator modes = JetspeedActions.getStandardPortletModes().iterator(); while (modes.hasNext()) { String mode = modes.next().toString(); @@ -96,32 +94,34 @@ String mode = modes.next().toString(); this.validPortletModes.put(mode, mode); } - Iterator states = JetspeedActions.getStandardWindowStates().iterator(); + Iterator states = JetspeedActions.getStandardWindowStates().iterator(); while (states.hasNext()) { String state = states.next().toString(); this.validWindowStates.put(state, state); - } - states = JetspeedActions.getExtendedWindowStates().iterator(); + } + states = JetspeedActions.getExtendedWindowStates().iterator(); while (states.hasNext()) { String state = states.next().toString(); this.validWindowStates.put(state, state); - } + } } - public boolean runBatch(RequestContext requestContext, Map resultMap) throws AJAXException + public boolean runBatch(RequestContext requestContext, Map resultMap) + throws AJAXException { return runAction(requestContext, resultMap, true); - } - + } + public boolean run(RequestContext requestContext, Map resultMap) throws AJAXException { return runAction(requestContext, resultMap, false); } - - public boolean runAction(RequestContext requestContext, Map resultMap, boolean batch) + + public boolean runAction(RequestContext requestContext, Map resultMap, + boolean batch) { boolean success = true; String status = "success"; @@ -130,148 +130,145 @@ resultMap.put(ACTION, action); // Get the necessary parameters off of the request String fragmentId = getActionParameter(requestContext, FRAGMENTID); - if (fragmentId == null) - { - throw new Exception("fragment id not provided"); - } + if (fragmentId == null) { throw new Exception( + "fragment id not provided"); } resultMap.put(FRAGMENTID, fragmentId); - - ContentPage page = requestContext.getPage(); + + ContentPage page = requestContext.getPage(); ContentFragment fragment = page.getContentFragmentById(fragmentId); - - if ( fragment == null ) + + if (fragment == null) { throw new Exception( + "fragment specified by id cannot be found"); } + String requestedState = getActionParameter(requestContext, + WINDOW_STATE); + String requestedMode = getActionParameter(requestContext, + PORTLET_MODE); + if ("layout".equals(fragment.getType())) { - throw new Exception( "fragment specified by id cannot be found" ); + if (!fragment.getId().equals(page.getRootFragment().getId())) { throw new Exception( + "for layout fragments, change action applies to only to the root layout fragment (i.e. it does not apply to nested layout fragments)"); } + PageActionAccess pageActionAccess = (PageActionAccess) requestContext + .getAttribute(PortalReservedParameters.PAGE_EDIT_ACCESS_ATTRIBUTE); + if (pageActionAccess == null) { throw new Exception( + "cannot change action for root layout fragment due to null PageActionAccess object"); } + // pageActionAccess. + PortletWindow window = windowAccessor + .getPortletWindow(fragment); + PortletMode currentMode = requestContext.getPortalURL() + .getNavigationalState().getMode(window); + WindowState currentState = requestContext.getPortalURL() + .getNavigationalState().getState(window); + + boolean requestedModeAlreadySet = false; + if (requestedMode == null) + requestedModeAlreadySet = true; + else + { + if (requestedMode.equals(PortletMode.EDIT.toString())) + { + if (pageActionAccess.isEditing()) + requestedModeAlreadySet = true; + else + { + if (pageActionAccess.isEditAllowed()) + { + pageActionAccess.setEditing(true); + resultMap.put(STATUS, status); + resultMap.put(OLD_PORTLET_MODE, currentMode + .toString()); + resultMap.put(PORTLET_MODE, requestedMode); + } + else + { + throw new Exception( + "permissions do no allow page edit"); + } + } + } + else if (requestedMode.equals(PortletMode.VIEW.toString())) + { + pageActionAccess.setEditing(false); + // if ( currentMode.equals( PortletMode.HELP ) ) + resultMap.put(STATUS, status); + resultMap.put(OLD_PORTLET_MODE, currentMode.toString()); + resultMap.put(PORTLET_MODE, requestedMode); + } + else + { + requestedModeAlreadySet = true; + } + } + if (requestedModeAlreadySet) + { + resultMap.put(STATUS, status); + resultMap.put(OLD_PORTLET_MODE, currentMode.toString()); + resultMap.put(PORTLET_MODE, currentMode.toString()); + } } - String requestedState = getActionParameter(requestContext, WINDOW_STATE); - String requestedMode = getActionParameter(requestContext, PORTLET_MODE); - if ( "layout".equals( fragment.getType() ) ) - { - if ( ! fragment.getId().equals( page.getRootFragment().getId() ) ) - { - throw new Exception( "for layout fragments, change action applies to only to the root layout fragment (i.e. it does not apply to nested layout fragments)" ); - } - PageActionAccess pageActionAccess = (PageActionAccess)requestContext.getAttribute( PortalReservedParameters.PAGE_EDIT_ACCESS_ATTRIBUTE ); - if ( pageActionAccess == null ) - { - throw new Exception( "cannot change action for root layout fragment due to null PageActionAccess object" ); - } - //pageActionAccess. - PortletWindow window = windowAccessor.getPortletWindow(fragment); - PortletMode currentMode = requestContext.getPortalURL().getNavigationalState().getMode( window ); - WindowState currentState = requestContext.getPortalURL().getNavigationalState().getState( window ); - - boolean requestedModeAlreadySet = false; - if ( requestedMode == null ) - requestedModeAlreadySet = true; - else - { - if ( requestedMode.equals( PortletMode.EDIT.toString() ) ) - { - if( pageActionAccess.isEditing() ) - requestedModeAlreadySet = true; - else - { - if ( pageActionAccess.isEditAllowed()) - { - pageActionAccess.setEditing( true ); - resultMap.put(STATUS, status); - resultMap.put(OLD_PORTLET_MODE, currentMode.toString()); - resultMap.put(PORTLET_MODE, requestedMode); - } - else - { - throw new Exception( "permissions do no allow page edit" ); - } - } - } - else if ( requestedMode.equals( PortletMode.VIEW.toString() ) ) - { - pageActionAccess.setEditing( false ); - //if ( currentMode.equals( PortletMode.HELP ) ) - resultMap.put(STATUS, status); - resultMap.put(OLD_PORTLET_MODE, currentMode.toString()); - resultMap.put(PORTLET_MODE, requestedMode); - } - else - { - requestedModeAlreadySet = true; - } - } - if ( requestedModeAlreadySet ) - { - resultMap.put(STATUS, status); - resultMap.put(OLD_PORTLET_MODE, currentMode.toString()); - resultMap.put(PORTLET_MODE, currentMode.toString()); - } - } else { - if (requestedState == null && requestedMode == null) - { - throw new Exception("portlet window state or mode not provided"); - } - if (requestedState != null && !isValidWindowState(requestedState)) - { - throw new Exception("portlet window state " + requestedState + " is not supported"); - } - if (requestedMode != null && !isValidPortletMode(requestedMode)) - { - throw new Exception("portlet mode " + requestedMode + " is not supported"); - } - - - String oldState = fragment.getState(); - String oldMode = fragment.getMode(); - - // Now Change the transient navigational state - MutableNavigationalState navState = (MutableNavigationalState)requestContext.getPortalURL().getNavigationalState(); - PortletWindow portletWindow = windowAccessor.getPortletWindow(fragment); - if (portletWindow != null) - { - oldState = navState.getState(portletWindow).toString(); - oldMode = navState.getMode(portletWindow).toString(); - if (requestedState != null) - { - navState.setState(portletWindow, new WindowState(requestedState)); - } - if (requestedMode != null) - { - navState.setMode(portletWindow, new PortletMode(requestedMode)); - } - navState.sync(requestContext); - } - - - if (checkAccess(requestContext, JetspeedActions.EDIT)) - { - if (requestedState != null) - fragment.setState(requestedState); - if (requestedMode != null) - fragment.setMode(requestedMode); - - if (pageManager != null && !batch) - { - pageManager.updatePage(page); - } - } - - //requestContext.getPortalURL().getNavigationalState(). - resultMap.put(STATUS, status); - - if (requestedState != null) - { - resultMap.put(OLD_WINDOW_STATE, oldState); - resultMap.put(WINDOW_STATE, requestedState); - } - - if (requestedMode != null) - { - resultMap.put(OLD_PORTLET_MODE, oldMode); - resultMap.put(PORTLET_MODE, requestedMode); - } + if (requestedState == null && requestedMode == null) { throw new Exception( + "portlet window state or mode not provided"); } + if (requestedState != null + && !isValidWindowState(requestedState)) { throw new Exception( + "portlet window state " + requestedState + + " is not supported"); } + if (requestedMode != null && !isValidPortletMode(requestedMode)) { throw new Exception( + "portlet mode " + requestedMode + " is not supported"); } + + String oldState = fragment.getState(); + String oldMode = fragment.getMode(); + + // Now Change the transient navigational state + MutableNavigationalState navState = (MutableNavigationalState) requestContext + .getPortalURL().getNavigationalState(); + PortletWindow portletWindow = windowAccessor + .getPortletWindow(fragment); + if (portletWindow != null) + { + oldState = navState.getState(portletWindow).toString(); + oldMode = navState.getMode(portletWindow).toString(); + if (requestedState != null) + { + navState.setState(portletWindow, new WindowState( + requestedState)); + } + if (requestedMode != null) + { + navState.setMode(portletWindow, new PortletMode( + requestedMode)); + } + navState.sync(requestContext); + } + + if (checkAccess(requestContext, JetspeedActions.EDIT)) + { + if (requestedState != null) + fragment.setState(requestedState); + if (requestedMode != null) fragment.setMode(requestedMode); + + if (pageManager != null && !batch) + { + pageManager.updatePage(page); + } + } + + // requestContext.getPortalURL().getNavigationalState(). + resultMap.put(STATUS, status); + + if (requestedState != null) + { + resultMap.put(OLD_WINDOW_STATE, oldState); + resultMap.put(WINDOW_STATE, requestedState); + } + + if (requestedMode != null) + { + resultMap.put(OLD_PORTLET_MODE, oldMode); + resultMap.put(PORTLET_MODE, requestedMode); + } } - } + } catch (Exception e) { // Log the exception @@ -283,23 +280,24 @@ return success; } - - // TODO: The validWindowStates and validPortletModes maps only contain - // internal (portal level) valid modes and states. - // *if* a pa defines a custom mode/state with a different name but - // mapped onto a internal (portal) mode/state - // *then* first the real internal mode/state needs to be retrieved from the - // targetted portlet its application: - // o.a.j.om.common.portlet.PortletApplication.getMappedMode(customMode) and - // o.a.j.om.common.portlet.PortletApplication.getMappedState(customState) - + + // TODO: The validWindowStates and validPortletModes maps only contain + // internal (portal level) valid modes and states. + // *if* a pa defines a custom mode/state with a different name but + // mapped onto a internal (portal) mode/state + // *then* first the real internal mode/state needs to be retrieved from the + // targetted portlet its application: + // o.a.j.om.common.portlet.PortletApplication.getMappedMode(customMode) and + // o.a.j.om.common.portlet.PortletApplication.getMappedState(customState) + protected boolean isValidWindowState(String windowState) { return this.validWindowStates.containsKey(windowState); } + protected boolean isValidPortletMode(String portletMode) { return this.validPortletModes.containsKey(portletMode); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/Constants.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/Constants.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/Constants.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,100 +17,179 @@ package org.apache.jetspeed.layout.impl; /** - * PortletPlacement implementation constants - * + * PortletPlacement implementation constants + * * @author David Gurney * @author David Sean Taylor * @version $Id: $ */ -public interface Constants +public interface Constants { - public static final String STATUS = "status"; - public static final String ACTION = "action"; + + public static final String STATUS = "status"; + + public static final String ACTION = "action"; + public static final String REASON = "reason"; - public static final String PORTLETID = "id"; + + public static final String PORTLETID = "id"; + public static final String FRAGMENTID = "id"; + public static final String PORTLETENTITY = "entity"; + public static final String LAYOUTID = "layoutid"; + public static final String WINDOW_STATE = "state"; + public static final String PORTLET_MODE = "mode"; + public static final String OLD_WINDOW_STATE = "oldState"; - public static final String OLD_PORTLET_MODE = "oldMode"; - public static final String OLDCOL = "oldcol"; - public static final String OLDROW = "oldrow"; - public static final String NEWCOL = "newcol"; - public static final String NEWROW = "newrow"; - public static final String COL = "col"; - public static final String ROW = "row"; + + public static final String OLD_PORTLET_MODE = "oldMode"; + + public static final String OLDCOL = "oldcol"; + + public static final String OLDROW = "oldrow"; + + public static final String NEWCOL = "newcol"; + + public static final String NEWROW = "newrow"; + + public static final String COL = "col"; + + public static final String ROW = "row"; + public static final String X = "x"; + public static final String Y = "y"; + public static final String Z = "z"; + public static final String WIDTH = "width"; + public static final String HEIGHT = "height"; + public static final String DESKTOP_EXTENDED = "jsdesktop"; + public static final String OLD_X = "oldx"; + public static final String OLD_Y = "oldy"; + public static final String OLD_Z = "oldz"; + public static final String OLD_WIDTH = "oldwidth"; + public static final String OLD_HEIGHT = "oldheight"; + public static final String OLD_DESKTOP_EXTENDED = "oldjsdesktop"; + public final static String SOURCE = "source"; + public final static String DESTINATION = "destination"; + public static final String FILTER = "filter"; + public static final String PORTLETS = "portlets"; + public static final String PAGES = "pages"; + public static final String PAGE = "page"; + public static final String PROFILED_PATH = "profiledPath"; + public static final String PAGE_QUALIFIED_CREATE_ON_EDIT = "pageQualifiedForCreateNewPageOnEdit"; + public static final String FOLDER = "folder"; + public static final String FOLDERS = "folders"; + public static final String SIZES = "sizes"; - public static final String RESOURCE_NAME = "name"; + + public static final String RESOURCE_NAME = "name"; + public static final String USERS = "users"; + public static final String GUESTUSERS = "guestusers"; + public static final String USERNAME = "username"; + public static final String USERINFO = "userinfo"; + public static final String USER_IS_ANONYMOUS = "userIsAnonymous"; + public static final String ROLES = "roles"; + public static final String SESSIONS = "sessions"; + public static final String IPADDRESS = "ipaddress"; - + public static final String OFFLINE = "offline"; + public static final String ONLINE = "online"; - + public static final String STANDARD_MENUS = "standardMenus"; + public static final String CUSTOM_MENUS = "customMenus"; + public static final String MENU_DEFINITIONS = "menuDefinitions"; + public static final String INCLUDE_MENU_DEFS = "includeMenuDefs"; + public static final String MENU = "menu"; + public static final String MENU_NAME = "name"; + public static final String MENU_CONTEXT = "menuContext"; + public static final String MENU_LOCALE = "menuLocale"; public static final String PAGE_DECORATIONS = "pageDecorations"; + public static final String PORTLET_DECORATIONS = "portletDecorations"; + public static final String DESKTOP_PAGE_DECORATIONS = "desktopPageDecorations"; + public static final String DESKTOP_PORTLET_DECORATIONS = "desktopPortletDecorations"; + public static final String LAYOUTS = "layouts"; + public static final String LAYOUT = "layout"; + public static final String DEFAULT_LAYOUT = "defaultLayout"; + public static final String TITLE = "title"; - public static final String SHORT_TITLE = "short-title"; + + public static final String SHORT_TITLE = "short-title"; + public static final String LINK = "link"; + public static final String LINKS = "links"; + public static final String FRAGMENTS = "fragments"; + public static final String TYPE = "type"; + public static final String FORMAT = "format"; + public static final String METADATA = "metadata"; + public static final String SECURITY_REFS = "securityRefs"; + public static final String SECURITY_DEFS = "securityDefs"; + public static final String SECURITY_OWNER = "securityOwner"; - - // Move types - public static final int ABS = 1; - public static final int UP = 2; - public static final int DOWN = 3; - public static final int LEFT = 4; - public static final int RIGHT = 5; - public static final int CARTESIAN = 6; + + // Move types + public static final int ABS = 1; + + public static final int UP = 2; + + public static final int DOWN = 3; + + public static final int LEFT = 4; + + public static final int RIGHT = 5; + + public static final int CARTESIAN = 6; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/ExportJetspeedSchema.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/ExportJetspeedSchema.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/ExportJetspeedSchema.java 2008-05-16 01:54:54 UTC (rev 940) @@ -51,11 +51,17 @@ // categories of export private static final String USERS = "users"; + private static final String GROUPS = "groups"; + private static final String ROLES = "roles"; + private static final String PERMISSIONS = "permissions"; + private static final String PROFILES = "profiles"; + private static final String CAPABILITIES = "capabilities"; + private static final String PREFS = "prefs"; String pathSeprator = System.getProperty("file.separator"); @@ -63,8 +69,7 @@ public ExportJetspeedSchema(String template, String errorTemplate, PageManager pageManager, PortletActionSecurityBehavior securityBehavior, - JetspeedSerializerFactory serializerFactory, - String dir) + JetspeedSerializerFactory serializerFactory, String dir) { super(template, errorTemplate, pageManager, securityBehavior); this.serializerFactory = serializerFactory; @@ -88,23 +93,33 @@ resultMap.put(REASON, "Insufficient access to get portlets"); return success; } - boolean processPrefs = getNonNullActionParameter(requestContext, PREFS).equalsIgnoreCase("y") ? true : false; + boolean processPrefs = getNonNullActionParameter(requestContext, + PREFS).equalsIgnoreCase("y") ? true : false; if (!processPrefs) { - settings.put(JetspeedSerializer.KEY_PROCESS_USERS, - getNonNullActionParameter(requestContext, USERS).equalsIgnoreCase("y") ? Boolean.TRUE : Boolean.FALSE); - settings.put(JetspeedSerializer.KEY_PROCESS_PERMISSIONS, - getNonNullActionParameter(requestContext, PERMISSIONS).equalsIgnoreCase("y") ? Boolean.TRUE : Boolean.FALSE); - settings.put(JetspeedSerializer.KEY_PROCESS_PROFILER, - getNonNullActionParameter(requestContext, PROFILES).equalsIgnoreCase("y") ? Boolean.TRUE : Boolean.FALSE); - settings.put(JetspeedSerializer.KEY_PROCESS_CAPABILITIES, - getNonNullActionParameter(requestContext, CAPABILITIES).equalsIgnoreCase("y") ? Boolean.TRUE : Boolean.FALSE); + settings.put(JetspeedSerializer.KEY_PROCESS_USERS, + getNonNullActionParameter(requestContext, USERS) + .equalsIgnoreCase("y") ? Boolean.TRUE + : Boolean.FALSE); + settings.put(JetspeedSerializer.KEY_PROCESS_PERMISSIONS, + getNonNullActionParameter(requestContext, PERMISSIONS) + .equalsIgnoreCase("y") ? Boolean.TRUE + : Boolean.FALSE); + settings.put(JetspeedSerializer.KEY_PROCESS_PROFILER, + getNonNullActionParameter(requestContext, PROFILES) + .equalsIgnoreCase("y") ? Boolean.TRUE + : Boolean.FALSE); + settings.put(JetspeedSerializer.KEY_PROCESS_CAPABILITIES, + getNonNullActionParameter(requestContext, CAPABILITIES) + .equalsIgnoreCase("y") ? Boolean.TRUE + : Boolean.FALSE); } else { - settings.put(JetspeedSerializer.KEY_PROCESS_PREFERENCES, Boolean.TRUE); + settings.put(JetspeedSerializer.KEY_PROCESS_PREFERENCES, + Boolean.TRUE); } - if (!cleanUserFolder(userName)) + if (!cleanUserFolder(userName)) { resultMap.put(STATUS, "failure"); resultMap.put(REASON, "Could not create temp files on disk."); @@ -117,16 +132,22 @@ Boolean.FALSE); JetspeedSerializer serializer = null; if (processPrefs) - serializer = serializerFactory.create(JetspeedSerializerFactory.SECONDARY); + serializer = serializerFactory + .create(JetspeedSerializerFactory.SECONDARY); else - serializer = serializerFactory.create(JetspeedSerializerFactory.PRIMARY); + serializer = serializerFactory + .create(JetspeedSerializerFactory.PRIMARY); serializer.setDefaultIndent("\t"); - serializer.exportData("jetspeedadmin_export_process", exportFileName, settings); - requestContext.getRequest().getSession().setAttribute("file", userName + "_ldapExport.xml"); - resultMap.put("link", getDownloadLink(requestContext, "tmpExport.xml", userName)); + serializer.exportData("jetspeedadmin_export_process", + exportFileName, settings); + requestContext.getRequest().getSession().setAttribute("file", + userName + "_ldapExport.xml"); + resultMap.put("link", getDownloadLink(requestContext, + "tmpExport.xml", userName)); resultMap.put(STATUS, status); - } catch (Exception e) + } + catch (Exception e) { // Log the exception e.printStackTrace(); @@ -178,7 +199,8 @@ if (files[i].isDirectory()) { deleteDir(files[i]); - } else + } + else { files[i].delete(); } @@ -194,7 +216,8 @@ if (fullPath) { return userName + pathSeprator; - } else + } + else { return pageRoot + pathSeprator + userName; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/ExportObject.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/ExportObject.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/ExportObject.java 2008-05-16 01:54:54 UTC (rev 940) @@ -36,275 +36,360 @@ import org.apache.jetspeed.om.page.Page; import org.apache.jetspeed.page.PageManager; import org.apache.jetspeed.request.RequestContext; + /** * Exporting the object using Ajax command * * @author Vivek Kumar * @version $Id$ */ -public class ExportObject extends BaseGetResourceAction implements AjaxAction, AjaxBuilder, Constants { - protected Log log = LogFactory.getLog(GetFolderAction.class); +public class ExportObject extends BaseGetResourceAction implements AjaxAction, + AjaxBuilder, Constants +{ - protected PageManager castorPageManager; + protected Log log = LogFactory.getLog(GetFolderAction.class); - protected String pageRoot; + protected PageManager castorPageManager; - private static final String OBJECT_NAME = "objName"; + protected String pageRoot; - private static final String OBJECT_TYPE = "objType"; + private static final String OBJECT_NAME = "objName"; - private static final String OBJECT_PATH = "objPath"; + private static final String OBJECT_TYPE = "objType"; - private static final String RECURSIVE = "exptRecusive"; - String pathSeprator = System.getProperty("file.separator"); - public ExportObject(String template, String errorTemplate, PageManager pageManager, - PortletActionSecurityBehavior securityBehavior, PageManager castorpagemanager, String dir) { - super(template, errorTemplate, pageManager, securityBehavior); - this.castorPageManager = castorpagemanager; - this.pageRoot = dir; - } + private static final String OBJECT_PATH = "objPath"; - public boolean run(RequestContext requestContext, Map resultMap) { - boolean success = true; - String status = "success"; - String userName = requestContext.getUserPrincipal().toString(); - try { - resultMap.put(ACTION, "export"); - if (false == checkAccess(requestContext, JetspeedActions.VIEW)) { - success = false; - resultMap.put(REASON, "Insufficient access to get portlets"); - return success; - } - String objectName = getActionParameter(requestContext, OBJECT_NAME); - String objectType = getActionParameter(requestContext, OBJECT_TYPE); - String objectPath = getActionParameter(requestContext, OBJECT_PATH); - String recursive = getActionParameter(requestContext, RECURSIVE); - boolean isRecursive = recursive != null && recursive.equals("1") ? true : false; + private static final String RECURSIVE = "exptRecusive"; - if (!cleanUserFolder(userName)) - success = false; - if (success) { - if (objectType.equalsIgnoreCase("folder")) { - Folder folder = pageManager.getFolder(objectPath); - if (isRecursive) { - importFolder(folder,userName,getRealPath(folder.getPath())); - } else { - Folder destFolder = castorPageManager.copyFolder(folder, getUserFolder(userName, true) - + objectName); - castorPageManager.updateFolder(destFolder); - } - } else if (objectType.equalsIgnoreCase("page")) { - objectPath = getParentPath(objectPath); - Folder folder = pageManager.getFolder(objectPath); - Page page = folder.getPage(objectName); - Page destPage = castorPageManager.copyPage(page, getUserFolder(userName, true) + objectName); - castorPageManager.updatePage(destPage); - } else if (objectType.equalsIgnoreCase("link")) { - objectPath = getParentPath(objectPath); - Folder folder = pageManager.getFolder(objectPath); - Link link = folder.getLink(objectName); - Link destLink = castorPageManager.copyLink(link, getUserFolder(userName, true) + objectName); - castorPageManager.updateLink(destLink); - } - String link = userName + "_" + objectName; - if (objectType.equalsIgnoreCase("folder")) link = userName + ".zip"; - requestContext.getRequest().getSession().setAttribute("file", link); - resultMap.put("link", getDownloadLink(requestContext, objectName, userName, objectType)); - } - if (!success) - status = "failure"; + String pathSeprator = System.getProperty("file.separator"); - resultMap.put(STATUS, status); - } catch (Exception e) { - // Log the exception - e.printStackTrace(); - log.error("exception while getting folder info", e); + public ExportObject(String template, String errorTemplate, + PageManager pageManager, + PortletActionSecurityBehavior securityBehavior, + PageManager castorpagemanager, String dir) + { + super(template, errorTemplate, pageManager, securityBehavior); + this.castorPageManager = castorpagemanager; + this.pageRoot = dir; + } - // Return a failure indicator - success = false; - } + public boolean run(RequestContext requestContext, Map resultMap) + { + boolean success = true; + String status = "success"; + String userName = requestContext.getUserPrincipal().toString(); + try + { + resultMap.put(ACTION, "export"); + if (false == checkAccess(requestContext, JetspeedActions.VIEW)) + { + success = false; + resultMap.put(REASON, "Insufficient access to get portlets"); + return success; + } + String objectName = getActionParameter(requestContext, OBJECT_NAME); + String objectType = getActionParameter(requestContext, OBJECT_TYPE); + String objectPath = getActionParameter(requestContext, OBJECT_PATH); + String recursive = getActionParameter(requestContext, RECURSIVE); + boolean isRecursive = recursive != null && recursive.equals("1") ? true + : false; - return success; - } + if (!cleanUserFolder(userName)) success = false; + if (success) + { + if (objectType.equalsIgnoreCase("folder")) + { + Folder folder = pageManager.getFolder(objectPath); + if (isRecursive) + { + importFolder(folder, userName, getRealPath(folder + .getPath())); + } + else + { + Folder destFolder = castorPageManager.copyFolder( + folder, getUserFolder(userName, true) + + objectName); + castorPageManager.updateFolder(destFolder); + } + } + else if (objectType.equalsIgnoreCase("page")) + { + objectPath = getParentPath(objectPath); + Folder folder = pageManager.getFolder(objectPath); + Page page = folder.getPage(objectName); + Page destPage = castorPageManager.copyPage(page, + getUserFolder(userName, true) + objectName); + castorPageManager.updatePage(destPage); + } + else if (objectType.equalsIgnoreCase("link")) + { + objectPath = getParentPath(objectPath); + Folder folder = pageManager.getFolder(objectPath); + Link link = folder.getLink(objectName); + Link destLink = castorPageManager.copyLink(link, + getUserFolder(userName, true) + objectName); + castorPageManager.updateLink(destLink); + } + String link = userName + "_" + objectName; + if (objectType.equalsIgnoreCase("folder")) + link = userName + ".zip"; + requestContext.getRequest().getSession().setAttribute("file", + link); + resultMap.put("link", getDownloadLink(requestContext, + objectName, userName, objectType)); + } + if (!success) status = "failure"; - private String getDownloadLink(RequestContext requestContext, String ObjectName, String userName, String objectType) - throws Exception { - String link = ""; - String basePath = requestContext.getRequest().getContextPath() + "/fileserver/_content/"; - if (objectType.equalsIgnoreCase("folder")) { - String sourcePath = getUserFolder(userName, false); - String target = sourcePath + ".zip"; - boolean success = zipObject(sourcePath, target); - if (!success) - throw new Exception("Error Occurered in zipping the file"); + resultMap.put(STATUS, status); + } + catch (Exception e) + { + // Log the exception + e.printStackTrace(); + log.error("exception while getting folder info", e); - link = basePath + ObjectName+".zip"; - } else { - link = basePath + userName + "/" + ObjectName; - } - return link; - } + // Return a failure indicator + success = false; + } - private boolean cleanUserFolder(String userName) { - boolean success = false; - synchronized (this) { - String folder = getUserFolder(userName, false); - File dir = new File(pageRoot+pathSeprator+userName+".zip"); - if(dir.exists()) dir.delete(); - - dir = new File(folder); - if (dir.exists()) { + return success; + } + + private String getDownloadLink(RequestContext requestContext, + String ObjectName, String userName, String objectType) + throws Exception + { + String link = ""; + String basePath = requestContext.getRequest().getContextPath() + + "/fileserver/_content/"; + if (objectType.equalsIgnoreCase("folder")) + { + String sourcePath = getUserFolder(userName, false); + String target = sourcePath + ".zip"; + boolean success = zipObject(sourcePath, target); + if (!success) + throw new Exception("Error Occurered in zipping the file"); + + link = basePath + ObjectName + ".zip"; + } + else + { + link = basePath + userName + "/" + ObjectName; + } + return link; + } + + private boolean cleanUserFolder(String userName) + { + boolean success = false; + synchronized (this) + { + String folder = getUserFolder(userName, false); + File dir = new File(pageRoot + pathSeprator + userName + ".zip"); + if (dir.exists()) dir.delete(); + + dir = new File(folder); + if (dir.exists()) + { success = deleteDir(dir); - } + } success = dir.mkdir(); - } - return success; - } + } + return success; + } - private boolean deleteDir(File dir) { - if( dir.exists() ) { + private boolean deleteDir(File dir) + { + if (dir.exists()) + { File[] files = dir.listFiles(); - for(int i=0; i0) + private Folder lookupFolder(String path) + { + try { - return path.substring(index); + return castorPageManager.getFolder(path); } + catch (Exception e) + { + return null; + } + } + + private String getRealPath(String path) + { + int index = path.lastIndexOf("/"); + if (index > 0) { return path.substring(index); } return path; - + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetFolderAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetFolderAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetFolderAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,23 +30,21 @@ /** * Retrieve a single page - * - * AJAX Parameters: - * folder = the path of the folder to retrieve information on - * + * + * AJAX Parameters: folder = the path of the folder to retrieve information on + * * @author David Sean Taylor * @version $Id: $ */ -public class GetFolderAction - extends BaseGetResourceAction - implements AjaxAction, AjaxBuilder, Constants +public class GetFolderAction extends BaseGetResourceAction implements + AjaxAction, AjaxBuilder, Constants { + protected Log log = LogFactory.getLog(GetFolderAction.class); - - public GetFolderAction(String template, - String errorTemplate, - PageManager pageManager, - PortletActionSecurityBehavior securityBehavior) + + public GetFolderAction(String template, String errorTemplate, + PageManager pageManager, + PortletActionSecurityBehavior securityBehavior) { super(template, errorTemplate, pageManager, securityBehavior); } @@ -60,15 +58,15 @@ resultMap.put(ACTION, "getfolder"); if (false == checkAccess(requestContext, JetspeedActions.VIEW)) { - success = false; - resultMap.put(REASON, "Insufficient access to get portlets"); - return success; - } - Folder folder = retrieveFolder(requestContext); + success = false; + resultMap.put(REASON, "Insufficient access to get portlets"); + return success; + } + Folder folder = retrieveFolder(requestContext); resultMap.put(STATUS, status); resultMap.put(FOLDER, folder); putSecurityInformation(resultMap, folder); - } + } catch (Exception e) { // Log the exception @@ -79,11 +77,11 @@ } return success; - } - + } + protected Folder retrieveFolder(RequestContext requestContext) - throws Exception - { + throws Exception + { String folderName = getActionParameter(requestContext, FOLDER); if (folderName == null) { @@ -92,6 +90,5 @@ Folder folder = pageManager.getFolder(folderName); return folder; } - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetFolderListAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetFolderListAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetFolderListAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,26 +30,24 @@ import org.apache.jetspeed.request.RequestContext; /** - * Get the immediate contents of a folder in JSON format - * - * AJAX Parameters: - * folder: full path to the folder - * + * Get the immediate contents of a folder in JSON format + * + * AJAX Parameters: folder: full path to the folder + * * @author David Sean Taylor * @version $Id: $ */ -public class GetFolderListAction - extends BaseGetResourceAction - implements AjaxAction, AjaxBuilder, Constants +public class GetFolderListAction extends BaseGetResourceAction implements + AjaxAction, AjaxBuilder, Constants { + protected Log log = LogFactory.getLog(GetThemesAction.class); - - public GetFolderListAction(String template, - String errorTemplate, + + public GetFolderListAction(String template, String errorTemplate, PageManager pageManager, PortletActionSecurityBehavior securityBehavior) { - super(template, errorTemplate, pageManager, securityBehavior); + super(template, errorTemplate, pageManager, securityBehavior); } public boolean run(RequestContext requestContext, Map resultMap) @@ -61,13 +59,13 @@ resultMap.put(ACTION, "getfolderlist"); if (false == checkAccess(requestContext, JetspeedActions.VIEW)) { - success = false; - resultMap.put(REASON, "Insufficient access to get folderlist"); - return success; - } + success = false; + resultMap.put(REASON, "Insufficient access to get folderlist"); + return success; + } String data = getActionParameter(requestContext, "data"); StringTokenizer tokenizer = new StringTokenizer(data, "[{:\""); - String folderName = null; + String folderName = null; while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); @@ -78,13 +76,12 @@ } } String format = getActionParameter(requestContext, FORMAT); - if (format == null) - format = "json"; + if (format == null) format = "json"; if (folderName == null) { success = false; resultMap.put(REASON, "Folder name not found."); - return success; + return success; } resultMap.put(FORMAT, format); Folder folder = pageManager.getFolder(folderName); @@ -92,8 +89,8 @@ resultMap.put("folders", folder.getFolders().iterator()); resultMap.put("pages", folder.getPages().iterator()); resultMap.put("links", folder.getLinks().iterator()); - resultMap.put(STATUS, status); - } + resultMap.put(STATUS, status); + } catch (Exception e) { // Log the exception @@ -104,6 +101,5 @@ return success; } - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetFoldersListAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetFoldersListAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetFoldersListAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,27 +29,25 @@ import org.apache.jetspeed.request.RequestContext; /** - * Get the immediate contents of a folder in Ajax Format - * + * Get the immediate contents of a folder in Ajax Format + * * @author Vivek Kumar - * @author Vivek Kumar - * AJAX Parameters: - * folder: full path to the folder - * + * @author Vivek Kumar AJAX + * Parameters: folder: full path to the folder + * * @version $Id: $ */ -public class GetFoldersListAction - extends BaseGetResourceAction - implements AjaxAction, AjaxBuilder, Constants +public class GetFoldersListAction extends BaseGetResourceAction implements + AjaxAction, AjaxBuilder, Constants { + protected Log log = LogFactory.getLog(GetThemesAction.class); - - public GetFoldersListAction(String template, - String errorTemplate, + + public GetFoldersListAction(String template, String errorTemplate, PageManager pageManager, PortletActionSecurityBehavior securityBehavior) { - super(template, errorTemplate, pageManager, securityBehavior); + super(template, errorTemplate, pageManager, securityBehavior); } public boolean run(RequestContext requestContext, Map resultMap) @@ -61,23 +59,23 @@ resultMap.put(ACTION, "getfolderlist"); if (false == checkAccess(requestContext, JetspeedActions.VIEW)) { - success = false; - resultMap.put(REASON, "Insufficient access to get folderlist"); - return success; - } - String folderName = getActionParameter(requestContext, "data"); + success = false; + resultMap.put(REASON, "Insufficient access to get folderlist"); + return success; + } + String folderName = getActionParameter(requestContext, "data"); if (folderName == null) { success = false; resultMap.put(REASON, "Folder name not found."); - return success; + return success; } Folder folder = pageManager.getFolder(folderName); resultMap.put("folders", folder.getFolders().iterator()); resultMap.put("pages", folder.getPages().iterator()); resultMap.put("links", folder.getLinks().iterator()); - resultMap.put(STATUS, status); - } + resultMap.put(STATUS, status); + } catch (Exception e) { // Log the exception @@ -88,6 +86,5 @@ return success; } - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetLinkAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetLinkAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetLinkAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,23 +30,21 @@ /** * Retrieve a single link - * - * AJAX Parameters: - * link = the path of the link to retrieve information on - * + * + * AJAX Parameters: link = the path of the link to retrieve information on + * * @author David Sean Taylor * @version $Id: $ */ -public class GetLinkAction - extends BaseGetResourceAction - implements AjaxAction, AjaxBuilder, Constants +public class GetLinkAction extends BaseGetResourceAction implements AjaxAction, + AjaxBuilder, Constants { + protected Log log = LogFactory.getLog(GetLinkAction.class); - - public GetLinkAction(String template, - String errorTemplate, - PageManager pageManager, - PortletActionSecurityBehavior securityBehavior) + + public GetLinkAction(String template, String errorTemplate, + PageManager pageManager, + PortletActionSecurityBehavior securityBehavior) { super(template, errorTemplate, pageManager, securityBehavior); } @@ -60,16 +58,16 @@ resultMap.put(ACTION, "getlink"); if (false == checkAccess(requestContext, JetspeedActions.VIEW)) { - success = false; - resultMap.put(REASON, "Insufficient access to get link"); - return success; - } - Link link = retrieveLink(requestContext); - resultMap.put(STATUS, status); + success = false; + resultMap.put(REASON, "Insufficient access to get link"); + return success; + } + Link link = retrieveLink(requestContext); + resultMap.put(STATUS, status); resultMap.put(LINK, link); // resultMap.put(METADATA, link.getMetadata().getFields()); - putSecurityInformation(resultMap, link); - } + putSecurityInformation(resultMap, link); + } catch (Exception e) { // Log the exception @@ -80,11 +78,10 @@ } return success; - } - - protected Link retrieveLink(RequestContext requestContext) - throws Exception - { + } + + protected Link retrieveLink(RequestContext requestContext) throws Exception + { String linkName = getActionParameter(requestContext, LINK); if (linkName == null) { @@ -92,5 +89,5 @@ } Link link = pageManager.getLink(linkName); return link; - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetMenuAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetMenuAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetMenuAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,21 +33,20 @@ /** * Get menu action retrieves a menu defined for the addressed page. - * - * AJAX Parameters: - * menu = the name of the menu definition to retrieve - * + * + * AJAX Parameters: menu = the name of the menu definition to retrieve + * * @author Randy Watler * @version $Id: $ */ -public class GetMenuAction extends BasePortletAction - implements AjaxAction, AjaxBuilder, Constants +public class GetMenuAction extends BasePortletAction implements AjaxAction, + AjaxBuilder, Constants { + protected static final Log log = LogFactory.getLog(GetMenusAction.class); - - public GetMenuAction(String template, - String errorTemplate, - PortletActionSecurityBehavior securityBehavior) + + public GetMenuAction(String template, String errorTemplate, + PortletActionSecurityBehavior securityBehavior) { super(template, errorTemplate, securityBehavior); } @@ -74,16 +73,20 @@ if (menuName == null) { success = false; - resultMap.put(REASON, "Missing required '" + MENU_NAME + "' parameter"); + resultMap.put(REASON, "Missing required '" + MENU_NAME + + "' parameter"); return success; } // get request context - PortalSiteRequestContext siteRequestContext = (PortalSiteRequestContext)requestContext.getAttribute(ProfilerValveImpl.PORTAL_SITE_REQUEST_CONTEXT_ATTR_KEY); + PortalSiteRequestContext siteRequestContext = (PortalSiteRequestContext) requestContext + .getAttribute(ProfilerValveImpl.PORTAL_SITE_REQUEST_CONTEXT_ATTR_KEY); if (siteRequestContext == null) { success = false; - resultMap.put(REASON, "Missing portal site request context from ProfilerValve"); + resultMap + .put(REASON, + "Missing portal site request context from ProfilerValve"); return success; } @@ -102,7 +105,8 @@ if (menuDefinition == null) { success = false; - resultMap.put(REASON, "Unable to lookup specified menu for page"); + resultMap.put(REASON, + "Unable to lookup specified menu for page"); return success; } @@ -119,5 +123,5 @@ } return success; - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetMenusAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetMenusAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetMenusAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,11 +16,11 @@ */ package org.apache.jetspeed.layout.impl; +import java.util.HashMap; +import java.util.Iterator; import java.util.Locale; import java.util.Map; -import java.util.HashMap; import java.util.Set; -import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -36,21 +36,20 @@ /** * Get menus action retrieves all menu names defined for the addressed page. - * - * AJAX Parameters: - * none - * + * + * AJAX Parameters: none + * * @author Randy Watler * @version $Id: $ */ -public class GetMenusAction extends BasePortletAction - implements AjaxAction, AjaxBuilder, Constants +public class GetMenusAction extends BasePortletAction implements AjaxAction, + AjaxBuilder, Constants { + protected static final Log log = LogFactory.getLog(GetMenusAction.class); - - public GetMenusAction(String template, - String errorTemplate, - PortletActionSecurityBehavior securityBehavior) + + public GetMenusAction(String template, String errorTemplate, + PortletActionSecurityBehavior securityBehavior) { super(template, errorTemplate, securityBehavior); } @@ -73,11 +72,14 @@ } // get request context - PortalSiteRequestContext siteRequestContext = (PortalSiteRequestContext)requestContext.getAttribute(ProfilerValveImpl.PORTAL_SITE_REQUEST_CONTEXT_ATTR_KEY); + PortalSiteRequestContext siteRequestContext = (PortalSiteRequestContext) requestContext + .getAttribute(ProfilerValveImpl.PORTAL_SITE_REQUEST_CONTEXT_ATTR_KEY); if (siteRequestContext == null) { success = false; - resultMap.put(REASON, "Missing portal site request context from ProfilerValve"); + resultMap + .put(REASON, + "Missing portal site request context from ProfilerValve"); return success; } @@ -91,52 +93,56 @@ catch (NodeNotFoundException nnfe) { } - + // return menu names action results resultMap.put(STANDARD_MENUS, standardMenuNames); resultMap.put(CUSTOM_MENUS, customMenuNames); - + // get action parameter - String includeMenuDefinitions = getActionParameter(requestContext, INCLUDE_MENU_DEFS); - if ( includeMenuDefinitions != null && includeMenuDefinitions.toLowerCase().equals( "true" ) ) + String includeMenuDefinitions = getActionParameter(requestContext, + INCLUDE_MENU_DEFS); + if (includeMenuDefinitions != null + && includeMenuDefinitions.toLowerCase().equals("true")) { // get request locale Locale locale = requestContext.getLocale(); - + HashMap menuDefinitionsMap = new HashMap(); - + StringBuffer failReason = new StringBuffer(); Iterator menuNamesIter = standardMenuNames.iterator(); - while ( menuNamesIter.hasNext() ) + while (menuNamesIter.hasNext()) { - String menuName = (String)menuNamesIter.next(); - Menu menuDefinition = getMenuDefinition( menuName, siteRequestContext, failReason ); - if ( menuDefinition != null ) - menuDefinitionsMap.put( menuName, menuDefinition ); + String menuName = (String) menuNamesIter.next(); + Menu menuDefinition = getMenuDefinition(menuName, + siteRequestContext, failReason); + if (menuDefinition != null) + menuDefinitionsMap.put(menuName, menuDefinition); } menuNamesIter = customMenuNames.iterator(); - while ( menuNamesIter.hasNext() ) + while (menuNamesIter.hasNext()) { - String menuName = (String)menuNamesIter.next(); - Menu menuDefinition = getMenuDefinition( menuName, siteRequestContext, failReason ); - if ( menuDefinition != null ) - menuDefinitionsMap.put( menuName, menuDefinition ); + String menuName = (String) menuNamesIter.next(); + Menu menuDefinition = getMenuDefinition(menuName, + siteRequestContext, failReason); + if (menuDefinition != null) + menuDefinitionsMap.put(menuName, menuDefinition); } - - if ( failReason.length() > 0 ) + + if (failReason.length() > 0) { success = false; - resultMap.put(REASON, failReason.toString() ); + resultMap.put(REASON, failReason.toString()); return success; } - resultMap.put( INCLUDE_MENU_DEFS, new Boolean( true ) ); - resultMap.put( MENU_DEFINITIONS, menuDefinitionsMap ); - resultMap.put( MENU_CONTEXT, siteRequestContext ); - resultMap.put( MENU_LOCALE, locale ); + resultMap.put(INCLUDE_MENU_DEFS, new Boolean(true)); + resultMap.put(MENU_DEFINITIONS, menuDefinitionsMap); + resultMap.put(MENU_CONTEXT, siteRequestContext); + resultMap.put(MENU_LOCALE, locale); } else { - resultMap.put( INCLUDE_MENU_DEFS, new Boolean( false ) ); + resultMap.put(INCLUDE_MENU_DEFS, new Boolean(false)); } resultMap.put(STATUS, status); } @@ -147,25 +153,27 @@ } return success; - } - - private Menu getMenuDefinition( String menuName, PortalSiteRequestContext siteRequestContext, StringBuffer failReason ) + } + + private Menu getMenuDefinition(String menuName, + PortalSiteRequestContext siteRequestContext, StringBuffer failReason) { // get menu definition Menu menuDefinition = null; try { - menuDefinition = siteRequestContext.getMenu( menuName ); + menuDefinition = siteRequestContext.getMenu(menuName); } - catch ( NodeNotFoundException nnfe ) + catch (NodeNotFoundException nnfe) { } - if ( menuDefinition == null && failReason != null ) + if (menuDefinition == null && failReason != null) { - if ( failReason.length() == 0 ) - failReason.append( "Unable to lookup specified menus: " ).append( menuName ); + if (failReason.length() == 0) + failReason.append("Unable to lookup specified menus: ").append( + menuName); else - failReason.append( ", " ).append( menuName ); + failReason.append(", ").append(menuName); } return menuDefinition; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPageAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPageAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPageAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -44,28 +44,27 @@ /** * Get Page retrieves a page from the Page Manager store and PSML format - * - * AJAX Parameters: - * page = the path and name of the page ("/_user/ronaldino/goals.psml") - * + * + * AJAX Parameters: page = the path and name of the page + * ("/_user/ronaldino/goals.psml") + * * @author David Sean Taylor * @version $Id: $ */ -public class GetPageAction - extends BaseGetResourceAction - implements AjaxAction, AjaxBuilder, Constants +public class GetPageAction extends BaseGetResourceAction implements AjaxAction, + AjaxBuilder, Constants { - protected Log log = LogFactory.getLog( GetPageAction.class ); - + + protected Log log = LogFactory.getLog(GetPageAction.class); + private PortletRegistry registry; + private DecorationValve decorationValve; - - public GetPageAction( String template, - String errorTemplate, - PageManager pageManager, - PortletActionSecurityBehavior securityBehavior, - PortletRegistry registry, - DecorationValve decorationValve ) + + public GetPageAction(String template, String errorTemplate, + PageManager pageManager, + PortletActionSecurityBehavior securityBehavior, + PortletRegistry registry, DecorationValve decorationValve) { super(template, errorTemplate, pageManager, securityBehavior); this.registry = registry; @@ -78,193 +77,207 @@ String status = "success"; try { - resultMap.put( ACTION, "getpage" ); - if ( false == checkAccess( requestContext, JetspeedActions.VIEW ) ) + resultMap.put(ACTION, "getpage"); + if (false == checkAccess(requestContext, JetspeedActions.VIEW)) { - resultMap.put( REASON, "Insufficient access to view page" ); + resultMap.put(REASON, "Insufficient access to view page"); success = false; return success; - } - + } + // Run the Decoration valve to get actions - decorationValve.invoke( requestContext, null ); - + decorationValve.invoke(requestContext, null); + Page page = requestContext.getPage(); - String pageName = getActionParameter( requestContext, PAGE ); - if ( pageName != null ) + String pageName = getActionParameter(requestContext, PAGE); + if (pageName != null) { - page = retrievePage( requestContext, pageName ); + page = retrievePage(requestContext, pageName); } - resultMap.put( STATUS, status ); - resultMap.put( PAGE, page ); - - Theme theme = (Theme)requestContext.getAttribute( PortalReservedParameters.PAGE_THEME_ATTRIBUTE ); + resultMap.put(STATUS, status); + resultMap.put(PAGE, page); + + Theme theme = (Theme) requestContext + .getAttribute(PortalReservedParameters.PAGE_THEME_ATTRIBUTE); String pageDecoratorName = null; - if ( theme != null ) + if (theme != null) { pageDecoratorName = theme.getPageLayoutDecoration().getName(); } else { - pageDecoratorName = page.getDefaultDecorator( LAYOUT ); + pageDecoratorName = page.getDefaultDecorator(LAYOUT); } - if ( pageDecoratorName != null ) - resultMap.put( DEFAULT_LAYOUT, pageDecoratorName ); - - PortalSiteRequestContext siteRequestContext = (PortalSiteRequestContext)requestContext.getAttribute( ProfilerValveImpl.PORTAL_SITE_REQUEST_CONTEXT_ATTR_KEY ); - if ( siteRequestContext == null ) + if (pageDecoratorName != null) + resultMap.put(DEFAULT_LAYOUT, pageDecoratorName); + + PortalSiteRequestContext siteRequestContext = (PortalSiteRequestContext) requestContext + .getAttribute(ProfilerValveImpl.PORTAL_SITE_REQUEST_CONTEXT_ATTR_KEY); + if (siteRequestContext == null) { success = false; - resultMap.put( REASON, "Missing portal site request context from ProfilerValve" ); + resultMap + .put(REASON, + "Missing portal site request context from ProfilerValve"); return success; } - + String profiledPath = siteRequestContext.getPage().getPath(); - resultMap.put( PROFILED_PATH, profiledPath ); - putSecurityInformation( resultMap, page ); - - PageActionAccess pageActionAccess = (PageActionAccess)requestContext.getAttribute( PortalReservedParameters.PAGE_EDIT_ACCESS_ATTRIBUTE ); + resultMap.put(PROFILED_PATH, profiledPath); + putSecurityInformation(resultMap, page); + + PageActionAccess pageActionAccess = (PageActionAccess) requestContext + .getAttribute(PortalReservedParameters.PAGE_EDIT_ACCESS_ATTRIBUTE); Boolean userIsAnonymous = Boolean.TRUE; - if ( pageActionAccess != null ) - userIsAnonymous = new Boolean( pageActionAccess.isAnonymous() ); - resultMap.put( USER_IS_ANONYMOUS, userIsAnonymous.toString() ); - + if (pageActionAccess != null) + userIsAnonymous = new Boolean(pageActionAccess.isAnonymous()); + resultMap.put(USER_IS_ANONYMOUS, userIsAnonymous.toString()); + Boolean isPageQualifiedForCreateNewPageOnEdit = Boolean.FALSE; - if ( ! userIsAnonymous.booleanValue() ) - isPageQualifiedForCreateNewPageOnEdit = new Boolean( isPageQualifiedForCreateNewPageOnEdit( requestContext ) ); - resultMap.put( PAGE_QUALIFIED_CREATE_ON_EDIT, isPageQualifiedForCreateNewPageOnEdit.toString() ); - - String fragments = getActionParameter( requestContext, FRAGMENTS ); - if ( fragments == null ) + if (!userIsAnonymous.booleanValue()) + isPageQualifiedForCreateNewPageOnEdit = new Boolean( + isPageQualifiedForCreateNewPageOnEdit(requestContext)); + resultMap.put(PAGE_QUALIFIED_CREATE_ON_EDIT, + isPageQualifiedForCreateNewPageOnEdit.toString()); + + String fragments = getActionParameter(requestContext, FRAGMENTS); + if (fragments == null) { - resultMap.put( FRAGMENTS, "true" ); + resultMap.put(FRAGMENTS, "true"); } else { - if ( fragments.equalsIgnoreCase( "true" ) ) + if (fragments.equalsIgnoreCase("true")) { - resultMap.put( FRAGMENTS, "true" ); + resultMap.put(FRAGMENTS, "true"); } else { - resultMap.put( FRAGMENTS, "false" ); + resultMap.put(FRAGMENTS, "false"); return success; } } - + Map fragSizes = new HashMap(); Map portletIcons = new HashMap(); - - String singleLayoutId = getActionParameter( requestContext, LAYOUTID ); - if ( singleLayoutId != null ) - { // build page representation with single layout - Fragment currentLayoutFragment = page.getFragmentById( singleLayoutId ); - if ( currentLayoutFragment == null ) - { - throw new Exception( "layout id not found: " + singleLayoutId ); - } + + String singleLayoutId = getActionParameter(requestContext, LAYOUTID); + if (singleLayoutId != null) + { // build page representation with single layout + Fragment currentLayoutFragment = page + .getFragmentById(singleLayoutId); + if (currentLayoutFragment == null) { throw new Exception( + "layout id not found: " + singleLayoutId); } Fragment currentPortletFragment = null; - - String singlePortletId = getActionParameter( requestContext, PORTLETENTITY ); - if ( singlePortletId != null ) + + String singlePortletId = getActionParameter(requestContext, + PORTLETENTITY); + if (singlePortletId != null) { - Iterator layoutChildIter = currentLayoutFragment.getFragments().iterator(); - while ( layoutChildIter.hasNext() ) + Iterator layoutChildIter = currentLayoutFragment + .getFragments().iterator(); + while (layoutChildIter.hasNext()) { - Fragment childFrag = (Fragment)layoutChildIter.next(); - if ( childFrag != null ) + Fragment childFrag = (Fragment) layoutChildIter.next(); + if (childFrag != null) { - if ( singlePortletId.equals( childFrag.getId() ) ) + if (singlePortletId.equals(childFrag.getId())) { currentPortletFragment = childFrag; break; } } } - if ( currentPortletFragment == null ) - { - throw new Exception( "portlet id " + singlePortletId + " not found in layout " + singleLayoutId ); - } - resultMap.put( "portletsingleId", currentPortletFragment.getId() ); + if (currentPortletFragment == null) { throw new Exception( + "portlet id " + singlePortletId + + " not found in layout " + singleLayoutId); } + resultMap.put("portletsingleId", currentPortletFragment + .getId()); } - - retrieveFragmentSpecialProperties( requestContext, currentLayoutFragment, fragSizes, portletIcons ); - resultMap.put( "layoutsingle", currentLayoutFragment ); + + retrieveFragmentSpecialProperties(requestContext, + currentLayoutFragment, fragSizes, portletIcons); + resultMap.put("layoutsingle", currentLayoutFragment); } else { - retrieveFragmentSpecialProperties( requestContext, page.getRootFragment(), fragSizes, portletIcons ); + retrieveFragmentSpecialProperties(requestContext, page + .getRootFragment(), fragSizes, portletIcons); } - resultMap.put( SIZES, fragSizes ); - resultMap.put( "portletIcons", portletIcons ); + resultMap.put(SIZES, fragSizes); + resultMap.put("portletIcons", portletIcons); } - catch ( Exception e ) + catch (Exception e) { // Log the exception - log.error( "exception while getting page", e ); + log.error("exception while getting page", e); // Return a failure indicator success = false; } return success; - } - - protected Page retrievePage( RequestContext requestContext, String pageName ) - throws Exception - { - if ( pageName == null ) + } + + protected Page retrievePage(RequestContext requestContext, String pageName) + throws Exception + { + if (pageName == null) { pageName = "/"; } - Page page = pageManager.getPage( pageName ); + Page page = pageManager.getPage(pageName); return page; - } - - - protected void retrieveFragmentSpecialProperties( RequestContext requestContext, Fragment frag, Map fragSizes, Map portletIcons ) + } + + protected void retrieveFragmentSpecialProperties( + RequestContext requestContext, Fragment frag, Map fragSizes, + Map portletIcons) { - if ( frag == null ) - { - return; + if (frag == null) { return; } + + if ("layout".equals(frag.getType())) + { // get layout fragment sizes + if (fragSizes != null) + PortletPlacementContextImpl.getColumnCountAndSizes(frag, + registry, fragSizes); + + List childFragments = frag.getFragments(); + if (childFragments != null) + { + Iterator childFragIter = childFragments.iterator(); + while (childFragIter.hasNext()) + { + Fragment childFrag = (Fragment) childFragIter.next(); + retrieveFragmentSpecialProperties(requestContext, + childFrag, fragSizes, portletIcons); + } + } } - - if ( "layout".equals( frag.getType() ) ) - { // get layout fragment sizes - if ( fragSizes != null ) - PortletPlacementContextImpl.getColumnCountAndSizes( frag, registry, fragSizes ); - - List childFragments = frag.getFragments(); - if ( childFragments != null ) - { - Iterator childFragIter = childFragments.iterator(); - while ( childFragIter.hasNext() ) - { - Fragment childFrag = (Fragment)childFragIter.next(); - retrieveFragmentSpecialProperties( requestContext, childFrag, fragSizes, portletIcons ); - } - } - } - else if ( portletIcons != null && "portlet".equals( frag.getType() ) ) - { // get portlet icon and locale specific portlet display name + else if (portletIcons != null && "portlet".equals(frag.getType())) + { // get portlet icon and locale specific portlet display name String portletName = frag.getName(); - if ( portletName != null && portletName.length() > 0 ) + if (portletName != null && portletName.length() > 0) { - PortletDefinition portletDef = registry.getPortletDefinitionByUniqueName( portletName ); - - if ( portletDef != null && portletIcons != null ) + PortletDefinition portletDef = registry + .getPortletDefinitionByUniqueName(portletName); + + if (portletDef != null && portletIcons != null) { ParameterSet paramSet = portletDef.getInitParameterSet(); - Parameter iconParam = paramSet.get( "portlet-icon" ); - String iconParamVal = ( iconParam == null ) ? null : iconParam.getValue(); - if ( iconParamVal != null && iconParamVal.length() > 0 ) + Parameter iconParam = paramSet.get("portlet-icon"); + String iconParamVal = (iconParam == null) ? null + : iconParam.getValue(); + if (iconParamVal != null && iconParamVal.length() > 0) { - portletIcons.put( frag.getId(), iconParamVal ); + portletIcons.put(frag.getId(), iconParamVal); } } - else if ( portletDef == null ) + else if (portletDef == null) { - log.error( "GetPageAction could not obtain PortletDefinition for portlet " + portletName ); + log + .error("GetPageAction could not obtain PortletDefinition for portlet " + + portletName); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPagesAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPagesAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPagesAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -36,23 +36,21 @@ /** * Get Pages retrieves all pages for the given folder - * - * AJAX Parameters: - * folder = the path of folder containing the pages - * + * + * AJAX Parameters: folder = the path of folder containing the pages + * * @author David Sean Taylor * @version $Id: $ */ -public class GetPagesAction - extends BasePortletAction - implements AjaxAction, AjaxBuilder, Constants, Comparator +public class GetPagesAction extends BasePortletAction implements AjaxAction, + AjaxBuilder, Constants, Comparator { + protected static final Log log = LogFactory.getLog(GetPortletsAction.class); - - public GetPagesAction(String template, - String errorTemplate, - PageManager pageManager, - PortletActionSecurityBehavior securityBehavior) + + public GetPagesAction(String template, String errorTemplate, + PageManager pageManager, + PortletActionSecurityBehavior securityBehavior) { super(template, errorTemplate, pageManager, securityBehavior); } @@ -66,18 +64,18 @@ resultMap.put(ACTION, "getpages"); if (false == checkAccess(requestContext, JetspeedActions.VIEW)) { -// if (!createNewPageOnEdit(requestContext)) -// { - success = false; - resultMap.put(REASON, "Insufficient access to get portlets"); - return success; -// } -// status = "refresh"; - } - List pages = retrievePages(requestContext); + // if (!createNewPageOnEdit(requestContext)) + // { + success = false; + resultMap.put(REASON, "Insufficient access to get portlets"); + return success; + // } + // status = "refresh"; + } + List pages = retrievePages(requestContext); resultMap.put(STATUS, status); resultMap.put(PAGES, pages); - } + } catch (Exception e) { // Log the exception @@ -88,39 +86,35 @@ } return success; - } - + } + protected List retrievePages(RequestContext requestContext) - { + { List list = new ArrayList(); - + String folderName = getActionParameter(requestContext, FOLDER); - if (folderName == null) - { - return list; - } + if (folderName == null) { return list; } try { Folder folder = pageManager.getFolder(folderName); Iterator it = folder.getPages().iterator(); while (it.hasNext()) { - Page page = (Page)it.next(); + Page page = (Page) it.next(); list.add(page); } Collections.sort(list, this); } catch (Exception e) - { + { } return list; } - - + public int compare(Object obj1, Object obj2) { - Page page1 = (Page)obj1; - Page page2 = (Page)obj2; + Page page1 = (Page) obj1; + Page page2 = (Page) obj2; String name1 = page1.getName(); String name2 = page2.getName(); name1 = (name1 == null) ? "unknown" : name1; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPortletActionsAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPortletActionsAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPortletActionsAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,103 +33,107 @@ import org.apache.jetspeed.request.RequestContext; /** - * Get Portlet Actions retrieves the current set of valid actions for one or more portlet windows - * - * AJAX Parameters: - * id = the fragment id of the portlet for which to retrieve the action list - * multiple id parameters are supported - * page = (implied in the URL) - * + * Get Portlet Actions retrieves the current set of valid actions for one or + * more portlet windows + * + * AJAX Parameters: id = the fragment id of the portlet for which to retrieve + * the action list multiple id parameters are supported page = (implied in the + * URL) + * * @author David Sean Taylor * @version $Id: $ */ -public class GetPortletActionsAction - extends BasePortletAction - implements AjaxAction, AjaxBuilder, Constants +public class GetPortletActionsAction extends BasePortletAction implements + AjaxAction, AjaxBuilder, Constants { - protected static final Log log = LogFactory.getLog(GetPortletActionsAction.class); + + protected static final Log log = LogFactory + .getLog(GetPortletActionsAction.class); + protected String action; + private DecorationValve decorationValve; - - public GetPortletActionsAction(String template, - String errorTemplate, - String action, - DecorationValve decorationValve) - throws AJAXException + + public GetPortletActionsAction(String template, String errorTemplate, + String action, DecorationValve decorationValve) + throws AJAXException { this(template, errorTemplate, action, decorationValve, null, null); } - - public GetPortletActionsAction(String template, - String errorTemplate, - String action, - DecorationValve decorationValve, - PageManager pageManager, - PortletActionSecurityBehavior securityBehavior) - throws AJAXException + + public GetPortletActionsAction(String template, String errorTemplate, + String action, DecorationValve decorationValve, + PageManager pageManager, + PortletActionSecurityBehavior securityBehavior) + throws AJAXException { super(template, errorTemplate, pageManager, securityBehavior); this.action = action; this.decorationValve = decorationValve; } - public boolean runBatch(RequestContext requestContext, Map resultMap) throws AJAXException + public boolean runBatch(RequestContext requestContext, Map resultMap) + throws AJAXException { return runAction(requestContext, resultMap, true); - } - + } + public boolean run(RequestContext requestContext, Map resultMap) throws AJAXException { return runAction(requestContext, resultMap, false); } - - public boolean runAction( RequestContext requestContext, Map resultMap, boolean batch ) + + public boolean runAction(RequestContext requestContext, Map resultMap, + boolean batch) { boolean success = true; String status = "success"; try { - resultMap.put( ACTION, action ); - + resultMap.put(ACTION, action); + ContentPage page = requestContext.getPage(); - + // Get the necessary parameters off of the request ArrayList getActionsForFragments = new ArrayList(); - String[] portletIds = requestContext.getRequest().getParameterValues( PORTLETID ); - if ( portletIds != null && portletIds.length > 0 ) + String[] portletIds = requestContext.getRequest() + .getParameterValues(PORTLETID); + if (portletIds != null && portletIds.length > 0) { - for ( int i = 0 ; i < portletIds.length ; i++ ) + for (int i = 0; i < portletIds.length; i++) { - String portletId = portletIds[ i ]; - ContentFragment fragment = (ContentFragment)page.getFragmentById( portletId ); - if ( fragment == null ) - { - throw new Exception("fragment not found for specified portlet id: " + portletId); - } - getActionsForFragments.add( fragment ); + String portletId = portletIds[i]; + ContentFragment fragment = (ContentFragment) page + .getFragmentById(portletId); + if (fragment == null) { throw new Exception( + "fragment not found for specified portlet id: " + + portletId); } + getActionsForFragments.add(fragment); } - getActionsForFragments.add( page.getRootContentFragment() ); + getActionsForFragments.add(page.getRootContentFragment()); } // Run the Decoration valve to get actions - decorationValve.initFragments( requestContext, true, getActionsForFragments ); - - if ( getActionsForFragments.size() > 0 ) + decorationValve.initFragments(requestContext, true, + getActionsForFragments); + + if (getActionsForFragments.size() > 0) { - Fragment rootFragment = (Fragment)getActionsForFragments.remove( getActionsForFragments.size()-1 ); - resultMap.put( PAGE, rootFragment ); + Fragment rootFragment = (Fragment) getActionsForFragments + .remove(getActionsForFragments.size() - 1); + resultMap.put(PAGE, rootFragment); } - - resultMap.put( PORTLETS, getActionsForFragments ); - - resultMap.put( STATUS, status ); - } + + resultMap.put(PORTLETS, getActionsForFragments); + + resultMap.put(STATUS, status); + } catch (Exception e) { // Log the exception - log.error( "exception while getting actions for a fragment", e ); - resultMap.put( REASON, e.toString() ); + log.error("exception while getting actions for a fragment", e); + resultMap.put(REASON, e.toString()); // Return a failure indicator success = false; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPortletsAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPortletsAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetPortletsAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -43,37 +43,38 @@ /** * Get Portlets retrieves the portlet list available to the current subject - * - * AJAX Parameters: - * filter = (optional)filter to lookup portlets using fulltext search - * + * + * AJAX Parameters: filter = (optional)filter to lookup portlets using fulltext + * search + * * @author David Gurney * @author David Sean Taylor * @version $Id: $ */ -public class GetPortletsAction - extends BasePortletAction - implements AjaxAction, AjaxBuilder, Constants, Comparator +public class GetPortletsAction extends BasePortletAction implements AjaxAction, + AjaxBuilder, Constants, Comparator { + protected static final Log log = LogFactory.getLog(GetPortletsAction.class); + private PortletRegistry registry = null; + private SearchEngine searchEngine = null; + private SecurityAccessController securityAccessController; - + public final static String PORTLET_ICON = "portlet-icon"; - + public GetPortletsAction(String template, String errorTemplate) { this(template, errorTemplate, null, null, null, null, null); } - - public GetPortletsAction(String template, - String errorTemplate, - PageManager pageManager, - PortletRegistry registry, - SearchEngine searchEngine, - SecurityAccessController securityAccessController, - PortletActionSecurityBehavior securityBehavior) + + public GetPortletsAction(String template, String errorTemplate, + PageManager pageManager, PortletRegistry registry, + SearchEngine searchEngine, + SecurityAccessController securityAccessController, + PortletActionSecurityBehavior securityBehavior) { super(template, errorTemplate, pageManager, securityBehavior); this.registry = registry; @@ -90,19 +91,19 @@ resultMap.put(ACTION, "getportlets"); if (false == checkAccess(requestContext, JetspeedActions.VIEW)) { -// if (!createNewPageOnEdit(requestContext)) -// { - success = false; - resultMap.put(REASON, "Insufficient access to edit page"); - return success; -// } -// status = "refresh"; - } - String filter = getActionParameter(requestContext, FILTER); - List portlets = retrievePortlets(requestContext, filter); + // if (!createNewPageOnEdit(requestContext)) + // { + success = false; + resultMap.put(REASON, "Insufficient access to edit page"); + return success; + // } + // status = "refresh"; + } + String filter = getActionParameter(requestContext, FILTER); + List portlets = retrievePortlets(requestContext, filter); resultMap.put(STATUS, status); resultMap.put(PORTLETS, portlets); - } + } catch (Exception e) { // Log the exception @@ -113,111 +114,118 @@ } return success; - } - + } + public List retrievePortlets(RequestContext requestContext, String filter) { Iterator portlets = null; List list = new ArrayList(); Locale locale = requestContext.getLocale(); - + if (filter == null) portlets = registry.getAllPortletDefinitions().iterator(); else portlets = searchEngine.search(filter).getResults().iterator(); - + while (portlets.hasNext()) { PortletDefinitionComposite portlet = null; if (filter == null) - portlet = (PortletDefinitionComposite)portlets.next(); + portlet = (PortletDefinitionComposite) portlets.next(); else - portlet = this.getPortletFromParsedObject((ParsedObject)portlets.next()); - - if (portlet == null) - continue; - + portlet = this + .getPortletFromParsedObject((ParsedObject) portlets + .next()); + + if (portlet == null) continue; + // Do not display Jetspeed Layout Applications - MutablePortletApplication pa = (MutablePortletApplication)portlet.getPortletApplicationDefinition(); - if (pa.isLayoutApplication()) - continue; - + MutablePortletApplication pa = (MutablePortletApplication) portlet + .getPortletApplicationDefinition(); + if (pa.isLayoutApplication()) continue; + // SECURITY filtering String uniqueName = pa.getName() + "::" + portlet.getName(); - if (securityAccessController.checkPortletAccess(portlet, JetspeedActions.MASK_VIEW)) + if (securityAccessController.checkPortletAccess(portlet, + JetspeedActions.MASK_VIEW)) { - Parameter param = portlet.getInitParameterSet().get(PORTLET_ICON); + Parameter param = portlet.getInitParameterSet().get( + PORTLET_ICON); String image; if (param != null) { - //String relativeImagePath = param.getValue(); - //String context = muta.getWebApplicationDefinition().getContextRoot(); - // Have to use a supported icon in jetspeed, otherwise image can be out of skew + // String relativeImagePath = param.getValue(); + // String context = + // muta.getWebApplicationDefinition().getContextRoot(); + // Have to use a supported icon in jetspeed, otherwise image + // can be out of skew image = "images/portlets/" + param.getValue(); } else - { + { image = "images/portlets/applications-internet.png"; - } - list.add(new PortletInfo(uniqueName, portlet.getDisplayNameText(locale), portlet.getDescriptionText(locale), image)); + } + list.add(new PortletInfo(uniqueName, portlet + .getDisplayNameText(locale), portlet + .getDescriptionText(locale), image)); } - } + } Collections.sort(list, this); return list; } - - protected PortletDefinitionComposite getPortletFromParsedObject(ParsedObject po) + + protected PortletDefinitionComposite getPortletFromParsedObject( + ParsedObject po) { boolean found = false; String name = ""; Map fields = po.getFields(); - if(fields != null) + if (fields != null) { Object id = fields.get("ID"); - - if(id != null) + + if (id != null) { - if(id instanceof Collection) + if (id instanceof Collection) { - Collection coll = (Collection)id; + Collection coll = (Collection) id; name = (String) coll.iterator().next(); } else { - name = (String)id; + name = (String) id; } } - - if(po.getType().equals("portlet")) + + if (po.getType().equals("portlet")) { Object pa = fields.get("portlet_application"); String paName = ""; - if(pa != null) + if (pa != null) { - if(id instanceof Collection) + if (id instanceof Collection) { - Collection coll = (Collection)pa; + Collection coll = (Collection) pa; paName = (String) coll.iterator().next(); } else { - paName = (String)pa; + paName = (String) pa; } } name = paName + "::" + name; found = true; } } - if (found == false) - return null; - + if (found == false) return null; + return registry.getPortletDefinitionByUniqueName(name); } - + public int compare(Object obj1, Object obj2) { - PortletInfo portlet1 = (PortletInfo)obj1; - PortletInfo portlet2 = (PortletInfo)obj2; + PortletInfo portlet1 = (PortletInfo) obj1; + PortletInfo portlet2 = (PortletInfo) obj2; String name1 = portlet1.getName(); String name2 = portlet2.getName(); name1 = (name1 == null) ? "unknown" : name1; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetThemesAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetThemesAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetThemesAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,72 +28,74 @@ import org.apache.jetspeed.request.RequestContext; /** - * Get Portal-wide themes lists - * (page decorators, portlet decorators, layouts, desktop-page-decorators, desktop-portlet-decorators) - * - * AJAX Parameters: - * none - * + * Get Portal-wide themes lists (page decorators, portlet decorators, layouts, + * desktop-page-decorators, desktop-portlet-decorators) + * + * AJAX Parameters: none + * * @author David Sean Taylor * @version $Id: $ */ -public class GetThemesAction - extends BasePortletAction - implements AjaxAction, AjaxBuilder, Constants +public class GetThemesAction extends BasePortletAction implements AjaxAction, + AjaxBuilder, Constants { + protected static final Log log = LogFactory.getLog(GetThemesAction.class); + protected DecorationFactory decorationFactory; - - public GetThemesAction(String template, - String errorTemplate, - DecorationFactory decorationFactory, - PortletActionSecurityBehavior securityBehavior) + + public GetThemesAction(String template, String errorTemplate, + DecorationFactory decorationFactory, + PortletActionSecurityBehavior securityBehavior) { super(template, errorTemplate, securityBehavior); this.decorationFactory = decorationFactory; } - public boolean run( RequestContext requestContext, Map resultMap ) + public boolean run(RequestContext requestContext, Map resultMap) { boolean success = true; String status = "success"; try { - resultMap.put( ACTION, "getthemes" ); - if (false == checkAccess( requestContext, JetspeedActions.VIEW ) ) + resultMap.put(ACTION, "getthemes"); + if (false == checkAccess(requestContext, JetspeedActions.VIEW)) { - success = false; - resultMap.put( REASON, "Insufficient access to get themes" ); - return success; - } - String type = getActionParameter(requestContext, TYPE ); - String format = getActionParameter(requestContext, FORMAT ); - if (format == null) - format = "xml"; - if (type == null || type.equals( PAGE_DECORATIONS ) ) - resultMap.put( PAGE_DECORATIONS, decorationFactory.getPageDecorations( requestContext ) ); - if (type == null || type.equals( PORTLET_DECORATIONS ) ) - resultMap.put( PORTLET_DECORATIONS, decorationFactory.getPortletDecorations( requestContext ) ); - if (type == null || type.equals( LAYOUTS ) ) - resultMap.put( LAYOUTS, decorationFactory.getLayouts( requestContext ) ); - if (type == null || type.equals( DESKTOP_PAGE_DECORATIONS) ) - resultMap.put( DESKTOP_PAGE_DECORATIONS, decorationFactory.getDesktopPageDecorations( requestContext ) ); - if (type == null || type.equals( DESKTOP_PORTLET_DECORATIONS ) ) - resultMap.put( DESKTOP_PORTLET_DECORATIONS, decorationFactory.getDesktopPortletDecorations( requestContext ) ); - resultMap.put( TYPE, type ); - resultMap.put( FORMAT, format ); - resultMap.put( STATUS, status ); - } + success = false; + resultMap.put(REASON, "Insufficient access to get themes"); + return success; + } + String type = getActionParameter(requestContext, TYPE); + String format = getActionParameter(requestContext, FORMAT); + if (format == null) format = "xml"; + if (type == null || type.equals(PAGE_DECORATIONS)) + resultMap.put(PAGE_DECORATIONS, decorationFactory + .getPageDecorations(requestContext)); + if (type == null || type.equals(PORTLET_DECORATIONS)) + resultMap.put(PORTLET_DECORATIONS, decorationFactory + .getPortletDecorations(requestContext)); + if (type == null || type.equals(LAYOUTS)) + resultMap.put(LAYOUTS, decorationFactory + .getLayouts(requestContext)); + if (type == null || type.equals(DESKTOP_PAGE_DECORATIONS)) + resultMap.put(DESKTOP_PAGE_DECORATIONS, decorationFactory + .getDesktopPageDecorations(requestContext)); + if (type == null || type.equals(DESKTOP_PORTLET_DECORATIONS)) + resultMap.put(DESKTOP_PORTLET_DECORATIONS, decorationFactory + .getDesktopPortletDecorations(requestContext)); + resultMap.put(TYPE, type); + resultMap.put(FORMAT, format); + resultMap.put(STATUS, status); + } catch (Exception e) { // Log the exception - log.error( "exception while getting theme info", e ); + log.error("exception while getting theme info", e); // Return a failure indicator success = false; } return success; - } - - + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetUserInformationAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetUserInformationAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/GetUserInformationAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,11 +17,11 @@ package org.apache.jetspeed.layout.impl; import java.security.Principal; +import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Map; -import java.util.List; -import java.util.ArrayList; import java.util.prefs.Preferences; import javax.security.auth.Subject; @@ -40,29 +40,25 @@ /** * Retrieve user information of the current user * - * AJAX action: - * action = getuserinfo + * AJAX action: action = getuserinfo * - * AJAX Parameters: - * none - * + * AJAX Parameters: none + * * @author Mikko Wuokko * @version $Id: $ */ -public class GetUserInformationAction - extends BaseUserAction - implements AjaxAction, AjaxBuilder, Constants +public class GetUserInformationAction extends BaseUserAction implements + AjaxAction, AjaxBuilder, Constants { + protected Log log = LogFactory.getLog(GetUserInformationAction.class); - public GetUserInformationAction(String template, - String errorTemplate, - UserManager um, - RolesSecurityBehavior rolesSecurityBehavior) + public GetUserInformationAction(String template, String errorTemplate, + UserManager um, RolesSecurityBehavior rolesSecurityBehavior) { super(template, errorTemplate, um, rolesSecurityBehavior); } - + public boolean run(RequestContext requestContext, Map resultMap) throws AJAXException { @@ -72,47 +68,51 @@ { resultMap.put(ACTION, "userinformation"); // Get the necessary parameters off of the request - if(!requestContext.getUserPrincipal().getName().equals(userManager.getAnonymousUser())) - { - Principal principal = requestContext.getUserPrincipal(); + if (!requestContext.getUserPrincipal().getName().equals( + userManager.getAnonymousUser())) + { + Principal principal = requestContext.getUserPrincipal(); resultMap.put(USERNAME, principal.getName()); resultMap.put(TYPE, principal.getClass().getName()); - + // Loading the userinfo User user = userManager.getUser(principal.getName()); - if(user != null) + if (user != null) { - Preferences prefs = user.getUserAttributes(); - String[] prefKeys = prefs.keys(); - Map prefsSet = new HashMap(); - for(int i = 0; iMikko Wuokko * @version $Id: $ */ -public class GetUserListAction - extends BaseUserAction - implements AjaxAction, AjaxBuilder, Constants +public class GetUserListAction extends BaseUserAction implements AjaxAction, + AjaxBuilder, Constants { + protected Log log = LogFactory.getLog(GetUserListAction.class); + private PortalStatistics pstats = null; + private PortalSessionsManager psm = null; + // By default the protection is set to all private String protectionScope = "all"; private final String PARAM_GUEST = "guest"; + private final String PARAM_USERINFO = "userinfo"; + private final String PARAM_OFFILE = "offline"; + private final String PARAM_ALL = "all"; - - public GetUserListAction(String template, - String errorTemplate, - UserManager um, - PortalStatistics pstats, - PortalSessionsManager psm) + + public GetUserListAction(String template, String errorTemplate, + UserManager um, PortalStatistics pstats, PortalSessionsManager psm) { - this(template, errorTemplate, um, pstats, psm, null); + this(template, errorTemplate, um, pstats, psm, null); } - - public GetUserListAction(String template, - String errorTemplate, - UserManager um, - PortalStatistics pstats, - PortalSessionsManager psm, + + public GetUserListAction(String template, String errorTemplate, + UserManager um, PortalStatistics pstats, PortalSessionsManager psm, RolesSecurityBehavior securityBehavior) { - super(template, errorTemplate, um, securityBehavior); - this.pstats = pstats; - this.psm = psm; + super(template, errorTemplate, um, securityBehavior); + this.pstats = pstats; + this.psm = psm; } - - public GetUserListAction(String template, - String errorTemplate, - UserManager um, - PortalStatistics pstats, - PortalSessionsManager psm, - RolesSecurityBehavior securityBehavior, - String protectionScope) + + public GetUserListAction(String template, String errorTemplate, + UserManager um, PortalStatistics pstats, PortalSessionsManager psm, + RolesSecurityBehavior securityBehavior, String protectionScope) { - super(template, errorTemplate, um, securityBehavior); - this.pstats = pstats; - this.psm = psm; - this.protectionScope = protectionScope; + super(template, errorTemplate, um, securityBehavior); + this.pstats = pstats; + this.psm = psm; + this.protectionScope = protectionScope; } - + public boolean run(RequestContext requestContext, Map resultMap) throws AJAXException { boolean success = true; String status = "success"; - - boolean includeGuests; - boolean includeUserInfo; + + boolean includeGuests; + boolean includeUserInfo; boolean includeOffline; - boolean includeAll = isTrue(getActionParameter(requestContext, PARAM_ALL)); - + boolean includeAll = isTrue(getActionParameter(requestContext, + PARAM_ALL)); + // Set everything true if "all" is set to true - if(includeAll){ - includeGuests = true; - includeUserInfo = true; - includeOffline = true; + if (includeAll) + { + includeGuests = true; + includeUserInfo = true; + includeOffline = true; } else - { - includeOffline = isTrue(getActionParameter(requestContext, PARAM_OFFILE)); - includeGuests = isTrue(getActionParameter(requestContext, PARAM_GUEST)); - includeUserInfo = isTrue(getActionParameter(requestContext, PARAM_USERINFO)); + { + includeOffline = isTrue(getActionParameter(requestContext, + PARAM_OFFILE)); + includeGuests = isTrue(getActionParameter(requestContext, + PARAM_GUEST)); + includeUserInfo = isTrue(getActionParameter(requestContext, + PARAM_USERINFO)); } - - // Do a security check if a behavior is set - if(securityBehavior != null) - { - // If protection is set to "none", everything will be allowed - if(!checkAccess(requestContext, JetspeedActions.EDIT) && !this.protectionScope.equals("none")) - { - // If we have set protection to private only and security check failed, - // will return basic information still - if(this.protectionScope.equals("private-offline")) - { - // If private and offline information is protected, disable that and offline users. - includeUserInfo = false; - includeOffline = false; - } - else if(this.protectionScope.equals("private")) - { - // Only private information is protected. - includeUserInfo = false; - } - else - { - - success = false; - resultMap.put(REASON, "Insufficient access see user details."); - return success; - } - } - } - + + // Do a security check if a behavior is set + if (securityBehavior != null) + { + // If protection is set to "none", everything will be allowed + if (!checkAccess(requestContext, JetspeedActions.EDIT) + && !this.protectionScope.equals("none")) + { + // If we have set protection to private only and security check + // failed, + // will return basic information still + if (this.protectionScope.equals("private-offline")) + { + // If private and offline information is protected, disable + // that and offline users. + includeUserInfo = false; + includeOffline = false; + } + else if (this.protectionScope.equals("private")) + { + // Only private information is protected. + includeUserInfo = false; + } + else + { + + success = false; + resultMap.put(REASON, + "Insufficient access see user details."); + return success; + } + } + } + int numberOfCurrentUsers = 0; int numberOfCurrentLoggedInUsers = 0; - + Collection users = new ArrayList(); Collection loggedInUsers = new ArrayList(); Collection offlineUsers = new ArrayList(); @@ -175,111 +174,131 @@ try { resultMap.put(ACTION, "getuserlist"); - // Check that the statistics is not disabled - if(pstats != null) - { - // Get the user counts - numberOfCurrentUsers = psm.sessionCount(); - numberOfCurrentLoggedInUsers = pstats.getNumberOfLoggedInUsers(); + // Check that the statistics is not disabled + if (pstats != null) + { + // Get the user counts + numberOfCurrentUsers = psm.sessionCount(); + numberOfCurrentLoggedInUsers = pstats + .getNumberOfLoggedInUsers(); - /* - * An helper to track the users that have already been added to the resultMap - * as logged in users, so there wouldn't be an offline duplicate. Trying - * to prevent some overhead with this. - * Needs some more thinking, maybe some helper functions to portal statistics - * to get just the names of the logged in users for contains comparison. - */ - List addedUserNames = new ArrayList(); - - // If no logged in users, nothing to do - if(numberOfCurrentLoggedInUsers > 0) - { + /* + * An helper to track the users that have already been added to + * the resultMap as logged in users, so there wouldn't be an + * offline duplicate. Trying to prevent some overhead with this. + * Needs some more thinking, maybe some helper functions to + * portal statistics to get just the names of the logged in + * users for contains comparison. + */ + List addedUserNames = new ArrayList(); - // Logged in users is a list of UserStats objects - Iterator usersIter = pstats.getListOfLoggedInUsers().iterator(); - while(usersIter.hasNext()) - { - Map userMap = (Map)usersIter.next(); - if(userMap != null && userMap.size() > 0) - { - Iterator userKeyIter = userMap.keySet().iterator(); - while(userKeyIter.hasNext()) - { - String userStatKey = String.valueOf(userKeyIter.next()); - UserStats userStat = (UserStats)userMap.get(userStatKey); - - Map singleUserMap = new HashMap(); - singleUserMap.put(USERNAME, userStat.getUsername()); - singleUserMap.put(SESSIONS, new Integer(userStat.getNumberOfSessions())); - singleUserMap.put(STATUS, ONLINE); - singleUserMap.put(IPADDRESS, userStat.getInetAddress().getHostAddress()); - if(includeUserInfo) - { - singleUserMap.put(USERINFO, getUserInfo(userStat.getUsername())); - } - - // Add user to the helper if not added yet - if(!addedUserNames.contains(userStat.getUsername())) - addedUserNames.add(userStat.getUsername()); - - loggedInUsers.add(singleUserMap); - } - - } - } - - // Adding online users to the collection - users.addAll(loggedInUsers); + // If no logged in users, nothing to do + if (numberOfCurrentLoggedInUsers > 0) + { + + // Logged in users is a list of UserStats objects + Iterator usersIter = pstats.getListOfLoggedInUsers() + .iterator(); + while (usersIter.hasNext()) + { + Map userMap = (Map) usersIter.next(); + if (userMap != null && userMap.size() > 0) + { + Iterator userKeyIter = userMap.keySet().iterator(); + while (userKeyIter.hasNext()) + { + String userStatKey = String.valueOf(userKeyIter + .next()); + UserStats userStat = (UserStats) userMap + .get(userStatKey); + + Map singleUserMap = new HashMap(); + singleUserMap.put(USERNAME, userStat + .getUsername()); + singleUserMap.put(SESSIONS, new Integer( + userStat.getNumberOfSessions())); + singleUserMap.put(STATUS, ONLINE); + singleUserMap.put(IPADDRESS, userStat + .getInetAddress().getHostAddress()); + if (includeUserInfo) + { + singleUserMap + .put(USERINFO, getUserInfo(userStat + .getUsername())); + } + + // Add user to the helper if not added yet + if (!addedUserNames.contains(userStat + .getUsername())) + addedUserNames.add(userStat.getUsername()); + + loggedInUsers.add(singleUserMap); + } + + } + } + + // Adding online users to the collection + users.addAll(loggedInUsers); } - - // Check whether we should iterate through all of the users or just logged in ones - if(includeOffline) - { - Iterator allUusers = userManager.getUsers(""); - while(allUusers.hasNext()) - { - User user = (User)allUusers.next(); - Principal userPrincipal = SecurityHelper.getPrincipal(user.getSubject(), UserPrincipal.class); - if(userPrincipal != null) - { - // Check if this users is already added as online user - if(!addedUserNames.contains(userPrincipal.getName())) - { - Map userMap = new HashMap(); - userMap.put(USERNAME, userPrincipal.getName()); - userMap.put(STATUS, OFFLINE); - if(includeUserInfo) - { - userMap.put(USERINFO, getUserInfo(userPrincipal.getName())); } - offlineUsers.add(userMap); - } - } - } - - // Adding online users to the collection - users.addAll(offlineUsers); - } - - // Add the logged in users to resultMap + // Check whether we should iterate through all of the users or + // just logged in ones + if (includeOffline) + { + Iterator allUusers = userManager.getUsers(""); + while (allUusers.hasNext()) + { + User user = (User) allUusers.next(); + Principal userPrincipal = SecurityHelper.getPrincipal( + user.getSubject(), UserPrincipal.class); + if (userPrincipal != null) + { + // Check if this users is already added as online + // user + if (!addedUserNames.contains(userPrincipal + .getName())) + { + Map userMap = new HashMap(); + userMap.put(USERNAME, userPrincipal.getName()); + userMap.put(STATUS, OFFLINE); + if (includeUserInfo) + { + userMap + .put(USERINFO, + getUserInfo(userPrincipal + .getName())); + } + + offlineUsers.add(userMap); + } + } + } + + // Adding online users to the collection + users.addAll(offlineUsers); + } + + // Add the logged in users to resultMap resultMap.put(USERS, users); - - if(includeGuests) - { - // Add number of guest accounts to resultMap - int guestUserCount = numberOfCurrentUsers - numberOfCurrentLoggedInUsers; + + if (includeGuests) + { + // Add number of guest accounts to resultMap + int guestUserCount = numberOfCurrentUsers + - numberOfCurrentLoggedInUsers; resultMap.put(GUESTUSERS, new Integer(guestUserCount)); - } - - } - else - { - status = "failure"; - resultMap.put(REASON, "Statistics not available"); - return false; - } + } + + } + else + { + status = "failure"; + resultMap.put(REASON, "Statistics not available"); + return false; + } resultMap.put(STATUS, status); - } + } catch (Exception e) { log.error("exception statistics access", e); @@ -287,33 +306,36 @@ success = false; } return success; - } + } - /** * Helper method to get the user information of an user as Map. * - * @param username Name of the user of request - * @return Map containing the user information keyed by the name of the attribute. + * @param username + * Name of the user of request + * @return Map containing the user information keyed by the name of the + * attribute. * @throws SecurityException * @throws BackingStoreException */ - private Map getUserInfo(String username) throws SecurityException, BackingStoreException + private Map getUserInfo(String username) throws SecurityException, + BackingStoreException { - Map userInfo = new HashMap(); - User user = userManager.getUser(username); - if(user != null) - { - Preferences userPrefs = user.getUserAttributes(); - String[] userPrefKeys = userPrefs.keys(); - - for(int i = 0; iDavid Gurney * @author David Sean Taylor * @version $Id: $ */ -public class MovePortletAction - extends BasePortletAction - implements AjaxAction, AjaxBuilder, Constants +public class MovePortletAction extends BasePortletAction implements AjaxAction, + AjaxBuilder, Constants { + protected static final Log log = LogFactory.getLog(MovePortletAction.class); - protected static final String eol = System.getProperty( "line.separator" ); - + + protected static final String eol = System.getProperty("line.separator"); + private PortletRegistry registry; + private int iMoveType = -1; + private String sMoveType = null; - public MovePortletAction( String template, - String errorTemplate, - PortletRegistry registry, - String sMoveType ) - throws AJAXException + public MovePortletAction(String template, String errorTemplate, + PortletRegistry registry, String sMoveType) throws AJAXException { - this( template, errorTemplate, registry, sMoveType, null, null ); + this(template, errorTemplate, registry, sMoveType, null, null); } - - public MovePortletAction( String template, - String errorTemplate, - PortletRegistry registry, - PageManager pageManager, - PortletActionSecurityBehavior securityBehavior ) - throws AJAXException + + public MovePortletAction(String template, String errorTemplate, + PortletRegistry registry, PageManager pageManager, + PortletActionSecurityBehavior securityBehavior) + throws AJAXException { - this( template, errorTemplate, registry, "moveabs", pageManager, securityBehavior ); + this(template, errorTemplate, registry, "moveabs", pageManager, + securityBehavior); } - public MovePortletAction( String template, - String errorTemplate, - PortletRegistry registry, - String sMoveType, - PageManager pageManager, - PortletActionSecurityBehavior securityBehavior ) - throws AJAXException + public MovePortletAction(String template, String errorTemplate, + PortletRegistry registry, String sMoveType, + PageManager pageManager, + PortletActionSecurityBehavior securityBehavior) + throws AJAXException { - super( template, errorTemplate, pageManager, securityBehavior ); - setMoveType( sMoveType ); + super(template, errorTemplate, pageManager, securityBehavior); + setMoveType(sMoveType); this.registry = registry; } @@ -103,19 +96,19 @@ if (p_sMoveType.equalsIgnoreCase("moveabs")) { iMoveType = ABS; - } + } else if (p_sMoveType.equalsIgnoreCase("moveup")) { iMoveType = UP; - } + } else if (p_sMoveType.equalsIgnoreCase("movedown")) { iMoveType = DOWN; - } + } else if (p_sMoveType.equalsIgnoreCase("moveleft")) { iMoveType = LEFT; - } + } else if (p_sMoveType.equalsIgnoreCase("moveright")) { iMoveType = RIGHT; @@ -130,18 +123,20 @@ } } - public boolean runBatch(RequestContext requestContext, Map resultMap) throws AJAXException + public boolean runBatch(RequestContext requestContext, Map resultMap) + throws AJAXException { return runAction(requestContext, resultMap, true); - } - + } + public boolean run(RequestContext requestContext, Map resultMap) throws AJAXException { return runAction(requestContext, resultMap, false); } - - protected boolean runAction( RequestContext requestContext, Map resultMap, boolean batch ) throws AJAXException + + protected boolean runAction(RequestContext requestContext, Map resultMap, + boolean batch) throws AJAXException { boolean success = true; String status = "success"; @@ -149,69 +144,79 @@ { resultMap.put(ACTION, sMoveType); // Get the necessary parameters off of the request - String moveFragmentId = getActionParameter(requestContext, FRAGMENTID); + String moveFragmentId = getActionParameter(requestContext, + FRAGMENTID); String layoutId = getActionParameter(requestContext, LAYOUTID); - if ( moveFragmentId == null ) - { - throw new Exception( FRAGMENTID + " not provided; must specify portlet or layout id" ); - } + if (moveFragmentId == null) { throw new Exception(FRAGMENTID + + " not provided; must specify portlet or layout id"); } resultMap.put(FRAGMENTID, moveFragmentId); - + Fragment currentLayoutFragment = null; Fragment moveToLayoutFragment = null; - // when layoutId is null we use old behavior, ignoring everything to do with multiple layout fragments - if ( layoutId != null && layoutId.length() > 0 && iMoveType != CARTESIAN ) + // when layoutId is null we use old behavior, ignoring everything to + // do with multiple layout fragments + if (layoutId != null && layoutId.length() > 0 + && iMoveType != CARTESIAN) { Page page = requestContext.getPage(); - currentLayoutFragment = page.getFragmentById( layoutId ); - if ( currentLayoutFragment == null ) + currentLayoutFragment = page.getFragmentById(layoutId); + if (currentLayoutFragment == null) { - throw new Exception("layout id not found: " + layoutId ); + throw new Exception("layout id not found: " + layoutId); } else { - // determine if layoutId parameter refers to the current layout fragment or to some other layout fragment + // determine if layoutId parameter refers to the current + // layout fragment or to some other layout fragment moveToLayoutFragment = currentLayoutFragment; - Iterator layoutChildIter = moveToLayoutFragment.getFragments().iterator(); - while ( layoutChildIter.hasNext() ) + Iterator layoutChildIter = moveToLayoutFragment + .getFragments().iterator(); + while (layoutChildIter.hasNext()) { - Fragment childFrag = (Fragment)layoutChildIter.next(); - if ( childFrag != null ) + Fragment childFrag = (Fragment) layoutChildIter.next(); + if (childFrag != null) { - if ( moveFragmentId.equals( childFrag.getId() ) ) + if (moveFragmentId.equals(childFrag.getId())) { moveToLayoutFragment = null; break; } } } - if ( moveToLayoutFragment != null ) + if (moveToLayoutFragment != null) { - // figure out the current layout fragment - must know to be able to find the portlet - // fragment by row/col when a new page is created - Fragment root = requestContext.getPage().getRootFragment(); - currentLayoutFragment = getParentFragmentById( moveFragmentId, root ); + // figure out the current layout fragment - must know to + // be able to find the portlet + // fragment by row/col when a new page is created + Fragment root = requestContext.getPage() + .getRootFragment(); + currentLayoutFragment = getParentFragmentById( + moveFragmentId, root); } } - if ( currentLayoutFragment == null ) + if (currentLayoutFragment == null) { // report error - throw new Exception("parent layout id not found for portlet id:" + moveFragmentId ); + throw new Exception( + "parent layout id not found for portlet id:" + + moveFragmentId); } } - - if ( false == checkAccess( requestContext, JetspeedActions.EDIT ) ) + + if (false == checkAccess(requestContext, JetspeedActions.EDIT)) { - if ( ! isPageQualifiedForCreateNewPageOnEdit( requestContext ) ) - { - success = false; - resultMap.put(REASON, "Page is not qualified for create-new-page-on-edit"); + if (!isPageQualifiedForCreateNewPageOnEdit(requestContext)) + { + success = false; + resultMap + .put(REASON, + "Page is not qualified for create-new-page-on-edit"); return success; - } - + } + Page page = requestContext.getPage(); - Fragment fragment = page.getFragmentById( moveFragmentId ); - if ( fragment == null ) + Fragment fragment = page.getFragmentById(moveFragmentId); + if (fragment == null) { success = false; resultMap.put(REASON, "Fragment not found"); @@ -221,358 +226,393 @@ NestedFragmentContext moveToFragmentContext = null; try { - moveFragmentContext = new NestedFragmentContext( fragment, page, registry ); - //log.info( "moveFragmentContext original : " + eol + moveFragmentContext.toString() ); - if ( moveToLayoutFragment != null ) - { - moveToFragmentContext = new NestedFragmentContext( moveToLayoutFragment, page, registry ); - //log.info( "moveToFragmentContext original : " + eol + moveToFragmentContext.toString() ); - } + moveFragmentContext = new NestedFragmentContext(fragment, + page, registry); + // log.info( "moveFragmentContext original : " + eol + + // moveFragmentContext.toString() ); + if (moveToLayoutFragment != null) + { + moveToFragmentContext = new NestedFragmentContext( + moveToLayoutFragment, page, registry); + // log.info( "moveToFragmentContext original : " + eol + + // moveToFragmentContext.toString() ); + } } - catch ( Exception ex ) + catch (Exception ex) { - log.error( "Failure to construct nested context for fragment " + moveFragmentId, ex ); - success = false; - resultMap.put( REASON, "Cannot construct nested context for fragment" ); + log.error( + "Failure to construct nested context for fragment " + + moveFragmentId, ex); + success = false; + resultMap.put(REASON, + "Cannot construct nested context for fragment"); return success; } - - //log.info("before createNewPageOnEdit page-name=" + page.getName() + " page-path=" + page.getPath() + " page-url=" + page.getUrl() ); - if ( ! createNewPageOnEdit( requestContext ) ) + + // log.info("before createNewPageOnEdit page-name=" + + // page.getName() + " page-path=" + page.getPath() + " + // page-url=" + page.getUrl() ); + if (!createNewPageOnEdit(requestContext)) { success = false; resultMap.put(REASON, "Insufficient access to edit page"); return success; } status = "refresh"; - - Page newPage = requestContext.getPage(); - //log.info("after createNewPageOnEdit page-name=" + newPage.getName() + " page-path=" + newPage.getPath() + " page-url=" + newPage.getUrl() ); + + Page newPage = requestContext.getPage(); + // log.info("after createNewPageOnEdit page-name=" + + // newPage.getName() + " page-path=" + newPage.getPath() + " + // page-url=" + newPage.getUrl() ); Fragment newPageRootFragment = newPage.getRootFragment(); - - // using NestedFragmentContext, find portlet id for copy of target portlet in the new page + + // using NestedFragmentContext, find portlet id for copy of + // target portlet in the new page Fragment newFragment = null; try { - newFragment = moveFragmentContext.getFragmentOnNewPage( newPage, registry ); - //log.info( "npe newFragment: " + newFragment.getType() + " " + newFragment.getId() ); + newFragment = moveFragmentContext.getFragmentOnNewPage( + newPage, registry); + // log.info( "npe newFragment: " + newFragment.getType() + " + // " + newFragment.getId() ); } - catch ( Exception ex ) + catch (Exception ex) { - log.error( "Failure to locate copy of fragment " + moveFragmentId, ex ); - success = false; - resultMap.put( REASON, "Failed to find new fragment for portlet id: " + moveFragmentId ); + log.error("Failure to locate copy of fragment " + + moveFragmentId, ex); + success = false; + resultMap.put(REASON, + "Failed to find new fragment for portlet id: " + + moveFragmentId); return success; } - + moveFragmentId = newFragment.getId(); - currentLayoutFragment = getParentFragmentById( moveFragmentId, newPageRootFragment ); - if ( currentLayoutFragment == null ) + currentLayoutFragment = getParentFragmentById(moveFragmentId, + newPageRootFragment); + if (currentLayoutFragment == null) { - success = false; - resultMap.put( REASON, "Failed to find parent layout for copied fragment " + moveFragmentId ); + success = false; + resultMap.put(REASON, + "Failed to find parent layout for copied fragment " + + moveFragmentId); return success; } - //log.info( "npe newParentFragment: " + currentLayoutFragment.getType() + " " + currentLayoutFragment.getId() ); - if ( moveToLayoutFragment != null ) + // log.info( "npe newParentFragment: " + + // currentLayoutFragment.getType() + " " + + // currentLayoutFragment.getId() ); + if (moveToLayoutFragment != null) { - Fragment newMoveToFragment = null; + Fragment newMoveToFragment = null; try { - newMoveToFragment = moveToFragmentContext.getFragmentOnNewPage( newPage, registry ); - //log.info( "npe newMoveToFragment: " + newMoveToFragment.getType() + " " + newMoveToFragment.getId() ); + newMoveToFragment = moveToFragmentContext + .getFragmentOnNewPage(newPage, registry); + // log.info( "npe newMoveToFragment: " + + // newMoveToFragment.getType() + " " + + // newMoveToFragment.getId() ); } - catch ( Exception ex ) + catch (Exception ex) { - log.error( "Failure to locate copy of destination fragment " + moveToLayoutFragment.getId(), ex ); - success = false; - resultMap.put( REASON, "Failed to find copy of destination fragment" ); + log.error( + "Failure to locate copy of destination fragment " + + moveToLayoutFragment.getId(), ex); + success = false; + resultMap.put(REASON, + "Failed to find copy of destination fragment"); return success; } moveToLayoutFragment = newMoveToFragment; } } - - if ( moveToLayoutFragment != null ) + + if (moveToLayoutFragment != null) { - success = moveToOtherLayoutFragment( requestContext, - batch, - resultMap, - moveFragmentId, - moveToLayoutFragment, - currentLayoutFragment ) ; + success = moveToOtherLayoutFragment(requestContext, batch, + resultMap, moveFragmentId, moveToLayoutFragment, + currentLayoutFragment); } else { - PortletPlacementContext placement = null; - Page page = requestContext.getPage(); - - if ( currentLayoutFragment == null ) - currentLayoutFragment = getParentFragmentById( moveFragmentId, page.getRootFragment() ); - - if ( currentLayoutFragment != null ) - placement = new PortletPlacementContextImpl( page, registry, currentLayoutFragment ); + PortletPlacementContext placement = null; + Page page = requestContext.getPage(); + + if (currentLayoutFragment == null) + currentLayoutFragment = getParentFragmentById( + moveFragmentId, page.getRootFragment()); + + if (currentLayoutFragment != null) + placement = new PortletPlacementContextImpl(page, registry, + currentLayoutFragment); else - placement = new PortletPlacementContextImpl( page, registry ); - + placement = new PortletPlacementContextImpl(page, registry); + Fragment fragment = placement.getFragmentById(moveFragmentId); - if ( fragment == null ) + if (fragment == null) { success = false; - resultMap.put( REASON, "Failed to find fragment for portlet id: " + moveFragmentId ); + resultMap.put(REASON, + "Failed to find fragment for portlet id: " + + moveFragmentId); return success; } - - success = moveInFragment( requestContext, placement, fragment, null, resultMap, batch ); + + success = moveInFragment(requestContext, placement, fragment, + null, resultMap, batch); } - if ( success ) + if (success) { - resultMap.put( STATUS, status ); + resultMap.put(STATUS, status); } } - catch ( Exception e ) + catch (Exception e) { // Log the exception - log.error( "exception while moving a portlet", e ); - resultMap.put( REASON, e.toString() ); + log.error("exception while moving a portlet", e); + resultMap.put(REASON, e.toString()); // Return a failure indicator success = false; } return success; } - - protected boolean moveInFragment( RequestContext requestContext, PortletPlacementContext placement, Fragment fragment, Fragment placeInLayoutFragment, Map resultMap, boolean batch ) - throws PortletPlacementException, NodeException, AJAXException + + protected boolean moveInFragment(RequestContext requestContext, + PortletPlacementContext placement, Fragment fragment, + Fragment placeInLayoutFragment, Map resultMap, boolean batch) + throws PortletPlacementException, NodeException, AJAXException { - boolean success = true; + boolean success = true; - String moveFragmentId = fragment.getId(); - boolean addFragment = (placeInLayoutFragment != null); + String moveFragmentId = fragment.getId(); + boolean addFragment = (placeInLayoutFragment != null); Coordinate returnCoordinate = null; float oldX = 0f, oldY = 0f, oldZ = 0f, oldWidth = 0f, oldHeight = 0f; float x = -1f, y = -1f, z = -1f, width = -1f, height = -1f; boolean absHeightChanged = false; // desktop extended - String posExtended = getActionParameter( requestContext, DESKTOP_EXTENDED ); - if ( posExtended != null ) + String posExtended = getActionParameter(requestContext, + DESKTOP_EXTENDED); + if (posExtended != null) { Map fragmentProperties = fragment.getProperties(); - if ( fragmentProperties == null ) + if (fragmentProperties == null) { success = false; - resultMap.put(REASON, "Failed to acquire fragment properties map for portlet id: " + moveFragmentId ); + resultMap.put(REASON, + "Failed to acquire fragment properties map for portlet id: " + + moveFragmentId); return success; } - String oldDeskExt = (String)fragmentProperties.get( DESKTOP_EXTENDED ); - resultMap.put( OLD_DESKTOP_EXTENDED, ( (oldDeskExt != null) ? oldDeskExt : "" ) ); - fragmentProperties.put( DESKTOP_EXTENDED, posExtended ); + String oldDeskExt = (String) fragmentProperties + .get(DESKTOP_EXTENDED); + resultMap.put(OLD_DESKTOP_EXTENDED, + ((oldDeskExt != null) ? oldDeskExt : "")); + fragmentProperties.put(DESKTOP_EXTENDED, posExtended); } - + // only required for moveabs - if ( iMoveType == ABS ) + if (iMoveType == ABS) { - Coordinate newCoordinate = getCoordinateFromParams( requestContext ); - returnCoordinate = placement.moveAbsolute( fragment, newCoordinate, addFragment ); - String sHeight = getActionParameter( requestContext, HEIGHT ); - if ( sHeight != null && sHeight.length() > 0 ) + Coordinate newCoordinate = getCoordinateFromParams(requestContext); + returnCoordinate = placement.moveAbsolute(fragment, newCoordinate, + addFragment); + String sHeight = getActionParameter(requestContext, HEIGHT); + if (sHeight != null && sHeight.length() > 0) { oldHeight = fragment.getLayoutHeight(); - height = Float.parseFloat( sHeight ); - fragment.setLayoutHeight( height ); + height = Float.parseFloat(sHeight); + fragment.setLayoutHeight(height); absHeightChanged = true; } - } - else if ( iMoveType == LEFT ) + } + else if (iMoveType == LEFT) { - returnCoordinate = placement.moveLeft( fragment ); - } - else if ( iMoveType == RIGHT ) + returnCoordinate = placement.moveLeft(fragment); + } + else if (iMoveType == RIGHT) { - returnCoordinate = placement.moveRight( fragment ); - } - else if ( iMoveType == UP ) + returnCoordinate = placement.moveRight(fragment); + } + else if (iMoveType == UP) { - returnCoordinate = placement.moveUp( fragment ); - } - else if ( iMoveType == DOWN ) + returnCoordinate = placement.moveUp(fragment); + } + else if (iMoveType == DOWN) { - returnCoordinate = placement.moveDown( fragment ); + returnCoordinate = placement.moveDown(fragment); } - else if ( iMoveType == CARTESIAN ) + else if (iMoveType == CARTESIAN) { - String sx = getActionParameter( requestContext, X ); - String sy = getActionParameter( requestContext, Y ); - String sz = getActionParameter( requestContext, Z ); - String sWidth = getActionParameter( requestContext, WIDTH ); - String sHeight = getActionParameter( requestContext, HEIGHT ); - if ( sx != null ) + String sx = getActionParameter(requestContext, X); + String sy = getActionParameter(requestContext, Y); + String sz = getActionParameter(requestContext, Z); + String sWidth = getActionParameter(requestContext, WIDTH); + String sHeight = getActionParameter(requestContext, HEIGHT); + if (sx != null) { oldX = fragment.getLayoutX(); - x = Float.parseFloat( sx ); - fragment.setLayoutX( x ); + x = Float.parseFloat(sx); + fragment.setLayoutX(x); } - if ( sy != null ) + if (sy != null) { - oldY = fragment.getLayoutY(); - y = Float.parseFloat( sy ); - fragment.setLayoutY( y ); - } - if ( sz != null ) + oldY = fragment.getLayoutY(); + y = Float.parseFloat(sy); + fragment.setLayoutY(y); + } + if (sz != null) { - oldZ = fragment.getLayoutZ(); - z = Float.parseFloat( sz ); - fragment.setLayoutZ( z ); - } - if ( sWidth != null ) + oldZ = fragment.getLayoutZ(); + z = Float.parseFloat(sz); + fragment.setLayoutZ(z); + } + if (sWidth != null) { - oldWidth = fragment.getLayoutWidth(); - width = Float.parseFloat( sWidth ); - fragment.setLayoutWidth( width ); + oldWidth = fragment.getLayoutWidth(); + width = Float.parseFloat(sWidth); + fragment.setLayoutWidth(width); } - if ( sHeight != null ) + if (sHeight != null) { - oldHeight = fragment.getLayoutHeight(); - height = Float.parseFloat( sHeight ); - fragment.setLayoutHeight( height ); + oldHeight = fragment.getLayoutHeight(); + height = Float.parseFloat(sHeight); + fragment.setLayoutHeight(height); } } - + // synchronize back to the page layout root fragment Page page = placement.syncPageFragments(); - - if ( placeInLayoutFragment != null ) + + if (placeInLayoutFragment != null) { - placeInLayoutFragment.getFragments().add( fragment ); + placeInLayoutFragment.getFragments().add(fragment); } - - if ( pageManager != null && ! batch ) + + if (pageManager != null && !batch) { - pageManager.updatePage( page ); + pageManager.updatePage(page); } - - if ( iMoveType == CARTESIAN ) + + if (iMoveType == CARTESIAN) { - putCartesianResult( resultMap, x, oldX, X, OLD_X ); - putCartesianResult( resultMap, y, oldY, Y, OLD_Y ); - putCartesianResult( resultMap, z, oldZ, Z, OLD_Z ); - putCartesianResult( resultMap, width, oldWidth, WIDTH, OLD_WIDTH ); - putCartesianResult( resultMap, height, oldHeight, HEIGHT, OLD_HEIGHT ); + putCartesianResult(resultMap, x, oldX, X, OLD_X); + putCartesianResult(resultMap, y, oldY, Y, OLD_Y); + putCartesianResult(resultMap, z, oldZ, Z, OLD_Z); + putCartesianResult(resultMap, width, oldWidth, WIDTH, OLD_WIDTH); + putCartesianResult(resultMap, height, oldHeight, HEIGHT, OLD_HEIGHT); } else { // Need to determine what the old col and row were - resultMap.put( OLDCOL, String.valueOf( returnCoordinate.getOldCol() ) ); - resultMap.put( OLDROW, String.valueOf( returnCoordinate.getOldRow() ) ); + resultMap.put(OLDCOL, String.valueOf(returnCoordinate.getOldCol())); + resultMap.put(OLDROW, String.valueOf(returnCoordinate.getOldRow())); // Need to determine what the new col and row were - resultMap.put( NEWCOL, String.valueOf( returnCoordinate.getNewCol() ) ); - resultMap.put( NEWROW, String.valueOf( returnCoordinate.getNewRow() ) ); - if ( absHeightChanged ) + resultMap.put(NEWCOL, String.valueOf(returnCoordinate.getNewCol())); + resultMap.put(NEWROW, String.valueOf(returnCoordinate.getNewRow())); + if (absHeightChanged) { - putCartesianResult( resultMap, height, oldHeight, HEIGHT, OLD_HEIGHT ); + putCartesianResult(resultMap, height, oldHeight, HEIGHT, + OLD_HEIGHT); } } - - resultMap.put( FRAGMENTID, moveFragmentId ); - + + resultMap.put(FRAGMENTID, moveFragmentId); + return success; } - protected boolean moveToOtherLayoutFragment( RequestContext requestContext, - boolean batch, - Map resultMap, - String moveFragmentId, - Fragment moveToLayoutFragment, - Fragment removeFromLayoutFragment ) - throws PortletPlacementException, NodeException, AJAXException + protected boolean moveToOtherLayoutFragment(RequestContext requestContext, + boolean batch, Map resultMap, String moveFragmentId, + Fragment moveToLayoutFragment, Fragment removeFromLayoutFragment) + throws PortletPlacementException, NodeException, AJAXException { boolean success = true; Fragment placeFragment = null; - if ( removeFromLayoutFragment != null ) + if (removeFromLayoutFragment != null) { - Page page = requestContext.getPage(); - PortletPlacementContext placement = new PortletPlacementContextImpl( page, registry, removeFromLayoutFragment ); - - placeFragment = placement.getFragmentById( moveFragmentId ); - if ( placeFragment == null ) + Page page = requestContext.getPage(); + PortletPlacementContext placement = new PortletPlacementContextImpl( + page, registry, removeFromLayoutFragment); + + placeFragment = placement.getFragmentById(moveFragmentId); + if (placeFragment == null) { success = false; - resultMap.put( REASON, "Failed to find fragment to move to another layout for fragment id: " + moveFragmentId ); + resultMap.put(REASON, + "Failed to find fragment to move to another layout for fragment id: " + + moveFragmentId); return success; } - placement.remove( placeFragment ); + placement.remove(placeFragment); page = placement.syncPageFragments(); - page.removeFragmentById( moveFragmentId ); + page.removeFragmentById(moveFragmentId); } - if ( placeFragment != null ) - { - return placeFragment( requestContext, - batch, - resultMap, - placeFragment, - moveToLayoutFragment ); - } + if (placeFragment != null) { return placeFragment(requestContext, + batch, resultMap, placeFragment, moveToLayoutFragment); } return success; } - protected boolean placeFragment( RequestContext requestContext, - boolean batch, - Map resultMap, - Fragment placeFragment, - Fragment placeInLayoutFragment ) - throws PortletPlacementException, NodeException, AJAXException + protected boolean placeFragment(RequestContext requestContext, + boolean batch, Map resultMap, Fragment placeFragment, + Fragment placeInLayoutFragment) throws PortletPlacementException, + NodeException, AJAXException { boolean success = true; - if ( placeFragment == null ) + if (placeFragment == null) { success = false; return success; } - + // add fragment Page page = requestContext.getPage(); - PortletPlacementContext placement = new PortletPlacementContextImpl( page, registry, placeInLayoutFragment ); - //placement.add( placeFragment, getCoordinateFromParams( requestContext ) ); - - success = moveInFragment( requestContext, placement, placeFragment, placeInLayoutFragment, resultMap, batch ); + PortletPlacementContext placement = new PortletPlacementContextImpl( + page, registry, placeInLayoutFragment); + // placement.add( placeFragment, getCoordinateFromParams( requestContext + // ) ); + success = moveInFragment(requestContext, placement, placeFragment, + placeInLayoutFragment, resultMap, batch); + return success; } - + protected Coordinate getCoordinateFromParams(RequestContext requestContext) { - String a_sCol = getActionParameter( requestContext, COL ); - String a_sRow = getActionParameter( requestContext, ROW ); + String a_sCol = getActionParameter(requestContext, COL); + String a_sRow = getActionParameter(requestContext, ROW); int a_iCol = 0; int a_iRow = 0; // Convert the col and row into integers - if ( a_sCol != null ) + if (a_sCol != null) { - a_iCol = Integer.parseInt( a_sCol ); + a_iCol = Integer.parseInt(a_sCol); } - if ( a_sRow != null ) + if (a_sRow != null) { - a_iRow = Integer.parseInt( a_sRow ); + a_iRow = Integer.parseInt(a_sRow); } - Coordinate a_oCoordinate = new CoordinateImpl( 0, 0, a_iCol, a_iRow ); + Coordinate a_oCoordinate = new CoordinateImpl(0, 0, a_iCol, a_iRow); return a_oCoordinate; } - protected void putCartesianResult(Map resultMap, float value, float oldValue, String name, String oldName) - { + protected void putCartesianResult(Map resultMap, float value, + float oldValue, String name, String oldName) + { if (value != -1F) { resultMap.put(oldName, new Float(oldValue)); resultMap.put(name, new Float(value)); } } - + protected PortletRegistry getPortletRegistry() { - return this.registry; + return this.registry; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/MultipleAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/MultipleAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/MultipleAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -80,8 +80,9 @@ protected VelocityEngine m_oVelocityEngine = null; - public MultipleAction(AjaxRequestService requestService, String p_sTemplate, - String p_sErrorTemplate, PageManager p_oPageManager, + public MultipleAction(AjaxRequestService requestService, + String p_sTemplate, String p_sErrorTemplate, + PageManager p_oPageManager, PortletActionSecurityBehavior p_oSecurityBehavior, VelocityEngine p_oVelocityEngine) { @@ -93,11 +94,12 @@ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - // get the proxied object for this, and put it in the map to avoid circular dep + // get the proxied object for this, and put it in the map to avoid + // circular dep Object proxy = beanFactory.getBean("AjaxMultipleAction"); - actionMap.put("multiple", proxy); + actionMap.put("multiple", proxy); } - + public boolean run(RequestContext p_oRequestContext, Map p_oResultMap) throws AJAXException { @@ -187,7 +189,8 @@ { a_bSuccess = a_oAction.runBatch(a_oJetspeedRequestContext, a_oResultMap); - } catch (Exception e) + } + catch (Exception e) { // Move the reason into the return map p_oResultMap.put(REASON, a_oResultMap.get(REASON)); @@ -231,7 +234,8 @@ // Save the results a_oResultArray.add(a_sBuildResults); } - } else + } + else { // Move the reason into the return map p_oResultMap.put(REASON, a_oResultMap.get(REASON)); @@ -262,7 +266,8 @@ { result = p_oBuilder .buildContext(p_oRequestContext, p_oInputMap); - } else + } + else { result = p_oBuilder.buildErrorContext(p_oRequestContext, p_oInputMap); @@ -279,7 +284,8 @@ if (p_oActionSuccessFlag == true) { a_sTemplateName = p_oBuilder.getTemplate(); - } else + } + else { a_sTemplateName = p_oBuilder.getErrorTemplate(); } @@ -302,11 +308,13 @@ // Save the results on the input map p_oInputMap.put(BUILD_RESULTS, a_sResults); - } else + } + else { log.error("could not create builder context"); } - } catch (Exception e) + } + catch (Exception e) { log.error("builder failed", e); p_oInputMap.put(Constants.REASON, e.toString()); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/NestedFragmentContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/NestedFragmentContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/NestedFragmentContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,8 +16,8 @@ */ package org.apache.jetspeed.layout.impl; +import java.util.ArrayList; import java.util.List; -import java.util.ArrayList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -25,21 +25,19 @@ import org.apache.jetspeed.layout.PortletPlacementException; import org.apache.jetspeed.om.page.Fragment; import org.apache.jetspeed.om.page.Page; + /** * NestedFragmentContext * - * This object captures the nested position of a fragment - * within a page. Given a target fragment and a page, - * the target fragment col/row within its parent is - * recorded, followed by the target fragment's parent - * col/row within its parent, etc. + * This object captures the nested position of a fragment within a page. Given a + * target fragment and a page, the target fragment col/row within its parent is + * recorded, followed by the target fragment's parent col/row within its parent, + * etc. * - * The purpose of this object is to support the - * create-new-page-on-edit feature. For example, when - * a fragment is moved, causing the creation of a new - * page, the information captured by this object - * allows the copy of the fragment in the new page to - * be located. + * The purpose of this object is to support the create-new-page-on-edit feature. + * For example, when a fragment is moved, causing the creation of a new page, + * the information captured by this object allows the copy of the fragment in + * the new page to be located. * * @author Steve Milek * @author Steve Milek @@ -47,173 +45,212 @@ */ public class NestedFragmentContext { - protected static final Log log = LogFactory.getLog( NestedFragmentContext.class ); - protected static final String eol = System.getProperty( "line.separator" ); - - private Fragment targetFragment; - private Fragment rootFragment; - private Page page; - private List fragmentLevels; - - public NestedFragmentContext( Fragment targetFragment, Page page, PortletRegistry registry ) - throws PortletPlacementException - { - this.targetFragment = targetFragment; - this.page = page; - this.rootFragment = page.getRootFragment(); - init( registry ); - } - - protected void init( PortletRegistry registry ) - throws PortletPlacementException - { - List nestedFragmentLevels = new ArrayList(); - Fragment nextTarget = targetFragment; - Fragment nextParent = null; - do - { - nextParent = NestedFragmentContext.getParentFragmentById( nextTarget.getId(), rootFragment ); - if ( nextParent != null ) - { - NestedFragmentLevel level = new NestedFragmentLevel( nextTarget, nextParent, registry ); - nestedFragmentLevels.add( level ); - - nextTarget = nextParent; - } - else - { - if ( ! nextTarget.getId().equals( rootFragment.getId() ) ) - { - throw new PortletPlacementException( "Cannot determine complete nested structure for fragment " + targetFragment.getId() ); - } - nextTarget = null; - } - } - while ( nextTarget != null ); - this.fragmentLevels = nestedFragmentLevels; - } - - public Fragment getFragmentOnNewPage( Page newPage, PortletRegistry registry ) - throws PortletPlacementException - { - Fragment newPageRootFragment = newPage.getRootFragment(); - - int depth = fragmentLevels.size(); - - Fragment nextFragment = newPageRootFragment; - for ( int i = depth -1; i >= 0 ; i-- ) - { - NestedFragmentLevel level = (NestedFragmentLevel)fragmentLevels.get(i); - PortletPlacementContextImpl placement = new PortletPlacementContextImpl( newPage, registry, nextFragment ); - try - { - nextFragment = placement.getFragmentAtOldCoordinate( new CoordinateImpl( level.getChildCol(), level.getChildRow() ) ); - - } - catch ( PortletPlacementException ppex ) - { - log.error( "getFragmentOnNewPage failure to locate fragment on new page (index=" + i + ") :" + eol + this.toString() + ( placement != null ? ( eol + placement.dumpFragments(null) ) : "" ) + eol, ppex ); - throw ppex; - } - catch ( RuntimeException ex ) - { - log.error( "getFragmentOnNewPage failure to locate fragment on new page (index=" + i + ") :" + eol + this.toString() + ( placement != null ? ( eol + placement.dumpFragments(null) ) : "" ) + eol, ex ); - throw ex; - } - if ( nextFragment == null ) - { - throw new PortletPlacementException( "Cannot locate copy of fragment " + targetFragment.getId() + " in the new page structure :" + eol + this.toString() + ( placement != null ? ( eol + placement.dumpFragments(null) ) : "" )); - } - } - return nextFragment; - } - - public String toString() - { - StringBuffer out = new StringBuffer(); - int depth = fragmentLevels.size(); - int ldepth = 0; - for ( int i = depth -1; i >= 0 ; i-- ) - { - NestedFragmentLevel level = (NestedFragmentLevel)fragmentLevels.get(i); - if ( ldepth > 0 ) - { - out.append( eol ); - for ( int j = 0 ; j < ldepth ; j++ ) - out.append( " " ); - } - ldepth++; - out.append( level.toString() ); - } - return out.toString(); - } - - class NestedFragmentLevel - { - private int childRow; - private int childCol; - private Fragment child; - private Fragment parent; - - NestedFragmentLevel( Fragment child, Fragment parent, PortletRegistry registry ) - throws PortletPlacementException - { - this.child = child; - this.parent = parent; - PortletPlacementContextImpl placement = new PortletPlacementContextImpl( page, registry, parent ); - this.childRow = placement.getFragmentRow( child ); - this.childCol = placement.getFragmentCol( child ); - } - - protected int getChildRow() - { - return this.childRow; - } - protected int getChildCol() - { - return this.childCol; - } - protected Fragment getChild() - { - return this.child; - } - protected Fragment getParent() - { - return this.parent; - } - public String toString() - { - return child.getType() + " col=" + childCol + " row=" + childRow + " id=" + child.getId() + " parent-id=" + parent.getId() ; - } - } - - public static Fragment getParentFragmentById( String id, Fragment parent ) - { - // find fragment by id, tracking fragment parent - if ( id == null ) + + protected static final Log log = LogFactory + .getLog(NestedFragmentContext.class); + + protected static final String eol = System.getProperty("line.separator"); + + private Fragment targetFragment; + + private Fragment rootFragment; + + private Page page; + + private List fragmentLevels; + + public NestedFragmentContext(Fragment targetFragment, Page page, + PortletRegistry registry) throws PortletPlacementException + { + this.targetFragment = targetFragment; + this.page = page; + this.rootFragment = page.getRootFragment(); + init(registry); + } + + protected void init(PortletRegistry registry) + throws PortletPlacementException + { + List nestedFragmentLevels = new ArrayList(); + Fragment nextTarget = targetFragment; + Fragment nextParent = null; + do { - return null; + nextParent = NestedFragmentContext.getParentFragmentById(nextTarget + .getId(), rootFragment); + if (nextParent != null) + { + NestedFragmentLevel level = new NestedFragmentLevel(nextTarget, + nextParent, registry); + nestedFragmentLevels.add(level); + + nextTarget = nextParent; + } + else + { + if (!nextTarget.getId().equals(rootFragment.getId())) { throw new PortletPlacementException( + "Cannot determine complete nested structure for fragment " + + targetFragment.getId()); } + nextTarget = null; + } + } while (nextTarget != null); + this.fragmentLevels = nestedFragmentLevels; + } + + public Fragment getFragmentOnNewPage(Page newPage, PortletRegistry registry) + throws PortletPlacementException + { + Fragment newPageRootFragment = newPage.getRootFragment(); + + int depth = fragmentLevels.size(); + + Fragment nextFragment = newPageRootFragment; + for (int i = depth - 1; i >= 0; i--) + { + NestedFragmentLevel level = (NestedFragmentLevel) fragmentLevels + .get(i); + PortletPlacementContextImpl placement = new PortletPlacementContextImpl( + newPage, registry, nextFragment); + try + { + nextFragment = placement + .getFragmentAtOldCoordinate(new CoordinateImpl(level + .getChildCol(), level.getChildRow())); + + } + catch (PortletPlacementException ppex) + { + log + .error( + "getFragmentOnNewPage failure to locate fragment on new page (index=" + + i + + ") :" + + eol + + this.toString() + + (placement != null ? (eol + placement + .dumpFragments(null)) : "") + + eol, ppex); + throw ppex; + } + catch (RuntimeException ex) + { + log.error( + "getFragmentOnNewPage failure to locate fragment on new page (index=" + + i + + ") :" + + eol + + this.toString() + + (placement != null ? (eol + placement + .dumpFragments(null)) : "") + eol, ex); + throw ex; + } + if (nextFragment == null) { throw new PortletPlacementException( + "Cannot locate copy of fragment " + + targetFragment.getId() + + " in the new page structure :" + + eol + + this.toString() + + (placement != null ? (eol + placement + .dumpFragments(null)) : "")); } } - - Fragment matchedParent = null; - if( parent != null ) + return nextFragment; + } + + public String toString() + { + StringBuffer out = new StringBuffer(); + int depth = fragmentLevels.size(); + int ldepth = 0; + for (int i = depth - 1; i >= 0; i--) { + NestedFragmentLevel level = (NestedFragmentLevel) fragmentLevels + .get(i); + if (ldepth > 0) + { + out.append(eol); + for (int j = 0; j < ldepth; j++) + out.append(" "); + } + ldepth++; + out.append(level.toString()); + } + return out.toString(); + } + + class NestedFragmentLevel + { + + private int childRow; + + private int childCol; + + private Fragment child; + + private Fragment parent; + + NestedFragmentLevel(Fragment child, Fragment parent, + PortletRegistry registry) throws PortletPlacementException + { + this.child = child; + this.parent = parent; + PortletPlacementContextImpl placement = new PortletPlacementContextImpl( + page, registry, parent); + this.childRow = placement.getFragmentRow(child); + this.childCol = placement.getFragmentCol(child); + } + + protected int getChildRow() + { + return this.childRow; + } + + protected int getChildCol() + { + return this.childCol; + } + + protected Fragment getChild() + { + return this.child; + } + + protected Fragment getParent() + { + return this.parent; + } + + public String toString() + { + return child.getType() + " col=" + childCol + " row=" + childRow + + " id=" + child.getId() + " parent-id=" + parent.getId(); + } + } + + public static Fragment getParentFragmentById(String id, Fragment parent) + { + // find fragment by id, tracking fragment parent + if (id == null) { return null; } + + Fragment matchedParent = null; + if (parent != null) + { // process the children List children = parent.getFragments(); - for( int i = 0, cSize = children.size() ; i < cSize ; i++) + for (int i = 0, cSize = children.size(); i < cSize; i++) { - Fragment childFrag = (Fragment)children.get( i ); - if ( childFrag != null ) + Fragment childFrag = (Fragment) children.get(i); + if (childFrag != null) { - if ( id.equals( childFrag.getId() ) ) + if (id.equals(childFrag.getId())) { matchedParent = parent; break; } else { - matchedParent = NestedFragmentContext.getParentFragmentById( id, childFrag ); - if ( matchedParent != null ) + matchedParent = NestedFragmentContext + .getParentFragmentById(id, childFrag); + if (matchedParent != null) { break; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletActionSecurityConstraintsBehavior.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletActionSecurityConstraintsBehavior.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletActionSecurityConstraintsBehavior.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,24 +29,29 @@ /** * Abstracted behavior of security checks for portlet actions - * + * * @author David Sean Taylor * @version $Id: $ */ -public class PortletActionSecurityConstraintsBehavior - extends PortletActionSecurityPathBehavior - implements PortletActionSecurityBehavior +public class PortletActionSecurityConstraintsBehavior extends + PortletActionSecurityPathBehavior implements + PortletActionSecurityBehavior { - protected Log log = LogFactory.getLog(PortletActionSecurityConstraintsBehavior.class); + + protected Log log = LogFactory + .getLog(PortletActionSecurityConstraintsBehavior.class); + protected String guest = "guest"; - + public PortletActionSecurityConstraintsBehavior(PageManager pageManager) { - this( pageManager, Boolean.FALSE ); + this(pageManager, Boolean.FALSE); } - public PortletActionSecurityConstraintsBehavior(PageManager pageManager, Boolean enableCreateUserPagesFromRolesOnEdit ) + + public PortletActionSecurityConstraintsBehavior(PageManager pageManager, + Boolean enableCreateUserPagesFromRolesOnEdit) { - super( pageManager, enableCreateUserPagesFromRolesOnEdit ); + super(pageManager, enableCreateUserPagesFromRolesOnEdit); PortalConfiguration config = Jetspeed.getConfiguration(); if (config != null) { @@ -59,17 +64,17 @@ Page page = context.getPage(); try { - page.checkAccess(action); + page.checkAccess(action); } catch (Exception e) { Principal principal = context.getRequest().getUserPrincipal(); String userName = this.guest; - if (principal != null) - userName = principal.getName(); - log.warn("Insufficient access to page " + page.getPath() + " by user " + userName); + if (principal != null) userName = principal.getName(); + log.warn("Insufficient access to page " + page.getPath() + + " by user " + userName); return false; - } + } return true; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletActionSecurityPathBehavior.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletActionSecurityPathBehavior.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletActionSecurityPathBehavior.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,80 +29,91 @@ /** * Abstracted behavior of security checks for portlet actions - * + * * @author David Sean Taylor * @version $Id: $ */ -public class PortletActionSecurityPathBehavior implements PortletActionSecurityBehavior +public class PortletActionSecurityPathBehavior implements + PortletActionSecurityBehavior { - protected Log log = LogFactory.getLog(PortletActionSecurityPathBehavior.class); + + protected Log log = LogFactory + .getLog(PortletActionSecurityPathBehavior.class); + protected PageManager pageManager; + private boolean enableCreateUserPagesFromRolesOnEdit; - - public PortletActionSecurityPathBehavior(PageManager pageManager ) + + public PortletActionSecurityPathBehavior(PageManager pageManager) { - this( pageManager, Boolean.FALSE ) ; + this(pageManager, Boolean.FALSE); } - public PortletActionSecurityPathBehavior(PageManager pageManager, Boolean enableCreateUserPagesFromRolesOnEdit ) + + public PortletActionSecurityPathBehavior(PageManager pageManager, + Boolean enableCreateUserPagesFromRolesOnEdit) { this.pageManager = pageManager; - this.enableCreateUserPagesFromRolesOnEdit = ( enableCreateUserPagesFromRolesOnEdit == null ? false : enableCreateUserPagesFromRolesOnEdit.booleanValue() ); + this.enableCreateUserPagesFromRolesOnEdit = (enableCreateUserPagesFromRolesOnEdit == null ? false + : enableCreateUserPagesFromRolesOnEdit.booleanValue()); } public boolean checkAccess(RequestContext context, String action) { Page page = context.getPage(); String path = page.getPath(); - if (path == null) - return false; - if (path.indexOf(Folder.ROLE_FOLDER) > -1 || path.indexOf(Folder.GROUP_FOLDER) > -1) + if (path == null) return false; + if (path.indexOf(Folder.ROLE_FOLDER) > -1 + || path.indexOf(Folder.GROUP_FOLDER) > -1) { - if (action.equals(JetspeedActions.VIEW)) - return true; + if (action.equals(JetspeedActions.VIEW)) return true; return false; } return true; } - + public boolean isCreateNewPageOnEditEnabled() { - return enableCreateUserPagesFromRolesOnEdit; + return enableCreateUserPagesFromRolesOnEdit; } + public boolean isPageQualifiedForCreateNewPageOnEdit(RequestContext context) { - if ( ! this.enableCreateUserPagesFromRolesOnEdit || context == null ) - return false ; - return isPageQualifiedForCreateNewPageOnEdit( context.getPage().getPath() ); + if (!this.enableCreateUserPagesFromRolesOnEdit || context == null) + return false; + return isPageQualifiedForCreateNewPageOnEdit(context.getPage() + .getPath()); } - - protected boolean isPageQualifiedForCreateNewPageOnEdit( String pagePath ) + + protected boolean isPageQualifiedForCreateNewPageOnEdit(String pagePath) { - if (pagePath == null) - return false; + if (pagePath == null) return false; // page must be in role directory return (pagePath.indexOf(Folder.ROLE_FOLDER) == 0); } public boolean createNewPageOnEdit(RequestContext context) { - if ( ! this.enableCreateUserPagesFromRolesOnEdit ) - return false ; + if (!this.enableCreateUserPagesFromRolesOnEdit) return false; - Page page = context.getPage(); + Page page = context.getPage(); String pagePath = page.getPath(); try { - if ( isPageQualifiedForCreateNewPageOnEdit( pagePath ) ) + if (isPageQualifiedForCreateNewPageOnEdit(pagePath)) { - String pageName = page.getName(); - this.pageManager.createUserHomePagesFromRoles(context.getSubject()); - page = this.pageManager.getPage(Folder.USER_FOLDER - + context.getRequest().getUserPrincipal().getName() - + Folder.PATH_SEPARATOR - + pageName); // was Folder.FALLBACK_DEFAULT_PAGE prior to 2007-11-06 + String pageName = page.getName(); + this.pageManager.createUserHomePagesFromRoles(context + .getSubject()); + page = this.pageManager.getPage(Folder.USER_FOLDER + + context.getRequest().getUserPrincipal().getName() + + Folder.PATH_SEPARATOR + pageName); // was + // Folder.FALLBACK_DEFAULT_PAGE + // prior to + // 2007-11-06 context.setPage(new ContentPageImpl(page)); - context.getRequest().getSession().removeAttribute(ProfilerValveImpl.PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY); - } + context.getRequest().getSession().removeAttribute( + ProfilerValveImpl.PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY); + } } catch (Exception e) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletActionSecurityPathMergeBehavior.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletActionSecurityPathMergeBehavior.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletActionSecurityPathMergeBehavior.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,50 +33,55 @@ import org.apache.jetspeed.security.impl.RolePrincipalImpl; /** - * Abstracted behavior of security checks when used with the - * profiling rule "user-rolecombo". This behavior merges - * all roles into a single role combo. - * + * Abstracted behavior of security checks when used with the profiling rule + * "user-rolecombo". This behavior merges all roles into a single role combo. + * * @author David Sean Taylor * @version $Id: $ */ -public class PortletActionSecurityPathMergeBehavior - extends PortletActionSecurityPathBehavior - implements PortletActionSecurityBehavior +public class PortletActionSecurityPathMergeBehavior extends + PortletActionSecurityPathBehavior implements + PortletActionSecurityBehavior { - protected Log log = LogFactory.getLog(PortletActionSecurityPathMergeBehavior.class); - - public PortletActionSecurityPathMergeBehavior( PageManager pageManager ) + + protected Log log = LogFactory + .getLog(PortletActionSecurityPathMergeBehavior.class); + + public PortletActionSecurityPathMergeBehavior(PageManager pageManager) { - this( pageManager, Boolean.FALSE ); + this(pageManager, Boolean.FALSE); } - public PortletActionSecurityPathMergeBehavior( PageManager pageManager, Boolean enableCreateUserPagesFromRolesOnEdit ) + + public PortletActionSecurityPathMergeBehavior(PageManager pageManager, + Boolean enableCreateUserPagesFromRolesOnEdit) { - super( pageManager, enableCreateUserPagesFromRolesOnEdit ); + super(pageManager, enableCreateUserPagesFromRolesOnEdit); } public Subject getSubject(RequestContext context) { Subject currentSubject = context.getSubject(); - Iterator roles = currentSubject.getPrincipals(RolePrincipalImpl.class).iterator(); + Iterator roles = currentSubject.getPrincipals(RolePrincipalImpl.class) + .iterator(); StringBuffer combo = new StringBuffer(); int count = 0; while (roles.hasNext()) { - RolePrincipal role = (RolePrincipal)roles.next(); + RolePrincipal role = (RolePrincipal) roles.next(); if (count > 0) { combo.append("-"); } combo.append(role.getName()); - count++; + count++; } Set principals = new HashSet(); - principals.add(SecurityHelper.getBestPrincipal(currentSubject, UserPrincipal.class)); + principals.add(SecurityHelper.getBestPrincipal(currentSubject, + UserPrincipal.class)); principals.add(new RolePrincipalImpl(combo.toString())); - Subject subject = - new Subject(true, principals, new HashSet(), new HashSet()); + Subject subject = new Subject(true, principals, new HashSet(), + new HashSet()); return subject; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletInfo.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletInfo.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletInfo.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,25 +18,31 @@ /** * Portlet Info populated into AJAX XML response per portlet - * + * * @author David Gurney * @author David Sean Taylor * @version $Id: $ */ -public class PortletInfo +public class PortletInfo { + private String name; + private String displayName; + private String description; + private String image; - - public PortletInfo(String name, String displayName, String description, String image) + + public PortletInfo(String name, String displayName, String description, + String image) { this.name = name; this.displayName = displayName; this.description = description; this.image = image; } + /** * @return Returns the description. */ @@ -44,6 +50,7 @@ { return description; } + /** * @return Returns the displayName. */ @@ -51,6 +58,7 @@ { return displayName; } + /** * @return Returns the name. */ @@ -58,7 +66,7 @@ { return name; } - + /** * @return Returns the image. */ @@ -66,9 +74,10 @@ { return image; } - + /** - * @param image The image to set. + * @param image + * The image to set. */ public void setImage(String image) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletPlacementContextImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletPlacementContextImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/PortletPlacementContextImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,888 +16,1005 @@ */ package org.apache.jetspeed.layout.impl; +import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; -import java.util.ArrayList; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jetspeed.components.portletregistry.PortletRegistry; import org.apache.jetspeed.layout.Coordinate; +import org.apache.jetspeed.layout.PortletPlacementContext; import org.apache.jetspeed.layout.PortletPlacementException; -import org.apache.jetspeed.layout.PortletPlacementContext; import org.apache.jetspeed.om.page.Fragment; import org.apache.jetspeed.om.page.Page; import org.apache.pluto.om.common.Parameter; import org.apache.pluto.om.common.ParameterSet; import org.apache.pluto.om.portlet.PortletDefinition; - /** * Portal Placement Context * - * The purpose of the object is to provide an API that - * can be used to move a portlet fragment on the page. - * This includes moving, adding, removing and getting - * information about portlets that are on the page and - * portlets that are available to be added to the page. + * The purpose of the object is to provide an API that can be used to move a + * portlet fragment on the page. This includes moving, adding, removing and + * getting information about portlets that are on the page and portlets that are + * available to be added to the page. * - * This object represents the fragment contents of a - * single layout fragment (i.e. nested depth cannot - * be captured by this object). + * This object represents the fragment contents of a single layout fragment + * (i.e. nested depth cannot be captured by this object). * - * An important note about this object: - * This object is really only intended to be used to do - * a single operation such as "moveabs" or "add". After - * performing the operation, the hashmap data structures - * are not correct and should not be used for subsequent - * operations. The reason they are incorrect is that when - * a fragment is moved, the coordinate of fragments below - * it are now different. These could be updated, but it - * really doesn't serve a purpose since this is a short - * lived object. + * An important note about this object: This object is really only intended to + * be used to do a single operation such as "moveabs" or "add". After performing + * the operation, the hashmap data structures are not correct and should not be + * used for subsequent operations. The reason they are incorrect is that when a + * fragment is moved, the coordinate of fragments below it are now different. + * These could be updated, but it really doesn't serve a purpose since this is a + * short lived object. * * @author David Gurney * @author David Sean Taylor * @author Steve Milek * @version $Id: $ */ -public class PortletPlacementContextImpl implements PortletPlacementContext +public class PortletPlacementContextImpl implements PortletPlacementContext { - private static Log log = LogFactory.getLog( PortletPlacementContextImpl.class ); - protected static final String eol = System.getProperty( "line.separator" ); - // Columns are reference by index, the rows are held - // in the columnsList as shown below: - // - // [0] [1] [2] - // ArrayList ArrayList ArrayList - // Row0Frag Row0Frag Row0Frag - // Row1Frag Row1Frag Row1Frag - // Row2Frag Row2Frag Row2Frag - // ... - // - protected ArrayList[] columnsList = null; - - // Used as a convience when looking up a particular fragment - // - // key is Fragment id (String), value is a Coordinate object - protected Map fragmentCoordinateMap = new HashMap(); - - // Used as a convience when looking up a particular fragment by id - // - // key is the Fragment id (String), value is the Fragment - protected Map fragmentMap = new HashMap(); - - // Number of columns - protected int numberOfColumns = -1; - + private static Log log = LogFactory + .getLog(PortletPlacementContextImpl.class); + + protected static final String eol = System.getProperty("line.separator"); + + // Columns are reference by index, the rows are held + // in the columnsList as shown below: + // + // [0] [1] [2] + // ArrayList ArrayList ArrayList + // Row0Frag Row0Frag Row0Frag + // Row1Frag Row1Frag Row1Frag + // Row2Frag Row2Frag Row2Frag + // ... + // + protected ArrayList[] columnsList = null; + + // Used as a convience when looking up a particular fragment + // + // key is Fragment id (String), value is a Coordinate object + protected Map fragmentCoordinateMap = new HashMap(); + + // Used as a convience when looking up a particular fragment by id + // + // key is the Fragment id (String), value is the Fragment + protected Map fragmentMap = new HashMap(); + + // Number of columns + protected int numberOfColumns = -1; + protected Page page; + private PortletRegistry registry; + protected Fragment layoutContainerFragment; - - public PortletPlacementContextImpl( Page page, PortletRegistry registry ) - throws PortletPlacementException + + public PortletPlacementContextImpl(Page page, PortletRegistry registry) + throws PortletPlacementException { - this( page, registry, null ); - } - - public PortletPlacementContextImpl( Page page, PortletRegistry registry, Fragment container ) - throws PortletPlacementException + this(page, registry, null); + } + + public PortletPlacementContextImpl(Page page, PortletRegistry registry, + Fragment container) throws PortletPlacementException { - if ( page == null ) - throw new NullPointerException( "PortletPlacementContext cannot be instantiated with a null Page argument" ); - if ( registry == null ) - throw new NullPointerException( "PortletPlacementContext cannot be instantiated with a null PortletRegistry argument" ); - - this.page = page; - this.registry = registry; - - init( container ); + if (page == null) + throw new NullPointerException( + "PortletPlacementContext cannot be instantiated with a null Page argument"); + if (registry == null) + throw new NullPointerException( + "PortletPlacementContext cannot be instantiated with a null PortletRegistry argument"); + + this.page = page; + this.registry = registry; + + init(container); } - - protected void init( Fragment container ) - throws PortletPlacementException + + protected void init(Fragment container) throws PortletPlacementException { - if ( container == null ) + if (container == null) { container = page.getRootFragment(); - if ( container == null ) - throw new PortletPlacementException( "PortletPlacementContext cannot acquire root layout fragment from page" ); - } - if ( ! "layout".equals( container.getType() ) ) - { - throw new PortletPlacementException( "PortletPlacementContext specified container fragment (" + container.getId() + ") is not a layout fragment, but is type: " + container.getType() ); + if (container == null) + throw new PortletPlacementException( + "PortletPlacementContext cannot acquire root layout fragment from page"); } + if (!"layout".equals(container.getType())) { throw new PortletPlacementException( + "PortletPlacementContext specified container fragment (" + + container.getId() + + ") is not a layout fragment, but is type: " + + container.getType()); } this.layoutContainerFragment = container; - - int columnCount = PortletPlacementContextImpl.getColumnCountAndSizes( container, registry, null ); - if ( columnCount <= 0 ) - { - throw new PortletPlacementException( "PortletPlacementContext cannot detemine number of columns in layout fragment (" + container.getId() + ")" ); - } + + int columnCount = PortletPlacementContextImpl.getColumnCountAndSizes( + container, registry, null); + if (columnCount <= 0) { throw new PortletPlacementException( + "PortletPlacementContext cannot detemine number of columns in layout fragment (" + + container.getId() + ")"); } this.numberOfColumns = columnCount; - + initProcessLayoutContainerFragment(); - - //debugFragments( "init" ); - } - - private void initProcessLayoutContainerFragment() - throws PortletPlacementException + + // debugFragments( "init" ); + } + + private void initProcessLayoutContainerFragment() + throws PortletPlacementException { List fragChildren = this.layoutContainerFragment.getFragments(); int fragChildCount = fragChildren.size(); - + int columnCount = this.numberOfColumns; - - // sort the fragments in the same manner as /portal and /desktop rendering + + // sort the fragments in the same manner as /portal and /desktop + // rendering FragmentLinkedListEntry[][] colLinkedLists = new FragmentLinkedListEntry[columnCount][fragChildCount]; FragmentLinkedListInfo[] colLinkedListsInfo = new FragmentLinkedListInfo[columnCount]; - for ( int colIndex = 0 ; colIndex < columnCount ; colIndex++ ) + for (int colIndex = 0; colIndex < columnCount; colIndex++) { - colLinkedListsInfo[ colIndex ] = new FragmentLinkedListInfo(); + colLinkedListsInfo[colIndex] = new FragmentLinkedListInfo(); } - for( int fragChildIndex = 0; fragChildIndex < fragChildCount; fragChildIndex++ ) + for (int fragChildIndex = 0; fragChildIndex < fragChildCount; fragChildIndex++) { - Fragment fragment = (Fragment)fragChildren.get( fragChildIndex ); - if ( fragment != null ) + Fragment fragment = (Fragment) fragChildren.get(fragChildIndex); + if (fragment != null) { - int col = getColumnFromFragment( fragment ); - - FragmentLinkedListEntry[] ll = colLinkedLists[col]; - FragmentLinkedListInfo llInfo = colLinkedListsInfo[col]; - - Integer rowObj = getRowFromFragment( fragment ); - int row; - if ( rowObj != null ) - row = rowObj.intValue(); - else - row = llInfo.getHigh() + 1; // fragment with unspecified row property is assigned - // the value of current fragment in the highest row + 1 - // - this is one of the reasons we are not using sort here - - FragmentLinkedListEntry fragLLentry = new FragmentLinkedListEntry( fragChildIndex, row ); - int llLen = llInfo.useNextAvailableIndex(); - ll[ llLen ] = fragLLentry; - if ( llLen == 0 ) - { - llInfo.setHead( 0 ); - llInfo.setTail( 0 ); - llInfo.setHigh( row ); - } - else - { - if ( row > llInfo.getHigh() ) - { - ll[ llInfo.getTail() ].setNextEntry( llLen ); - llInfo.setHigh( row ); - llInfo.setTail( llLen ); - } - else - { - int llEntryIndex = llInfo.getHead(); - int llPrevEntryIndex = -1; - while ( ll[llEntryIndex].getRow() < row ) - { - llPrevEntryIndex = llEntryIndex; - llEntryIndex = ll[llEntryIndex].getNextEntry(); - } - if ( ll[llEntryIndex].getRow() == row ) - { // a subsequent fragment (in the document) with a row value equal to that - // of a previous fragment is inserted before the previous fragment - // - this is one of the reasons we are not using sort here - int incrementedRow = row + 1; - ll[llEntryIndex].setRow( incrementedRow ); - if ( llInfo.getTail() == llEntryIndex ) - llInfo.setHigh( incrementedRow ); - } - fragLLentry.setNextEntry( llEntryIndex ); - if ( llPrevEntryIndex == -1 ) - llInfo.setHead( llLen ); - else - ll[llPrevEntryIndex].setNextEntry( llLen ); - } - } + int col = getColumnFromFragment(fragment); + + FragmentLinkedListEntry[] ll = colLinkedLists[col]; + FragmentLinkedListInfo llInfo = colLinkedListsInfo[col]; + + Integer rowObj = getRowFromFragment(fragment); + int row; + if (rowObj != null) + row = rowObj.intValue(); + else + row = llInfo.getHigh() + 1; // fragment with unspecified row + // property is assigned + // the value of current fragment in the highest row + 1 + // - this is one of the reasons we are not using sort here + + FragmentLinkedListEntry fragLLentry = new FragmentLinkedListEntry( + fragChildIndex, row); + int llLen = llInfo.useNextAvailableIndex(); + ll[llLen] = fragLLentry; + if (llLen == 0) + { + llInfo.setHead(0); + llInfo.setTail(0); + llInfo.setHigh(row); + } + else + { + if (row > llInfo.getHigh()) + { + ll[llInfo.getTail()].setNextEntry(llLen); + llInfo.setHigh(row); + llInfo.setTail(llLen); + } + else + { + int llEntryIndex = llInfo.getHead(); + int llPrevEntryIndex = -1; + while (ll[llEntryIndex].getRow() < row) + { + llPrevEntryIndex = llEntryIndex; + llEntryIndex = ll[llEntryIndex].getNextEntry(); + } + if (ll[llEntryIndex].getRow() == row) + { // a subsequent fragment (in the document) with a + // row value equal to that + // of a previous fragment is inserted before the + // previous fragment + // - this is one of the reasons we are not using + // sort here + int incrementedRow = row + 1; + ll[llEntryIndex].setRow(incrementedRow); + if (llInfo.getTail() == llEntryIndex) + llInfo.setHigh(incrementedRow); + } + fragLLentry.setNextEntry(llEntryIndex); + if (llPrevEntryIndex == -1) + llInfo.setHead(llLen); + else + ll[llPrevEntryIndex].setNextEntry(llLen); + } + } } } - ArrayList[] columnFragments = new ArrayList[ columnCount ]; - for ( int colIndex = 0 ; colIndex < columnCount ; colIndex++ ) + ArrayList[] columnFragments = new ArrayList[columnCount]; + for (int colIndex = 0; colIndex < columnCount; colIndex++) { - ArrayList fragmentsInColumn = new ArrayList(); - columnFragments[ colIndex ] = fragmentsInColumn; - - FragmentLinkedListEntry[] ll = colLinkedLists[colIndex]; - FragmentLinkedListInfo llInfo = colLinkedListsInfo[colIndex]; - - int rowIndex = 0; + ArrayList fragmentsInColumn = new ArrayList(); + columnFragments[colIndex] = fragmentsInColumn; + + FragmentLinkedListEntry[] ll = colLinkedLists[colIndex]; + FragmentLinkedListInfo llInfo = colLinkedListsInfo[colIndex]; + + int rowIndex = 0; int nextEntryIndex = llInfo.getHead(); - while ( nextEntryIndex != -1 ) + while (nextEntryIndex != -1) { FragmentLinkedListEntry fragLLentry = ll[nextEntryIndex]; - Fragment fragment = (Fragment)fragChildren.get( fragLLentry.getFragmentIndex() ); - - fragmentsInColumn.add( fragment ); - CoordinateImpl coordinate = new CoordinateImpl( colIndex, rowIndex ); - this.fragmentCoordinateMap.put( fragment.getId(), coordinate ); - this.fragmentMap.put( fragment.getId(), fragment ); - + Fragment fragment = (Fragment) fragChildren.get(fragLLentry + .getFragmentIndex()); + + fragmentsInColumn.add(fragment); + CoordinateImpl coordinate = new CoordinateImpl(colIndex, + rowIndex); + this.fragmentCoordinateMap.put(fragment.getId(), coordinate); + this.fragmentMap.put(fragment.getId(), fragment); + nextEntryIndex = fragLLentry.getNextEntry(); - rowIndex++; + rowIndex++; } } this.columnsList = columnFragments; - } - - private int getColumnFromFragment( Fragment fragment ) - { - // get column value in the same manner as /portal and /desktop rendering - - // get column from properties to distinguish between null and -1 (fragment.getLayoutColumn() is -1 when column is not specified) - String colStr = (String)fragment.getProperties().get( "column" ); + } + + private int getColumnFromFragment(Fragment fragment) + { + // get column value in the same manner as /portal and /desktop rendering + + // get column from properties to distinguish between null and -1 + // (fragment.getLayoutColumn() is -1 when column is not specified) + String colStr = (String) fragment.getProperties().get("column"); int columnCount = this.numberOfColumns; - int col = columnCount - 1; - if ( colStr != null ) - { - try - { - col = Integer.parseInt( colStr ); - if ( col < 0 ) - col = 0; - else if ( col >= columnCount ) - col = columnCount - 1; - } - catch ( NumberFormatException ex ) - { - col = columnCount - 1; - } - } - return col; - } - private Integer getRowFromFragment( Fragment fragment ) - { - // get row value in the same manner as /portal and /desktop rendering - - // get row from properties to distinguish between null and -1 (fragment.getLayoutRow() is -1 when row is not specified) - String rowStr = (String)fragment.getProperties().get( "row" ); - if ( rowStr != null ) - { - try - { - int row = Integer.parseInt( rowStr ); - if ( row < 0 ) - row = 0; - return new Integer( row ); - } - catch ( NumberFormatException ex ) - { - } - } - return null; - } - - private int normalizeColumnIndex( int col, ArrayList[] columnFragments, int defaultForUnspecifiedCol ) - { - int columnCount = this.numberOfColumns; - if ( col >= columnCount ) - col = (columnCount -1); - else if ( col < 0 && defaultForUnspecifiedCol >= 0 && defaultForUnspecifiedCol < columnCount ) - col = defaultForUnspecifiedCol; - else if ( col < 0 ) - col = 0; - return col; - } + int col = columnCount - 1; + if (colStr != null) + { + try + { + col = Integer.parseInt(colStr); + if (col < 0) + col = 0; + else if (col >= columnCount) col = columnCount - 1; + } + catch (NumberFormatException ex) + { + col = columnCount - 1; + } + } + return col; + } - class FragmentLinkedListInfo - { - private int head = -1; - private int tail = -1; - private int high = -1; - private int availableNextIndex = 0; - - FragmentLinkedListInfo() - { - } - - public int getHead() - { - return head; + private Integer getRowFromFragment(Fragment fragment) + { + // get row value in the same manner as /portal and /desktop rendering + + // get row from properties to distinguish between null and -1 + // (fragment.getLayoutRow() is -1 when row is not specified) + String rowStr = (String) fragment.getProperties().get("row"); + if (rowStr != null) + { + try + { + int row = Integer.parseInt(rowStr); + if (row < 0) row = 0; + return new Integer(row); + } + catch (NumberFormatException ex) + { + } } - public void setHead( int newOne ) - { - this.head = newOne; + return null; + } + + private int normalizeColumnIndex(int col, ArrayList[] columnFragments, + int defaultForUnspecifiedCol) + { + int columnCount = this.numberOfColumns; + if (col >= columnCount) + col = (columnCount - 1); + else if (col < 0 && defaultForUnspecifiedCol >= 0 + && defaultForUnspecifiedCol < columnCount) + col = defaultForUnspecifiedCol; + else if (col < 0) col = 0; + return col; + } + + class FragmentLinkedListInfo + { + + private int head = -1; + + private int tail = -1; + + private int high = -1; + + private int availableNextIndex = 0; + + FragmentLinkedListInfo() + { } - public int getTail() - { - return tail; + + public int getHead() + { + return head; } - public void setTail( int newOne ) - { - this.tail = newOne; + + public void setHead(int newOne) + { + this.head = newOne; } - public int getHigh() - { - return high; + + public int getTail() + { + return tail; } - public void setHigh( int newOne ) - { - this.high = newOne; + + public void setTail(int newOne) + { + this.tail = newOne; } - public int useNextAvailableIndex() - { - return this.availableNextIndex++; - } - } - - class FragmentLinkedListEntry - { - private int fragmentIndex; - private int row; - private int nextEntry = -1; - - FragmentLinkedListEntry( int fragmentIndex, int row ) - { - this.fragmentIndex = fragmentIndex; - this.row = row; - } - - public int getFragmentIndex() - { - return this.fragmentIndex; - } - public int getRow() - { - return this.row; - } - public void setRow( int newOne ) - { - this.row = newOne; - } - public int getNextEntry() - { - return this.nextEntry; - } - public void setNextEntry( int newOne ) - { - this.nextEntry = newOne; - } - } - - public String dumpFragments( String debug ) - { + + public int getHigh() + { + return high; + } + + public void setHigh(int newOne) + { + this.high = newOne; + } + + public int useNextAvailableIndex() + { + return this.availableNextIndex++; + } + } + + class FragmentLinkedListEntry + { + + private int fragmentIndex; + + private int row; + + private int nextEntry = -1; + + FragmentLinkedListEntry(int fragmentIndex, int row) + { + this.fragmentIndex = fragmentIndex; + this.row = row; + } + + public int getFragmentIndex() + { + return this.fragmentIndex; + } + + public int getRow() + { + return this.row; + } + + public void setRow(int newOne) + { + this.row = newOne; + } + + public int getNextEntry() + { + return this.nextEntry; + } + + public void setNextEntry(int newOne) + { + this.nextEntry = newOne; + } + } + + public String dumpFragments(String debug) + { StringBuffer out = new StringBuffer(); - out.append( "PortletPlacementContext - " ); - if ( debug != null ) - out.append( debug ).append( " - " ); - out.append( "container: " ).append( this.layoutContainerFragment == null ? "" : ( this.layoutContainerFragment.getId() + " / " + this.layoutContainerFragment.getType() ) ).append( " column-count=" ).append( this.numberOfColumns ).append( eol ); + out.append("PortletPlacementContext - "); + if (debug != null) out.append(debug).append(" - "); + out + .append("container: ") + .append( + this.layoutContainerFragment == null ? "" + : (this.layoutContainerFragment.getId() + " / " + this.layoutContainerFragment + .getType())).append(" column-count=") + .append(this.numberOfColumns).append(eol); for (int ix = 0; ix < this.columnsList.length; ix++) { ArrayList column = this.columnsList[ix]; - out.append( " column " ).append( ix ).append( eol ); + out.append(" column ").append(ix).append(eol); Iterator frags = column.iterator(); - while ( frags.hasNext() ) + while (frags.hasNext()) { - Fragment f = (Fragment)frags.next(); - out.append( " frag " ).append( f == null ? "" : ( f.getId() + " / " + f.getType() ) ).append( eol ); + Fragment f = (Fragment) frags.next(); + out.append(" frag ").append( + f == null ? "" + : (f.getId() + " / " + f.getType())) + .append(eol); } } return out.toString(); } - public Fragment debugFragments( String debug ) + + public Fragment debugFragments(String debug) { - log.info( dumpFragments( debug ) ); + log.info(dumpFragments(debug)); return layoutContainerFragment; } /** - * Takes the internal portlet placement state and stores back - * out to fragment state + * Takes the internal portlet placement state and stores back out to + * fragment state * - * @return the managed page layout with updated fragment state. + * @return the managed page layout with updated fragment state. */ public Page syncPageFragments() { - syncFragments( true, -1 ); - //debugFragments( "syncPage" ); - return this.page; + syncFragments(true, -1); + // debugFragments( "syncPage" ); + return this.page; } - - protected int getLatestColumn( Coordinate coordinate ) + + protected int getLatestColumn(Coordinate coordinate) { - int col = -1; - if ( coordinate != null ) - { - col = coordinate.getNewCol(); - if ( col == -1 ) - col = coordinate.getOldCol(); - } - return col; + int col = -1; + if (coordinate != null) + { + col = coordinate.getNewCol(); + if (col == -1) col = coordinate.getOldCol(); + } + return col; } - protected int getLatestRow( Coordinate coordinate ) + + protected int getLatestRow(Coordinate coordinate) { - int row = -1; - if ( coordinate != null ) - { - row = coordinate.getNewRow(); - if ( row == -1 ) - row = coordinate.getOldRow(); - } - return row; + int row = -1; + if (coordinate != null) + { + row = coordinate.getNewRow(); + if (row == -1) row = coordinate.getOldRow(); + } + return row; } - - protected void syncFragments( boolean updateFragmentObjects, int onlyForColumnIndex ) + + protected void syncFragments(boolean updateFragmentObjects, + int onlyForColumnIndex) { - for ( int colIndex = 0; colIndex < this.columnsList.length; colIndex++ ) + for (int colIndex = 0; colIndex < this.columnsList.length; colIndex++) { - if ( onlyForColumnIndex == -1 || onlyForColumnIndex == colIndex ) - { - ArrayList column = this.columnsList[colIndex]; - int colRowCount = column.size(); - for ( int rowIndex= 0; rowIndex < colRowCount; rowIndex++ ) - { - Fragment fragment = (Fragment)column.get( rowIndex ); - Coordinate coordinate = (Coordinate)this.fragmentCoordinateMap.get( fragment.getId() ); - boolean needsReplacementCoordinate = false; - - if ( getLatestColumn( coordinate ) != colIndex || getLatestRow( coordinate ) != rowIndex ) - needsReplacementCoordinate = true; + if (onlyForColumnIndex == -1 || onlyForColumnIndex == colIndex) + { + ArrayList column = this.columnsList[colIndex]; + int colRowCount = column.size(); + for (int rowIndex = 0; rowIndex < colRowCount; rowIndex++) + { + Fragment fragment = (Fragment) column.get(rowIndex); + Coordinate coordinate = (Coordinate) this.fragmentCoordinateMap + .get(fragment.getId()); + boolean needsReplacementCoordinate = false; - if ( needsReplacementCoordinate ) - { - Coordinate replacementCoordinate = new CoordinateImpl( coordinate.getOldCol(), coordinate.getOldRow(), colIndex, rowIndex ); - this.fragmentCoordinateMap.put( fragment.getId(), replacementCoordinate ); - } - if ( updateFragmentObjects ) - { - fragment.setLayoutColumn( colIndex ); - fragment.setLayoutRow( rowIndex ); - } - } - } + if (getLatestColumn(coordinate) != colIndex + || getLatestRow(coordinate) != rowIndex) + needsReplacementCoordinate = true; + + if (needsReplacementCoordinate) + { + Coordinate replacementCoordinate = new CoordinateImpl( + coordinate.getOldCol(), coordinate.getOldRow(), + colIndex, rowIndex); + this.fragmentCoordinateMap.put(fragment.getId(), + replacementCoordinate); + } + if (updateFragmentObjects) + { + fragment.setLayoutColumn(colIndex); + fragment.setLayoutRow(rowIndex); + } + } + } } } - - public int getFragmentRow( Fragment fragment ) + + public int getFragmentRow(Fragment fragment) { - if ( fragment == null ) return -1; - Coordinate coordinate = (Coordinate)this.fragmentCoordinateMap.get( fragment.getId() ); - - if ( coordinate == null ) - return -1; - if ( coordinate.getNewRow() >= 0 ) - return coordinate.getNewRow(); - return coordinate.getOldRow(); + if (fragment == null) return -1; + Coordinate coordinate = (Coordinate) this.fragmentCoordinateMap + .get(fragment.getId()); + + if (coordinate == null) return -1; + if (coordinate.getNewRow() >= 0) return coordinate.getNewRow(); + return coordinate.getOldRow(); } - - public int getFragmentCol( Fragment fragment ) + + public int getFragmentCol(Fragment fragment) { - if ( fragment == null ) return -1; - Coordinate coordinate = (Coordinate)this.fragmentCoordinateMap.get( fragment.getId() ); - - if ( coordinate == null ) - return -1; - if ( coordinate.getNewCol() >= 0 ) - return coordinate.getNewCol(); - return coordinate.getOldCol(); + if (fragment == null) return -1; + Coordinate coordinate = (Coordinate) this.fragmentCoordinateMap + .get(fragment.getId()); + + if (coordinate == null) return -1; + if (coordinate.getNewCol() >= 0) return coordinate.getNewCol(); + return coordinate.getOldCol(); } - - public Fragment getFragment( String fragmentId ) throws PortletPlacementException + + public Fragment getFragment(String fragmentId) + throws PortletPlacementException { - return (Fragment)this.fragmentMap.get( fragmentId ); - } - - public Fragment getFragmentAtOldCoordinate( Coordinate coordinate ) throws PortletPlacementException + return (Fragment) this.fragmentMap.get(fragmentId); + } + + public Fragment getFragmentAtOldCoordinate(Coordinate coordinate) + throws PortletPlacementException { - return getFragmentAtCoordinate( coordinate, true, false ); - } + return getFragmentAtCoordinate(coordinate, true, false); + } - public Fragment getFragmentAtNewCoordinate( Coordinate coordinate ) throws PortletPlacementException + public Fragment getFragmentAtNewCoordinate(Coordinate coordinate) + throws PortletPlacementException { - return getFragmentAtCoordinate( coordinate, false, false ); - } + return getFragmentAtCoordinate(coordinate, false, false); + } - protected Fragment getFragmentAtCoordinate( Coordinate coordinate, boolean useOldCoordinateValues, boolean suppressExceptions ) throws PortletPlacementException + protected Fragment getFragmentAtCoordinate(Coordinate coordinate, + boolean useOldCoordinateValues, boolean suppressExceptions) + throws PortletPlacementException { - int col = -1; - int row = -1; - if ( useOldCoordinateValues ) + int col = -1; + int row = -1; + if (useOldCoordinateValues) { - col = coordinate.getOldCol(); - row = coordinate.getOldRow(); - } - else + col = coordinate.getOldCol(); + row = coordinate.getOldRow(); + } + else { - col = coordinate.getNewCol(); - row = coordinate.getNewRow(); - } - - // Do some sanity checking about the request - if ( col < 0 || col >= this.numberOfColumns ) + col = coordinate.getNewCol(); + row = coordinate.getNewRow(); + } + + // Do some sanity checking about the request + if (col < 0 || col >= this.numberOfColumns) { - if ( suppressExceptions ) - return null; - throw new PortletPlacementException( "Requested column (" + col + ") is out of bounds (column-count=" + this.numberOfColumns + ")" ); - } - - // Get the array list associated with the column - ArrayList columnArray = this.columnsList[col]; - if ( row < 0 || row >= columnArray.size() ) + if (suppressExceptions) return null; + throw new PortletPlacementException("Requested column (" + col + + ") is out of bounds (column-count=" + + this.numberOfColumns + ")"); + } + + // Get the array list associated with the column + ArrayList columnArray = this.columnsList[col]; + if (row < 0 || row >= columnArray.size()) { - if ( suppressExceptions ) - return null; - throw new PortletPlacementException( "Requested row (" + row + ") is out of bounds (col[" + col + "].row-count=" + columnArray.size() + ")" ); - } - - return (Fragment)columnArray.get( row ); - } - - public Fragment getFragmentById( String fragmentId ) throws PortletPlacementException + if (suppressExceptions) return null; + throw new PortletPlacementException("Requested row (" + row + + ") is out of bounds (col[" + col + "].row-count=" + + columnArray.size() + ")"); + } + + return (Fragment) columnArray.get(row); + } + + public Fragment getFragmentById(String fragmentId) + throws PortletPlacementException { - return (Fragment)this.fragmentMap.get( fragmentId ); - } + return (Fragment) this.fragmentMap.get(fragmentId); + } - public int getNumberColumns() throws PortletPlacementException + public int getNumberColumns() throws PortletPlacementException { return this.numberOfColumns; - } + } - public int getNumberRows( int col ) throws PortletPlacementException + public int getNumberRows(int col) throws PortletPlacementException { - // Sanity check the column - if ( col < 0 || col >= this.numberOfColumns ) - { - throw new PortletPlacementException( "Requested column (" + col + ") is out of bounds (column-count=" + this.numberOfColumns + ")" ); - } - return this.columnsList[col].size(); - } - - public Coordinate add( Fragment fragment, Coordinate coordinate ) throws PortletPlacementException + // Sanity check the column + if (col < 0 || col >= this.numberOfColumns) { throw new PortletPlacementException( + "Requested column (" + col + + ") is out of bounds (column-count=" + + this.numberOfColumns + ")"); } + return this.columnsList[col].size(); + } + + public Coordinate add(Fragment fragment, Coordinate coordinate) + throws PortletPlacementException { - return moveAbsolute( fragment, coordinate, true ); - } + return moveAbsolute(fragment, coordinate, true); + } - public Coordinate moveAbsolute( Fragment fragment, Coordinate newCoordinate ) - throws PortletPlacementException + public Coordinate moveAbsolute(Fragment fragment, Coordinate newCoordinate) + throws PortletPlacementException { - return moveAbsolute( fragment, newCoordinate, false ); + return moveAbsolute(fragment, newCoordinate, false); } - public Coordinate moveAbsolute( Fragment fragment, Coordinate newCoordinate, boolean okToAddFragment ) - throws PortletPlacementException + + public Coordinate moveAbsolute(Fragment fragment, Coordinate newCoordinate, + boolean okToAddFragment) throws PortletPlacementException { - if ( fragment == null ) - throw new NullPointerException( "PortletPlacementContext moveAbsolute() cannot accept a null Fragment argument" ); + if (fragment == null) + throw new NullPointerException( + "PortletPlacementContext moveAbsolute() cannot accept a null Fragment argument"); - Coordinate currentCoordinate = (Coordinate)this.fragmentCoordinateMap.get( fragment.getId() ); - int currentCol = getLatestColumn( currentCoordinate ); - int currentRow = getLatestRow( currentCoordinate ); - - int newCol = normalizeColumnIndex( getLatestColumn( newCoordinate ), this.columnsList, currentCol ); - int newRow = getLatestRow( newCoordinate ); + Coordinate currentCoordinate = (Coordinate) this.fragmentCoordinateMap + .get(fragment.getId()); + int currentCol = getLatestColumn(currentCoordinate); + int currentRow = getLatestRow(currentCoordinate); - if ( currentCoordinate == null ) - { - if ( ! okToAddFragment ) - throw new NullPointerException( "PortletPlacementContext moveAbsolute() cannot add fragment (" + fragment.getId() + ") unless the okToAddFragment argument is set to true" ); - - // add fragment - ArrayList newColumn = this.columnsList[newCol]; - if ( newRow < 0 || newRow >= newColumn.size() ) - newRow = newColumn.size(); - newColumn.add( newRow, fragment ); - - CoordinateImpl coordinate = new CoordinateImpl( newCol, newRow ); - this.fragmentCoordinateMap.put( fragment.getId(), coordinate ); - this.fragmentMap.put( fragment.getId(), fragment ); - syncFragments( false, newCol ); - } - else - { - boolean columnChanged = ( currentCol != newCol ); - boolean rowChanged = ( currentRow != newRow ); + int newCol = normalizeColumnIndex(getLatestColumn(newCoordinate), + this.columnsList, currentCol); + int newRow = getLatestRow(newCoordinate); - if ( columnChanged || rowChanged ) - { - verifyFragmentAtExpectedCoordinate( currentCol, currentRow, fragment, "moveAbsolute()" ); - - ArrayList currentColumn = this.columnsList[currentCol]; - currentColumn.remove( currentRow ); - - ArrayList newColumn = currentColumn; - if ( columnChanged ) - newColumn = this.columnsList[newCol]; + if (currentCoordinate == null) + { + if (!okToAddFragment) + throw new NullPointerException( + "PortletPlacementContext moveAbsolute() cannot add fragment (" + + fragment.getId() + + ") unless the okToAddFragment argument is set to true"); - if ( newRow < 0 || newRow >= newColumn.size() ) - newColumn.add( fragment ); - else - newColumn.add( newRow, fragment ); - - this.fragmentMap.put( fragment.getId(), fragment ); - - syncFragments( false, currentCol ); - if ( columnChanged ) - syncFragments( false, newCol ); - } - } - return (Coordinate)this.fragmentCoordinateMap.get( fragment.getId() ); - } + // add fragment + ArrayList newColumn = this.columnsList[newCol]; + if (newRow < 0 || newRow >= newColumn.size()) + newRow = newColumn.size(); + newColumn.add(newRow, fragment); - protected Coordinate moveDirection( Fragment fragment, int deltaCol, int deltaRow ) - throws PortletPlacementException + CoordinateImpl coordinate = new CoordinateImpl(newCol, newRow); + this.fragmentCoordinateMap.put(fragment.getId(), coordinate); + this.fragmentMap.put(fragment.getId(), fragment); + syncFragments(false, newCol); + } + else + { + boolean columnChanged = (currentCol != newCol); + boolean rowChanged = (currentRow != newRow); + + if (columnChanged || rowChanged) + { + verifyFragmentAtExpectedCoordinate(currentCol, currentRow, + fragment, "moveAbsolute()"); + + ArrayList currentColumn = this.columnsList[currentCol]; + currentColumn.remove(currentRow); + + ArrayList newColumn = currentColumn; + if (columnChanged) newColumn = this.columnsList[newCol]; + + if (newRow < 0 || newRow >= newColumn.size()) + newColumn.add(fragment); + else + newColumn.add(newRow, fragment); + + this.fragmentMap.put(fragment.getId(), fragment); + + syncFragments(false, currentCol); + if (columnChanged) syncFragments(false, newCol); + } + } + return (Coordinate) this.fragmentCoordinateMap.get(fragment.getId()); + } + + protected Coordinate moveDirection(Fragment fragment, int deltaCol, + int deltaRow) throws PortletPlacementException { - if ( fragment == null ) - throw new NullPointerException( "PortletPlacementContext moveDirection() cannot accept a null Fragment argument" ); + if (fragment == null) + throw new NullPointerException( + "PortletPlacementContext moveDirection() cannot accept a null Fragment argument"); - if ( deltaCol != 0 || deltaRow != 0 ) - { - Coordinate currentCoordinate = (Coordinate)this.fragmentCoordinateMap.get( fragment.getId() ); - if ( currentCoordinate == null ) - throw new NullPointerException( "PortletPlacementContext moveDirection() cannot locate target fragment (" + fragment.getId() + ")" ); - - int currentCol = getLatestColumn( currentCoordinate ); - int currentRow = getLatestRow( currentCoordinate ); - - verifyFragmentAtExpectedCoordinate( currentCol, currentRow, fragment, "moveDirection()" ); - - int newCol = currentCol + deltaCol; - int newRow = currentRow + deltaRow; - if ( newCol >= 0 && newCol < this.numberOfColumns ) - { - ArrayList currentColumn = this.columnsList[currentCol]; - ArrayList newColumn = currentColumn; - if ( newCol != currentCol ) - newColumn = this.columnsList[newCol]; - - currentColumn.remove( currentRow ); - - if ( newRow < 0 || newRow >= newColumn.size() ) - newColumn.add( fragment ); - else - newColumn.add( newRow, fragment ); - - this.fragmentMap.put( fragment.getId(), fragment ); - - syncFragments( false, currentCol ); - if ( newCol != currentCol ) - syncFragments( false, newCol ); - } - } - return (Coordinate)this.fragmentCoordinateMap.get( fragment.getId() ); - } - - public Coordinate moveDown( Fragment fragment ) throws PortletPlacementException + if (deltaCol != 0 || deltaRow != 0) + { + Coordinate currentCoordinate = (Coordinate) this.fragmentCoordinateMap + .get(fragment.getId()); + if (currentCoordinate == null) + throw new NullPointerException( + "PortletPlacementContext moveDirection() cannot locate target fragment (" + + fragment.getId() + ")"); + + int currentCol = getLatestColumn(currentCoordinate); + int currentRow = getLatestRow(currentCoordinate); + + verifyFragmentAtExpectedCoordinate(currentCol, currentRow, + fragment, "moveDirection()"); + + int newCol = currentCol + deltaCol; + int newRow = currentRow + deltaRow; + if (newCol >= 0 && newCol < this.numberOfColumns) + { + ArrayList currentColumn = this.columnsList[currentCol]; + ArrayList newColumn = currentColumn; + if (newCol != currentCol) newColumn = this.columnsList[newCol]; + + currentColumn.remove(currentRow); + + if (newRow < 0 || newRow >= newColumn.size()) + newColumn.add(fragment); + else + newColumn.add(newRow, fragment); + + this.fragmentMap.put(fragment.getId(), fragment); + + syncFragments(false, currentCol); + if (newCol != currentCol) syncFragments(false, newCol); + } + } + return (Coordinate) this.fragmentCoordinateMap.get(fragment.getId()); + } + + public Coordinate moveDown(Fragment fragment) + throws PortletPlacementException { - return moveDirection( fragment, 0, 1 ); - } + return moveDirection(fragment, 0, 1); + } - public Coordinate moveUp( Fragment fragment ) throws PortletPlacementException + public Coordinate moveUp(Fragment fragment) + throws PortletPlacementException { - return moveDirection( fragment, 0, -1 ); - } + return moveDirection(fragment, 0, -1); + } - public Coordinate moveLeft( Fragment fragment ) throws PortletPlacementException + public Coordinate moveLeft(Fragment fragment) + throws PortletPlacementException { - return moveDirection( fragment, -1, 0 ); - } + return moveDirection(fragment, -1, 0); + } - public Coordinate moveRight( Fragment fragment ) throws PortletPlacementException + public Coordinate moveRight(Fragment fragment) + throws PortletPlacementException { - return moveDirection( fragment, 1, 0 ); - } + return moveDirection(fragment, 1, 0); + } - public Coordinate remove( Fragment fragment ) throws PortletPlacementException + public Coordinate remove(Fragment fragment) + throws PortletPlacementException { - if ( fragment == null ) - throw new NullPointerException( "PortletPlacementContext remove() cannot accept a null Fragment argument" ); - - Coordinate currentCoordinate = (Coordinate)this.fragmentCoordinateMap.get( fragment.getId() ); - if ( currentCoordinate == null ) - throw new NullPointerException( "PortletPlacementContext remove() cannot locate target fragment (" + fragment.getId() + ")" ); + if (fragment == null) + throw new NullPointerException( + "PortletPlacementContext remove() cannot accept a null Fragment argument"); - int currentCol = getLatestColumn( currentCoordinate ); - int currentRow = getLatestRow( currentCoordinate ); - - verifyFragmentAtExpectedCoordinate( currentCol, currentRow, fragment, "moveDirection()" ); + Coordinate currentCoordinate = (Coordinate) this.fragmentCoordinateMap + .get(fragment.getId()); + if (currentCoordinate == null) + throw new NullPointerException( + "PortletPlacementContext remove() cannot locate target fragment (" + + fragment.getId() + ")"); - ArrayList currentColumn = this.columnsList[currentCol]; - - currentColumn.remove( currentRow ); - - this.fragmentCoordinateMap.remove( fragment.getId() ); - this.fragmentMap.remove( fragment.getId() ); - - syncFragments( false, currentCol ); - - return currentCoordinate; - } - - protected Fragment verifyFragmentAtExpectedCoordinate( int colIndex, int rowIndex, Fragment fragment, String sourceDesc ) - throws PortletPlacementException - { - CoordinateImpl coordinate = new CoordinateImpl( colIndex, rowIndex ); - - boolean suppressExceptions = ( fragment != null ); - Fragment foundFragment = getFragmentAtCoordinate( coordinate, true, suppressExceptions ); - - if ( fragment != null ) - { - if ( foundFragment == null || foundFragment.getId() != fragment.getId() ) - { - sourceDesc = ( sourceDesc == null ? "getFragmentAtExpectedCoordinate" : sourceDesc ); - - ArrayList column = null; - int colFragCount = -1; - if ( colIndex >= 0 && colIndex < this.numberOfColumns ) - { - column = this.columnsList[colIndex]; - colFragCount = column.size(); - } - StringBuffer out = new StringBuffer(); - out.append( "PortletPlacementContext " ).append( sourceDesc ).append( " has encountered unexpected results"); - out.append( " using the current instance state to locate fragment " ).append( fragment.getId() ).append( " (" ); - if ( foundFragment == null ) - out.append( "no fragment" ); - else - out.append( "different fragment" ); - out.append( " in row " ).append( rowIndex ).append( " of column " ).append( colIndex ); - if ( column == null ) - { - out.append( " - column is out of bounds, column-count=" ).append( this.numberOfColumns ); - } - else - { - out.append( " - " ); - if ( rowIndex < 0 || rowIndex >= colFragCount ) - out.append( "row is out of bounds, " ); - out.append( "row-count=" ).append( colFragCount ); - } - out.append( ")" ); - throw new PortletPlacementException( out.toString() ); - } - } - return fragment; - } + int currentCol = getLatestColumn(currentCoordinate); + int currentRow = getLatestRow(currentCoordinate); - static public int getColumnCountAndSizes( Fragment layoutFragment, PortletRegistry registry, Map fragSizes ) - { - return PortletPlacementContextImpl.getColumnCountAndSizes( layoutFragment, registry, fragSizes, false ); - } - static public int getColumnCountAndSizes( Fragment layoutFragment, PortletRegistry registry, Map fragSizes, boolean suppressErrorLogging ) - { - if ( layoutFragment == null ) - throw new NullPointerException( "getColumnCountAndSizes cannot accept a null Fragment argument" ); - if ( registry == null ) - throw new NullPointerException( "getColumnCountAndSizes cannot accept a null PortletRegistry argument" ); - - int columnCount = -1; - if ( ! "layout".equals( layoutFragment.getType() ) ) - { - if ( ! suppressErrorLogging ) - log.error( "getColumnCountAndSizes not a layout fragment - " + layoutFragment.getId() + " type=" + layoutFragment.getType() ); - } - else - { // get layout fragment sizes - String sizesVal = layoutFragment.getProperty( "sizes" ); - String layoutName = layoutFragment.getName(); - layoutName = ( (layoutName != null && layoutName.length() > 0) ? layoutName : (String)null ); - ParameterSet paramSet = null; - PortletDefinition portletDef = null; - if ( sizesVal == null || sizesVal.length() == 0 ) - { - if ( layoutName != null ) - { - // logic below is copied from org.apache.jetspeed.portlets.MultiColumnPortlet - portletDef = registry.getPortletDefinitionByUniqueName( layoutName ); - if ( portletDef != null ) + verifyFragmentAtExpectedCoordinate(currentCol, currentRow, fragment, + "moveDirection()"); + + ArrayList currentColumn = this.columnsList[currentCol]; + + currentColumn.remove(currentRow); + + this.fragmentCoordinateMap.remove(fragment.getId()); + this.fragmentMap.remove(fragment.getId()); + + syncFragments(false, currentCol); + + return currentCoordinate; + } + + protected Fragment verifyFragmentAtExpectedCoordinate(int colIndex, + int rowIndex, Fragment fragment, String sourceDesc) + throws PortletPlacementException + { + CoordinateImpl coordinate = new CoordinateImpl(colIndex, rowIndex); + + boolean suppressExceptions = (fragment != null); + Fragment foundFragment = getFragmentAtCoordinate(coordinate, true, + suppressExceptions); + + if (fragment != null) + { + if (foundFragment == null + || foundFragment.getId() != fragment.getId()) + { + sourceDesc = (sourceDesc == null ? "getFragmentAtExpectedCoordinate" + : sourceDesc); + + ArrayList column = null; + int colFragCount = -1; + if (colIndex >= 0 && colIndex < this.numberOfColumns) + { + column = this.columnsList[colIndex]; + colFragCount = column.size(); + } + StringBuffer out = new StringBuffer(); + out.append("PortletPlacementContext ").append(sourceDesc) + .append(" has encountered unexpected results"); + out + .append( + " using the current instance state to locate fragment ") + .append(fragment.getId()).append(" ("); + if (foundFragment == null) + out.append("no fragment"); + else + out.append("different fragment"); + out.append(" in row ").append(rowIndex).append(" of column ") + .append(colIndex); + if (column == null) + { + out.append(" - column is out of bounds, column-count=") + .append(this.numberOfColumns); + } + else + { + out.append(" - "); + if (rowIndex < 0 || rowIndex >= colFragCount) + out.append("row is out of bounds, "); + out.append("row-count=").append(colFragCount); + } + out.append(")"); + throw new PortletPlacementException(out.toString()); + } + } + return fragment; + } + + static public int getColumnCountAndSizes(Fragment layoutFragment, + PortletRegistry registry, Map fragSizes) + { + return PortletPlacementContextImpl.getColumnCountAndSizes( + layoutFragment, registry, fragSizes, false); + } + + static public int getColumnCountAndSizes(Fragment layoutFragment, + PortletRegistry registry, Map fragSizes, + boolean suppressErrorLogging) + { + if (layoutFragment == null) + throw new NullPointerException( + "getColumnCountAndSizes cannot accept a null Fragment argument"); + if (registry == null) + throw new NullPointerException( + "getColumnCountAndSizes cannot accept a null PortletRegistry argument"); + + int columnCount = -1; + if (!"layout".equals(layoutFragment.getType())) + { + if (!suppressErrorLogging) + log.error("getColumnCountAndSizes not a layout fragment - " + + layoutFragment.getId() + " type=" + + layoutFragment.getType()); + } + else + { // get layout fragment sizes + String sizesVal = layoutFragment.getProperty("sizes"); + String layoutName = layoutFragment.getName(); + layoutName = ((layoutName != null && layoutName.length() > 0) ? layoutName + : (String) null); + ParameterSet paramSet = null; + PortletDefinition portletDef = null; + if (sizesVal == null || sizesVal.length() == 0) + { + if (layoutName != null) + { + // logic below is copied from + // org.apache.jetspeed.portlets.MultiColumnPortlet + portletDef = registry + .getPortletDefinitionByUniqueName(layoutName); + if (portletDef != null) { - paramSet = portletDef.getInitParameterSet(); - if ( paramSet != null ) - { - Parameter sizesParam = paramSet.get( "sizes" ); - sizesVal = ( sizesParam == null ) ? null : sizesParam.getValue(); - } + paramSet = portletDef.getInitParameterSet(); + if (paramSet != null) + { + Parameter sizesParam = paramSet.get("sizes"); + sizesVal = (sizesParam == null) ? null : sizesParam + .getValue(); + } } - } - } - if ( sizesVal != null && sizesVal.length() > 0 ) - { - if ( fragSizes != null ) - fragSizes.put( layoutFragment.getId(), sizesVal ); - - int sepPos = -1, startPos = 0, sizesLen = sizesVal.length(); - columnCount = 0; - do - { - sepPos = sizesVal.indexOf( ',', startPos ); - if ( sepPos != -1 ) - { - if ( sepPos > startPos ) - columnCount++; - startPos = sepPos +1; - } - else if ( startPos < sizesLen ) - { - columnCount++; - } - } while ( startPos < sizesLen && sepPos != -1 ); - if ( ! suppressErrorLogging && columnCount <= 0 ) - log.error( "getColumnCountAndSizes invalid columnCount - " + layoutFragment.getId() + " / " + layoutName + " count=" + columnCount + " sizes=" + sizesVal ); - } - else if ( paramSet == null ) - { - if ( ! suppressErrorLogging ) - { - if ( layoutName == null ) - log.error( "getColumnCountAndSizes null sizes, null layoutName - " + layoutFragment.getId() ); - else if ( portletDef == null ) - log.error( "getColumnCountAndSizes null sizes, null PortletDefinition - " + layoutFragment.getId() + " / " + layoutName ); - else - log.error( "getColumnCountAndSizes null sizes, null ParameterSet - " + layoutFragment.getId() + " / " + layoutName ); - } - } - else - { - Parameter colsParam = paramSet.get( "columns" ); - String colsParamVal = ( colsParam == null ) ? null : colsParam.getValue(); - if ( colsParamVal != null && colsParamVal.length() > 0 ) - { - try - { - columnCount = Integer.parseInt( colsParamVal ); - } - catch ( NumberFormatException ex ) - { - } - if ( columnCount < 1 ) - { - columnCount = 2; - } - switch ( columnCount ) - { - case 1: sizesVal = "100%"; break; - case 2: sizesVal = "50%,50%"; break; - case 3: sizesVal = "34%,33%,33%"; break; - case 4: sizesVal = "25%,25%,25%,25%"; break; - default: - { - sizesVal = "50%,50%"; - columnCount = 2; - break; - } - } - if ( fragSizes != null ) - fragSizes.put( layoutFragment.getId(), sizesVal ); - //log.info( "getColumnCountAndSizes " + layoutFragment.getId() + " count=" + columnCount + " defaulted-sizes=" + sizesParamVal ); - } - else - { - if ( ! suppressErrorLogging ) - log.error( "getColumnCountAndSizes null sizes, columns not defined in ParameterSet - " + layoutFragment.getId() + " / " + layoutName ); - } - } - } - return columnCount; - } + } + } + if (sizesVal != null && sizesVal.length() > 0) + { + if (fragSizes != null) + fragSizes.put(layoutFragment.getId(), sizesVal); + + int sepPos = -1, startPos = 0, sizesLen = sizesVal.length(); + columnCount = 0; + do + { + sepPos = sizesVal.indexOf(',', startPos); + if (sepPos != -1) + { + if (sepPos > startPos) columnCount++; + startPos = sepPos + 1; + } + else if (startPos < sizesLen) + { + columnCount++; + } + } while (startPos < sizesLen && sepPos != -1); + if (!suppressErrorLogging && columnCount <= 0) + log.error("getColumnCountAndSizes invalid columnCount - " + + layoutFragment.getId() + " / " + layoutName + + " count=" + columnCount + " sizes=" + sizesVal); + } + else if (paramSet == null) + { + if (!suppressErrorLogging) + { + if (layoutName == null) + log + .error("getColumnCountAndSizes null sizes, null layoutName - " + + layoutFragment.getId()); + else if (portletDef == null) + log + .error("getColumnCountAndSizes null sizes, null PortletDefinition - " + + layoutFragment.getId() + + " / " + + layoutName); + else + log + .error("getColumnCountAndSizes null sizes, null ParameterSet - " + + layoutFragment.getId() + + " / " + + layoutName); + } + } + else + { + Parameter colsParam = paramSet.get("columns"); + String colsParamVal = (colsParam == null) ? null : colsParam + .getValue(); + if (colsParamVal != null && colsParamVal.length() > 0) + { + try + { + columnCount = Integer.parseInt(colsParamVal); + } + catch (NumberFormatException ex) + { + } + if (columnCount < 1) + { + columnCount = 2; + } + switch (columnCount) + { + case 1: + sizesVal = "100%"; + break; + case 2: + sizesVal = "50%,50%"; + break; + case 3: + sizesVal = "34%,33%,33%"; + break; + case 4: + sizesVal = "25%,25%,25%,25%"; + break; + default: { + sizesVal = "50%,50%"; + columnCount = 2; + break; + } + } + if (fragSizes != null) + fragSizes.put(layoutFragment.getId(), sizesVal); + // log.info( "getColumnCountAndSizes " + + // layoutFragment.getId() + " count=" + columnCount + " + // defaulted-sizes=" + sizesParamVal ); + } + else + { + if (!suppressErrorLogging) + log + .error("getColumnCountAndSizes null sizes, columns not defined in ParameterSet - " + + layoutFragment.getId() + + " / " + + layoutName); + } + } + } + return columnCount; + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/RemovePortletAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/RemovePortletAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/RemovePortletAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,152 +33,162 @@ import org.apache.jetspeed.pipeline.PipelineException; import org.apache.jetspeed.request.RequestContext; - /** * Remove Portlet portlet placement action * - * AJAX Parameters: - * id = the fragment id of the portlet to remove - * page = (implied in the URL) - * + * AJAX Parameters: id = the fragment id of the portlet to remove page = + * (implied in the URL) + * * @author David Gurney * @author David Sean Taylor * @version $Id: $ */ -public class RemovePortletAction - extends BasePortletAction - implements AjaxAction, AjaxBuilder, Constants +public class RemovePortletAction extends BasePortletAction implements + AjaxAction, AjaxBuilder, Constants { - protected static final Log log = LogFactory.getLog(RemovePortletAction.class); - + + protected static final Log log = LogFactory + .getLog(RemovePortletAction.class); + private PortletRegistry registry; - public RemovePortletAction( String template, String errorTemplate, PortletRegistry registry ) - throws PipelineException + public RemovePortletAction(String template, String errorTemplate, + PortletRegistry registry) throws PipelineException { - this( template, errorTemplate, registry, null, null ); + this(template, errorTemplate, registry, null, null); } - public RemovePortletAction( String template, - String errorTemplate, - PortletRegistry registry, - PageManager pageManager, - PortletActionSecurityBehavior securityBehavior ) - throws PipelineException + public RemovePortletAction(String template, String errorTemplate, + PortletRegistry registry, PageManager pageManager, + PortletActionSecurityBehavior securityBehavior) + throws PipelineException { - super( template, errorTemplate, pageManager, securityBehavior ); + super(template, errorTemplate, pageManager, securityBehavior); this.registry = registry; } - - public boolean runBatch(RequestContext requestContext, Map resultMap) throws AJAXException + + public boolean runBatch(RequestContext requestContext, Map resultMap) + throws AJAXException { return runAction(requestContext, resultMap, true); - } - + } + public boolean run(RequestContext requestContext, Map resultMap) throws AJAXException { return runAction(requestContext, resultMap, false); } - - public boolean runAction(RequestContext requestContext, Map resultMap, boolean batch) + + public boolean runAction(RequestContext requestContext, Map resultMap, + boolean batch) { boolean success = true; String status = "success"; try { - resultMap.put( ACTION, "remove" ); + resultMap.put(ACTION, "remove"); // Get the necessary parameters off of the request - String portletId = getActionParameter( requestContext, PORTLETID ); - if (portletId == null) - { + String portletId = getActionParameter(requestContext, PORTLETID); + if (portletId == null) + { success = false; - resultMap.put( REASON, "Portlet ID not provided" ); + resultMap.put(REASON, "Portlet ID not provided"); return success; } - resultMap.put( PORTLETID, portletId ); - if ( false == checkAccess( requestContext, JetspeedActions.EDIT ) ) + resultMap.put(PORTLETID, portletId); + if (false == checkAccess(requestContext, JetspeedActions.EDIT)) { Page page = requestContext.getPage(); - Fragment fragment = page.getFragmentById( portletId ); - if ( fragment == null ) + Fragment fragment = page.getFragmentById(portletId); + if (fragment == null) { success = false; - resultMap.put( REASON, "Fragment not found" ); - return success; + resultMap.put(REASON, "Fragment not found"); + return success; } - + NestedFragmentContext removeFragmentContext = null; try { - removeFragmentContext = new NestedFragmentContext( fragment, page, registry ); + removeFragmentContext = new NestedFragmentContext(fragment, + page, registry); } - catch ( Exception ex ) + catch (Exception ex) { - log.error( "Failure to construct nested context for fragment " + portletId, ex ); - success = false; - resultMap.put( REASON, "Cannot construct nested context for fragment" ); + log.error( + "Failure to construct nested context for fragment " + + portletId, ex); + success = false; + resultMap.put(REASON, + "Cannot construct nested context for fragment"); return success; } - - if ( ! createNewPageOnEdit( requestContext ) ) - { + + if (!createNewPageOnEdit(requestContext)) + { success = false; - resultMap.put( REASON, "Insufficient access to edit page" ); + resultMap.put(REASON, "Insufficient access to edit page"); return success; } status = "refresh"; - + Page newPage = requestContext.getPage(); - // using NestedFragmentContext, find portlet id for copy of target portlet in the new page + // using NestedFragmentContext, find portlet id for copy of + // target portlet in the new page Fragment newFragment = null; try { - newFragment = removeFragmentContext.getFragmentOnNewPage( newPage, registry ); + newFragment = removeFragmentContext.getFragmentOnNewPage( + newPage, registry); } - catch ( Exception ex ) + catch (Exception ex) { - log.error( "Failure to locate copy of fragment " + portletId, ex ); - success = false; - resultMap.put( REASON, "Failed to find new fragment for portlet id: " + portletId ); + log.error( + "Failure to locate copy of fragment " + portletId, + ex); + success = false; + resultMap.put(REASON, + "Failed to find new fragment for portlet id: " + + portletId); return success; } portletId = newFragment.getId(); } - + // Use the Portlet Placement Manager to accomplish the removal Page page = requestContext.getPage(); Fragment root = page.getRootFragment(); - Fragment layoutContainerFragment = getParentFragmentById( portletId, root ); + Fragment layoutContainerFragment = getParentFragmentById(portletId, + root); PortletPlacementContext placement = null; Fragment fragment = null; - if ( layoutContainerFragment != null ) + if (layoutContainerFragment != null) { - placement = new PortletPlacementContextImpl( page, registry, layoutContainerFragment ); - fragment = placement.getFragmentById( portletId ); + placement = new PortletPlacementContextImpl(page, registry, + layoutContainerFragment); + fragment = placement.getFragmentById(portletId); } - if ( fragment == null ) + if (fragment == null) { success = false; - resultMap.put( REASON, "Fragment not found" ); - return success; + resultMap.put(REASON, "Fragment not found"); + return success; } placement.remove(fragment); page = placement.syncPageFragments(); - page.removeFragmentById( fragment.getId() ); + page.removeFragmentById(fragment.getId()); if (!batch) { - if (pageManager != null) - pageManager.updatePage( page ); + if (pageManager != null) pageManager.updatePage(page); } // Build the results for the response - resultMap.put( PORTLETID, portletId ); - resultMap.put( STATUS, status ); - resultMap.put( OLDCOL, String.valueOf( fragment.getLayoutColumn() ) ); - resultMap.put( OLDROW, String.valueOf( fragment.getLayoutRow() ) ); - } - catch ( Exception e ) + resultMap.put(PORTLETID, portletId); + resultMap.put(STATUS, status); + resultMap.put(OLDCOL, String.valueOf(fragment.getLayoutColumn())); + resultMap.put(OLDROW, String.valueOf(fragment.getLayoutRow())); + } + catch (Exception e) { // Log the exception log.error("exception while adding a portlet", e); @@ -189,9 +199,9 @@ return success; } - + protected PortletRegistry getPortletRegistry() { - return this.registry; + return this.registry; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/RolesSecurityBehavior.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/RolesSecurityBehavior.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/RolesSecurityBehavior.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,15 +26,18 @@ /** * Abstracted behavior of security checks for portlet actions - * + * * @author David Sean Taylor * @version $Id: $ */ public class RolesSecurityBehavior implements PortletActionSecurityBehavior { - protected Log log = LogFactory.getLog(PortletActionSecurityPathBehavior.class); + + protected Log log = LogFactory + .getLog(PortletActionSecurityPathBehavior.class); + protected List roles; - + public RolesSecurityBehavior(List roles) { this.roles = roles; @@ -45,20 +48,20 @@ Iterator iterator = roles.iterator(); while (iterator.hasNext()) { - String role = (String)iterator.next(); - if (context.getRequest().isUserInRole(role)) - return true; - } + String role = (String) iterator.next(); + if (context.getRequest().isUserInRole(role)) return true; + } return false; } - + public boolean isCreateNewPageOnEditEnabled() { - return false; + return false; } + public boolean isPageQualifiedForCreateNewPageOnEdit(RequestContext context) { - return false ; + return false; } public boolean createNewPageOnEdit(RequestContext context) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/SecurityConstraintsAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/SecurityConstraintsAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/SecurityConstraintsAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -41,40 +41,37 @@ /** * Security Permission action * - * AJAX Parameters: - * action = constraints - * method = add-def | update-def | remove-def | add-global | remove-global - * name = name of constraint definition or global definition - * xml = the constraints payload, same format as PSML constraint defs - * + * AJAX Parameters: action = constraints method = add-def | update-def | + * remove-def | add-global | remove-global name = name of constraint definition + * or global definition xml = the constraints payload, same format as PSML + * constraint defs + * * @author David Sean Taylor * @version $Id: $ */ -public class SecurityConstraintsAction - extends BasePortletAction - implements AjaxAction, AjaxBuilder, Constants +public class SecurityConstraintsAction extends BasePortletAction implements + AjaxAction, AjaxBuilder, Constants { - protected static final Log log = LogFactory.getLog(SecurityConstraintsAction.class); - public SecurityConstraintsAction(String template, - String errorTemplate, - PageManager pm, - PortletActionSecurityBehavior securityBehavior) + protected static final Log log = LogFactory + .getLog(SecurityConstraintsAction.class); + + public SecurityConstraintsAction(String template, String errorTemplate, + PageManager pm, PortletActionSecurityBehavior securityBehavior) { - super(template, errorTemplate, pm, securityBehavior); + super(template, errorTemplate, pm, securityBehavior); } - public SecurityConstraintsAction(String template, - String errorTemplate, + public SecurityConstraintsAction(String template, String errorTemplate, PageManager pm) { - this(template, errorTemplate, pm, null); + this(template, errorTemplate, pm, null); } - + public boolean run(RequestContext requestContext, Map resultMap) throws AJAXException { - System.out.println( "SecurityConstraintsAction run" ); + System.out.println("SecurityConstraintsAction run"); boolean success = true; String status = "success"; try @@ -82,17 +79,16 @@ resultMap.put(ACTION, "constraints"); // Get the necessary parameters off of the request String method = getActionParameter(requestContext, "method"); - if (method == null) - { - throw new RuntimeException("Method not provided"); - } + if (method == null) { throw new RuntimeException( + "Method not provided"); } resultMap.put("method", method); if (false == checkAccess(requestContext, JetspeedActions.EDIT)) { success = false; - resultMap.put(REASON, "Insufficient access to administer portal permissions"); + resultMap.put(REASON, + "Insufficient access to administer portal permissions"); return success; - } + } int count = 0; if (method.equals("add-def") || method.equals("update-def")) { @@ -113,39 +109,40 @@ else { success = false; - resultMap.put(REASON, "Unsupported portal constraints method: " + method); - return success; + resultMap.put(REASON, "Unsupported portal constraints method: " + + method); + return success; } resultMap.put("count", Integer.toString(count)); resultMap.put(STATUS, status); - } + } catch (Exception e) { - System.out.println( "SecurityConstraintsAction run failure caused by " + e.getClass().getName() + " " + e.getMessage() ); - e.printStackTrace(); + System.out + .println("SecurityConstraintsAction run failure caused by " + + e.getClass().getName() + " " + e.getMessage()); + e.printStackTrace(); log.error("exception administering portal permissions", e); resultMap.put(REASON, e.toString()); success = false; } - System.out.println( "SecurityConstraintsAction complete " + resultMap.toString() ); + System.out.println("SecurityConstraintsAction complete " + + resultMap.toString()); return success; } - - protected int removeConstraintDefinition(RequestContext requestContext, Map resultMap) - throws AJAXException + + protected int removeConstraintDefinition(RequestContext requestContext, + Map resultMap) throws AJAXException { String name = getActionParameter(requestContext, "name"); - if (name == null) - throw new AJAXException("Missing 'name' parameter"); - + if (name == null) throw new AJAXException("Missing 'name' parameter"); + try { - PageSecurity pageSecurity = pageManager.getPageSecurity(); - SecurityConstraintsDef def = pageSecurity.getSecurityConstraintsDef(name); - if (def == null) - { - return 0; - } + PageSecurity pageSecurity = pageManager.getPageSecurity(); + SecurityConstraintsDef def = pageSecurity + .getSecurityConstraintsDef(name); + if (def == null) { return 0; } List defs = pageSecurity.getSecurityConstraintsDefs(); defs.remove(def); pageSecurity.setSecurityConstraintsDefs(defs); @@ -154,20 +151,20 @@ catch (Exception e) { throw new AJAXException(e); - } + } return 1; } - - protected int updateConstraintDefinition(RequestContext requestContext, Map resultMap) - throws AJAXException + + protected int updateConstraintDefinition(RequestContext requestContext, + Map resultMap) throws AJAXException { - System.out.println( "SecurityConstraintsAction updateConstraintDefinition started" ); - + System.out + .println("SecurityConstraintsAction updateConstraintDefinition started"); + int count = 0; boolean added = false; String xml = getActionParameter(requestContext, "xml"); - if (xml == null) - throw new AJAXException("Missing 'xml' parameter"); + if (xml == null) throw new AJAXException("Missing 'xml' parameter"); try { SAXBuilder saxBuilder = new SAXBuilder(); @@ -176,7 +173,8 @@ Element root = document.getRootElement(); String name = root.getAttribute("name").getValue(); PageSecurity pageSecurity = pageManager.getPageSecurity(); - SecurityConstraintsDef def = pageSecurity.getSecurityConstraintsDef(name); + SecurityConstraintsDef def = pageSecurity + .getSecurityConstraintsDef(name); int defsSize = 0; if (def == null) { @@ -198,10 +196,11 @@ } for (int ix = 0; ix < min; ix++) { - Element xmlConstraint = (Element)xmlConstraints.get(ix); - SecurityConstraint constraint = (SecurityConstraint)constraints.get(ix); + Element xmlConstraint = (Element) xmlConstraints.get(ix); + SecurityConstraint constraint = (SecurityConstraint) constraints + .get(ix); updateConstraintValues(xmlConstraint, constraint); - count++; + count++; } if (xmlSize < defsSize) { @@ -214,46 +213,55 @@ for (int ix = 0; ix < deletes.size(); ix++) { constraints.remove(deletes.get(ix)); - count++; - } + count++; + } } else if (xmlSize > defsSize) { // add new constraints for (int ix = min; ix < xmlSize; ix++) { - Element xmlConstraint = (Element)xmlConstraints.get(ix); - SecurityConstraint constraint = pageManager.newPageSecuritySecurityConstraint(); + Element xmlConstraint = (Element) xmlConstraints.get(ix); + SecurityConstraint constraint = pageManager + .newPageSecuritySecurityConstraint(); updateConstraintValues(xmlConstraint, constraint); - constraints.add(constraint); + constraints.add(constraint); count++; - } + } } if (added) - { + { pageSecurity.getSecurityConstraintsDefs().add(def); - pageSecurity.setSecurityConstraintsDefs(pageSecurity.getSecurityConstraintsDefs()); + pageSecurity.setSecurityConstraintsDefs(pageSecurity + .getSecurityConstraintsDefs()); } pageManager.updatePageSecurity(pageSecurity); } catch (Exception e) { - System.out.println( "SecurityConstraintsAction updateConstraintDefinition failure caused by " + e.getClass().getName() + " " + e.getMessage() ); - e.printStackTrace(); - log.error( "SecurityConstraintsAction updateConstraintDefinition failure caused by " + e.getClass().getName() + " " + e.getMessage(), e ); + System.out + .println("SecurityConstraintsAction updateConstraintDefinition failure caused by " + + e.getClass().getName() + " " + e.getMessage()); + e.printStackTrace(); + log.error( + "SecurityConstraintsAction updateConstraintDefinition failure caused by " + + e.getClass().getName() + " " + e.getMessage(), e); throw new AJAXException(e); } return count; } - - protected void updateConstraintValues(Element xmlConstraint, SecurityConstraint constraint) + + protected void updateConstraintValues(Element xmlConstraint, + SecurityConstraint constraint) { constraint.setRoles(parseCSVList(xmlConstraint.getChildText("roles"))); - constraint.setGroups(parseCSVList(xmlConstraint.getChildText("groups"))); - constraint.setPermissions(parseCSVList(xmlConstraint.getChildText("permissions"))); - constraint.setUsers(parseCSVList(xmlConstraint.getChildText("users"))); + constraint + .setGroups(parseCSVList(xmlConstraint.getChildText("groups"))); + constraint.setPermissions(parseCSVList(xmlConstraint + .getChildText("permissions"))); + constraint.setUsers(parseCSVList(xmlConstraint.getChildText("users"))); } - + protected List parseCSVList(String csv) { if (csv != null) @@ -275,23 +283,19 @@ } return null; } - + protected int removeGlobal(RequestContext requestContext, Map resultMap) - throws AJAXException + throws AJAXException { int count = 0; String name = getActionParameter(requestContext, "name"); - if (name == null) - throw new AJAXException("Missing 'name' parameter"); - + if (name == null) throw new AJAXException("Missing 'name' parameter"); + try { - PageSecurity pageSecurity = pageManager.getPageSecurity(); + PageSecurity pageSecurity = pageManager.getPageSecurity(); List globals = pageSecurity.getGlobalSecurityConstraintsRefs(); - if (!globals.contains(name)) - { - return 0; - } + if (!globals.contains(name)) { return 0; } globals.remove(name); pageSecurity.setGlobalSecurityConstraintsRefs(globals); pageManager.updatePageSecurity(pageSecurity); @@ -300,26 +304,23 @@ catch (Exception e) { throw new AJAXException(e); - } + } return count; } - + protected int addGlobal(RequestContext requestContext, Map resultMap) - throws AJAXException + throws AJAXException { int count = 0; String name = getActionParameter(requestContext, "name"); - if (name == null) - throw new AJAXException("Missing 'name' parameter"); - + if (name == null) throw new AJAXException("Missing 'name' parameter"); + try { - PageSecurity pageSecurity = pageManager.getPageSecurity(); + PageSecurity pageSecurity = pageManager.getPageSecurity(); List globals = pageSecurity.getGlobalSecurityConstraintsRefs(); - if (pageSecurity.getSecurityConstraintsDef(name) == null) - { - throw new AJAXException("global name doesnt exist in definitions"); - } + if (pageSecurity.getSecurityConstraintsDef(name) == null) { throw new AJAXException( + "global name doesnt exist in definitions"); } if (globals.contains(name)) { // already exist; @@ -333,8 +334,8 @@ catch (Exception e) { throw new AJAXException(e); - } + } return count; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/SecurityPermissionAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/SecurityPermissionAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/SecurityPermissionAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -39,37 +39,34 @@ /** * Security Permission action * - * AJAX Parameters: - * action = permission - * method = add | update | delete - * resource = name of the resource to modify - * type = portlet | page | folder - * roles = comma separated list of roles - * actions = comma separated list of actions - * oldactions = comma separated list of old actions - * + * AJAX Parameters: action = permission method = add | update | delete resource = + * name of the resource to modify type = portlet | page | folder roles = comma + * separated list of roles actions = comma separated list of actions oldactions = + * comma separated list of old actions + * * @author David Sean Taylor * @version $Id: $ */ -public class SecurityPermissionAction - extends BasePortletAction - implements AjaxAction, AjaxBuilder, Constants +public class SecurityPermissionAction extends BasePortletAction implements + AjaxAction, AjaxBuilder, Constants { - protected static final Log log = LogFactory.getLog(SecurityPermissionAction.class); + + protected static final Log log = LogFactory + .getLog(SecurityPermissionAction.class); + protected PermissionManager pm = null; + protected Map permissionMap = null; - public SecurityPermissionAction(String template, - String errorTemplate, - PermissionManager pm, - PortletActionSecurityBehavior securityBehavior, - Map permissionMap) + public SecurityPermissionAction(String template, String errorTemplate, + PermissionManager pm, + PortletActionSecurityBehavior securityBehavior, Map permissionMap) { - super(template, errorTemplate, securityBehavior); + super(template, errorTemplate, securityBehavior); this.pm = pm; this.permissionMap = permissionMap; } - + public boolean run(RequestContext requestContext, Map resultMap) throws AJAXException { @@ -80,17 +77,16 @@ resultMap.put(ACTION, "permissions"); // Get the necessary parameters off of the request String method = getActionParameter(requestContext, "method"); - if (method == null) - { - throw new RuntimeException("Method not provided"); - } + if (method == null) { throw new RuntimeException( + "Method not provided"); } resultMap.put("method", method); if (false == checkAccess(requestContext, JetspeedActions.EDIT)) { success = false; - resultMap.put(REASON, "Insufficient access to administer portal permissions"); + resultMap.put(REASON, + "Insufficient access to administer portal permissions"); return success; - } + } int count = 0; if (method.equals("add")) { @@ -99,7 +95,7 @@ else if (method.equals("update")) { count = updatePermission(requestContext, resultMap); - } + } else if (method.equals("remove")) { count = removePermission(requestContext, resultMap); @@ -107,16 +103,19 @@ else { success = false; - resultMap.put(REASON, "Unsupported portal permissions method: " + method); - return success; + resultMap.put(REASON, "Unsupported portal permissions method: " + + method); + return success; } resultMap.put("count", Integer.toString(count)); - resultMap.put("resource", getActionParameter(requestContext, "resource")); + resultMap.put("resource", getActionParameter(requestContext, + "resource")); resultMap.put("type", getActionParameter(requestContext, "type")); - resultMap.put("actions", getActionParameter(requestContext, "actions")); + resultMap.put("actions", getActionParameter(requestContext, + "actions")); resultMap.put("roles", getActionParameter(requestContext, "roles")); resultMap.put(STATUS, status); - } + } catch (Exception e) { log.error("exception administering portal permissions", e); @@ -125,9 +124,9 @@ } return success; } - + protected int addPermission(RequestContext requestContext, Map resultMap) - throws AJAXException + throws AJAXException { try { @@ -140,25 +139,24 @@ String actions = getActionParameter(requestContext, "actions"); if (actions == null) throw new AJAXException("Missing 'actions' parameter"); - - Permission permission = createPermissionFromClass(type, resource, actions); - if (pm.permissionExists(permission)) - { - throw new AJAXException("Permission " + resource + " already exists"); - } - - pm.addPermission(permission); + + Permission permission = createPermissionFromClass(type, resource, + actions); + if (pm.permissionExists(permission)) { throw new AJAXException( + "Permission " + resource + " already exists"); } + + pm.addPermission(permission); String roleNames = getActionParameter(requestContext, "roles"); return updateRoles(permission, roleNames); } catch (SecurityException e) { throw new AJAXException(e.toString(), e); - } + } } protected int updatePermission(RequestContext requestContext, Map resultMap) - throws AJAXException + throws AJAXException { try { @@ -180,11 +178,12 @@ Permission permission = null; if (!oldActions.equals(actions)) { - permission = createPermissionFromClass(type, resource, oldActions); + permission = createPermissionFromClass(type, resource, + oldActions); pm.removePermission(permission); permission = createPermissionFromClass(type, resource, actions); pm.addPermission(permission); - } + } else { permission = createPermissionFromClass(type, resource, actions); @@ -195,11 +194,11 @@ catch (SecurityException e) { throw new AJAXException(e.toString(), e); - } + } } - + protected int updateRoles(Permission permission, String roleNames) - throws SecurityException + throws SecurityException { List principals = new LinkedList(); if (roleNames != null) @@ -210,13 +209,13 @@ String roleName = toke.nextToken(); Principal role = new RolePrincipalImpl(roleName); principals.add(role); - } + } } - return pm.updatePermission(permission, principals); + return pm.updatePermission(permission, principals); } protected int removePermission(RequestContext requestContext, Map resultMap) - throws AJAXException + throws AJAXException { try { @@ -228,8 +227,9 @@ throw new AJAXException("Missing 'resource' parameter"); String actions = getActionParameter(requestContext, "actions"); if (actions == null) - throw new AJAXException("Missing 'actions' parameter"); - Permission permission = createPermissionFromClass(type, resource, actions); + throw new AJAXException("Missing 'actions' parameter"); + Permission permission = createPermissionFromClass(type, resource, + actions); if (pm.permissionExists(permission)) { pm.removePermission(permission); @@ -242,32 +242,33 @@ throw new AJAXException(e.toString(), e); } } - - protected String mapTypeToClassname(String type) - throws AJAXException + + protected String mapTypeToClassname(String type) throws AJAXException { - String classname = (String)this.permissionMap.get(type); - if (classname != null) - return classname; - throw new AJAXException("Bad resource 'type' parameter: " + type); + String classname = (String) this.permissionMap.get(type); + if (classname != null) return classname; + throw new AJAXException("Bad resource 'type' parameter: " + type); } - - protected Permission createPermissionFromClass(String type, String resource, String actions) - throws AJAXException - { + + protected Permission createPermissionFromClass(String type, + String resource, String actions) throws AJAXException + { String classname = this.mapTypeToClassname(type); try { Class permissionClass = Class.forName(classname); - Class[] parameterTypes = { String.class, String.class }; - Constructor permissionConstructor = permissionClass.getConstructor(parameterTypes); - Object[] initArgs = { resource, actions }; - return (Permission)permissionConstructor.newInstance(initArgs); + Class[] parameterTypes = + {String.class, String.class}; + Constructor permissionConstructor = permissionClass + .getConstructor(parameterTypes); + Object[] initArgs = + {resource, actions}; + return (Permission) permissionConstructor.newInstance(initArgs); } catch (Exception e) { throw new AJAXException("Failed to create permission: " + type, e); } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/UpdateFolderAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/UpdateFolderAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/UpdateFolderAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,35 +34,26 @@ /** * Update Folder action -- updates various parts of the PSML folder * - * AJAX Parameters: - * action = updatefolder - * General methods: - * method = add | remove - * Info methods: - * | info - * Meta methods: - * | add-meta | update-meta | remove-meta - * Security methods: - * | add-secref | remove-secref - * + * AJAX Parameters: action = updatefolder General methods: method = add | remove + * Info methods: | info Meta methods: | add-meta | update-meta | remove-meta + * Security methods: | add-secref | remove-secref + * * @author David Sean Taylor * @version $Id: $ */ -public class UpdateFolderAction - extends BaseSiteUpdateAction - implements AjaxAction, AjaxBuilder, Constants +public class UpdateFolderAction extends BaseSiteUpdateAction implements + AjaxAction, AjaxBuilder, Constants { + protected Log log = LogFactory.getLog(UpdateFolderAction.class); - public UpdateFolderAction(String template, - String errorTemplate, - PageManager pm, - PortletActionSecurityBehavior securityBehavior) - + public UpdateFolderAction(String template, String errorTemplate, + PageManager pm, PortletActionSecurityBehavior securityBehavior) + { - super(template, errorTemplate, pm, securityBehavior); + super(template, errorTemplate, pm, securityBehavior); } - + public boolean run(RequestContext requestContext, Map resultMap) throws AJAXException { @@ -73,44 +64,45 @@ resultMap.put(ACTION, "updatefolder"); // Get the necessary parameters off of the request String method = getActionParameter(requestContext, "method"); - if (method == null) - { - throw new RuntimeException("Method not provided"); - } + if (method == null) { throw new RuntimeException( + "Method not provided"); } resultMap.put("method", method); if (false == checkAccess(requestContext, JetspeedActions.EDIT)) { success = false; - resultMap.put(REASON, "Insufficient access to administer portal permissions"); + resultMap.put(REASON, + "Insufficient access to administer portal permissions"); return success; - } + } int count = 0; String path = getActionParameter(requestContext, "path"); if (path == null) - throw new AJAXException("Missing 'path' parameter"); - Folder folder = null; + throw new AJAXException("Missing 'path' parameter"); + Folder folder = null; if (!method.equals("add")) { folder = pageManager.getFolder(path); - } + } else { if (pageManager.folderExists(path)) { success = false; - resultMap.put(REASON, "Can't create: Folder already exists: " + path); - return success; + resultMap.put(REASON, + "Can't create: Folder already exists: " + path); + return success; } - } + } if (method.equals("info")) { - count = updateInformation(requestContext, resultMap, folder, path); + count = updateInformation(requestContext, resultMap, folder, + path); } else if (method.equals("add-meta")) { count = insertMetadata(requestContext, resultMap, folder); } - else if ( method.equals("update-meta")) + else if (method.equals("update-meta")) { count = updateMetadata(requestContext, resultMap, folder); } @@ -120,61 +112,66 @@ } else if (method.equals("update-secref")) { - count = updateSecurityReference(requestContext, resultMap, folder); - } + count = updateSecurityReference(requestContext, resultMap, + folder); + } else if (method.equals("add-secref")) { - count = insertSecurityReference(requestContext, resultMap, folder); + count = insertSecurityReference(requestContext, resultMap, + folder); } else if (method.equals("remove-secref")) { - count = removeSecurityReference(requestContext, resultMap, folder); + count = removeSecurityReference(requestContext, resultMap, + folder); } else if (method.equals("remove-secdef")) { count = removeSecurityDef(requestContext, resultMap, folder); - } + } else if (method.equals("add")) { folder = pageManager.newFolder(path); folder.setTitle(getActionParameter(requestContext, "title")); String s = getActionParameter(requestContext, "short-title"); - if (!isBlank(s)) - folder.setShortTitle(s); - count++; + if (!isBlank(s)) folder.setShortTitle(s); + count++; } else if (method.equals("copy")) - { - String destination = getActionParameter(requestContext, "destination"); - String name = getActionParameter(requestContext, RESOURCE_NAME); - destination = destination + Folder.PATH_SEPARATOR + name; - pageManager.deepCopyFolder(folder,destination,null); + { + String destination = getActionParameter(requestContext, + "destination"); + String name = getActionParameter(requestContext, RESOURCE_NAME); + destination = destination + Folder.PATH_SEPARATOR + name; + pageManager.deepCopyFolder(folder, destination, null); } else if (method.equals("move")) - { - String destination = getActionParameter(requestContext, "destination"); - String name = getActionParameter(requestContext, RESOURCE_NAME); - destination = destination + Folder.PATH_SEPARATOR + name; - pageManager.deepCopyFolder(folder,destination,null); - pageManager.removeFolder(folder); - } + { + String destination = getActionParameter(requestContext, + "destination"); + String name = getActionParameter(requestContext, RESOURCE_NAME); + destination = destination + Folder.PATH_SEPARATOR + name; + pageManager.deepCopyFolder(folder, destination, null); + pageManager.removeFolder(folder); + } else if (method.equals("remove")) { pageManager.removeFolder(folder); - } + } else { success = false; - resultMap.put(REASON, "Unsupported Site Update method: " + method); - return success; + resultMap.put(REASON, "Unsupported Site Update method: " + + method); + return success; } if (count > 0) { - pageManager.updateFolder(folder); + pageManager.updateFolder(folder); } resultMap.put("count", Integer.toString(count)); resultMap.put(STATUS, status); - } + } catch (Exception e) { log.error("exception administering Site update", e); @@ -183,47 +180,51 @@ } return success; } - - protected int updateInformation(RequestContext requestContext, Map resultMap, Node node, String path) - throws AJAXException + + protected int updateInformation(RequestContext requestContext, + Map resultMap, Node node, String path) throws AJAXException { int count = 0; try { - Folder folder = (Folder)node; + Folder folder = (Folder) node; String title = getActionParameter(requestContext, "title"); if (isFieldModified(title, folder.getTitle())) folder.setTitle(title); - String shortTitle = getActionParameter(requestContext, "short-title"); + String shortTitle = getActionParameter(requestContext, + "short-title"); if (isFieldModified(shortTitle, folder.getShortTitle())) folder.setShortTitle(shortTitle); - String layoutDecorator = getActionParameter(requestContext, "layout-decorator"); - if (isFieldModified(layoutDecorator, folder.getDefaultDecorator(Fragment.LAYOUT))) + String layoutDecorator = getActionParameter(requestContext, + "layout-decorator"); + if (isFieldModified(layoutDecorator, folder + .getDefaultDecorator(Fragment.LAYOUT))) { - if (isBlank(layoutDecorator)) - layoutDecorator = null; + if (isBlank(layoutDecorator)) layoutDecorator = null; folder.setDefaultDecorator(layoutDecorator, Fragment.LAYOUT); } - String portletDecorator = getActionParameter(requestContext, "portlet-decorator"); - if (isFieldModified(portletDecorator, folder.getDefaultDecorator(Fragment.PORTLET))) + String portletDecorator = getActionParameter(requestContext, + "portlet-decorator"); + if (isFieldModified(portletDecorator, folder + .getDefaultDecorator(Fragment.PORTLET))) { - if (isBlank(portletDecorator)) - portletDecorator = null; + if (isBlank(portletDecorator)) portletDecorator = null; folder.setDefaultDecorator(portletDecorator, Fragment.PORTLET); } - String defaultPage = getActionParameter(requestContext, "default-page"); + String defaultPage = getActionParameter(requestContext, + "default-page"); if (isFieldModified(defaultPage, folder.getDefaultPage())) - folder.setDefaultPage(defaultPage); + folder.setDefaultPage(defaultPage); String hidden = getActionParameter(requestContext, "hidden"); if (isBooleanModified(hidden, folder.isHidden())) - folder.setHidden(!folder.isHidden()); + folder.setHidden(!folder.isHidden()); count++; } catch (Exception e) { throw new AJAXException(e); - } + } return count; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/UpdateLinkAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/UpdateLinkAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/UpdateLinkAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,35 +34,26 @@ /** * Update Link action -- updates various parts of the PSML link * - * AJAX Parameters: - * action = updatelink - * General methods: - * method = add | remove - * Info methods: - * | info - * Meta methods: - * | add-meta | update-meta | remove-meta - * Security methods: - * | add-secref | remove-secref - * + * AJAX Parameters: action = updatelink General methods: method = add | remove + * Info methods: | info Meta methods: | add-meta | update-meta | remove-meta + * Security methods: | add-secref | remove-secref + * * @author David Sean Taylor * @version $Id: $ */ -public class UpdateLinkAction - extends BaseSiteUpdateAction - implements AjaxAction, AjaxBuilder, Constants +public class UpdateLinkAction extends BaseSiteUpdateAction implements + AjaxAction, AjaxBuilder, Constants { + protected Log log = LogFactory.getLog(UpdateLinkAction.class); - public UpdateLinkAction(String template, - String errorTemplate, - PageManager pm, - PortletActionSecurityBehavior securityBehavior) - + public UpdateLinkAction(String template, String errorTemplate, + PageManager pm, PortletActionSecurityBehavior securityBehavior) + { - super(template, errorTemplate, pm, securityBehavior); + super(template, errorTemplate, pm, securityBehavior); } - + public boolean run(RequestContext requestContext, Map resultMap) throws AJAXException { @@ -73,33 +64,33 @@ resultMap.put(ACTION, "updatelink"); // Get the necessary parameters off of the request String method = getActionParameter(requestContext, "method"); - if (method == null) - { - throw new RuntimeException("Method not provided"); - } + if (method == null) { throw new RuntimeException( + "Method not provided"); } resultMap.put("method", method); if (false == checkAccess(requestContext, JetspeedActions.EDIT)) { success = false; - resultMap.put(REASON, "Insufficient access to administer portal permissions"); + resultMap.put(REASON, + "Insufficient access to administer portal permissions"); return success; - } + } int count = 0; String path = getActionParameter(requestContext, "path"); if (path == null) - throw new AJAXException("Missing 'path' parameter"); - Link link = null; + throw new AJAXException("Missing 'path' parameter"); + Link link = null; if (!method.equals("add")) { - link = pageManager.getLink(path); - } + link = pageManager.getLink(path); + } else { if (pageManager.linkExists(path)) { success = false; - resultMap.put(REASON, "Can't create: Link already exists: " + path); - return success; + resultMap.put(REASON, "Can't create: Link already exists: " + + path); + return success; } } if (method.equals("info")) @@ -125,7 +116,7 @@ else if (method.equals("update-secref")) { count = updateSecurityReference(requestContext, resultMap, link); - } + } else if (method.equals("remove-secref")) { count = removeSecurityReference(requestContext, resultMap, link); @@ -133,52 +124,54 @@ else if (method.equals("remove-secdef")) { count = removeSecurityDef(requestContext, resultMap, link); - } + } else if (method.equals("add")) { link = pageManager.newLink(path); link.setTitle(getActionParameter(requestContext, "title")); String s = getActionParameter(requestContext, "short-title"); - if (!isBlank(s)) - link.setShortTitle(s); + if (!isBlank(s)) link.setShortTitle(s); link.setUrl(getActionParameter(requestContext, "url")); count++; } else if (method.equals("copy")) - { - String destination = getActionParameter(requestContext, "destination"); - String name = getActionParameter(requestContext, RESOURCE_NAME); - destination = destination + Folder.PATH_SEPARATOR + name; - Link newLink = pageManager.copyLink(link, destination); - pageManager.updateLink(newLink); + { + String destination = getActionParameter(requestContext, + "destination"); + String name = getActionParameter(requestContext, RESOURCE_NAME); + destination = destination + Folder.PATH_SEPARATOR + name; + Link newLink = pageManager.copyLink(link, destination); + pageManager.updateLink(newLink); } else if (method.equals("move")) - { - String destination = getActionParameter(requestContext, "destination"); - String name = getActionParameter(requestContext, RESOURCE_NAME); - destination = destination + Folder.PATH_SEPARATOR + name; - Link newLink = pageManager.copyLink(link, destination); - pageManager.updateLink(newLink); - pageManager.removeLink(link); - - } + { + String destination = getActionParameter(requestContext, + "destination"); + String name = getActionParameter(requestContext, RESOURCE_NAME); + destination = destination + Folder.PATH_SEPARATOR + name; + Link newLink = pageManager.copyLink(link, destination); + pageManager.updateLink(newLink); + pageManager.removeLink(link); + + } else if (method.equals("remove")) { pageManager.removeLink(link); - } + } else { success = false; - resultMap.put(REASON, "Unsupported Site Update method: " + method); - return success; + resultMap.put(REASON, "Unsupported Site Update method: " + + method); + return success; } if (count > 0) { - pageManager.updateLink(link); - } + pageManager.updateLink(link); + } resultMap.put("count", Integer.toString(count)); resultMap.put(STATUS, status); - } + } catch (Exception e) { log.error("exception administering Site update", e); @@ -187,36 +180,35 @@ } return success; } - - protected int updateInformation(RequestContext requestContext, Map resultMap, Node node, String path) - throws AJAXException + + protected int updateInformation(RequestContext requestContext, + Map resultMap, Node node, String path) throws AJAXException { int count = 0; try { - Link link = (Link)node; + Link link = (Link) node; String title = getActionParameter(requestContext, "title"); - if (isFieldModified(title, link.getTitle())) - link.setTitle(title); - String shortTitle = getActionParameter(requestContext, "short-title"); + if (isFieldModified(title, link.getTitle())) link.setTitle(title); + String shortTitle = getActionParameter(requestContext, + "short-title"); if (isFieldModified(shortTitle, link.getShortTitle())) link.setShortTitle(shortTitle); String url = getActionParameter(requestContext, "url"); - if (isFieldModified(url, link.getUrl())) - link.setUrl(url); + if (isFieldModified(url, link.getUrl())) link.setUrl(url); String target = getActionParameter(requestContext, "target"); if (isFieldModified(target, link.getTarget())) - link.setTarget(target); + link.setTarget(target); String hidden = getActionParameter(requestContext, "hidden"); if (isBooleanModified(hidden, link.isHidden())) - link.setHidden(!link.isHidden()); + link.setHidden(!link.isHidden()); count++; } catch (Exception e) { throw new AJAXException(e); - } + } return count; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/UpdatePageAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/UpdatePageAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/layout/impl/UpdatePageAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -43,45 +43,37 @@ /** * Update Page action -- updates various parts of the PSML page * - * AJAX Parameters: - * action = updatepage - * General methods: - * method = add | remove - * Info methods: - * | info - * Meta methods: - * | add-meta | update-meta | remove-meta - * Security methods: - * | add-secref | remove-secref - * Fragment methods: - * | update-fragment | add-fragment | remove-fragment - * - * update-fragment params: id, layout(name), sizes, layoutid (add) - * + * AJAX Parameters: action = updatepage General methods: method = add | remove + * Info methods: | info Meta methods: | add-meta | update-meta | remove-meta + * Security methods: | add-secref | remove-secref Fragment methods: | + * update-fragment | add-fragment | remove-fragment + * + * update-fragment params: id, layout(name), sizes, layoutid (add) + * * @author David Sean Taylor * @version $Id: $ */ -public class UpdatePageAction - extends BaseSiteUpdateAction - implements AjaxAction, AjaxBuilder, Constants +public class UpdatePageAction extends BaseSiteUpdateAction implements + AjaxAction, AjaxBuilder, Constants { + protected Log log = LogFactory.getLog(UpdatePageAction.class); + protected PortletWindowAccessor windowAccess; + protected PortletEntityAccessComponent entityAccess; - - public UpdatePageAction(String template, - String errorTemplate, - PageManager pm, - PortletWindowAccessor windowAccess, - PortletEntityAccessComponent entityAccess, - PortletActionSecurityBehavior securityBehavior) - + + public UpdatePageAction(String template, String errorTemplate, + PageManager pm, PortletWindowAccessor windowAccess, + PortletEntityAccessComponent entityAccess, + PortletActionSecurityBehavior securityBehavior) + { super(template, errorTemplate, pm, securityBehavior); this.windowAccess = windowAccess; this.entityAccess = entityAccess; } - + public boolean run(RequestContext requestContext, Map resultMap) throws AJAXException { @@ -92,19 +84,18 @@ resultMap.put(ACTION, "updatepage"); // Get the necessary parameters off of the request String method = getActionParameter(requestContext, "method"); - if (method == null) - { - throw new RuntimeException("Method not provided"); - } + if (method == null) { throw new RuntimeException( + "Method not provided"); } resultMap.put("method", method); if (false == checkAccess(requestContext, JetspeedActions.EDIT)) { success = false; - resultMap.put(REASON, "Insufficient access to administer portal permissions"); + resultMap.put(REASON, + "Insufficient access to administer portal permissions"); return success; - } + } int count = 0; - Page page = null; + Page page = null; String path = getActionParameter(requestContext, "path"); if (path == null) { @@ -121,8 +112,9 @@ if (pageManager.pageExists(path)) { success = false; - resultMap.put(REASON, "Can't create: Page already exists: " + path); - return success; + resultMap.put(REASON, + "Can't create: Page already exists: " + path); + return success; } } } @@ -149,7 +141,7 @@ else if (method.equals("update-secref")) { count = updateSecurityReference(requestContext, resultMap, page); - } + } else if (method.equals("remove-secref")) { count = removeSecurityReference(requestContext, resultMap, page); @@ -157,94 +149,108 @@ else if (method.equals("remove-secdef")) { count = removeSecurityDef(requestContext, resultMap, page); - } + } else if (method.equals("add")) { page = pageManager.newPage(path); page.setTitle(getActionParameter(requestContext, TITLE)); - String s = getActionParameter(requestContext, SHORT_TITLE ); - if (!isBlank(s)) - page.setShortTitle(s); - page.getRootFragment().setName(getActionParameter(requestContext, DEFAULT_LAYOUT)); - count++; + String s = getActionParameter(requestContext, SHORT_TITLE); + if (!isBlank(s)) page.setShortTitle(s); + page.getRootFragment().setName( + getActionParameter(requestContext, DEFAULT_LAYOUT)); + count++; } else if (method.equals("copy")) - { - String destination = getActionParameter(requestContext, "destination"); - String name = getActionParameter(requestContext, RESOURCE_NAME); - destination = destination + Folder.PATH_SEPARATOR + name; - Page newPage = pageManager.copyPage(page,destination); - pageManager.updatePage(newPage); + { + String destination = getActionParameter(requestContext, + "destination"); + String name = getActionParameter(requestContext, RESOURCE_NAME); + destination = destination + Folder.PATH_SEPARATOR + name; + Page newPage = pageManager.copyPage(page, destination); + pageManager.updatePage(newPage); } else if (method.equals("move")) - { - String destination = getActionParameter(requestContext, "destination"); - String name = getActionParameter(requestContext, RESOURCE_NAME); - destination = destination + Folder.PATH_SEPARATOR + name; - Page newPage = pageManager.copyPage(page, destination); - pageManager.updatePage(newPage); - pageManager.removePage(page); - } + { + String destination = getActionParameter(requestContext, + "destination"); + String name = getActionParameter(requestContext, RESOURCE_NAME); + destination = destination + Folder.PATH_SEPARATOR + name; + Page newPage = pageManager.copyPage(page, destination); + pageManager.updatePage(newPage); + pageManager.removePage(page); + } else if (method.equals("remove")) { pageManager.removePage(page); } else if (method.equals("update-fragment")) { - String fragmentId = getActionParameter(requestContext, PORTLETID); - String layout = getActionParameter(requestContext, LAYOUT); + String fragmentId = getActionParameter(requestContext, + PORTLETID); + String layout = getActionParameter(requestContext, LAYOUT); if (isBlank(fragmentId) || isBlank(layout)) { - resultMap.put(REASON, "Missing parameter to update fragment"); - return false; - } - count = updateFragment(requestContext, resultMap, page, fragmentId, layout); + resultMap.put(REASON, + "Missing parameter to update fragment"); + return false; + } + count = updateFragment(requestContext, resultMap, page, + fragmentId, layout); } else if (method.equals("add-fragment")) { String parentId = getActionParameter(requestContext, LAYOUTID); - String layout = getActionParameter(requestContext, LAYOUT); + String layout = getActionParameter(requestContext, LAYOUT); if (isBlank(parentId) || isBlank(layout)) { - resultMap.put(REASON, "Missing parameter to add fragment"); - return false; - } - count = addFragment(requestContext, resultMap, page, parentId, layout); + resultMap.put(REASON, "Missing parameter to add fragment"); + return false; + } + count = addFragment(requestContext, resultMap, page, parentId, + layout); } else if (method.equals("remove-fragment")) { - String fragmentId = getActionParameter(requestContext, PORTLETID); + String fragmentId = getActionParameter(requestContext, + PORTLETID); if (isBlank(fragmentId)) { - resultMap.put(REASON, "Missing parameter to remove fragment"); - return false; - } - count = removeFragment(requestContext, resultMap, page, fragmentId); + resultMap.put(REASON, + "Missing parameter to remove fragment"); + return false; + } + count = removeFragment(requestContext, resultMap, page, + fragmentId); } else if (method.equals("update-portlet-decorator")) { - String fragmentId = getActionParameter(requestContext, PORTLETID); - String portletDecorator = getActionParameter(requestContext, "portlet-decorator"); + String fragmentId = getActionParameter(requestContext, + PORTLETID); + String portletDecorator = getActionParameter(requestContext, + "portlet-decorator"); if (isBlank(fragmentId) || isBlank(portletDecorator)) { - resultMap.put(REASON, "Missing parameter to update portlet decorator"); - return false; - } - count = updatePortletDecorator(requestContext, resultMap, page, fragmentId, portletDecorator); + resultMap.put(REASON, + "Missing parameter to update portlet decorator"); + return false; + } + count = updatePortletDecorator(requestContext, resultMap, page, + fragmentId, portletDecorator); } else { success = false; - resultMap.put(REASON, "Unsupported Site Update method: " + method); - return success; + resultMap.put(REASON, "Unsupported Site Update method: " + + method); + return success; } if (count > 0) { - pageManager.updatePage(page); - } + pageManager.updatePage(page); + } resultMap.put("count", Integer.toString(count)); resultMap.put(STATUS, status); - } + } catch (Exception e) { log.error("exception administering Site update", e); @@ -253,40 +259,48 @@ } return success; } - - protected int updatePortletDecorator(RequestContext requestContext, Map resultMap, Page page, String fragmentId, String portletDecorator) - throws PortletEntityNotStoredException, FailedToRetrievePortletWindow + + protected int updatePortletDecorator(RequestContext requestContext, + Map resultMap, Page page, String fragmentId, String portletDecorator) + throws PortletEntityNotStoredException, + FailedToRetrievePortletWindow { - int count = 0; - Fragment fragment = page.getFragmentById(fragmentId); + int count = 0; + Fragment fragment = page.getFragmentById(fragmentId); if (fragment != null) - { - fragment.setDecorator( portletDecorator ); - count++; + { + fragment.setDecorator(portletDecorator); + count++; } - return count; + return count; } - - protected int updateFragment(RequestContext requestContext, Map resultMap, Page page, String fragmentId, String layout) - throws PortletEntityNotStoredException, FailedToRetrievePortletWindow + + protected int updateFragment(RequestContext requestContext, Map resultMap, + Page page, String fragmentId, String layout) + throws PortletEntityNotStoredException, + FailedToRetrievePortletWindow { int count = 0; String sizes = getActionParameter(requestContext, SIZES); Fragment fragment = page.getFragmentById(fragmentId); if (fragment != null) - { + { if (!layout.equals(fragment.getName())) { fragment.setName(layout); - ContentFragment contentFragment = new ContentFragmentImpl(fragment, new HashMap()); - PortletWindow window = windowAccess.getPortletWindow(contentFragment); + ContentFragment contentFragment = new ContentFragmentImpl( + fragment, new HashMap()); + PortletWindow window = windowAccess + .getPortletWindow(contentFragment); if (window != null) { - entityAccess.updatePortletEntity(window.getPortletEntity(), contentFragment); + entityAccess.updatePortletEntity(window.getPortletEntity(), + contentFragment); entityAccess.storePortletEntity(window.getPortletEntity()); - windowAccess.createPortletWindow(window.getPortletEntity(), contentFragment.getId()); + windowAccess.createPortletWindow(window.getPortletEntity(), + contentFragment.getId()); count++; - if ( isBlank(sizes) ) + if (isBlank(sizes)) { fragment.setLayoutSizes(null); } @@ -309,7 +323,8 @@ return count; } - protected int addFragment(RequestContext requestContext, Map resultMap, Page page, String parentFragmentId, String layout) + protected int addFragment(RequestContext requestContext, Map resultMap, + Page page, String parentFragmentId, String layout) { int count = 0; String sizes = getActionParameter(requestContext, SIZES); @@ -317,10 +332,10 @@ if (fragment != null) { Fragment newFragment = pageManager.newFragment(); - newFragment.setType(Fragment.LAYOUT); + newFragment.setType(Fragment.LAYOUT); newFragment.setName(layout); - fragment.getFragments().add(newFragment); - resultMap.put(PORTLETID, newFragment.getId()); + fragment.getFragments().add(newFragment); + resultMap.put(PORTLETID, newFragment.getId()); count++; if (!isBlank(sizes)) { @@ -331,7 +346,8 @@ return count; } - protected int removeFragment(RequestContext requestContext, Map resultMap, Page page, String fragmentId) + protected int removeFragment(RequestContext requestContext, Map resultMap, + Page page, String fragmentId) { int count = 0; Fragment fragment = page.getFragmentById(fragmentId); @@ -341,52 +357,57 @@ count++; } return count; - } - - protected int updateInformation(RequestContext requestContext, Map resultMap, Node node, String path) - throws AJAXException + } + + protected int updateInformation(RequestContext requestContext, + Map resultMap, Node node, String path) throws AJAXException { int count = 0; try { - Page page = (Page)node; + Page page = (Page) node; String title = getActionParameter(requestContext, "title"); if (title != null && isFieldModified(title, page.getTitle())) page.setTitle(title); - String shortTitle = getActionParameter(requestContext, "short-title"); - if (shortTitle != null && isFieldModified(shortTitle, page.getShortTitle())) + String shortTitle = getActionParameter(requestContext, + "short-title"); + if (shortTitle != null + && isFieldModified(shortTitle, page.getShortTitle())) page.setShortTitle(shortTitle); - String layoutDecorator = getActionParameter(requestContext, "layout-decorator"); - if (layoutDecorator != null && isFieldModified(layoutDecorator, page.getDefaultDecorator(Fragment.LAYOUT))) + String layoutDecorator = getActionParameter(requestContext, + "layout-decorator"); + if (layoutDecorator != null + && isFieldModified(layoutDecorator, page + .getDefaultDecorator(Fragment.LAYOUT))) { - if (isBlank(layoutDecorator)) - layoutDecorator = null; + if (isBlank(layoutDecorator)) layoutDecorator = null; page.setDefaultDecorator(layoutDecorator, Fragment.LAYOUT); } - String portletDecorator = getActionParameter(requestContext, "portlet-decorator"); - if (portletDecorator != null && isFieldModified(portletDecorator, page.getDefaultDecorator(Fragment.PORTLET))) + String portletDecorator = getActionParameter(requestContext, + "portlet-decorator"); + if (portletDecorator != null + && isFieldModified(portletDecorator, page + .getDefaultDecorator(Fragment.PORTLET))) { - if (isBlank(portletDecorator)) - portletDecorator = null; + if (isBlank(portletDecorator)) portletDecorator = null; page.setDefaultDecorator(portletDecorator, Fragment.PORTLET); } String theme = getActionParameter(requestContext, "theme"); if (theme != null && isFieldModified(theme, page.getSkin())) { - if (isBlank(theme)) - theme = null; + if (isBlank(theme)) theme = null; page.setSkin(theme); } String hidden = getActionParameter(requestContext, "hidden"); if (hidden != null && isBooleanModified(hidden, page.isHidden())) - page.setHidden(!page.isHidden()); + page.setHidden(!page.isHidden()); count++; } catch (Exception e) { throw new AJAXException(e); - } + } return count; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/localization/impl/LocalizationValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/localization/impl/LocalizationValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/localization/impl/LocalizationValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -46,17 +46,23 @@ * @author David Sean Taylor * @version $Id: LocalizationValveImpl.java 516448 2007-03-09 16:25:47Z ate $ */ -public class LocalizationValveImpl extends AbstractValve implements LocalizationValve +public class LocalizationValveImpl extends AbstractValve implements + LocalizationValve { - private static final Log log = LogFactory.getLog(LocalizationValveImpl.class); + + private static final Log log = LogFactory + .getLog(LocalizationValveImpl.class); + private Locale defaultLocale = null; - - public LocalizationValveImpl() {} - + + public LocalizationValveImpl() + { + } + public LocalizationValveImpl(String defaultLanguage) { String language = defaultLanguage != null ? defaultLanguage.trim() : ""; - if (language.length()>0) + if (language.length() > 0) { // Code taken from LocaleSelectorPorltet String country = ""; @@ -76,68 +82,87 @@ } defaultLocale = new Locale(language, country, variant); - if ( defaultLocale.getLanguage().length() == 0 ) + if (defaultLocale.getLanguage().length() == 0) { // not a valid language defaultLocale = null; - log.warn("Invalid or unrecognized default language: "+language); + log.warn("Invalid or unrecognized default language: " + + language); } else { - log.info("Default language set: "+defaultLocale); + log.info("Default language set: " + defaultLocale); } - + } } - + /* * (non-Javadoc) * * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, * org.apache.jetspeed.pipeline.valve.ValveContext) */ - public void invoke( RequestContext request, ValveContext context ) throws PipelineException + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { - Locale locale = (Locale)request.getRequest().getSession().getAttribute(PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE); + Locale locale = (Locale) request.getRequest().getSession() + .getAttribute( + PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE); if (null == locale) - { - // Get the prefered locale from user's preferences(persistent storage) if not anon user + { + // Get the prefered locale from user's preferences(persistent + // storage) if not anon user Subject subject = request.getSubject(); if (null != subject) { - Principal userPrincipal = SecurityHelper.getPrincipal(subject, UserPrincipal.class); + Principal userPrincipal = SecurityHelper.getPrincipal(subject, + UserPrincipal.class); if (null != userPrincipal) { log.debug("Got user principal: " + userPrincipal.getName()); - UserManager userMgr = (UserManager) Jetspeed.getComponentManager().getComponent(UserManager.class); + UserManager userMgr = (UserManager) Jetspeed + .getComponentManager().getComponent( + UserManager.class); try { - if (!userMgr.getAnonymousUser().equals(userPrincipal.getName()) + if (!userMgr.getAnonymousUser().equals( + userPrincipal.getName()) && userMgr.userExists(userPrincipal.getName())) { - User user = userMgr.getUser(userPrincipal.getName()); - // TODO if preferred lang or locale is defined in PLT.D, it's better to use it + User user = userMgr + .getUser(userPrincipal.getName()); + // TODO if preferred lang or locale is defined in + // PLT.D, it's better to use it Preferences prefs = user.getPreferences(); - String localeString = prefs.get(PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE, null); + String localeString = prefs + .get( + PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE, + null); if (localeString != null) { - locale = JetspeedLocale.convertStringToLocale(localeString); + locale = JetspeedLocale + .convertStringToLocale(localeString); } } } catch (SecurityException e) { - log.warn("Unexpected SecurityException in UserInfoManager", e); + log + .warn( + "Unexpected SecurityException in UserInfoManager", + e); } } } } if (locale == null) { - locale = (Locale) request.getSessionAttribute(PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE); + locale = (Locale) request + .getSessionAttribute(PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE); } - - if ( locale == null && defaultLocale != null ) + + if (locale == null && defaultLocale != null) { locale = defaultLocale; } @@ -146,7 +171,7 @@ { locale = request.getRequest().getLocale(); } - + if (locale == null) { Enumeration preferedLocales = request.getRequest().getLocales(); @@ -162,10 +187,12 @@ } request.setLocale(locale); - request.getRequest().setAttribute(PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE, locale); - request.getRequest().getSession().setAttribute(PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE, locale); + request.getRequest().setAttribute( + PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE, locale); + request.getRequest().getSession().setAttribute( + PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE, locale); CurrentLocale.set(locale); - + // Pass control to the next Valve in the Pipeline context.invokeNext(request); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/localization/impl/SimplifiedLocalizationValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/localization/impl/SimplifiedLocalizationValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/localization/impl/SimplifiedLocalizationValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -35,17 +35,23 @@ * @author David Sean Taylor * @version $Id: LocalizationValveImpl.java 378091 2006-02-15 21:12:28Z taylor $ */ -public class SimplifiedLocalizationValveImpl extends AbstractValve implements LocalizationValve +public class SimplifiedLocalizationValveImpl extends AbstractValve implements + LocalizationValve { - private static final Log log = LogFactory.getLog(LocalizationValveImpl.class); + + private static final Log log = LogFactory + .getLog(LocalizationValveImpl.class); + private Locale defaultLocale = null; - - public SimplifiedLocalizationValveImpl() {} - + + public SimplifiedLocalizationValveImpl() + { + } + public SimplifiedLocalizationValveImpl(String defaultLanguage) { String language = defaultLanguage != null ? defaultLanguage.trim() : ""; - if (language.length()>0) + if (language.length() > 0) { // Code taken from LocaleSelectorPorltet String country = ""; @@ -65,31 +71,35 @@ } defaultLocale = new Locale(language, country, variant); - if ( defaultLocale.getLanguage().length() == 0 ) + if (defaultLocale.getLanguage().length() == 0) { // not a valid language defaultLocale = null; - log.warn("Invalid or unrecognized default language: "+language); + log.warn("Invalid or unrecognized default language: " + + language); } else { - log.info("Default language set: "+defaultLocale); + log.info("Default language set: " + defaultLocale); } - + } } - + /* * (non-Javadoc) * * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, * org.apache.jetspeed.pipeline.valve.ValveContext) */ - public void invoke( RequestContext request, ValveContext context ) throws PipelineException + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { - Locale locale = (Locale)request.getRequest().getSession().getAttribute(PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE); - - if ( locale == null && defaultLocale != null ) + Locale locale = (Locale) request.getRequest().getSession() + .getAttribute( + PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE); + + if (locale == null && defaultLocale != null) { locale = defaultLocale; } @@ -98,7 +108,7 @@ { locale = request.getRequest().getLocale(); } - + if (locale == null) { Enumeration preferedLocales = request.getRequest().getLocales(); @@ -114,10 +124,12 @@ } request.setLocale(locale); - request.getRequest().setAttribute(PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE, locale); - request.getRequest().getSession().setAttribute(PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE, locale); + request.getRequest().setAttribute( + PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE, locale); + request.getRequest().getSession().setAttribute( + PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE, locale); CurrentLocale.set(locale); - + // Pass control to the next Valve in the Pipeline context.invokeNext(request); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginErrorServlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginErrorServlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginErrorServlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -36,18 +36,18 @@ public class LoginErrorServlet extends HttpServlet { - public void doGet(HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { HttpSession session = request.getSession(); - // String destination = (String) session - // .getAttribute(LoginConstants.DESTINATION); - // if (destination == null) - // destination = request.getContextPath() + "/"; - // else - // session.removeAttribute(LoginConstants.DESTINATION); + // String destination = (String) session + // .getAttribute(LoginConstants.DESTINATION); + // if (destination == null) + // destination = request.getContextPath() + "/"; + // else + // session.removeAttribute(LoginConstants.DESTINATION); String destination = request.getContextPath() + "/login/proxy"; - + Integer retryCount = (Integer) session .getAttribute(LoginConstants.RETRYCOUNT); if (retryCount == null) @@ -56,12 +56,16 @@ retryCount = new Integer(retryCount.intValue() + 1); session.setAttribute(LoginConstants.RETRYCOUNT, retryCount); - String username = (String)session.getAttribute(LoginConstants.USERNAME); - AuditActivity audit = (AuditActivity)Jetspeed.getComponentManager().getComponent("org.apache.jetspeed.audit.AuditActivity"); + String username = (String) session + .getAttribute(LoginConstants.USERNAME); + AuditActivity audit = (AuditActivity) Jetspeed.getComponentManager() + .getComponent("org.apache.jetspeed.audit.AuditActivity"); if (audit != null) { - audit.logUserActivity(username, request.getRemoteAddr(), AuditActivity.AUTHENTICATION_FAILURE, "Active Authentication"); - } + audit.logUserActivity(username, request.getRemoteAddr(), + AuditActivity.AUTHENTICATION_FAILURE, + "Active Authentication"); + } response.sendRedirect(response.encodeURL(destination)); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginProxyServlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginProxyServlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginProxyServlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -41,8 +41,9 @@ */ public class LoginProxyServlet extends HttpServlet { + private boolean credentialsFromRequest = true; - + public void init(ServletConfig config) throws ServletException { super.init(config); @@ -53,13 +54,13 @@ } } - public void doGet(HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { String parameter; String username; - request.setCharacterEncoding( "UTF-8" ); - + request.setCharacterEncoding("UTF-8"); + HttpSession session = request.getSession(true); parameter = request.getParameter(LoginConstants.DESTINATION); @@ -82,10 +83,10 @@ } else { - username = (String)session.getAttribute(LoginConstants.USERNAME); - parameter = (String)session.getAttribute(LoginConstants.PASSWORD); + username = (String) session.getAttribute(LoginConstants.USERNAME); + parameter = (String) session.getAttribute(LoginConstants.PASSWORD); } - + // Globaly override all psml themes if (request .getParameter(PortalReservedParameters.PAGE_THEME_OVERRIDE_ATTRIBUTE) != null) @@ -97,21 +98,28 @@ decoratorName); } - PortalAuthenticationConfiguration authenticationConfiguration = (PortalAuthenticationConfiguration) - Jetspeed.getComponentManager().getComponent("org.apache.jetspeed.administration.PortalAuthenticationConfiguration"); + PortalAuthenticationConfiguration authenticationConfiguration = (PortalAuthenticationConfiguration) Jetspeed + .getComponentManager() + .getComponent( + "org.apache.jetspeed.administration.PortalAuthenticationConfiguration"); if (authenticationConfiguration.isCreateNewSessionOnLogin()) { - - ActiveAuthenticationIdentityProvider identityProvider = (ActiveAuthenticationIdentityProvider) - Jetspeed.getComponentManager().getComponent("org.apache.jetspeed.security.activeauthentication.ActiveAuthenticationIdentityProvider"); - IdentityToken token = identityProvider.createIdentityToken(username); - saveState(session, token, identityProvider.getSessionAttributeNames()); + + ActiveAuthenticationIdentityProvider identityProvider = (ActiveAuthenticationIdentityProvider) Jetspeed + .getComponentManager() + .getComponent( + "org.apache.jetspeed.security.activeauthentication.ActiveAuthenticationIdentityProvider"); + IdentityToken token = identityProvider + .createIdentityToken(username); + saveState(session, token, identityProvider + .getSessionAttributeNames()); request.getSession().invalidate(); HttpSession newSession = request.getSession(true); restoreState(newSession, token); response.sendRedirect(response.encodeURL(request.getContextPath() - + "/login/redirector?token=") + token.getToken()); - + + "/login/redirector?token=") + + token.getToken()); + } else { @@ -120,12 +128,13 @@ } } - protected void saveState(HttpSession session, IdentityToken token, List sessionAttributes) + protected void saveState(HttpSession session, IdentityToken token, + List sessionAttributes) { Iterator sessionNames = sessionAttributes.iterator(); while (sessionNames.hasNext()) { - String name = (String)sessionNames.next(); + String name = (String) sessionNames.next(); token.setAttribute(name, session.getAttribute(name)); } } @@ -135,12 +144,12 @@ Iterator names = token.getAttributeNames(); while (names.hasNext()) { - String name = (String)names.next(); + String name = (String) names.next(); Object attribute = token.getAttribute(name); session.setAttribute(name, attribute); - } + } } - + public final void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginRedirectorServlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginRedirectorServlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginRedirectorServlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,8 +37,8 @@ public class LoginRedirectorServlet extends HttpServlet { - public void doGet(HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { HttpSession session = request.getSession(true); String destination = (String) session @@ -48,17 +48,22 @@ else session.removeAttribute(LoginConstants.DESTINATION); - String username = (String)session.getAttribute(LoginConstants.USERNAME); - + String username = (String) session + .getAttribute(LoginConstants.USERNAME); + session.removeAttribute(LoginConstants.USERNAME); session.removeAttribute(LoginConstants.PASSWORD); session.removeAttribute(LoginConstants.RETRYCOUNT); - session.removeAttribute(PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE); + session + .removeAttribute(PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE); - AuditActivity audit = (AuditActivity)Jetspeed.getComponentManager().getComponent("org.apache.jetspeed.audit.AuditActivity"); + AuditActivity audit = (AuditActivity) Jetspeed.getComponentManager() + .getComponent("org.apache.jetspeed.audit.AuditActivity"); if (audit != null) { - audit.logUserActivity(username, request.getRemoteAddr(), AuditActivity.AUTHENTICATION_SUCCESS, "Active Authentication"); + audit.logUserActivity(username, request.getRemoteAddr(), + AuditActivity.AUTHENTICATION_SUCCESS, + "Active Authentication"); } response.sendRedirect(response.encodeURL(destination)); } @@ -67,5 +72,5 @@ HttpServletResponse response) throws IOException, ServletException { doGet(request, response); - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginServlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginServlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LoginServlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -42,10 +42,11 @@ */ public class LoginServlet extends HttpServlet { + private static final Log log = LogFactory.getLog(LoginServlet.class); - public void doGet(HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { HttpSession session = request.getSession(true); @@ -54,34 +55,40 @@ String destination = (String) session .getAttribute(LoginConstants.DESTINATION); if (destination == null) - destination = request.getContextPath() + "/"; + destination = request.getContextPath() + "/"; response.sendRedirect(response.encodeURL(destination)); } if (Jetspeed.getEngine() != null) { - request.setAttribute(PortalReservedParameters.PIPELINE, PortalReservedParameters.LOGIN_PIPELINE); + request.setAttribute(PortalReservedParameters.PIPELINE, + PortalReservedParameters.LOGIN_PIPELINE); Engine engine = Jetspeed.getEngine(); try { - RequestContextComponent contextComponent = (RequestContextComponent) Jetspeed.getComponentManager() - .getComponent(RequestContextComponent.class); - RequestContext context = contextComponent.create(request, response, getServletConfig()); + RequestContextComponent contextComponent = (RequestContextComponent) Jetspeed + .getComponentManager().getComponent( + RequestContextComponent.class); + RequestContext context = contextComponent.create(request, + response, getServletConfig()); engine.service(context); contextComponent.release(context); } catch (JetspeedException e) { log.warn("Jetspeed engine does not work properly.", e); - // forward to JetspeedServlet - response.sendRedirect(response.encodeURL(request.getContextPath() + "/")); + // forward to JetspeedServlet + response.sendRedirect(response.encodeURL(request + .getContextPath() + + "/")); } } else { // forward to JetspeedServlet to create Engine - response.sendRedirect(response.encodeURL(request.getContextPath() + "/")); + response.sendRedirect(response.encodeURL(request.getContextPath() + + "/")); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LogoutServlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LogoutServlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/LogoutServlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,14 +32,14 @@ public class LogoutServlet extends HttpServlet { - public void doGet(HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { String destination = request.getParameter(LoginConstants.DESTINATION); request.getSession(true).invalidate(); if (destination == null) { - destination = request.getContextPath() + "/"; + destination = request.getContextPath() + "/"; } response.sendRedirect(response.encodeURL(destination)); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/filter/PortalFilter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/filter/PortalFilter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/filter/PortalFilter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -47,34 +47,41 @@ public class PortalFilter implements Filter { + protected String guest = "guest"; - + public void init(FilterConfig filterConfig) throws ServletException { PortalConfiguration config = Jetspeed.getConfiguration(); - if (config != null) - guest = config.getString("default.user.principal"); + if (config != null) guest = config.getString("default.user.principal"); } - public void doFilter(ServletRequest sRequest, - ServletResponse sResponse, FilterChain filterChain) - throws IOException, ServletException + public void doFilter(ServletRequest sRequest, ServletResponse sResponse, + FilterChain filterChain) throws IOException, ServletException { if (sRequest instanceof HttpServletRequest) { - HttpServletRequest request = (HttpServletRequest)sRequest; + HttpServletRequest request = (HttpServletRequest) sRequest; String username = request.getParameter(LoginConstants.USERNAME); - String password = request.getParameter(LoginConstants.PASSWORD); + String password = request.getParameter(LoginConstants.PASSWORD); if (username != null) { - UserManager userManager = (UserManager)Jetspeed.getComponentManager().getComponent("org.apache.jetspeed.security.UserManager"); - AuditActivity audit = (AuditActivity)Jetspeed.getComponentManager().getComponent("org.apache.jetspeed.audit.AuditActivity"); + UserManager userManager = (UserManager) Jetspeed + .getComponentManager().getComponent( + "org.apache.jetspeed.security.UserManager"); + AuditActivity audit = (AuditActivity) Jetspeed + .getComponentManager().getComponent( + "org.apache.jetspeed.audit.AuditActivity"); boolean success = userManager.authenticate(username, password); if (success) { - audit.logUserActivity(username, request.getRemoteAddr(), AuditActivity.AUTHENTICATION_SUCCESS, "PortalFilter"); - PortalAuthenticationConfiguration authenticationConfiguration = (PortalAuthenticationConfiguration) - Jetspeed.getComponentManager().getComponent("org.apache.jetspeed.administration.PortalAuthenticationConfiguration"); + audit.logUserActivity(username, request.getRemoteAddr(), + AuditActivity.AUTHENTICATION_SUCCESS, + "PortalFilter"); + PortalAuthenticationConfiguration authenticationConfiguration = (PortalAuthenticationConfiguration) Jetspeed + .getComponentManager() + .getComponent( + "org.apache.jetspeed.administration.PortalAuthenticationConfiguration"); if (authenticationConfiguration.isCreateNewSessionOnLogin()) { request.getSession().invalidate(); @@ -84,65 +91,80 @@ { // load the user principals (roles, groups, credentials) User user = userManager.getUser(username); - if ( user != null ) + if (user != null) { subject = user.getSubject(); } } catch (SecurityException sex) { - } + } if (subject == null) { Set principals = new PrincipalsSet(); - UserSubjectPrincipalImpl userPrincipal = new UserSubjectPrincipalImpl(username); + UserSubjectPrincipalImpl userPrincipal = new UserSubjectPrincipalImpl( + username); principals.add(userPrincipal); - subject = new Subject(true, principals, new HashSet(), new HashSet()); + subject = new Subject(true, principals, new HashSet(), + new HashSet()); userPrincipal.setSubject(subject); } - Principal principal = SecurityHelper.getPrincipal(subject, UserPrincipal.class); + Principal principal = SecurityHelper.getPrincipal(subject, + UserPrincipal.class); sRequest = wrapperRequest(request, subject, principal); - request.getSession().removeAttribute(LoginConstants.ERRORCODE); + request.getSession().removeAttribute( + LoginConstants.ERRORCODE); HttpSession session = request.getSession(true); - session.setAttribute(PortalReservedParameters.SESSION_KEY_SUBJECT, subject); - //System.out.println("*** login session = " + session); + session.setAttribute( + PortalReservedParameters.SESSION_KEY_SUBJECT, + subject); + // System.out.println("*** login session = " + session); } else { - audit.logUserActivity(username, request.getRemoteAddr(), AuditActivity.AUTHENTICATION_FAILURE, "PortalFilter"); - request.getSession().setAttribute(LoginConstants.ERRORCODE, LoginConstants.ERROR_INVALID_PASSWORD); + audit.logUserActivity(username, request.getRemoteAddr(), + AuditActivity.AUTHENTICATION_FAILURE, + "PortalFilter"); + request.getSession().setAttribute(LoginConstants.ERRORCODE, + LoginConstants.ERROR_INVALID_PASSWORD); } } else { - //HttpSession session = request.getSession(); - //System.out.println("*** session = " + session); - Subject subject = (Subject)request.getSession().getAttribute(PortalReservedParameters.SESSION_KEY_SUBJECT); + // HttpSession session = request.getSession(); + // System.out.println("*** session = " + session); + Subject subject = (Subject) request.getSession().getAttribute( + PortalReservedParameters.SESSION_KEY_SUBJECT); if (subject != null) { - Principal principal = SecurityHelper.getPrincipal(subject, UserPrincipal.class); - if (principal != null && principal.getName().equals(this.guest)) - { + Principal principal = SecurityHelper.getPrincipal(subject, + UserPrincipal.class); + if (principal != null + && principal.getName().equals(this.guest)) + { } else { sRequest = wrapperRequest(request, subject, principal); } - } - } + } + } - sRequest.setAttribute(PortalReservedParameters.PORTAL_FILTER_ATTRIBUTE, "true"); + sRequest.setAttribute( + PortalReservedParameters.PORTAL_FILTER_ATTRIBUTE, "true"); } - + if (filterChain != null) { filterChain.doFilter(sRequest, sResponse); } } - - private ServletRequest wrapperRequest(HttpServletRequest request, Subject subject, Principal principal) + + private ServletRequest wrapperRequest(HttpServletRequest request, + Subject subject, Principal principal) { - PortalRequestWrapper wrapper = new PortalRequestWrapper(request, subject, principal); + PortalRequestWrapper wrapper = new PortalRequestWrapper(request, + subject, principal); return wrapper; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/filter/PortalRequestWrapper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/filter/PortalRequestWrapper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/filter/PortalRequestWrapper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,9 +29,11 @@ public class PortalRequestWrapper extends HttpServletRequestWrapper { + private Principal userPrincipal = null; - private Subject subject ; - + + private Subject subject; + public PortalRequestWrapper(HttpServletRequest request, Subject subject, Principal userPrincipal) { @@ -42,21 +44,17 @@ public boolean isUserInRole(String roleName) { - if (subject == null) - { - return false; - } + if (subject == null) { return false; } List roles = SecurityHelper.getPrincipals(subject, RolePrincipal.class); Iterator ir = roles.iterator(); while (ir.hasNext()) { - RolePrincipal role = (RolePrincipal)ir.next(); - if (roleName.equals(role.getName())) - return true; + RolePrincipal role = (RolePrincipal) ir.next(); + if (roleName.equals(role.getName())) return true; } return false; } - + public void setUserPrincipal(Principal userPrincipal) { this.userPrincipal = userPrincipal; @@ -68,8 +66,8 @@ } /** - * Return the name of the remote user that has been authenticated - * for this Request. + * Return the name of the remote user that has been authenticated for this + * Request. */ public String getRemoteUser() { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/impl/LoginJSPViewValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/impl/LoginJSPViewValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/login/impl/LoginJSPViewValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,11 +33,13 @@ * LoginJSPViewValveImpl * * TODO: move this class into a new component? + * * @author Shinsuke Sugaya * @version $Id: LoginJSPViewValve.java 186726 2004-06-05 05:13:09Z shinsuke $ */ public class LoginJSPViewValve extends AbstractValve implements LoginViewValve { + private static final Log log = LogFactory.getLog(LoginJSPViewValve.class); private static final String DEFAULT_TEMPLATE_PATH = "/WEB-INF/templates/login"; @@ -60,24 +62,34 @@ * @see org.apache.jetspeed.pipeline.valve.AbstractValve#invoke(org.apache.jetspeed.request.RequestContext, * org.apache.jetspeed.pipeline.valve.ValveContext) */ - public void invoke(RequestContext request, ValveContext context) throws PipelineException + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { - String loginTemplateFile = templatePath + "/" + request.getMediaType() + "/login.jsp"; + String loginTemplateFile = templatePath + "/" + request.getMediaType() + + "/login.jsp"; try { - RequestDispatcher rd = request.getRequest().getRequestDispatcher(loginTemplateFile); + RequestDispatcher rd = request.getRequest().getRequestDispatcher( + loginTemplateFile); rd.include(request.getRequest(), request.getResponse()); } catch (ServletException e) { - log.warn("The included login template file threw the exception.", e); - throw new PipelineException("The included login template file threw the exception.", e); + log + .warn( + "The included login template file threw the exception.", + e); + throw new PipelineException( + "The included login template file threw the exception.", e); } catch (IOException e) { - log.warn("I/O error occurred on the included login template file.", e); - throw new PipelineException("I/O error occurred on the included login template file.", e); + log.warn("I/O error occurred on the included login template file.", + e); + throw new PipelineException( + "I/O error occurred on the included login template file.", + e); } // Pass control to the next Valve in the Pipeline Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/manager/ManagerServlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/manager/ManagerServlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/manager/ManagerServlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -43,36 +43,53 @@ import org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManagerResult; /** - * ManagerServlet ala Tomcat ManagerServlet - * + * ManagerServlet ala Tomcat ManagerServlet + * * @author Ate Douma * @version $Id: ManagerServlet.java 517719 2007-03-13 15:05:48Z ate $ */ public class ManagerServlet extends HttpServlet { - private static int OK = 0; - private static int ERROR_NO_DATA = 1; - private static int ERROR_UNKNOWN_COMMAND = 2; - private static int ERROR_UNKNOWN_PA = 3; - private static int ERROR_INVALID = 4; - private static int ERROR_UNSUPPORTED = 5; - private static int ERROR_UNAVAILABLE = 6; - private static int ERROR_SERVER = 7; - private static int ERROR_UNEXPECTED = 8; - private static int ERROR_IGNORED = 9; + private static int OK = 0; + + private static int ERROR_NO_DATA = 1; + + private static int ERROR_UNKNOWN_COMMAND = 2; + + private static int ERROR_UNKNOWN_PA = 3; + + private static int ERROR_INVALID = 4; + + private static int ERROR_UNSUPPORTED = 5; + + private static int ERROR_UNAVAILABLE = 6; + + private static int ERROR_SERVER = 7; + + private static int ERROR_UNEXPECTED = 8; + + private static int ERROR_IGNORED = 9; + private ApplicationServerManager asm; - private PortletRegistry registry; - private PortletFactory portletFactory; - private DeploymentManager dm; + private PortletRegistry registry; + + private PortletFactory portletFactory; + + private DeploymentManager dm; + public void init() throws ServletException { super.init(); - asm = (ApplicationServerManager) Jetspeed.getComponentManager().getComponent(ApplicationServerManager.class); - registry = (PortletRegistry) Jetspeed.getComponentManager().getComponent(PortletRegistry.class); - portletFactory = (PortletFactory) Jetspeed.getComponentManager().getComponent("portletFactory"); - dm = (DeploymentManager) Jetspeed.getComponentManager().getComponent("deploymentManager"); + asm = (ApplicationServerManager) Jetspeed.getComponentManager() + .getComponent(ApplicationServerManager.class); + registry = (PortletRegistry) Jetspeed.getComponentManager() + .getComponent(PortletRegistry.class); + portletFactory = (PortletFactory) Jetspeed.getComponentManager() + .getComponent("portletFactory"); + dm = (DeploymentManager) Jetspeed.getComponentManager().getComponent( + "deploymentManager"); } public void destroy() @@ -80,18 +97,21 @@ super.destroy(); } - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { process(request, response, false); } - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException + protected void doPost(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { process(request, response, true); } - protected void process(HttpServletRequest request, HttpServletResponse response, boolean posted) - throws ServletException, IOException + protected void process(HttpServletRequest request, + HttpServletResponse response, boolean posted) + throws ServletException, IOException { // Prepare our output writer to generate the response message response.setContentType("text/plain; charset=utf-8"); @@ -167,8 +187,16 @@ while (iter.hasNext()) { pa = (PortletApplication) iter.next(); - writer.println(pa.getId() + ":" + pa.getName() + ":" + pa.getWebApplicationDefinition().getContextRoot() - + ":" + (portletFactory.isPortletApplicationRegistered(pa) ? "ACTIVE" : "INACTIVE")); + writer + .println(pa.getId() + + ":" + + pa.getName() + + ":" + + pa.getWebApplicationDefinition().getContextRoot() + + ":" + + (portletFactory + .isPortletApplicationRegistered(pa) ? "ACTIVE" + : "INACTIVE")); } return OK; } @@ -187,12 +215,14 @@ } if (portletFactory.isPortletApplicationRegistered(pa)) { - writer.println("Warning: Portlet Application " + paName + " already started"); + writer.println("Warning: Portlet Application " + paName + + " already started"); return OK; } else if (pa.getApplicationType() == MutablePortletApplication.LOCAL) { - writer.println("Error: Starting LOCAL Portlet Application " + paName + " not supported"); + writer.println("Error: Starting LOCAL Portlet Application " + + paName + " not supported"); return ERROR_UNSUPPORTED; } else if (!asm.isConnected()) @@ -204,23 +234,28 @@ { try { - ApplicationServerManagerResult result = asm.start(pa.getWebApplicationDefinition().getContextRoot()); + ApplicationServerManagerResult result = asm.start(pa + .getWebApplicationDefinition().getContextRoot()); if (result.isOk()) { - writer.println("Portlet Application " + paName + " started"); + writer + .println("Portlet Application " + paName + + " started"); writer.println(result.getResponse()); return OK; } else { - writer.println("Error: Portlet Application " + paName + " could not be started"); + writer.println("Error: Portlet Application " + paName + + " could not be started"); writer.println(result.getResponse()); return ERROR_SERVER; } } catch (Exception e) { - writer.println("Error: Failed to start Portlet Application " + paName + ": " + e.getMessage()); + writer.println("Error: Failed to start Portlet Application " + + paName + ": " + e.getMessage()); e.printStackTrace(writer); return ERROR_UNEXPECTED; } @@ -241,12 +276,15 @@ } if (!portletFactory.isPortletApplicationRegistered(pa)) { - writer.println("Portlet Application " + paName + " already stopped"); + writer + .println("Portlet Application " + paName + + " already stopped"); return OK; } else if (pa.getApplicationType() == MutablePortletApplication.LOCAL) { - writer.println("Error: Stopping LOCAL Portlet Application " + paName + " not supported"); + writer.println("Error: Stopping LOCAL Portlet Application " + + paName + " not supported"); return ERROR_UNSUPPORTED; } else if (!asm.isConnected()) @@ -258,23 +296,28 @@ { try { - ApplicationServerManagerResult result = asm.stop(pa.getWebApplicationDefinition().getContextRoot()); + ApplicationServerManagerResult result = asm.stop(pa + .getWebApplicationDefinition().getContextRoot()); if (result.isOk()) { - writer.println("Portlet Application " + paName + " stopped"); + writer + .println("Portlet Application " + paName + + " stopped"); writer.println(result.getResponse()); return OK; } else { - writer.println("Error: Portlet Application " + paName + " could not be stopped"); + writer.println("Error: Portlet Application " + paName + + " could not be stopped"); writer.println(result.getResponse()); return ERROR_SERVER; } } catch (Exception e) { - writer.println("Error: Failed to stop Portlet Application " + paName + ": " + e.getMessage()); + writer.println("Error: Failed to stop Portlet Application " + + paName + ": " + e.getMessage()); e.printStackTrace(writer); return ERROR_UNEXPECTED; } @@ -297,7 +340,8 @@ PortletApplication pa = registry.getPortletApplication(paName); try { - ApplicationServerManagerResult result = asm.undeploy(pa.getWebApplicationDefinition().getContextRoot()); + ApplicationServerManagerResult result = asm.undeploy(pa + .getWebApplicationDefinition().getContextRoot()); if (result.isOk()) { writer.println("Portlet Application " + paName + " undeployed"); @@ -306,14 +350,16 @@ } else { - writer.println("Error: Portlet Application " + paName + " could not be undeployed"); + writer.println("Error: Portlet Application " + paName + + " could not be undeployed"); writer.println(result.getResponse()); return ERROR_SERVER; } } catch (Exception e) { - writer.println("Error: Failed to undeploy Portlet Application " + paName + ": " + e.getMessage()); + writer.println("Error: Failed to undeploy Portlet Application " + + paName + ": " + e.getMessage()); e.printStackTrace(writer); return ERROR_UNEXPECTED; } @@ -323,10 +369,7 @@ { int result = stop(writer, paName); - if (result != OK) - { - return result; - } + if (result != OK) { return result; } PortletApplication pa = registry.getPortletApplication(paName); try @@ -337,7 +380,8 @@ } catch (RegistryException e) { - writer.println("Error: Failed to unregister Portlet Application " + paName + ": " + e.getMessage()); + writer.println("Error: Failed to unregister Portlet Application " + + paName + ": " + e.getMessage()); e.printStackTrace(writer); return ERROR_UNEXPECTED; } @@ -345,7 +389,7 @@ protected int deploy(PrintWriter writer, HttpServletRequest request) { - if ( !FileUpload.isMultipartContent(request) ) + if (!FileUpload.isMultipartContent(request)) { writer.println("Error: No file multipart content provided"); return ERROR_NO_DATA; @@ -361,40 +405,44 @@ tempDir.delete(); tempDir.mkdirs(); tempDir.deleteOnExit(); - List items = upload.parseRequest(request,0,-1L,tempDir.getAbsolutePath()); + List items = upload.parseRequest(request, 0, -1L, tempDir + .getAbsolutePath()); Iterator iter = items.iterator(); - while ( iter.hasNext() ) + while (iter.hasNext()) { - FileItem item = (FileItem)iter.next(); + FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { String fileName = item.getName(); - tempFile = new File(tempDir, fileName ); + tempFile = new File(tempDir, fileName); tempFile.deleteOnExit(); item.write(tempFile); try { DeploymentStatus status = dm.deploy(tempFile); - if ( status.getStatus() == DeploymentStatus.STATUS_OKAY ) + if (status.getStatus() == DeploymentStatus.STATUS_OKAY) { writer.println("Deployed " + fileName); return OK; } - else if ( status.getStatus() == DeploymentStatus.STATUS_EVAL ) + else if (status.getStatus() == DeploymentStatus.STATUS_EVAL) { - writer.println("Error: Unrecognized file "+ fileName); + writer.println("Error: Unrecognized file " + + fileName); return ERROR_IGNORED; } else { - writer.println("Error: Failed to deploy file "+ fileName); + writer.println("Error: Failed to deploy file " + + fileName); return ERROR_IGNORED; - } + } } catch (Throwable e) { - writer.println("Error: Failed to deploy file " + fileName + ": " + e.getMessage()); + writer.println("Error: Failed to deploy file " + + fileName + ": " + e.getMessage()); e.printStackTrace(writer); return ERROR_UNEXPECTED; } @@ -404,7 +452,8 @@ } catch (Throwable e) { - writer.println("Error: Failed to process uploaded data: "+e.getMessage()); + writer.println("Error: Failed to process uploaded data: " + + e.getMessage()); e.printStackTrace(writer); return ERROR_UNEXPECTED; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/messaging/PortletMessagingImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/messaging/PortletMessagingImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/messaging/PortletMessagingImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,43 +32,53 @@ import org.apache.pluto.invoker.PortletInvokerAccess; import org.apache.pluto.om.window.PortletWindow; - /** - * Message - * + * Message + * * @author David Sean Taylor * @version $Id: $ */ -public class PortletMessagingImpl +public class PortletMessagingImpl { + private PortletWindowAccessor windowAccessor; + private PortletInvoker invoker; + private ActionRequest actionRequest; + private ActionResponse actionResponse; - + public PortletMessagingImpl(PortletWindowAccessor windowAccessor) { this.windowAccessor = windowAccessor; } - - public void processActionMessage(String portletName, RequestContext jetspeedRequest) - throws PortletException, IOException + + public void processActionMessage(String portletName, + RequestContext jetspeedRequest) throws PortletException, + IOException { - //RequestContext jetspeedRequest = (RequestContext)request.getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); + // RequestContext jetspeedRequest = + // (RequestContext)request.getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); PortletContainerServices.prepare("Jetspeed"); PortletWindow window = windowAccessor.getPortletWindow("psd-1"); - HttpServletRequest requestForWindow = jetspeedRequest.getRequestForWindow(window); - HttpServletResponse responseForWindow = jetspeedRequest.getResponseForWindow(window); - - actionRequest = PortletObjectAccess.getActionRequest(window, requestForWindow, responseForWindow); - actionResponse = PortletObjectAccess.getActionResponse(window, requestForWindow, responseForWindow); - - invoker = PortletInvokerAccess.getPortletInvoker(window.getPortletEntity().getPortletDefinition()); - + HttpServletRequest requestForWindow = jetspeedRequest + .getRequestForWindow(window); + HttpServletResponse responseForWindow = jetspeedRequest + .getResponseForWindow(window); + + actionRequest = PortletObjectAccess.getActionRequest(window, + requestForWindow, responseForWindow); + actionResponse = PortletObjectAccess.getActionResponse(window, + requestForWindow, responseForWindow); + + invoker = PortletInvokerAccess.getPortletInvoker(window + .getPortletEntity().getPortletDefinition()); + invoker.action(actionRequest, actionResponse); - + PortletContainerServices.release(); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/JetspeedPipeline.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/JetspeedPipeline.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/JetspeedPipeline.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,12 +16,12 @@ */ package org.apache.jetspeed.pipeline; +import java.util.List; + import org.apache.jetspeed.pipeline.valve.Valve; import org.apache.jetspeed.pipeline.valve.ValveContext; import org.apache.jetspeed.request.RequestContext; -import java.util.List; - /** * Flexible implementation of a {@link Pipeline}.



        Suggested * order of valves: Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/AbstractValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/AbstractValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/AbstractValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,23 +16,22 @@ */ package org.apache.jetspeed.pipeline.valve; -import org.apache.jetspeed.request.RequestContext; import org.apache.jetspeed.pipeline.PipelineException; +import org.apache.jetspeed.request.RequestContext; /** * Valve that can be used as the basis of Valve implementations. - * + * * @author Jason van Zyl * @version $Id: AbstractValve.java 516448 2007-03-09 16:25:47Z ate $ */ -public abstract class AbstractValve - implements Valve +public abstract class AbstractValve implements Valve { + public abstract void invoke(RequestContext request, ValveContext context) - throws PipelineException; + throws PipelineException; - public void initialize() - throws PipelineException + public void initialize() throws PipelineException { } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/ActionValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/ActionValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/ActionValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,25 +17,22 @@ package org.apache.jetspeed.pipeline.valve; /** - * Check if PortletAction needs to be processed and process it, if - * required - * - *
        - * Read from the ValveContext: + * Check if PortletAction needs to be processed and process it, if required + * + *
        Read from the ValveContext: *

          *
        - * - *
        - * Written into the ValveContext: + * + *
        Written into the ValveContext: *
          *
        - * + * *
        * Note: The primary purpose of this interface is primary for documention. * * @author Paul Spencer * @version $Id: ActionValve.java 516448 2007-03-09 16:25:47Z ate $ - * + * * @see ValveContext */ public interface ActionValve extends Valve Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/AggregateValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/AggregateValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/AggregateValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,25 +17,23 @@ package org.apache.jetspeed.pipeline.valve; /** - * Invokes all Layout components in render mode to aggregate the - * generated contents and send result to client. - * - *
        - * Read from the ValveContext: + * Invokes all Layout components in render mode to aggregate the generated + * contents and send result to client. + * + *
        Read from the ValveContext: *
          *
        - * - *
        - * Written into the ValveContext: + * + *
        Written into the ValveContext: *
          *
        - * + * *
        * Note: The primary purpose of this interface is primary for documention. * * @author Paul Spencer * @version $Id: AggregateValve.java 516448 2007-03-09 16:25:47Z ate $ - * + * * @see ValveContext */ public interface AggregateValve extends Valve Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/CapabilityValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/CapabilityValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/CapabilityValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,18 +18,16 @@ /** * Identifies the browser and add a Capability object to RequestContext - * - *
        - * Read from the ValveContext: + * + *
        Read from the ValveContext: *
          *
        - * - *
        - * Written into the ValveContext: + * + *
        Written into the ValveContext: *
          *
        • Capability
        • *
        - * + * *
        * Note: The primary purpose of this interface is primary for documention. * @@ -37,7 +35,7 @@ * @author Roger Ruttimann * * @version $Id: CapabilityValve.java 516448 2007-03-09 16:25:47Z ate $ - * + * * @see ValveContext */ public interface CapabilityValve extends Valve Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/CleanupValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/CleanupValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/CleanupValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,25 +17,23 @@ package org.apache.jetspeed.pipeline.valve; /** - * Return all recycle objects in the ValveContext. This includes - * returning poolable object. - * - *
        - * Read from the ValveContext: + * Return all recycle objects in the ValveContext. This includes returning + * poolable object. + * + *
        Read from the ValveContext: *
          *
        - * - *
        - * Written into the ValveContext: + * + *
        Written into the ValveContext: *
          *
        - * + * *
        * Note: The primary purpose of this interface is primary for documention. * * @author Paul Spencer * @version $Id: CleanupValve.java 516448 2007-03-09 16:25:47Z ate $ - * + * * @see ValveContext */ public interface CleanupValve extends Valve Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/ContainerValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/ContainerValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/ContainerValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,24 +18,21 @@ /** * Initialize the RequestContext and session if required. - * - *
        - * Read from the ValveContext: - * nothing - * - *
        - * Written into the ValveContext: + * + *
        Read from the ValveContext: nothing + * + *
        Written into the ValveContext: *
          *
        • RequestContext
        • *
        • Session (If required)
        • *
        - * + * *
        * Note: The primary purpose of this interface is primary for documention. * * @author Paul Spencer * @version $Id: ContainerValve.java 516448 2007-03-09 16:25:47Z ate $ - * + * * @see ValveContext */ public interface ContainerValve extends Valve Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/ContentValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/ContentValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/ContentValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,23 +18,21 @@ /** * Render all marked portlet and store RenderResponse in RequestContext. - * - *
        - * Read from the ValveContext: + * + *
        Read from the ValveContext: *
          *
        - * - *
        - * Written into the ValveContext: + * + *
        Written into the ValveContext: *
          *
        - * + * *
        * Note: The primary purpose of this interface is primary for documention. * * @author Paul Spencer * @version $Id: ContentValve.java 516448 2007-03-09 16:25:47Z ate $ - * + * * @see ValveContext */ public interface ContentValve extends Valve Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LayoutValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LayoutValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LayoutValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,25 +17,22 @@ package org.apache.jetspeed.pipeline.valve; /** - * Invokes all Layout components to mark all visible elements of - * the Page. - * - *
        - * Read from the ValveContext: + * Invokes all Layout components to mark all visible elements of the Page. + * + *
        Read from the ValveContext: *
          *
        - * - *
        - * Written into the ValveContext: + * + *
        Written into the ValveContext: *
          *
        - * + * *
        * Note: The primary purpose of this interface is primary for documention. * * @author Paul Spencer * @version $Id: LayoutValve.java 516448 2007-03-09 16:25:47Z ate $ - * + * * @see ValveContext */ public interface LayoutValve extends Valve Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LocalizationValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LocalizationValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LocalizationValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,7 +18,7 @@ /** * LocalizationValve - * + * * @author David Sean Taylor * @version $Id: LocalizationValve.java 516448 2007-03-09 16:25:47Z ate $ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LoginValidationValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LoginValidationValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LoginValidationValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,17 +17,15 @@ package org.apache.jetspeed.pipeline.valve; /** - * Checks if a login attempt failed and determines the cause. - *
        - * Read from the ValveContext: + * Checks if a login attempt failed and determines the cause.
        Read from + * the ValveContext: *
          *
        - * - *
        - * Written into the ValveContext: + * + *
        Written into the ValveContext: *
          *
        - * + * *
        * Note: The primary purpose of this interface is primary for documention. * Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LoginViewValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LoginViewValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/LoginViewValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,7 +18,7 @@ /** * LoginViewValve - * + * * @author Shinsuke Sugaya * @version $Id: LoginViewValve.java 186726 2004-06-05 05:13:09Z shinsuke $ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/PageProfilerValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/PageProfilerValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/PageProfilerValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,27 +18,27 @@ /** * Determine the page to display and add it to the RequestContext - * - *
        - * Read from the ValveContext: + * + *
        Read from the ValveContext: *
          *
        - * - *
        - * Written into the ValveContext: + * + *
        Written into the ValveContext: *
          *
        - * + * *
        * Note: The primary purpose of this interface is primary for documention. * * @author Paul Spencer * @version $Id: PageProfilerValve.java 516448 2007-03-09 16:25:47Z ate $ - * + * * @see ValveContext */ public interface PageProfilerValve extends Valve { + String PROFILE_LOCATOR_REQUEST_ATTR_KEY = "org.apache.jetspeed.profiler.ProfileLocator"; + String PROFILE_LOCATORS_PER_PRINCIPAL = "org.apache.jetspeed.profiler.ProfileLocatorsPrincipal"; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/PasswordCredentialValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/PasswordCredentialValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/PasswordCredentialValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,18 +17,16 @@ package org.apache.jetspeed.pipeline.valve; /** - * Checks the PasswordCredential (only once) after a User is logged in - * and redirects to a Change Password page if necessary. - *
        - * Read from the ValveContext: + * Checks the PasswordCredential (only once) after a User is logged in and + * redirects to a Change Password page if necessary.
        Read from the + * ValveContext: *
          *
        - * - *
        - * Written into the ValveContext: + * + *
        Written into the ValveContext: *
          *
        - * + * *
        * Note: The primary purpose of this interface is primary for documention. * Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/SecurityValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/SecurityValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/SecurityValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,19 +19,17 @@ import org.apache.jetspeed.security.impl.SecurityValveImpl; /** - * Authenticates the User or redirects to Login if necessary, add - * authenticated Subject to RequestContext - * - *
        - * Read from the ValveContext: + * Authenticates the User or redirects to Login if necessary, add authenticated + * Subject to RequestContext + * + *
        Read from the ValveContext: *
          *
        - * - *
        - * Written into the ValveContext: + * + *
        Written into the ValveContext: *
          *
        - * + * *
        * Note: The primary purpose of this interface is primary for documention. * @@ -42,5 +40,6 @@ */ public interface SecurityValve extends Valve { - final String IP_ADDRESS = SecurityValveImpl.class.getName() + ".ipaddress"; + + final String IP_ADDRESS = SecurityValveImpl.class.getName() + ".ipaddress"; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/UserProfilerValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/UserProfilerValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/UserProfilerValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,25 +17,23 @@ package org.apache.jetspeed.pipeline.valve; /** - * Authenticates the User or redirects to Login if necessary, add - * authenticated User to RequestContext - * - *
        - * Read from the ValveContext: + * Authenticates the User or redirects to Login if necessary, add authenticated + * User to RequestContext + * + *
        Read from the ValveContext: *
          *
        - * - *
        - * Written into the ValveContext: + * + *
        Written into the ValveContext: *
          *
        - * + * *
        * Note: The primary purpose of this interface is primary for documention. * * @author Paul Spencer * @version $Id: UserProfilerValve.java 516448 2007-03-09 16:25:47Z ate $ - * + * * @see ValveContext */ public interface UserProfilerValve extends Valve Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/ActionValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/ActionValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/ActionValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,8 +30,8 @@ import org.apache.jetspeed.PortalReservedParameters; import org.apache.jetspeed.cache.ContentCacheKey; import org.apache.jetspeed.cache.JetspeedContentCache; +import org.apache.jetspeed.container.state.MutableNavigationalState; import org.apache.jetspeed.container.window.PortletWindowAccessor; -import org.apache.jetspeed.container.state.MutableNavigationalState; import org.apache.jetspeed.exception.JetspeedException; import org.apache.jetspeed.om.common.portlet.MutablePortletEntity; import org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite; @@ -55,108 +55,132 @@ * ActionValveImpl *

        * - * Default implementation of the ActionValve interface. Expects to be - * called after the ContainerValve has set up the appropriate action window - * within the request context. This should come before ANY rendering takes - * place. + * Default implementation of the ActionValve interface. Expects to be called + * after the ContainerValve has set up the appropriate action window within the + * request context. This should come before ANY rendering takes place. * * @author Scott T. Weaver * @version $Id: ActionValveImpl.java 589933 2007-10-30 01:51:50Z woonsan $ - * + * */ public class ActionValveImpl extends AbstractValve implements ActionValve { private static final Log log = LogFactory.getLog(ActionValveImpl.class); + private PortletContainer container; + private PortletWindowAccessor windowAccessor; + private boolean patchResponseCommitted = false; + private JetspeedContentCache portletContentCache; - public ActionValveImpl(PortletContainer container, PortletWindowAccessor windowAccessor, JetspeedContentCache portletContentCache) + public ActionValveImpl(PortletContainer container, + PortletWindowAccessor windowAccessor, + JetspeedContentCache portletContentCache) { this.container = container; this.windowAccessor = windowAccessor; this.portletContentCache = portletContentCache; } - - public ActionValveImpl(PortletContainer container, PortletWindowAccessor windowAccessor, JetspeedContentCache portletContentCache, boolean patchResponseCommitted) + + public ActionValveImpl(PortletContainer container, + PortletWindowAccessor windowAccessor, + JetspeedContentCache portletContentCache, + boolean patchResponseCommitted) { this.container = container; this.windowAccessor = windowAccessor; - this.portletContentCache = portletContentCache; + this.portletContentCache = portletContentCache; this.patchResponseCommitted = patchResponseCommitted; } /** - * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.pipeline.valve.ValveContext) + * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.pipeline.valve.ValveContext) */ - public void invoke(RequestContext request, ValveContext context) throws PipelineException - { + public void invoke(RequestContext request, ValveContext context) + throws PipelineException + { boolean responseCommitted = false; try - { + { PortletWindow actionWindow = request.getActionWindow(); if (actionWindow != null) { // If portlet entity is null, try to refresh the actionWindow. - // Under some clustered environments, a cached portlet window could have null entity. + // Under some clustered environments, a cached portlet window + // could have null entity. if (null == actionWindow.getPortletEntity()) { - try + try { - Fragment fragment = request.getPage().getFragmentById(actionWindow.getId().toString()); - + Fragment fragment = request.getPage().getFragmentById( + actionWindow.getId().toString()); + if (fragment != null) { - ContentFragment contentFragment = new ContentFragmentImpl(fragment, new HashMap()); - actionWindow = this.windowAccessor.getPortletWindow(contentFragment); + ContentFragment contentFragment = new ContentFragmentImpl( + fragment, new HashMap()); + actionWindow = this.windowAccessor + .getPortletWindow(contentFragment); } - } + } catch (Exception e) { log.error("Failed to refresh action window.", e); } } - + if (actionWindow.getPortletEntity() == null) { - // a session is expired and the target actionWindow doesn't have portlet entity. - // Redirect the user back to the target page (with possibly retaining the other windows navigational state). - log.warn("Portlet action was canceled because the session was expired. The actionWindow's id is " + actionWindow.getId()); - + // a session is expired and the target actionWindow doesn't + // have portlet entity. + // Redirect the user back to the target page (with possibly + // retaining the other windows navigational state). + log + .warn("Portlet action was canceled because the session was expired. The actionWindow's id is " + + actionWindow.getId()); + request.setActionWindow(null); - MutableNavigationalState state = (MutableNavigationalState) request.getPortalURL().getNavigationalState(); - + MutableNavigationalState state = (MutableNavigationalState) request + .getPortalURL().getNavigationalState(); + if (state != null) { state.removeState(actionWindow); state.sync(request); - request.getResponse().sendRedirect(request.getPortalURL().getPortalURL()); + request.getResponse().sendRedirect( + request.getPortalURL().getPortalURL()); return; } } initWindow(actionWindow, request); - HttpServletResponse response = request.getResponseForWindow(actionWindow); - HttpServletRequest requestForWindow = request.getRequestForWindow(actionWindow); - requestForWindow.setAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE, request); - - //PortletMessagingImpl msg = new PortletMessagingImpl(windowAccessor); - + HttpServletResponse response = request + .getResponseForWindow(actionWindow); + HttpServletRequest requestForWindow = request + .getRequestForWindow(actionWindow); + requestForWindow.setAttribute( + PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE, + request); + + // PortletMessagingImpl msg = new + // PortletMessagingImpl(windowAccessor); + requestForWindow.setAttribute("JETSPEED_ACTION", request); - container.processPortletAction( - actionWindow, - requestForWindow, - response); - // The container redirects the client after PortletAction processing + container.processPortletAction(actionWindow, requestForWindow, + response); + // The container redirects the client after PortletAction + // processing // so there is no need to continue the pipeline - - //msg.processActionMessage("todo", request); - + + // msg.processActionMessage("todo", request); + // clear the cache for all portlets on the current page clearPortletCacheForPage(request, actionWindow); - + if (patchResponseCommitted) { responseCommitted = true; @@ -165,28 +189,36 @@ { responseCommitted = response.isCommitted(); } - request.setAttribute(PortalReservedParameters.PIPELINE, null); // clear the pipeline + request.setAttribute(PortalReservedParameters.PIPELINE, null); // clear + // the + // pipeline } } catch (PortletContainerException e) { log.fatal("Unable to retrieve portlet container!", e); - throw new PipelineException("Unable to retrieve portlet container!", e); + throw new PipelineException( + "Unable to retrieve portlet container!", e); } catch (PortletException e) { log.warn("Unexpected PortletException in ActionValveImpl", e); - // throw new PipelineException("Unexpected PortletException in ActionValveImpl", e); + // throw new PipelineException("Unexpected PortletException in + // ActionValveImpl", e); } catch (IOException e) { log.error("Unexpected IOException in ActionValveImpl", e); - // throw new PipelineException("Unexpected IOException in ActionValveImpl", e); + // throw new PipelineException("Unexpected IOException in + // ActionValveImpl", e); } catch (IllegalStateException e) { - log.error("Illegal State Exception. Response was written to in Action Phase", e); + log + .error( + "Illegal State Exception. Response was written to in Action Phase", + e); responseCommitted = true; } catch (Throwable t) @@ -195,11 +227,13 @@ } finally { - // Check if an action was processed and if its response has been committed + // Check if an action was processed and if its response has been + // committed // (Pluto will redirect the client after PorletAction processing) - if ( responseCommitted ) + if (responseCommitted) { - log.info("Action processed and response committed (pipeline processing stopped)"); + log + .info("Action processed and response committed (pipeline processing stopped)"); } else { @@ -210,24 +244,21 @@ } - protected void clearPortletCacheForPage(RequestContext request, PortletWindow actionWindow) - throws JetspeedException + protected void clearPortletCacheForPage(RequestContext request, + PortletWindow actionWindow) throws JetspeedException { ContentPage page = request.getPage(); - if (null == page) - { - throw new JetspeedException("Failed to find PSML Pin ContentPageAggregator.build"); - } + if (null == page) { throw new JetspeedException( + "Failed to find PSML Pin ContentPageAggregator.build"); } ContentFragment root = page.getRootContentFragment(); - if (root == null) - { - throw new JetspeedException("No root ContentFragment found in ContentPage"); - } + if (root == null) { throw new JetspeedException( + "No root ContentFragment found in ContentPage"); } if (!isNonStandardAction(actionWindow)) { notifyFragments(root, request, page); - - // if the fragment is rendered from a decorator template, the target cache would not be cleared by the above notification. + + // if the fragment is rendered from a decorator template, the target + // cache would not be cleared by the above notification. // so, let's clear target cache of action window directly again. String fragmentId = actionWindow.getId().toString(); if (page.getFragmentById(fragmentId) == null) @@ -237,8 +268,9 @@ } else { - ContentFragment fragment = page.getContentFragmentById(actionWindow.getId().toString()); - + ContentFragment fragment = page.getContentFragmentById(actionWindow + .getId().toString()); + if (fragment != null) { clearTargetCache(fragment, request); @@ -249,43 +281,48 @@ } } } - + /** * Actions can be marked as non-standard if they don't participate in - * JSR-168 standard action behavior. By default, actions are supposed - * to clear the cache of all other portlets on the page. - * By setting this parameter, we can ignore the standard behavior - * and not clear the cache on actions. This is useful for portlets - * which never participate with other portlets. + * JSR-168 standard action behavior. By default, actions are supposed to + * clear the cache of all other portlets on the page. By setting this + * parameter, we can ignore the standard behavior and not clear the cache on + * actions. This is useful for portlets which never participate with other + * portlets. * - */ + */ protected boolean isNonStandardAction(PortletWindow actionWindow) { PortletEntity entity = actionWindow.getPortletEntity(); if (entity != null) { - PortletDefinitionComposite portletDefinition = (PortletDefinitionComposite)entity.getPortletDefinition(); + PortletDefinitionComposite portletDefinition = (PortletDefinitionComposite) entity + .getPortletDefinition(); if (portletDefinition != null) { Collection actionList = null; - + if (portletDefinition != null) { - actionList = portletDefinition.getMetadata().getFields(PortalReservedParameters.PORTLET_EXTENDED_DESCRIPTOR_NON_STANDARD_ACTION); + actionList = portletDefinition + .getMetadata() + .getFields( + PortalReservedParameters.PORTLET_EXTENDED_DESCRIPTOR_NON_STANDARD_ACTION); } - if (actionList != null) + if (actionList != null) { - if (!actionList.isEmpty()) - return true; + if (!actionList.isEmpty()) return true; } } } return false; } - - protected void notifyFragments(ContentFragment f, RequestContext context, ContentPage page) + + protected void notifyFragments(ContentFragment f, RequestContext context, + ContentPage page) { - if (f.getContentFragments() != null && f.getContentFragments().size() > 0) + if (f.getContentFragments() != null + && f.getContentFragments().size() > 0) { Iterator children = f.getContentFragments().iterator(); while (children.hasNext()) @@ -295,9 +332,10 @@ { notifyFragments(child, context, page); } - } - } - ContentCacheKey cacheKey = portletContentCache.createCacheKey(context, f.getId()); + } + } + ContentCacheKey cacheKey = portletContentCache.createCacheKey(context, + f.getId()); if (portletContentCache.isKeyInCache(cacheKey)) { portletContentCache.remove(cacheKey); @@ -309,18 +347,19 @@ { clearTargetCache(f.getId(), context); } - + protected void clearTargetCache(String fragmentId, RequestContext context) { - ContentCacheKey cacheKey = portletContentCache.createCacheKey(context, fragmentId); - + ContentCacheKey cacheKey = portletContentCache.createCacheKey(context, + fragmentId); + if (portletContentCache.isKeyInCache(cacheKey)) { portletContentCache.remove(cacheKey); portletContentCache.invalidate(context); } } - + /** * @see java.lang.Object#toString() */ @@ -329,10 +368,11 @@ // TODO Auto-generated method stub return "ActionValveImpl"; } - + /** * Makes sure that this PortletWindow's PortletEntity is set to have the * current requests fragment. + * * @param window * @param request */ @@ -340,10 +380,11 @@ { Page page = request.getPage(); Fragment fragment = page.getFragmentById(window.getId().toString()); - + if (fragment != null) { - ((MutablePortletEntity)window.getPortletEntity()).setFragment(fragment); + ((MutablePortletEntity) window.getPortletEntity()) + .setFragment(fragment); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/CleanupValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/CleanupValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/CleanupValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,13 +34,13 @@ * CleanupValveImpl *

        * - * All this valve does right now is look for JSP pages that were - * pushed onto the org.apache.jetspeed.renderStack - * request attribute, and attempts to includde them. + * All this valve does right now is look for JSP pages that were pushed onto the + * org.apache.jetspeed.renderStack request attribute, and + * attempts to includde them. * * @author Scott T. Weaver * @version $Id: CleanupValveImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class CleanupValveImpl extends AbstractValve implements CleanupValve { @@ -49,18 +49,19 @@ private static final Log log = LogFactory.getLog(CleanupValveImpl.class); - public CleanupValveImpl() { } /** - * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.pipeline.valve.ValveContext) + * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.pipeline.valve.ValveContext) */ - public void invoke(RequestContext request, ValveContext context) throws PipelineException + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { - // Complete any renderings that are on the rendering stack + // Complete any renderings that are on the rendering stack // TODO: we should abstract the rendering as we will // want to eventually support other types of templates @@ -75,18 +76,21 @@ while (!renderStack.empty()) { fragment = (String) renderStack.pop(); - RequestDispatcher rd = httpRequest.getRequestDispatcher(fragment); + RequestDispatcher rd = httpRequest + .getRequestDispatcher(fragment); rd.include(httpRequest, request.getResponse()); } } } catch (Exception e) { - log.error("CleanupValveImpl: failed while trying to render fragment " + fragment); + log + .error("CleanupValveImpl: failed while trying to render fragment " + + fragment); log.error("CleanupValveImpl: Unable to complete all renderings", e); - } + } } - + /** * @see java.lang.Object#toString() */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/DebugValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/DebugValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/DebugValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,18 +32,20 @@ * * @author Scott T. Weaver * @version $Id: $ - * + * */ -public class DebugValveImpl extends AbstractValve +public class DebugValveImpl extends AbstractValve { + private static final Log log = LogFactory.getLog(DebugValveImpl.class); public DebugValveImpl() { } - public void invoke(RequestContext request, ValveContext context) throws PipelineException - { + public void invoke(RequestContext request, ValveContext context) + throws PipelineException + { debugHeaders(request.getRequest()); context.invokeNext(request); } @@ -55,8 +57,8 @@ { return "DebugValveImpl"; } - - private void debugHeaders( HttpServletRequest req ) + + private void debugHeaders(HttpServletRequest req) { log.info("-- Jetspeed Debug Valve: Debugging standard headers --"); java.util.Enumeration e = req.getHeaderNames(); @@ -65,7 +67,7 @@ String name = (String) e.nextElement(); String value = req.getHeader(name); log.info("http header = " + name + " : " + value); -// System.out.println("http header = " + name + " : " + value); + // System.out.println("http header = " + name + " : " + value); } } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/PropertyLoaderValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/PropertyLoaderValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/PropertyLoaderValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -75,6 +75,7 @@ */ public class PropertyLoaderValve implements Valve { + protected String m_sKey = null; protected PropertiesConfiguration m_oPropertiesConfiguration = null; @@ -122,7 +123,8 @@ { m_oPropertiesConfiguration = new PropertiesConfiguration( m_sPropertyFilePath); - } catch (ConfigurationException e) + } + catch (ConfigurationException e) { throw new PipelineException(e); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/VerySimpleLayoutValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/VerySimpleLayoutValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/pipeline/valve/impl/VerySimpleLayoutValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,35 +37,43 @@ * VerySimpleLayoutValveImpl *

        * - * Like the descriptions said this is a very simple - * layout valve and should not be used in production. + * Like the descriptions said this is a very simple layout + * valve and should not be used in production. * * * @author Scott T. Weaver * @version $Id: VerySimpleLayoutValveImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public class VerySimpleLayoutValveImpl extends AbstractValve implements LayoutValve +public class VerySimpleLayoutValveImpl extends AbstractValve implements + LayoutValve { - private static final Log log = LogFactory.getLog(VerySimpleLayoutValveImpl.class); + private static final Log log = LogFactory + .getLog(VerySimpleLayoutValveImpl.class); + /** - * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.pipeline.valve.ValveContext) + * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.pipeline.valve.ValveContext) */ - public void invoke(RequestContext request, ValveContext context) throws PipelineException + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { try { log.info("Invoking the VerySimpleLayoutValve..."); HttpServletRequest httpRequest = request.getRequest(); - RequestDispatcher rd = httpRequest.getRequestDispatcher("/pages/SimpleLayoutHeader.jsp"); + RequestDispatcher rd = httpRequest + .getRequestDispatcher("/pages/SimpleLayoutHeader.jsp"); rd.include(httpRequest, request.getResponse()); - Stack renderStack = (Stack) httpRequest.getAttribute(CleanupValveImpl.RENDER_STACK_ATTR); + Stack renderStack = (Stack) httpRequest + .getAttribute(CleanupValveImpl.RENDER_STACK_ATTR); if (renderStack == null) { renderStack = new Stack(); - httpRequest.setAttribute(CleanupValveImpl.RENDER_STACK_ATTR, renderStack); + httpRequest.setAttribute(CleanupValveImpl.RENDER_STACK_ATTR, + renderStack); } renderStack.push("/pages/SimpleLayoutFooter.jsp"); @@ -74,17 +82,23 @@ { try { - log.error("VerySimpleLayout: Unable to include layout header. Layout not processed", e); + log + .error( + "VerySimpleLayout: Unable to include layout header. Layout not processed", + e); PrintWriter pw = request.getResponse().getWriter(); - pw.write("VerySimpleLayoutFailed failed to include servlet resources. (details below)
        "); + pw + .write("VerySimpleLayoutFailed failed to include servlet resources. (details below)
        "); pw.write("Exception: " + e.getClass().getName() + "
        "); pw.write("Message: " + e.getMessage() + "
        "); writeStackTrace(e.getStackTrace(), pw); - if (e instanceof ServletException && ((ServletException) e).getRootCause() != null) + if (e instanceof ServletException + && ((ServletException) e).getRootCause() != null) { Throwable rootCause = ((ServletException) e).getRootCause(); - pw.write("Root Cause: " + rootCause.getClass().getName() + "
        "); + pw.write("Root Cause: " + rootCause.getClass().getName() + + "
        "); pw.write("Message: " + rootCause.getMessage() + "
        "); writeStackTrace(rootCause.getStackTrace(), pw); } @@ -110,12 +124,15 @@ return "VerySimpleLayoutValveImpl"; } - protected static final void writeStackTrace(StackTraceElement[] traceArray, PrintWriter pw) + protected static final void writeStackTrace(StackTraceElement[] traceArray, + PrintWriter pw) { pw.write("

        Stack Trace:

        "); for (int i = 0; i < traceArray.length; i++) { - pw.write("   " + traceArray[i].toString() + "
        "); + pw + .write("   " + traceArray[i].toString() + + "
        "); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/profiler/impl/CreatePageValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/profiler/impl/CreatePageValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/profiler/impl/CreatePageValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,28 +33,30 @@ */ public class CreatePageValveImpl extends AbstractValve implements Valve { + protected Log log = LogFactory.getLog(CreatePageValveImpl.class); - + private PortletActionSecurityBehavior securityBehavior; /** * CreatePageValveImpl - constructor - * - * @param securityBehavior the behavior to create new page for new user + * + * @param securityBehavior + * the behavior to create new page for new user */ public CreatePageValveImpl(PortletActionSecurityBehavior behavior) { this.securityBehavior = behavior; } - /* * (non-Javadoc) * * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, * org.apache.jetspeed.pipeline.valve.ValveContext) */ - public void invoke( RequestContext request, ValveContext context ) throws PipelineException + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { securityBehavior.createNewPageOnEdit(request); context.invokeNext(request); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/profiler/impl/CreateUserTemplatePagesValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/profiler/impl/CreateUserTemplatePagesValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/profiler/impl/CreateUserTemplatePagesValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,6 +16,8 @@ */ package org.apache.jetspeed.profiler.impl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.apache.jetspeed.om.folder.Folder; import org.apache.jetspeed.om.folder.FolderNotFoundException; import org.apache.jetspeed.page.PageManager; @@ -23,55 +25,68 @@ import org.apache.jetspeed.pipeline.valve.ValveContext; import org.apache.jetspeed.portalsite.PortalSite; import org.apache.jetspeed.profiler.Profiler; -import org.apache.jetspeed.profiler.impl.ProfilerValveImpl; import org.apache.jetspeed.request.RequestContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - /** * CreateUserTemplatePagesValveImpl * - * Create User Pages from template folder on first login feature - * The CreateUserTemplatePagesValveImpl creates a new user's home page from the user template folder. + * Create User Pages from template folder on first login feature The + * CreateUserTemplatePagesValveImpl creates a new user's home page from the user + * template folder. * * @author Woonsan Ko - * @version $Id: CreateUserTemplatePagesValveImpl.java 555324 2007-07-11 16:23:56Z ate $ + * @version $Id: CreateUserTemplatePagesValveImpl.java 555324 2007-07-11 + * 16:23:56Z ate $ */ public class CreateUserTemplatePagesValveImpl extends ProfilerValveImpl { - private static final Log log = LogFactory.getLog(CreateUserTemplatePagesValveImpl.class); + private static final Log log = LogFactory + .getLog(CreateUserTemplatePagesValveImpl.class); + public static final String USER_TEMPLATE_FOLDER_REQUEST_ATTR_KEY = "org.apache.jetspeed.profiler.UserTemplateFolder"; - + protected PageManager pageManager; + protected String defaultTemplateFolder = "/_user/template/"; /** * CreateUserTemplatePagesValveImpl - constructor - * - * @param profiler profiler component reference - * @param portalSite portal site component reference - * @param requestFallback flag to enable root folder fallback - * @param useHistory flag to enable selection of last visited folder page - * @param pageManager pageManagerComponent reference + * + * @param profiler + * profiler component reference + * @param portalSite + * portal site component reference + * @param requestFallback + * flag to enable root folder fallback + * @param useHistory + * flag to enable selection of last visited folder page + * @param pageManager + * pageManagerComponent reference */ - public CreateUserTemplatePagesValveImpl(Profiler profiler, PortalSite portalSite, boolean requestFallback, boolean useHistoryPageManager, PageManager pageManager) + public CreateUserTemplatePagesValveImpl(Profiler profiler, + PortalSite portalSite, boolean requestFallback, + boolean useHistoryPageManager, PageManager pageManager) { super(profiler, portalSite, requestFallback, useHistoryPageManager); this.pageManager = pageManager; } - + /** * CreateUserTemplatePagesValveImpl - constructor - * - * @param profiler profiler component reference - * @param portalSite portal site component reference - * @param requestFallback flag to enable root folder fallback - * @param pageManager pageManagerComponent reference + * + * @param profiler + * profiler component reference + * @param portalSite + * portal site component reference + * @param requestFallback + * flag to enable root folder fallback + * @param pageManager + * pageManagerComponent reference */ - public CreateUserTemplatePagesValveImpl(Profiler profiler, PortalSite portalSite, - boolean requestFallback, PageManager pageManager) + public CreateUserTemplatePagesValveImpl(Profiler profiler, + PortalSite portalSite, boolean requestFallback, + PageManager pageManager) { super(profiler, portalSite, requestFallback); this.pageManager = pageManager; @@ -79,29 +94,35 @@ /** * CreateUserTemplatePagesValveImpl - constructor - * - * @param profiler profiler component reference - * @param portalSite portal site component reference - * @param pageManager pageManagerComponent reference + * + * @param profiler + * profiler component reference + * @param portalSite + * portal site component reference + * @param pageManager + * pageManagerComponent reference */ - public CreateUserTemplatePagesValveImpl(Profiler profiler, PortalSite portalSite, PageManager pageManager) + public CreateUserTemplatePagesValveImpl(Profiler profiler, + PortalSite portalSite, PageManager pageManager) { super(profiler, portalSite); this.pageManager = pageManager; } - + public void setDefaultTemplateFolder(String defaultTemplateFolder) { this.defaultTemplateFolder = defaultTemplateFolder; } - + /** - * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.pipeline.valve.ValveContext) + * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.pipeline.valve.ValveContext) */ - public void invoke(RequestContext request, ValveContext context) throws PipelineException + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { boolean created = false; - + try { created = createUserFolderPages(request); @@ -122,16 +143,17 @@ } } } - - private boolean createUserFolderPages(RequestContext request) throws Exception + + private boolean createUserFolderPages(RequestContext request) + throws Exception { boolean created = false; - + String userName = request.getUserPrincipal().getName(); - String userFolder = Folder.USER_FOLDER + userName; - + String userFolder = Folder.USER_FOLDER + userName; + boolean found = true; - + try { this.pageManager.getFolder(userFolder); @@ -145,24 +167,25 @@ { try { - String templateFolder = (String) request.getAttribute(USER_TEMPLATE_FOLDER_REQUEST_ATTR_KEY); - + String templateFolder = (String) request + .getAttribute(USER_TEMPLATE_FOLDER_REQUEST_ATTR_KEY); + if (templateFolder == null) { templateFolder = this.defaultTemplateFolder; } - + Folder source = this.pageManager.getFolder(templateFolder); - + // copy the entire dir tree from the template folder this.pageManager.deepCopyFolder(source, userFolder, userName); - + // The user folder will have titles named after the user name. Folder destFolder = this.pageManager.getFolder(userFolder); destFolder.setTitle(userName); - destFolder.setShortTitle(userName); + destFolder.setShortTitle(userName); this.pageManager.updateFolder(destFolder); - + created = true; } catch (Exception e) @@ -170,7 +193,7 @@ throw e; } } - + return created; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/profiler/impl/ProfilerValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/profiler/impl/ProfilerValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/profiler/impl/ProfilerValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -51,22 +51,27 @@ * @author David Sean Taylor * @version $Id: ProfilerValveImpl.java 631787 2008-02-28 00:25:08Z taylor $ */ -public class ProfilerValveImpl extends AbstractValve implements PageProfilerValve +public class ProfilerValveImpl extends AbstractValve implements + PageProfilerValve { - protected Log log = LogFactory.getLog(ProfilerValveImpl.class); + protected Log log = LogFactory.getLog(ProfilerValveImpl.class); + /** - * PORTAL_SITE_REQUEST_CONTEXT_ATTR_KEY - session portal site context attribute key + * PORTAL_SITE_REQUEST_CONTEXT_ATTR_KEY - session portal site context + * attribute key */ public static final String PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY = "org.apache.jetspeed.portalsite.PortalSiteSessionContext"; /** - * PORTAL_SITE_REQUEST_CONTEXT_ATTR_KEY - request portal site context attribute key + * PORTAL_SITE_REQUEST_CONTEXT_ATTR_KEY - request portal site context + * attribute key */ public static final String PORTAL_SITE_REQUEST_CONTEXT_ATTR_KEY = "org.apache.jetspeed.portalsite.PortalSiteRequestContext"; /** - * PROFILED_PAGE_CONTEXT_ATTR_KEY - legacy request portal site context attribute key + * PROFILED_PAGE_CONTEXT_ATTR_KEY - legacy request portal site context + * attribute key */ public static final String PROFILED_PAGE_CONTEXT_ATTR_KEY = "org.apache.jetspeed.profiledPageContext"; @@ -74,7 +79,7 @@ * session key for storing map of PageActionAccess instances */ private static final String PAGE_ACTION_ACCESS_MAP_SESSION_ATTR_KEY = "org.apache.jetspeed.profiler.pageActionAccessMap"; - + /** * profiler - profiler component */ @@ -86,27 +91,31 @@ private PortalSite portalSite; /** - * requestFallback - flag indicating whether request should fallback to root folder - * if locators do not select a page or access is forbidden + * requestFallback - flag indicating whether request should fallback to root + * folder if locators do not select a page or access is forbidden */ private boolean requestFallback; /** - * useHistory - flag indicating whether to use visited page - * history to select default page per site folder + * useHistory - flag indicating whether to use visited page history to + * select default page per site folder */ private boolean useHistory; /** * ProfilerValveImpl - constructor - * - * @param profiler profiler component reference - * @param portalSite portal site component reference - * @param requestFallback flag to enable root folder fallback - * @param useHistory flag to enable selection of last visited folder page + * + * @param profiler + * profiler component reference + * @param portalSite + * portal site component reference + * @param requestFallback + * flag to enable root folder fallback + * @param useHistory + * flag to enable selection of last visited folder page */ - public ProfilerValveImpl( Profiler profiler, PortalSite portalSite, - boolean requestFallback, boolean useHistory) + public ProfilerValveImpl(Profiler profiler, PortalSite portalSite, + boolean requestFallback, boolean useHistory) { this.profiler = profiler; this.portalSite = portalSite; @@ -116,57 +125,63 @@ /** * ProfilerValveImpl - constructor - * - * @param profiler profiler component reference - * @param portalSite portal site component reference - * @param requestFallback flag to enable root folder fallback + * + * @param profiler + * profiler component reference + * @param portalSite + * portal site component reference + * @param requestFallback + * flag to enable root folder fallback */ - public ProfilerValveImpl(Profiler profiler, PortalSite portalSite, - boolean requestFallback) + public ProfilerValveImpl(Profiler profiler, PortalSite portalSite, + boolean requestFallback) { this(profiler, portalSite, requestFallback, true); } /** * ProfilerValveImpl - constructor - * - * @param profiler profiler component reference - * @param portalSite portal site component reference + * + * @param profiler + * profiler component reference + * @param portalSite + * portal site component reference */ public ProfilerValveImpl(Profiler profiler, PortalSite portalSite) { this(profiler, portalSite, true, true); } - + /* * (non-Javadoc) * * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, * org.apache.jetspeed.pipeline.valve.ValveContext) */ - public void invoke( RequestContext request, ValveContext context ) throws PipelineException + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { try { - // get profiler locators for request subject/principal using the profiler + // get profiler locators for request subject/principal using the + // profiler Subject subject = request.getSubject(); - if (subject == null) - { - throw new ProfilerException("Missing subject for request: " + request.getPath()); - } - Principal principal = SecurityHelper.getBestPrincipal(subject, UserPrincipal.class); - if (principal == null) - { - throw new ProfilerException("Missing principal for request: " + request.getPath()); - } - + if (subject == null) { throw new ProfilerException( + "Missing subject for request: " + request.getPath()); } + Principal principal = SecurityHelper.getBestPrincipal(subject, + UserPrincipal.class); + if (principal == null) { throw new ProfilerException( + "Missing principal for request: " + request.getPath()); } + // get request specific profile locators if required Map locators = null; - String locatorName = (String)request.getAttribute(PROFILE_LOCATOR_REQUEST_ATTR_KEY); - if ( locatorName != null ) + String locatorName = (String) request + .getAttribute(PROFILE_LOCATOR_REQUEST_ATTR_KEY); + if (locatorName != null) { - ProfileLocator locator = profiler.getProfile(request,locatorName); - if ( locator != null ) + ProfileLocator locator = profiler.getProfile(request, + locatorName); + if (locator != null) { locators = new HashMap(); locators.put(ProfileLocator.PAGE_LOCATOR, locator); @@ -176,19 +191,20 @@ // get specified or default locators for the current user, // falling back to global defaults and, if necessary, explicity // fallback to 'page' profile locators - if ( locators == null ) + if (locators == null) { locators = profiler.getProfileLocators(request, principal); } if (locators.size() == 0) { - locators = profiler.getDefaultProfileLocators(request); + locators = profiler.getDefaultProfileLocators(request); } if (locators.size() == 0) { - locators.put(ProfileLocator.PAGE_LOCATOR, profiler.getProfile(request, ProfileLocator.PAGE_LOCATOR)); + locators.put(ProfileLocator.PAGE_LOCATOR, profiler.getProfile( + request, ProfileLocator.PAGE_LOCATOR)); } - + // get profiled page using the profiler, page manager, // and portal site components if (locators != null) @@ -203,13 +219,19 @@ // is invalid, (perhaps because the session was persisted // and is now being reloaded in a new server), it must be // replaced with a newly created session context - PortalSiteSessionContext sessionContext = (PortalSiteSessionContext)request.getSessionAttribute(PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY); + PortalSiteSessionContext sessionContext = (PortalSiteSessionContext) request + .getSessionAttribute(PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY); String pipeline = request.getPipeline().getName(); - if ((sessionContext == null) || !sessionContext.isValid() || hasPipelineChanged(pipeline, sessionContext.getPipeline())) - { + if ((sessionContext == null) + || !sessionContext.isValid() + || hasPipelineChanged(pipeline, sessionContext + .getPipeline())) + { sessionContext = portalSite.newSessionContext(); sessionContext.setPipeline(pipeline); - request.setSessionAttribute(PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY, sessionContext); + request.setSessionAttribute( + PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY, + sessionContext); } // construct and save a new portalsite request context @@ -222,12 +244,16 @@ // request context here does not select the page or build // menus: that is done when the request context is // accessed subsequently - PortalSiteRequestContext requestContext = sessionContext.newRequestContext(locators, requestFallback, useHistory); - request.setAttribute(PORTAL_SITE_REQUEST_CONTEXT_ATTR_KEY, requestContext); + PortalSiteRequestContext requestContext = sessionContext + .newRequestContext(locators, requestFallback, + useHistory); + request.setAttribute(PORTAL_SITE_REQUEST_CONTEXT_ATTR_KEY, + requestContext); // additionally save request context under legacy key // to support existing decorator access - request.setAttribute(PROFILED_PAGE_CONTEXT_ATTR_KEY, requestContext); + request.setAttribute(PROFILED_PAGE_CONTEXT_ATTR_KEY, + requestContext); // get profiled page from portalsite request context // and save profile locators map; accessing the request @@ -238,10 +264,13 @@ // as returned by the PageManager component; accessing // the managed page here selects the current page for the // request - request.setPage(new ContentPageImpl(requestContext.getManagedPage())); + request.setPage(new ContentPageImpl(requestContext + .getManagedPage())); request.setProfileLocators(requestContext.getLocators()); - - request.setAttribute(PortalReservedParameters.PAGE_EDIT_ACCESS_ATTRIBUTE,getPageActionAccess(request)); + + request.setAttribute( + PortalReservedParameters.PAGE_EDIT_ACCESS_ATTRIBUTE, + getPageActionAccess(request)); } // continue @@ -255,27 +284,32 @@ // this is rarely the case since the anonymous // user is normally defined unless the default // security system has been replaced/overridden - if (request.getRequest().getUserPrincipal() == null && - request.getPath() != null && - !request.getPath().equals("/")) + if (request.getRequest().getUserPrincipal() == null + && request.getPath() != null + && !request.getPath().equals("/")) { - try + try { - request.getResponse().sendRedirect(request.getRequest().getContextPath()); + request.getResponse().sendRedirect( + request.getRequest().getContextPath()); } - catch (IOException ioe){} + catch (IOException ioe) + { + } return; } // return standard HTTP 403 - FORBIDDEN status log.error(se.getMessage(), se); try - { - request.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN, se.getMessage()); + { + request.getResponse().sendError( + HttpServletResponse.SC_FORBIDDEN, se.getMessage()); } catch (IOException ioe) { - log.error("Failed to invoke HttpServletReponse.sendError: " + ioe.getMessage(), ioe); + log.error("Failed to invoke HttpServletReponse.sendError: " + + ioe.getMessage(), ioe); } } catch (NodeNotFoundException nnfe) @@ -284,11 +318,13 @@ log.error(nnfe.getMessage(), nnfe); try { - request.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, nnfe.getMessage()); + request.getResponse().sendError( + HttpServletResponse.SC_NOT_FOUND, nnfe.getMessage()); } catch (IOException ioe) { - log.error("Failed to invoke HttpServletReponse.sendError: " + ioe.getMessage(), ioe); + log.error("Failed to invoke HttpServletReponse.sendError: " + + ioe.getMessage(), ioe); } } catch (Exception e) @@ -297,20 +333,23 @@ throw new PipelineException(e.toString(), e); } } - - protected boolean hasPipelineChanged(String requestPipeline, String sessionPipeline) + + protected boolean hasPipelineChanged(String requestPipeline, + String sessionPipeline) { return !requestPipeline.equals(sessionPipeline); } /** * Returns the PageActionAccess for the current user request. + * * @see PageActionAccess - * @param requestContext RequestContext of the current portal request. + * @param requestContext + * RequestContext of the current portal request. * @return PageActionAccess for the current user request. */ protected PageActionAccess getPageActionAccess(RequestContext requestContext) - { + { Page page = requestContext.getPage(); String key = page.getId(); boolean loggedOn = requestContext.getRequest().getUserPrincipal() != null; @@ -320,11 +359,15 @@ Map sessionActions = null; synchronized (this) { - sessionActions = (Map) requestContext.getSessionAttribute(PAGE_ACTION_ACCESS_MAP_SESSION_ATTR_KEY); + sessionActions = (Map) requestContext + .getSessionAttribute(PAGE_ACTION_ACCESS_MAP_SESSION_ATTR_KEY); if (sessionActions == null) { sessionActions = new HashMap(); - requestContext.setSessionAttribute(PAGE_ACTION_ACCESS_MAP_SESSION_ATTR_KEY, sessionActions); + requestContext + .setSessionAttribute( + PAGE_ACTION_ACCESS_MAP_SESSION_ATTR_KEY, + sessionActions); } else { @@ -341,9 +384,9 @@ else { pageActionAccess.checkReset(anonymous, page); - } + } } - + return pageActionAccess; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/JetspeedRequestContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/JetspeedRequestContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/JetspeedRequestContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -68,32 +68,54 @@ */ public class JetspeedRequestContext implements RequestContext { + private static final String ACTION_ERROR_ATTR = "org.apache.jetspeed.action.error:"; + private HttpServletRequest request; + private HttpServletResponse response; + private ServletConfig config; + private HttpSession session; + private Map locators; + private ContentPage page; + private PortletDefinition portletDefinition; + private Subject subject; + private Locale locale; + private ContentDispatcher dispatcher; + private Pipeline pipeline; private CapabilityMap capabilityMap; + private String mimeType; + private String mediaType; + private PortalURL url; + private PortletWindow actionWindow; + private String encoding; + private String requestPath = null; + /** The user info manager. */ private UserInfoManager userInfoMgr; + private Map requestsForWindows; + private Map responsesForWindows; + private final Map objects; - + /** * Create a new Request Context * @@ -102,13 +124,15 @@ * @param response * @param config */ - public JetspeedRequestContext( HttpServletRequest request, HttpServletResponse response, ServletConfig config, - UserInfoManager userInfoMgr ) + public JetspeedRequestContext(HttpServletRequest request, + HttpServletResponse response, ServletConfig config, + UserInfoManager userInfoMgr) { this(request, response, config, userInfoMgr, new HashMap()); } - public JetspeedRequestContext( HttpServletRequest request, HttpServletResponse response, ServletConfig config, + public JetspeedRequestContext(HttpServletRequest request, + HttpServletResponse response, ServletConfig config, UserInfoManager userInfoMgr, Map objects) { this.request = request; @@ -123,17 +147,19 @@ // set context in Request for later use if (null != this.request) { - this.request.setAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE, this); + this.request.setAttribute( + PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE, this); PortalRequestFactory prf = null; try { - prf = (PortalRequestFactory)Jetspeed.getComponentManager().getComponent(PortalRequestFactory.class); + prf = (PortalRequestFactory) Jetspeed.getComponentManager() + .getComponent(PortalRequestFactory.class); } catch (Throwable t) { // allow undefined } - if ( prf != null ) + if (prf != null) { this.request = prf.createPortalRequest(this.request); } @@ -145,14 +171,14 @@ // to the original request. this.request = new HttpServletRequestWrapper(this.request); } - } + } } - + public HttpServletRequest getRequest() { return request; } - + public HttpServletResponse getResponse() { return response; @@ -168,7 +194,7 @@ return locators; } - public void setProfileLocators( Map locators ) + public void setProfileLocators(Map locators) { this.locators = locators; } @@ -178,7 +204,7 @@ return this.page; } - public void setPage( ContentPage page ) + public void setPage(ContentPage page) { this.page = page; } @@ -188,7 +214,7 @@ return portletDefinition; } - public void setPortletDefinition( PortletDefinition portletDefinition ) + public void setPortletDefinition(PortletDefinition portletDefinition) { this.portletDefinition = portletDefinition; } @@ -198,14 +224,14 @@ return dispatcher; } - public void setContentDispatcher( ContentDispatcher dispatcher ) + public void setContentDispatcher(ContentDispatcher dispatcher) { this.dispatcher = dispatcher; } /** * get the Capability Map - * + * */ public CapabilityMap getCapabilityMap() { @@ -217,14 +243,14 @@ * * @param mimeType */ - public void setMimeType( String mimeType ) + public void setMimeType(String mimeType) { this.mimeType = mimeType; } /** * get the mimeType for the request - * + * */ public String getMimeType() { @@ -236,14 +262,14 @@ * * @param mediaType */ - public void setMediaType( String mediaType ) + public void setMediaType(String mediaType) { this.mediaType = mediaType; } /** * get the Media Type - * + * */ public String getMediaType() { @@ -265,18 +291,17 @@ * * @param window */ - public void setActionWindow( PortletWindow portletWindow ) + public void setActionWindow(PortletWindow portletWindow) { this.actionWindow = portletWindow; } - /** * Set the capabilityMap. Used by the CapabilityValve * * @param capabilityMap */ - public void setCapabilityMap( CapabilityMap map ) + public void setCapabilityMap(CapabilityMap map) { this.capabilityMap = map; } @@ -284,7 +309,7 @@ /** * get the character encoding * - * + * */ public String getCharacterEncoding() { @@ -296,13 +321,17 @@ * * @param enc */ - public void setCharacterEncoding( String enc ) + public void setCharacterEncoding(String enc) { - String preferedEnc = (String) session.getAttribute(PortalReservedParameters.PREFERED_CHARACTERENCODING_ATTRIBUTE); + String preferedEnc = (String) session + .getAttribute(PortalReservedParameters.PREFERED_CHARACTERENCODING_ATTRIBUTE); if (preferedEnc == null || !enc.equals(preferedEnc)) { - request.setAttribute(PortalReservedParameters.PREFERED_CHARACTERENCODING_ATTRIBUTE, enc); + request + .setAttribute( + PortalReservedParameters.PREFERED_CHARACTERENCODING_ATTRIBUTE, + enc); } this.encoding = enc; @@ -317,13 +346,15 @@ * @param window * @return */ - public HttpServletRequest getRequestForWindow( PortletWindow window ) + public HttpServletRequest getRequestForWindow(PortletWindow window) { if (!requestsForWindows.containsKey(window.getId())) { - ServletRequestFactory reqFac = (ServletRequestFactory) Jetspeed.getEngine().getFactory( - javax.servlet.http.HttpServletRequest.class); - HttpServletRequest requestWrapper = reqFac.getServletRequest(request, window); + ServletRequestFactory reqFac = (ServletRequestFactory) Jetspeed + .getEngine().getFactory( + javax.servlet.http.HttpServletRequest.class); + HttpServletRequest requestWrapper = reqFac.getServletRequest( + request, window); requestsForWindows.put(window.getId(), requestWrapper); return requestWrapper; } @@ -343,7 +374,7 @@ * @param window * @return */ - public HttpServletResponse getResponseForWindow( PortletWindow window ) + public HttpServletResponse getResponseForWindow(PortletWindow window) { HttpServletResponse wrappedResponse = null; @@ -351,12 +382,13 @@ { if (getContentDispatcher() != null) { - wrappedResponse = ((ContentDispatcherCtrl) getContentDispatcher()).getResponseForWindow(window, this); + wrappedResponse = ((ContentDispatcherCtrl) getContentDispatcher()) + .getResponseForWindow(window, this); } else { - ServletResponseFactory rspFac = (ServletResponseFactory) Jetspeed.getEngine().getFactory( - HttpServletResponse.class); + ServletResponseFactory rspFac = (ServletResponseFactory) Jetspeed + .getEngine().getFactory(HttpServletResponse.class); wrappedResponse = rspFac.getServletResponse(this.response); } @@ -367,7 +399,8 @@ } else { - return (HttpServletResponse) responsesForWindows.get(window.getId()); + return (HttpServletResponse) responsesForWindows + .get(window.getId()); } } @@ -381,13 +414,14 @@ public Principal getUserPrincipal() { - return SecurityHelper.getBestPrincipal(getSubject(), UserPrincipal.class); + return SecurityHelper.getBestPrincipal(getSubject(), + UserPrincipal.class); } - + /** * @see org.apache.jetspeed.request.RequestContext#setSubject(javax.security.auth.Subject) */ - public void setSubject( Subject subject ) + public void setSubject(Subject subject) { this.subject = subject; } @@ -403,17 +437,23 @@ /** * @see org.apache.jetspeed.request.RequestContext#setLocale(java.util.Locale) */ - public void setLocale( Locale locale ) + public void setLocale(Locale locale) { - Locale preferedLocale = (Locale) session.getAttribute(PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE); + Locale preferedLocale = (Locale) session + .getAttribute(PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE); if (preferedLocale == null || !locale.equals(preferedLocale)) { - // PREFERED_LANGUAGE_ATTRIBUTE doesn't seem to be used anywhere anymore, and as a WeakHashMap isn't - // Serializable, "fixing" that problem (JS2-174) by simply not putting it in the session anymore - // request.getSession().setAttribute(PortalReservedParameters.PREFERED_LANGUAGE_ATTRIBUTE, new WeakHashMap()); - session.setAttribute(PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE, locale); - request.setAttribute(PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE, locale); + // PREFERED_LANGUAGE_ATTRIBUTE doesn't seem to be used anywhere + // anymore, and as a WeakHashMap isn't + // Serializable, "fixing" that problem (JS2-174) by simply not + // putting it in the session anymore + // request.getSession().setAttribute(PortalReservedParameters.PREFERED_LANGUAGE_ATTRIBUTE, + // new WeakHashMap()); + session.setAttribute( + PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE, locale); + request.setAttribute( + PortalReservedParameters.PREFERED_LOCALE_ATTRIBUTE, locale); } this.locale = locale; @@ -422,11 +462,11 @@ /** * @see org.apache.jetspeed.request.RequestContext#getRequestParameter(java.lang.String) */ - public String getRequestParameter( String key ) + public String getRequestParameter(String key) { return request.getParameter(key); } - + public void setRequestParameter(String key, String value) { request.getParameterMap().put(key, value); @@ -443,7 +483,7 @@ /** * @see org.apache.jetspeed.request.RequestContext#getRequestAttribute(java.lang.String) */ - public Object getRequestAttribute( String key ) + public Object getRequestAttribute(String key) { return request.getAttribute(key); } @@ -451,7 +491,7 @@ /** * @see org.apache.jetspeed.request.RequestContext#getSessionAttribute(java.lang.String) */ - public Object getSessionAttribute( String key ) + public Object getSessionAttribute(String key) { return session.getAttribute(key); } @@ -460,7 +500,7 @@ * @see org.apache.jetspeed.request.RequestContext#setSessionAttribute(java.lang.String, * java.lang.Object) */ - public void setSessionAttribute( String key, Object value ) + public void setSessionAttribute(String key, Object value) { session.setAttribute(key, value); } @@ -469,7 +509,7 @@ * @see org.apache.jetspeed.request.RequestContext#setAttribute(java.lang.String, * java.lang.Object) */ - public void setAttribute( String key, Object value ) + public void setAttribute(String key, Object value) { request.setAttribute(key, value); } @@ -477,7 +517,7 @@ /** * @see org.apache.jetspeed.request.RequestContext#getAttribute(java.lang.String) */ - public Object getAttribute( String key ) + public Object getAttribute(String key) { return request.getAttribute(key); } @@ -493,12 +533,12 @@ } return this.requestPath; } - + public void setPortalURL(PortalURL url) { - if ( this.url != null ) + if (this.url != null) throw new IllegalStateException("PortalURL already set"); - if ( url == null ) + if (url == null) throw new IllegalArgumentException("PortalURL may not be nullified"); this.url = url; } @@ -511,7 +551,7 @@ /** * @see org.apache.jetspeed.request.RequestContext#getUserInfoMap(org.apache.pluto.om.common.ObjectID) */ - public Map getUserInfoMap( ObjectID oid ) + public Map getUserInfoMap(ObjectID oid) { return userInfoMgr.getUserInfoMap(oid, this); } @@ -526,7 +566,7 @@ * @param portlet * @return */ - public Language getPreferedLanguage( PortletDefinition portlet ) + public Language getPreferedLanguage(PortletDefinition portlet) { // TODO cannot get a proper Language when changing a locale by Locale // Selector @@ -536,7 +576,7 @@ // Language language = (Language) languageMap.get(portlet); // if(language != null) // { - // return language; + // return language; // } LanguageSet languageSet = portlet.getLanguageSet(); Language language = languageSet.get(locale); @@ -553,7 +593,7 @@ { language = (Language) langItr.next(); } - + if (language == null) { language = languageSet.get(languageSet.getDefaultLocale()); @@ -580,13 +620,14 @@ * @see org.apache.jetspeed.request.RequestContext#setPath(java.lang.String) * @param path */ - public void setPath( String path ) + public void setPath(String path) { this.requestPath = path; } - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.request.RequestContext#getActionFailure() */ public Throwable popActionFailure(PortletWindow window) @@ -599,7 +640,6 @@ } - /* * (non-Javadoc) * @@ -607,10 +647,9 @@ */ public void setActionFailure(PortletWindow window, Throwable actionFailure) { - setSessionAttribute(ACTION_ERROR_ATTR + window.getId(), - actionFailure); + setSessionAttribute(ACTION_ERROR_ATTR + window.getId(), actionFailure); } - + /** * Get the current executing pipeline * @@ -620,10 +659,10 @@ { return pipeline; } - - + /** * Set the current pipeline + * * @param pipeline */ public void setPipeline(Pipeline pipeline) @@ -631,43 +670,47 @@ this.pipeline = pipeline; } - /** - * @param request The request to set. + * @param request + * The request to set. */ public void setRequest(HttpServletRequest request) { this.request = request; } - + /** - * @param response The request to set. + * @param response + * The request to set. */ public void setResponse(HttpServletResponse response) { this.response = response; } - + public ContentPage locatePage(Profiler profiler, String nonProfiledPath) { try { - String pathSave = this.getPath(); + String pathSave = this.getPath(); this.setPath(nonProfiledPath); ContentPage realPage = this.getPage(); - this.setPage(null); + this.setPage(null); Map locators = null; - ProfileLocator locator = profiler.getProfile(this, ProfileLocator.PAGE_LOCATOR); - if ( locator != null ) + ProfileLocator locator = profiler.getProfile(this, + ProfileLocator.PAGE_LOCATOR); + if (locator != null) { locators = new HashMap(); locators.put(ProfileLocator.PAGE_LOCATOR, locator); - } - PortalSiteSessionContext sessionContext = (PortalSiteSessionContext)getSessionAttribute(ProfilerValveImpl.PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY); - PortalSiteRequestContext requestContext = sessionContext.newRequestContext(locators, true, true); - ContentPage cpage = new ContentPageImpl(requestContext.getManagedPage()); - //System.out.println("page is " + cpage.getPath()); - this.setPage(realPage); + } + PortalSiteSessionContext sessionContext = (PortalSiteSessionContext) getSessionAttribute(ProfilerValveImpl.PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY); + PortalSiteRequestContext requestContext = sessionContext + .newRequestContext(locators, true, true); + ContentPage cpage = new ContentPageImpl(requestContext + .getManagedPage()); + // System.out.println("page is " + cpage.getPath()); + this.setPage(realPage); this.setPath(pathSave); return cpage; } @@ -676,7 +719,7 @@ t.printStackTrace(); } return null; - } + } public Map getObjects() { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/JetspeedRequestContextComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/JetspeedRequestContextComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/JetspeedRequestContextComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -89,10 +89,10 @@ } Constructor constructor = contextClass.getConstructor(new Class[] - { HttpServletRequest.class, HttpServletResponse.class, + {HttpServletRequest.class, HttpServletResponse.class, ServletConfig.class, UserInfoManager.class, Map.class}); context = (RequestContext) constructor.newInstance(new Object[] - { req, resp, config, userInfoMgr, requestContextObjects}); + {req, resp, config, userInfoMgr, requestContextObjects}); } catch (Exception e) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/PortalRequest.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/PortalRequest.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/PortalRequest.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,23 +22,22 @@ /** * PortalRequest wraps the original request to the portal and keeps local - * references to properties like contextPath, servletPath and the Session - * when its created. + * references to properties like contextPath, servletPath and the Session when + * its created. *

        * Some web servers like WebSphere don't store these properties inside the - * request but derive them dynamically based on the web application context - * in which they are invoked. + * request but derive them dynamically based on the web application context in + * which they are invoked. *

        *

        - * For cross-context invoked portlet applications, getting access to the - * portal contextPath using requestContext.getRequest().getContextPath() - * this clearly is a problem. Also, access to the Portal Session is not - * possible this way. + * For cross-context invoked portlet applications, getting access to the portal + * contextPath using requestContext.getRequest().getContextPath() this clearly + * is a problem. Also, access to the Portal Session is not possible this way. *

        *

        - * The requestContext.request is actually wrapped by this class which solves - * the problem by storing a reference to the actual properties at the time - * of creation and returning + * The requestContext.request is actually wrapped by this class which solves the + * problem by storing a reference to the actual properties at the time of + * creation and returning *

        * * @author Ate Douma @@ -46,10 +45,13 @@ */ public class PortalRequest extends HttpServletRequestWrapper { - private final String contextPath; - private final String servletPath; + + private final String contextPath; + + private final String servletPath; + private final HttpSession session; - + public PortalRequest(HttpServletRequest request) { super(request); @@ -70,11 +72,11 @@ public HttpSession getSession() { - return this.session; + return this.session; } public HttpSession getSession(boolean create) { return this.session; - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/PortalRequestFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/PortalRequestFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/PortalRequestFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,15 +19,15 @@ import javax.servlet.http.HttpServletRequest; /** - * PortalRequestFactory allows specialized instantiation of a PortalRequest to be - * used for JetspeedRequestContext.request. + * PortalRequestFactory allows specialized instantiation of a PortalRequest to + * be used for JetspeedRequestContext.request. *

        * JetspeedRequestContext also implements this interface and simply returns the * provided request as no wrapping is needed for Tomcat. *

        *

        - * To actually use a PortalRequest as wrapper (as needed for instance on WebSphere), - * inject the PortalRequestFactoryImpl in JetspeedRequestContext. + * To actually use a PortalRequest as wrapper (as needed for instance on + * WebSphere), inject the PortalRequestFactoryImpl in JetspeedRequestContext. *

        * * @author Ate Douma @@ -35,5 +35,6 @@ */ public interface PortalRequestFactory { + HttpServletRequest createPortalRequest(HttpServletRequest request); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/PortalRequestFactoryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/PortalRequestFactoryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/request/PortalRequestFactoryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,13 +19,14 @@ import javax.servlet.http.HttpServletRequest; /** - * PortalRequestFactoryImpl - * + * PortalRequestFactoryImpl + * * @author Ate Douma * @version $Id$ */ public class PortalRequestFactoryImpl implements PortalRequestFactory { + public HttpServletRequest createPortalRequest(HttpServletRequest request) { return new PortalRequest(request); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/resource/BufferedHttpServletResponse.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/resource/BufferedHttpServletResponse.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/resource/BufferedHttpServletResponse.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,76 +33,99 @@ /** *

        - * BufferedHttpServletResponse fully captures all HttpServletResponse interactions to be flushed out later. - * This wrapper is specifically written to allow included servlets to set headers, cookies, encoding etc. which isn't allowed by - * the servlet specification on included responses. + * BufferedHttpServletResponse fully captures all HttpServletResponse + * interactions to be flushed out later. This wrapper is specifically written to + * allow included servlets to set headers, cookies, encoding etc. which isn't + * allowed by the servlet specification on included responses. *

        *

        - * Call flush(HttpServletResponse) after the include has returned to flush out the buffered data, headers and state. + * Call flush(HttpServletResponse) after the include has returned to flush out + * the buffered data, headers and state. *

        *

        - * Note: the only method not fully supported by this buffered version is getCharacterEncoding(). Setting characterEncoding through - * setContentType or setLocale on this class won't be reflected in the return value from getCharacterEncoding(), and calling getWriter() - * won't set it either although calling setLocale, setContentType or setCharacterEncoding (servlet api 2.4+) after that will be ignored. - * But, when this object is flused to a (real) response, the contentType, locale and/or characterEncoding recorded will be set on the - * target response then. + * Note: the only method not fully supported by this buffered version is + * getCharacterEncoding(). Setting characterEncoding through setContentType or + * setLocale on this class won't be reflected in the return value from + * getCharacterEncoding(), and calling getWriter() won't set it either although + * calling setLocale, setContentType or setCharacterEncoding (servlet api 2.4+) + * after that will be ignored. But, when this object is flused to a (real) + * response, the contentType, locale and/or characterEncoding recorded will be + * set on the target response then. *

        * * @author Ate Douma - * @version $Id: BufferedHttpServletResponse.java 544024 2007-06-04 00:59:09Z ate $ + * @version $Id: BufferedHttpServletResponse.java 544024 2007-06-04 00:59:09Z + * ate $ */ public class BufferedHttpServletResponse extends HttpServletResponseWrapper { + private static class CharArrayWriterBuffer extends CharArrayWriter { + public char[] getBuffer() { return buf; } - + public int getCount() { return count; } } - + private ByteArrayOutputStream byteOutputBuffer; + private CharArrayWriterBuffer charOutputBuffer; + private ServletOutputStream outputStream; + private PrintWriter printWriter; + private HashMap headers; + private ArrayList cookies; + private int errorCode; + private int statusCode; + private String errorMessage; + private String redirectLocation; + private boolean committed; + private boolean hasStatus; + private boolean hasError; + private Locale locale; + private boolean closed; + private String characterEncoding; + private int contentLength = -1; + private String contentType; + private boolean flushed; - + public BufferedHttpServletResponse(HttpServletResponse response) { super(response); } - + public void flush(HttpServletResponse response) throws IOException { - if (flushed) - { - throw new IllegalStateException("Already flushed"); - } + if (flushed) { throw new IllegalStateException("Already flushed"); } flushed = true; - + if (locale != null) { response.setLocale(locale); - } + } if (contentType != null) { response.setContentType(contentType); @@ -112,7 +135,10 @@ // setCharacterEncoding only available on Servlet Spec 2.4+ try { - response.getClass().getMethod("setCharacterEncoding", new Class[]{String.class}).invoke(response, new Object[]{characterEncoding}); + response.getClass().getMethod("setCharacterEncoding", + new Class[] + {String.class}).invoke(response, new Object[] + {characterEncoding}); } catch (NoSuchMethodException nsme) { @@ -125,9 +151,9 @@ } if (cookies != null) { - for (int i=0,size=cookies.size(); i -1 && contentLength < len) { @@ -190,7 +219,8 @@ } if (len > 0) { - realOutputStream.write(byteOutputBuffer.toByteArray(), 0, len); + realOutputStream.write(byteOutputBuffer.toByteArray(), 0, + len); } outputStream.close(); outputStream = null; @@ -201,51 +231,53 @@ if (!closed) { printWriter.flush(); - if ( charOutputBuffer.getCount() > 0) + if (charOutputBuffer.getCount() > 0) { - response.getWriter().write(charOutputBuffer.getBuffer(), 0, charOutputBuffer.getCount()); + response.getWriter().write( + charOutputBuffer.getBuffer(), 0, + charOutputBuffer.getCount()); } printWriter.close(); - + printWriter = null; charOutputBuffer = null; } } - + } } - + private ArrayList getHeaderList(String name, boolean create) { - if ( headers == null ) + if (headers == null) { headers = new HashMap(); } - ArrayList headerList = (ArrayList)headers.get(name); - if ( headerList == null && create ) + ArrayList headerList = (ArrayList) headers.get(name); + if (headerList == null && create) { headerList = new ArrayList(); - headers.put(name,headerList); + headers.put(name, headerList); } return headerList; } - + private void failIfCommitted() { - if (committed) - { - throw new IllegalStateException("Response is already committed"); - } + if (committed) { throw new IllegalStateException( + "Response is already committed"); } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletResponseWrapper#addCookie(javax.servlet.http.Cookie) */ public void addCookie(Cookie cookie) { - if ( !committed ) + if (!committed) { - if ( cookies == null ) + if (cookies == null) { cookies = new ArrayList(); } @@ -253,8 +285,11 @@ } } - /* (non-Javadoc) - * @see javax.servlet.http.HttpServletResponseWrapper#addDateHeader(java.lang.String, long) + /* + * (non-Javadoc) + * + * @see javax.servlet.http.HttpServletResponseWrapper#addDateHeader(java.lang.String, + * long) */ public void addDateHeader(String name, long date) { @@ -265,8 +300,11 @@ } } - /* (non-Javadoc) - * @see javax.servlet.http.HttpServletResponseWrapper#addHeader(java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see javax.servlet.http.HttpServletResponseWrapper#addHeader(java.lang.String, + * java.lang.String) */ public void addHeader(String name, String value) { @@ -277,8 +315,11 @@ } } - /* (non-Javadoc) - * @see javax.servlet.http.HttpServletResponseWrapper#addIntHeader(java.lang.String, int) + /* + * (non-Javadoc) + * + * @see javax.servlet.http.HttpServletResponseWrapper#addIntHeader(java.lang.String, + * int) */ public void addIntHeader(String name, int value) { @@ -289,7 +330,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletResponseWrapper#containsHeader(java.lang.String) */ public boolean containsHeader(String name) @@ -297,10 +340,14 @@ return getHeaderList(name, false) != null; } - /* (non-Javadoc) - * @see javax.servlet.http.HttpServletResponseWrapper#sendError(int, java.lang.String) + /* + * (non-Javadoc) + * + * @see javax.servlet.http.HttpServletResponseWrapper#sendError(int, + * java.lang.String) */ - public void sendError(int errorCode, String errorMessage) throws IOException + public void sendError(int errorCode, String errorMessage) + throws IOException { failIfCommitted(); committed = true; @@ -310,7 +357,9 @@ this.errorMessage = errorMessage; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletResponseWrapper#sendError(int) */ public void sendError(int errorCode) throws IOException @@ -318,7 +367,9 @@ sendError(errorCode, null); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletResponseWrapper#sendRedirect(java.lang.String) */ public void sendRedirect(String redirectLocation) throws IOException @@ -329,8 +380,11 @@ this.redirectLocation = redirectLocation; } - /* (non-Javadoc) - * @see javax.servlet.http.HttpServletResponseWrapper#setDateHeader(java.lang.String, long) + /* + * (non-Javadoc) + * + * @see javax.servlet.http.HttpServletResponseWrapper#setDateHeader(java.lang.String, + * long) */ public void setDateHeader(String name, long date) { @@ -342,8 +396,11 @@ } } - /* (non-Javadoc) - * @see javax.servlet.http.HttpServletResponseWrapper#setHeader(java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see javax.servlet.http.HttpServletResponseWrapper#setHeader(java.lang.String, + * java.lang.String) */ public void setHeader(String name, String value) { @@ -355,8 +412,11 @@ } } - /* (non-Javadoc) - * @see javax.servlet.http.HttpServletResponseWrapper#setIntHeader(java.lang.String, int) + /* + * (non-Javadoc) + * + * @see javax.servlet.http.HttpServletResponseWrapper#setIntHeader(java.lang.String, + * int) */ public void setIntHeader(String name, int value) { @@ -368,15 +428,21 @@ } } - /* (non-Javadoc) - * @see javax.servlet.http.HttpServletResponseWrapper#setStatus(int, java.lang.String) + /* + * (non-Javadoc) + * + * @see javax.servlet.http.HttpServletResponseWrapper#setStatus(int, + * java.lang.String) */ public void setStatus(int statusCode, String message) { - throw new UnsupportedOperationException("This method is deprecated and no longer available"); + throw new UnsupportedOperationException( + "This method is deprecated and no longer available"); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletResponseWrapper#setStatus(int) */ public void setStatus(int statusCode) @@ -389,7 +455,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletResponseWrapper#flushBuffer() */ public void flushBuffer() throws IOException @@ -400,7 +468,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletResponseWrapper#getBufferSize() */ public int getBufferSize() @@ -408,7 +478,9 @@ return Integer.MAX_VALUE; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletResponseWrapper#getCharacterEncoding() */ public String getCharacterEncoding() @@ -416,7 +488,9 @@ return characterEncoding != null ? characterEncoding : "ISO-8859-1"; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletResponseWrapper#getLocale() */ public Locale getLocale() @@ -424,26 +498,28 @@ return locale != null ? locale : super.getLocale(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletResponseWrapper#getOutputStream() */ public ServletOutputStream getOutputStream() throws IOException { if (outputStream == null) { - if (printWriter != null) - { - throw new IllegalStateException("getWriter() has already been called on this response"); - } + if (printWriter != null) { throw new IllegalStateException( + "getWriter() has already been called on this response"); } byteOutputBuffer = new ByteArrayOutputStream(); outputStream = new ServletOutputStream() { + public void write(int b) throws IOException { if (!closed) { byteOutputBuffer.write(b); - if (contentLength>-1 && byteOutputBuffer.size()>=contentLength) + if (contentLength > -1 + && byteOutputBuffer.size() >= contentLength) { committed = true; closed = true; @@ -455,24 +531,26 @@ return outputStream; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletResponseWrapper#getWriter() */ public PrintWriter getWriter() throws IOException { if (printWriter == null) { - if (outputStream != null) - { - throw new IllegalStateException("getOutputStream() has already been called on this response"); - } + if (outputStream != null) { throw new IllegalStateException( + "getOutputStream() has already been called on this response"); } charOutputBuffer = new CharArrayWriterBuffer(); printWriter = new PrintWriter(charOutputBuffer); } return printWriter; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletResponseWrapper#isCommitted() */ public boolean isCommitted() @@ -480,7 +558,9 @@ return committed; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletResponseWrapper#reset() */ public void reset() @@ -498,7 +578,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletResponseWrapper#resetBuffer() */ public void resetBuffer() @@ -506,7 +588,13 @@ failIfCommitted(); if (outputStream != null) { - try { outputStream.flush(); } catch (Exception e){} + try + { + outputStream.flush(); + } + catch (Exception e) + { + } byteOutputBuffer.reset(); } else if (printWriter != null) @@ -516,20 +604,22 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletResponseWrapper#setBufferSize(int) */ public void setBufferSize(int size) { failIfCommitted(); - if ( (charOutputBuffer != null && charOutputBuffer.size() > 0) - || (byteOutputBuffer != null && byteOutputBuffer.size() > 0) ) - { - throw new IllegalStateException("Content has already been written"); - } + if ((charOutputBuffer != null && charOutputBuffer.size() > 0) + || (byteOutputBuffer != null && byteOutputBuffer.size() > 0)) { throw new IllegalStateException( + "Content has already been written"); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletResponseWrapper#setCharacterEncoding(java.lang.String) */ public void setCharacterEncoding(String charset) @@ -540,7 +630,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletResponseWrapper#setContentLength(int) */ public void setContentLength(int len) @@ -550,9 +642,16 @@ contentLength = len; if (outputStream != null) { - try { outputStream.flush(); } catch (Exception e){} + try + { + outputStream.flush(); + } + catch (Exception e) + { + } } - if ( !closed && byteOutputBuffer != null && byteOutputBuffer.size() >= len ) + if (!closed && byteOutputBuffer != null + && byteOutputBuffer.size() >= len) { committed = true; closed = true; @@ -560,7 +659,9 @@ } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletResponseWrapper#setContentType(java.lang.String) */ public void setContentType(String type) @@ -570,12 +671,15 @@ contentType = type; if (printWriter == null) { - // TODO: parse possible encoding for better return value from getCharacterEncoding() + // TODO: parse possible encoding for better return value from + // getCharacterEncoding() } } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletResponseWrapper#setLocale(java.util.Locale) */ public void setLocale(Locale locale) @@ -583,8 +687,10 @@ if (!committed) { this.locale = locale; - /* NON-FIXABLE ISSUE: defaulting the characterEncoding from the Locale - This feature cannot be implemented/wrapped as it might depend on web.xml locale settings + /* + * NON-FIXABLE ISSUE: defaulting the characterEncoding from the + * Locale This feature cannot be implemented/wrapped as it might + * depend on web.xml locale settings */ } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/resource/ResourceValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/resource/ResourceValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/resource/ResourceValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -44,67 +44,96 @@ *

        * ResourceValveImpl *

        + * * @author Ate Douma * @version $Id: ResourceValveImpl.java 544024 2007-06-04 00:59:09Z ate $ - * + * */ public class ResourceValveImpl extends AbstractValve { private static final Log log = LogFactory.getLog(ResourceValveImpl.class); + private PortletContainer container; + private PortletWindowAccessor windowAccessor; - public ResourceValveImpl(PortletContainer container, PortletWindowAccessor windowAccessor) + public ResourceValveImpl(PortletContainer container, + PortletWindowAccessor windowAccessor) { this.container = container; this.windowAccessor = windowAccessor; } - + /** - * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.pipeline.valve.ValveContext) + * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.pipeline.valve.ValveContext) */ - public void invoke(RequestContext request, ValveContext context) throws PipelineException - { - PortletWindow resourceWindow = request.getPortalURL().getNavigationalState().getPortletWindowOfResource(); - - if ( resourceWindow != null ) + public void invoke(RequestContext request, ValveContext context) + throws PipelineException + { + PortletWindow resourceWindow = request.getPortalURL() + .getNavigationalState().getPortletWindowOfResource(); + + if (resourceWindow != null) { try - { + { Page page = request.getPage(); - Fragment fragment = page.getFragmentById(resourceWindow.getId().toString()); + Fragment fragment = page.getFragmentById(resourceWindow.getId() + .toString()); // If portlet entity is null, try to refresh the resourceWindow. - // Under some clustered environments, a cached portlet window could have null entity. + // Under some clustered environments, a cached portlet window + // could have null entity. if (null == resourceWindow.getPortletEntity()) { - try + try { - ContentFragment contentFragment = new ContentFragmentImpl(fragment, new HashMap()); - resourceWindow = this.windowAccessor.getPortletWindow(contentFragment); - } + ContentFragment contentFragment = new ContentFragmentImpl( + fragment, new HashMap()); + resourceWindow = this.windowAccessor + .getPortletWindow(contentFragment); + } catch (Exception e) { log.error("Failed to refresh resource window.", e); } } - ((MutablePortletEntity)resourceWindow.getPortletEntity()).setFragment(fragment); + ((MutablePortletEntity) resourceWindow.getPortletEntity()) + .setFragment(fragment); HttpServletResponse response = request.getResponse(); - HttpServletRequest requestForWindow = request.getRequestForWindow(resourceWindow); - requestForWindow.setAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE, request); - requestForWindow.setAttribute(PortalReservedParameters.PAGE_ATTRIBUTE, request.getPage()); - requestForWindow.setAttribute(PortalReservedParameters.FRAGMENT_ATTRIBUTE, fragment); - request.setAttribute(PortalReservedParameters.REQUEST_CONTEXT_OBJECTS, request.getObjects()); - request.setAttribute(PortalReservedParameters.PATH_ATTRIBUTE, request.getAttribute(PortalReservedParameters.PATH_ATTRIBUTE)); - request.setAttribute(PortalReservedParameters.PORTLET_WINDOW_ATTRIBUTE, resourceWindow); - BufferedHttpServletResponse bufferedResponse = new BufferedHttpServletResponse(response); - container.renderPortlet(resourceWindow, requestForWindow, bufferedResponse); + HttpServletRequest requestForWindow = request + .getRequestForWindow(resourceWindow); + requestForWindow.setAttribute( + PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE, + request); + requestForWindow.setAttribute( + PortalReservedParameters.PAGE_ATTRIBUTE, request + .getPage()); + requestForWindow.setAttribute( + PortalReservedParameters.FRAGMENT_ATTRIBUTE, fragment); + request.setAttribute( + PortalReservedParameters.REQUEST_CONTEXT_OBJECTS, + request.getObjects()); + request + .setAttribute( + PortalReservedParameters.PATH_ATTRIBUTE, + request + .getAttribute(PortalReservedParameters.PATH_ATTRIBUTE)); + request.setAttribute( + PortalReservedParameters.PORTLET_WINDOW_ATTRIBUTE, + resourceWindow); + BufferedHttpServletResponse bufferedResponse = new BufferedHttpServletResponse( + response); + container.renderPortlet(resourceWindow, requestForWindow, + bufferedResponse); bufferedResponse.flush(response); } catch (PortletContainerException e) { log.fatal("Unable to retrieve portlet container!", e); - throw new PipelineException("Unable to retrieve portlet container!", e); + throw new PipelineException( + "Unable to retrieve portlet container!", e); } catch (PortletException e) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/AbstractSecurityValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/AbstractSecurityValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/AbstractSecurityValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.impl; import java.io.IOException; @@ -37,40 +37,48 @@ * AbstractSecurityValve *

        *

        - * + * *

        + * * @author Scott T. Weaver * @version $Id: AbstractSecurityValve.java 544402 2007-06-05 06:20:00Z taylor $ - * + * */ -public abstract class AbstractSecurityValve extends AbstractValve implements SecurityValve +public abstract class AbstractSecurityValve extends AbstractValve implements + SecurityValve { + protected PortalAuthenticationConfiguration authenticationConfiguration = null; - + /** * *

        * getSubject *

        - * Should build and return a javax.security.Subject + * Should build and return a javax.security.Subject + * * @param request * @return Subject */ - protected abstract Subject getSubject(RequestContext request) throws Exception; - + protected abstract Subject getSubject(RequestContext request) + throws Exception; + /** * *

        * getUserPrincipal *

        - * Should build and return a java.security.Principal that represents the user name - * the Subject returned from getSubject() + * Should build and return a java.security.Principal that + * represents the user name the Subject returned from + * getSubject() + * * @param request * @return Principal * @throws Exception */ - protected abstract Principal getUserPrincipal(RequestContext request) throws Exception; - + protected abstract Principal getUserPrincipal(RequestContext request) + throws Exception; + /** * *

        @@ -78,12 +86,15 @@ *

        * * @param request - * @return javax.security.Subject or null if there is no servlet session attribute defined - * for the key org.apache.jetspeed.PortalReservedParameters.SESSION_KEY_SUBJECT. + * @return javax.security.Subject or null if there is no + * servlet session attribute defined for the key + * org.apache.jetspeed.PortalReservedParameters.SESSION_KEY_SUBJECT. */ - protected final Subject getSubjectFromSession(RequestContext request) throws Exception + protected final Subject getSubjectFromSession(RequestContext request) + throws Exception { - return (Subject) request.getRequest().getSession().getAttribute(PortalReservedParameters.SESSION_KEY_SUBJECT); + return (Subject) request.getRequest().getSession().getAttribute( + PortalReservedParameters.SESSION_KEY_SUBJECT); } /** @@ -92,24 +103,29 @@ *

        * *

        - * Uses getSubject() to call ValveContext.invokeNext() via - * JSSubjectdoAsPrivileged(). This method also takes care of setting the value of - * the RequestContext.subject property and the session attribute + * Uses getSubject() to call + * ValveContext.invokeNext() via + * JSSubjectdoAsPrivileged(). This method also takes care of + * setting the value of the RequestContext.subject property + * and the session attribute * org.apache.jetspeed.PortalReservedParameters.SESSION_KEY_SUBJECT *

        - * - * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.pipeline.valve.ValveContext) + * + * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.pipeline.valve.ValveContext) * @param request * @param context - * @throws PipelineException if the is an error encountered during any security operations. + * @throws PipelineException + * if the is an error encountered during any security + * operations. */ - public void invoke( RequestContext request, ValveContext context ) throws PipelineException + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { - if (isSessionExpired(request)) - { - return; // short circuit processing and redirect + if (isSessionExpired(request)) { return; // short circuit processing + // and redirect } - + // initialize/validate security subject Subject subject; try @@ -118,39 +134,39 @@ } catch (Exception e1) { - throw new PipelineException(e1.getMessage(), e1); + throw new PipelineException(e1.getMessage(), e1); } - request.getRequest().getSession().setAttribute(PortalReservedParameters.SESSION_KEY_SUBJECT, subject); - + request.getRequest().getSession().setAttribute( + PortalReservedParameters.SESSION_KEY_SUBJECT, subject); + // set request context subject request.setSubject(subject); - + // Pass control to the next Valve in the Pipeline and execute under // the current subject final ValveContext vc = context; - final RequestContext rc = request; - PipelineException pe = (PipelineException) JSSubject.doAsPrivileged(subject, new PrivilegedAction() - { - public Object run() - { - try + final RequestContext rc = request; + PipelineException pe = (PipelineException) JSSubject.doAsPrivileged( + subject, new PrivilegedAction() { - vc.invokeNext(rc); - return null; - } - catch (PipelineException e) - { - return e; - } - } - }, null); - - if(pe != null) - { - throw pe; - } + + public Object run() + { + try + { + vc.invokeNext(rc); + return null; + } + catch (PipelineException e) + { + return e; + } + } + }, null); + + if (pe != null) { throw pe; } } - + /** * Check for hard limit session expiration time out * @@ -158,18 +174,25 @@ * @return * @throws PipelineException */ - protected boolean isSessionExpired(RequestContext request) throws PipelineException + protected boolean isSessionExpired(RequestContext request) + throws PipelineException { - if (authenticationConfiguration != null && authenticationConfiguration.isMaxSessionHardLimitEnabled()) + if (authenticationConfiguration != null + && authenticationConfiguration.isMaxSessionHardLimitEnabled()) { HttpSession session = request.getRequest().getSession(); long sessionCreationTime = session.getCreationTime(); long currentTime = System.currentTimeMillis(); - if ((currentTime - sessionCreationTime) > authenticationConfiguration.getMsMaxSessionHardLimit()) + if ((currentTime - sessionCreationTime) > authenticationConfiguration + .getMsMaxSessionHardLimit()) { session.invalidate(); - String redirector = request.getRequest().getContextPath() + authenticationConfiguration.getTimeoutRedirectLocation(); - // System.out.println("logging user out " + redirector + ", " + (currentTime - sessionCreationTime) + ", " + this.msMaxSessionHardLimit); + String redirector = request.getRequest().getContextPath() + + authenticationConfiguration + .getTimeoutRedirectLocation(); + // System.out.println("logging user out " + redirector + ", " + + // (currentTime - sessionCreationTime) + ", " + + // this.msMaxSessionHardLimit); try { request.getResponse().sendRedirect(redirector); @@ -182,10 +205,11 @@ } else { - // System.out.println("Not logging user out: " + (currentTime - sessionCreationTime) + ", " + this.msMaxSessionHardLimit); + // System.out.println("Not logging user out: " + (currentTime - + // sessionCreationTime) + ", " + this.msMaxSessionHardLimit); } } - return false; + return false; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/Jetspeed1CredentialPasswordEncoder.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/Jetspeed1CredentialPasswordEncoder.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/Jetspeed1CredentialPasswordEncoder.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.impl; import java.io.ByteArrayOutputStream; @@ -26,60 +26,62 @@ import org.apache.jetspeed.security.spi.CredentialPasswordEncoder; public class Jetspeed1CredentialPasswordEncoder implements - CredentialPasswordEncoder { + CredentialPasswordEncoder +{ protected String passwordsAlgorithm = "SHA"; + protected String encodingMethod = "base64"; // We don't need the constructors to do anything, but it crashes if we // don't provide them. /* - public Jetspeed1CredentialPasswordEncoder() {} - public Jetspeed1CredentialPasswordEncoder(boolean dummy) {} - public Jetspeed1CredentialPasswordEncoder(String algorithm) - { - this.passwordsAlgorithm = algorithm; - } - - public Jetspeed1CredentialPasswordEncoder(boolean dummy1, String dummy2) {} - */ - + * public Jetspeed1CredentialPasswordEncoder() {} public + * Jetspeed1CredentialPasswordEncoder(boolean dummy) {} public + * Jetspeed1CredentialPasswordEncoder(String algorithm) { + * this.passwordsAlgorithm = algorithm; } + * + * public Jetspeed1CredentialPasswordEncoder(boolean dummy1, String dummy2) {} + */ + public Jetspeed1CredentialPasswordEncoder() { - this("SHA", "base64"); + this("SHA", "base64"); } - - public Jetspeed1CredentialPasswordEncoder( String algorithm ) + + public Jetspeed1CredentialPasswordEncoder(String algorithm) { - this(algorithm, "base64"); + this(algorithm, "base64"); } - - public Jetspeed1CredentialPasswordEncoder( String algorithm, String encoding ) + + public Jetspeed1CredentialPasswordEncoder(String algorithm, String encoding) { - this.passwordsAlgorithm = algorithm; - this.encodingMethod = encoding; + this.passwordsAlgorithm = algorithm; + this.encodingMethod = encoding; } - + public String encode(String userName, String clearTextPassword) - throws SecurityException { - try - { - MessageDigest md = MessageDigest.getInstance(passwordsAlgorithm); - // We need to use unicode here, to be independent of platform's - // default encoding. Thanks to SGawin for spotting this. - byte[] digest = md.digest(clearTextPassword.getBytes("UTF-8")); - ByteArrayOutputStream bas = new ByteArrayOutputStream(digest.length + digest.length / 3 + 1); - OutputStream encodedStream = MimeUtility.encode(bas, "base64"); - encodedStream.write(digest); - encodedStream.flush(); - encodedStream.close(); - return bas.toString(); - } - catch( Exception e ) - { - //logger.error("Unable to encrypt password."+e.getMessage(), e); + throws SecurityException + { + try + { + MessageDigest md = MessageDigest.getInstance(passwordsAlgorithm); + // We need to use unicode here, to be independent of platform's + // default encoding. Thanks to SGawin for spotting this. + byte[] digest = md.digest(clearTextPassword.getBytes("UTF-8")); + ByteArrayOutputStream bas = new ByteArrayOutputStream(digest.length + + digest.length / 3 + 1); + OutputStream encodedStream = MimeUtility.encode(bas, "base64"); + encodedStream.write(digest); + encodedStream.flush(); + encodedStream.close(); + return bas.toString(); + } + catch (Exception e) + { + // logger.error("Unable to encrypt password."+e.getMessage(), e); return null; - } - } + } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/LoginValidationValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/LoginValidationValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/LoginValidationValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,20 +37,26 @@ /** * LoginValidationValve - * + * * @author Ate Douma - * @version $Id: LoginValidationValveImpl.java 544402 2007-06-05 06:20:00Z taylor $ + * @version $Id: LoginValidationValveImpl.java 544402 2007-06-05 06:20:00Z + * taylor $ */ -public class LoginValidationValveImpl extends AbstractValve implements org.apache.jetspeed.pipeline.valve.LoginValidationValve +public class LoginValidationValveImpl extends AbstractValve implements + org.apache.jetspeed.pipeline.valve.LoginValidationValve { - private static final Log log = LogFactory.getLog(LoginValidationValveImpl.class); - + + private static final Log log = LogFactory + .getLog(LoginValidationValveImpl.class); + private int maxNumberOfAuthenticationFailures; - private List sessionAttributes; - + + private List sessionAttributes; + /** - * Creates a LoginValidationValveImpl instance which doesn't evaluate the maxNumberOfAuthenticationFailures - * for LoginConstant.ERROR_FINAL_LOGIN_ATTEMPT error reporting. + * Creates a LoginValidationValveImpl instance which doesn't evaluate the + * maxNumberOfAuthenticationFailures for + * LoginConstant.ERROR_FINAL_LOGIN_ATTEMPT error reporting. */ public LoginValidationValveImpl(List sessionAttributes) { @@ -59,12 +65,17 @@ /** *

        - * Creates a LoginValidationValveImpl instance which can evaluate {@link PasswordCredential#getAuthenticationFailures()} - * to determine if a user only has one login attempt available before the maxNumberOfAuthenticationFailures parameter - * value is reached and the credential will be disabled.

        + * Creates a LoginValidationValveImpl instance which can evaluate + * {@link PasswordCredential#getAuthenticationFailures()} to determine if a + * user only has one login attempt available before the + * maxNumberOfAuthenticationFailures parameter value is reached and the + * credential will be disabled. + *

        *

        - * The provided maxNumberOfAuthenticationFailures value should be equal to the value configured for the - * MaxPasswordAuthenticationFailuresInterceptor (and > 2 to be useful).

        + * The provided maxNumberOfAuthenticationFailures value should be equal to + * the value configured for the MaxPasswordAuthenticationFailuresInterceptor + * (and > 2 to be useful). + *

        */ public LoginValidationValveImpl(int maxNumberOfAuthenticationFailures) { @@ -74,76 +85,111 @@ /** *

        - * Creates a LoginValidationValveImpl instance which can evaluate {@link PasswordCredential#getAuthenticationFailures()} - * to determine if a user only has one login attempt available before the maxNumberOfAuthenticationFailures parameter - * value is reached and the credential will be disabled.

        + * Creates a LoginValidationValveImpl instance which can evaluate + * {@link PasswordCredential#getAuthenticationFailures()} to determine if a + * user only has one login attempt available before the + * maxNumberOfAuthenticationFailures parameter value is reached and the + * credential will be disabled. + *

        *

        - * The provided maxNumberOfAuthenticationFailures value should be equal to the value configured for the - * MaxPasswordAuthenticationFailuresInterceptor (and > 2 to be useful).

        + * The provided maxNumberOfAuthenticationFailures value should be equal to + * the value configured for the MaxPasswordAuthenticationFailuresInterceptor + * (and > 2 to be useful). + *

        */ - public LoginValidationValveImpl(int maxNumberOfAuthenticationFailures, List sessionAttributes) + public LoginValidationValveImpl(int maxNumberOfAuthenticationFailures, + List sessionAttributes) { this.maxNumberOfAuthenticationFailures = maxNumberOfAuthenticationFailures; this.sessionAttributes = sessionAttributes; } /** - * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.pipeline.valve.ValveContext) + * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.pipeline.valve.ValveContext) */ - public void invoke(RequestContext request, ValveContext context) throws PipelineException + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { try { - if ( request.getRequest().getUserPrincipal() == null ) + if (request.getRequest().getUserPrincipal() == null) { - if ( request.getSessionAttribute(LoginConstants.RETRYCOUNT) != null ) + if (request.getSessionAttribute(LoginConstants.RETRYCOUNT) != null) { // we have a login attempt failure - String userName = (String)request.getSessionAttribute(LoginConstants.USERNAME); - if ( userName != null && !userName.equals("")) + String userName = (String) request + .getSessionAttribute(LoginConstants.USERNAME); + if (userName != null && !userName.equals("")) { - UserManager um = (UserManager)Jetspeed.getComponentManager().getComponent(UserManager.class); - if ( um != null ) + UserManager um = (UserManager) Jetspeed + .getComponentManager().getComponent( + UserManager.class); + if (um != null) { User user = null; try { user = um.getUser(userName); - UserPrincipal userPrincipal = (UserPrincipal)SecurityHelper.getPrincipal(user.getSubject(), UserPrincipal.class); - if ( !userPrincipal.isEnabled() ) + UserPrincipal userPrincipal = (UserPrincipal) SecurityHelper + .getPrincipal(user.getSubject(), + UserPrincipal.class); + if (!userPrincipal.isEnabled()) { - request.setSessionAttribute(LoginConstants.ERRORCODE, LoginConstants.ERROR_USER_DISABLED); + request.setSessionAttribute( + LoginConstants.ERRORCODE, + LoginConstants.ERROR_USER_DISABLED); } else { - PasswordCredential pwdCredential = SecurityHelper.getPasswordCredential(user.getSubject()); - if ( pwdCredential == null || !pwdCredential.isEnabled() ) + PasswordCredential pwdCredential = SecurityHelper + .getPasswordCredential(user + .getSubject()); + if (pwdCredential == null + || !pwdCredential.isEnabled()) { - request.setSessionAttribute(LoginConstants.ERRORCODE, LoginConstants.ERROR_CREDENTIAL_DISABLED); + request + .setSessionAttribute( + LoginConstants.ERRORCODE, + LoginConstants.ERROR_CREDENTIAL_DISABLED); } - else if ( pwdCredential.isExpired() ) + else if (pwdCredential.isExpired()) { - request.setSessionAttribute(LoginConstants.ERRORCODE, LoginConstants.ERROR_CREDENTIAL_EXPIRED); + request + .setSessionAttribute( + LoginConstants.ERRORCODE, + LoginConstants.ERROR_CREDENTIAL_EXPIRED); } - else if ( maxNumberOfAuthenticationFailures > 1 && pwdCredential.getAuthenticationFailures() == maxNumberOfAuthenticationFailures -1 ) + else if (maxNumberOfAuthenticationFailures > 1 + && pwdCredential + .getAuthenticationFailures() == maxNumberOfAuthenticationFailures - 1) { - request.setSessionAttribute(LoginConstants.ERRORCODE, LoginConstants.ERROR_FINAL_LOGIN_ATTEMPT); + request + .setSessionAttribute( + LoginConstants.ERRORCODE, + LoginConstants.ERROR_FINAL_LOGIN_ATTEMPT); } else { - request.setSessionAttribute(LoginConstants.ERRORCODE, LoginConstants.ERROR_INVALID_PASSWORD); + request + .setSessionAttribute( + LoginConstants.ERRORCODE, + LoginConstants.ERROR_INVALID_PASSWORD); } } } catch (SecurityException sex) { - request.setSessionAttribute(LoginConstants.ERRORCODE, LoginConstants.ERROR_UNKNOWN_USER); + request.setSessionAttribute( + LoginConstants.ERRORCODE, + LoginConstants.ERROR_UNKNOWN_USER); } } } else { - request.setSessionAttribute(LoginConstants.ERRORCODE, LoginConstants.ERROR_UNKNOWN_USER); + request.setSessionAttribute(LoginConstants.ERRORCODE, + LoginConstants.ERROR_UNKNOWN_USER); } } } @@ -152,10 +198,11 @@ if (request.getSessionAttribute(LoginConstants.LOGIN_CHECK) == null) { clearSessionAttributes(request); - request.getRequest().getSession().setAttribute(LoginConstants.LOGIN_CHECK, "true"); - } + request.getRequest().getSession().setAttribute( + LoginConstants.LOGIN_CHECK, "true"); + } } - + context.invokeNext(request); } catch (Exception e) @@ -164,13 +211,13 @@ throw new PipelineException(e.toString(), e); } } - + private void clearSessionAttributes(RequestContext request) - { + { Iterator attributes = this.sessionAttributes.iterator(); while (attributes.hasNext()) { - String attribute = (String)attributes.next(); + String attribute = (String) attributes.next(); request.getRequest().getSession().removeAttribute(attribute); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/PasswordCredentialValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/PasswordCredentialValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/PasswordCredentialValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,42 +34,57 @@ /** * PasswordCredentialValve - * + * * @author Ate Douma - * @version $Id: PasswordCredentialValveImpl.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: PasswordCredentialValveImpl.java 516448 2007-03-09 16:25:47Z + * ate $ */ -public class PasswordCredentialValveImpl extends AbstractValve implements org.apache.jetspeed.pipeline.valve.PasswordCredentialValve +public class PasswordCredentialValveImpl extends AbstractValve implements + org.apache.jetspeed.pipeline.valve.PasswordCredentialValve { - private static final Log log = LogFactory.getLog(PasswordCredentialValveImpl.class); - - private static final String CHECKED_KEY = PasswordCredentialValveImpl.class.getName() + ".checked"; - //private PageManager pageManager; + + private static final Log log = LogFactory + .getLog(PasswordCredentialValveImpl.class); + + private static final String CHECKED_KEY = PasswordCredentialValveImpl.class + .getName() + + ".checked"; + + // private PageManager pageManager; private int[] expirationWarningDays; - + /** - * Create a PasswordCredentialValveImpl which only checks and handles PasswordCredential.isUpdateRequired(). - * + * Create a PasswordCredentialValveImpl which only checks and handles + * PasswordCredential.isUpdateRequired(). + * */ public PasswordCredentialValveImpl() - { - expirationWarningDays = new int[]{}; + { + expirationWarningDays = new int[] + {}; } - + /** *

        - * Creates a PasswordCredentialValveImpl which, besides checking and handling PasswordCredential.isUpdateRequired(), - * also provides a warning when a password is about to be expired according to the provided list of - * expirationWarningDays.

        - * @param expirationWarningDays the list of days before password expiration when a warning should be presented + * Creates a PasswordCredentialValveImpl which, besides checking and + * handling PasswordCredential.isUpdateRequired(), also provides a warning + * when a password is about to be expired according to the provided list of + * expirationWarningDays. + *

        + * + * @param expirationWarningDays + * the list of days before password expiration when a warning + * should be presented */ public PasswordCredentialValveImpl(List expirationWarningDays) { - if ( expirationWarningDays != null ) + if (expirationWarningDays != null) { this.expirationWarningDays = new int[expirationWarningDays.size()]; - for ( int i = 0; i < this.expirationWarningDays.length; i++ ) + for (int i = 0; i < this.expirationWarningDays.length; i++) { - this.expirationWarningDays[i] = Integer.parseInt((String)expirationWarningDays.get(i)); + this.expirationWarningDays[i] = Integer + .parseInt((String) expirationWarningDays.get(i)); } Arrays.sort(this.expirationWarningDays); } @@ -80,57 +95,65 @@ } /** - * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.pipeline.valve.ValveContext) + * @see org.apache.jetspeed.pipeline.valve.Valve#invoke(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.pipeline.valve.ValveContext) */ - public void invoke(RequestContext request, ValveContext context) throws PipelineException + public void invoke(RequestContext request, ValveContext context) + throws PipelineException { try { - if ( request.getRequest().getUserPrincipal() != null ) + if (request.getRequest().getUserPrincipal() != null) { Subject subject = request.getSubject(); - PasswordCredential pwdCredential = SecurityHelper.getPasswordCredential(subject); + PasswordCredential pwdCredential = SecurityHelper + .getPasswordCredential(subject); Integer passwordDaysValid = null; - + // check for an existing password credential - if ( pwdCredential != null ) + if (pwdCredential != null) { - if ( pwdCredential.isUpdateRequired() ) + if (pwdCredential.isUpdateRequired()) { passwordDaysValid = new Integer(0); // required change } - if ( request.getSessionAttribute(CHECKED_KEY) == null ) + if (request.getSessionAttribute(CHECKED_KEY) == null) { - request.setSessionAttribute(CHECKED_KEY,Boolean.TRUE); - if ( pwdCredential.getPreviousAuthenticationDate() != null && - pwdCredential.getLastAuthenticationDate() != null && - pwdCredential.getExpirationDate() != null ) + request.setSessionAttribute(CHECKED_KEY, Boolean.TRUE); + if (pwdCredential.getPreviousAuthenticationDate() != null + && pwdCredential.getLastAuthenticationDate() != null + && pwdCredential.getExpirationDate() != null) { - long expirationTime = pwdCredential.getExpirationDate().getTime(); - long lastAuthTime = pwdCredential.getLastAuthenticationDate().getTime(); - int lastAuthDaysBeforeExpiration = (int)((expirationTime-lastAuthTime)/(24*60*60*1000)); - if ( lastAuthDaysBeforeExpiration < 1 ) + long expirationTime = pwdCredential + .getExpirationDate().getTime(); + long lastAuthTime = pwdCredential + .getLastAuthenticationDate().getTime(); + int lastAuthDaysBeforeExpiration = (int) ((expirationTime - lastAuthTime) / (24 * 60 * 60 * 1000)); + if (lastAuthDaysBeforeExpiration < 1) { passwordDaysValid = new Integer(1); } else if (expirationWarningDays.length > 0) { long prevAuthTime = Long.MIN_VALUE; - if (pwdCredential.getPreviousAuthenticationDate() != null ) + if (pwdCredential + .getPreviousAuthenticationDate() != null) { - prevAuthTime = pwdCredential.getPreviousAuthenticationDate().getTime(); + prevAuthTime = pwdCredential + .getPreviousAuthenticationDate() + .getTime(); } - int prevAuthDaysBeforeExpiration = (int)((expirationTime-prevAuthTime)/(24*60*60*1000)); - if ( prevAuthDaysBeforeExpiration > lastAuthDaysBeforeExpiration ) + int prevAuthDaysBeforeExpiration = (int) ((expirationTime - prevAuthTime) / (24 * 60 * 60 * 1000)); + if (prevAuthDaysBeforeExpiration > lastAuthDaysBeforeExpiration) { - for ( int i = 0; i < expirationWarningDays.length; i++ ) + for (int i = 0; i < expirationWarningDays.length; i++) { - int daysBefore = expirationWarningDays[i]-1; - if ( lastAuthDaysBeforeExpiration == daysBefore || - (lastAuthDaysBeforeExpiration < daysBefore && - prevAuthDaysBeforeExpiration > daysBefore ) ) + int daysBefore = expirationWarningDays[i] - 1; + if (lastAuthDaysBeforeExpiration == daysBefore + || (lastAuthDaysBeforeExpiration < daysBefore && prevAuthDaysBeforeExpiration > daysBefore)) { - passwordDaysValid = new Integer(lastAuthDaysBeforeExpiration+1); + passwordDaysValid = new Integer( + lastAuthDaysBeforeExpiration + 1); break; } } @@ -139,12 +162,18 @@ } } } - if ( passwordDaysValid != null ) + if (passwordDaysValid != null) { - // enforce the SECURITY_LOCATOR to be used to redirect to a change password portlet page - request.setAttribute(PageProfilerValve.PROFILE_LOCATOR_REQUEST_ATTR_KEY,ProfileLocator.SECURITY_LOCATOR); + // enforce the SECURITY_LOCATOR to be used to redirect to a + // change password portlet page + request.setAttribute( + PageProfilerValve.PROFILE_LOCATOR_REQUEST_ATTR_KEY, + ProfileLocator.SECURITY_LOCATOR); // inform the change password portlet why it is invoked - request.setAttribute(PasswordCredential.PASSWORD_CREDENTIAL_DAYS_VALID_REQUEST_ATTR_KEY, passwordDaysValid); + request + .setAttribute( + PasswordCredential.PASSWORD_CREDENTIAL_DAYS_VALID_REQUEST_ATTR_KEY, + passwordDaysValid); } } context.invokeNext(request); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/SecurityAccessControllerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/SecurityAccessControllerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/SecurityAccessControllerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,7 +16,6 @@ */ package org.apache.jetspeed.security.impl; - import java.security.AccessControlException; import java.security.AccessController; @@ -28,51 +27,55 @@ import org.apache.jetspeed.security.SecurityAccessController; /** - * SecurityAccessorImpl implements SecurityAccessor component abstracting - * access to either Security Permission or Security Constraint implementations + * SecurityAccessorImpl implements SecurityAccessor component abstracting access + * to either Security Permission or Security Constraint implementations * * @author David Sean Taylor * @version $Id: $ */ public class SecurityAccessControllerImpl implements SecurityAccessController { + protected PageManager pageManager; + protected int securityMode = SecurityAccessController.PERMISSIONS; - - public SecurityAccessControllerImpl(PageManager pageManager, int securityMode) + + public SecurityAccessControllerImpl(PageManager pageManager, + int securityMode) { this.pageManager = pageManager; this.securityMode = securityMode; } - + public int getSecurityMode() { return securityMode; } - - public boolean checkPortletAccess(PortletDefinitionComposite portlet, int mask) + + public boolean checkPortletAccess(PortletDefinitionComposite portlet, + int mask) { - if (portlet == null) - return false; + if (portlet == null) return false; if (securityMode == SecurityAccessController.CONSTRAINTS) { String constraintRef = portlet.getJetspeedSecurityConstraint(); if (constraintRef == null) { - constraintRef = ((MutablePortletApplication)portlet.getPortletApplicationDefinition()).getJetspeedSecurityConstraint(); - if (constraintRef == null) - { - return true; // allow access + constraintRef = ((MutablePortletApplication) portlet + .getPortletApplicationDefinition()) + .getJetspeedSecurityConstraint(); + if (constraintRef == null) { return true; // allow access } } String actions = JetspeedActions.getContainerActions(mask); - return pageManager.checkConstraint(constraintRef, actions); + return pageManager.checkConstraint(constraintRef, actions); } else { try { - AccessController.checkPermission(new PortletPermission(portlet.getUniqueName(), mask)); + AccessController.checkPermission(new PortletPermission(portlet + .getUniqueName(), mask)); } catch (AccessControlException ace) { @@ -80,6 +83,6 @@ } return true; } - + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/SecurityValveImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/SecurityValveImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/SecurityValveImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -41,20 +41,25 @@ * @author Scott T. Weaver * @version $Id: SecurityValveImpl.java 544250 2007-06-04 20:30:43Z taylor $ */ -public class SecurityValveImpl extends AbstractSecurityValve implements SecurityValve +public class SecurityValveImpl extends AbstractSecurityValve implements + SecurityValve { + private UserManager userMgr; + private PortalStatistics statistics; - public SecurityValveImpl(Profiler profiler, UserManager userMgr, PortalStatistics statistics, - PortalAuthenticationConfiguration authenticationConfiguration) + public SecurityValveImpl(Profiler profiler, UserManager userMgr, + PortalStatistics statistics, + PortalAuthenticationConfiguration authenticationConfiguration) { this.userMgr = userMgr; this.statistics = statistics; this.authenticationConfiguration = authenticationConfiguration; } - - public SecurityValveImpl( Profiler profiler, UserManager userMgr, PortalStatistics statistics ) + + public SecurityValveImpl(Profiler profiler, UserManager userMgr, + PortalStatistics statistics) { this.userMgr = userMgr; this.statistics = statistics; @@ -65,38 +70,41 @@ this.userMgr = userMgr; this.statistics = null; } - + public String toString() { return "SecurityValve"; } - + /** * *

        * getSubject *

        - * Check for previously established session subject and - * invalidate if subject and current user principals do - * not match + * Check for previously established session subject and invalidate if + * subject and current user principals do not match + * * @param request - * @return + * @return * @throws Exception */ protected final Subject getSubject(RequestContext request) throws Exception { Principal userPrincipal = getUserPrincipal(request); - + Subject subject = getSubjectFromSession(request); if (subject != null) { - Principal subjectUserPrincipal = SecurityHelper.getPrincipal(subject, UserPrincipal.class); - if ((subjectUserPrincipal == null) || !subjectUserPrincipal.getName().equals(getUserPrincipal(request).getName())) + Principal subjectUserPrincipal = SecurityHelper.getPrincipal( + subject, UserPrincipal.class); + if ((subjectUserPrincipal == null) + || !subjectUserPrincipal.getName().equals( + getUserPrincipal(request).getName())) { subject = null; } } - + // create new session subject for user principal if required if (subject == null) { @@ -105,7 +113,7 @@ try { User user = userMgr.getUser(userPrincipal.getName()); - if ( user != null ) + if (user != null) { subject = user.getSubject(); } @@ -113,39 +121,43 @@ catch (SecurityException sex) { subject = null; - } - + } + // if subject not available, generate default subject using // request or default profiler anonymous user principal if (subject == null) { Set principals = new HashSet(); principals.add(userPrincipal); - subject = new Subject(true, principals, new HashSet(), new HashSet()); - } - + subject = new Subject(true, principals, new HashSet(), + new HashSet()); + } + // create a new statistics *user* session if (statistics != null) { statistics.logUserLogin(request, 0); } // put IP address in session for logout - request.setSessionAttribute(IP_ADDRESS, request.getRequest().getRemoteAddr()); - } + request.setSessionAttribute(IP_ADDRESS, request.getRequest() + .getRemoteAddr()); + } return subject; } - + /** * *

        * getUserPrincipal *

        - * Aaccess request user principal if defined or default - * to profiler anonymous user + * Aaccess request user principal if defined or default to profiler + * anonymous user + * * @param request * @return */ - protected Principal getUserPrincipal(RequestContext request) throws Exception + protected Principal getUserPrincipal(RequestContext request) + throws Exception { Principal userPrincipal = request.getRequest().getUserPrincipal(); if (userPrincipal == null) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/ntlm/NtlmHttpServletRequestFilter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/ntlm/NtlmHttpServletRequestFilter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/ntlm/NtlmHttpServletRequestFilter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,35 +26,45 @@ import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + /** - * NtlmHttpServletRequestFilter can be used in combination with an Ntml authentication filter (jCIFS). - * The NtlmHttpServletRequestFilter must be configured after the jCIFS filter in web.xml. The - * NtlmHttpServletRequestFilter wraps the jCIFS HttpServletRequest with a NtlmHttpServletRequestWrapper. - * This is done to control which principal / remoteUser is returned by the request. - * If a fallback authentication method is used (e.g. container-based form authentication) then you must - * use the filter param org.apache.jetspeed.security.ntlm.ignoreUrls in web.xml to specify the urls for - * which the Ntlm principal / remoteUser should be ignored. + * NtlmHttpServletRequestFilter can be used in combination with + * an Ntml authentication filter (jCIFS). The + * NtlmHttpServletRequestFilter must be configured after + * the jCIFS filter in web.xml. The NtlmHttpServletRequestFilter wraps the jCIFS + * HttpServletRequest with a NtlmHttpServletRequestWrapper. This + * is done to control which principal / remoteUser is returned by the request. + * If a fallback authentication method is used (e.g. container-based form + * authentication) then you must use the filter param + * org.apache.jetspeed.security.ntlm.ignoreUrls in web.xml to + * specify the urls for which the Ntlm principal / remoteUser should be ignored. * * @see NtlmHttpServletRequestWrapper * @author Dennis Dam * @version $Id$ */ -public class NtlmHttpServletRequestFilter implements Filter { - - private String ignoreNtlmUrls; - - public void destroy() { +public class NtlmHttpServletRequestFilter implements Filter +{ + + private String ignoreNtlmUrls; + + public void destroy() + { } - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, - ServletException { - HttpServletRequest req = (HttpServletRequest)request; - HttpServletResponse resp = (HttpServletResponse)response; - chain.doFilter( new NtlmHttpServletRequestWrapper( req, ignoreNtlmUrls ), resp ); + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException + { + HttpServletRequest req = (HttpServletRequest) request; + HttpServletResponse resp = (HttpServletResponse) response; + chain.doFilter(new NtlmHttpServletRequestWrapper(req, ignoreNtlmUrls), + resp); } - public void init(FilterConfig config) throws ServletException { - ignoreNtlmUrls = config.getInitParameter("org.apache.jetspeed.security.ntlm.ignoreUrls"); + public void init(FilterConfig config) throws ServletException + { + ignoreNtlmUrls = config + .getInitParameter("org.apache.jetspeed.security.ntlm.ignoreUrls"); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/ntlm/NtlmHttpServletRequestWrapper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/ntlm/NtlmHttpServletRequestWrapper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/ntlm/NtlmHttpServletRequestWrapper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,59 +25,82 @@ import org.apache.commons.lang.StringUtils; /** - * NtlmHttpServletRequestWrapper should be used in combination with an Ntml authentication filter (jCIFS). - * This filter wraps the original request, setting the principal and remoteUser retrieved by Ntml - * authentication with the client. The wrapper Request sets the principal and remoteUser, regardless - * of the principal already present in the original request. This HttpServletRequestWrapper returns the principal - * from the original request when it's there, and otherwise returns the Ntml principal. When the - * the Ntml principal is actually returned can be influenced by a comma-separated list of servlet urls: - * only for these urls the Ntlm principal / remoteUser is ignored. + * NtlmHttpServletRequestWrapper should be used in combination with an Ntml + * authentication filter (jCIFS). This filter wraps the original request, + * setting the principal and remoteUser retrieved by Ntml authentication with + * the client. The wrapper Request sets the principal and remoteUser, + * regardless of the principal already present in the original request. + * This HttpServletRequestWrapper returns the principal from the original + * request when it's there, and otherwise returns the Ntml principal. When the + * the Ntml principal is actually returned can be influenced by a + * comma-separated list of servlet urls: only for these urls the Ntlm principal / + * remoteUser is ignored. + * * @see NtlmHttpServletRequestFilter * @author Dennis Dam * @version $Id$ */ -public class NtlmHttpServletRequestWrapper extends HttpServletRequestWrapper { +public class NtlmHttpServletRequestWrapper extends HttpServletRequestWrapper +{ + private Principal principal; + private String remoteUser; - - public NtlmHttpServletRequestWrapper(HttpServletRequest req, String ignoreNtmlUrls) { - super(req); - if (req instanceof HttpServletRequestWrapper){ - String[] urls = ignoreNtmlUrls != null ? StringUtils.split(ignoreNtmlUrls, ',') : new String[]{}; + + public NtlmHttpServletRequestWrapper(HttpServletRequest req, + String ignoreNtmlUrls) + { + super(req); + if (req instanceof HttpServletRequestWrapper) + { + String[] urls = ignoreNtmlUrls != null ? StringUtils.split( + ignoreNtmlUrls, ',') : new String[] + {}; String servletUrl = req.getServletPath(); Principal reqPrincipal = req.getUserPrincipal(); - HttpServletRequest originalRequest = (HttpServletRequest)((HttpServletRequestWrapper) req).getRequest(); + HttpServletRequest originalRequest = (HttpServletRequest) ((HttpServletRequestWrapper) req) + .getRequest(); /* - * Original request principal has precedence over Ntml authenticated principal. This is needed - * in the case that the Ntlm authenticated principal is not authorized by Jetspeed: a fallback login - * method can then be used. If Ntml authentication succeeds, then the principal from the - * original request will be null. - */ - if (originalRequest.getUserPrincipal() != null){ + * Original request principal has precedence over Ntml authenticated + * principal. This is needed in the case that the Ntlm authenticated + * principal is not authorized by Jetspeed: a fallback login method + * can then be used. If Ntml authentication succeeds, then the + * principal from the original request will be null. + */ + if (originalRequest.getUserPrincipal() != null) + { principal = originalRequest.getUserPrincipal(); - } else + } + else /* - * If no principal in the original request, take principal from Ntlm authentication, but - * only if the current servlet url is not in the ignore list. The last - * requirement is necessary when falling back to another authentication method, e.g. container-based - * form authentication: these authentication methods might only work if there is no - * principal in the request. + * If no principal in the original request, take principal from Ntlm + * authentication, but only if the current servlet url is not in the + * ignore list. The last requirement is necessary when falling back + * to another authentication method, e.g. container-based form + * authentication: these authentication methods might only work if + * there is no principal in the request. */ - if (!ArrayUtils.contains(urls,servletUrl) && reqPrincipal != null && req.getRemoteUser() != null){ + if (!ArrayUtils.contains(urls, servletUrl) && reqPrincipal != null + && req.getRemoteUser() != null) + { principal = reqPrincipal; remoteUser = req.getRemoteUser(); - } - } else { + } + } + else + { principal = super.getUserPrincipal(); } } - - public Principal getUserPrincipal() { + + public Principal getUserPrincipal() + { return principal; } - - public String getRemoteUser() { + + public String getRemoteUser() + { return remoteUser; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/ntlm/NtlmSecurityValve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/ntlm/NtlmSecurityValve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/security/impl/ntlm/NtlmSecurityValve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,57 +34,88 @@ import org.apache.jetspeed.security.impl.AbstractSecurityValve; import org.apache.jetspeed.security.impl.UserPrincipalImpl; import org.apache.jetspeed.statistics.PortalStatistics; + /** - * NTLMSecurityValve provides Subject creation based on the - * NTLM provided request.getRemoteUser() user name. When request.getRemoteUser() holds - * a valid value, then this user is authorized. Otherwise the username is retrieved - * from the Principal name in the request. In this way you can use NTLM authentication, with - * a fallback authentication method in case the user is not properly authenticated / authorized using - * NTLM. + * NTLMSecurityValve provides Subject creation based on the NTLM provided + * request.getRemoteUser() user name. When request.getRemoteUser() holds a valid + * value, then this user is authorized. Otherwise the username is retrieved from + * the Principal name in the request. In this way you can use NTLM + * authentication, with a fallback authentication method in case the user is not + * properly authenticated / authorized using NTLM. * * There are basically three authentication scenarios: *
          - *
        1. - *

          The user is successfully authenticated and authorized by Ntml authentication

          - *

          A Subject is created, with Principal derived from the remoteUser value from Ntlm authentication

          - *
        2. - *
        3. - *

          The user is not authenticated by Ntlm, or the authenticated (can be NTLM or any other method) user cannot be authorized by Jetspeed.

          - *

          An anonymous Subject is created. The user can then be redirected to a login page for example.

          - *
        4. - *
        5. - *

          The user is authenticated by a (non-NTLM) authentication method, e.g. container-based form authentication.

          - *

          - * A subject is created based on the Principal name in the request. - *

          - *
        6. + *
        7. + *

          + * The user is successfully authenticated and authorized by Ntml + * authentication + *

          + *

          + * A Subject is created, with Principal derived from the remoteUser value from + * Ntlm authentication + *

          + *
        8. + *
        9. + *

          + * The user is not authenticated by Ntlm, or the authenticated (can be NTLM + * or any other method) user cannot be authorized by Jetspeed. + *

          + *

          + * An anonymous Subject is created. The user can then be redirected to a login + * page for example. + *

          + *
        10. + *
        11. + *

          + * The user is authenticated by a (non-NTLM) authentication method, e.g. + * container-based form authentication. + *

          + *

          + * A subject is created based on the Principal name in the request. + *

          + *
        12. *
        + * * @author David Sean Taylor * @author Randy Walter * @author Scott T. Weaver * @author Dennis Dam * @version $Id$ */ -public class NtlmSecurityValve extends AbstractSecurityValve +public class NtlmSecurityValve extends AbstractSecurityValve { + private UserManager userMgr; + private PortalStatistics statistics; + private String networkDomain; + private boolean ntlmAuthRequired; + private boolean omitDomain; - - + /** - * @param userMgr A UserManager - * @param statistics Portal Statistics - * @param networkDomain The network domain is used in combination with the omitDomain flag. - * @param omitDomain If true, then the network domain is stripped from the remoteUser name. - * @param ntlmAuthRequired if true, then an exception is thrown when there is no valid remoteUser, - * or the remoteUser cannot be authorized. + * @param userMgr + * A UserManager + * @param statistics + * Portal Statistics + * @param networkDomain + * The network domain is used in combination with the + * omitDomain flag. + * @param omitDomain + * If true, then the network domain is stripped + * from the remoteUser name. + * @param ntlmAuthRequired + * if true, then an exception is thrown when + * there is no valid remoteUser, or the remoteUser cannot be + * authorized. * */ - public NtlmSecurityValve(UserManager userMgr, String networkDomain, boolean omitDomain, boolean ntlmAuthRequired, - PortalStatistics statistics, PortalAuthenticationConfiguration authenticationConfiguration) + public NtlmSecurityValve(UserManager userMgr, String networkDomain, + boolean omitDomain, boolean ntlmAuthRequired, + PortalStatistics statistics, + PortalAuthenticationConfiguration authenticationConfiguration) { this.userMgr = userMgr; this.statistics = statistics; @@ -94,12 +125,16 @@ this.authenticationConfiguration = authenticationConfiguration; } - public NtlmSecurityValve(UserManager userMgr, String networkDomain, boolean omitDomain, boolean ntlmAuthRequired, PortalStatistics statistics) + public NtlmSecurityValve(UserManager userMgr, String networkDomain, + boolean omitDomain, boolean ntlmAuthRequired, + PortalStatistics statistics) { - this(userMgr, networkDomain, omitDomain, ntlmAuthRequired, statistics, null); + this(userMgr, networkDomain, omitDomain, ntlmAuthRequired, statistics, + null); } - - public NtlmSecurityValve(UserManager userMgr, String networkDomain, boolean omitDomain, boolean ntlmAuthRequired) + + public NtlmSecurityValve(UserManager userMgr, String networkDomain, + boolean omitDomain, boolean ntlmAuthRequired) { this(userMgr, networkDomain, omitDomain, ntlmAuthRequired, null); } @@ -108,80 +143,94 @@ { return "NtlmSecurityValve"; } - - protected Principal getUserPrincipal(RequestContext context) throws Exception + + protected Principal getUserPrincipal(RequestContext context) + throws Exception { Subject subject = getSubjectFromSession(context); - if (subject != null) - { - return SecurityHelper.getPrincipal(subject, UserPrincipal.class); - } + if (subject != null) { return SecurityHelper.getPrincipal(subject, + UserPrincipal.class); } // otherwise return anonymous principal return new UserPrincipalImpl(userMgr.getAnonymousUser()); } - protected Subject getSubject(RequestContext context) throws Exception + protected Subject getSubject(RequestContext context) throws Exception { Subject subject = getSubjectFromSession(context); // Get remote user name set by web container String userName = context.getRequest().getRemoteUser(); - if ( userName == null ) - { - if (ntlmAuthRequired){ - throw new PipelineException("Authorization failed."); - } else if (context.getRequest().getUserPrincipal() != null){ + if (userName == null) + { + if (ntlmAuthRequired) + { + throw new PipelineException("Authorization failed."); + } + else if (context.getRequest().getUserPrincipal() != null) + { userName = context.getRequest().getUserPrincipal().getName(); - } - } else { - if (omitDomain && networkDomain != null){ - userName = StringUtils.stripStart( userName , networkDomain+"\\"); } } - - // check whether principal name stored in session subject equals the remote user name passed by the web container + else + { + if (omitDomain && networkDomain != null) + { + userName = StringUtils.stripStart(userName, networkDomain + + "\\"); + } + } + + // check whether principal name stored in session subject equals the + // remote user name passed by the web container if (subject != null) { - Principal subjectUserPrincipal = SecurityHelper.getPrincipal(subject, UserPrincipal.class); - if ((subjectUserPrincipal == null) || !subjectUserPrincipal.getName().equals(userName)) + Principal subjectUserPrincipal = SecurityHelper.getPrincipal( + subject, UserPrincipal.class); + if ((subjectUserPrincipal == null) + || !subjectUserPrincipal.getName().equals(userName)) { subject = null; } } - if ( subject == null ){ - if (userName != null){ + if (subject == null) + { + if (userName != null) + { try - { + { User user = userMgr.getUser(userName); - if ( user != null ) + if (user != null) { subject = user.getSubject(); } - } catch (SecurityException sex) + } + catch (SecurityException sex) { subject = null; } - - if (subject == null && this.ntlmAuthRequired){ - throw new PipelineException("Authorization failed for user '"+userName+"'."); - } - } - if (subject == null){ + + if (subject == null && this.ntlmAuthRequired) { throw new PipelineException( + "Authorization failed for user '" + userName + "'."); } + } + if (subject == null) + { // create anonymous user Principal userPrincipal = getUserPrincipal(context); Set principals = new HashSet(); principals.add(userPrincipal); - subject = new Subject(true, principals, new HashSet(), new HashSet()); + subject = new Subject(true, principals, new HashSet(), + new HashSet()); } - + // create a new statistics *user* session if (statistics != null) { statistics.logUserLogin(context, 0); } // put IP address in session for logout - context.setSessionAttribute(IP_ADDRESS, context.getRequest().getRemoteAddr()); - } - + context.setSessionAttribute(IP_ADDRESS, context.getRequest() + .getRemoteAddr()); + } + return subject; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/DynamicInformationProviderImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/DynamicInformationProviderImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/DynamicInformationProviderImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,60 +16,60 @@ */ package org.apache.jetspeed.services.information; -import java.util.Iterator; import java.util.HashSet; +import java.util.Iterator; + +import javax.portlet.PortletMode; +import javax.portlet.WindowState; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; -import javax.portlet.WindowState; -import javax.portlet.PortletMode; -import org.apache.pluto.services.information.DynamicInformationProvider; -import org.apache.pluto.services.information.PortletActionProvider; -import org.apache.pluto.services.information.ResourceURLProvider; -import org.apache.pluto.om.window.PortletWindow; -import org.apache.pluto.services.information.PortletURLProvider; +import org.apache.jetspeed.Jetspeed; import org.apache.jetspeed.container.state.MutableNavigationalState; import org.apache.jetspeed.container.state.NavigationalState; import org.apache.jetspeed.engine.core.PortletActionProviderImpl; import org.apache.jetspeed.request.RequestContext; import org.apache.jetspeed.request.RequestContextComponent; -import org.apache.jetspeed.Jetspeed; +import org.apache.pluto.om.window.PortletWindow; +import org.apache.pluto.services.information.DynamicInformationProvider; +import org.apache.pluto.services.information.PortletActionProvider; +import org.apache.pluto.services.information.PortletURLProvider; +import org.apache.pluto.services.information.ResourceURLProvider; /** * Provides dynamic information to Pluto Container: * - * 1. getPortletURL - * 2. getRequestMimetype - * 3. getResponseMimetype - * 4. getResponseMimetypes - * 5. getPortletMode - * 6. getPreviousPortletMode - * 7. getWindowState - * 8. getPreviousWindowState - * 9. isPortletModeAllowed - * 10. isWindowStateAllowed - * 11. getSupportedPortletModes - * 12. getSupportedWindowStates - * 13. getAllParameters - * + * 1. getPortletURL 2. getRequestMimetype 3. getResponseMimetype 4. + * getResponseMimetypes 5. getPortletMode 6. getPreviousPortletMode 7. + * getWindowState 8. getPreviousWindowState 9. isPortletModeAllowed 10. + * isWindowStateAllowed 11. getSupportedPortletModes 12. + * getSupportedWindowStates 13. getAllParameters + * * @author David Sean Taylor - * @version $Id: DynamicInformationProviderImpl.java 517719 2007-03-13 15:05:48Z ate $ + * @version $Id: DynamicInformationProviderImpl.java 517719 2007-03-13 15:05:48Z + * ate $ */ -public class DynamicInformationProviderImpl implements DynamicInformationProvider +public class DynamicInformationProviderImpl implements + DynamicInformationProvider { + HttpServletRequest request = null; + ServletConfig config = null; RequestContext context; - + public DynamicInformationProviderImpl(HttpServletRequest request, - ServletConfig config) + ServletConfig config) { this.request = request; this.config = config; - - // TODO: assemble this dependency when this provider is converted to a component - RequestContextComponent rcc = (RequestContextComponent)Jetspeed.getComponentManager().getComponent(RequestContextComponent.class); + + // TODO: assemble this dependency when this provider is converted to a + // component + RequestContextComponent rcc = (RequestContextComponent) Jetspeed + .getComponentManager().getComponent( + RequestContextComponent.class); this.context = rcc.getRequestContext(request); } @@ -78,36 +78,38 @@ return new PortletURLProviderImpl(this.context, portletWindow); } - public String getRequestContentType() - { - return context.getMimeType().toString(); - } + public String getRequestContentType() + { + return context.getMimeType().toString(); + } - public String getResponseContentType() - { - return context.getMimeType().toString(); - } + public String getResponseContentType() + { + return context.getMimeType().toString(); + } - public Iterator getResponseContentTypes() - { + public Iterator getResponseContentTypes() + { HashSet responseMimeTypes = new HashSet(NumberOfKnownMimetypes); - // TODO: need to integrate with capability code + // TODO: need to integrate with capability code responseMimeTypes.add("text/html"); - + return responseMimeTypes.iterator(); - } + } - public PortletMode getPortletMode(PortletWindow portletWindow) - { - NavigationalState navState = context.getPortalURL().getNavigationalState(); - return navState.getMode(portletWindow); - } + public PortletMode getPortletMode(PortletWindow portletWindow) + { + NavigationalState navState = context.getPortalURL() + .getNavigationalState(); + return navState.getMode(portletWindow); + } - public WindowState getWindowState(PortletWindow portletWindow) - { - NavigationalState navState = context.getPortalURL().getNavigationalState(); - return navState.getState(portletWindow); - } + public WindowState getWindowState(PortletWindow portletWindow) + { + NavigationalState navState = context.getPortalURL() + .getNavigationalState(); + return navState.getState(portletWindow); + } public boolean isPortletModeAllowed(PortletMode mode) { @@ -118,54 +120,47 @@ { return Jetspeed.getContext().isWindowStateAllowed(state); } - + public String getBasePortalURL() { - return context.getPortalURL().getBaseURL(); + return context.getPortalURL().getBaseURL(); } /* - private Map getAllParameters(PortletWindow portletWindow) - { - Enumeration parameters = request.getParameterNames(); + * private Map getAllParameters(PortletWindow portletWindow) { Enumeration + * parameters = request.getParameterNames(); + * + * Map portletParameters = new HashMap(); + * + * NamespaceMapper namespaceMapper = ((NamespaceMapperFactory) + * Jetspeed.getComponentManager().getComponent( + * org.apache.pluto.util.NamespaceMapper.class)).getNamespaceMapper(); while + * (parameters.hasMoreElements()) { String name = + * (String)parameters.nextElement(); + * + * String portletParameter = + * namespaceMapper.decode(portletWindow.getId(),name); + * + * if (portletParameter!=null) // it is in the portlet's namespace { + * portletParameters.put(portletParameter, request.getParameterValues(name) ); } } + * + * PortalURL url = context.getPortalURL(); + * + * Iterator iterator = + * url.getNavigationalState().getParameterNames(portletWindow); while + * (iterator.hasNext()) { String name = (String)iterator.next(); + * + * String[] values = + * url.getNavigationalState().getParameterValues(portletWindow, name); + * + * portletParameters.put(name, values ); } + * + * return portletParameters; } + */ - Map portletParameters = new HashMap(); - - NamespaceMapper namespaceMapper = ((NamespaceMapperFactory) Jetspeed.getComponentManager().getComponent( - org.apache.pluto.util.NamespaceMapper.class)).getNamespaceMapper(); - while (parameters.hasMoreElements()) - { - String name = (String)parameters.nextElement(); - - String portletParameter = namespaceMapper.decode(portletWindow.getId(),name); - - if (portletParameter!=null) // it is in the portlet's namespace - { - portletParameters.put(portletParameter, request.getParameterValues(name) ); - } - } - - PortalURL url = context.getPortalURL(); - - Iterator iterator = url.getNavigationalState().getParameterNames(portletWindow); - while (iterator.hasNext()) - { - String name = (String)iterator.next(); - - String[] values = url.getNavigationalState().getParameterValues(portletWindow, name); - - portletParameters.put(name, values ); - - } - - return portletParameters; - } - */ - private final static int NumberOfKnownMimetypes = 15; - - /** + /** *

        * getPortletActionProvider *

        @@ -175,11 +170,12 @@ * @return */ public PortletActionProvider getPortletActionProvider(PortletWindow window) - { - return new PortletActionProviderImpl((MutableNavigationalState)context.getPortalURL().getNavigationalState(), window); + { + return new PortletActionProviderImpl((MutableNavigationalState) context + .getPortalURL().getNavigationalState(), window); } - /** + /** *

        * getResourceURLProvider *

        @@ -190,7 +186,7 @@ */ public ResourceURLProvider getResourceURLProvider(PortletWindow window) { - + return new ResourceURLProviderImpl(this.context, window); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/InformationProviderServiceImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/InformationProviderServiceImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/InformationProviderServiceImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,83 +23,102 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; +import org.apache.jetspeed.aggregator.CurrentWorkerContext; import org.apache.pluto.factory.Factory; import org.apache.pluto.services.information.DynamicInformationProvider; import org.apache.pluto.services.information.InformationProviderService; import org.apache.pluto.services.information.StaticInformationProvider; -import org.apache.jetspeed.aggregator.CurrentWorkerContext; - /** * Factory class for getting Information Provider access - * + * * @author David Sean Taylor - * @version $Id: InformationProviderServiceImpl.java 587813 2007-10-24 08:20:39Z woonsan $ + * @version $Id: InformationProviderServiceImpl.java 587813 2007-10-24 08:20:39Z + * woonsan $ */ -public class InformationProviderServiceImpl implements Factory, InformationProviderService +public class InformationProviderServiceImpl implements Factory, + InformationProviderService { + private javax.servlet.ServletConfig servletConfig; + private final StaticInformationProvider staticInformationProvider; - - public InformationProviderServiceImpl(StaticInformationProvider staticInformationProvider, ServletConfig config) + + public InformationProviderServiceImpl( + StaticInformationProvider staticInformationProvider, + ServletConfig config) { this.staticInformationProvider = staticInformationProvider; - + } public void init(ServletConfig config, Map properties) throws Exception { - // does nothing at all + // does nothing at all } public StaticInformationProvider getStaticProvider() - { + { return staticInformationProvider; } - public DynamicInformationProvider getDynamicProvider(HttpServletRequest request) + public DynamicInformationProvider getDynamicProvider( + HttpServletRequest request) { DynamicInformationProvider provider = null; - + boolean isParallel = CurrentWorkerContext.getParallelRenderingMode(); ServletRequest servletRequest = null; - + if (isParallel) { - // request should be an instance of org.apache.jetspeed.engine.servlet.ServletRequestImpl - // unwrap the real request instance provided by the container to synchronize + // request should be an instance of + // org.apache.jetspeed.engine.servlet.ServletRequestImpl + // unwrap the real request instance provided by the container to + // synchronize servletRequest = ((HttpServletRequestWrapper) request).getRequest(); - // if it is not an instance of HttpServletRequestWrapper any more, then it is not AdjustedSRTServletRequest instance. + // if it is not an instance of HttpServletRequestWrapper any more, + // then it is not AdjustedSRTServletRequest instance. if (servletRequest instanceof HttpServletRequestWrapper) { - servletRequest = ((HttpServletRequestWrapper) servletRequest).getRequest(); + servletRequest = ((HttpServletRequestWrapper) servletRequest) + .getRequest(); } - + synchronized (servletRequest) { - provider = (DynamicInformationProvider) servletRequest.getAttribute("org.apache.jetspeed.engine.core.DynamicInformationProvider"); + provider = (DynamicInformationProvider) servletRequest + .getAttribute("org.apache.jetspeed.engine.core.DynamicInformationProvider"); } } else { - provider = (DynamicInformationProvider) request.getAttribute("org.apache.jetspeed.engine.core.DynamicInformationProvider"); + provider = (DynamicInformationProvider) request + .getAttribute("org.apache.jetspeed.engine.core.DynamicInformationProvider"); } if (provider == null) { - provider = new DynamicInformationProviderImpl(request, servletConfig); - + provider = new DynamicInformationProviderImpl(request, + servletConfig); + if (isParallel) { synchronized (servletRequest) { - servletRequest.setAttribute("org.apache.jetspeed.engine.core.DynamicInformationProvider", provider); + servletRequest + .setAttribute( + "org.apache.jetspeed.engine.core.DynamicInformationProvider", + provider); } } else { - request.setAttribute("org.apache.jetspeed.engine.core.DynamicInformationProvider", provider); + request + .setAttribute( + "org.apache.jetspeed.engine.core.DynamicInformationProvider", + provider); } } @@ -110,12 +129,12 @@ *

        * destroy *

        - * + * * @see org.apache.pluto.factory.Factory#destroy() * @throws java.lang.Exception */ public void destroy() throws Exception - { - // also does nothing + { + // also does nothing } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/PortletURLProviderImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/PortletURLProviderImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/PortletURLProviderImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,27 +27,34 @@ import org.apache.pluto.services.information.PortletURLProvider; /** - * Provides access to the Portal URL manipulation + * Provides access to the Portal URL manipulation * - * + * * @author David Sean Taylor * @version $Id: PortletURLProviderImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class PortletURLProviderImpl implements PortletURLProvider { + private PortletWindow portletWindow = null; + private PortletMode mode = null; + private WindowState state = null; + private boolean action = false; + private boolean secure = false; + private Map parameters = null; private PortalURL url; - - public PortletURLProviderImpl(RequestContext context, PortletWindow portletWindow) + + public PortletURLProviderImpl(RequestContext context, + PortletWindow portletWindow) { this.portletWindow = portletWindow; - + url = context.getPortalURL(); } @@ -83,6 +90,7 @@ public String toString() { - return url.createPortletURL(portletWindow,parameters,mode,state,action,secure); + return url.createPortletURL(portletWindow, parameters, mode, state, + action, secure); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/ResourceURLProviderImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/ResourceURLProviderImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/ResourceURLProviderImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,19 +23,18 @@ /** *

        * ResourceURLProviderImpl - *

        - * - * - * @ + *

        @ * @author Scott T. Weaver * @version $ $ - * + * */ public class ResourceURLProviderImpl implements ResourceURLProvider { + private String stringUrl = ""; - public ResourceURLProviderImpl(RequestContext context, PortletWindow portletWindow) + public ResourceURLProviderImpl(RequestContext context, + PortletWindow portletWindow) { } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/StaticInformationProviderImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/StaticInformationProviderImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/information/StaticInformationProviderImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,41 +27,46 @@ /** * Provides static information to Pluto Container: * - * 1. PortletDefinition - given a unique registry id, - * retrieve the portlet definition from the portlet registry - * + * 1. PortletDefinition - given a unique registry id, retrieve the portlet + * definition from the portlet registry + * * @author David Sean Taylor - * @version $Id: StaticInformationProviderImpl.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: StaticInformationProviderImpl.java 516448 2007-03-09 16:25:47Z + * ate $ */ public class StaticInformationProviderImpl implements StaticInformationProvider { + private final PortletRegistry portletRegistry; /** * @obsolete */ - public StaticInformationProviderImpl(ServletConfig config, PortalContextProvider portalContextProvider, PortletRegistry portletRegistry) + public StaticInformationProviderImpl(ServletConfig config, + PortalContextProvider portalContextProvider, + PortletRegistry portletRegistry) { this(portletRegistry); } - + public StaticInformationProviderImpl(PortletRegistry portletRegistry) { this.portletRegistry = portletRegistry; } /** - * Given a unique registry id, - * retrieve the portlet definition from the portlet registry - * - * @param uniqueId The uniquely identifying portlet id in the registry + * Given a unique registry id, retrieve the portlet definition from the + * portlet registry + * + * @param uniqueId + * The uniquely identifying portlet id in the registry */ public PortletDefinition getPortletDefinition(String uniqueId) - { + { return portletRegistry.getPortletDefinitionByIdentifier(uniqueId); } - /** + /** *

        * getPortalContextProvider *

        @@ -74,7 +79,7 @@ throw new UnsupportedOperationException(); } - /** + /** *

        * getPortletDefinition *

        @@ -84,7 +89,7 @@ * @return */ public PortletDefinition getPortletDefinition(ObjectID id) - { + { return portletRegistry.getPortletDefinition(id); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/title/DynamicTitleService.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/title/DynamicTitleService.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/title/DynamicTitleService.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,27 +1,28 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.services.title; import javax.servlet.http.HttpServletRequest; import org.apache.pluto.om.window.PortletWindow; +public interface DynamicTitleService extends + org.apache.pluto.services.title.DynamicTitleService +{ -public interface DynamicTitleService extends org.apache.pluto.services.title.DynamicTitleService -{ String getDynamicTitle(PortletWindow window, HttpServletRequest request); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/title/DynamicTitleServiceImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/title/DynamicTitleServiceImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/services/title/DynamicTitleServiceImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,31 +33,32 @@ public void setDynamicTitle(PortletWindow window, HttpServletRequest request, String titleArg) { - //String title = getTitleFromPreference(window, request); + // String title = getTitleFromPreference(window, request); String title = null; -// if (title == null || title.length() < 0) -// { - if (titleArg == null || titleArg.length() == 0) - { - title = getTitleFromPortletDefinition(window, request); - } - else - { - title = titleArg; - } + // if (title == null || title.length() < 0) + // { + if (titleArg == null || titleArg.length() == 0) + { + title = getTitleFromPortletDefinition(window, request); + } + else + { + title = titleArg; + } -// } + // } request.setAttribute( PortalReservedParameters.OVERRIDE_PORTLET_TITLE_ATTR + "::window.id::" + window.getId(), title); } - + public String getDynamicTitle(PortletWindow window, HttpServletRequest request) { - return (String)request.getAttribute(PortalReservedParameters.OVERRIDE_PORTLET_TITLE_ATTR + return (String) request + .getAttribute(PortalReservedParameters.OVERRIDE_PORTLET_TITLE_ATTR + "::window.id::" + window.getId()); } @@ -67,7 +68,7 @@ String title = null; RequestContext requestContext = (RequestContext) request .getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); - + PortletEntity entity = window.getPortletEntity(); if (entity != null && entity.getPortletDefinition() != null) { @@ -83,7 +84,7 @@ { title = "Invalid portlet entity " + entity.getId(); } - + return title; } @@ -105,10 +106,8 @@ if (titlePref != null) { Iterator values = titlePref.getValues(); - if (values.hasNext()) - { - return (String) titlePref.getValues().next(); - } + if (values.hasNext()) { return (String) titlePref.getValues() + .next(); } } return null; @@ -116,13 +115,13 @@ public static String createTitleKey(Locale locale, boolean languageOnly) { - if(languageOnly) + if (languageOnly) { - return "jetspeed.title."+locale.getLanguage(); + return "jetspeed.title." + locale.getLanguage(); } else { - return "jetspeed.title."+locale.toString(); + return "jetspeed.title." + locale.toString(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/PortletApplicationException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/PortletApplicationException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/PortletApplicationException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,37 +19,36 @@ import org.apache.jetspeed.exception.JetspeedException; /** - * Occurs when anything unexpected happens within the Portlet Application Manager. + * Occurs when anything unexpected happens within the Portlet Application + * Manager. * * @author David Sean Taylor - * @author Roger Ruttimann - * @version $Id: PortletApplicationException.java 516448 2007-03-09 16:25:47Z ate $ - **/ + * @author Roger Ruttimann + * @version $Id: PortletApplicationException.java 516448 2007-03-09 16:25:47Z + * ate $ + */ -public class PortletApplicationException extends JetspeedException +public class PortletApplicationException extends JetspeedException { - public PortletApplicationException() + public PortletApplicationException() { super(); } - - public PortletApplicationException(String message) + + public PortletApplicationException(String message) { super(message); } - + public PortletApplicationException(Throwable nested) { super(nested); } - + public PortletApplicationException(String msg, Throwable nested) { super(msg, nested); } - - } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/PortletApplicationManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/PortletApplicationManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/PortletApplicationManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -52,79 +52,107 @@ /** * PortletApplicationManager - * + * * @author Ate Douma - * @version $Id: PortletApplicationManager.java,v 1.21 2005/04/09 00:24:44 shinsuke Exp $ + * @version $Id: PortletApplicationManager.java,v 1.21 2005/04/09 00:24:44 + * shinsuke Exp $ */ public class PortletApplicationManager implements PortletApplicationManagement { - private static int DEFAULT_DESCRIPTOR_CHANGE_MONITOR_INTERVAL = 10*1000; // 10 seconds + + private static int DEFAULT_DESCRIPTOR_CHANGE_MONITOR_INTERVAL = 10 * 1000; // 10 + + // seconds + private static int DEFAULT_MAX_RETRIED_STARTS = 10; // 10 times retry PA - private static final Log log = LogFactory.getLog("deployment"); + private static final Log log = LogFactory.getLog("deployment"); + protected PortletEntityAccessComponent entityAccess; - protected PortletFactory portletFactory; - protected PortletRegistry registry; + + protected PortletFactory portletFactory; + + protected PortletRegistry registry; + protected PortletWindowAccessor windowAccess; - protected SearchEngine searchEngine; - protected RoleManager roleManager; - protected PermissionManager permissionManager; - protected boolean autoCreateRoles; - protected List permissionRoles; - protected int descriptorChangeMonitorInterval = DEFAULT_DESCRIPTOR_CHANGE_MONITOR_INTERVAL; + + protected SearchEngine searchEngine; + + protected RoleManager roleManager; + + protected PermissionManager permissionManager; + + protected boolean autoCreateRoles; + + protected List permissionRoles; + + protected int descriptorChangeMonitorInterval = DEFAULT_DESCRIPTOR_CHANGE_MONITOR_INTERVAL; + /** - * holds the max number of retries in case of unsuccessful PA start - * this addresses possible startup errors in clustered environments + * holds the max number of retries in case of unsuccessful PA start this + * addresses possible startup errors in clustered environments */ - protected int maxRetriedStarts = DEFAULT_MAX_RETRIED_STARTS; + protected int maxRetriedStarts = DEFAULT_MAX_RETRIED_STARTS; + protected DescriptorChangeMonitor monitor = null; + protected boolean started; + protected String appRoot; + protected NodeManager nodeManager; - + /** - * Creates a new PortletApplicationManager object. - */ - public PortletApplicationManager(PortletFactory portletFactory, PortletRegistry registry, - PortletEntityAccessComponent entityAccess, PortletWindowAccessor windowAccess, - PermissionManager permissionManager, SearchEngine searchEngine, - RoleManager roleManager, List permissionRoles, NodeManager nodeManager, String appRoot) - { - this.portletFactory = portletFactory; - this.registry = registry; - this.entityAccess = entityAccess; - this.windowAccess = windowAccess; - this.permissionManager = permissionManager; - this.searchEngine = searchEngine; - this.roleManager = roleManager; - this.permissionRoles = permissionRoles; - this.nodeManager = nodeManager; - this.appRoot = appRoot; - } - + * Creates a new PortletApplicationManager object. + */ + public PortletApplicationManager(PortletFactory portletFactory, + PortletRegistry registry, + PortletEntityAccessComponent entityAccess, + PortletWindowAccessor windowAccess, + PermissionManager permissionManager, SearchEngine searchEngine, + RoleManager roleManager, List permissionRoles, + NodeManager nodeManager, String appRoot) + { + this.portletFactory = portletFactory; + this.registry = registry; + this.entityAccess = entityAccess; + this.windowAccess = windowAccess; + this.permissionManager = permissionManager; + this.searchEngine = searchEngine; + this.roleManager = roleManager; + this.permissionRoles = permissionRoles; + this.nodeManager = nodeManager; + this.appRoot = appRoot; + } + public void start() { - if ( descriptorChangeMonitorInterval > 0 ) + if (descriptorChangeMonitorInterval > 0) { try { - monitor = new DescriptorChangeMonitor(Thread.currentThread().getThreadGroup(), - "PortletApplicationManager Descriptor Change Monitor Thread", this, descriptorChangeMonitorInterval, maxRetriedStarts); + monitor = new DescriptorChangeMonitor( + Thread.currentThread().getThreadGroup(), + "PortletApplicationManager Descriptor Change Monitor Thread", + this, descriptorChangeMonitorInterval, maxRetriedStarts); monitor.setContextClassLoader(getClass().getClassLoader()); monitor.start(); - log.info("PortletApplicationManager Descriptor Change Monitor started!"); + log + .info("PortletApplicationManager Descriptor Change Monitor started!"); } catch (Exception e) { - log.warn("Unable to start PortletApplicationManager Descriptor Change Monitor: "+ e.toString(), e); + log.warn( + "Unable to start PortletApplicationManager Descriptor Change Monitor: " + + e.toString(), e); monitor.safeStop(); monitor = null; } } started = true; } - + public void stop() { started = false; @@ -134,95 +162,106 @@ monitor = null; } } - + public boolean isStarted() { return started; } - + public void setRoleManager(RoleManager roleManager) { this.roleManager = roleManager; } - + public void setAutoCreateRoles(boolean autoCreateRoles) { this.autoCreateRoles = autoCreateRoles; } - public void setSearchEngine(SearchEngine searchEngine) - { - this.searchEngine = searchEngine; - } - + public void setSearchEngine(SearchEngine searchEngine) + { + this.searchEngine = searchEngine; + } + protected void checkStarted() { - if (!started) - { - throw new IllegalStateException("Not started yet"); - } + if (!started) { throw new IllegalStateException("Not started yet"); } } - public void startLocalPortletApplication(String contextName, FileSystemHelper warStruct, - ClassLoader paClassLoader) - throws RegistryException - { + public void startLocalPortletApplication(String contextName, + FileSystemHelper warStruct, ClassLoader paClassLoader) + throws RegistryException + { checkStarted(); - startPA(contextName, "/"+contextName, warStruct, paClassLoader, MutablePortletApplication.LOCAL); - } + startPA(contextName, "/" + contextName, warStruct, paClassLoader, + MutablePortletApplication.LOCAL); + } - public void startInternalApplication(String contextName) throws RegistryException + public void startInternalApplication(String contextName) + throws RegistryException { checkStarted(); - File webinf = new File (appRoot); - ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + File webinf = new File(appRoot); + ClassLoader contextClassLoader = Thread.currentThread() + .getContextClassLoader(); DirectoryHelper dir = new DirectoryHelper(webinf); - String appName = (contextName.startsWith("/")) ? contextName.substring(1) : contextName; - MutablePortletApplication app = registry.getPortletApplicationByIdentifier(appName); - if (app != null && app.getApplicationType() == MutablePortletApplication.LOCAL) + String appName = (contextName.startsWith("/")) ? contextName + .substring(1) : contextName; + MutablePortletApplication app = registry + .getPortletApplicationByIdentifier(appName); + if (app != null + && app.getApplicationType() == MutablePortletApplication.LOCAL) { app.setApplicationType(MutablePortletApplication.INTERNAL); registry.updatePortletApplication(app); } - startPA(contextName, "/"+contextName, dir, contextClassLoader, MutablePortletApplication.INTERNAL); - // startInternal(contextName, warStruct, paClassLoader, true); + startPA(contextName, "/" + contextName, dir, contextClassLoader, + MutablePortletApplication.INTERNAL); + // startInternal(contextName, warStruct, paClassLoader, true); } - - public void startPortletApplication(String contextName, FileSystemHelper warStruct, - ClassLoader paClassLoader) - throws RegistryException - { - startPortletApplication(contextName, "/"+contextName, warStruct, paClassLoader); - } - - public void startPortletApplication(String contextName, String contextPath, FileSystemHelper warStruct, - ClassLoader paClassLoader) throws RegistryException + + public void startPortletApplication(String contextName, + FileSystemHelper warStruct, ClassLoader paClassLoader) + throws RegistryException { + startPortletApplication(contextName, "/" + contextName, warStruct, + paClassLoader); + } + + public void startPortletApplication(String contextName, String contextPath, + FileSystemHelper warStruct, ClassLoader paClassLoader) + throws RegistryException + { checkStarted(); - ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); + ClassLoader contextClassLoader = Thread.currentThread() + .getContextClassLoader(); + Thread.currentThread().setContextClassLoader( + this.getClass().getClassLoader()); try { - startPA(contextName, contextPath, warStruct, paClassLoader, MutablePortletApplication.WEBAPP); + startPA(contextName, contextPath, warStruct, paClassLoader, + MutablePortletApplication.WEBAPP); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } - - } - public void stopLocalPortletApplication(String contextName) - throws RegistryException - { - stopPA(contextName, MutablePortletApplication.LOCAL); - } + } - public void stopPortletApplication(String contextName) - throws RegistryException - { - ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); + public void stopLocalPortletApplication(String contextName) + throws RegistryException + { + stopPA(contextName, MutablePortletApplication.LOCAL); + } + + public void stopPortletApplication(String contextName) + throws RegistryException + { + ClassLoader contextClassLoader = Thread.currentThread() + .getContextClassLoader(); + Thread.currentThread().setContextClassLoader( + this.getClass().getClassLoader()); try { stopPA(contextName, MutablePortletApplication.WEBAPP); @@ -231,17 +270,19 @@ { Thread.currentThread().setContextClassLoader(contextClassLoader); } - } + } - public void unregisterPortletApplication(String paName) - throws RegistryException - { - ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); + public void unregisterPortletApplication(String paName) + throws RegistryException + { + ClassLoader contextClassLoader = Thread.currentThread() + .getContextClassLoader(); + Thread.currentThread().setContextClassLoader( + this.getClass().getClassLoader()); try { MutablePortletApplication pa = null; - + try { pa = registry.getPortletApplication(paName); @@ -251,23 +292,20 @@ // ignore errors during portal shutdown } - if (pa != null) { - if (portletFactory.isPortletApplicationRegistered(pa)) - { - throw new RegistryException("Portlet Application " + paName + " still running"); - } + if (portletFactory.isPortletApplicationRegistered(pa)) { throw new RegistryException( + "Portlet Application " + paName + " still running"); } unregisterPortletApplication(pa, true); try { - if (nodeManager != null) - nodeManager.removeNode(paName); + if (nodeManager != null) nodeManager.removeNode(paName); } catch (Exception ee) { - // we actually do not care about an exception in the remove operation... + // we actually do not care about an exception in the remove + // operation... } } } @@ -275,170 +313,181 @@ { Thread.currentThread().setContextClassLoader(contextClassLoader); } - } - - protected void checkValidContextName(String contextName, boolean local) - throws RegistryException - { - int prefixLength = LOCAL_PA_PREFIX.length(); + } - if ((contextName.length() >= prefixLength) - && contextName.substring(0, prefixLength).equalsIgnoreCase(LOCAL_PA_PREFIX)) - { - if (!local) - { - throw new RegistryException("Prefix \"" + LOCAL_PA_PREFIX - + "\" is reserved for Local Portlet Applications only."); - } - } - else if (local) - { - throw new RegistryException("Prefix \"" + LOCAL_PA_PREFIX - + "\" is required for Local Portlet Applications."); - } - } + protected void checkValidContextName(String contextName, boolean local) + throws RegistryException + { + int prefixLength = LOCAL_PA_PREFIX.length(); - protected MutablePortletApplication registerPortletApplication(PortletApplicationWar paWar, - MutablePortletApplication oldPA, int paType, ClassLoader paClassLoader) - throws RegistryException - { - if (oldPA != null) - { - unregisterPortletApplication(oldPA, false); - oldPA = null; - } + if ((contextName.length() >= prefixLength) + && contextName.substring(0, prefixLength).equalsIgnoreCase( + LOCAL_PA_PREFIX)) + { + if (!local) { throw new RegistryException("Prefix \"" + + LOCAL_PA_PREFIX + + "\" is reserved for Local Portlet Applications only."); } + } + else if (local) { throw new RegistryException("Prefix \"" + + LOCAL_PA_PREFIX + + "\" is required for Local Portlet Applications."); } + } - MutablePortletApplication pa = null; - boolean registered = false; - String paName = paWar.getPortletApplicationName(); + protected MutablePortletApplication registerPortletApplication( + PortletApplicationWar paWar, MutablePortletApplication oldPA, + int paType, ClassLoader paClassLoader) throws RegistryException + { + if (oldPA != null) + { + unregisterPortletApplication(oldPA, false); + oldPA = null; + } - try - { - log.info("Loading portlet.xml...." + paName); - pa = paWar.createPortletApp(paClassLoader); - pa.setApplicationType(paType); + MutablePortletApplication pa = null; + boolean registered = false; + String paName = paWar.getPortletApplicationName(); - // load the web.xml - log.info("Loading web.xml...." + paName); - MutableWebApplication wa = paWar.createWebApp(); - paWar.validate(); + try + { + log.info("Loading portlet.xml...." + paName); + pa = paWar.createPortletApp(paClassLoader); + pa.setApplicationType(paType); - if (paType == MutablePortletApplication.LOCAL) - { - wa.setContextRoot(""); - } + // load the web.xml + log.info("Loading web.xml...." + paName); + MutableWebApplication wa = paWar.createWebApp(); + paWar.validate(); + + if (paType == MutablePortletApplication.LOCAL) + { + wa.setContextRoot(""); + } else if (paType == MutablePortletApplication.INTERNAL) { - // TODO: this is screwing up the PSML as its set all over the place to "jetspeed-layouts", not good - wa.setContextRoot("/" + paName); + // TODO: this is screwing up the PSML as its set all over the + // place to "jetspeed-layouts", not good + wa.setContextRoot("/" + paName); } - pa.setWebApplicationDefinition(wa); - + pa.setWebApplicationDefinition(wa); + // Make sure existing entities are refreshed with the most // recent PortletDefintion. Collection portletDefs = pa.getPortletDefinitions(); - if(portletDefs != null && portletDefs.size() > 0) + if (portletDefs != null && portletDefs.size() > 0) { Iterator pdItr = portletDefs.iterator(); - while(pdItr.hasNext()) + while (pdItr.hasNext()) { PortletDefinition pd = (PortletDefinition) pdItr.next(); - Collection portletEntites = entityAccess.getPortletEntities(pd); - if(portletEntites != null && portletEntites.size() > 0) + Collection portletEntites = entityAccess + .getPortletEntities(pd); + if (portletEntites != null && portletEntites.size() > 0) { Iterator peItr = portletEntites.iterator(); - while(peItr.hasNext()) + while (peItr.hasNext()) { - PortletEntityCtrl portletEntity = (PortletEntityCtrl) peItr.next(); + PortletEntityCtrl portletEntity = (PortletEntityCtrl) peItr + .next(); portletEntity.setPortletDefinition(pd); } } } } - } - catch (Exception e) - { - String msg = "Failed to load portlet application for " - + paWar.getPortletApplicationName(); - log.error(msg, e); - throw new RegistryException(msg); - } + } + catch (Exception e) + { + String msg = "Failed to load portlet application for " + + paWar.getPortletApplicationName(); + log.error(msg, e); + throw new RegistryException(msg); + } - // register the portlet application - try - { - registry.registerPortletApplication(pa); - registered = true; - log.info("Registered the portlet application " + paName); + // register the portlet application + try + { + registry.registerPortletApplication(pa); + registered = true; + log.info("Registered the portlet application " + paName); - // add to search engine result - this.updateSearchEngine(false, pa); - - // and add to the current node info + // add to search engine result + this.updateSearchEngine(false, pa); + + // and add to the current node info if (nodeManager != null) { - nodeManager.addNode(new Long(pa.getId().toString()), pa.getName()); + nodeManager.addNode(new Long(pa.getId().toString()), pa + .getName()); } // grant default permissions to portlet application - grantDefaultPermissions(paName); - - if ( autoCreateRoles && roleManager != null && pa.getWebApplicationDefinition().getSecurityRoles() != null ) + grantDefaultPermissions(paName); + + if (autoCreateRoles + && roleManager != null + && pa.getWebApplicationDefinition().getSecurityRoles() != null) { try { - Iterator rolesIter = pa.getWebApplicationDefinition().getSecurityRoles().iterator(); + Iterator rolesIter = pa.getWebApplicationDefinition() + .getSecurityRoles().iterator(); SecurityRole sr; - while ( rolesIter.hasNext() ) + while (rolesIter.hasNext()) { - sr = (SecurityRole)rolesIter.next(); - if ( !roleManager.roleExists(sr.getRoleName()) ) + sr = (SecurityRole) rolesIter.next(); + if (!roleManager.roleExists(sr.getRoleName())) { roleManager.addRole(sr.getRoleName()); - log.info("AutoCreated role: "+sr.getRoleName()+" from portlet application "+paName+" its web definition"); + log.info("AutoCreated role: " + sr.getRoleName() + + " from portlet application " + paName + + " its web definition"); } } } catch (SecurityException sex) { - log.warn("Failed to autoCreate roles for portlet application " + paName+": "+sex.getMessage(), sex); + log.warn( + "Failed to autoCreate roles for portlet application " + + paName + ": " + sex.getMessage(), sex); } } - return pa; - } - catch (Exception e) - { - String msg = "Failed to register portlet application, " + paName; - log.error(msg, e); + return pa; + } + catch (Exception e) + { + String msg = "Failed to register portlet application, " + paName; + log.error(msg, e); - if (registered) - { - try - { - unregisterPortletApplication(pa, (paType == MutablePortletApplication.LOCAL)); - } - catch (Exception re) - { - log.error("Failed to rollback registration of portlet application " + paName, re); - } - } + if (registered) + { + try + { + unregisterPortletApplication(pa, + (paType == MutablePortletApplication.LOCAL)); + } + catch (Exception re) + { + log.error( + "Failed to rollback registration of portlet application " + + paName, re); + } + } - throw new RegistryException(msg, e); - } - } + throw new RegistryException(msg, e); + } + } - protected void startPA(String contextName, String contextPath, FileSystemHelper warStruct, - ClassLoader paClassLoader, int paType) - throws RegistryException - { - startPA(contextName, contextPath, warStruct, paClassLoader, paType, 0); - } - - protected void startPA(String contextName, String contextPath, FileSystemHelper warStruct, - ClassLoader paClassLoader, int paType, long checksum) - throws RegistryException - { + protected void startPA(String contextName, String contextPath, + FileSystemHelper warStruct, ClassLoader paClassLoader, int paType) + throws RegistryException + { + startPA(contextName, contextPath, warStruct, paClassLoader, paType, 0); + } + + protected void startPA(String contextName, String contextPath, + FileSystemHelper warStruct, ClassLoader paClassLoader, int paType, + long checksum) throws RegistryException + { boolean register = true; boolean monitored = false; DescriptorChangeMonitor changeMonitor = this.monitor; @@ -448,212 +497,268 @@ } if (log.isDebugEnabled()) { - log.debug("Is portlet application " + contextName + " monitored? -> " + monitored); + log.debug("Is portlet application " + contextName + + " monitored? -> " + monitored); } PortletApplicationWar paWar = null; - try - { + try + { if (log.isDebugEnabled()) { - log.debug("Try to start portlet application " + contextName + "."); + log.debug("Try to start portlet application " + contextName + + "."); } - // create PA from war (file) structure - // paWar = new PortletApplicationWar(warStruct, contextName, "/" + contextName, checksum); - paWar = new PortletApplicationWar(warStruct, contextName, contextPath, checksum); + // create PA from war (file) structure + // paWar = new PortletApplicationWar(warStruct, contextName, "/" + + // contextName, checksum); + paWar = new PortletApplicationWar(warStruct, contextName, + contextPath, checksum); try { if (paClassLoader == null) { - paClassLoader = paWar.createClassloader(getClass().getClassLoader()); - } + paClassLoader = paWar.createClassloader(getClass() + .getClassLoader()); + } // create checksum from PA descriptors - checksum = paWar.getPortletApplicationChecksum(); - + checksum = paWar.getPortletApplicationChecksum(); + if (log.isDebugEnabled()) { - log.debug("New checksum for portlet application " + contextName + " is " + checksum); + log.debug("New checksum for portlet application " + + contextName + " is " + checksum); } } catch (IOException e) { String msg = "Invalid PA WAR for " + contextName; log.error(msg, e); - if ( paClassLoader == null ) + if (paClassLoader == null) { - // nothing to be done about it anymore: this pa is beyond repair :( + // nothing to be done about it anymore: this pa is beyond + // repair :( throw new RegistryException(e); } register = false; } - // try to get the PA from database by context name - MutablePortletApplication pa = registry.getPortletApplication(contextName); + // try to get the PA from database by context name + MutablePortletApplication pa = registry + .getPortletApplication(contextName); if (pa != null) { if (log.isDebugEnabled()) { - log.debug("Portlet Application " + contextName + " found in registry."); - } - if ( pa.getApplicationType() != paType ) - { - throw new RegistryException("Cannot start portlet application "+contextName+": as Application Types don't match: " + pa.getApplicationType() + " != " + paType); + log.debug("Portlet Application " + contextName + + " found in registry."); } + if (pa.getApplicationType() != paType) { throw new RegistryException( + "Cannot start portlet application " + contextName + + ": as Application Types don't match: " + + pa.getApplicationType() + " != " + paType); } if (!monitored && changeMonitor != null) { changeMonitor.remove(contextName); } if (log.isDebugEnabled()) { - log.debug("unregistering portlet application " + contextName + "..."); + log.debug("unregistering portlet application " + + contextName + "..."); } - portletFactory.unregisterPortletApplication(pa); + portletFactory.unregisterPortletApplication(pa); } -// if (register && (pa == null || checksum != pa.getChecksum())) + // if (register && (pa == null || checksum != pa.getChecksum())) if (register) { - if (pa == null) - { - // new - try - { - if (log.isDebugEnabled()) + if (pa == null) + { + // new + try + { + if (log.isDebugEnabled()) { - log.debug("Register new portlet application " + contextName + "."); + log.debug("Register new portlet application " + + contextName + "."); } - pa = registerPortletApplication(paWar, pa, paType, paClassLoader); - } - catch (Exception e) - { - String msg = "Error register new portlet application " + contextName + "."; - - if (log.isDebugEnabled()) - { - log.debug(msg); - } - throw new RegistryException(msg); - - } - } - else - { + pa = registerPortletApplication(paWar, pa, paType, + paClassLoader); + } + catch (Exception e) + { + String msg = "Error register new portlet application " + + contextName + "."; + + if (log.isDebugEnabled()) + { + log.debug(msg); + } + throw new RegistryException(msg); + + } + } + else + { if (log.isDebugEnabled()) { - log.debug("Re-register existing portlet application " + contextName + "."); + log.debug("Re-register existing portlet application " + + contextName + "."); } - int status = nodeManager.checkNode(new Long(pa.getId().toString()), pa.getName()); - boolean reregister = false; - boolean deploy = false; - switch (status) - { - case NodeManager.NODE_NEW: - { - if (log.isDebugEnabled()) - { - log.debug("Node for Portlet application " + contextName + " is NEW."); - } - //only reason is that the file got somehow corrupted - // so we really do not know what is going on here... - // the best chance at this point is to reregister (which might be the absolute wrong choice) - log.warn("The portlet application " + pa.getName() + " is registered in the database but not locally .... we will reregister"); - reregister = true; - if (checksum != pa.getChecksum()) - { - log.warn("The provided portlet application " + pa.getName() + " is a different version than in the database (db-checksum=" + pa.getChecksum() + ", local-checksum=: " + checksum + ") .... we will redeploy (also to the database)"); - deploy = true; - } - break; - } - case NodeManager.NODE_SAVED: - { - if (log.isDebugEnabled()) - { - log.debug("Node for Portlet application " + contextName + " is SAVED."); - } - if (checksum != pa.getChecksum()) - { - log.warn("The provided portlet application " + pa.getName() + " is a different version than in the local node info and the database (db-checksum=" + pa.getChecksum() + ", local-checksum=: " + checksum + ") .... we will reregister AND redeploy (also to the database)"); - //database and local node info are in synch, so we assume that this is a brand new - // war .... let's deploy - reregister = true; - deploy = true; - } - break; - } - case NodeManager.NODE_OUTDATED: - { - // new version in database, maybe changed by a different cluster node - if (log.isDebugEnabled()) - { - log.debug("Node for Portlet application " + contextName + " is OUTDATED (local PA.id < DB PA.id)."); - } - //database version is older (determined by id) than the database - //let's deploy and reregister - if (checksum != pa.getChecksum()) - { - log.error("The portlet application " + pa.getName() + " provided for the upgrade IS WRONG. The database checksum= " + pa.getChecksum() + ", but the local=" + checksum + "....THIS NEEDS TO BE CORRECTED"); - // if the checksums do not match make sure the database is updated with the new PA from file system - // I've observed "unavailable PA" in clustered env for the cluster node that reported OUTDATED state - deploy = true; - } - reregister = true; - break; - } - } - if (deploy) - { - if (log.isDebugEnabled()) - { - log.debug("Register (deploy=true) Portlet application " + contextName + " in database."); + int status = nodeManager.checkNode(new Long(pa.getId() + .toString()), pa.getName()); + boolean reregister = false; + boolean deploy = false; + switch (status) + { + case NodeManager.NODE_NEW: { + if (log.isDebugEnabled()) + { + log.debug("Node for Portlet application " + + contextName + " is NEW."); } - pa = registerPortletApplication(paWar, pa, paType, paClassLoader); - } - else - if (reregister) - { - if (log.isDebugEnabled()) - { - log.debug("Re-Register (reregister=true) Portlet application " + contextName + "."); - } - // add to search engine result - this.updateSearchEngine(true, pa); - this.updateSearchEngine(false, pa); - - // and add to the current node info - try - { - nodeManager.addNode(new Long(pa.getId().toString()), pa.getName()); - } catch (Exception e) - { - log.error("Adding node for portlet application " + pa.getName() + " caused exception" , e); - } - } - - - } + // only reason is that the file got somehow corrupted + // so we really do not know what is going on here... + // the best chance at this point is to reregister (which + // might be the absolute wrong choice) + log + .warn("The portlet application " + + pa.getName() + + " is registered in the database but not locally .... we will reregister"); + reregister = true; + if (checksum != pa.getChecksum()) + { + log + .warn("The provided portlet application " + + pa.getName() + + " is a different version than in the database (db-checksum=" + + pa.getChecksum() + + ", local-checksum=: " + + checksum + + ") .... we will redeploy (also to the database)"); + deploy = true; + } + break; + } + case NodeManager.NODE_SAVED: { + if (log.isDebugEnabled()) + { + log.debug("Node for Portlet application " + + contextName + " is SAVED."); + } + if (checksum != pa.getChecksum()) + { + log + .warn("The provided portlet application " + + pa.getName() + + " is a different version than in the local node info and the database (db-checksum=" + + pa.getChecksum() + + ", local-checksum=: " + + checksum + + ") .... we will reregister AND redeploy (also to the database)"); + // database and local node info are in synch, so we + // assume that this is a brand new + // war .... let's deploy + reregister = true; + deploy = true; + } + break; + } + case NodeManager.NODE_OUTDATED: { + // new version in database, maybe changed by a different + // cluster node + if (log.isDebugEnabled()) + { + log.debug("Node for Portlet application " + + contextName + + " is OUTDATED (local PA.id < DB PA.id)."); + } + // database version is older (determined by id) than the + // database + // let's deploy and reregister + if (checksum != pa.getChecksum()) + { + log + .error("The portlet application " + + pa.getName() + + " provided for the upgrade IS WRONG. The database checksum= " + + pa.getChecksum() + + ", but the local=" + checksum + + "....THIS NEEDS TO BE CORRECTED"); + // if the checksums do not match make sure the + // database is updated with the new PA from file + // system + // I've observed "unavailable PA" in clustered env + // for the cluster node that reported OUTDATED state + deploy = true; + } + reregister = true; + break; + } + } + if (deploy) + { + if (log.isDebugEnabled()) + { + log + .debug("Register (deploy=true) Portlet application " + + contextName + " in database."); + } + pa = registerPortletApplication(paWar, pa, paType, + paClassLoader); + } + else if (reregister) + { + if (log.isDebugEnabled()) + { + log + .debug("Re-Register (reregister=true) Portlet application " + + contextName + "."); + } + // add to search engine result + this.updateSearchEngine(true, pa); + this.updateSearchEngine(false, pa); + + // and add to the current node info + try + { + nodeManager.addNode( + new Long(pa.getId().toString()), pa + .getName()); + } + catch (Exception e) + { + log.error("Adding node for portlet application " + + pa.getName() + " caused exception", e); + } + } + + } } if (register) { if (log.isDebugEnabled()) { - log.debug("Register Portlet application " + contextName + " in portlet factory."); + log.debug("Register Portlet application " + contextName + + " in portlet factory."); } portletFactory.registerPortletApplication(pa, paClassLoader); } - + if (!monitored && changeMonitor != null) { if (log.isDebugEnabled()) { - log.debug("Add change monitor for application " + contextName + " with checksum " + checksum + "."); + log.debug("Add change monitor for application " + + contextName + " with checksum " + checksum + "."); } - changeMonitor.monitor(contextName, contextPath, paClassLoader, paType, warStruct.getRootDirectory(), checksum); + changeMonitor.monitor(contextName, contextPath, paClassLoader, + paType, warStruct.getRootDirectory(), checksum); } - } + } catch (Exception e) { String msg = "Error starting portlet application " + contextName; - + log.error(msg, e); // monitor PA for changes // do not add monitor if a monitor already exists @@ -662,34 +767,37 @@ // this code should be hit only during startup process if (log.isDebugEnabled()) { - log.debug("Add change monitor for application " + contextName + " and set unsuccessful starts to 1."); + log.debug("Add change monitor for application " + + contextName + + " and set unsuccessful starts to 1."); } - changeMonitor.monitor(contextName, contextPath, paClassLoader, paType, warStruct.getRootDirectory(), checksum); + changeMonitor.monitor(contextName, contextPath, paClassLoader, + paType, warStruct.getRootDirectory(), checksum); changeMonitor.get(contextName).setUnsuccessfulStarts(1); } throw new RegistryException(msg); } - finally - { - if (paWar != null) - { - try - { - paWar.close(); - } - catch (IOException e) - { - log.error("Failed to close PA WAR for " + contextName, e); - } - } - } - } + finally + { + if (paWar != null) + { + try + { + paWar.close(); + } + catch (IOException e) + { + log.error("Failed to close PA WAR for " + contextName, e); + } + } + } + } - protected void stopPA(String contextName, int paType) - throws RegistryException - { - MutablePortletApplication pa = null; - + protected void stopPA(String contextName, int paType) + throws RegistryException + { + MutablePortletApplication pa = null; + try { pa = registry.getPortletApplication(contextName); @@ -698,112 +806,122 @@ { // ignore errors during portal shutdown } - if (pa != null && pa.getApplicationType() != paType) - { - throw new RegistryException("Cannot stop portlet application "+contextName+": as Application Types don't match: " + pa.getApplicationType() + " != " + paType); - } + if (pa != null && pa.getApplicationType() != paType) { throw new RegistryException( + "Cannot stop portlet application " + contextName + + ": as Application Types don't match: " + + pa.getApplicationType() + " != " + paType); } DescriptorChangeMonitor monitor = this.monitor; - if ( monitor != null ) + if (monitor != null) { monitor.remove(contextName); } - if (pa != null) - { + if (pa != null) + { portletFactory.unregisterPortletApplication(pa); - } - } + } + } - - protected void updateSearchEngine(boolean remove,MutablePortletApplication pa ) - { - if (searchEngine != null) - { - if (remove) - { - searchEngine.remove(pa); - searchEngine.remove(pa.getPortletDefinitions()); - log.info("Un-Registered the portlet application in the search engine... " + pa.getName()); - } - else - { - searchEngine.add(pa); + protected void updateSearchEngine(boolean remove, + MutablePortletApplication pa) + { + if (searchEngine != null) + { + if (remove) + { + searchEngine.remove(pa); + searchEngine.remove(pa.getPortletDefinitions()); + log + .info("Un-Registered the portlet application in the search engine... " + + pa.getName()); + } + else + { + searchEngine.add(pa); searchEngine.add(pa.getPortletDefinitions()); - log.info("Registered the portlet application in the search engine... " + pa.getName()); - } - } - - } - protected void unregisterPortletApplication(MutablePortletApplication pa, - boolean purgeEntityInfo) - throws RegistryException - { + log + .info("Registered the portlet application in the search engine... " + + pa.getName()); + } + } - updateSearchEngine(true,pa); - log.info("Remove all registry entries defined for portlet application " + pa.getName()); + } - Iterator portlets = pa.getPortletDefinitions().iterator(); + protected void unregisterPortletApplication(MutablePortletApplication pa, + boolean purgeEntityInfo) throws RegistryException + { - while (portlets.hasNext()) - { - PortletDefinition portletDefinition = (PortletDefinition) portlets.next(); - Iterator entities = entityAccess.getPortletEntities(portletDefinition) - .iterator(); + updateSearchEngine(true, pa); + log.info("Remove all registry entries defined for portlet application " + + pa.getName()); - while (entities.hasNext()) - { - PortletEntity entity = (PortletEntity) entities.next(); + Iterator portlets = pa.getPortletDefinitions().iterator(); - if (purgeEntityInfo) - { - try - { - entityAccess.removePortletEntity(entity); - } - catch (PortletEntityNotDeletedException e) - { - String msg = "Failed to delete Portlet Entity " + entity.getId(); - log.error(msg, e); - throw new RegistryException(msg, e); - } - } + while (portlets.hasNext()) + { + PortletDefinition portletDefinition = (PortletDefinition) portlets + .next(); + Iterator entities = entityAccess.getPortletEntities( + portletDefinition).iterator(); - entityAccess.removeFromCache(entity); - windowAccess.removeWindows(entity); - } - } + while (entities.hasNext()) + { + PortletEntity entity = (PortletEntity) entities.next(); - // todo keep (User)Prefs? - registry.removeApplication(pa); + if (purgeEntityInfo) + { + try + { + entityAccess.removePortletEntity(entity); + } + catch (PortletEntityNotDeletedException e) + { + String msg = "Failed to delete Portlet Entity " + + entity.getId(); + log.error(msg, e); + throw new RegistryException(msg, e); + } + } + + entityAccess.removeFromCache(entity); + windowAccess.removeWindows(entity); + } + } + + // todo keep (User)Prefs? + registry.removeApplication(pa); revokeDefaultPermissions(pa.getName()); - } - + } + protected void grantDefaultPermissions(String paName) { try { - // create a default permission for this portlet app, granting configured roles to the portlet application + // create a default permission for this portlet app, granting + // configured roles to the portlet application Iterator roles = permissionRoles.iterator(); while (roles.hasNext()) { - String roleName = (String)roles.next(); + String roleName = (String) roles.next(); Role userRole = roleManager.getRole(roleName); if (userRole != null) { - Permission permission = new PortletPermission(paName + "::*", "view, edit"); + Permission permission = new PortletPermission(paName + + "::*", "view, edit"); if (!permissionManager.permissionExists(permission)) { permissionManager.addPermission(permission); - permissionManager.grantPermission(userRole.getPrincipal(), permission); - } + permissionManager.grantPermission(userRole + .getPrincipal(), permission); + } } } } catch (SecurityException e) { log.error("Error granting default permissions for " + paName, e); - } + } } - + protected void revokeDefaultPermissions(String paName) { try @@ -811,16 +929,17 @@ Iterator roles = permissionRoles.iterator(); while (roles.hasNext()) { - String roleName = (String)roles.next(); + String roleName = (String) roles.next(); Role userRole = roleManager.getRole(roleName); if (userRole != null) { - Permission permission = new PortletPermission(paName + "::*", "view, edit"); + Permission permission = new PortletPermission(paName + + "::*", "view, edit"); if (permissionManager.permissionExists(permission)) { permissionManager.removePermission(permission); - } - + } + } } } @@ -832,75 +951,94 @@ public int getDescriptorChangeMonitorInterval() { - return descriptorChangeMonitorInterval/1000; + return descriptorChangeMonitorInterval / 1000; } - public void setDescriptorChangeMonitorInterval(int descriptorChangeMonitorInterval) + public void setDescriptorChangeMonitorInterval( + int descriptorChangeMonitorInterval) { - this.descriptorChangeMonitorInterval = descriptorChangeMonitorInterval*1000; - } - + this.descriptorChangeMonitorInterval = descriptorChangeMonitorInterval * 1000; + } + private static class DescriptorChangeMonitor extends Thread { + private static class DescriptorChangeMonitorInfo { + private String contextName; + private String contextPath; + private ClassLoader paClassLoader; - private int paType; + + private int paType; + private File paDir; + private File[] descriptors; + private long descriptorModificationTime; + private long extendedDescriptorModificationTime; + private long checksum; + private boolean obsolete; - + /** * holds the number of unsuccessful starts of the monitored PA */ private int unsuccessfulStarts; - + /* - * Constructor only used for looking up the matching registered one in monitorsInfo + * Constructor only used for looking up the matching registered one + * in monitorsInfo */ public DescriptorChangeMonitorInfo(String contextName) { this.contextName = contextName; } - - public DescriptorChangeMonitorInfo(String contextName, String contextPath, ClassLoader paClassLoader, int paType, File paDir, long checksum) + + public DescriptorChangeMonitorInfo(String contextName, + String contextPath, ClassLoader paClassLoader, int paType, + File paDir, long checksum) { this.contextName = contextName; this.contextPath = contextPath; this.paClassLoader = paClassLoader; this.paType = paType; - this.paDir = paDir.isAbsolute() ? paDir : paDir.getAbsoluteFile(); + this.paDir = paDir.isAbsolute() ? paDir : paDir + .getAbsoluteFile(); this.checksum = checksum; - - this.descriptors = new File[] { + + this.descriptors = new File[] + { new File(paDir, PortletApplicationWar.WEB_XML_PATH), new File(paDir, PortletApplicationWar.PORTLET_XML_PATH), - new File(paDir, PortletApplicationWar.EXTENDED_PORTLET_XML_PATH) }; + new File(paDir, + PortletApplicationWar.EXTENDED_PORTLET_XML_PATH)}; descriptorModificationTime = descriptors[1].lastModified(); - extendedDescriptorModificationTime = descriptors[2].lastModified(); + extendedDescriptorModificationTime = descriptors[2] + .lastModified(); } - + public String getContextName() { return contextName; } - + public ClassLoader getPAClassLoader() { return paClassLoader; } - + public int getPortletApplicationType() { return paType; } - + public File getPADir() { return paDir; @@ -910,31 +1048,44 @@ { return checksum; } - + public boolean isChanged() { - if ( !obsolete) + if (!obsolete) { - long newDescriptorModificationTime = descriptors[1].lastModified(); - long newExtendedDescriptorModificationTime = descriptors[2].lastModified(); - if ( descriptorModificationTime != newDescriptorModificationTime || - extendedDescriptorModificationTime != newExtendedDescriptorModificationTime ) + long newDescriptorModificationTime = descriptors[1] + .lastModified(); + long newExtendedDescriptorModificationTime = descriptors[2] + .lastModified(); + if (descriptorModificationTime != newDescriptorModificationTime + || extendedDescriptorModificationTime != newExtendedDescriptorModificationTime) { descriptorModificationTime = newDescriptorModificationTime; extendedDescriptorModificationTime = newExtendedDescriptorModificationTime; - long newChecksum = MultiFileChecksumHelper.getChecksum(descriptors); - if (log.isDebugEnabled()) + long newChecksum = MultiFileChecksumHelper + .getChecksum(descriptors); + if (log.isDebugEnabled()) { - log.debug("checksum check for descriptors for application " + contextName + ": old (" + checksum + ") new (" + newChecksum + ")."); - } - if ( checksum != newChecksum ) + log + .debug("checksum check for descriptors for application " + + contextName + + ": old (" + + checksum + + ") new (" + + newChecksum + ")."); + } + if (checksum != newChecksum) { - if (log.isDebugEnabled()) + if (log.isDebugEnabled()) { - log.debug("portlet descriptors for application " + contextName + " have changed."); - } + log + .debug("portlet descriptors for application " + + contextName + + " have changed."); + } checksum = newChecksum; - // reset this to restart unsuccessful PA start handling for evers PA descriptor change + // reset this to restart unsuccessful PA start + // handling for evers PA descriptor change unsuccessfulStarts = 0; return true; } @@ -942,12 +1093,12 @@ } return false; } - + public void setObsolete() { obsolete = true; } - + public boolean isObsolete() { return obsolete; @@ -957,25 +1108,31 @@ { return unsuccessfulStarts; } - + public void setUnsuccessfulStarts(int unsuccessfulStarts) { this.unsuccessfulStarts = unsuccessfulStarts; } - + public String getContextPath() { return contextPath; } - } + } private PortletApplicationManager pam; + private long interval; + private boolean started = true; + private ArrayList monitorInfos; + private int maxRetriedStarts; - public DescriptorChangeMonitor(ThreadGroup group, String name, PortletApplicationManager pam, long interval, int maxretriedStarts) + public DescriptorChangeMonitor(ThreadGroup group, String name, + PortletApplicationManager pam, long interval, + int maxretriedStarts) { super(group, name); this.pam = pam; @@ -985,7 +1142,7 @@ setDaemon(true); this.maxRetriedStarts = maxretriedStarts; } - + public void run() { try @@ -1011,28 +1168,33 @@ } /** - * notifies a switch variable that exits the watcher's montior loop started in the run() method. + * notifies a switch variable that exits the watcher's montior loop + * started in the run() method. */ public synchronized void safeStop() { started = false; monitorInfos.clear(); } - - public synchronized void monitor(String contextName, String contextPath, ClassLoader paClassLoader, int paType, File paDir, long checksum) + + public synchronized void monitor(String contextName, + String contextPath, ClassLoader paClassLoader, int paType, + File paDir, long checksum) { - monitorInfos.add(new DescriptorChangeMonitorInfo(contextName, contextPath, paClassLoader, paType, paDir, checksum)); + monitorInfos.add(new DescriptorChangeMonitorInfo(contextName, + contextPath, paClassLoader, paType, paDir, checksum)); } - + public synchronized void remove(String contextName) { DescriptorChangeMonitorInfo monitorInfo; - for ( int i = monitorInfos.size()-1; i > -1; i-- ) + for (int i = monitorInfos.size() - 1; i > -1; i--) { - monitorInfo = (DescriptorChangeMonitorInfo)monitorInfos.get(i); + monitorInfo = (DescriptorChangeMonitorInfo) monitorInfos.get(i); if (contextName.equals(monitorInfo.getContextName())) { - // will be removed by checkDescriptorChanges on next iteration + // will be removed by checkDescriptorChanges on next + // iteration monitorInfo.setObsolete(); break; } @@ -1042,102 +1204,145 @@ public synchronized DescriptorChangeMonitorInfo get(String contextName) { DescriptorChangeMonitorInfo monitorInfo; - for ( int i = monitorInfos.size()-1; i > -1; i-- ) + for (int i = monitorInfos.size() - 1; i > -1; i--) { - monitorInfo = (DescriptorChangeMonitorInfo)monitorInfos.get(i); - if (contextName.equals(monitorInfo.getContextName())) - { - return monitorInfo; - } + monitorInfo = (DescriptorChangeMonitorInfo) monitorInfos.get(i); + if (contextName.equals(monitorInfo.getContextName())) { return monitorInfo; } } return null; } - + public boolean isMonitored(String contextName) { - DescriptorChangeMonitorInfo monitorInfo = this.get(contextName); - if (monitorInfo != null && !monitorInfo.isObsolete()) - { - return true; - } + DescriptorChangeMonitorInfo monitorInfo = this.get(contextName); + if (monitorInfo != null && !monitorInfo.isObsolete()) { return true; } return false; } - + private synchronized void checkDescriptorChanges() { int size = monitorInfos.size(); - if (log.isDebugEnabled()) + if (log.isDebugEnabled()) { - log.debug("check for portlet application descriptor changes."); - } - - for (int i = size-1; i > -1; i--) + log.debug("check for portlet application descriptor changes."); + } + + for (int i = size - 1; i > -1; i--) { DescriptorChangeMonitorInfo monitorInfo; - - if ( started ) + + if (started) + { + monitorInfo = (DescriptorChangeMonitorInfo) monitorInfos + .get(i); + if (monitorInfo.isObsolete()) { - monitorInfo = (DescriptorChangeMonitorInfo)monitorInfos.get(i); - if (monitorInfo.isObsolete()) + monitorInfos.remove(i); + } + else + { + try { - monitorInfos.remove(i); - } - else - { - try + int unsuccessfulStarts = monitorInfo + .getUnsuccessfulStarts(); + // try to restart PA if the PA-descriptors have + // change + // OR (if we encountered an exception while starting + // the PA) + // keep on trying to restart PA until + // maxRetriedStarts is reached + // This ensures we finally startup in a clustered + // enviroment, where parallel registration + // of PAs could lead to contraint violation + // eceptions in DB. + // see https://issues.apache.org/jira/browse/JS2-666 + // Note: monitorInfo.isChanged() will reset + // unsuccessfulStarts to 0 if a PA descriptor change + // has been detected (monitorInfo.isChanged() == + // true). + if (monitorInfo.isChanged() + || (unsuccessfulStarts > 0 && unsuccessfulStarts <= maxRetriedStarts)) { - int unsuccessfulStarts = monitorInfo.getUnsuccessfulStarts(); - // try to restart PA if the PA-descriptors have change - // OR (if we encountered an exception while starting the PA) - // keep on trying to restart PA until maxRetriedStarts is reached - // This ensures we finally startup in a clustered enviroment, where parallel registration - // of PAs could lead to contraint violation eceptions in DB. - // see https://issues.apache.org/jira/browse/JS2-666 - // Note: monitorInfo.isChanged() will reset unsuccessfulStarts to 0 if a PA descriptor change - // has been detected (monitorInfo.isChanged() == true). - if (monitorInfo.isChanged() || (unsuccessfulStarts > 0 && unsuccessfulStarts <= maxRetriedStarts)) + try { - try + pam + .startPA( + monitorInfo + .getContextName(), + monitorInfo + .getContextPath(), + new DirectoryHelper( + monitorInfo + .getPADir()), + monitorInfo + .getPAClassLoader(), + monitorInfo + .getPortletApplicationType(), + monitorInfo.getChecksum()); + // great! we have a successful start. set + // unsuccessful starts to 0 + monitorInfo.setUnsuccessfulStarts(0); + } + catch (Exception e) + { + if (monitorInfo.isChanged()) { - pam.startPA(monitorInfo.getContextName(), monitorInfo.getContextPath(), new DirectoryHelper(monitorInfo.getPADir()), - monitorInfo.getPAClassLoader(), monitorInfo.getPortletApplicationType(), monitorInfo.getChecksum()); - // great! we have a successful start. set unsuccessful starts to 0 - monitorInfo.setUnsuccessfulStarts(0); + log + .error( + "Failed to restart PortletApplication " + + monitorInfo + .getContextName(), + e); } - catch (Exception e) + else if (log.isWarnEnabled()) { - if (monitorInfo.isChanged()) - { - log.error("Failed to restart PortletApplication "+monitorInfo.getContextName(),e); - } - else if (log.isWarnEnabled()) - { - log.warn("Failed to restart PortletApplication "+monitorInfo.getContextName(),e); - } - // we encountered an error while starting the PA - // this could result from clustered environments problems (see above) - // increase unsuccessfulStarts until the maxRetriedStarts is reached - monitorInfo.setUnsuccessfulStarts(unsuccessfulStarts + 1); - if (log.isDebugEnabled()) - { - log.debug("Number of unsuccessful PA starts is " + monitorInfo.getUnsuccessfulStarts() + "."); - } - if (monitorInfo.getUnsuccessfulStarts() > maxRetriedStarts) - { - log.error("Max number of retries (" + maxRetriedStarts +") reached. Ignoring Monitor for " + monitorInfo.getContextName()); - } + log + .warn( + "Failed to restart PortletApplication " + + monitorInfo + .getContextName(), + e); } + // we encountered an error while starting + // the PA + // this could result from clustered + // environments problems (see above) + // increase unsuccessfulStarts until the + // maxRetriedStarts is reached + monitorInfo + .setUnsuccessfulStarts(unsuccessfulStarts + 1); + if (log.isDebugEnabled()) + { + log + .debug("Number of unsuccessful PA starts is " + + monitorInfo + .getUnsuccessfulStarts() + + "."); + } + if (monitorInfo.getUnsuccessfulStarts() > maxRetriedStarts) + { + log + .error("Max number of retries (" + + maxRetriedStarts + + ") reached. Ignoring Monitor for " + + monitorInfo + .getContextName()); + } } } - catch (Exception e) - { - // ignore filesystem and/or descriptor errors, maybe next time round they'll be fixed again - log.error("Descriptor Change check failure for PortletApplication "+monitorInfo.getContextName(),e); - } } + catch (Exception e) + { + // ignore filesystem and/or descriptor errors, maybe + // next time round they'll be fixed again + log.error( + "Descriptor Change check failure for PortletApplication " + + monitorInfo.getContextName(), e); + } } } + } } } @@ -1149,5 +1354,5 @@ public int getMaxRetriedStarts() { return maxRetriedStarts; - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/VersionedPortletApplicationManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/VersionedPortletApplicationManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/VersionedPortletApplicationManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -38,42 +38,46 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * contributor license agreements. See the NOTICE file distributed with this + * work for additional information regarding copyright ownership. The ASF + * licenses this file to You under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. */ +public class VersionedPortletApplicationManager extends + PortletApplicationManager implements PortletApplicationManagement +{ + private static final Log log = LogFactory.getLog("deployment"); -public class VersionedPortletApplicationManager extends PortletApplicationManager implements PortletApplicationManagement -{ - private static final Log log = LogFactory.getLog("deployment"); - - public VersionedPortletApplicationManager(PortletFactory portletFactory, PortletRegistry registry, - PortletEntityAccessComponent entityAccess, PortletWindowAccessor windowAccess, - PermissionManager permissionManager, SearchEngine searchEngine, RoleManager roleManager, - List permissionRoles, /* node manager, */ String appRoot) + public VersionedPortletApplicationManager(PortletFactory portletFactory, + PortletRegistry registry, + PortletEntityAccessComponent entityAccess, + PortletWindowAccessor windowAccess, + PermissionManager permissionManager, SearchEngine searchEngine, + RoleManager roleManager, List permissionRoles, /* node manager, */ + String appRoot) { - super(portletFactory, registry, entityAccess, windowAccess, permissionManager, - searchEngine, roleManager, permissionRoles, null, appRoot); - + super(portletFactory, registry, entityAccess, windowAccess, + permissionManager, searchEngine, roleManager, permissionRoles, + null, appRoot); + } - + public boolean isStarted() { return started; } - + public void start() { started = true; @@ -83,41 +87,48 @@ { started = false; } - + // override to implement versioning logic - protected void startPA(String contextName, String contextPath, FileSystemHelper warStruct, - ClassLoader paClassLoader, int paType, long checksum) - throws RegistryException + protected void startPA(String contextName, String contextPath, + FileSystemHelper warStruct, ClassLoader paClassLoader, int paType, + long checksum) throws RegistryException { PortletApplicationWar paWar = null; try { - paWar = new PortletApplicationWar(warStruct, contextName, contextPath, checksum); + paWar = new PortletApplicationWar(warStruct, contextName, + contextPath, checksum); try { if (paClassLoader == null) { - paClassLoader = paWar.createClassloader(getClass().getClassLoader()); + paClassLoader = paWar.createClassloader(getClass() + .getClassLoader()); } } catch (IOException e) { String msg = "Invalid PA WAR for " + contextName; log.error(msg, e); - if ( paClassLoader == null ) + if (paClassLoader == null) { - // nothing to be done about it anymore: this pa is beyond repair :( + // nothing to be done about it anymore: this pa is beyond + // repair :( throw new RegistryException(e); } - //register = false; + // register = false; } - - MutablePortletApplication regPA = registry.getPortletApplication(contextName); + + MutablePortletApplication regPA = registry + .getPortletApplication(contextName); MutablePortletApplication newPA = paWar.createPortletApp(); if (regPA == null) { - System.out.println("**** New portlet app found - registration required..." + contextName); - regPA = this.registerPortletApplication(paWar, null, paType, paClassLoader); + System.out + .println("**** New portlet app found - registration required..." + + contextName); + regPA = this.registerPortletApplication(paWar, null, paType, + paClassLoader); } else { @@ -127,12 +138,17 @@ System.out.print(", New version is " + newVersion); if (newVersion.compareTo(regVersion) > 0) { - System.out.println(" - **** New Version is greater: registration required... " + contextName); - regPA = this.registerPortletApplication(paWar, regPA, paType, paClassLoader); + System.out + .println(" - **** New Version is greater: registration required... " + + contextName); + regPA = this.registerPortletApplication(paWar, regPA, + paType, paClassLoader); } else { - System.out.println(" - New Version is NOT greater: registration not required ... " + contextName); + System.out + .println(" - New Version is NOT greater: registration not required ... " + + contextName); } } if (portletFactory.isPortletApplicationRegistered(regPA)) @@ -143,12 +159,12 @@ } catch (Exception e) { - String msg = "Error starting portlet application " + contextName; + String msg = "Error starting portlet application " + contextName; log.error(msg, e); throw new RegistryException(msg, e); } } - + protected String getVersion(MutablePortletApplication pa) { String version = ""; @@ -158,7 +174,7 @@ Iterator it = versionList.iterator(); if (it.hasNext()) { - LocalizedField field = (LocalizedField)it.next(); + LocalizedField field = (LocalizedField) it.next(); version = field.getValue(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/JetspeedServiceRule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/JetspeedServiceRule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/JetspeedServiceRule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,7 +20,6 @@ import org.apache.jetspeed.om.common.JetspeedServiceReference; import org.apache.jetspeed.om.common.portlet.MutablePortletApplication; - /** * This class helps load the jetspeed portlet extension service declarations. * @@ -28,6 +27,7 @@ */ public class JetspeedServiceRule extends Rule { + private MutablePortletApplication app; public JetspeedServiceRule(MutablePortletApplication app) @@ -37,7 +37,8 @@ public void end(String namespace, String name) throws Exception { - JetspeedServiceReference service = (JetspeedServiceReference) digester.peek(0); + JetspeedServiceReference service = (JetspeedServiceReference) digester + .peek(0); app.addJetspeedService(service); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/JetspeedServicesRuleSet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/JetspeedServicesRuleSet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/JetspeedServicesRuleSet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,6 +28,7 @@ */ public class JetspeedServicesRuleSet extends RuleSetBase { + private MutablePortletApplication app; public JetspeedServicesRuleSet(MutablePortletApplication app) @@ -39,12 +40,15 @@ * @see org.apache.commons.digester.RuleSet#addRuleInstances(org.apache.commons.digester.Digester) */ public void addRuleInstances(Digester digester) - { - digester.addObjectCreate("portlet-app/services/service", JetspeedServiceReferenceImpl.class); - digester.addSetProperties("portlet-app/services/service", "name", "name"); - - digester.addRule("portlet-app/services/service", new JetspeedServiceRule(app)); - + { + digester.addObjectCreate("portlet-app/services/service", + JetspeedServiceReferenceImpl.class); + digester.addSetProperties("portlet-app/services/service", "name", + "name"); + + digester.addRule("portlet-app/services/service", + new JetspeedServiceRule(app)); + } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/LocalizedFieldRule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/LocalizedFieldRule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/LocalizedFieldRule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,15 +19,12 @@ import java.util.Locale; import org.apache.commons.digester.Rule; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.apache.jetspeed.om.common.GenericMetadata; import org.apache.jetspeed.om.common.LocalizedField; import org.apache.jetspeed.om.common.portlet.MutablePortletApplication; import org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite; - import org.xml.sax.Attributes; /** @@ -38,8 +35,10 @@ */ public class LocalizedFieldRule extends Rule { - protected final static Log log = LogFactory.getLog(LocalizedFieldRule.class); + protected final static Log log = LogFactory + .getLog(LocalizedFieldRule.class); + /** * Handle the beginning of an XML element. * @@ -48,12 +47,13 @@ * @exception Exception * if a processing error occurs */ - public void begin(String namespace, String name, Attributes attributes) throws Exception + public void begin(String namespace, String name, Attributes attributes) + throws Exception { if (digester.getLogger().isDebugEnabled()) digester.getLogger().debug("Setting localized field " + name); - + Object obj = digester.peek(); if (null == obj) { @@ -102,7 +102,8 @@ } } - public void body(String namespace, String name, String text) throws Exception + public void body(String namespace, String name, String text) + throws Exception { LocalizedField child = (LocalizedField) digester.peek(0); if (child != null) @@ -134,7 +135,7 @@ if (null != metadata) { metadata.addField(child); - } + } } } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/MetadataRuleSet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/MetadataRuleSet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/MetadataRuleSet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,12 +21,13 @@ /** * RuleSet for adding metadata - * + * * @author Jeremy Ford * @version $Id: MetadataRuleSet.java 516448 2007-03-09 16:25:47Z ate $ */ public class MetadataRuleSet extends RuleSetBase { + private String prefix; /** @@ -43,7 +44,7 @@ public void addRuleInstances(Digester digester) { LocalizedFieldRule fieldRule = new LocalizedFieldRule(); - + digester.addRule(prefix + "title", fieldRule); digester.addRule(prefix + "contributor", fieldRule); digester.addRule(prefix + "creator", fieldRule); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/PortletRule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/PortletRule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/PortletRule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,6 +30,7 @@ */ public class PortletRule extends Rule { + protected final static Log log = LogFactory.getLog(PortletRule.class); private MutablePortletApplication app; @@ -39,9 +40,11 @@ this.app = app; } - public void body(String namespace, String name, String text) throws Exception + public void body(String namespace, String name, String text) + throws Exception { - PortletDefinitionComposite def = (PortletDefinitionComposite) app.getPortletDefinitionByName(text); + PortletDefinitionComposite def = (PortletDefinitionComposite) app + .getPortletDefinitionByName(text); digester.push(def); - } + } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/SecurityConstraintRefRule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/SecurityConstraintRefRule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/SecurityConstraintRefRule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,24 +28,28 @@ */ public class SecurityConstraintRefRule extends Rule { + private MutablePortletApplication app = null; public SecurityConstraintRefRule(MutablePortletApplication app) { this.app = app; } - - public void body(String namespace, String name, String text) throws Exception + + public void body(String namespace, String name, String text) + throws Exception { Object obj = digester.peek(); if (obj instanceof MutablePortletApplication) { - ((MutablePortletApplication) obj).setJetspeedSecurityConstraint(text); + ((MutablePortletApplication) obj) + .setJetspeedSecurityConstraint(text); } else if (obj instanceof PortletDefinitionComposite) { - ((PortletDefinitionComposite) obj).setJetspeedSecurityConstraint(text); + ((PortletDefinitionComposite) obj) + .setJetspeedSecurityConstraint(text); } } - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/UserAttributeRefRule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/UserAttributeRefRule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/UserAttributeRefRule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,10 +17,8 @@ package org.apache.jetspeed.tools.pamanager.rules; import org.apache.commons.digester.Rule; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.apache.jetspeed.om.common.UserAttributeRef; import org.apache.jetspeed.om.common.portlet.MutablePortletApplication; @@ -31,8 +29,10 @@ */ public class UserAttributeRefRule extends Rule { - protected final static Log log = LogFactory.getLog(UserAttributeRefRule.class); + protected final static Log log = LogFactory + .getLog(UserAttributeRefRule.class); + private MutablePortletApplication app; public UserAttributeRefRule(MutablePortletApplication app) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/UserAttributeRefRuleSet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/UserAttributeRefRuleSet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/rules/UserAttributeRefRuleSet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,10 +18,8 @@ import org.apache.commons.digester.Digester; import org.apache.commons.digester.RuleSetBase; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.apache.jetspeed.om.common.portlet.MutablePortletApplication; import org.apache.jetspeed.om.impl.UserAttributeRefImpl; @@ -32,8 +30,10 @@ */ public class UserAttributeRefRuleSet extends RuleSetBase { - protected final static Log log = LogFactory.getLog(UserAttributeRefRuleSet.class); + protected final static Log log = LogFactory + .getLog(UserAttributeRefRuleSet.class); + private MutablePortletApplication app; public UserAttributeRefRuleSet(MutablePortletApplication app) @@ -45,11 +45,15 @@ * @see org.apache.commons.digester.RuleSet#addRuleInstances(org.apache.commons.digester.Digester) */ public void addRuleInstances(Digester digester) - { - digester.addObjectCreate("portlet-app/user-attribute-ref", UserAttributeRefImpl.class); - digester.addBeanPropertySetter("portlet-app/user-attribute-ref/name", "name"); - digester.addBeanPropertySetter("portlet-app/user-attribute-ref/name-link", "nameLink"); - digester.addRule("portlet-app/user-attribute-ref", new UserAttributeRefRule(app)); + { + digester.addObjectCreate("portlet-app/user-attribute-ref", + UserAttributeRefImpl.class); + digester.addBeanPropertySetter("portlet-app/user-attribute-ref/name", + "name"); + digester.addBeanPropertySetter( + "portlet-app/user-attribute-ref/name-link", "nameLink"); + digester.addRule("portlet-app/user-attribute-ref", + new UserAttributeRefRule(app)); } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/GlassFishManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/GlassFishManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/GlassFishManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -3,86 +3,116 @@ import java.io.IOException; import java.io.InputStream; -public class GlassFishManager implements ApplicationServerManager { +public class GlassFishManager implements ApplicationServerManager +{ - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#start(java.lang.String) */ public ApplicationServerManagerResult start(String appPath) - throws IOException { + throws IOException + { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#stop(java.lang.String) */ public ApplicationServerManagerResult stop(String appPath) - throws IOException { + throws IOException + { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#reload(java.lang.String) */ public ApplicationServerManagerResult reload(String appPath) - throws IOException { + throws IOException + { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#undeploy(java.lang.String) */ public ApplicationServerManagerResult undeploy(String appPath) - throws IOException { + throws IOException + { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) - * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#deploy(java.lang.String, java.io.InputStream, int) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#deploy(java.lang.String, + * java.io.InputStream, int) */ public ApplicationServerManagerResult deploy(String appPath, - InputStream is, int size) throws IOException { + InputStream is, int size) throws IOException + { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#getHostPort() */ - public int getHostPort() { + public int getHostPort() + { // TODO Auto-generated method stub return 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#getHostUrl() */ - public String getHostUrl() { + public String getHostUrl() + { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#isConnected() */ - public boolean isConnected() { + public boolean isConnected() + { // TODO Auto-generated method stub return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see groovy.swing.impl.Startable#start() */ - public void start() { + public void start() + { // TODO Auto-generated method stub } - public String getAppServerTarget(String appName) { + public String getAppServerTarget(String appName) + { return appName + ".war"; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/JBossManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/JBossManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/JBossManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,60 +21,77 @@ /** * JBoss application server management - * + * * @author David Sean Taylor * @version $Id: JBossManager.java 516881 2007-03-11 10:34:21Z ate $ */ public class JBossManager implements ApplicationServerManager { - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#start(java.lang.String) */ - public ApplicationServerManagerResult start(String appPath) throws IOException + public ApplicationServerManagerResult start(String appPath) + throws IOException { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#stop(java.lang.String) */ - public ApplicationServerManagerResult stop(String appPath) throws IOException + public ApplicationServerManagerResult stop(String appPath) + throws IOException { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#reload(java.lang.String) */ - public ApplicationServerManagerResult reload(String appPath) throws IOException + public ApplicationServerManagerResult reload(String appPath) + throws IOException { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#undeploy(java.lang.String) */ - public ApplicationServerManagerResult undeploy(String appPath) throws IOException + public ApplicationServerManagerResult undeploy(String appPath) + throws IOException { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) - * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#deploy(java.lang.String, java.io.InputStream, int) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#deploy(java.lang.String, + * java.io.InputStream, int) */ - public ApplicationServerManagerResult deploy(String appPath, InputStream is, int size) - throws IOException + public ApplicationServerManagerResult deploy(String appPath, + InputStream is, int size) throws IOException { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#getHostPort() */ public int getHostPort() @@ -83,7 +100,9 @@ return 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#getHostUrl() */ public String getHostUrl() @@ -92,7 +111,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#isConnected() */ public boolean isConnected() @@ -101,7 +122,9 @@ return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see groovy.swing.impl.Startable#start() */ public void start() @@ -113,5 +136,5 @@ public String getAppServerTarget(String appName) { return appName + ".war"; - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/TomcatManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/TomcatManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/TomcatManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -40,24 +40,33 @@ * * @author Scott T. Weaver * @version $Id: TomcatManager.java 517719 2007-03-13 15:05:48Z ate $ - * + * */ public class TomcatManager implements ApplicationServerManager { + private static final String DEFAULT_MANAGER_APP_PATH = "/manager"; + protected static final Log log = LogFactory.getLog("deployment"); private String hostUrl; + private int hostPort; + private String userName; + private String password; - - + private String managerAppPath = DEFAULT_MANAGER_APP_PATH; + private String stopPath = managerAppPath + "/stop"; + private String startPath = managerAppPath + "/start"; + private String deployPath = managerAppPath + "/deploy"; + private String undeployPath = managerAppPath + "/undeploy"; + private HttpClient client; private HttpMethod start; @@ -68,40 +77,45 @@ private PutMethod deploy; - public TomcatManager(String catalinaBase, String catalinaEngine, String hostName, int hostPort, String userName, String password) throws IOException + public TomcatManager(String catalinaBase, String catalinaEngine, + String hostName, int hostPort, String userName, String password) + throws IOException { super(); - - if ( !catalinaBase.endsWith("/") ) + + if (!catalinaBase.endsWith("/")) { } else { - } + } this.hostUrl = hostName; this.hostPort = hostPort; this.userName = userName; this.password = password; } - + private ApplicationServerManagerResult parseResult(String responseBody) { - if ( responseBody.startsWith("OK - ")) + if (responseBody.startsWith("OK - ")) { - return new ApplicationServerManagerResult(true, responseBody.substring(5), responseBody); + return new ApplicationServerManagerResult(true, responseBody + .substring(5), responseBody); } - else if ( responseBody.startsWith("FAIL - ")) + else if (responseBody.startsWith("FAIL - ")) { - return new ApplicationServerManagerResult(false, responseBody.substring(7), responseBody); + return new ApplicationServerManagerResult(false, responseBody + .substring(7), responseBody); } else { - return new ApplicationServerManagerResult(false, responseBody, responseBody); + return new ApplicationServerManagerResult(false, responseBody, + responseBody); } } - public void start() - { + public void start() + { client = new HttpClient(); HostConfiguration hostConfig = new HostConfiguration(); @@ -110,7 +124,8 @@ client.setHostConfiguration(hostConfig); // Fix for non-buffereing large WAR files during deploy client.getState().setAuthenticationPreemptive(true); - client.getState().setCredentials(null, hostUrl, new UsernamePasswordCredentials(userName, password)); + client.getState().setCredentials(null, hostUrl, + new UsernamePasswordCredentials(userName, password)); start = new GetMethod(startPath); stop = new GetMethod(stopPath); @@ -118,7 +133,8 @@ deploy = new PutMethod(deployPath); } - public ApplicationServerManagerResult start(String appPath) throws IOException + public ApplicationServerManagerResult start(String appPath) + throws IOException { try { @@ -133,7 +149,8 @@ } } - public ApplicationServerManagerResult stop(String appPath) throws IOException + public ApplicationServerManagerResult stop(String appPath) + throws IOException { try { @@ -148,11 +165,12 @@ } } - public ApplicationServerManagerResult reload(String appPath) throws IOException + public ApplicationServerManagerResult reload(String appPath) + throws IOException { try { - // reload.setQueryString(buildPathQueryArgs(appPath)); + // reload.setQueryString(buildPathQueryArgs(appPath)); // This is the only way to get changes made to web.xml to // be picked up, reload DOES NOT reload the web.xml stop(appPath); @@ -161,7 +179,7 @@ } catch (InterruptedException e) { - return parseResult("FAIL - "+e.toString()); + return parseResult("FAIL - " + e.toString()); } finally { @@ -172,7 +190,8 @@ } } - public ApplicationServerManagerResult undeploy(String appPath) throws IOException + public ApplicationServerManagerResult undeploy(String appPath) + throws IOException { try { @@ -187,13 +206,14 @@ } } - public ApplicationServerManagerResult deploy(String appPath, InputStream is, int size) throws IOException + public ApplicationServerManagerResult deploy(String appPath, + InputStream is, int size) throws IOException { try { deploy.setQueryString(buildPathQueryArgs(appPath)); - //deploy.setRequestContentLength(PutMethod.CONTENT_LENGTH_CHUNKED); + // deploy.setRequestContentLength(PutMethod.CONTENT_LENGTH_CHUNKED); if (size != -1) { @@ -217,20 +237,23 @@ { appPath = "/" + appPath; } - return new NameValuePair[] { new NameValuePair("path", appPath)}; + return new NameValuePair[] + {new NameValuePair("path", appPath)}; } - protected NameValuePair[] buildWarQueryArgs(String warPath, String appPath) throws MalformedURLException + protected NameValuePair[] buildWarQueryArgs(String warPath, String appPath) + throws MalformedURLException { - return new NameValuePair[] { - new NameValuePair("war", new File(warPath).toURL().toString()), + return new NameValuePair[] + {new NameValuePair("war", new File(warPath).toURL().toString()), new NameValuePair("path", appPath)}; } - protected NameValuePair[] buildConfigQueryArgs(String configPath, String appPath) throws MalformedURLException + protected NameValuePair[] buildConfigQueryArgs(String configPath, + String appPath) throws MalformedURLException { - return new NameValuePair[] { - new NameValuePair("config", new File(configPath).toURL().toString()), + return new NameValuePair[] + {new NameValuePair("config", new File(configPath).toURL().toString()), new NameValuePair("path", appPath)}; } @@ -254,7 +277,7 @@ *

        * isConnected *

        - * + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#isConnected() * @return */ @@ -294,18 +317,19 @@ } } } + /** *

        * stop *

        * * @see org.picocontainer.Startable#stop() - * + * */ public void stop() { } - + public String getAppServerTarget(String appName) { return appName; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/WeblogicManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/WeblogicManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/WeblogicManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,60 +21,77 @@ /** * Weblogic application server management - * + * * @author David Sean Taylor * @version $Id: WeblogicManager.java 516881 2007-03-11 10:34:21Z ate $ */ public class WeblogicManager implements ApplicationServerManager { - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#start(java.lang.String) */ - public ApplicationServerManagerResult start(String appPath) throws IOException + public ApplicationServerManagerResult start(String appPath) + throws IOException { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#stop(java.lang.String) */ - public ApplicationServerManagerResult stop(String appPath) throws IOException + public ApplicationServerManagerResult stop(String appPath) + throws IOException { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#reload(java.lang.String) */ - public ApplicationServerManagerResult reload(String appPath) throws IOException + public ApplicationServerManagerResult reload(String appPath) + throws IOException { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#undeploy(java.lang.String) */ - public ApplicationServerManagerResult undeploy(String appPath) throws IOException + public ApplicationServerManagerResult undeploy(String appPath) + throws IOException { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) - * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#deploy(java.lang.String, java.io.InputStream, int) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#deploy(java.lang.String, + * java.io.InputStream, int) */ - public ApplicationServerManagerResult deploy(String appPath, InputStream is, int size) - throws IOException + public ApplicationServerManagerResult deploy(String appPath, + InputStream is, int size) throws IOException { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#getHostPort() */ public int getHostPort() @@ -83,7 +100,9 @@ return 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#getHostUrl() */ public String getHostUrl() @@ -92,7 +111,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#isConnected() */ public boolean isConnected() @@ -101,7 +122,9 @@ return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.tools.pamanager.servletcontainer.ApplicationServerManager#getAppServerTarget(java.lang.String) */ public String getAppServerTarget(String appName) @@ -109,7 +132,9 @@ return appName; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.picocontainer.Startable#start() */ public void start() @@ -118,7 +143,9 @@ } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.picocontainer.Startable#stop() */ public void stop() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/registration/RegistrationTool.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/registration/RegistrationTool.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/tools/registration/RegistrationTool.java 2008-05-16 01:54:54 UTC (rev 940) @@ -40,52 +40,68 @@ *

        * * @author Scott T. Weaver - * @version $Id: PersistenceBrokerPortletRegistry.java 225622 2005-07-27 20:39:14Z weaver $ - * + * @version $Id: PersistenceBrokerPortletRegistry.java 225622 2005-07-27 + * 20:39:14Z weaver $ + * */ -public class RegistrationTool +public class RegistrationTool { + private PortletRegistry registry; - + public static void main(String args[]) { - String fileName = System.getProperty("org.apache.jetspeed.portletregistry.configuration", "registration.properties"); + String fileName = System.getProperty( + "org.apache.jetspeed.portletregistry.configuration", + "registration.properties"); PropertiesConfiguration configuration = new PropertiesConfiguration(); try { - File appRootDir = new File("./src/webapp"); - System.setProperty(JetspeedEngineConstants.APPLICATION_ROOT_KEY, appRootDir.getAbsolutePath()); - configuration.load(fileName); - String [] bootAssemblies = configuration.getStringArray("boot.assemblies"); - String [] assemblies = configuration.getStringArray("assemblies"); - ClassPathXmlApplicationContext ctx; - + File appRootDir = new File("./src/webapp"); + System.setProperty(JetspeedEngineConstants.APPLICATION_ROOT_KEY, + appRootDir.getAbsolutePath()); + configuration.load(fileName); + String[] bootAssemblies = configuration + .getStringArray("boot.assemblies"); + String[] assemblies = configuration.getStringArray("assemblies"); + ClassPathXmlApplicationContext ctx; + if (bootAssemblies != null) { - ApplicationContext bootContext = new ClassPathXmlApplicationContext(bootAssemblies, true); - ctx = new ClassPathXmlApplicationContext(assemblies, true, bootContext); + ApplicationContext bootContext = new ClassPathXmlApplicationContext( + bootAssemblies, true); + ctx = new ClassPathXmlApplicationContext(assemblies, true, + bootContext); } else { ctx = new ClassPathXmlApplicationContext(assemblies, true); } - - boolean overwriteApps = configuration.getBoolean("overwrite.apps", true); - String registryBean = configuration.getString("registry.component", ""); + + boolean overwriteApps = configuration.getBoolean("overwrite.apps", + true); + String registryBean = configuration.getString("registry.component", + ""); String[] appNames = configuration.getStringArray("apps"); - String[] appDescriptors = configuration.getStringArray("descriptors"); - String[] webappDescriptors = configuration.getStringArray("webapp.descriptors"); - String[] extendedDescriptors = configuration.getStringArray("extended.descriptors"); - PortletRegistry registry = (PortletRegistry)ctx.getBean(registryBean); - RegistrationTool tool = new RegistrationTool(registry, overwriteApps); - - for (int ix=0; ix < appNames.length; ix++) + String[] appDescriptors = configuration + .getStringArray("descriptors"); + String[] webappDescriptors = configuration + .getStringArray("webapp.descriptors"); + String[] extendedDescriptors = configuration + .getStringArray("extended.descriptors"); + PortletRegistry registry = (PortletRegistry) ctx + .getBean(registryBean); + RegistrationTool tool = new RegistrationTool(registry, + overwriteApps); + + for (int ix = 0; ix < appNames.length; ix++) { if (overwriteApps) { tool.unregister(appNames[ix]); } - tool.register(appNames[ix], appDescriptors[ix], webappDescriptors[ix], extendedDescriptors[ix]); + tool.register(appNames[ix], appDescriptors[ix], + webappDescriptors[ix], extendedDescriptors[ix]); } } catch (Exception e) @@ -93,16 +109,15 @@ System.err.println("Failed to import: " + e); e.printStackTrace(); } - + } - + public RegistrationTool(PortletRegistry registry, boolean overwriteApps) { this.registry = registry; } - - public void unregister(String appName) - throws Exception + + public void unregister(String appName) throws Exception { if (registry.portletApplicationExists(appName)) { @@ -113,17 +128,21 @@ } } } - - public void register(String appName, String appDescriptor, String webappDescriptor, String extendedDescriptor) - throws Exception + + public void register(String appName, String appDescriptor, + String webappDescriptor, String extendedDescriptor) + throws Exception { - WebApplicationDescriptor wad = new WebApplicationDescriptor(new FileReader(webappDescriptor), "/" + appName); + WebApplicationDescriptor wad = new WebApplicationDescriptor( + new FileReader(webappDescriptor), "/" + appName); MutableWebApplication webapp = wad.createWebApplication(); - PortletApplicationDescriptor pad = new PortletApplicationDescriptor(new FileReader(appDescriptor), appName); - MutablePortletApplication app = pad.createPortletApplication(); + PortletApplicationDescriptor pad = new PortletApplicationDescriptor( + new FileReader(appDescriptor), appName); + MutablePortletApplication app = pad.createPortletApplication(); app.setWebApplicationDefinition(webapp); - ExtendedPortletMetadata extMetaData = new ExtendedPortletMetadata(new FileReader(extendedDescriptor), app); - extMetaData.load(); + ExtendedPortletMetadata extMetaData = new ExtendedPortletMetadata( + new FileReader(extendedDescriptor), app); + extMetaData.load(); registry.registerPortletApplication(app); } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/AbstractUserInfoManagerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/AbstractUserInfoManagerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/AbstractUserInfoManagerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.userinfo.impl; import java.util.ArrayList; @@ -27,17 +27,20 @@ import org.apache.jetspeed.om.impl.UserAttributeRefImpl; /** - *

        Common user info management support + *

        + * Common user info management support *

        * * @author David Le Strat - * @version $Id: AbstractUserInfoManagerImpl.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: AbstractUserInfoManagerImpl.java 516448 2007-03-09 16:25:47Z + * ate $ */ public abstract class AbstractUserInfoManagerImpl { + /** Logger */ private static final Log log = LogFactory.getLog(UserInfoManagerImpl.class); - + /** *

        * Return the linked attributes mapping portlet user attributes to portal @@ -51,7 +54,8 @@ * reference. * @return The collection of linked attributes. */ - protected Collection mapLinkedUserAttributes(Collection userAttributes, Collection userAttributeRefs) + protected Collection mapLinkedUserAttributes(Collection userAttributes, + Collection userAttributeRefs) { Collection linkedUserAttributes = new ArrayList(); if ((null != userAttributeRefs) && (userAttributeRefs.size() > 0)) @@ -59,21 +63,29 @@ Iterator attrIter = userAttributes.iterator(); while (attrIter.hasNext()) { - UserAttribute currentAttribute = (UserAttribute) attrIter.next(); + UserAttribute currentAttribute = (UserAttribute) attrIter + .next(); boolean linkedAttribute = false; if (null != currentAttribute) { Iterator attrRefsIter = userAttributeRefs.iterator(); while (attrRefsIter.hasNext()) { - UserAttributeRef currentAttributeRef = (UserAttributeRef) attrRefsIter.next(); + UserAttributeRef currentAttributeRef = (UserAttributeRef) attrRefsIter + .next(); if (null != currentAttributeRef) { - if ((currentAttribute.getName()).equals(currentAttributeRef.getNameLink())) + if ((currentAttribute.getName()) + .equals(currentAttributeRef.getNameLink())) { if (log.isDebugEnabled()) - log.debug("Linking user attribute ref: [[name, " + currentAttribute.getName() - + "], [linked name, " + currentAttributeRef.getName() + "]]"); + log + .debug("Linking user attribute ref: [[name, " + + currentAttribute + .getName() + + "], [linked name, " + + currentAttributeRef + .getName() + "]]"); linkedUserAttributes.add(currentAttributeRef); linkedAttribute = true; } @@ -82,7 +94,8 @@ } if (!linkedAttribute) { - linkedUserAttributes.add(new UserAttributeRefImpl(currentAttribute)); + linkedUserAttributes.add(new UserAttributeRefImpl( + currentAttribute)); } } } @@ -91,8 +104,10 @@ Iterator attrIter = userAttributes.iterator(); while (attrIter.hasNext()) { - UserAttribute currentAttribute = (UserAttribute) attrIter.next(); - linkedUserAttributes.add(new UserAttributeRefImpl(currentAttribute)); + UserAttribute currentAttribute = (UserAttribute) attrIter + .next(); + linkedUserAttributes.add(new UserAttributeRefImpl( + currentAttribute)); } } return linkedUserAttributes; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/MultiSourceUserInfoManagerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/MultiSourceUserInfoManagerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/MultiSourceUserInfoManagerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,12 +33,11 @@ import org.apache.jetspeed.userinfo.UserAttributeRetrievalException; import org.apache.jetspeed.userinfo.UserAttributeSource; import org.apache.jetspeed.userinfo.UserInfoManager; -import org.apache.jetspeed.userinfo.impl.AbstractUserInfoManagerImpl; import org.apache.pluto.om.common.ObjectID; /** - * Multisource User Information manager - * One or more sources are assembled in Spring configuration and setter injected + * Multisource User Information manager One or more sources are assembled in + * Spring configuration and setter injected * * @author Keith Garry Boyce * @author David Sean Taylor @@ -55,7 +54,7 @@ private List sources; private PortletRegistry portletRegistry; - + /* * (non-Javadoc) * @@ -71,7 +70,7 @@ Subject subject = context.getSubject(); MutablePortletApplication pa = portletRegistry .getPortletApplication(oid); -//System.out.println("*** PA = " + pa); + // System.out.println("*** PA = " + pa); if (null == pa) { log.debug(PortletRequest.USER_INFO + " is set to null"); @@ -91,10 +90,11 @@ userInfoMap.putAll(sourceMap); } return userInfoMap; - } catch (UserAttributeRetrievalException e) + } + catch (UserAttributeRetrievalException e) { // Until external api is changed return - e.printStackTrace(); + e.printStackTrace(); return null; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/UserInfoManagerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/UserInfoManagerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/UserInfoManagerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -51,7 +51,8 @@ * @author David Le Strat * @version $Id: UserInfoManagerImpl.java 516448 2007-03-09 16:25:47Z ate $ */ -public class UserInfoManagerImpl extends AbstractUserInfoManagerImpl implements UserInfoManager +public class UserInfoManagerImpl extends AbstractUserInfoManagerImpl implements + UserInfoManager { /** Logger */ @@ -79,8 +80,10 @@ * Constructor providing access to the {@link UserManager}. *

        * - * @param userMgr The user manager. - * @param registry The portlet registry component. + * @param userMgr + * The user manager. + * @param registry + * The portlet registry component. */ public UserInfoManagerImpl(UserManager userMgr, PortletRegistry registry) { @@ -96,12 +99,16 @@ * which property set to use for user information. *

        * - * @param userMgr The user manager. - * @param registry The portlet registry component. - * @param userInfoPropertySet The user information property set. - * + * @param userMgr + * The user manager. + * @param registry + * The portlet registry component. + * @param userInfoPropertySet + * The user information property set. + * */ - public UserInfoManagerImpl(UserManager userMgr, PortletRegistry registry, String userInfoPropertySet) + public UserInfoManagerImpl(UserManager userMgr, PortletRegistry registry, + String userInfoPropertySet) { this.userMgr = userMgr; this.registry = registry; @@ -116,13 +123,12 @@ public Map getUserInfoMap(ObjectID oid, RequestContext context) { if (log.isDebugEnabled()) - log.debug("Getting user info for portlet application: " + oid.toString()); + log.debug("Getting user info for portlet application: " + + oid.toString()); // Check if user info map is in cache. - if (userInfoMapCache.containsKey(oid)) - { - return (Map) userInfoMapCache.get(oid); - } + if (userInfoMapCache.containsKey(oid)) { return (Map) userInfoMapCache + .get(oid); } // Not in cache, map user info. Preferences userPrefs = getUserPreferences(context); if (null == userPrefs) @@ -140,7 +146,8 @@ Preferences userInfoPrefs = userPrefs.node(userInfoPropertySet); Collection userAttributes = pa.getUserAttributes(); Collection userAttributeRefs = pa.getUserAttributeRefs(); - Map userInfoMap = mapUserInfo(userInfoPrefs, userAttributes, userAttributeRefs); + Map userInfoMap = mapUserInfo(userInfoPrefs, userAttributes, + userAttributeRefs); return userInfoMap; } @@ -151,18 +158,19 @@ * user info attribute declared in the portlet.xml descriptor. *

        * - * @param userInfoPrefs The user info preferences. - * @param userAttributes The declarative portlet user attributes. - * @param userAttributeRefs The declarative jetspeed portlet extension user - * attributes reference. + * @param userInfoPrefs + * The user info preferences. + * @param userAttributes + * The declarative portlet user attributes. + * @param userAttributeRefs + * The declarative jetspeed portlet extension user attributes + * reference. * @return The user info map. */ - private Map mapUserInfo(Preferences userInfoPrefs, Collection userAttributes, Collection userAttributeRefs) + private Map mapUserInfo(Preferences userInfoPrefs, + Collection userAttributes, Collection userAttributeRefs) { - if ((null == userAttributes) || (userAttributes.size() == 0)) - { - return null; - } + if ((null == userAttributes) || (userAttributes.size() == 0)) { return null; } Map userInfoMap = new HashMap(); String[] propertyKeys = null; @@ -170,38 +178,42 @@ { propertyKeys = userInfoPrefs.keys(); if ((null != propertyKeys) && log.isDebugEnabled()) - log.debug("Found " + propertyKeys.length + " children for " + userInfoPrefs.absolutePath()); + log.debug("Found " + propertyKeys.length + " children for " + + userInfoPrefs.absolutePath()); } catch (BackingStoreException bse) { log.error("BackingStoreException: " + bse.toString()); } - if (null == propertyKeys) - { - return null; - } + if (null == propertyKeys) { return null; } - Collection linkedUserAttributes = mapLinkedUserAttributes(userAttributes, userAttributeRefs); + Collection linkedUserAttributes = mapLinkedUserAttributes( + userAttributes, userAttributeRefs); Iterator iter = linkedUserAttributes.iterator(); while (iter.hasNext()) { - UserAttributeRef currentAttributeRef = (UserAttributeRef) iter.next(); + UserAttributeRef currentAttributeRef = (UserAttributeRef) iter + .next(); if (null != currentAttributeRef) { for (int i = 0; i < propertyKeys.length; i++) { if (null != currentAttributeRef.getNameLink()) { - if ((currentAttributeRef.getNameLink()).equals(propertyKeys[i])) + if ((currentAttributeRef.getNameLink()) + .equals(propertyKeys[i])) { - userInfoMap.put(currentAttributeRef.getName(), userInfoPrefs.get(propertyKeys[i], null)); + userInfoMap.put(currentAttributeRef.getName(), + userInfoPrefs.get(propertyKeys[i], null)); } } else { - if ((currentAttributeRef.getName()).equals(propertyKeys[i])) + if ((currentAttributeRef.getName()) + .equals(propertyKeys[i])) { - userInfoMap.put(currentAttributeRef.getName(), userInfoPrefs.get(propertyKeys[i], null)); + userInfoMap.put(currentAttributeRef.getName(), + userInfoPrefs.get(propertyKeys[i], null)); } } } @@ -221,7 +233,8 @@ * If no user is logged in, return null. *

        * - * @param context The request context. + * @param context + * The request context. * @return The user preferences. */ private Preferences getUserPreferences(RequestContext context) @@ -230,7 +243,8 @@ Subject subject = context.getSubject(); if (null != subject) { - Principal userPrincipal = SecurityHelper.getPrincipal(subject, UserPrincipal.class); + Principal userPrincipal = SecurityHelper.getPrincipal(subject, + UserPrincipal.class); if (null != userPrincipal) { log.debug("Got user principal: " + userPrincipal.getName()); @@ -244,7 +258,8 @@ } catch (SecurityException sex) { - log.warn("Unexpected SecurityException in UserInfoManager", sex); + log.warn("Unexpected SecurityException in UserInfoManager", + sex); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/UserManagerUserAttributeSourceImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/UserManagerUserAttributeSourceImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/userinfo/impl/UserManagerUserAttributeSourceImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -38,7 +38,8 @@ import org.apache.jetspeed.userinfo.UserAttributeSource; /** - * Default implementation of a UserAttribute source Provides users attributes from standard prefs implementation + * Default implementation of a UserAttribute source Provides users attributes + * from standard prefs implementation * * @author Keith Garry Boyce * @author David Sean Taylor @@ -48,7 +49,8 @@ { /** Logger */ - private static final Log log = LogFactory.getLog(UserManagerUserAttributeSourceImpl.class); + private static final Log log = LogFactory + .getLog(UserManagerUserAttributeSourceImpl.class); /** The user manager */ private UserManager userManager; @@ -65,14 +67,17 @@ /* * (non-Javadoc) * - * @see org.jetspeed.userinfo.UserAttributeSource#getUserAttributeMap(javax.security.auth.Subject, java.util.Set) + * @see org.jetspeed.userinfo.UserAttributeSource#getUserAttributeMap(javax.security.auth.Subject, + * java.util.Set) */ - public Map getUserAttributeMap(Subject subject, Collection userAttributeRefs, RequestContext context) + public Map getUserAttributeMap(Subject subject, + Collection userAttributeRefs, RequestContext context) throws UserAttributeRetrievalException { Map userAttributeMap = new HashMap(); - Principal userPrincipal = SecurityHelper.getPrincipal(subject, UserPrincipal.class); + Principal userPrincipal = SecurityHelper.getPrincipal(subject, + UserPrincipal.class); if (null != userPrincipal) { log.debug("Got user principal: " + userPrincipal.getName()); @@ -82,13 +87,17 @@ { User user = userManager.getUser(userPrincipal.getName()); Preferences userInfoPrefs = user.getPreferences(); - for (Iterator iter = userAttributeRefs.iterator(); iter.hasNext();) + for (Iterator iter = userAttributeRefs.iterator(); iter + .hasNext();) { - UserAttributeRef currentAttributeRef = (UserAttributeRef) iter.next(); - Object value = userInfoPrefs.get(currentAttributeRef.getName(), null); + UserAttributeRef currentAttributeRef = (UserAttributeRef) iter + .next(); + Object value = userInfoPrefs.get(currentAttributeRef + .getName(), null); if (value != null) { - userAttributeMap.put(currentAttributeRef.getName(), value); + userAttributeMap.put(currentAttributeRef.getName(), + value); } } @@ -96,7 +105,10 @@ } catch (SecurityException sex) { - log.warn("Unexpected SecurityException in UserInfoManager", sex); + log + .warn( + "Unexpected SecurityException in UserInfoManager", + sex); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/CloneUtil.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/CloneUtil.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/CloneUtil.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,23 +28,29 @@ */ public class CloneUtil { + /** - * Provides a deep clone serializing/de-serializng objToClone + * Provides a deep clone serializing/de-serializng objToClone * - * @param objToClone The object to be cloned + * @param objToClone + * The object to be cloned * @return The cloned object */ public static final Object deepClone(Object objToClone) { try { - ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(100); - ObjectOutputStream objectoutputstream = new ObjectOutputStream(bytearrayoutputstream); + ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream( + 100); + ObjectOutputStream objectoutputstream = new ObjectOutputStream( + bytearrayoutputstream); objectoutputstream.writeObject(objToClone); byte abyte0[] = bytearrayoutputstream.toByteArray(); objectoutputstream.close(); - ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(abyte0); - ObjectInputStream objectinputstream = new ObjectInputStream(bytearrayinputstream); + ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream( + abyte0); + ObjectInputStream objectinputstream = new ObjectInputStream( + bytearrayinputstream); Object clone = objectinputstream.readObject(); objectinputstream.close(); return clone; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/DirectoryUtils.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/DirectoryUtils.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/DirectoryUtils.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,97 +18,95 @@ import java.io.File; - /* * File System Directory Utilities. Some utilities that java.io doesn't give us. - * - * rmdir() - removes a directory and all subdirectories and files underneath. - * + * + * rmdir() - removes a directory and all subdirectories and files underneath. + * * @author David S. Taylor David Sean Taylor + * * @version $Id: DirectoryUtils.java 517124 2007-03-12 08:10:25Z ate $ - * + * */ public class DirectoryUtils { + public static void main(String[] args) { DirectoryUtils.rmdir(new File(args[0])); } /** - * Removes a directory and all subdirectories and files beneath it. - * - * @param directory The name of the root directory to be deleted. + * Removes a directory and all subdirectories and files beneath it. + * + * @param directory + * The name of the root directory to be deleted. * @return boolean If all went successful, returns true, otherwise false. * */ public static final boolean rmdir(File dir) - { - if (dir.isDirectory()) - { - String[] children = dir.list(); - for (int i = 0; i < children.length; i++) - { - boolean success = rmdir(new File(dir, children[i])); - if (!success) - { - return false; - } - } - } + { + if (dir.isDirectory()) + { + String[] children = dir.list(); + for (int i = 0; i < children.length; i++) + { + boolean success = rmdir(new File(dir, children[i])); + if (!success) { return false; } + } + } - // The directory is now empty so delete it OR it is a plain file - return dir.delete(); + // The directory is now empty so delete it OR it is a plain file + return dir.delete(); } /** - * Recursive deletion engine, traverses through all subdirectories, - * attempting to delete every file and directory it comes across. - * NOTE: this version doesn't do any security checks, nor does it - * check for file modes and attempt to change them. - * - * @param path The directory path to be traversed. + * Recursive deletion engine, traverses through all subdirectories, + * attempting to delete every file and directory it comes across. NOTE: this + * version doesn't do any security checks, nor does it check for file modes + * and attempt to change them. * - */ -// private static void deleteTraversal(String path) -// { -// File file = new File(path); -// if (file.isFile()) -// { -// try -// { -// file.delete(); -// } -// catch (Exception e) -// { -// log.error("Failed to Delete file: " + path + " : " , e); -// file.deleteOnExit(); // try to get it later... -// } -// } -// else if (file.isDirectory()) -// { -// if (!path.endsWith(File.separator)) -// path += File.separator; -// -// String list[] = file.list(); -// -// // Process all files recursivly -// for(int ix = 0; list != null && ix < list.length; ix++) -// deleteTraversal(path + list[ix]); -// -// // now try to delete the directory -// try -// { -// file.delete(); -// } -// catch (Exception e) -// { -// log.error("Failed to Delete directory: " + path + " : " , e); -// file.deleteOnExit(); // try to get it later... -// } -// -// } -// } + * @param path + * The directory path to be traversed. + * + */ + // private static void deleteTraversal(String path) + // { + // File file = new File(path); + // if (file.isFile()) + // { + // try + // { + // file.delete(); + // } + // catch (Exception e) + // { + // log.error("Failed to Delete file: " + path + " : " , e); + // file.deleteOnExit(); // try to get it later... + // } + // } + // else if (file.isDirectory()) + // { + // if (!path.endsWith(File.separator)) + // path += File.separator; + // + // String list[] = file.list(); + // + // // Process all files recursivly + // for(int ix = 0; list != null && ix < list.length; ix++) + // deleteTraversal(path + list[ix]); + // + // // now try to delete the directory + // try + // { + // file.delete(); + // } + // catch (Exception e) + // { + // log.error("Failed to Delete directory: " + path + " : " , e); + // file.deleteOnExit(); // try to get it later... + // } + // + // } + // } } - - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/MimeType.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/MimeType.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/MimeType.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,61 +17,64 @@ package org.apache.jetspeed.util; - /** - * - *

        Utility class for declaring MIME types to use for various requests and provide - * utility manipulation methods.

        - *

        Added Content-Encoding capability, with defaults - * + * + *

        + * Utility class for declaring MIME types to use for various requests and + * provide utility manipulation methods. + *

        + *

        + * Added Content-Encoding capability, with defaults + * * @author Rapha\u00ebl Luta * @author Santiago Gala * @version $Id: MimeType.java 516448 2007-03-09 16:25:47Z ate $ */ public class MimeType { - - public static final MimeType HTML = new MimeType("text/html", "UTF-8"); //FIXME: test + + public static final MimeType HTML = new MimeType("text/html", "UTF-8"); // FIXME: + + // test + public static final MimeType XHTML = new MimeType("text/xhtml"); - public static final MimeType WML = new MimeType("text/vnd.wap.wml"); - public static final MimeType XML = new MimeType("text/xml"); - public static final MimeType VXML = new MimeType("text/vxml"); - + + public static final MimeType WML = new MimeType("text/vnd.wap.wml"); + + public static final MimeType XML = new MimeType("text/xml"); + + public static final MimeType VXML = new MimeType("text/vxml"); + /** * Standard ContentType String, with no encoding appended. */ private String mimeType = ""; + /** - * null value means default encoding. - * Otherwise, charset to be used. + * null value means default encoding. Otherwise, charset to be used. */ private String charSet = null; - + public MimeType(String mimeType) { - if (mimeType == null) - { - throw new NullPointerException(); - } + if (mimeType == null) { throw new NullPointerException(); } this.mimeType = mimeType; } - + /** - * + * */ public MimeType(String mimeType, String charSet) { - if (mimeType == null) - { - throw new NullPointerException(); - } + if (mimeType == null) { throw new NullPointerException(); } this.mimeType = mimeType; this.charSet = charSet; } - - /** Extracts from this MimeType a user-friendly identifying code - * ie "html" for "text/html" or "wml" for "text/vnd.wap.wml" - * + + /** + * Extracts from this MimeType a user-friendly identifying code ie "html" + * for "text/html" or "wml" for "text/vnd.wap.wml" + * * @return the simplified type */ public String getCode() @@ -85,16 +88,16 @@ { type = type.substring(idx + 1); } - //remove anything before a "-" + // remove anything before a "-" idx = type.lastIndexOf("-"); if (idx >= 0) { type = type.substring(idx + 1); } - + return type.toLowerCase(); } - + /** * Return the media type associated */ @@ -102,7 +105,7 @@ { return this.mimeType; } - + /** * Return the character encoding associated, if any */ @@ -110,29 +113,23 @@ { return this.charSet; } - + /** * Convert this MimeType to its external String representation */ public String toString() { - if (null == this.charSet) - { - return this.mimeType; - } + if (null == this.charSet) { return this.mimeType; } return this.mimeType + "; charset=" + this.charSet; } - + /** * Compare one MimeType to another */ public boolean equals(Object obj) { - if (this == obj) - { - return true; - } - + if (this == obj) { return true; } + if (obj instanceof MimeType) { MimeType comp = (MimeType) obj; @@ -143,5 +140,5 @@ return false; } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/MultiFileChecksumHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/MultiFileChecksumHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/MultiFileChecksumHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,27 +25,31 @@ /** * Perform a single checksum calculation for multiple files - * + * * @author Ate Douma * @author David Sean Taylor * @version $Id$ */ public class MultiFileChecksumHelper { + public static long getChecksum(File[] files) { CheckedInputStream cis = null; FileInputStream is = null; Checksum checksum = new Adler32(); byte[] tempBuf = new byte[128]; - - for ( int i = 0; i < files.length && files[i] != null && files[i].exists() && files[i].isFile(); i++ ) + + for (int i = 0; i < files.length && files[i] != null + && files[i].exists() && files[i].isFile(); i++) { - try + try { is = new FileInputStream(files[i]); cis = new CheckedInputStream(is, checksum); - while (cis.read(tempBuf) >= 0) {} + while (cis.read(tempBuf) >= 0) + { + } } catch (Exception e) { @@ -59,7 +63,9 @@ { cis.close(); } - catch (IOException ioe) {} + catch (IOException ioe) + { + } cis = null; } if (is != null) @@ -68,7 +74,9 @@ { is.close(); } - catch (IOException ioe) {} + catch (IOException ioe) + { + } is = null; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/ExtendedPortletMetadata.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/ExtendedPortletMetadata.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/ExtendedPortletMetadata.java 2008-05-16 01:54:54 UTC (rev 940) @@ -39,26 +39,29 @@ import org.xml.sax.Attributes; /** - * This class is used to load extended MetaData, like that of the Dublin Core, + * This class is used to load extended MetaData, like that of the Dublin Core, * into an exsting PortletApplicationDefinition's object graph. * * @author Jeremy Ford * @author Scott T. Weaver * @version $Id: JetspeedDescriptorUtilities.java,v 1.10 2004/06/08 01:35:01 - * dlestrat Exp $ + * dlestrat Exp $ */ public class ExtendedPortletMetadata { + private static class CollectionRule extends Rule { + private Collection collection; - + public CollectionRule(Collection collection) { this.collection = collection; } - public void begin(String arg0, String arg1, Attributes arg2) throws Exception + public void begin(String arg0, String arg1, Attributes arg2) + throws Exception { digester.push(collection); } @@ -66,27 +69,35 @@ public void end(String arg0, String arg1) throws Exception { digester.pop(); - } + } } - - protected final static Log log = LogFactory.getLog(ExtendedPortletMetadata.class); + protected final static Log log = LogFactory + .getLog(ExtendedPortletMetadata.class); + protected Reader extendedMetaData; + protected MutablePortletApplication portletApp; - + /** * - * @param extendedMetaData Reader that contains the extended metadata, usually jetspeed-portlet.xml - * @param portletApp the MutablePortletApplication we are adding the extended metadata to. + * @param extendedMetaData + * Reader that contains the extended metadata, usually + * jetspeed-portlet.xml + * @param portletApp + * the MutablePortletApplication we are adding the extended + * metadata to. */ - public ExtendedPortletMetadata( Reader extendedMetaData, MutablePortletApplication portletApp ) + public ExtendedPortletMetadata(Reader extendedMetaData, + MutablePortletApplication portletApp) { this.extendedMetaData = extendedMetaData; this.portletApp = portletApp; } /** - * Performs the actual loading and mapping of the metadata into the PortletApplicationDefinition. + * Performs the actual loading and mapping of the metadata into the + * PortletApplicationDefinition. * */ public void load() throws MetaDataException @@ -101,70 +112,95 @@ digester.addRuleSet(new MetadataRuleSet("portlet-app/")); digester.addRuleSet(new JetspeedServicesRuleSet(portletApp)); - digester.addRule("portlet-app/security-constraint-ref", new SecurityConstraintRefRule(portletApp)); - - digester.addRule("portlet-app/portlet/portlet-name", new PortletRule(portletApp)); + digester.addRule("portlet-app/security-constraint-ref", + new SecurityConstraintRefRule(portletApp)); + + digester.addRule("portlet-app/portlet/portlet-name", + new PortletRule(portletApp)); digester.addRuleSet(new MetadataRuleSet("portlet-app/portlet/")); - - digester.addRule("portlet-app/portlet/security-constraint-ref", new SecurityConstraintRefRule(portletApp)); - + + digester.addRule("portlet-app/portlet/security-constraint-ref", + new SecurityConstraintRefRule(portletApp)); + digester.addRuleSet(new UserAttributeRefRuleSet(portletApp)); - + ArrayList mappedPortletModes = new ArrayList(); - digester.addRule("portlet-app/custom-portlet-mode",new CollectionRule(mappedPortletModes)); - digester.addObjectCreate("portlet-app/custom-portlet-mode",CustomPortletModeImpl.class); - - digester.addBeanPropertySetter("portlet-app/custom-portlet-mode/name", "customName"); - digester.addBeanPropertySetter("portlet-app/custom-portlet-mode/mapped-name", "mappedName"); + digester.addRule("portlet-app/custom-portlet-mode", + new CollectionRule(mappedPortletModes)); + digester.addObjectCreate("portlet-app/custom-portlet-mode", + CustomPortletModeImpl.class); + + digester.addBeanPropertySetter( + "portlet-app/custom-portlet-mode/name", "customName"); + digester + .addBeanPropertySetter( + "portlet-app/custom-portlet-mode/mapped-name", + "mappedName"); digester.addSetNext("portlet-app/custom-portlet-mode", "add"); - + ArrayList mappedWindowStates = new ArrayList(); - digester.addRule("portlet-app/custom-window-state",new CollectionRule(mappedWindowStates)); - digester.addObjectCreate("portlet-app/custom-window-state",CustomWindowStateImpl.class); - - digester.addBeanPropertySetter("portlet-app/custom-window-state/name", "customName"); - digester.addBeanPropertySetter("portlet-app/custom-window-state/mapped-name", "mappedName"); + digester.addRule("portlet-app/custom-window-state", + new CollectionRule(mappedWindowStates)); + digester.addObjectCreate("portlet-app/custom-window-state", + CustomWindowStateImpl.class); + + digester.addBeanPropertySetter( + "portlet-app/custom-window-state/name", "customName"); + digester + .addBeanPropertySetter( + "portlet-app/custom-window-state/mapped-name", + "mappedName"); digester.addSetNext("portlet-app/custom-window-state", "add"); - + digester.parse(extendedMetaData); - + if (mappedPortletModes.size() > 0) { - PortletApplicationDefinitionImpl pa = (PortletApplicationDefinitionImpl)portletApp; - ArrayList customModes = new ArrayList(pa.getCustomPortletModes()); + PortletApplicationDefinitionImpl pa = (PortletApplicationDefinitionImpl) portletApp; + ArrayList customModes = new ArrayList(pa + .getCustomPortletModes()); Iterator mappedModesIter = mappedPortletModes.iterator(); - while ( mappedModesIter.hasNext() ) + while (mappedModesIter.hasNext()) { - CustomPortletModeImpl mappedMode = (CustomPortletModeImpl)mappedModesIter.next(); - if (!mappedMode.getMappedMode().equals(mappedMode.getCustomMode())) + CustomPortletModeImpl mappedMode = (CustomPortletModeImpl) mappedModesIter + .next(); + if (!mappedMode.getMappedMode().equals( + mappedMode.getCustomMode())) { int index = customModes.indexOf(mappedMode); - if ( index > -1 ) + if (index > -1) { - CustomPortletMode customMode = (CustomPortletMode)customModes.get(index); - mappedMode.setDescription(customMode.getDescription()); - customModes.set(index,mappedMode); + CustomPortletMode customMode = (CustomPortletMode) customModes + .get(index); + mappedMode.setDescription(customMode + .getDescription()); + customModes.set(index, mappedMode); } } } pa.setCustomPortletModes(customModes); } - if ( mappedWindowStates.size() > 0) + if (mappedWindowStates.size() > 0) { - PortletApplicationDefinitionImpl pa = (PortletApplicationDefinitionImpl)portletApp; - ArrayList customStates = new ArrayList(pa.getCustomWindowStates()); + PortletApplicationDefinitionImpl pa = (PortletApplicationDefinitionImpl) portletApp; + ArrayList customStates = new ArrayList(pa + .getCustomWindowStates()); Iterator mappedStatesIter = mappedWindowStates.iterator(); - while ( mappedStatesIter.hasNext() ) + while (mappedStatesIter.hasNext()) { - CustomWindowStateImpl mappedState = (CustomWindowStateImpl)mappedStatesIter.next(); - if (!mappedState.getMappedState().equals(mappedState.getCustomState())) + CustomWindowStateImpl mappedState = (CustomWindowStateImpl) mappedStatesIter + .next(); + if (!mappedState.getMappedState().equals( + mappedState.getCustomState())) { int index = customStates.indexOf(mappedState); - if ( index > -1 ) + if (index > -1) { - CustomWindowState customState = (CustomWindowState)customStates.get(index); - mappedState.setDescription(customState.getDescription()); - customStates.set(index,mappedState); + CustomWindowState customState = (CustomWindowState) customStates + .get(index); + mappedState.setDescription(customState + .getDescription()); + customStates.set(index, mappedState); } } } @@ -173,8 +209,8 @@ } catch (Throwable t) { - throw new MetaDataException("Unable to marshall extended metadata. " + t.toString(), t); + throw new MetaDataException( + "Unable to marshall extended metadata. " + t.toString(), t); } } } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/MetaDataException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/MetaDataException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/MetaDataException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,7 +33,7 @@ /** * @param message */ - public MetaDataException( String message ) + public MetaDataException(String message) { super(message); // TODO Auto-generated constructor stub @@ -42,7 +42,7 @@ /** * @param nested */ - public MetaDataException( Throwable nested ) + public MetaDataException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -52,7 +52,7 @@ * @param msg * @param nested */ - public MetaDataException( String msg, Throwable nested ) + public MetaDataException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationDescriptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationDescriptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationDescriptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -48,20 +48,24 @@ * * Object used to perform operation upon a portlet application descriptor, * usually, portlet.xml. - * + * * @author Roger Ruttimann - * @author David Sean Taylor + * @author David Sean Taylor * @author Scott T. Weaver - * - * @version $Id: PortletApplicationDescriptor.java 516448 2007-03-09 16:25:47Z ate $ + * + * @version $Id: PortletApplicationDescriptor.java 516448 2007-03-09 16:25:47Z + * ate $ */ public class PortletApplicationDescriptor { - protected final static Log log = LogFactory.getLog(PortletApplicationDescriptor.class); + + protected final static Log log = LogFactory + .getLog(PortletApplicationDescriptor.class); + protected Reader portletXmlReader; + private String appName; - public PortletApplicationDescriptor(Reader portletXmlReader, String appName) { this.portletXmlReader = portletXmlReader; @@ -69,131 +73,210 @@ } public MutablePortletApplication createPortletApplication() - throws PortletApplicationException + throws PortletApplicationException { return createPortletApplication(this.getClass().getClassLoader()); } - + /** - * Maps the content of the portlet application descriptor into - * a new MutablePortletApplication object + * Maps the content of the portlet application descriptor into a new + * MutablePortletApplication object * - * @return MutablePortletApplication newly created MutablePortletApplication with - * all values of the portlet application descriptor mapped into it. + * @return MutablePortletApplication newly created MutablePortletApplication + * with all values of the portlet application descriptor mapped into + * it. */ - public MutablePortletApplication createPortletApplication(ClassLoader classLoader) - throws PortletApplicationException + public MutablePortletApplication createPortletApplication( + ClassLoader classLoader) throws PortletApplicationException { try { - // TODO move config to digester-rules.xml. Example: http://www.onjava.com/pub/a/onjava/2002/10/23/digester.html?page=3 + // TODO move config to digester-rules.xml. Example: + // http://www.onjava.com/pub/a/onjava/2002/10/23/digester.html?page=3 Digester digester = new Digester(); digester.setValidating(false); digester.setClassLoader(this.getClass().getClassLoader()); - + // digester.addRuleSet(new PortletApplicationRuleSet(appName)); - - digester.addRule("portlet-app", new PortletApplicationRule(appName)); - digester.addSetProperties("portlet-app", "id", "applicationIdentifier"); + digester + .addRule("portlet-app", new PortletApplicationRule(appName)); + digester.addSetProperties("portlet-app", "id", + "applicationIdentifier"); digester.addRule("portlet-app/portlet", new PortletRule()); - - digester.addSetProperties("portlet-app/portlet", "id", "portletIdentifier"); - digester.addBeanPropertySetter("portlet-app/portlet/portlet-name", "name"); - digester.addBeanPropertySetter("portlet-app/portlet/portlet-class", "className"); - digester.addBeanPropertySetter("portlet-app/portlet/expiration-cache", "expirationCache"); - digester.addBeanPropertySetter("portlet-app/portlet/resource-bundle", "resourceBundle"); - digester.addCallMethod("portlet-app/portlet/supported-locale", "addSupportedLocale", 0); - - digester.addObjectCreate("portlet-app/portlet/display-name", PortletDisplayNameImpl.class); - digester.addSetProperties("portlet-app/portlet/display-name", "xml:lang", "language"); - digester.addBeanPropertySetter("portlet-app/portlet/display-name", "displayName"); - digester.addSetNext("portlet-app/portlet/display-name", "addDisplayName"); - digester.addObjectCreate("portlet-app/portlet/description", PortletDescriptionImpl.class); - digester.addSetProperties("portlet-app/portlet/description", "xml:lang", "language"); - digester.addBeanPropertySetter("portlet-app/portlet/description", "description"); - digester.addSetNext("portlet-app/portlet/description", "addDescription"); + digester.addSetProperties("portlet-app/portlet", "id", + "portletIdentifier"); + digester.addBeanPropertySetter("portlet-app/portlet/portlet-name", + "name"); + digester.addBeanPropertySetter("portlet-app/portlet/portlet-class", + "className"); + digester.addBeanPropertySetter( + "portlet-app/portlet/expiration-cache", "expirationCache"); + digester.addBeanPropertySetter( + "portlet-app/portlet/resource-bundle", "resourceBundle"); + digester.addCallMethod("portlet-app/portlet/supported-locale", + "addSupportedLocale", 0); - digester.addObjectCreate("portlet-app/portlet/init-param", PortletInitParameterImpl.class); - digester.addBeanPropertySetter("portlet-app/portlet/init-param/name", "name"); - digester.addBeanPropertySetter("portlet-app/portlet/init-param/value", "value"); - digester.addSetNext("portlet-app/portlet/init-param", "addInitParameter"); + digester.addObjectCreate("portlet-app/portlet/display-name", + PortletDisplayNameImpl.class); + digester.addSetProperties("portlet-app/portlet/display-name", + "xml:lang", "language"); + digester.addBeanPropertySetter("portlet-app/portlet/display-name", + "displayName"); + digester.addSetNext("portlet-app/portlet/display-name", + "addDisplayName"); - digester.addObjectCreate("portlet-app/portlet/init-param/description", ParameterDescriptionImpl.class); - digester.addSetProperties("portlet-app/portlet/init-param/description", "xml:lang", "language"); - digester.addBeanPropertySetter("portlet-app/portlet/init-param/description", "description"); - digester.addSetNext("portlet-app/portlet/init-param/description", "addDescription"); + digester.addObjectCreate("portlet-app/portlet/description", + PortletDescriptionImpl.class); + digester.addSetProperties("portlet-app/portlet/description", + "xml:lang", "language"); + digester.addBeanPropertySetter("portlet-app/portlet/description", + "description"); + digester.addSetNext("portlet-app/portlet/description", + "addDescription"); - digester.addObjectCreate("portlet-app/portlet/supports", ContentTypeImpl.class); - digester.addBeanPropertySetter("portlet-app/portlet/supports/mime-type", "contentType"); - digester.addCallMethod("portlet-app/portlet/supports/portlet-mode", "addPortletMode", 0); - digester.addSetNext("portlet-app/portlet/supports", "addContentType"); + digester.addObjectCreate("portlet-app/portlet/init-param", + PortletInitParameterImpl.class); + digester.addBeanPropertySetter( + "portlet-app/portlet/init-param/name", "name"); + digester.addBeanPropertySetter( + "portlet-app/portlet/init-param/value", "value"); + digester.addSetNext("portlet-app/portlet/init-param", + "addInitParameter"); - digester.addObjectCreate("portlet-app/portlet/portlet-info", LanguageImpl.class); - digester.addBeanPropertySetter("portlet-app/portlet/portlet-info/title", "title"); - digester.addBeanPropertySetter("portlet-app/portlet/portlet-info/short-title", "shortTitle"); - digester.addCallMethod("portlet-app/portlet/portlet-info/keywords", "setKeywords", 0, new Class[]{String.class}); - digester.addSetNext("portlet-app/portlet/portlet-info", "addLanguage"); - + digester.addObjectCreate( + "portlet-app/portlet/init-param/description", + ParameterDescriptionImpl.class); + digester.addSetProperties( + "portlet-app/portlet/init-param/description", "xml:lang", + "language"); + digester + .addBeanPropertySetter( + "portlet-app/portlet/init-param/description", + "description"); + digester.addSetNext("portlet-app/portlet/init-param/description", + "addDescription"); + + digester.addObjectCreate("portlet-app/portlet/supports", + ContentTypeImpl.class); + digester.addBeanPropertySetter( + "portlet-app/portlet/supports/mime-type", "contentType"); + digester.addCallMethod("portlet-app/portlet/supports/portlet-mode", + "addPortletMode", 0); + digester.addSetNext("portlet-app/portlet/supports", + "addContentType"); + + digester.addObjectCreate("portlet-app/portlet/portlet-info", + LanguageImpl.class); + digester.addBeanPropertySetter( + "portlet-app/portlet/portlet-info/title", "title"); + digester.addBeanPropertySetter( + "portlet-app/portlet/portlet-info/short-title", + "shortTitle"); + digester.addCallMethod("portlet-app/portlet/portlet-info/keywords", + "setKeywords", 0, new Class[] + {String.class}); + digester.addSetNext("portlet-app/portlet/portlet-info", + "addLanguage"); + digester.addRuleSet(new PortletPreferenceRuleSet()); - - digester.addObjectCreate("portlet-app/user-attribute", UserAttributeImpl.class); - digester.addBeanPropertySetter("portlet-app/user-attribute/description", "description"); - digester.addBeanPropertySetter("portlet-app/user-attribute/name", "name"); - digester.addSetNext("portlet-app/user-attribute", "addUserAttribute"); - - digester.addObjectCreate("portlet-app/custom-portlet-mode", CustomPortletModeImpl.class); - digester.addBeanPropertySetter("portlet-app/custom-portlet-mode/description", "description"); - // support both custom-portlet-mode/portlet-mode (correct) and custom-portlet-mode/name (incorrect but needed for backwards compatibility) + digester.addObjectCreate("portlet-app/user-attribute", + UserAttributeImpl.class); + digester.addBeanPropertySetter( + "portlet-app/user-attribute/description", "description"); + digester.addBeanPropertySetter("portlet-app/user-attribute/name", + "name"); + digester.addSetNext("portlet-app/user-attribute", + "addUserAttribute"); + + digester.addObjectCreate("portlet-app/custom-portlet-mode", + CustomPortletModeImpl.class); + digester.addBeanPropertySetter( + "portlet-app/custom-portlet-mode/description", + "description"); + // support both custom-portlet-mode/portlet-mode (correct) and + // custom-portlet-mode/name (incorrect but needed for backwards + // compatibility) // see: http://issues.apache.org/jira/browse/JS2-611 - // TODO: when portlet.xml xsd validation is added the custom-portlet-mode/name definition will no longer be needed/supported - digester.addBeanPropertySetter("portlet-app/custom-portlet-mode/portlet-mode", "customName"); - digester.addBeanPropertySetter("portlet-app/custom-portlet-mode/name", "customName"); - digester.addSetNext("portlet-app/custom-portlet-mode", "addCustomPortletMode"); - - digester.addObjectCreate("portlet-app/custom-window-state", CustomWindowStateImpl.class); - digester.addBeanPropertySetter("portlet-app/custom-window-state/description", "description"); - // support both custom-window-state/window-state (correct) and custom-window-state/name (incorrect but needed for backwards compatibility) + // TODO: when portlet.xml xsd validation is added the + // custom-portlet-mode/name definition will no longer be + // needed/supported + digester.addBeanPropertySetter( + "portlet-app/custom-portlet-mode/portlet-mode", + "customName"); + digester.addBeanPropertySetter( + "portlet-app/custom-portlet-mode/name", "customName"); + digester.addSetNext("portlet-app/custom-portlet-mode", + "addCustomPortletMode"); + + digester.addObjectCreate("portlet-app/custom-window-state", + CustomWindowStateImpl.class); + digester.addBeanPropertySetter( + "portlet-app/custom-window-state/description", + "description"); + // support both custom-window-state/window-state (correct) and + // custom-window-state/name (incorrect but needed for backwards + // compatibility) // see: http://issues.apache.org/jira/browse/JS2-611 - // TODO: when portlet.xml xsd validation is added the custom-window-state/name definition will no longer be needed/supported - digester.addBeanPropertySetter("portlet-app/custom-window-state/window-state", "customName"); - digester.addBeanPropertySetter("portlet-app/custom-window-state/name", "customName"); - digester.addSetNext("portlet-app/custom-window-state", "addCustomWindowState"); - - digester.addObjectCreate("portlet-app/portlet/security-role-ref", SecurityRoleRefImpl.class); - digester.addBeanPropertySetter("portlet-app/portlet/security-role-ref/role-name", "roleName"); - digester.addBeanPropertySetter("portlet-app/portlet/security-role-ref/role-link", "roleLink"); - digester.addSetNext("portlet-app/portlet/security-role-ref", "addSecurityRoleRef"); + // TODO: when portlet.xml xsd validation is added the + // custom-window-state/name definition will no longer be + // needed/supported + digester.addBeanPropertySetter( + "portlet-app/custom-window-state/window-state", + "customName"); + digester.addBeanPropertySetter( + "portlet-app/custom-window-state/name", "customName"); + digester.addSetNext("portlet-app/custom-window-state", + "addCustomWindowState"); - digester.addObjectCreate("portlet-app/portlet/security-role-ref/description", SecurityRoleRefDescriptionImpl.class); - digester.addSetProperties("portlet-app/portlet/security-role-ref/description", "xml:lang", "language"); - digester.addBeanPropertySetter("portlet-app/portlet/security-role-ref/description", "description"); - digester.addSetNext("portlet-app/portlet/security-role-ref/description", "addDescription"); - - PortletApplicationDefinitionImpl pd = (PortletApplicationDefinitionImpl) digester.parse(portletXmlReader); + digester.addObjectCreate("portlet-app/portlet/security-role-ref", + SecurityRoleRefImpl.class); + digester.addBeanPropertySetter( + "portlet-app/portlet/security-role-ref/role-name", + "roleName"); + digester.addBeanPropertySetter( + "portlet-app/portlet/security-role-ref/role-link", + "roleLink"); + digester.addSetNext("portlet-app/portlet/security-role-ref", + "addSecurityRoleRef"); - - if(pd.getApplicationIdentifier() == null) + digester.addObjectCreate( + "portlet-app/portlet/security-role-ref/description", + SecurityRoleRefDescriptionImpl.class); + digester.addSetProperties( + "portlet-app/portlet/security-role-ref/description", + "xml:lang", "language"); + digester.addBeanPropertySetter( + "portlet-app/portlet/security-role-ref/description", + "description"); + digester.addSetNext( + "portlet-app/portlet/security-role-ref/description", + "addDescription"); + + PortletApplicationDefinitionImpl pd = (PortletApplicationDefinitionImpl) digester + .parse(portletXmlReader); + + if (pd.getApplicationIdentifier() == null) { pd.setApplicationIdentifier(appName); } - + Iterator portletDefs = pd.getPortletDefinitions().iterator(); - while(portletDefs.hasNext()) + while (portletDefs.hasNext()) { Object obj = portletDefs.next(); PortletDefinitionComposite portletDef = (PortletDefinitionComposite) obj; - if(portletDef.getPortletIdentifier() == null) + if (portletDef.getPortletIdentifier() == null) { portletDef.setPortletIdentifier(portletDef.getName()); } - - ((Support)obj).postLoad(classLoader); + + ((Support) obj).postLoad(classLoader); } - + return pd; } @@ -203,9 +286,7 @@ throw new PortletApplicationException(msg, t); } } - - /** * Validate a PortletApplicationDefinition tree AFTER its * WebApplicationDefinition has been loaded. Currently, only the security Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationRule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationRule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationRule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,45 +25,47 @@ */ public class PortletApplicationRule extends Rule { + protected String appName; - + public PortletApplicationRule(String appName) { this.appName = appName; } - /** *

        * begin *

        - * - * @see org.apache.commons.digester.Rule#begin(java.lang.String, java.lang.String, org.xml.sax.Attributes) + * + * @see org.apache.commons.digester.Rule#begin(java.lang.String, + * java.lang.String, org.xml.sax.Attributes) * @param arg0 * @param arg1 * @param arg2 * @throws java.lang.Exception */ - public void begin( String arg0, String arg1, Attributes arg2 ) throws Exception + public void begin(String arg0, String arg1, Attributes arg2) + throws Exception { PortletApplicationDefinitionImpl app = new PortletApplicationDefinitionImpl(); app.setName(appName); - digester.push(app); + digester.push(app); } - - + /** *

        * end *

        - * - * @see org.apache.commons.digester.Rule#end(java.lang.String, java.lang.String) + * + * @see org.apache.commons.digester.Rule#end(java.lang.String, + * java.lang.String) * @param arg0 * @param arg1 * @throws java.lang.Exception */ - public void end( String arg0, String arg1 ) throws Exception + public void end(String arg0, String arg1) throws Exception { - // digester.pop(); + // digester.pop(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationRuleSet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationRuleSet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationRuleSet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,8 +24,9 @@ */ public class PortletApplicationRuleSet extends RuleSetBase { + protected String appName; - + public PortletApplicationRuleSet(String appName) { this.appName = appName; @@ -35,11 +36,11 @@ *

        * addRuleInstances *

        - * + * * @see org.apache.commons.digester.RuleSet#addRuleInstances(org.apache.commons.digester.Digester) * @param arg0 */ - public void addRuleInstances( Digester digester ) + public void addRuleInstances(Digester digester) { digester.addRule("portlet-app", new PortletApplicationRule(appName)); digester.addSetProperties("portlet-app", "id", "applicationIdentifier"); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationWar.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationWar.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletApplicationWar.java 2008-05-16 01:54:54 UTC (rev 940) @@ -80,36 +80,48 @@ */ public class PortletApplicationWar { - protected static final String WEB_XML_STRING = - "" + - "\n" + - ""; + protected static final String WEB_XML_STRING = "" + + "\n" + + ""; + public static final String PORTLET_XML_PATH = "WEB-INF/portlet.xml"; + public static final String WEB_XML_PATH = "WEB-INF/web.xml"; + public static final String EXTENDED_PORTLET_XML_PATH = "WEB-INF/jetspeed-portlet.xml"; protected static final int MAX_BUFFER_SIZE = 1024; public static final String JETSPEED_SERVLET_XPATH = "/web-app/servlet/servlet-name[contains(child::text(), \"JetspeedContainer\")]"; + public static final String JETSPEED_SERVLET_MAPPING_XPATH = "/web-app/servlet-mapping/servlet-name[contains(child::text(), \"JetspeedContainer\")]"; protected static final Log log = LogFactory.getLog("deployment"); protected String paName; + protected String webAppContextRoot; + protected FileSystemHelper warStruct; + private MutableWebApplication webApp; + private MutablePortletApplication portletApp; + private long paChecksum; + protected final List openedResources; - protected static final String[] ELEMENTS_BEFORE_SERVLET = new String[]{"icon", "display-name", "description", - "distributable", "context-param", "filter", "filter-mapping", "listener", "servlet"}; - protected static final String[] ELEMENTS_BEFORE_SERVLET_MAPPING = new String[]{"icon", "display-name", - "description", "distributable", "context-param", "filter", "filter-mapping", "listener", "servlet", + protected static final String[] ELEMENTS_BEFORE_SERVLET = new String[] + {"icon", "display-name", "description", "distributable", "context-param", + "filter", "filter-mapping", "listener", "servlet"}; + + protected static final String[] ELEMENTS_BEFORE_SERVLET_MAPPING = new String[] + {"icon", "display-name", "description", "distributable", "context-param", + "filter", "filter-mapping", "listener", "servlet", "servlet-mapping"}; /** @@ -122,12 +134,14 @@ * @param webAppContextRoot * context root relative to the servlet container of this app */ - public PortletApplicationWar( FileSystemHelper warStruct, String paName, String webAppContextRoot ) + public PortletApplicationWar(FileSystemHelper warStruct, String paName, + String webAppContextRoot) { this(warStruct, paName, webAppContextRoot, 0); } - public PortletApplicationWar( FileSystemHelper warStruct, String paName, String webAppContextRoot, long paChecksum ) + public PortletApplicationWar(FileSystemHelper warStruct, String paName, + String webAppContextRoot, long paChecksum) { validatePortletApplicationName(paName); @@ -137,21 +151,22 @@ this.warStruct = warStruct; this.paChecksum = paChecksum; } - + public long getPortletApplicationChecksum() throws IOException { - if ( this.paChecksum == 0) + if (this.paChecksum == 0) { - this.paChecksum = MultiFileChecksumHelper.getChecksum(new File[] { + this.paChecksum = MultiFileChecksumHelper.getChecksum(new File[] + { new File(warStruct.getRootDirectory(), WEB_XML_PATH), new File(warStruct.getRootDirectory(), PORTLET_XML_PATH), - new File(warStruct.getRootDirectory(), EXTENDED_PORTLET_XML_PATH) }); + new File(warStruct.getRootDirectory(), + EXTENDED_PORTLET_XML_PATH)}); } - if (this.paChecksum == 0) - { - throw new IOException("Cannot find any deployment descriptor for Portlet Application "+paName); - } - return paChecksum; + if (this.paChecksum == 0) { throw new IOException( + "Cannot find any deployment descriptor for Portlet Application " + + paName); } + return paChecksum; } /** @@ -161,14 +176,13 @@ * * @param paName */ - private void validatePortletApplicationName( String paName ) + private void validatePortletApplicationName(String paName) { - if (paName == null || paName.startsWith("/") || paName.startsWith("\\") || paName.endsWith("/") - || paName.endsWith("\\")) - { - throw new IllegalStateException("Invalid paName \"" + paName - + "\". paName cannot be null nor can it begin nor end with any slashes."); - } + if (paName == null || paName.startsWith("/") || paName.startsWith("\\") + || paName.endsWith("/") || paName.endsWith("\\")) { throw new IllegalStateException( + "Invalid paName \"" + + paName + + "\". paName cannot be null nor can it begin nor end with any slashes."); } } /** @@ -179,18 +193,20 @@ * Creates a web applicaiton object based on the values in this WAR's * WEB-INF/web.xml * - * @return @throws - * PortletApplicationException + * @return + * @throws PortletApplicationException * @throws IOException * @see org.apache.jetspeed.util.descriptor.WebApplicationDescriptor */ - public MutableWebApplication createWebApp() throws PortletApplicationException, IOException + public MutableWebApplication createWebApp() + throws PortletApplicationException, IOException { Reader webXmlReader = getReader(WEB_XML_PATH); try { - WebApplicationDescriptor webAppDescriptor = new WebApplicationDescriptor(webXmlReader, webAppContextRoot); + WebApplicationDescriptor webAppDescriptor = new WebApplicationDescriptor( + webXmlReader, webAppContextRoot); webApp = webAppDescriptor.createWebApplication(); return webApp; } @@ -220,18 +236,20 @@ * Creates a portlet application object based of the WAR file's * WEB-INF/portlet.xml * - * @return @throws - * PortletApplicationException + * @return + * @throws PortletApplicationException * @throws IOException * @see org.apache.jetspeed.uitl.descriptor.PortletApplicationDescriptor */ - public MutablePortletApplication createPortletApp(ClassLoader classLoader) throws PortletApplicationException, IOException + public MutablePortletApplication createPortletApp(ClassLoader classLoader) + throws PortletApplicationException, IOException { Reader portletXmlReader = getReader(PORTLET_XML_PATH); - + try { - PortletApplicationDescriptor paDescriptor = new PortletApplicationDescriptor(portletXmlReader, paName); + PortletApplicationDescriptor paDescriptor = new PortletApplicationDescriptor( + portletXmlReader, paName); portletApp = paDescriptor.createPortletApplication(classLoader); // validate(portletApplication); Reader extMetaDataXml = null; @@ -240,24 +258,27 @@ extMetaDataXml = getReader(EXTENDED_PORTLET_XML_PATH); if (extMetaDataXml != null) { - ExtendedPortletMetadata extMetaData = new ExtendedPortletMetadata(extMetaDataXml, portletApp); + ExtendedPortletMetadata extMetaData = new ExtendedPortletMetadata( + extMetaDataXml, portletApp); extMetaData.load(); } } catch (IOException e) { - if ( e instanceof FileNotFoundException ) + if (e instanceof FileNotFoundException) { log.info("No extended metadata found."); } else { - throw new PortletApplicationException("Failed to load existing metadata.",e); + throw new PortletApplicationException( + "Failed to load existing metadata.", e); } } catch (MetaDataException e) { - throw new PortletApplicationException("Failed to load existing metadata.", e); + throw new PortletApplicationException( + "Failed to load existing metadata.", e); } finally { @@ -278,12 +299,12 @@ } } - public MutablePortletApplication createPortletApp() - throws PortletApplicationException, IOException + public MutablePortletApplication createPortletApp() + throws PortletApplicationException, IOException { return createPortletApp(this.getClass().getClassLoader()); } - + /** * *

        @@ -298,9 +319,9 @@ * @throws IOException * if the path does not exist or there was a problem reading the * WAR. - * + * */ - protected Reader getReader( String path ) throws IOException + protected Reader getReader(String path) throws IOException { BufferedInputStream is = new BufferedInputStream(getInputStream(path)); @@ -322,7 +343,8 @@ int off = data.indexOf(key); if (off > 0) { - enc = data.substring(off + key.length(), data.indexOf('"', off + key.length())); + enc = data.substring(off + key.length(), data.indexOf('"', + off + key.length())); } } } @@ -335,7 +357,7 @@ log.warn("Unsupported encoding.", e); } - //Reset the bytes read + // Reset the bytes read is.reset(); return new InputStreamReader(is, enc); } @@ -356,13 +378,11 @@ * if the path does not exist or there was a problem reading the * WAR. */ - protected InputStream getInputStream( String path ) throws IOException + protected InputStream getInputStream(String path) throws IOException { File child = new File(warStruct.getRootDirectory(), path); - if (child == null || !child.exists()) - { - throw new FileNotFoundException("Unable to locate file or path " + child); - } + if (child == null || !child.exists()) { throw new FileNotFoundException( + "Unable to locate file or path " + child); } FileInputStream fileInputStream = new FileInputStream(child); openedResources.add(fileInputStream); @@ -385,19 +405,17 @@ * if the path does not exist or there was a problem reading the * WAR. */ - protected OutputStream getOutputStream( String path ) throws IOException + protected OutputStream getOutputStream(String path) throws IOException { File child = new File(warStruct.getRootDirectory(), path); - if (child == null) - { - throw new FileNotFoundException("Unable to locate file or path " + child); - } + if (child == null) { throw new FileNotFoundException( + "Unable to locate file or path " + child); } FileOutputStream fileOutputStream = new FileOutputStream(child); openedResources.add(fileOutputStream); return fileOutputStream; } - protected Writer getWriter( String path ) throws IOException + protected Writer getWriter(String path) throws IOException { return new OutputStreamWriter(getOutputStream(path)); } @@ -417,7 +435,8 @@ * @return PortletApplicationWar representing the newly created WAR. * @throws IOException */ - public PortletApplicationWar copyWar( String targetAppRoot ) throws IOException + public PortletApplicationWar copyWar(String targetAppRoot) + throws IOException { // FileObject target = fsManager.resolveFile(new // File(targetAppRoot).getAbsolutePath()); @@ -426,7 +445,8 @@ { target.copyFrom(warStruct.getRootDirectory()); - return new PortletApplicationWar(target, paName, webAppContextRoot, paChecksum); + return new PortletApplicationWar(target, paName, webAppContextRoot, + paChecksum); } catch (IOException e) @@ -459,8 +479,8 @@ } else { - throw new FileNotFoundException("PortletApplicationWar ," + warStruct.getRootDirectory() - + ", does not exist."); + throw new FileNotFoundException("PortletApplicationWar ," + + warStruct.getRootDirectory() + ", does not exist."); } } @@ -480,23 +500,23 @@ */ public void validate() throws PortletApplicationException { - if (portletApp == null || webApp == null) - { - throw new IllegalStateException( - "createWebApp() and createPortletApp() must be called before invoking validate()"); - } + if (portletApp == null || webApp == null) { throw new IllegalStateException( + "createWebApp() and createPortletApp() must be called before invoking validate()"); } SecurityRoleSet roles = webApp.getSecurityRoles(); Collection portlets = portletApp.getPortletDefinitions(); Iterator portletIterator = portlets.iterator(); while (portletIterator.hasNext()) { - PortletDefinition portlet = (PortletDefinition) portletIterator.next(); - SecurityRoleRefSet securityRoleRefs = portlet.getInitSecurityRoleRefSet(); + PortletDefinition portlet = (PortletDefinition) portletIterator + .next(); + SecurityRoleRefSet securityRoleRefs = portlet + .getInitSecurityRoleRefSet(); Iterator roleRefsIterator = securityRoleRefs.iterator(); while (roleRefsIterator.hasNext()) { - SecurityRoleRef roleRef = (SecurityRoleRef) roleRefsIterator.next(); + SecurityRoleRef roleRef = (SecurityRoleRef) roleRefsIterator + .next(); String roleName = roleRef.getRoleLink(); if (roleName == null || roleName.length() == 0) { @@ -504,8 +524,8 @@ } if (roles.get(roleName) == null) { - String errorMsg = "Undefined security role " + roleName + " referenced from portlet " - + portlet.getName(); + String errorMsg = "Undefined security role " + roleName + + " referenced from portlet " + portlet.getName(); throw new PortletApplicationException(errorMsg); } } @@ -538,20 +558,25 @@ // allows to deploy the application offline builder.setEntityResolver(new EntityResolver() { - public InputSource resolveEntity( java.lang.String publicId, java.lang.String systemId ) - throws SAXException, java.io.IOException + + public InputSource resolveEntity(java.lang.String publicId, + java.lang.String systemId) throws SAXException, + java.io.IOException { - if (systemId.equals("http://java.sun.com/dtd/web-app_2_3.dtd")) + if (systemId + .equals("http://java.sun.com/dtd/web-app_2_3.dtd")) { - return new InputSource(getClass().getResourceAsStream("web-app_2_3.dtd")); + return new InputSource(getClass().getResourceAsStream( + "web-app_2_3.dtd")); } - else return null; + else + return null; } }); Document doc = null; - + try { webXmlIn = getInputStream(WEB_XML_PATH); @@ -567,17 +592,17 @@ doc = builder.build(file); file.delete(); } - - + if (webXmlIn != null) { webXmlIn.close(); } JetspeedWebApplicationRewriterFactory rewriterFactory = new JetspeedWebApplicationRewriterFactory(); - JetspeedWebApplicationRewriter rewriter = rewriterFactory.getInstance(doc); + JetspeedWebApplicationRewriter rewriter = rewriterFactory + .getInstance(doc); rewriter.processWebXML(); - + if (rewriter.isChanged()) { System.out.println("Writing out infused web.xml for " + paName); @@ -587,23 +612,25 @@ webXmlWriter.flush(); } - - if(rewriter.isPortletTaglibAdded()) + + if (rewriter.isPortletTaglibAdded()) { - //add portlet tag lib to war + // add portlet tag lib to war String path = Jetspeed.getRealPath("WEB-INF/tld"); if (path != null) { File portletTaglibDir = new File(path); - File child = new File(warStruct.getRootDirectory(), "WEB-INF/tld"); + File child = new File(warStruct.getRootDirectory(), + "WEB-INF/tld"); DirectoryHelper dh = new DirectoryHelper(child); - dh.copyFrom(portletTaglibDir, new FileFilter(){ + dh.copyFrom(portletTaglibDir, new FileFilter() + { public boolean accept(File pathname) { return pathname.getName().indexOf("portlet.tld") != -1; - } - }); + } + }); dh.close(); } } @@ -612,7 +639,8 @@ catch (Exception e) { e.printStackTrace(); - throw new MetaDataException("Unable to process web.xml for infusion " + e.toString(), e); + throw new MetaDataException( + "Unable to process web.xml for infusion " + e.toString(), e); } finally { @@ -643,7 +671,6 @@ } - /** * *

        @@ -693,15 +720,16 @@ * * @param parent * Parent ClassLoader. Can be null - * @return @throws - * IOException + * @return + * @throws IOException */ - public ClassLoader createClassloader( ClassLoader parent ) throws IOException + public ClassLoader createClassloader(ClassLoader parent) throws IOException { ArrayList urls = new ArrayList(); File webInfClasses = null; - webInfClasses = new File(warStruct.getRootDirectory(), ("WEB-INF/classes/")); + webInfClasses = new File(warStruct.getRootDirectory(), + ("WEB-INF/classes/")); if (webInfClasses.exists()) { log.info("Adding " + webInfClasses.toURL() + " to class path."); @@ -722,7 +750,8 @@ } } - return new URLClassLoader((URL[]) urls.toArray(new URL[urls.size()]), parent); + return new URLClassLoader((URL[]) urls.toArray(new URL[urls.size()]), + parent); } /** @@ -753,7 +782,7 @@ return null; } } - + public FileSystemHelper getFileSystem() { return warStruct; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletPreferenceRule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletPreferenceRule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletPreferenceRule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,86 +30,94 @@ */ public class PortletPreferenceRule extends Rule { - protected PortletDefinitionComposite portlet; - + protected String name; + protected boolean readOnly; - protected List values; - + + protected List values; + /** *

        * begin *

        - * - * @see org.apache.commons.digester.Rule#begin(java.lang.String, java.lang.String, org.xml.sax.Attributes) + * + * @see org.apache.commons.digester.Rule#begin(java.lang.String, + * java.lang.String, org.xml.sax.Attributes) * @param arg0 * @param arg1 * @param arg2 * @throws java.lang.Exception */ - public void begin( String arg0, String arg1, Attributes arg2 ) throws Exception + public void begin(String arg0, String arg1, Attributes arg2) + throws Exception { Object peeked = digester.peek(); portlet = (PortletDefinitionComposite) peeked; - portlet.setPortletApplicationDefinition((PortletApplicationDefinition) digester.getRoot()); - + portlet + .setPortletApplicationDefinition((PortletApplicationDefinition) digester + .getRoot()); + // reset properties to default values // as the same instance of this rule can be used multiple times - values = new ArrayList(); + values = new ArrayList(); readOnly = false; - + TempValueObject temp = new TempValueObject(); digester.push(temp); } + /** *

        * end *

        - * - * @see org.apache.commons.digester.Rule#end(java.lang.String, java.lang.String) + * + * @see org.apache.commons.digester.Rule#end(java.lang.String, + * java.lang.String) * @param arg0 * @param arg1 * @throws java.lang.Exception */ - public void end( String arg0, String arg1 ) throws Exception - { + public void end(String arg0, String arg1) throws Exception + { PrefsPreference pref = new PrefsPreference(portlet, name); pref.setValues(values); pref.setReadOnly(readOnly); digester.pop(); } - + public class TempValueObject { + public void setName(String name) { PortletPreferenceRule.this.name = name; } - + public void setReadOnly(boolean readOnly) { PortletPreferenceRule.this.readOnly = readOnly; } - + public void addValue(String value) { PortletPreferenceRule.this.values.add(value); } } - + /** *

        * finish *

        - * + * * @see org.apache.commons.digester.Rule#finish() * @throws java.lang.Exception */ public void finish() throws Exception { - if(values != null) + if (values != null) { values.clear(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletPreferenceRuleSet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletPreferenceRuleSet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletPreferenceRuleSet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,27 +25,32 @@ public class PortletPreferenceRuleSet extends RuleSetBase { - - /** *

        * addRuleInstances *

        - * + * * @see org.apache.commons.digester.RuleSet#addRuleInstances(org.apache.commons.digester.Digester) * @param arg0 */ - public void addRuleInstances( Digester digester ) + public void addRuleInstances(Digester digester) { - digester.addBeanPropertySetter("portlet-app/portlet/portlet-preferences/preferences-validator", "preferenceValidatorClassname"); - digester.addRule("portlet-app/portlet/portlet-preferences/preference", new PortletPreferenceRule()); - digester.addBeanPropertySetter("portlet-app/portlet/portlet-preferences/preference/name", "name"); - digester.addCallMethod("portlet-app/portlet/portlet-preferences/preference/value", "addValue", 0); - digester.addCallMethod( - "portlet-app/portlet/portlet-preferences/preference/read-only", - "setReadOnly", - 0, - new Class[] { Boolean.class }); + digester + .addBeanPropertySetter( + "portlet-app/portlet/portlet-preferences/preferences-validator", + "preferenceValidatorClassname"); + digester.addRule("portlet-app/portlet/portlet-preferences/preference", + new PortletPreferenceRule()); + digester.addBeanPropertySetter( + "portlet-app/portlet/portlet-preferences/preference/name", + "name"); + digester.addCallMethod( + "portlet-app/portlet/portlet-preferences/preference/value", + "addValue", 0); + digester.addCallMethod( + "portlet-app/portlet/portlet-preferences/preference/read-only", + "setReadOnly", 0, new Class[] + {Boolean.class}); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletRule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletRule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/PortletRule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,31 +31,36 @@ *

        * begin *

        - * - * @see org.apache.commons.digester.Rule#begin(java.lang.String, java.lang.String, org.xml.sax.Attributes) + * + * @see org.apache.commons.digester.Rule#begin(java.lang.String, + * java.lang.String, org.xml.sax.Attributes) * @param arg0 * @param arg1 * @param arg2 * @throws java.lang.Exception */ - public void begin( String arg0, String arg1, Attributes arg2 ) throws Exception + public void begin(String arg0, String arg1, Attributes arg2) + throws Exception { PortletDefinitionImpl portlet = new PortletDefinitionImpl(); - PortletApplicationDefinitionImpl app = (PortletApplicationDefinitionImpl) digester.getRoot(); + PortletApplicationDefinitionImpl app = (PortletApplicationDefinitionImpl) digester + .getRoot(); app.addPortletDefinition(portlet); digester.push(portlet); } + /** *

        * end *

        - * - * @see org.apache.commons.digester.Rule#end(java.lang.String, java.lang.String) + * + * @see org.apache.commons.digester.Rule#end(java.lang.String, + * java.lang.String) * @param arg0 * @param arg1 * @throws java.lang.Exception */ - public void end( String arg0, String arg1 ) throws Exception + public void end(String arg0, String arg1) throws Exception { digester.pop(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/WebApplicationDescriptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/WebApplicationDescriptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/util/descriptor/WebApplicationDescriptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,38 +30,38 @@ * * @author Ate Douma * * @version $Id: WebDescriptorUtilities.java,v 1.2 2004/05/12 22:25:04 taylor - * Exp $ + * Exp $ */ public class WebApplicationDescriptor { protected Reader webXmlReader; + protected String contextRoot; - public WebApplicationDescriptor(Reader webXmlReader, String contextRoot ) + + public WebApplicationDescriptor(Reader webXmlReader, String contextRoot) { - if(webXmlReader == null) - { - throw new IllegalArgumentException("webXmlReader cannot be null"); - } + if (webXmlReader == null) { throw new IllegalArgumentException( + "webXmlReader cannot be null"); } this.webXmlReader = webXmlReader; this.contextRoot = contextRoot; } - /** * Load a web.xml file into a Web Application tree * * @param pathWebXML - * The path to the web.xml file + * The path to the web.xml file * @param contexRoot - * The context root of the web application + * The context root of the web application * @param locale - * The locale of the display name of the web application + * The locale of the display name of the web application * @param displayName - * The display name of the web application + * The display name of the web application * @return The Java object tree representing web.xml */ - public MutableWebApplication createWebApplication() throws PortletApplicationException + public MutableWebApplication createWebApplication() + throws PortletApplicationException { try { @@ -71,30 +71,39 @@ Digester digester = new Digester(); digester.setClassLoader(this.getClass().getClassLoader()); digester.setValidating(false); - - digester.register("-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN", WebApplicationDescriptor.class - .getResource("web-app_2_2.dtd").toString()); - digester.register("-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN", WebApplicationDescriptor.class - .getResource("web-app_2_3.dtd").toString()); - - digester.addObjectCreate("web-app", WebApplicationDefinitionImpl.class); - digester.addObjectCreate("web-app/security-role", SecurityRoleImpl.class); - digester.addBeanPropertySetter("web-app/security-role/description", "description"); - digester.addBeanPropertySetter("web-app/security-role/role-name", "roleName"); + digester.register( + "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN", + WebApplicationDescriptor.class.getResource( + "web-app_2_2.dtd").toString()); + digester.register( + "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN", + WebApplicationDescriptor.class.getResource( + "web-app_2_3.dtd").toString()); + + digester.addObjectCreate("web-app", + WebApplicationDefinitionImpl.class); + + digester.addObjectCreate("web-app/security-role", + SecurityRoleImpl.class); + digester.addBeanPropertySetter("web-app/security-role/description", + "description"); + digester.addBeanPropertySetter("web-app/security-role/role-name", + "roleName"); digester.addSetNext("web-app/security-role", "addSecurityRole"); - WebApplicationDefinitionImpl wd = (WebApplicationDefinitionImpl) digester.parse(webXmlReader); + WebApplicationDefinitionImpl wd = (WebApplicationDefinitionImpl) digester + .parse(webXmlReader); wd.setContextRoot(contextRoot); - //wd.addDescription(locale, displayName); + // wd.addDescription(locale, displayName); wd.addDescription(JetspeedLocale.getDefaultLocale(), contextRoot); return wd; } catch (Throwable t) - { - String msg = "Could not digester web.xml." + t.toString(); + { + String msg = "Could not digester web.xml." + t.toString(); throw new PortletApplicationException(msg, t); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/HtmlUtilTool.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/HtmlUtilTool.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/HtmlUtilTool.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,11 +23,12 @@ * HtmlUtilTool *

        *

        - * + * *

        + * * @author Scott T. Weaver * @version $Id: HtmlUtilTool.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class HtmlUtilTool implements ViewTool { @@ -36,18 +37,18 @@ *

        * init *

        - * + * * @see org.apache.velocity.tools.view.tools.ViewTool#init(java.lang.Object) * @param arg0 */ - public void init( Object arg0 ) - { - + public void init(Object arg0) + { + } - + public String getSafeElementId(Object obj) { - if(obj == null) + if (obj == null) { return "null"; } @@ -55,7 +56,7 @@ { // Convert "/" to "-" String initValue = obj.toString(); - return initValue.replaceAll("[\\/,\\.]","-"); + return initValue.replaceAll("[\\/,\\.]", "-"); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedPowerToolFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedPowerToolFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedPowerToolFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,35 +27,44 @@ import org.apache.jetspeed.request.RequestContext; import org.apache.jetspeed.services.title.DynamicTitleService; -public class JetspeedPowerToolFactory implements org.apache.jetspeed.layout.JetspeedPowerToolFactory +public class JetspeedPowerToolFactory implements + org.apache.jetspeed.layout.JetspeedPowerToolFactory { - protected static final Log log = LogFactory.getLog(JetspeedPowerToolFactory.class); - + + protected static final Log log = LogFactory + .getLog(JetspeedPowerToolFactory.class); + private Class jptClass; + private Constructor constructor; + private DynamicTitleService titleService; - + /* Allows us to render portlets and other fragments */ private PortletRenderer renderer; - - public JetspeedPowerToolFactory(String jptClassName, DynamicTitleService titleService, PortletRenderer renderer) - throws ClassNotFoundException, NoSuchMethodException + + public JetspeedPowerToolFactory(String jptClassName, + DynamicTitleService titleService, PortletRenderer renderer) + throws ClassNotFoundException, NoSuchMethodException { - jptClass = Thread.currentThread().getContextClassLoader().loadClass(jptClassName); - constructor = - jptClass.getConstructor( - new Class[] {RequestContext.class, DynamicTitleService.class, PortletRenderer.class}); + jptClass = Thread.currentThread().getContextClassLoader().loadClass( + jptClassName); + constructor = jptClass + .getConstructor(new Class[] + {RequestContext.class, DynamicTitleService.class, + PortletRenderer.class}); this.titleService = titleService; this.renderer = renderer; } - + public JetspeedPowerTool getJetspeedPowerTool(RequestContext requestContext) - throws PortletException + throws PortletException { try { - Object [] initArgs = { requestContext, this.titleService, this.renderer }; - return (JetspeedPowerTool)constructor.newInstance(initArgs); + Object[] initArgs = + {requestContext, this.titleService, this.renderer}; + return (JetspeedPowerTool) constructor.newInstance(initArgs); } catch (Exception e) { @@ -64,4 +73,3 @@ } } } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedPowerToolImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedPowerToolImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedPowerToolImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -110,7 +110,8 @@ protected Writer templateWriter; - protected static final Log log = LogFactory.getLog(JetspeedPowerToolImpl.class); + protected static final Log log = LogFactory + .getLog(JetspeedPowerToolImpl.class); protected CapabilityMap capabilityMap; @@ -133,31 +134,38 @@ protected Context velocityContext; private DynamicTitleService titleService; - + private BasePortalURL baseUrlAccess; - + private PortletRenderer renderer; - public JetspeedPowerToolImpl(RequestContext requestContext, DynamicTitleService titleService,PortletRenderer renderer) throws Exception + public JetspeedPowerToolImpl(RequestContext requestContext, + DynamicTitleService titleService, PortletRenderer renderer) + throws Exception { HttpServletRequest request = requestContext.getRequest(); this.requestContext = requestContext; this.titleService = titleService; - windowAccess = (PortletWindowAccessor) getComponent(PortletWindowAccessor.class.getName()); - entityAccess = (PortletEntityAccessComponent) getComponent(PortletEntityAccessComponent.class.getName()); + windowAccess = (PortletWindowAccessor) getComponent(PortletWindowAccessor.class + .getName()); + entityAccess = (PortletEntityAccessComponent) getComponent(PortletEntityAccessComponent.class + .getName()); try { baseUrlAccess = (BasePortalURL) getComponent("BasePortalURL"); } catch (Exception e) - { - // BasePortalURL is optional: ignore (org.springframework.beans.factory.NoSuchBeanDefinitionException) + { + // BasePortalURL is optional: ignore + // (org.springframework.beans.factory.NoSuchBeanDefinitionException) } - - renderRequest = (RenderRequest) request.getAttribute(RENDER_REQUEST_ATTR); - renderResponse = (RenderResponse) request.getAttribute(RENDER_RESPONSE_ATTR); - portletConfig = (PortletConfig) request.getAttribute(PORTLET_CONFIG_ATTR); + renderRequest = (RenderRequest) request + .getAttribute(RENDER_REQUEST_ATTR); + renderResponse = (RenderResponse) request + .getAttribute(RENDER_RESPONSE_ATTR); + portletConfig = (PortletConfig) request + .getAttribute(PORTLET_CONFIG_ATTR); templateLocator = (TemplateLocator) getComponent("TemplateLocator"); decorationLocator = (TemplateLocator) getComponent("DecorationLocator"); @@ -165,16 +173,20 @@ capabilityMap = requestContext.getCapabilityMap(); locale = requestContext.getLocale(); - templateLocatorDescriptor = templateLocator.createLocatorDescriptor(null); - templateLocatorDescriptor.setMediaType(capabilityMap.getPreferredMediaType().getName()); + templateLocatorDescriptor = templateLocator + .createLocatorDescriptor(null); + templateLocatorDescriptor.setMediaType(capabilityMap + .getPreferredMediaType().getName()); templateLocatorDescriptor.setCountry(locale.getCountry()); templateLocatorDescriptor.setLanguage(locale.getLanguage()); - decorationLocatorDescriptor = decorationLocator.createLocatorDescriptor(null); - decorationLocatorDescriptor.setMediaType(capabilityMap.getPreferredMediaType().getName()); + decorationLocatorDescriptor = decorationLocator + .createLocatorDescriptor(null); + decorationLocatorDescriptor.setMediaType(capabilityMap + .getPreferredMediaType().getName()); decorationLocatorDescriptor.setCountry(locale.getCountry()); decorationLocatorDescriptor.setLanguage(locale.getLanguage()); - + this.renderer = renderer; } @@ -200,8 +212,10 @@ { try { - NavigationalState nav = getRequestContext().getPortalURL().getNavigationalState(); - return nav.getState(windowAccess.getPortletWindow(getCurrentFragment())); + NavigationalState nav = getRequestContext().getPortalURL() + .getNavigationalState(); + return nav.getState(windowAccess + .getPortletWindow(getCurrentFragment())); } catch (Exception e) { @@ -211,7 +225,8 @@ } /** - * Gets the internal (portal) window state for the current portlet window (fragment) + * Gets the internal (portal) window state for the current portlet window + * (fragment) * * @return The window state for the current window * @throws Exception @@ -220,8 +235,10 @@ { try { - NavigationalState nav = getRequestContext().getPortalURL().getNavigationalState(); - return nav.getMappedState(windowAccess.getPortletWindow(getCurrentFragment())); + NavigationalState nav = getRequestContext().getPortalURL() + .getNavigationalState(); + return nav.getMappedState(windowAccess + .getPortletWindow(getCurrentFragment())); } catch (Exception e) { @@ -239,10 +256,12 @@ public PortletMode getPortletMode() throws Exception { - NavigationalState nav = getRequestContext().getPortalURL().getNavigationalState(); + NavigationalState nav = getRequestContext().getPortalURL() + .getNavigationalState(); try { - return nav.getMode(windowAccess.getPortletWindow(getCurrentFragment())); + return nav.getMode(windowAccess + .getPortletWindow(getCurrentFragment())); } catch (FailedToRetrievePortletWindow e) { @@ -252,7 +271,8 @@ } /** - * Gets the internal (portal) portlet mode for a current portlet window (fragment) + * Gets the internal (portal) portlet mode for a current portlet window + * (fragment) * * @return The portlet mode of the current window * @throws Exception @@ -260,10 +280,12 @@ public PortletMode getMappedPortletMode() throws Exception { - NavigationalState nav = getRequestContext().getPortalURL().getNavigationalState(); + NavigationalState nav = getRequestContext().getPortalURL() + .getNavigationalState(); try { - return nav.getMappedMode(windowAccess.getPortletWindow(getCurrentFragment())); + return nav.getMappedMode(windowAccess + .getPortletWindow(getCurrentFragment())); } catch (FailedToRetrievePortletWindow e) { @@ -279,7 +301,8 @@ public ContentFragment getCurrentFragment() { checkState(); - return (ContentFragment) renderRequest.getAttribute(PortalReservedParameters.FRAGMENT_ATTRIBUTE); + return (ContentFragment) renderRequest + .getAttribute(PortalReservedParameters.FRAGMENT_ATTRIBUTE); } /** @@ -297,7 +320,8 @@ { checkState(); - ContentFragment f = (ContentFragment) getRequestContext().getRequest().getAttribute(LAYOUT_ATTR); + ContentFragment f = (ContentFragment) getRequestContext().getRequest() + .getAttribute(LAYOUT_ATTR); setAttribute(LAYOUT_ATTR, f); } @@ -337,8 +361,7 @@ { checkState(); Object o = renderRequest.getAttribute(COLUMN_SIZES); - if (o == null) - return null; + if (o == null) return null; return (List) renderRequest.getAttribute(COLUMN_SIZES); } @@ -351,12 +374,14 @@ { try { - return windowAccess.getPortletWindow(getCurrentFragment()).getPortletEntity(); + return windowAccess.getPortletWindow(getCurrentFragment()) + .getPortletEntity(); } catch (Exception e) { - handleError(e, "JetspeedPowerTool failed to retreive the current PortletEntity. " + e.toString(), - getCurrentFragment()); + handleError(e, + "JetspeedPowerTool failed to retreive the current PortletEntity. " + + e.toString(), getCurrentFragment()); return null; } } @@ -371,8 +396,10 @@ */ public PortletEntity getPortletEntity(ContentFragment f) throws Exception { - PortletEntity portletEntity = windowAccess.getPortletWindow(f).getPortletEntity(); - // This API hits the DB: PortletEntity portletEntity = entityAccess.getPortletEntityForFragment(f); + PortletEntity portletEntity = windowAccess.getPortletWindow(f) + .getPortletEntity(); + // This API hits the DB: PortletEntity portletEntity = + // entityAccess.getPortletEntityForFragment(f); if (portletEntity == null) { try @@ -382,14 +409,14 @@ } catch (PortletEntityNotGeneratedException e) { - String msg = "JetspeedPowerTool failed to retreive a PortletEntity for Fragment " + f.getId() + ". " - + e.toString(); + String msg = "JetspeedPowerTool failed to retreive a PortletEntity for Fragment " + + f.getId() + ". " + e.toString(); handleError(e, msg, f); } catch (PortletEntityNotStoredException e) { - String msg = "JetspeedPowerTool failed to store a PortletEntity for Fragment " + f.getId() + ". " - + e.toString(); + String msg = "JetspeedPowerTool failed to store a PortletEntity for Fragment " + + f.getId() + ". " + e.toString(); handleError(e, msg, f); } } @@ -408,10 +435,8 @@ public boolean isHidden(ContentFragment f) { checkState(); - if (f == null) - { - throw new IllegalArgumentException("Fragment cannot be null for isHidden(Fragment)"); - } + if (f == null) { throw new IllegalArgumentException( + "Fragment cannot be null for isHidden(Fragment)"); } return f.getState() != null && f.getState().equals(HIDDEN); } @@ -432,16 +457,21 @@ * @throws TemplateLocatorException * if the path does not exist. */ - public TemplateDescriptor getTemplate(String path, String templateType) throws TemplateLocatorException + public TemplateDescriptor getTemplate(String path, String templateType) + throws TemplateLocatorException { checkState(); - return getTemplate(path, templateType, templateLocator, templateLocatorDescriptor); + return getTemplate(path, templateType, templateLocator, + templateLocatorDescriptor); } - public Configuration getTypeConfiguration(String type, String name, String location) throws Exception + public Configuration getTypeConfiguration(String type, String name, + String location) throws Exception { - ArgUtil.assertNotNull(String.class, type, this, "getTypeConfiguration(String type, String name)"); - ArgUtil.assertNotNull(String.class, name, this, "getTypeConfiguration(String type, String name)"); + ArgUtil.assertNotNull(String.class, type, this, + "getTypeConfiguration(String type, String name)"); + ArgUtil.assertNotNull(String.class, name, this, + "getTypeConfiguration(String type, String name)"); try { TemplateDescriptor locator = null; @@ -467,13 +497,16 @@ } } - public TemplateDescriptor getDecoration(String path, String templateType) throws TemplateLocatorException + public TemplateDescriptor getDecoration(String path, String templateType) + throws TemplateLocatorException { checkState(); - return getTemplate(path, templateType, decorationLocator, decorationLocatorDescriptor); + return getTemplate(path, templateType, decorationLocator, + decorationLocatorDescriptor); } - public String includeTemplate(String template, String templateType) throws IOException + public String includeTemplate(String template, String templateType) + throws IOException { checkState(); try @@ -483,15 +516,18 @@ } catch (Exception e) { - PrintWriter directError = new PrintWriter(renderResponse.getWriter()); - directError.write("Error occured process includeTemplate(): " + e.toString() + "\n\n"); + PrintWriter directError = new PrintWriter(renderResponse + .getWriter()); + directError.write("Error occured process includeTemplate(): " + + e.toString() + "\n\n"); e.printStackTrace(directError); directError.close(); return null; } } - public String includeDecoration(String template, String templateType) throws IOException + public String includeDecoration(String template, String templateType) + throws IOException { checkState(); try @@ -500,8 +536,10 @@ } catch (Exception e) { - PrintWriter directError = new PrintWriter(renderResponse.getWriter()); - directError.write("Error occured process includeDecoration(): " + e.toString() + "\n\n"); + PrintWriter directError = new PrintWriter(renderResponse + .getWriter()); + directError.write("Error occured process includeDecoration(): " + + e.toString() + "\n\n"); e.printStackTrace(directError); directError.close(); return null; @@ -569,7 +607,8 @@ * Portlet fragment to "decorate" * @throws Exception */ - protected String decorateAndIncludePortlet(ContentFragment f) throws Exception + protected String decorateAndIncludePortlet(ContentFragment f) + throws Exception { // make sure that any previous content has been written to // preserve natural HTML rendering order @@ -584,17 +623,20 @@ } // get fragment properties for fragmentType or generic - TemplateDescriptor propsTemp = getTemplate(decorator + "/" + DECORATOR_TYPE + ".properties", fragmentType, + TemplateDescriptor propsTemp = getTemplate(decorator + "/" + + DECORATOR_TYPE + ".properties", fragmentType, decorationLocator, decorationLocatorDescriptor); if (propsTemp == null) { fragmentType = GENERIC_TEMPLATE_TYPE; - propsTemp = getTemplate(decorator + "/" + DECORATOR_TYPE + ".properties", fragmentType, decorationLocator, + propsTemp = getTemplate(decorator + "/" + DECORATOR_TYPE + + ".properties", fragmentType, decorationLocator, decorationLocatorDescriptor); } // get decorator template - Configuration decoConf = new PropertiesConfiguration(propsTemp.getAbsolutePath()); + Configuration decoConf = new PropertiesConfiguration(propsTemp + .getAbsolutePath()); String ext = decoConf.getString("template.extension"); String decoratorPath = decorator + "/" + DECORATOR_TYPE + ext; TemplateDescriptor template = null; @@ -607,12 +649,14 @@ String parent = decoConf.getString("extends"); if (parent != null) { - template = getDecoration(parent + "/" + DECORATOR_TYPE + ext, fragmentType); + template = getDecoration(parent + "/" + DECORATOR_TYPE + ext, + fragmentType); } } setAttribute(DECORATOR_ID_ATTR, decoConf.getString("id")); - setAttribute(ACTION_IMAGE_EXTENSION_ATTR, decoConf.getString("action.image.extension", ".gif")); + setAttribute(ACTION_IMAGE_EXTENSION_ATTR, decoConf.getString( + "action.image.extension", ".gif")); return template.getAppRelativePath(); } @@ -626,16 +670,17 @@ */ protected void checkState() { - if (portletConfig == null || renderRequest == null || renderResponse == null) - { - throw new IllegalStateException("JetspeedPowerTool has not been properly initialized. " + "" - + "The JetspeedPowerTool generally only usuable during the rendering phase of " - + "internal portlet applications."); - } + if (portletConfig == null || renderRequest == null + || renderResponse == null) { throw new IllegalStateException( + "JetspeedPowerTool has not been properly initialized. " + + "" + + "The JetspeedPowerTool generally only usuable during the rendering phase of " + + "internal portlet applications."); } } - protected TemplateDescriptor getTemplate(String path, String templateType, TemplateLocator locator, - LocatorDescriptor descriptor) throws TemplateLocatorException + protected TemplateDescriptor getTemplate(String path, String templateType, + TemplateLocator locator, LocatorDescriptor descriptor) + throws TemplateLocatorException { checkState(); if (templateType == null) @@ -655,7 +700,8 @@ Path pathObject = new Path(path); if (pathObject.length() > 1) { - template = getTemplate(pathObject.getSegment(1).toString(), templateType, locator, descriptor); + template = getTemplate(pathObject.getSegment(1).toString(), + templateType, locator, descriptor); } } return template; @@ -663,7 +709,7 @@ catch (TemplateLocatorException e) { log.error("Unable to locate template: " + path, e); -// System.out.println("Unable to locate template: " + path); + // System.out.println("Unable to locate template: " + path); throw e; } } @@ -680,11 +726,14 @@ { log.error(msg, e); - Set exceptions = (Set) renderRequest.getAttribute(FRAGMENT_PROCESSING_ERROR_PREFIX + fragment.getId()); + Set exceptions = (Set) renderRequest + .getAttribute(FRAGMENT_PROCESSING_ERROR_PREFIX + + fragment.getId()); if (exceptions == null) { exceptions = new HashSet(); - setAttribute(FRAGMENT_PROCESSING_ERROR_PREFIX + fragment.getId(), exceptions); + setAttribute(FRAGMENT_PROCESSING_ERROR_PREFIX + fragment.getId(), + exceptions); } exceptions.add(e); @@ -742,11 +791,13 @@ try { - return titleService.getDynamicTitle(windowAccess.getPortletWindow(f), getRequestContext().getRequest()); + return titleService.getDynamicTitle(windowAccess + .getPortletWindow(f), getRequestContext().getRequest()); } catch (Exception e) { - log.error("Unable to reteive portlet title: " + e.getMessage(), e); + log.error("Unable to reteive portlet title: " + e.getMessage(), + e); return "Title Error: " + e.getMessage(); } } @@ -768,7 +819,8 @@ { try { - return titleService.getDynamicTitle(windowAccess.getPortletWindow(getCurrentFragment()), + return titleService.getDynamicTitle(windowAccess + .getPortletWindow(getCurrentFragment()), getRequestContext().getRequest()); } catch (Exception e) @@ -787,23 +839,30 @@ public String getAbsoluteUrl(String relativePath) { // only rewrite a non-absolute url - if (relativePath != null && relativePath.indexOf("://") == -1 && relativePath.indexOf("mailto:") == -1) + if (relativePath != null && relativePath.indexOf("://") == -1 + && relativePath.indexOf("mailto:") == -1) { HttpServletRequest request = getRequestContext().getRequest(); StringBuffer path = new StringBuffer(); - if ( !getRequestContext().getPortalURL().isRelativeOnly() ) + if (!getRequestContext().getPortalURL().isRelativeOnly()) { if (this.baseUrlAccess == null) { - path.append(request.getScheme()).append("://").append(request.getServerName()).append(":").append(request.getServerPort()); + path.append(request.getScheme()).append("://").append( + request.getServerName()).append(":").append( + request.getServerPort()); } else { - path.append(baseUrlAccess.getServerScheme()).append("://").append(baseUrlAccess.getServerName()).append(":").append(baseUrlAccess.getServerPort()); + path.append(baseUrlAccess.getServerScheme()).append("://") + .append(baseUrlAccess.getServerName()).append(":") + .append(baseUrlAccess.getServerPort()); } } - return renderResponse.encodeURL(path.append(request.getContextPath()).append(request.getServletPath()).append(relativePath).toString()); - + return renderResponse.encodeURL(path.append( + request.getContextPath()).append(request.getServletPath()) + .append(relativePath).toString()); + } else { @@ -856,7 +915,7 @@ velocityContext.put(name, object); } } - + public String renderPortletEntity(String entityId, String portletId) { @@ -866,7 +925,8 @@ entityId); fragment.setType(Fragment.PORTLET); fragment.setName(portletId); - ContentFragment contentFragment = new ContentFragmentImpl(fragment, new HashMap(), true); + ContentFragment contentFragment = new ContentFragmentImpl(fragment, + new HashMap(), true); renderer.renderNow(contentFragment, context); return contentFragment.getRenderedContent(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedVelocityPowerTool.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedVelocityPowerTool.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedVelocityPowerTool.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,13 +23,15 @@ * JetspeedPowerTool * * @author David Sean Taylor - * @version $Id: JetspeedVelocityPowerTool.java 536746 2007-05-10 05:38:04Z taylor $ + * @version $Id: JetspeedVelocityPowerTool.java 536746 2007-05-10 05:38:04Z + * taylor $ */ public interface JetspeedVelocityPowerTool extends JetspeedPowerTool { + /** - * Sets the Velocity Context object for this powertool instance. This is + * Sets the Velocity Context object for this powertool instance. This is * only required if using Velocity based decortaions and layouts. * * @param velocityContext Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedVelocityViewServlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedVelocityViewServlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/JetspeedVelocityViewServlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -64,12 +64,15 @@ import org.apache.velocity.tools.view.servlet.WebappLoader; /** - * @version $Id: JetspeedVelocityViewServlet.java 550655 2007-06-26 01:41:35Z taylor $ + * @version $Id: JetspeedVelocityViewServlet.java 550655 2007-06-26 01:41:35Z + * taylor $ */ public class JetspeedVelocityViewServlet extends BridgesVelocityViewServlet { + /** logging */ - private static final Log log = LogFactory.getLog(JetspeedVelocityViewServlet.class); + private static final Log log = LogFactory + .getLog(JetspeedVelocityViewServlet.class); /** default cache size */ private static final long DEFAULT_CACHE_SIZE = 50; @@ -92,24 +95,32 @@ /** velocity engine configuration caching object */ private class VelocityEngineConfig { + public String decoration; + public String type; + public String mediaType; + public String language; + public String country; public File macros; + public long macrosLastModified; + public long lastValidated; - public VelocityEngineConfig(String decoration, String type, String mediaType, String language, String country) + public VelocityEngineConfig(String decoration, String type, + String mediaType, String language, String country) { this.decoration = decoration; this.type = type; this.mediaType = mediaType; this.language = language; this.country = country; - + this.macrosLastModified = -1; this.lastValidated = System.currentTimeMillis(); } @@ -126,16 +137,17 @@ /** default velocity engine */ private VelocityEngine defaultVelocityEngine; - + /** Velocity EventCartridge for handling event */ EventCartridge eventCartridge; /** * Initialize servlet, BridgesVelocityViewServlet, and VelocityViewServlet. - * + * * @see org.apache.velocity.tools.view.servlet.VelocityViewServlet.init() - * - * @param config servlet configuation + * + * @param config + * servlet configuation */ public void init(ServletConfig config) throws ServletException { @@ -144,42 +156,60 @@ // get jetspeed component manager configuration for decorations ComponentManager cm = Jetspeed.getComponentManager(); - int count =0; - while(cm == null) { - try { + int count = 0; + while (cm == null) + { + try + { Thread.sleep(200); - } catch(InterruptedException ie) { - } + catch (InterruptedException ie) + { + + } cm = Jetspeed.getComponentManager(); - if( count > 5 ) { + if (count > 5) + { if (null == cm) - throw new ServletException("Could not get Jetspeed Component Manager after "+count+"tries"); + throw new ServletException( + "Could not get Jetspeed Component Manager after " + + count + "tries"); } count++; - + } - decorationLocator = (TemplateLocator) cm.getComponent("DecorationLocator"); + decorationLocator = (TemplateLocator) cm + .getComponent("DecorationLocator"); // initialize thread safe velocity engine cache - int cacheSize = (int) getLongInitParameter(config, CACHE_SIZE_PARAMETER, DEFAULT_CACHE_SIZE); + int cacheSize = (int) getLongInitParameter(config, + CACHE_SIZE_PARAMETER, DEFAULT_CACHE_SIZE); velocityEngineConfigCache = new LRUMap(cacheSize); - velocityEngineCache = new LRUMap(cacheSize/2); - + velocityEngineCache = new LRUMap(cacheSize / 2); + eventCartridge = new EventCartridge(); - // setup NullSetEventHandler to ignore those pesky "ERROR velocity - RHS of #set statement is null. Context will not be modified." + // setup NullSetEventHandler to ignore those pesky "ERROR velocity - RHS + // of #set statement is null. Context will not be modified." eventCartridge.addEventHandler(new NullSetEventHandler() { - public boolean shouldLogOnNullSet(String lhs, String rhs) { return false; } + + public boolean shouldLogOnNullSet(String lhs, String rhs) + { + return false; + } }); // initialize velocity engine cache validation interval - cacheValidationInterval = getLongInitParameter(config, CACHE_VALIDATION_INTERVAL_PARAMETER, DEFAULT_CACHE_VALIDATION_INTERVAL); + cacheValidationInterval = getLongInitParameter(config, + CACHE_VALIDATION_INTERVAL_PARAMETER, + DEFAULT_CACHE_VALIDATION_INTERVAL); } /** - * overriding VelocityViewServlet initialization of global Velocity to properly provide our own velocity.properties - * so to prevent an ERROR logging for not finding the default global VM_global_library.vm (which isn't available). + * overriding VelocityViewServlet initialization of global Velocity to + * properly provide our own velocity.properties so to prevent an ERROR + * logging for not finding the default global VM_global_library.vm (which + * isn't available). */ protected void initVelocity(ServletConfig config) throws ServletException { @@ -190,93 +220,109 @@ // if the user points commons-logging to the LogSystemCommonsLog LogSystemCommonsLog.setVelocityEngine(velocity); - velocity.setApplicationAttribute(SERVLET_CONTEXT_KEY, getServletContext()); + velocity.setApplicationAttribute(SERVLET_CONTEXT_KEY, + getServletContext()); // default to servletlogger, which logs to the servlet engines log - velocity.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.tools.view.servlet.ServletLogger"); + velocity.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, + "org.apache.velocity.tools.view.servlet.ServletLogger"); // by default, load resources with webapp resource loader velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "webapp"); - velocity.setProperty("webapp.resource.loader.class", - WebappLoader.class.getName()); + velocity.setProperty("webapp.resource.loader.class", WebappLoader.class + .getName()); // Try reading an overriding Velocity configuration try { ExtendedProperties p = loadConfiguration(config); p.addProperty("velocimacro.library", "/WEB-INF/jetspeed_macros.vm"); - p.setProperty("file.resource.loader.path", getServletContext().getRealPath("/")); + p.setProperty("file.resource.loader.path", getServletContext() + .getRealPath("/")); velocity.setExtendedProperties(p); } - catch(Exception e) + catch (Exception e) { - getServletContext().log("VelocityViewServlet: Unable to read Velocity configuration file: "+e); - getServletContext().log("VelocityViewServlet: Using default Velocity configuration."); - } + getServletContext().log( + "VelocityViewServlet: Unable to read Velocity configuration file: " + + e); + getServletContext() + .log( + "VelocityViewServlet: Using default Velocity configuration."); + } // now all is ready - init Velocity try { velocity.init(); } - catch(Exception e) + catch (Exception e) { - getServletContext().log("VelocityViewServlet: PANIC! unable to init() - "+e); + getServletContext().log( + "VelocityViewServlet: PANIC! unable to init() - " + e); throw new ServletException(e); } } - + /** * Handle the template processing request. - * + * * @see org.apache.velocity.tools.view.servlet.VelocityViewServlet.handleRequest() - * - * @param request client request - * @param response client response - * @param ctx VelocityContext to fill + * + * @param request + * client request + * @param response + * client response + * @param ctx + * VelocityContext to fill * @return Velocity Template object or null */ - protected Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) throws Exception + protected Template handleRequest(HttpServletRequest request, + HttpServletResponse response, Context ctx) throws Exception { - RequestContext requestContext = (RequestContext)request.getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); - if(requestContext == null) - { - throw new IllegalStateException("JetspeedVelocityViewServlet unable to handle request because there is no RequestContext in "+ - "the HttpServletRequest."); - } - - // hook up eventHandlers to the context, specifically our own IgnoringNullSetEventHandling + RequestContext requestContext = (RequestContext) request + .getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); + if (requestContext == null) { throw new IllegalStateException( + "JetspeedVelocityViewServlet unable to handle request because there is no RequestContext in " + + "the HttpServletRequest."); } + + // hook up eventHandlers to the context, specifically our own + // IgnoringNullSetEventHandling eventCartridge.attachToContext(ctx); - - JetspeedDesktopContext desktopContext = (JetspeedDesktopContext)request.getAttribute(JetspeedDesktopContext.DESKTOP_CONTEXT_ATTRIBUTE); + + JetspeedDesktopContext desktopContext = (JetspeedDesktopContext) request + .getAttribute(JetspeedDesktopContext.DESKTOP_CONTEXT_ATTRIBUTE); if (desktopContext != null) { // standard render request and response also available in context - ctx.put(JetspeedDesktopContext.DESKTOP_CONTEXT_ATTRIBUTE, desktopContext); + ctx.put(JetspeedDesktopContext.DESKTOP_CONTEXT_ATTRIBUTE, + desktopContext); ctx.put("JS2RequestContext", requestContext); - + // setup TLS for Context propagation - handlingRequestContext.set(ctx); - return super.handleRequest(request, response, ctx); + handlingRequestContext.set(ctx); + return super.handleRequest(request, response, ctx); } // configure velocity context - PortletRequest renderRequest = (PortletRequest) request.getAttribute(Constants.PORTLET_REQUEST); - RenderResponse renderResponse = (RenderResponse) request.getAttribute(Constants.PORTLET_RESPONSE); - PortletConfig portletConfig = (PortletConfig) request.getAttribute(Constants.PORTLET_CONFIG); + PortletRequest renderRequest = (PortletRequest) request + .getAttribute(Constants.PORTLET_REQUEST); + RenderResponse renderResponse = (RenderResponse) request + .getAttribute(Constants.PORTLET_RESPONSE); + PortletConfig portletConfig = (PortletConfig) request + .getAttribute(Constants.PORTLET_CONFIG); if (renderRequest != null) { renderRequest.setAttribute(VELOCITY_CONTEXT_ATTR, ctx); } - - JetspeedVelocityPowerTool jpt = (JetspeedVelocityPowerTool) renderRequest.getAttribute(PortalReservedParameters.JETSPEED_POWER_TOOL_REQ_ATTRIBUTE); - if(jpt == null) - { - throw new IllegalStateException("JetspeedVelocityViewServlet unable to handle request because there is no JetspeedPowerTool in "+ - "the HttpServletRequest."); - } - + + JetspeedVelocityPowerTool jpt = (JetspeedVelocityPowerTool) renderRequest + .getAttribute(PortalReservedParameters.JETSPEED_POWER_TOOL_REQ_ATTRIBUTE); + if (jpt == null) { throw new IllegalStateException( + "JetspeedVelocityViewServlet unable to handle request because there is no JetspeedPowerTool in " + + "the HttpServletRequest."); } + jpt.setVelocityContext(ctx); - ctx.put("jetspeed", jpt); + ctx.put("jetspeed", jpt); ctx.put("JS2RequestContext", requestContext); ctx.put("renderRequest", renderRequest); ctx.put("renderResponse", renderResponse); @@ -291,32 +337,38 @@ StringBuffer appRoot = new StringBuffer(); if (!requestContext.getPortalURL().isRelativeOnly()) { - appRoot.append(request.getScheme()).append("://").append(request.getServerName()).append(":").append(request.getServerPort()); + appRoot.append(request.getScheme()).append("://").append( + request.getServerName()).append(":").append( + request.getServerPort()); } appRoot.append(renderRequest.getContextPath()); - ctx.put("appRoot", appRoot.toString()); - - + ctx.put("appRoot", appRoot.toString()); + // setup TLS for Context propagation handlingRequestContext.set(ctx); - // handle request normally + // handle request normally return super.handleRequest(request, response, ctx); } /** * Retrieves the requested template. - * + * * @see org.apache.velocity.tools.view.servlet.VelocityViewServlet.getTemplate() - * - * @param name The file name of the template to retrieve relative to the template root. + * + * @param name + * The file name of the template to retrieve relative to the + * template root. * @return The requested template. - * @throws ResourceNotFoundException if template not found from any available source. - * @throws ParseErrorException if template cannot be parsed due to syntax (or other) error. - * @throws Exception if an error occurs in template initialization + * @throws ResourceNotFoundException + * if template not found from any available source. + * @throws ParseErrorException + * if template cannot be parsed due to syntax (or other) error. + * @throws Exception + * if an error occurs in template initialization */ - public Template getTemplate(String name) - throws ResourceNotFoundException, ParseErrorException, Exception + public Template getTemplate(String name) throws ResourceNotFoundException, + ParseErrorException, Exception { // retrieve Context to lookup appropriate velocity engine Context ctx = (Context) handlingRequestContext.get(); @@ -337,18 +389,24 @@ /** * Retrieves the requested template with the specified character encoding. - * + * * @see org.apache.velocity.tools.view.servlet.VelocityViewServlet.getTemplate() - * - * @param name The file name of the template to retrieve relative to the template root. - * @param encoding the character encoding of the template + * + * @param name + * The file name of the template to retrieve relative to the + * template root. + * @param encoding + * the character encoding of the template * @return The requested template. - * @throws ResourceNotFoundException if template not found from any available source. - * @throws ParseErrorException if template cannot be parsed due to syntax (or other) error. - * @throws Exception if an error occurs in template initialization + * @throws ResourceNotFoundException + * if template not found from any available source. + * @throws ParseErrorException + * if template cannot be parsed due to syntax (or other) error. + * @throws Exception + * if an error occurs in template initialization */ public Template getTemplate(String name, String encoding) - throws ResourceNotFoundException, ParseErrorException, Exception + throws ResourceNotFoundException, ParseErrorException, Exception { // retrieve Context to lookup appropriate velocity engine Context ctx = (Context) handlingRequestContext.get(); @@ -369,73 +427,85 @@ /** * Get VelocityEngine for template access. - * - * @param ctx the velocity context. + * + * @param ctx + * the velocity context. * @return The VelocityEngine or null. */ private VelocityEngine getVelocityEngine(Context ctx) { - RequestContext requestContext = (RequestContext) ctx.get("JS2RequestContext"); - JetspeedDesktopContext desktopContext = (JetspeedDesktopContext)requestContext.getRequest().getAttribute(JetspeedDesktopContext.DESKTOP_CONTEXT_ATTRIBUTE); + RequestContext requestContext = (RequestContext) ctx + .get("JS2RequestContext"); + JetspeedDesktopContext desktopContext = (JetspeedDesktopContext) requestContext + .getRequest().getAttribute( + JetspeedDesktopContext.DESKTOP_CONTEXT_ATTRIBUTE); if (desktopContext != null) { if (defaultVelocityEngine == null) { - defaultVelocityEngine = initVelocity((TemplateDescriptor)null); + defaultVelocityEngine = initVelocity((TemplateDescriptor) null); } - return defaultVelocityEngine; - } + return defaultVelocityEngine; + } // get render request and request context from Context RenderRequest renderRequest = (RenderRequest) ctx.get("renderRequest"); - JetspeedVelocityPowerTool jpt = (JetspeedVelocityPowerTool) ctx.get("jetspeed"); + JetspeedVelocityPowerTool jpt = (JetspeedVelocityPowerTool) ctx + .get("jetspeed"); if ((renderRequest != null) && (requestContext != null)) { // get layout type and decoration, fallback to // page default decorations - Fragment layout = (Fragment) renderRequest.getAttribute(JetspeedVelocityPowerTool.LAYOUT_ATTR); + Fragment layout = (Fragment) renderRequest + .getAttribute(JetspeedVelocityPowerTool.LAYOUT_ATTR); if (layout == null) { - // layout = (Fragment) renderRequest.getAttribute(JetspeedPowerTool.FRAGMENT_ATTR); + // layout = (Fragment) + // renderRequest.getAttribute(JetspeedPowerTool.FRAGMENT_ATTR); layout = jpt.getCurrentFragment(); } String layoutType = layout.getType(); String layoutDecoration = layout.getDecorator(); if (layoutDecoration == null) { - //Page page = (Page) renderRequest.getAttribute(PortalReservedParameters.PAGE_ATTRIBUTE_KEY); + // Page page = (Page) + // renderRequest.getAttribute(PortalReservedParameters.PAGE_ATTRIBUTE_KEY); Page page = requestContext.getPage(); - layoutDecoration = page.getEffectiveDefaultDecorator(layoutType); + layoutDecoration = page + .getEffectiveDefaultDecorator(layoutType); } - + // get layout capabilites and locale CapabilityMap capabilityMap = requestContext.getCapabilityMap(); Locale locale = requestContext.getLocale(); - String layoutMediaType = capabilityMap.getPreferredMediaType().getName(); + String layoutMediaType = capabilityMap.getPreferredMediaType() + .getName(); String layoutLanguage = locale.getLanguage(); String layoutCountry = locale.getCountry(); - + // lookup cache config based on decoration cache key - String cacheKey = layoutDecoration + ":" + layoutType + ":" + layoutMediaType + ":" + layoutLanguage + ":" + layoutCountry; + String cacheKey = layoutDecoration + ":" + layoutType + ":" + + layoutMediaType + ":" + layoutLanguage + ":" + + layoutCountry; VelocityEngineConfig config = null; synchronized (velocityEngineConfigCache) { - config = (VelocityEngineConfig) velocityEngineConfigCache.get(cacheKey); + config = (VelocityEngineConfig) velocityEngineConfigCache + .get(cacheKey); } - + // validate cached configuration and return VelocityEngine if cached long now = System.currentTimeMillis(); - if ((config != null) && ((cacheValidationInterval == -1) || (now <= (config.lastValidated + cacheValidationInterval)))) + if ((config != null) + && ((cacheValidationInterval == -1) || (now <= (config.lastValidated + cacheValidationInterval)))) { if (config.macros != null) { synchronized (velocityEngineCache) { // use cached velocity engine if available - VelocityEngine velocity = (VelocityEngine) velocityEngineCache.get(config.macros.getAbsolutePath()); - if (velocity != null) - { - return velocity; - } + VelocityEngine velocity = (VelocityEngine) velocityEngineCache + .get(config.macros.getAbsolutePath()); + if (velocity != null) { return velocity; } } } else @@ -446,16 +516,16 @@ // construct and cache default velocity engine if (defaultVelocityEngine == null) { - defaultVelocityEngine = initVelocity((TemplateDescriptor)null); + defaultVelocityEngine = initVelocity((TemplateDescriptor) null); } return defaultVelocityEngine; } } } - + // load and/or verify decorator macros configuration TemplateDescriptor macrosDescriptor = null; - + // create reusable decoration base descriptor LocatorDescriptor descriptor = null; try @@ -464,27 +534,32 @@ } catch (TemplateLocatorException tle) { - log.error("getVelocityEngine(): unable create base descriptor", tle); + log.error("getVelocityEngine(): unable create base descriptor", + tle); } descriptor.setMediaType(layoutMediaType); descriptor.setCountry(layoutCountry); descriptor.setLanguage(layoutLanguage); descriptor.setType(layoutType); - + // get decoration configuration properties descriptor - descriptor.setName(layoutDecoration + "/" + JetspeedVelocityPowerTool.DECORATOR_TYPE + ".properties"); + descriptor.setName(layoutDecoration + "/" + + JetspeedVelocityPowerTool.DECORATOR_TYPE + ".properties"); TemplateDescriptor propertiesDescriptor = null; try { - propertiesDescriptor = decorationLocator.locateTemplate(descriptor); + propertiesDescriptor = decorationLocator + .locateTemplate(descriptor); } catch (TemplateLocatorException tle) { // fallback to generic template type try { - descriptor.setType(JetspeedVelocityPowerTool.GENERIC_TEMPLATE_TYPE); - propertiesDescriptor = decorationLocator.locateTemplate(descriptor); + descriptor + .setType(JetspeedVelocityPowerTool.GENERIC_TEMPLATE_TYPE); + propertiesDescriptor = decorationLocator + .locateTemplate(descriptor); } catch (TemplateLocatorException tleFallback) { @@ -496,11 +571,15 @@ { try { - configuration = new PropertiesConfiguration(propertiesDescriptor.getAbsolutePath()); + configuration = new PropertiesConfiguration( + propertiesDescriptor.getAbsolutePath()); } catch (ConfigurationException ce) { - log.warn("getVelocityEngine(): unable read decorator properties from " + propertiesDescriptor.getAbsolutePath(), ce); + log.warn( + "getVelocityEngine(): unable read decorator properties from " + + propertiesDescriptor.getAbsolutePath(), + ce); } } if (configuration != null) @@ -508,26 +587,36 @@ // get decoration template macros extension and suffix String ext = configuration.getString("template.extension"); String macros = configuration.getString("template.macros"); - + // get decoration template macros descriptor if defined - if ((ext != null) && (ext.length() > 0) && (macros != null) && (macros.length() > 0)) + if ((ext != null) && (ext.length() > 0) && (macros != null) + && (macros.length() > 0)) { - descriptor.setName(layoutDecoration + "/" + JetspeedVelocityPowerTool.DECORATOR_TYPE + macros + ext); + descriptor.setName(layoutDecoration + "/" + + JetspeedVelocityPowerTool.DECORATOR_TYPE + macros + + ext); try { - macrosDescriptor = decorationLocator.locateTemplate(descriptor); + macrosDescriptor = decorationLocator + .locateTemplate(descriptor); } catch (TemplateLocatorException tle) { - // fallback to extends decoration, (assume macros named the + // fallback to extends decoration, (assume macros named + // the // same in the parent decoration as configured here) try { String parent = configuration.getString("extends"); if ((parent != null) && (parent.length() > 0)) { - descriptor.setName(parent + "/" + JetspeedVelocityPowerTool.DECORATOR_TYPE + macros + ext); - macrosDescriptor = decorationLocator.locateTemplate(descriptor); + descriptor + .setName(parent + + "/" + + JetspeedVelocityPowerTool.DECORATOR_TYPE + + macros + ext); + macrosDescriptor = decorationLocator + .locateTemplate(descriptor); } } catch (TemplateLocatorException tleExtends) @@ -536,25 +625,27 @@ } } } - + // compare located macros file with cached version // to validate/refresh cached config and velocity engine boolean newVelocityEngineConfig = false; boolean forceVelocityEngineRefresh = false; if (config == null) { - config = new VelocityEngineConfig(layoutDecoration, layoutType, layoutMediaType, layoutLanguage, layoutCountry); + config = new VelocityEngineConfig(layoutDecoration, layoutType, + layoutMediaType, layoutLanguage, layoutCountry); synchronized (velocityEngineConfigCache) { velocityEngineConfigCache.put(cacheKey, config); } newVelocityEngineConfig = true; } - if (((macrosDescriptor == null) && (config.macros != null)) || - ((macrosDescriptor != null) && (config.macros == null)) || - ((macrosDescriptor != null) && (config.macros != null) && - (!macrosDescriptor.getAbsolutePath().equals(config.macros.getAbsolutePath()) || - (config.macros.lastModified() != config.macrosLastModified)))) + if (((macrosDescriptor == null) && (config.macros != null)) + || ((macrosDescriptor != null) && (config.macros == null)) + || ((macrosDescriptor != null) && (config.macros != null) && (!macrosDescriptor + .getAbsolutePath().equals( + config.macros.getAbsolutePath()) || (config.macros + .lastModified() != config.macrosLastModified)))) { // set or reset configuration cache entry config.lastValidated = now; @@ -591,7 +682,8 @@ if (!forceVelocityEngineRefresh) { // use cached velocity engine - velocity = (VelocityEngine) velocityEngineCache.get(config.macros.getAbsolutePath()); + velocity = (VelocityEngine) velocityEngineCache + .get(config.macros.getAbsolutePath()); } if (velocity == null) { @@ -599,7 +691,8 @@ velocity = initVelocity(macrosDescriptor); if (velocity != null) { - velocityEngineCache.put(config.macros.getAbsolutePath(), velocity); + velocityEngineCache.put(config.macros + .getAbsolutePath(), velocity); } } } @@ -613,12 +706,12 @@ // construct and cache default velocity engine if (defaultVelocityEngine == null) { - defaultVelocityEngine = initVelocity((TemplateDescriptor)null); + defaultVelocityEngine = initVelocity((TemplateDescriptor) null); } velocity = defaultVelocityEngine; } } - + // return velocity engine for validated configuration return velocity; } @@ -627,10 +720,11 @@ /** * Initialize new velocity instance using specified macros template. - * + * * @see org.apache.velocity.tools.view.servlet.VelocityViewServlet.initVelocity() - * - * @param macros template descriptor. + * + * @param macros + * template descriptor. * @return new VelocityEngine instance. */ private VelocityEngine initVelocity(TemplateDescriptor macros) @@ -639,48 +733,63 @@ { // create new instance to initialize VelocityEngine velocity = new VelocityEngine(); - + // initialize new instance as is done with the default // velocity singleton, appending macros template to the // base configuration velocimacro.library property - velocity.setApplicationAttribute(SERVLET_CONTEXT_KEY, getServletContext()); - velocity.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.tools.view.servlet.ServletLogger"); + velocity.setApplicationAttribute(SERVLET_CONTEXT_KEY, + getServletContext()); + velocity.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS, + "org.apache.velocity.tools.view.servlet.ServletLogger"); ExtendedProperties configuration = loadConfiguration(getServletConfig()); if (macros != null) { - configuration.addProperty("velocimacro.library", macros.getAppRelativePath()); + configuration.addProperty("velocimacro.library", macros + .getAppRelativePath()); } - configuration.setProperty("file.resource.loader.path", getServletContext().getRealPath("/")); + configuration.setProperty("file.resource.loader.path", + getServletContext().getRealPath("/")); velocity.setExtendedProperties(configuration); // initialize and return velocity engine velocity.init(); if (macros != null) { - log.debug("initVelocity(): create new VelocityEngine instance to support " + macros.getAppRelativePath() + " decoration template macros"); + log + .debug("initVelocity(): create new VelocityEngine instance to support " + + macros.getAppRelativePath() + + " decoration template macros"); } else { - log.debug("initVelocity(): create new default VelocityEngine instance"); + log + .debug("initVelocity(): create new default VelocityEngine instance"); } return velocity; } catch (Exception e) { - log.error("initVelocity(): unable to initialize velocity engine instance, using default singleton", e); + log + .error( + "initVelocity(): unable to initialize velocity engine instance, using default singleton", + e); } return null; } /** * Utility to get long init parameters. - * - * @param config servlet config - * @param name of init parameter - * @param defaultValue value + * + * @param config + * servlet config + * @param name + * of init parameter + * @param defaultValue + * value * @return parameter value */ - private long getLongInitParameter(ServletConfig config, String name, long defaultValue) + private long getLongInitParameter(ServletConfig config, String name, + long defaultValue) { String value = config.getInitParameter(name); if ((value == null) || (value.length() == 0)) @@ -699,11 +808,9 @@ } return defaultValue; } - - protected void error(HttpServletRequest request, - HttpServletResponse response, - Exception e) - throws ServletException + + protected void error(HttpServletRequest request, + HttpServletResponse response, Exception e) throws ServletException { try { @@ -716,8 +823,8 @@ } catch (Exception e2) { - log.error("Error writing error message to vm template ", e2); - } + log.error("Error writing error message to vm template ", e2); + } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/RemoteContentTool.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/RemoteContentTool.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/java/org/apache/jetspeed/velocity/RemoteContentTool.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /* * Created on Jul 28, 2004 * @@ -31,11 +31,12 @@ * ContentTool *

        *

        - * + * *

        + * * @author Scott T. Weaver * @version $Id: RemoteContentTool.java 516881 2007-03-11 10:34:21Z ate $ - * + * */ public class RemoteContentTool implements ViewTool { @@ -44,20 +45,19 @@ *

        * init *

        - * + * * @see org.apache.velocity.tools.view.tools.ViewTool#init(java.lang.Object) * @param arg0 */ - public void init( Object arg0 ) + public void init(Object arg0) { - - + } - + public String include(String remoteContentUrl) { GetMethod remoteContentGet = null; - + try { HttpClient client = new HttpClient(); @@ -67,17 +67,15 @@ } catch (Exception e) { - return e.toString()+" message:"+ e.getMessage(); + return e.toString() + " message:" + e.getMessage(); } finally { - if(remoteContentGet != null) + if (remoteContentGet != null) { remoteContentGet.releaseConnection(); } } } - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/AbstractPortalContainerTestCase.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/AbstractPortalContainerTestCase.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/AbstractPortalContainerTestCase.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,7 +16,6 @@ */ package org.apache.jetspeed; - import org.apache.jetspeed.container.window.PortletWindowAccessor; import org.apache.jetspeed.container.window.impl.PortletWindowAccessorImpl; import org.apache.pluto.PortletContainer; @@ -25,8 +24,10 @@ * @author Scott T. Weaver * */ -public class AbstractPortalContainerTestCase extends AbstractRequestContextTestCase +public class AbstractPortalContainerTestCase extends + AbstractRequestContextTestCase { + protected PortletWindowAccessor windowAccessor; protected PortletContainer portletContainer; @@ -40,8 +41,6 @@ { super.setUp(); windowAccessor = new PortletWindowAccessorImpl(entityAccess, - PortletFactoryMock.instance, - new HashMapWindowCache(), - true); + PortletFactoryMock.instance, new HashMapWindowCache(), true); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/AbstractRequestContextTestCase.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/AbstractRequestContextTestCase.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/AbstractRequestContextTestCase.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,7 +16,6 @@ */ package org.apache.jetspeed; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -28,8 +27,9 @@ protected String[] getConfigurations() { -// File webapp = new File("../../src/webapp"); -// System.setProperty(JetspeedEngineConstants.APPLICATION_ROOT_KEY, webapp.getAbsolutePath()); + // File webapp = new File("../../src/webapp"); + // System.setProperty(JetspeedEngineConstants.APPLICATION_ROOT_KEY, + // webapp.getAbsolutePath()); String[] confs = super.getConfigurations(); List confList = new ArrayList(Arrays.asList(confs)); confList.add("rc2.xml"); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/HashMapWindowCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/HashMapWindowCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/HashMapWindowCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,29 +27,30 @@ import org.apache.pluto.om.window.PortletWindow; /** - * This implementation of {@link PortletWindowCache} is to be used ONLY for testing purposes. + * This implementation of {@link PortletWindowCache} is to be used ONLY for + * testing purposes. * * @author Scott T. Weaver - * + * */ public class HashMapWindowCache implements PortletWindowCache { + private Map portletEntityToWindow = new HashMap(); - private Map portletEntityToWindow = new HashMap(); private Map windows = new HashMap(); - + public Set getAllPortletWindows() { Set windowSet = new HashSet(); - + Iterator itr = windows.entrySet().iterator(); - while(itr.hasNext()) + while (itr.hasNext()) { - Map.Entry entry = (Entry) itr.next(); - windowSet.add((PortletWindow)entry.getValue()); + Map.Entry entry = (Entry) itr.next(); + windowSet.add((PortletWindow) entry.getValue()); } - + return windowSet; } @@ -60,9 +61,10 @@ public PortletWindow getPortletWindowByEntityId(String portletEntityId) { - if(portletEntityToWindow.containsKey(portletEntityId)) + if (portletEntityToWindow.containsKey(portletEntityId)) { - return (PortletWindow) windows.get((String) portletEntityToWindow.get(portletEntityId)); + return (PortletWindow) windows.get((String) portletEntityToWindow + .get(portletEntityId)); } else { @@ -73,17 +75,19 @@ public void putPortletWindow(PortletWindow window) { windows.put(window.getId().toString(), window); - portletEntityToWindow.put(window.getPortletEntity().getId().toString(), window.getId().toString()); + portletEntityToWindow.put(window.getPortletEntity().getId().toString(), + window.getId().toString()); } public void removePortletWindow(String windowId) { PortletWindow window = (PortletWindow) windows.get(windowId); - if(window != null) + if (window != null) { windows.remove(windowId); - portletEntityToWindow.remove(window.getPortletEntity().getId().toString()); + portletEntityToWindow.remove(window.getPortletEntity().getId() + .toString()); } } @@ -91,8 +95,8 @@ public void removePortletWindowByPortletEntityId(String portletEntityId) { PortletWindow window = getPortletWindowByEntityId(portletEntityId); - if(window != null) - { + if (window != null) + { removePortletWindow(window.getId().toString()); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/PortalTestConstants.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/PortalTestConstants.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/PortalTestConstants.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,9 +25,10 @@ */ public class PortalTestConstants { + public final static String JETSPEED_PROPERTIES_PATH = "../../src/webapp/WEB-INF/conf/jetspeed.properties"; - + public final static String PORTAL_WEBAPP_PATH = "../../src/webapp"; - + public static final String JETSPEED_APPLICATION_ROOT = "../../src/webapp"; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/PortletFactoryMock.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/PortletFactoryMock.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/PortletFactoryMock.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,19 +27,40 @@ public final class PortletFactoryMock implements PortletFactory { - public void registerPortletApplication(PortletApplication pa, ClassLoader paClassLoader){} - public void unregisterPortletApplication(PortletApplication pa){} + public void registerPortletApplication(PortletApplication pa, + ClassLoader paClassLoader) + { + } - public ClassLoader getPortletApplicationClassLoader(PortletApplication pa){return null;} + public void unregisterPortletApplication(PortletApplication pa) + { + } - public PortletInstance getPortletInstance(ServletContext servletContext, PortletDefinition pd) throws PortletException{return null;} + public ClassLoader getPortletApplicationClassLoader(PortletApplication pa) + { + return null; + } - public PreferencesValidator getPreferencesValidator(PortletDefinition pd){return null;} + public PortletInstance getPortletInstance(ServletContext servletContext, + PortletDefinition pd) throws PortletException + { + return null; + } - public boolean isPortletApplicationRegistered(PortletApplication pa){return true;} - + public PreferencesValidator getPreferencesValidator(PortletDefinition pd) + { + return null; + } + + public boolean isPortletApplicationRegistered(PortletApplication pa) + { + return true; + } + public static final PortletFactoryMock instance = new PortletFactoryMock(); - - public void updatePortletConfig(PortletDefinition pd) {} + + public void updatePortletConfig(PortletDefinition pd) + { + } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/administration/TestPortalAdministrationImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/administration/TestPortalAdministrationImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/administration/TestPortalAdministrationImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.administration; import java.util.ArrayList; @@ -28,25 +28,22 @@ import org.apache.jetspeed.aggregator.TestWorkerMonitor; +public class TestPortalAdministrationImpl extends TestCase -public class TestPortalAdministrationImpl extends TestCase - { - public static void main(String args[]) { - junit.awtui.TestRunner.main(new String[] { TestWorkerMonitor.class.getName()}); + junit.awtui.TestRunner.main(new String[] + {TestWorkerMonitor.class.getName()}); } protected void setUp() throws Exception { super.setUp(); - - - + } - + public static Test suite() { // All methods starting with "test" will be executed in the test suite. @@ -55,38 +52,43 @@ public void testPasswordGen() throws Exception { - PortalAdministrationImpl pai = new PortalAdministrationImpl(null,null,null,null,null,null,null,null); + PortalAdministrationImpl pai = new PortalAdministrationImpl(null, null, + null, null, null, null, null, null); String newPassword = pai.generatePassword(); - assertNotNull("new password was NULL!!!",newPassword); - assertTrue("password is not long enough",(newPassword.length() > 4) ); - + assertNotNull("new password was NULL!!!", newPassword); + assertTrue("password is not long enough", (newPassword.length() > 4)); + } - - public void xtestSendEmail() throws Exception { - PortalAdministrationImpl pai = new PortalAdministrationImpl(null,null,null,null,null,null,null,null); - pai.sendEmail("chris ¡÷ bluesunrise.com","this is a unittest","chris ¡÷ bluesunrise.com","this is the content of the message"); - + + public void xtestSendEmail() throws Exception + { + PortalAdministrationImpl pai = new PortalAdministrationImpl(null, null, + null, null, null, null, null, null); + pai.sendEmail("chris ¡÷ bluesunrise.com", "this is a unittest", + "chris ¡÷ bluesunrise.com", "this is the content of the message"); + } - + // this needs too much init to test easily right now public void xtestRegUser() throws Exception { - PortalAdministrationImpl pai = new PortalAdministrationImpl(null,null,null,null,null,null,null,null); - String user = "user"+(Math.abs(new Date().getTime())); + PortalAdministrationImpl pai = new PortalAdministrationImpl(null, null, + null, null, null, null, null, null); + String user = "user" + (Math.abs(new Date().getTime())); String password = "password"; List emptyList = new ArrayList(); Map emptyMap = new HashMap(); Map userAttributes = new HashMap(); String emailTemplate = ""; - pai.registerUser(user, - password, - emptyList, - emptyList, - userAttributes, // note use of only PLT.D values here. - emptyMap, - emailTemplate); - + pai.registerUser(user, password, emptyList, emptyList, userAttributes, // note + // use + // of + // only + // PLT.D + // values + // here. + emptyMap, emailTemplate); + } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/MockRenderJob.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/MockRenderJob.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/MockRenderJob.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,7 +24,6 @@ import org.apache.pluto.om.portlet.PortletDefinition; import org.apache.pluto.om.window.PortletWindow; - /** * MockRenderJob * @@ -32,15 +31,19 @@ * @version $Id: $ */ -public class MockRenderJob implements RenderingJob +public class MockRenderJob implements RenderingJob { + private long mockTime; + private String jobName; + private PortletWindow window; protected long startTimeMillis = 0; + protected long timeout; - + public MockRenderJob(String jobName, long mockTime, PortletWindow window) { this.mockTime = mockTime; @@ -51,38 +54,44 @@ /** * Sets portlet timout in milliseconds. */ - public void setTimeout(long timeout) { + public void setTimeout(long timeout) + { this.timeout = timeout; } /** * Gets portlet timout in milliseconds. */ - public long getTimeout() { + public long getTimeout() + { return this.timeout; } /** * Checks if the portlet rendering is timeout */ - public boolean isTimeout() { - if ((this.timeout > 0) && (this.startTimeMillis > 0)) { - return (System.currentTimeMillis() - this.startTimeMillis > this.timeout); - } + public boolean isTimeout() + { + if ((this.timeout > 0) && (this.startTimeMillis > 0)) { return (System + .currentTimeMillis() + - this.startTimeMillis > this.timeout); } return false; } - + public void run() - { - if (this.timeout > 0) { + { + if (this.timeout > 0) + { this.startTimeMillis = System.currentTimeMillis(); } execute(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.aggregator.RenderingJob#execute() */ public void execute() @@ -99,7 +108,9 @@ System.out.println("mock job completed " + jobName); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.aggregator.RenderingJob#getWindow() */ public PortletWindow getWindow() @@ -108,7 +119,9 @@ return window; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.aggregator.RenderingJob#getPortletContent() */ public PortletContent getPortletContent() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/TestAggregator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/TestAggregator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/TestAggregator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -56,37 +56,55 @@ import com.mockrunner.mock.web.MockServletConfig; /** - *

        Test the aggregation service

        - * + *

        + * Test the aggregation service + *

        + * * @author David Sean Taylor * @version $Id: TestAggregator.java 517719 2007-03-13 15:05:48Z ate $ * */ public class TestAggregator extends TestCase { + private SpringEngineHelper engineHelper; + private Engine engine; + private PortletAggregator portletAggregator; + private PageAggregator pageAggregator; + private PageAggregator asyncPageAggregator; + private Profiler profiler; + private Capabilities capabilities; + private NavigationalStateComponent navComponent; + private PortletFactory portletFactory; + private ServletConfig servletConfig; + private ServletContext servletContext; + private PortletRegistry portletRegistry; + private RequestContextComponent rcc; + private String testPage = "/default-page.psml"; /** * Start the tests. - * - * @param args the arguments. Not used + * + * @param args + * the arguments. Not used */ public static void main(String args[]) { - junit.awtui.TestRunner.main(new String[] { TestAggregator.class.getName()}); + junit.awtui.TestRunner.main(new String[] + {TestAggregator.class.getName()}); } protected void setUp() throws Exception @@ -100,31 +118,42 @@ e.printStackTrace(); return; } - + HashMap context = new HashMap(); engineHelper = new SpringEngineHelper(context); engineHelper.setUp(); engine = (Engine) context.get(SpringEngineHelper.ENGINE_ATTR); - pageAggregator = (PageAggregator) engine.getComponentManager().getComponent(PageAggregator.class); - asyncPageAggregator = - (PageAggregator) engine.getComponentManager().getComponent("org.apache.jetspeed.aggregator.AsyncPageAggregator"); - portletAggregator = (PortletAggregator) engine.getComponentManager().getComponent(PortletAggregator.class); - - profiler = (Profiler) engine.getComponentManager().getComponent(Profiler.class); - capabilities = (Capabilities) engine.getComponentManager().getComponent(Capabilities.class); - navComponent = - (NavigationalStateComponent) engine.getComponentManager().getComponent(NavigationalStateComponent.class); + pageAggregator = (PageAggregator) engine.getComponentManager() + .getComponent(PageAggregator.class); + asyncPageAggregator = (PageAggregator) engine.getComponentManager() + .getComponent( + "org.apache.jetspeed.aggregator.AsyncPageAggregator"); + portletAggregator = (PortletAggregator) engine.getComponentManager() + .getComponent(PortletAggregator.class); + profiler = (Profiler) engine.getComponentManager().getComponent( + Profiler.class); + capabilities = (Capabilities) engine.getComponentManager() + .getComponent(Capabilities.class); + navComponent = (NavigationalStateComponent) engine + .getComponentManager().getComponent( + NavigationalStateComponent.class); + servletConfig = engine.getServletConfig(); servletContext = servletConfig.getServletContext(); - portletRegistry = (PortletRegistry) engine.getComponentManager().getComponent("portletRegistry"); - portletFactory = (PortletFactory) engine.getComponentManager().getComponent("portletFactory"); - rcc = (RequestContextComponent) engine.getComponentManager().getComponent("org.apache.jetspeed.request.RequestContextComponent"); + portletRegistry = (PortletRegistry) engine.getComponentManager() + .getComponent("portletRegistry"); + portletFactory = (PortletFactory) engine.getComponentManager() + .getComponent("portletFactory"); + rcc = (RequestContextComponent) engine.getComponentManager() + .getComponent( + "org.apache.jetspeed.request.RequestContextComponent"); File paRootDir = null; - paRootDir = new File("../../layout-portlets/target/jetspeed-layout-portlets"); + paRootDir = new File( + "../../layout-portlets/target/jetspeed-layout-portlets"); initPA("jetspeed-layouts", "/jetspeed-layouts", paRootDir); paRootDir = new File("../../applications/demo/target/demo"); @@ -132,11 +161,15 @@ paRootDir = new File("../../applications/j2-admin/target/j2-admin"); initPA("j2-admin", "/j2-admin", paRootDir); - - // j2-admin portlet needs user manager component, but the followings does not effect.. -// userManager = (UserManager) engine.getComponentManager().getComponent(UserManager.class); -// paContext.setAttribute(CommonPortletServices.CPS_USER_MANAGER_COMPONENT, userManager); -// assertEquals(userManager, paContext.getAttribute(CommonPortletServices.CPS_USER_MANAGER_COMPONENT)); + + // j2-admin portlet needs user manager component, but the followings + // does not effect.. + // userManager = (UserManager) + // engine.getComponentManager().getComponent(UserManager.class); + // paContext.setAttribute(CommonPortletServices.CPS_USER_MANAGER_COMPONENT, + // userManager); + // assertEquals(userManager, + // paContext.getAttribute(CommonPortletServices.CPS_USER_MANAGER_COMPONENT)); } public static Test suite() @@ -145,10 +178,10 @@ return new TestSuite(TestAggregator.class); } -// public void testBasic() throws Exception -// { -// doAggregation(false); -// } + // public void testBasic() throws Exception + // { + // doAggregation(false); + // } public void testParallelMode() throws Exception { @@ -176,45 +209,58 @@ final RequestContext requestContext = initRequestContext(); final Subject subject = SecurityHelper.createSubject("user"); - requestContext.getRequest().getSession().setAttribute(PortalReservedParameters.SESSION_KEY_SUBJECT, subject); + requestContext.getRequest().getSession().setAttribute( + PortalReservedParameters.SESSION_KEY_SUBJECT, subject); requestContext.setSubject(subject); - + ProfileLocator locator = profiler.createLocator(requestContext); HashMap locators = new HashMap(); locators.put(ProfileLocator.PAGE_LOCATOR, locator); requestContext.setProfileLocators(locators); - requestContext.setCapabilityMap(capabilities.getCapabilityMap("Mozilla/5")); - requestContext.setPortalURL(navComponent.createURL(requestContext.getRequest(), requestContext.getCharacterEncoding())); + requestContext.setCapabilityMap(capabilities + .getCapabilityMap("Mozilla/5")); + requestContext.setPortalURL(navComponent.createURL(requestContext + .getRequest(), requestContext.getCharacterEncoding())); - Exception ex = (Exception) JSSubject.doAsPrivileged(subject, new PrivilegedAction() - { - public Object run() + Exception ex = (Exception) JSSubject.doAsPrivileged(subject, + new PrivilegedAction() { - try { - PageManager pageManager = - (PageManager) engine.getComponentManager().getComponent(PageManager.class); - Page page = pageManager.getPage(testPage); - assertNotNull(page); - requestContext.setPage(new ContentPageImpl(page)); - if (!isParallelMode) { - pageAggregator.build(requestContext); - } else { - asyncPageAggregator.build(requestContext); + public Object run() + { + try + { + PageManager pageManager = (PageManager) engine + .getComponentManager().getComponent( + PageManager.class); + Page page = pageManager.getPage(testPage); + assertNotNull(page); + requestContext.setPage(new ContentPageImpl(page)); + + if (!isParallelMode) + { + pageAggregator.build(requestContext); + } + else + { + asyncPageAggregator.build(requestContext); + } + + MockHttpServletResponse rsp = (MockHttpServletResponse) requestContext + .getResponse(); + System.out.println(">>>> " + + rsp.getOutputStreamContent()); } - - MockHttpServletResponse rsp = (MockHttpServletResponse) requestContext.getResponse(); - System.out.println(">>>> " + rsp.getOutputStreamContent()); - } catch (Exception e) { - return e; + catch (Exception e) + { + return e; + } + return null; } - return null; - } - }, null); + }, null); - if (ex != null) - throw ex; + if (ex != null) throw ex; } private RequestContext initRequestContext() @@ -228,37 +274,43 @@ request.setSession(session); - //Principal p = new UserPrincipalImpl("user"); - //request.setUserPrincipal(p); + // Principal p = new UserPrincipalImpl("user"); + // request.setUserPrincipal(p); request.setScheme("http"); request.setContextPath("/jetspeed"); request.setServletPath("/portal" + testPage); request.setMethod("GET"); -// RequestContext rc = -// new JetspeedRequestContext(request, response, servletConfig, null); + // RequestContext rc = + // new JetspeedRequestContext(request, response, servletConfig, null); RequestContext rc = rcc.create(request, response, servletConfig); return rc; } - private ResourceLocatingServletContext initPA(String paName, String paContextPath, File paRootDir) + private ResourceLocatingServletContext initPA(String paName, + String paContextPath, File paRootDir) { - ResourceLocatingServletContext paContext = new ResourceLocatingServletContext(paRootDir, true); + ResourceLocatingServletContext paContext = new ResourceLocatingServletContext( + paRootDir, true); MockServletConfig paConfig = new MockServletConfig(); paConfig.setServletContext(paContext); - ((ResourceLocatingServletContext) servletContext).setContext(paContextPath, paContext); + ((ResourceLocatingServletContext) servletContext).setContext( + paContextPath, paContext); try { - ClassLoader paCl = createPAClassLoader(new File(paRootDir, "WEB-INF")); - PortletApplication pa = portletRegistry.getPortletApplication(paName); + ClassLoader paCl = createPAClassLoader(new File(paRootDir, + "WEB-INF")); + PortletApplication pa = portletRegistry + .getPortletApplication(paName); portletFactory.registerPortletApplication(pa, paCl); } catch (Exception e) { - System.out.println("Failed to register portlet application, " + paName + ": " + e); - } + System.out.println("Failed to register portlet application, " + + paName + ": " + e); + } return paContext; } @@ -270,30 +322,32 @@ ArrayList urls = new ArrayList(); File webInfClassesDir = null; - try + try { - webInfClassesDir = new File(webInfDir, "classes"); + webInfClassesDir = new File(webInfDir, "classes"); if (webInfClassesDir.isDirectory()) { urls.add(webInfClassesDir.toURL()); } - + File webInfLibDir = new File(webInfDir, "lib"); if (webInfLibDir.isDirectory()) { - File [] jars = webInfLibDir.listFiles(); + File[] jars = webInfLibDir.listFiles(); for (int i = 0; i < jars.length; i++) { File jar = jars[i]; urls.add(jar.toURL()); } } - - localPAClassLoader = - new URLClassLoader((URL[]) urls.toArray(new URL[urls.size()]), getClass().getClassLoader()); - } catch (Exception e) + + localPAClassLoader = new URLClassLoader((URL[]) urls + .toArray(new URL[urls.size()]), getClass().getClassLoader()); + } + catch (Exception e) { - throw new RuntimeException("Failed to create classloader for PA.", e); + throw new RuntimeException("Failed to create classloader for PA.", + e); } return localPAClassLoader; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/TestRenderer.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/TestRenderer.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/TestRenderer.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,23 +25,25 @@ /** * TestPortletRenderer - * + * * @author David Sean Taylor * @version $Id: TestRenderer.java 516448 2007-03-09 16:25:47Z ate $ */ public class TestRenderer extends AbstractPortalContainerTestCase { + protected PortletRenderer renderer; - - + /** * Start the tests. - * - * @param args the arguments. Not used + * + * @param args + * the arguments. Not used */ public static void main(String args[]) { - junit.awtui.TestRunner.main(new String[] { TestRenderer.class.getName()}); + junit.awtui.TestRunner.main(new String[] + {TestRenderer.class.getName()}); } protected void setUp() throws Exception @@ -49,15 +51,16 @@ super.setUp(); WorkerMonitor monitor = new WorkerMonitorImpl(5, 20, 5, 10); monitor.start(); - - renderer = new PortletRendererImpl(portletContainer, windowAccessor, monitor, null); + + renderer = new PortletRendererImpl(portletContainer, windowAccessor, + monitor, null); } /** * Creates the test suite. - * - * @return a test suite (TestSuite) that includes all methods - * starting with "test" + * + * @return a test suite (TestSuite) that includes all + * methods starting with "test" */ public static Test suite() { @@ -69,5 +72,5 @@ { assertNotNull("portlet renderer is null", renderer); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/TestWorkerMonitor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/TestWorkerMonitor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/aggregator/TestWorkerMonitor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -15,7 +15,7 @@ * limitations under the License. */ package org.apache.jetspeed.aggregator; - + import java.util.ArrayList; import java.util.List; @@ -28,32 +28,35 @@ import org.apache.pluto.om.window.PortletWindow; /** - *

        Test the aggregation service

        - * + *

        + * Test the aggregation service + *

        + * * @author David Sean Taylor * @version $Id: $ * */ public class TestWorkerMonitor extends TestCase -{ +{ + /** * Start the tests. - * - * @param args the arguments. Not used + * + * @param args + * the arguments. Not used */ public static void main(String args[]) { - junit.awtui.TestRunner.main(new String[] { TestWorkerMonitor.class.getName()}); + junit.awtui.TestRunner.main(new String[] + {TestWorkerMonitor.class.getName()}); } protected void setUp() throws Exception { super.setUp(); - - - + } - + public static Test suite() { // All methods starting with "test" will be executed in the test suite. @@ -61,24 +64,26 @@ } private static final int JOB_COUNT = 2; - + public void testBasic() throws Exception { WorkerMonitor monitor = new WorkerMonitorImpl(1, 2, 1, 1); - + List jobs = new ArrayList(JOB_COUNT); for (int ix = 0; ix < JOB_COUNT; ix++) { - PortletWindow window = new PortletWindowImpl("w" + String.valueOf(ix)); + PortletWindow window = new PortletWindowImpl("w" + + String.valueOf(ix)); jobs.add(new MockRenderJob("Job-" + (ix + 1), 4000, window)); } assertNotNull("monitor is null", monitor); monitor.start(); for (int ix = 0; ix < JOB_COUNT; ix++) - monitor.process((RenderingJob)jobs.get(ix)); - + monitor.process((RenderingJob) jobs.get(ix)); + Thread.sleep(2000); - assertTrue("available jobs expect 0", monitor.getAvailableJobsCount() == 0); + assertTrue("available jobs expect 0", + monitor.getAvailableJobsCount() == 0); assertTrue("running jobs expect 2", monitor.getRunningJobsCount() == 2); assertTrue("queued jobs expect 0", monitor.getQueuedJobsCount() == 0); monitor.stop(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/cluster/TestCluster.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/cluster/TestCluster.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/cluster/TestCluster.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,12 +28,12 @@ * * @author Scott T. Weaver * @version $Id: TestCluster.java 463270 2006-10-12 15:19:29Z taylor $ - * + * */ public class TestCluster extends DatasourceEnabledSpringTestCase { - - /** The node manager. */ + + /** The node manager. */ private NodeManager single; /** @@ -41,12 +41,13 @@ */ public void setUp() throws Exception { - System.setProperty("applicationRoot","target/jetspeed"); + System.setProperty("applicationRoot", "target/jetspeed"); super.setUp(); - single = (NodeManager) ctx.getBean("org.apache.jetspeed.cluster.NodeManager"); + single = (NodeManager) ctx + .getBean("org.apache.jetspeed.cluster.NodeManager"); } - + public static Test suite() { // All methods starting with "test" will be executed in the test suite. @@ -56,51 +57,56 @@ /** Test set user info map. * */ public void testCluser() throws Exception { - String contextName = "SOME_NEW_PORTLET_APPLICATION"; - Long id = new Long(10); - + String contextName = "SOME_NEW_PORTLET_APPLICATION"; + Long id = new Long(10); + assertNotNull("Manager should be instantiated", single); - + int numExistingApps = single.getNumberOfNodes(); - - //create a new node + + // create a new node int status = single.checkNode(id, contextName); if (status != NodeManager.NODE_NEW) { - single.removeNode(contextName); //previous run didn't clean up - status = single.checkNode(id, contextName); - assertEquals("Should be a new node",NodeManager.NODE_NEW,status); + single.removeNode(contextName); // previous run didn't clean up + status = single.checkNode(id, contextName); + assertEquals("Should be a new node", NodeManager.NODE_NEW, status); } - + // ok - create a new node single.addNode(id, contextName); int newApps = single.getNumberOfNodes(); - assertEquals("Should have added new node",newApps, numExistingApps+1); - + assertEquals("Should have added new node", newApps, numExistingApps + 1); + status = single.checkNode(id, contextName); - assertEquals("Should be a current (saved) node",NodeManager.NODE_SAVED,status); - - id = new Long(20); + assertEquals("Should be a current (saved) node", + NodeManager.NODE_SAVED, status); + + id = new Long(20); status = single.checkNode(id, contextName); - assertEquals("Should be an outdated node",NodeManager.NODE_OUTDATED,status); + assertEquals("Should be an outdated node", NodeManager.NODE_OUTDATED, + status); single.addNode(id, contextName); status = single.checkNode(id, contextName); - assertEquals("Should be again a current (saved) node",NodeManager.NODE_SAVED,status); + assertEquals("Should be again a current (saved) node", + NodeManager.NODE_SAVED, status); - id = new Long(10); + id = new Long(10); status = single.checkNode(id, contextName); - assertEquals("Should still be a current (saved) node",NodeManager.NODE_SAVED,status); + assertEquals("Should still be a current (saved) node", + NodeManager.NODE_SAVED, status); - single.removeNode(contextName); //previous run didn't clean up + single.removeNode(contextName); // previous run didn't clean up status = single.checkNode(id, contextName); - assertEquals("Node should be gone....",NodeManager.NODE_NEW,status); + assertEquals("Node should be gone....", NodeManager.NODE_NEW, status); } + protected String[] getConfigurations() { return new String[] - { "system-properties.xml", "cluster-node.xml"}; + {"system-properties.xml", "cluster-node.xml"}; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/container/TestPortletContainer.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/container/TestPortletContainer.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/container/TestPortletContainer.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,16 +22,18 @@ /** * TestPortletContainer - * + * * @author David Sean Taylor * @version $Id: TestPortletContainer.java 517719 2007-03-13 15:05:48Z ate $ */ -public class TestPortletContainer extends TestCase +public class TestPortletContainer extends TestCase { + /** * Defines the testcase name for JUnit. - * - * @param name the testcase's name. + * + * @param name + * the testcase's name. */ public TestPortletContainer(String name) { @@ -40,22 +42,25 @@ /** * Start the tests. - * - * @param args the arguments. Not used + * + * @param args + * the arguments. Not used */ public static void main(String args[]) { - junit.awtui.TestRunner.main(new String[] { TestPortletContainer.class.getName()}); + junit.awtui.TestRunner.main(new String[] + {TestPortletContainer.class.getName()}); } protected void setUp() throws Exception { super.setUp(); - - // portletContainer = new JetspeedPortletContainerWrapper(new PortletContainerImpl()); + + // portletContainer = new JetspeedPortletContainerWrapper(new + // PortletContainerImpl()); } - public static Test suite() + public static Test suite() { // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestPortletContainer.class); @@ -63,7 +68,8 @@ public void testBasic() { - - // not much more i can do without setting up a mock servlet or portlet framework + + // not much more i can do without setting up a mock servlet or portlet + // framework } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/container/state/TestNavigationalState.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/container/state/TestNavigationalState.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/container/state/TestNavigationalState.java 2008-05-16 01:54:54 UTC (rev 940) @@ -60,26 +60,35 @@ /** * TestPortletContainer - * + * * @author David Sean Taylor * @version $Id: TestNavigationalState.java 550655 2007-06-26 01:41:35Z taylor $ */ public class TestNavigationalState extends TestCase { + // needed to be able to Mock PortletWindowListCtrl - private interface CompositeWindowList extends PortletWindowList, PortletWindowListCtrl{} + private interface CompositeWindowList extends PortletWindowList, + PortletWindowListCtrl + { + } private SpringEngineHelper engineHelper; + private Engine engine; + private NavigationalStateCodec codec; + private PortalContext portalContext; + private JetspeedContentCache cache; /** * Defines the testcase name for JUnit. - * - * @param name the testcase's name. + * + * @param name + * the testcase's name. */ public TestNavigationalState(String name) { @@ -88,14 +97,16 @@ /** * Start the tests. - * - * @param args the arguments. Not used + * + * @param args + * the arguments. Not used */ public static void main(String args[]) { - junit.awtui.TestRunner.main(new String[] { TestNavigationalState.class.getName()}); + junit.awtui.TestRunner.main(new String[] + {TestNavigationalState.class.getName()}); } - + protected void setUp() throws Exception { super.setUp(); @@ -104,29 +115,49 @@ engineHelper = new SpringEngineHelper(context); engineHelper.setUp(); engine = (Engine) context.get(SpringEngineHelper.ENGINE_ATTR); - // mock test PortletWindow, PortletEntity, PortletDefinition and PortletApplication - Mock entityMock = new Mock(MutablePortletEntity.class); + // mock test PortletWindow, PortletEntity, PortletDefinition and + // PortletApplication + Mock entityMock = new Mock(MutablePortletEntity.class); Mock portletDefinitionMock = new Mock(PortletDefinition.class); Mock portletApplicationMock = new Mock(PortletApplication.class); Mock windowListMock = new Mock(CompositeWindowList.class); - PortletWindowListCtrl windowList = (PortletWindowListCtrl)windowListMock.proxy(); - entityMock.expects(new AnyArgumentsMatcher()).method("getPortletWindowList").withNoArguments().will(new ReturnStub(windowList)); - windowListMock.expects(new AnyArgumentsMatcher()).method("add").withAnyArguments().will(new VoidStub()); - portletApplicationMock.expects(new AnyArgumentsMatcher()).method("getId").withNoArguments().will(new ReturnStub(new JetspeedLongObjectID(1))); - portletDefinitionMock.expects(new AnyArgumentsMatcher()).method("getPortletApplicationDefinition").withNoArguments().will(new ReturnStub(portletApplicationMock.proxy())); - entityMock.expects(new AnyArgumentsMatcher()).method("getPortletDefinition").withNoArguments().will(new ReturnStub(portletDefinitionMock.proxy())); - PortletWindowAccessor accessor = (PortletWindowAccessor) engine.getComponentManager().getComponent(PortletWindowAccessor.class); - accessor.createPortletWindow((PortletEntity)entityMock.proxy(), "111"); - accessor.createPortletWindow((PortletEntity)entityMock.proxy(), "222"); - accessor.createPortletWindow((PortletEntity)entityMock.proxy(), "333"); - - // register mocked PortletApplication in PortletFactory so the PortletWindowAccessor check for it won't break the tests - PortletFactory portletFactory = (PortletFactory)engine.getComponentManager().getComponent("portletFactory"); - portletFactory.registerPortletApplication((PortletApplication)portletApplicationMock.proxy(),Thread.currentThread().getContextClassLoader()); - - codec = (NavigationalStateCodec) engine.getComponentManager().getComponent("NavigationalStateCodec"); - portalContext = (PortalContext) engine.getComponentManager().getComponent("PortalContext"); - cache = (JetspeedContentCache) engine.getComponentManager().getComponent("portletContentCache"); + PortletWindowListCtrl windowList = (PortletWindowListCtrl) windowListMock + .proxy(); + entityMock.expects(new AnyArgumentsMatcher()).method( + "getPortletWindowList").withNoArguments().will( + new ReturnStub(windowList)); + windowListMock.expects(new AnyArgumentsMatcher()).method("add") + .withAnyArguments().will(new VoidStub()); + portletApplicationMock.expects(new AnyArgumentsMatcher()).method( + "getId").withNoArguments().will( + new ReturnStub(new JetspeedLongObjectID(1))); + portletDefinitionMock.expects(new AnyArgumentsMatcher()).method( + "getPortletApplicationDefinition").withNoArguments().will( + new ReturnStub(portletApplicationMock.proxy())); + entityMock.expects(new AnyArgumentsMatcher()).method( + "getPortletDefinition").withNoArguments().will( + new ReturnStub(portletDefinitionMock.proxy())); + PortletWindowAccessor accessor = (PortletWindowAccessor) engine + .getComponentManager() + .getComponent(PortletWindowAccessor.class); + accessor.createPortletWindow((PortletEntity) entityMock.proxy(), "111"); + accessor.createPortletWindow((PortletEntity) entityMock.proxy(), "222"); + accessor.createPortletWindow((PortletEntity) entityMock.proxy(), "333"); + + // register mocked PortletApplication in PortletFactory so the + // PortletWindowAccessor check for it won't break the tests + PortletFactory portletFactory = (PortletFactory) engine + .getComponentManager().getComponent("portletFactory"); + portletFactory.registerPortletApplication( + (PortletApplication) portletApplicationMock.proxy(), Thread + .currentThread().getContextClassLoader()); + + codec = (NavigationalStateCodec) engine.getComponentManager() + .getComponent("NavigationalStateCodec"); + portalContext = (PortalContext) engine.getComponentManager() + .getComponent("PortalContext"); + cache = (JetspeedContentCache) engine.getComponentManager() + .getComponent("portletContentCache"); } public static Test suite() @@ -135,40 +166,44 @@ return new TestSuite(TestNavigationalState.class); } - public void testSessionFullStateAndQuery() - { - SessionFullNavigationalState navState = new SessionFullNavigationalState(codec, cache); - QueryStringEncodingPortalURL portalUrl = new QueryStringEncodingPortalURL(navState, portalContext); + { + SessionFullNavigationalState navState = new SessionFullNavigationalState( + codec, cache); + QueryStringEncodingPortalURL portalUrl = new QueryStringEncodingPortalURL( + navState, portalContext); HttpServletRequest request = buildRequest(portalUrl, true); navState = new SessionFullNavigationalState(codec, cache); portalUrl = new QueryStringEncodingPortalURL(navState, portalContext); doTestUrl(portalUrl, request); - + } - + public void testSessionStateAndPathInfo() - { - SessionNavigationalState navState = new SessionNavigationalState(codec, cache); - PathInfoEncodingPortalURL portalUrl = new PathInfoEncodingPortalURL(navState, portalContext); + { + SessionNavigationalState navState = new SessionNavigationalState(codec, + cache); + PathInfoEncodingPortalURL portalUrl = new PathInfoEncodingPortalURL( + navState, portalContext); HttpServletRequest request = buildRequest(portalUrl, false); navState = new SessionNavigationalState(codec, cache); portalUrl = new PathInfoEncodingPortalURL(navState, portalContext); doTestUrl(portalUrl, request); } - + public void testPathStateAndPathInfo() - { + { PathNavigationalState navState = new PathNavigationalState(codec, cache); - PathInfoEncodingPortalURL portalUrl = new PathInfoEncodingPortalURL(navState, portalContext); + PathInfoEncodingPortalURL portalUrl = new PathInfoEncodingPortalURL( + navState, portalContext); HttpServletRequest request = buildRequest(portalUrl, false); navState = new PathNavigationalState(codec, cache); portalUrl = new PathInfoEncodingPortalURL(navState, portalContext); doTestUrl(portalUrl, request); } - - - protected HttpServletRequest buildRequest(PortalURL portalURL, boolean useQueryStringPortalURL) + + protected HttpServletRequest buildRequest(PortalURL portalURL, + boolean useQueryStringPortalURL) { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpSession session = new MockHttpSession(); @@ -187,58 +222,74 @@ PortletWindow window = new PortletWindowImpl("111"); HashMap parameters = new HashMap(); - parameters.put("test",new String[]{"one","two","three"}); + parameters.put("test", new String[] + {"one", "two", "three"}); - String portletURL = portalURL.createPortletURL(window,parameters,PortletMode.EDIT,WindowState.MAXIMIZED,true,false); - - String navStateParameterName = engine.getContext().getConfigurationProperty("portalurl.navigationalstate.parameter.name", AbstractPortalURL.DEFAULT_NAV_STATE_PARAMETER); + String portletURL = portalURL.createPortletURL(window, parameters, + PortletMode.EDIT, WindowState.MAXIMIZED, true, false); - if ( useQueryStringPortalURL ) + String navStateParameterName = engine.getContext() + .getConfigurationProperty( + "portalurl.navigationalstate.parameter.name", + AbstractPortalURL.DEFAULT_NAV_STATE_PARAMETER); + + if (useQueryStringPortalURL) { - request.setupAddParameter(navStateParameterName,portletURL.substring(portletURL.indexOf('=')+1)); + request.setupAddParameter(navStateParameterName, portletURL + .substring(portletURL.indexOf('=') + 1)); } else { - request.setPathInfo(portletURL.substring(portletURL.indexOf("/portal")+7)); + request.setPathInfo(portletURL.substring(portletURL + .indexOf("/portal") + 7)); } - - return request; + + return request; } - + protected void doTestUrl(PortalURL portalURL, HttpServletRequest request) - { - portalURL.setRequest(request); - portalURL.setCharacterEncoding("UTF-8"); - - PortletWindow window = new PortletWindowImpl("111"); - NavigationalState nav = portalURL.getNavigationalState(); + { + portalURL.setRequest(request); + portalURL.setCharacterEncoding("UTF-8"); - // Check that they come out correctly - assertTrue("window mode is not set", nav.getMode(window).equals(PortletMode.EDIT)); - assertTrue("window state is not set", nav.getState(window).equals(WindowState.MAXIMIZED)); - PortletWindow target = nav.getPortletWindowOfAction(); - assertNotNull("target window is null", target); - assertEquals("target window should equal window 111", target.getId(), "111"); + PortletWindow window = new PortletWindowImpl("111"); + NavigationalState nav = portalURL.getNavigationalState(); - PortletWindow maximizedWindow = nav.getMaximizedWindow(); - assertNotNull("maximized window is null", maximizedWindow); - assertEquals("maximized window should equal window 111", maximizedWindow.getId(), "111"); + // Check that they come out correctly + assertTrue("window mode is not set", nav.getMode(window).equals( + PortletMode.EDIT)); + assertTrue("window state is not set", nav.getState(window).equals( + WindowState.MAXIMIZED)); + PortletWindow target = nav.getPortletWindowOfAction(); + assertNotNull("target window is null", target); + assertEquals("target window should equal window 111", target.getId(), + "111"); - Iterator iter = nav.getParameterNames(target); - assertTrue("There should be one parameter",iter.hasNext()); - while ( iter.hasNext() ) { - assertEquals("parameter name should equals \"test\"", (String)iter.next(), "test"); - String[] values = nav.getParameterValues(target,"test"); - assertNotNull("parameter name has no values", values); - assertEquals("parameter test should have 3 values", values.length, 3); - assertEquals("parameter test[0] should be \"one\"", values[0], "one"); - assertEquals("parameter test[1] should be \"two\"", values[1], "two"); - assertEquals("parameter test[2] should be \"three\"", values[2], "three"); - } - + PortletWindow maximizedWindow = nav.getMaximizedWindow(); + assertNotNull("maximized window is null", maximizedWindow); + assertEquals("maximized window should equal window 111", + maximizedWindow.getId(), "111"); + + Iterator iter = nav.getParameterNames(target); + assertTrue("There should be one parameter", iter.hasNext()); + while (iter.hasNext()) + { + assertEquals("parameter name should equals \"test\"", (String) iter + .next(), "test"); + String[] values = nav.getParameterValues(target, "test"); + assertNotNull("parameter name has no values", values); + assertEquals("parameter test should have 3 values", values.length, + 3); + assertEquals("parameter test[0] should be \"one\"", values[0], + "one"); + assertEquals("parameter test[1] should be \"two\"", values[1], + "two"); + assertEquals("parameter test[2] should be \"three\"", values[2], + "three"); + } + } - protected void tearDown() throws Exception { engineHelper.tearDown(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/decoration/OnConsecutiveInvokes.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/decoration/OnConsecutiveInvokes.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/decoration/OnConsecutiveInvokes.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,36 +1,39 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.decoration; import org.jmock.core.Constraint; public class OnConsecutiveInvokes implements Constraint { + private final Constraint[] constraints; + private int pointer = 0; + private boolean toManyCalls = false; - + public OnConsecutiveInvokes(Constraint[] constraints) { this.constraints = constraints; } public boolean eval(Object arg0) - { + { if (pointer < constraints.length) { try @@ -51,13 +54,14 @@ public StringBuffer describeTo(StringBuffer buffer) { - if(!toManyCalls) + if (!toManyCalls) { return constraints[pointer].describeTo(buffer); } else { - return buffer.append("Should be invoked "+constraints.length+" times."); + return buffer.append("Should be invoked " + constraints.length + + " times."); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/decoration/StringReaderInputStream.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/decoration/StringReaderInputStream.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/decoration/StringReaderInputStream.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.decoration; import java.io.IOException; @@ -22,14 +22,15 @@ public class StringReaderInputStream extends InputStream { + private final StringReader reader; - + public StringReaderInputStream(StringReader reader) { super(); this.reader = reader; } - + public StringReaderInputStream(String value) { this(new StringReader(value)); @@ -39,7 +40,5 @@ { return reader.read(); } - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/decoration/TestDecorations.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/decoration/TestDecorations.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/decoration/TestDecorations.java 2008-05-16 01:54:54 UTC (rev 940) @@ -38,26 +38,47 @@ public class TestDecorations extends MockObjectTestCase { + private Path testPathHtmlEn; + private Path testPath; + private Mock prcMock; + private Mock rvMock; + private PathResolverCache prc; + private ResourceValidator rv; + private Properties config; + private Page page; + private RequestContext requestContext; + private Mock pageMock; + private Mock factoryMock; + private Mock fragmentMock; + private Mock requestContextMock; + private Fragment fragment; + private Mock childFragmentMock; + private Fragment childFragment; + private Mock layoutMock; + private LayoutDecoration layout; + private Mock portletDecorMock; + private PortletDecoration portletDecor; + private DecorationFactory factory; protected void themeInitExpectations() @@ -76,19 +97,18 @@ layout = (LayoutDecoration) layoutMock.proxy(); portletDecorMock = new Mock(PortletDecoration.class); portletDecor = (PortletDecoration) portletDecorMock.proxy(); - + // Define expected behavior - ArrayList list = new ArrayList(1); list.add(childFragment); - + expectAndReturn(fragmentMock, "getFragments", list); - + expectAndReturn(atLeastOnce(), fragmentMock, "getId", "001"); - - expectAndReturn(atLeastOnce(), childFragmentMock, "getId", "002"); + expectAndReturn(atLeastOnce(), childFragmentMock, "getId", "002"); + expectAndReturn(childFragmentMock, "getFragments", null); expectAndReturn(childFragmentMock, "getType", "portlet"); } @@ -96,19 +116,21 @@ protected void setUp1() throws Exception { super.setUp(); - + prcMock = new Mock(PathResolverCache.class); - prcMock.expects(atLeastOnce()).method("getPath").withAnyArguments().will(returnValue(null)); - prcMock.expects(atLeastOnce()).method("addPath").withAnyArguments().isVoid(); - + prcMock.expects(atLeastOnce()).method("getPath").withAnyArguments() + .will(returnValue(null)); + prcMock.expects(atLeastOnce()).method("addPath").withAnyArguments() + .isVoid(); + rvMock = new Mock(ResourceValidator.class); - - prc = (PathResolverCache)prcMock.proxy(); - rv = (ResourceValidator)rvMock.proxy(); - + + prc = (PathResolverCache) prcMock.proxy(); + rv = (ResourceValidator) rvMock.proxy(); + config = new Properties(); config.setProperty("name", "test"); - + testPath = new Path("/decorations/test"); testPathHtmlEn = new Path("/decorations/test/html/en"); } @@ -116,192 +138,232 @@ public void testSimpleLocation() throws Exception { setUp1(); - - String expectedResult = testPathHtmlEn.getChild("/images/myimage.gif").toString(); - rvMock.expects(once()).method("resourceExists").with(eq(expectedResult)).will(returnValue(true)); - BaseDecoration decoration = new BaseDecoration(config, rv, testPath, testPathHtmlEn, prc ); - + String expectedResult = testPathHtmlEn.getChild("/images/myimage.gif") + .toString(); + rvMock.expects(once()).method("resourceExists") + .with(eq(expectedResult)).will(returnValue(true)); + + BaseDecoration decoration = new BaseDecoration(config, rv, testPath, + testPathHtmlEn, prc); + String result = decoration.getResource("/images/myimage.gif"); assertNotNull(result); assertEquals(expectedResult, result); - + verify(); } - + public void testResolution() throws Exception { setUp1(); - + Path testPath = testPathHtmlEn; String failure1 = testPath.getChild("/images/myimage.gif").toString(); testPath = testPath.removeLastPathSegment(); String failure2 = testPath.getChild("/images/myimage.gif").toString(); testPath = testPath.removeLastPathSegment(); String success = testPath.getChild("/images/myimage.gif").toString(); - - Constraint[] constraints = new Constraint[]{eq(failure1), eq(failure2), eq(success)}; - - rvMock.expects(atLeastOnce()).method("resourceExists").with(new OnConsecutiveInvokes(constraints)) - .will(onConsecutiveCalls(returnValue(false), returnValue(false), returnValue(true))); - - BaseDecoration decoration = new BaseDecoration(config, rv, testPath, testPathHtmlEn, prc); - + + Constraint[] constraints = new Constraint[] + {eq(failure1), eq(failure2), eq(success)}; + + rvMock.expects(atLeastOnce()).method("resourceExists").with( + new OnConsecutiveInvokes(constraints)).will( + onConsecutiveCalls(returnValue(false), returnValue(false), + returnValue(true))); + + BaseDecoration decoration = new BaseDecoration(config, rv, testPath, + testPathHtmlEn, prc); + String result = decoration.getResource("/images/myimage.gif"); - + assertNotNull(result); assertEquals(success, result); - + verify(); } - + public void testTheme() { themeInitExpectations(); - + expectAndReturn(pageMock, "getRootFragment", fragment); - expectAndReturn(factoryMock, - "isDesktopEnabled", - new Constraint[] {eq(requestContext)}, - Boolean.FALSE); - - expectAndReturn(factoryMock, - "getDecoration", - new Constraint[] {eq(page), eq(fragment), eq(requestContext)}, - layout); - - expectAndReturn(factoryMock, - "getDecoration", - new Constraint[] {eq(page), eq(childFragment), eq(requestContext)}, - portletDecor); - - expectAndReturn(layoutMock, "getStyleSheet", "/decorations/layout/test/html/css/styles.css"); + expectAndReturn(factoryMock, "isDesktopEnabled", new Constraint[] + {eq(requestContext)}, Boolean.FALSE); + + expectAndReturn(factoryMock, "getDecoration", new Constraint[] + {eq(page), eq(fragment), eq(requestContext)}, layout); + + expectAndReturn(factoryMock, "getDecoration", new Constraint[] + {eq(page), eq(childFragment), eq(requestContext)}, portletDecor); + + expectAndReturn(layoutMock, "getStyleSheet", + "/decorations/layout/test/html/css/styles.css"); expectAndReturn(layoutMock, "getStyleSheetPortal", null); - - expectAndReturn(portletDecorMock, "getStyleSheet", "/decorations/portlet/test/html/css/styles.css"); + + expectAndReturn(portletDecorMock, "getStyleSheet", + "/decorations/portlet/test/html/css/styles.css"); expectAndReturn(portletDecorMock, "getStyleSheetPortal", null); - portletDecorMock.expects(atLeastOnce()).method("getName").withNoArguments().will(returnValue("tigris")); - - fragmentMock.expects(once()).method("getId") - .withNoArguments() - .will(returnValue("001")); + portletDecorMock.expects(atLeastOnce()).method("getName") + .withNoArguments().will(returnValue("tigris")); - childFragmentMock.expects(once()).method("getId") - .withNoArguments() - .will(returnValue("002")); - - + fragmentMock.expects(once()).method("getId").withNoArguments().will( + returnValue("001")); + + childFragmentMock.expects(once()).method("getId").withNoArguments() + .will(returnValue("002")); + Theme theme = new PageTheme(page, factory, requestContext); - + assertEquals(layout, theme.getPageLayoutDecoration()); - + assertEquals(2, theme.getStyleSheets().size()); - + Iterator itr = theme.getStyleSheets().iterator(); assertEquals("/decorations/layout/test/html/css/styles.css", itr.next()); - assertEquals("/decorations/portlet/test/html/css/styles.css", itr.next()); - + assertEquals("/decorations/portlet/test/html/css/styles.css", itr + .next()); + assertEquals(layout, theme.getDecoration(fragment)); assertEquals(portletDecor, theme.getDecoration(childFragment)); - + verify(); } public void testDecortaionFactory() - { - + { + rvMock = new Mock(ResourceValidator.class); - rv = (ResourceValidator)rvMock.proxy(); + rv = (ResourceValidator) rvMock.proxy(); rvMock.expects(atLeastOnce()).method("resourceExists") - .withAnyArguments() - .will(returnValue(false)); - + .withAnyArguments().will(returnValue(false)); + // Define expected behavior Mock servletContextMock = new Mock(ServletContext.class); - - DecorationFactoryImpl testFactory = new DecorationFactoryImpl("/decorations", rv); - testFactory.setServletContext((ServletContext)servletContextMock.proxy()); - + + DecorationFactoryImpl testFactory = new DecorationFactoryImpl( + "/decorations", rv); + testFactory.setServletContext((ServletContext) servletContextMock + .proxy()); + themeInitExpectations(); - - expectAndReturn(atLeastOnce(),requestContextMock, "getAttribute", new Constraint[] {eq("desktop.enabled")}, Boolean.FALSE); + expectAndReturn(atLeastOnce(), requestContextMock, "getAttribute", + new Constraint[] + {eq("desktop.enabled")}, Boolean.FALSE); + expectAndReturn(fragmentMock, "getDecorator", "myLayoutDecorator"); - + expectAndReturn(fragmentMock, "getType", Fragment.LAYOUT); expectAndReturn(childFragmentMock, "getType", Fragment.PORTLET); - -// expectAndReturn(pageMock, "getRootFragment", fragment); - - expectAndReturn(atLeastOnce(), requestContextMock, "getMediaType", "html"); - - expectAndReturn(atLeastOnce(), requestContextMock, "getLocale", Locale.ENGLISH); - - StringReaderInputStream is1 = new StringReaderInputStream("id=myLayoutDecorator"); - StringReaderInputStream is2 = new StringReaderInputStream("id=myPortletDecoration"); - - expectAndReturn(atLeastOnce(), servletContextMock, "getResourceAsStream",new Constraint[] {eq("/decorations/layout/myLayoutDecorator/decorator.properties")}, is1); - expectAndReturn(atLeastOnce(), servletContextMock, "getResourceAsStream",new Constraint[] {eq("/decorations/portlet/myPortletDecoration/decorator.properties")}, is2); - expectAndReturn(atLeastOnce(), servletContextMock, "getResourceAsStream",new Constraint[] {eq("/decorations/layout/myLayoutDecorator/decoratordesktop.properties")}, is1); - expectAndReturn(atLeastOnce(), servletContextMock, "getResourceAsStream",new Constraint[] {eq("/decorations/portlet/myPortletDecoration/decoratordesktop.properties")}, is2); - + + // expectAndReturn(pageMock, "getRootFragment", fragment); + + expectAndReturn(atLeastOnce(), requestContextMock, "getMediaType", + "html"); + + expectAndReturn(atLeastOnce(), requestContextMock, "getLocale", + Locale.ENGLISH); + + StringReaderInputStream is1 = new StringReaderInputStream( + "id=myLayoutDecorator"); + StringReaderInputStream is2 = new StringReaderInputStream( + "id=myPortletDecoration"); + + expectAndReturn( + atLeastOnce(), + servletContextMock, + "getResourceAsStream", + new Constraint[] + {eq("/decorations/layout/myLayoutDecorator/decorator.properties")}, + is1); + expectAndReturn( + atLeastOnce(), + servletContextMock, + "getResourceAsStream", + new Constraint[] + {eq("/decorations/portlet/myPortletDecoration/decorator.properties")}, + is2); + expectAndReturn( + atLeastOnce(), + servletContextMock, + "getResourceAsStream", + new Constraint[] + {eq("/decorations/layout/myLayoutDecorator/decoratordesktop.properties")}, + is1); + expectAndReturn( + atLeastOnce(), + servletContextMock, + "getResourceAsStream", + new Constraint[] + {eq("/decorations/portlet/myPortletDecoration/decoratordesktop.properties")}, + is2); + Mock servletRequestMock = new Mock(HttpServletRequest.class); Mock sessionMock = new Mock(HttpSession.class); - - expectAndReturn(atLeastOnce(), servletRequestMock, "getSession", sessionMock.proxy()); - expectAndReturn(atLeastOnce(), requestContextMock, "getRequest", servletRequestMock.proxy()); - - expectAndReturn(atLeastOnce(), sessionMock, "getAttribute", new Constraint[]{eq(PortalReservedParameters.RESOVLER_CACHE_ATTR)}, new HashMap()); - //expectAndReturn(sessionMock, "getAttribute", PortalReservedParameters.RESOVLER_CACHE_ATTR); - expectAndReturn(childFragmentMock, "getDecorator", "myPortletDecoration"); + expectAndReturn(atLeastOnce(), servletRequestMock, "getSession", + sessionMock.proxy()); + expectAndReturn(atLeastOnce(), requestContextMock, "getRequest", + servletRequestMock.proxy()); + expectAndReturn(atLeastOnce(), sessionMock, "getAttribute", + new Constraint[] + {eq(PortalReservedParameters.RESOVLER_CACHE_ATTR)}, + new HashMap()); + // expectAndReturn(sessionMock, "getAttribute", + // PortalReservedParameters.RESOVLER_CACHE_ATTR); + + expectAndReturn(childFragmentMock, "getDecorator", + "myPortletDecoration"); + expectAndReturn(pageMock, "getRootFragment", fragment); Theme theme = testFactory.getTheme(page, requestContext); - + Decoration result1 = theme.getDecoration(fragment); - + assertNotNull(result1); assertEquals("myLayoutDecorator", result1.getName()); - + Decoration result2 = theme.getDecoration(childFragment); assertNotNull(result2); assertEquals("myPortletDecoration", result2.getName()); - + verify(); - + } - - protected void expectAndReturn(Mock mock, String methodName, Object returnValue) + + protected void expectAndReturn(Mock mock, String methodName, + Object returnValue) { - mock.expects(once()).method(methodName) - .withNoArguments() - .will(returnValue(returnValue)); + mock.expects(once()).method(methodName).withNoArguments().will( + returnValue(returnValue)); } - - protected void expectAndReturn(Mock mock, String methodName, Constraint[] constraints, Object returnValue) + + protected void expectAndReturn(Mock mock, String methodName, + Constraint[] constraints, Object returnValue) { - mock.expects(once()).method(methodName) - .with(constraints) - .will(returnValue(returnValue)); + mock.expects(once()).method(methodName).with(constraints).will( + returnValue(returnValue)); } - - protected void expectAndReturn(InvocationMatcher matcher, Mock mock, String methodName, Object returnValue) + + protected void expectAndReturn(InvocationMatcher matcher, Mock mock, + String methodName, Object returnValue) { - mock.expects(matcher).method(methodName) - .withNoArguments() - .will(returnValue(returnValue)); + mock.expects(matcher).method(methodName).withNoArguments().will( + returnValue(returnValue)); } - - protected void expectAndReturn(InvocationMatcher matcher, Mock mock, String methodName, Constraint[] constraints, Object returnValue) + + protected void expectAndReturn(InvocationMatcher matcher, Mock mock, + String methodName, Constraint[] constraints, Object returnValue) { - mock.expects(matcher).method(methodName) - .with(constraints) - .will(returnValue(returnValue)); + mock.expects(matcher).method(methodName).with(constraints).will( + returnValue(returnValue)); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/deployment/TestSimpleDeployment.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/deployment/TestSimpleDeployment.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/deployment/TestSimpleDeployment.java 2008-05-16 01:54:54 UTC (rev 940) @@ -46,11 +46,13 @@ * * @author Scott T. Weaver * @version $Id: TestSimpleDeployment.java 517719 2007-03-13 15:05:48Z ate $ - * + * */ public class TestSimpleDeployment extends AbstractRequestContextTestCase { + protected static final String TEST_PORTLET_APP_NAME = "HW_App"; + protected String webAppsDir; protected File deploySrc; @@ -58,12 +60,16 @@ protected File deployRootFile; protected String testDb; + protected File webAppsDirFile; + protected File copyFrom; + protected PortletWindowAccessor windowAccess; + protected PortletFactory portletFactory; + protected ApplicationServerManager manager; - /** * Start the tests. @@ -71,9 +77,10 @@ * @param args * the arguments. Not used */ - public static void main( String args[] ) + public static void main(String args[]) { - junit.awtui.TestRunner.main(new String[]{TestSimpleDeployment.class.getName()}); + junit.awtui.TestRunner.main(new String[] + {TestSimpleDeployment.class.getName()}); } /** @@ -88,269 +95,244 @@ // return new JetspeedTestSuite(TestSimpleDeployment.class); return new TestSuite(TestSimpleDeployment.class); } + public void testFileSystemHelperOnWar() throws Exception { File demoApp = new File(deploySrc, "demo.war"); - + JarHelper jarHelper = new JarHelper(demoApp, true); File rootDirectory = jarHelper.getRootDirectory(); File webXml = new File(rootDirectory, "WEB-INF/web.xml"); assertTrue(webXml.exists()); - jarHelper.close(); + jarHelper.close(); assertFalse(webXml.exists()); - + // Test for keeping jar temp files around jarHelper = new JarHelper(demoApp, false); assertTrue(webXml.exists()); - jarHelper.close(); + jarHelper.close(); assertTrue(webXml.exists()); } - + public void testFileSystemManagerOnDir() throws Exception { File demoApp = new File("./test/testdata/deploy/webapp"); assertTrue(demoApp.exists()); - + DirectoryHelper dirHelper = new DirectoryHelper(demoApp); File webXml = new File(dirHelper.getRootDirectory(), "WEB-INF/web.xml"); assertTrue(webXml.exists()); - - } - - /* - - public void testDeploy() throws Exception - { - System.out.println("Deployment src: " + deploySrc); - manager = new TomcatManager("", "", 0, "", 0, "", ""); - SimpleRegistry simpleRegistry = new InMemoryRegistryImpl(); - DeployDecoratorEventListener ddel = new DeployDecoratorEventListener(simpleRegistry, deployRootFile - .getAbsolutePath()); - - DeployPortletAppEventListener dpal = new DeployPortletAppEventListener(webAppsDir, new FileSystemPAM( - webAppsDir, portletRegistry, entityAccess, windowAccess, portletCache, portletFactory, manager), portletRegistry ); - ArrayList eventListeners = new ArrayList(2); - eventListeners.add(ddel); - eventListeners.add(dpal); - // Use a -1 delay to disable auto scan - StandardDeploymentManager autoDeployment = new StandardDeploymentManager(deploySrc.getAbsolutePath(), -1, eventListeners ); - - autoDeployment.start(); - autoDeployment.fireDeploymentEvent(); - - File decoratorVm = new File(deployRootFile.getAbsolutePath() + File.separator + "generic" + File.separator + "html" + File.separator - + "portletstd" + File.separator + "decorator.vm"); - - File demoAppDeployed = new File(webAppsDirFile, TEST_PORTLET_APP_NAME); - File demoApp = demoAppDeployed; - File securityApp = new File(webAppsDirFile, "TestSecurityRoles"); - - assertTrue(decoratorVm.getCanonicalPath() + " was not created!", decoratorVm.exists()); - - verifyDemoAppCreated(TEST_PORTLET_APP_NAME, demoApp); - verifyDemoAppCreated("TestSecurityRoles", securityApp); - - MutablePortletApplication jetspeedApp = portletRegistry.getPortletApplicationByIdentifier("jetspeed"); - assertNotNull("jetspeed was not registered into the portlet registery.", jetspeedApp); - assertFalse("local app, jetspeed, got deployed when it should have only been registered.", new File(webAppsDir - + "/jetspeed").exists()); - - //make sure we can load registered app's classes - Iterator portletDefItr = jetspeedApp.getPortletDefinitions().iterator(); - while (portletDefItr.hasNext()) - { - PortletDefinition def = (PortletDefinition) portletDefItr.next(); - try - { - Portlet portlet = JetspeedPortletFactoryProxy.loadPortletClass(def.getClassName()); - assertNotNull("Could not load portlet class: "+def.getClassName(), portlet); - } - catch (Exception e) - { - assertNull("Unable to load registered portlet class, " + def.getClassName(), e); - } - - } - - // test undeploy - File demoWar = new File(deploySrc, "demo.war"); - demoWar.delete(); - autoDeployment.fireUndeploymentEvent(); - verifyDemoAppDeleted(TEST_PORTLET_APP_NAME, demoApp); - - // test deploy again - copyDeployables(); - autoDeployment.fireDeploymentEvent(); - verifyDemoAppCreated(TEST_PORTLET_APP_NAME, demoApp); - demoWar.delete(); - autoDeployment.fireUndeploymentEvent(); - verifyDemoAppDeleted(TEST_PORTLET_APP_NAME, demoApp); - - // test redeploy - - // So, first deploy the typical demo.war we have been using before. - copyDeployables(); - autoDeployment.fireDeploymentEvent(); - verifyDemoAppCreated(TEST_PORTLET_APP_NAME, demoApp); - DirectoryHelper demoAppDeployedDir = new DirectoryHelper(demoAppDeployed); - long beforeSize = new File(demoAppDeployedDir.getRootDirectory(), "WEB-INF/portlet.xml").length(); - - // Trigger re-deployment using a demo.war that has a slightly larger portlet.xml - // then the one we just deployed. We will use size comparisons as or litmus test. - File redeployDemoWar = new File("./test/deployment/redeploy/demo.war"); - FileChannel srcDemoWarChannel = new FileInputStream(redeployDemoWar).getChannel(); - FileChannel dstDemoWarChannel = new FileOutputStream(demoWar).getChannel(); - dstDemoWarChannel.transferFrom(srcDemoWarChannel, 0, srcDemoWarChannel.size()); - srcDemoWarChannel.close(); - dstDemoWarChannel.close(); - - // Make sure the demo.war that will trigger redeploy has a larger portlet.xml then the current one - JarHelper rdDemoWar = new JarHelper(demoWar, true); - assertTrue(new File(rdDemoWar.getRootDirectory(), "WEB-INF/portlet.xml").length() > beforeSize); - - // Need to slow it down so the timestamp check works - Thread.sleep(500); - demoWar.setLastModified(System.currentTimeMillis()); - autoDeployment.fireRedeploymentEvent(); - - long afterSize = new File(demoAppDeployedDir.getRootDirectory(), "WEB-INF/portlet.xml").length(); - // The portlet.xml in re-deploy has an additional portlet entry in portlet.xml, so it should be bigger - assertTrue(afterSize > beforeSize); - autoDeployment.stop(); - } - - - public void testUndeployVersusRedeploy() throws Exception - { - manager = new TomcatManager("", "", 0, "", 0, "", ""); - - DeployPortletAppEventListener dpal = new DeployPortletAppEventListener(webAppsDir, new FileSystemPAM( - webAppsDir, portletRegistry, entityAccess, windowAccess, portletCache, portletFactory, manager), portletRegistry ); - ArrayList eventListeners = new ArrayList(1); - - eventListeners.add(dpal); - - // Use a -1 delay to disable auto scan - StandardDeploymentManager autoDeployment = new StandardDeploymentManager(deploySrc.getAbsolutePath(), -1, eventListeners ); - autoDeployment.start(); - buildEntityTestData(autoDeployment); - - - MutablePortletEntity entity = entityAccess.getPortletEntity("testEnity"); - - PreferenceSetCtrl prefs = (PreferenceSetCtrl) entity.getPreferenceSet(); - List values = new ArrayList(1); - values.add("some value"); - prefs.add("pref1", values); - - entity.store(); - - assertNotNull(entity); - - Preference pref = entity.getPreferenceSet().get("pref1"); - - assertNotNull(pref); - - //test entity removal via undeploy - File demoWar = new File(deploySrc, "demo.war"); - demoWar.delete(); - - autoDeployment.fireUndeploymentEvent(); - - - entity = entityAccess.getPortletEntity("testEnity"); - - assertNull(entity); - - // Now test that redploy DOES NOT kill the entity - buildEntityTestData(autoDeployment); - - entity = entityAccess.getPortletEntity("testEnity"); - - assertNotNull(entity); - - pref = entity.getPreferenceSet().get("pref1"); - - assertNull("Preference was not deleted with last undeploy",pref); - - demoWar.setLastModified(System.currentTimeMillis()); - - autoDeployment.fireRedeploymentEvent(); - - entity = entityAccess.getPortletEntity("testEnity"); - - assertNotNull(entity); - - } -*/ + /* + * + * public void testDeploy() throws Exception { + * + * System.out.println("Deployment src: " + deploySrc); manager = new + * TomcatManager("", "", 0, "", 0, "", ""); SimpleRegistry simpleRegistry = + * new InMemoryRegistryImpl(); DeployDecoratorEventListener ddel = new + * DeployDecoratorEventListener(simpleRegistry, deployRootFile + * .getAbsolutePath()); + * + * DeployPortletAppEventListener dpal = new + * DeployPortletAppEventListener(webAppsDir, new FileSystemPAM( webAppsDir, + * portletRegistry, entityAccess, windowAccess, portletCache, + * portletFactory, manager), portletRegistry ); ArrayList eventListeners = + * new ArrayList(2); eventListeners.add(ddel); eventListeners.add(dpal); // + * Use a -1 delay to disable auto scan StandardDeploymentManager + * autoDeployment = new + * StandardDeploymentManager(deploySrc.getAbsolutePath(), -1, eventListeners ); + * + * autoDeployment.start(); autoDeployment.fireDeploymentEvent(); + * + * File decoratorVm = new File(deployRootFile.getAbsolutePath() + + * File.separator + "generic" + File.separator + "html" + File.separator + + * "portletstd" + File.separator + "decorator.vm"); + * + * File demoAppDeployed = new File(webAppsDirFile, TEST_PORTLET_APP_NAME); + * File demoApp = demoAppDeployed; File securityApp = new + * File(webAppsDirFile, "TestSecurityRoles"); + * + * assertTrue(decoratorVm.getCanonicalPath() + " was not created!", + * decoratorVm.exists()); + * + * verifyDemoAppCreated(TEST_PORTLET_APP_NAME, demoApp); + * verifyDemoAppCreated("TestSecurityRoles", securityApp); + * + * MutablePortletApplication jetspeedApp = + * portletRegistry.getPortletApplicationByIdentifier("jetspeed"); + * assertNotNull("jetspeed was not registered into the portlet registery.", + * jetspeedApp); assertFalse("local app, jetspeed, got deployed when it + * should have only been registered.", new File(webAppsDir + + * "/jetspeed").exists()); + * + * //make sure we can load registered app's classes Iterator portletDefItr = + * jetspeedApp.getPortletDefinitions().iterator(); while + * (portletDefItr.hasNext()) { PortletDefinition def = (PortletDefinition) + * portletDefItr.next(); try { Portlet portlet = + * JetspeedPortletFactoryProxy.loadPortletClass(def.getClassName()); + * assertNotNull("Could not load portlet class: "+def.getClassName(), + * portlet); } catch (Exception e) { assertNull("Unable to load registered + * portlet class, " + def.getClassName(), e); } } // test undeploy File + * demoWar = new File(deploySrc, "demo.war"); demoWar.delete(); + * autoDeployment.fireUndeploymentEvent(); + * verifyDemoAppDeleted(TEST_PORTLET_APP_NAME, demoApp); // test deploy + * again copyDeployables(); autoDeployment.fireDeploymentEvent(); + * verifyDemoAppCreated(TEST_PORTLET_APP_NAME, demoApp); demoWar.delete(); + * autoDeployment.fireUndeploymentEvent(); + * verifyDemoAppDeleted(TEST_PORTLET_APP_NAME, demoApp); // test redeploy // + * So, first deploy the typical demo.war we have been using before. + * copyDeployables(); autoDeployment.fireDeploymentEvent(); + * verifyDemoAppCreated(TEST_PORTLET_APP_NAME, demoApp); DirectoryHelper + * demoAppDeployedDir = new DirectoryHelper(demoAppDeployed); long + * beforeSize = new File(demoAppDeployedDir.getRootDirectory(), + * "WEB-INF/portlet.xml").length(); // Trigger re-deployment using a + * demo.war that has a slightly larger portlet.xml // then the one we just + * deployed. We will use size comparisons as or litmus test. File + * redeployDemoWar = new File("./test/deployment/redeploy/demo.war"); + * FileChannel srcDemoWarChannel = new + * FileInputStream(redeployDemoWar).getChannel(); FileChannel + * dstDemoWarChannel = new FileOutputStream(demoWar).getChannel(); + * dstDemoWarChannel.transferFrom(srcDemoWarChannel, 0, + * srcDemoWarChannel.size()); srcDemoWarChannel.close(); + * dstDemoWarChannel.close(); // Make sure the demo.war that will trigger + * redeploy has a larger portlet.xml then the current one JarHelper + * rdDemoWar = new JarHelper(demoWar, true); assertTrue(new + * File(rdDemoWar.getRootDirectory(), "WEB-INF/portlet.xml").length() > + * beforeSize); // Need to slow it down so the timestamp check works + * Thread.sleep(500); demoWar.setLastModified(System.currentTimeMillis()); + * autoDeployment.fireRedeploymentEvent(); + * + * long afterSize = new File(demoAppDeployedDir.getRootDirectory(), + * "WEB-INF/portlet.xml").length(); // The portlet.xml in re-deploy has an + * additional portlet entry in portlet.xml, so it should be bigger + * assertTrue(afterSize > beforeSize); autoDeployment.stop(); } + * + * + * public void testUndeployVersusRedeploy() throws Exception { manager = new + * TomcatManager("", "", 0, "", 0, "", ""); + * + * DeployPortletAppEventListener dpal = new + * DeployPortletAppEventListener(webAppsDir, new FileSystemPAM( webAppsDir, + * portletRegistry, entityAccess, windowAccess, portletCache, + * portletFactory, manager), portletRegistry ); ArrayList eventListeners = + * new ArrayList(1); + * + * eventListeners.add(dpal); // Use a -1 delay to disable auto scan + * StandardDeploymentManager autoDeployment = new + * StandardDeploymentManager(deploySrc.getAbsolutePath(), -1, eventListeners ); + * autoDeployment.start(); + * + * buildEntityTestData(autoDeployment); + * + * + * MutablePortletEntity entity = entityAccess.getPortletEntity("testEnity"); + * + * PreferenceSetCtrl prefs = (PreferenceSetCtrl) entity.getPreferenceSet(); + * List values = new ArrayList(1); values.add("some value"); + * prefs.add("pref1", values); + * + * entity.store(); + * + * assertNotNull(entity); + * + * Preference pref = entity.getPreferenceSet().get("pref1"); + * + * assertNotNull(pref); + * + * //test entity removal via undeploy File demoWar = new File(deploySrc, + * "demo.war"); demoWar.delete(); + * + * autoDeployment.fireUndeploymentEvent(); + * + * + * entity = entityAccess.getPortletEntity("testEnity"); + * + * assertNull(entity); // Now test that redploy DOES NOT kill the entity + * buildEntityTestData(autoDeployment); + * + * entity = entityAccess.getPortletEntity("testEnity"); + * + * assertNotNull(entity); + * + * pref = entity.getPreferenceSet().get("pref1"); + * + * assertNull("Preference was not deleted with last undeploy",pref); + * + * demoWar.setLastModified(System.currentTimeMillis()); + * + * autoDeployment.fireRedeploymentEvent(); + * + * entity = entityAccess.getPortletEntity("testEnity"); + * + * assertNotNull(entity); } + */ /** *

        * buildEntityTestData *

        - * + * * @param autoDeployment * @throws IOException * @throws PortletEntityNotStoredException */ - protected void buildEntityTestData( StandardDeploymentManager autoDeployment ) throws Exception + protected void buildEntityTestData(StandardDeploymentManager autoDeployment) + throws Exception { copyDeployables(); - + File demoApp = new File(webAppsDirFile, TEST_PORTLET_APP_NAME); - + autoDeployment.fireDeploymentEvent(); - + verifyDemoAppCreated(TEST_PORTLET_APP_NAME, demoApp); - - MutablePortletApplication app = portletRegistry.getPortletApplication(TEST_PORTLET_APP_NAME); - - PortletDefinition portlet = (PortletDefinition) app.getPortletDefinitionList().iterator().next(); - - MutablePortletEntity entity = entityAccess.newPortletEntityInstance(portlet); + + MutablePortletApplication app = portletRegistry + .getPortletApplication(TEST_PORTLET_APP_NAME); + + PortletDefinition portlet = (PortletDefinition) app + .getPortletDefinitionList().iterator().next(); + + MutablePortletEntity entity = entityAccess + .newPortletEntityInstance(portlet); entity.setId("testEnity"); - + entityAccess.storePortletEntity(entity); - - - + } /** *

        * verifyDemoAppCreated *

        - * + * * @param demoApp */ - private void verifyDemoAppCreated( String appName, File appFile ) + private void verifyDemoAppCreated(String appName, File appFile) { - assertNotNull(appName + " was not registered into the portlet registery.", portletRegistry - .getPortletApplicationByIdentifier(TEST_PORTLET_APP_NAME)); - assertTrue(appName + " directory was not created, app not deployed.", appFile.exists()); + assertNotNull( + appName + " was not registered into the portlet registery.", + portletRegistry + .getPortletApplicationByIdentifier(TEST_PORTLET_APP_NAME)); + assertTrue(appName + " directory was not created, app not deployed.", + appFile.exists()); } - - - - /** *

        * verifyDemoAppDeleted *

        - * + * * @param demoApp - * - private void verifyDemoAppDeleted( String appName, File appFile ) - { - assertNull(appName + " was not removed from the registry.", portletRegistry - .getPortletApplicationByIdentifier(TEST_PORTLET_APP_NAME)); - assertFalse(appName+" directory was not deleted.", appFile.exists()); - } - */ + * + * private void verifyDemoAppDeleted( String appName, File appFile ) { + * assertNull(appName + " was not removed from the registry.", + * portletRegistry + * .getPortletApplicationByIdentifier(TEST_PORTLET_APP_NAME)); + * assertFalse(appName+" directory was not deleted.", appFile.exists()); } + */ /** * @see junit.framework.TestCase#setUp() @@ -364,21 +346,23 @@ copyFrom = new File("./test/deployment/deploy"); deploySrc = new File("./target/deployment/deploy"); deploySrc.mkdirs(); - deployRootFile = new File("./target/deployment/templates/decorators"); + deployRootFile = new File( + "./target/deployment/templates/decorators"); deployRootFile.mkdirs(); webAppsDirFile = new File("./target/deployment/webapps"); webAppsDirFile.mkdirs(); webAppsDir = webAppsDirFile.getCanonicalPath(); - testDb = new File("./test/db/hsql/Registry").getCanonicalPath(); - + testDb = new File("./test/db/hsql/Registry").getCanonicalPath(); + copyDeployables(); -// windowAccess = new PortletWindowAccessorImpl(entityAccess, true); + // windowAccess = new PortletWindowAccessorImpl(entityAccess, true); } catch (Exception e) { e.printStackTrace(); - throw new AssertionFailedError("Unable to set up test environment " + e.toString()); + throw new AssertionFailedError("Unable to set up test environment " + + e.toString()); } } @@ -387,38 +371,39 @@ *

        * copyDeployables *

        + * * @throws IOException */ protected void copyDeployables() throws IOException - { - - + { + copyFiles(copyFrom, deploySrc); - + } - - /** *

        * copyFiles *

        - * + * * @throws IOException * @throws FileNotFoundException */ - protected void copyFiles(File srcDir, File dstDir) throws IOException, FileNotFoundException + protected void copyFiles(File srcDir, File dstDir) throws IOException, + FileNotFoundException { File[] children = srcDir.listFiles(); - for(int i=0; iScott T. Weaver * @version $Id: TestSpringEngine.java 516881 2007-03-11 10:34:21Z ate $ - * + * */ public class TestSpringEngine extends AbstractEngineTest { + public TestSpringEngine() - { - keysToCheck = new Object[] {"IdGenerator", "DecorationLocator", "TemplateLocator", "IdGenerator", "PageFileCache", PageManager.class, - PortletRegistry.class, PortletEntityAccessComponent.class, "PortalServices", - Profiler.class, Capabilities.class, PreferencesProvider.class, UserManager.class, - GroupManager.class, RoleManager.class, PermissionManager.class, RdbmsPolicy.class, SecurityProvider.class, - UserInfoManager.class, RequestContextComponent.class, PortletWindowAccessor.class, - PortletRenderer.class, PageAggregator.class, PortletAggregator.class, "PAM", - "deploymentManager", "portletFactory", ServletConfig.class, - StaticInformationProvider.class, "NavigationalStateCodec", "PortalURL", "NavigationalStateComponent"}; + { + keysToCheck = new Object[] + {"IdGenerator", "DecorationLocator", "TemplateLocator", "IdGenerator", + "PageFileCache", PageManager.class, PortletRegistry.class, + PortletEntityAccessComponent.class, "PortalServices", + Profiler.class, Capabilities.class, PreferencesProvider.class, + UserManager.class, GroupManager.class, RoleManager.class, + PermissionManager.class, RdbmsPolicy.class, + SecurityProvider.class, UserInfoManager.class, + RequestContextComponent.class, PortletWindowAccessor.class, + PortletRenderer.class, PageAggregator.class, + PortletAggregator.class, "PAM", "deploymentManager", + "portletFactory", ServletConfig.class, + StaticInformationProvider.class, "NavigationalStateCodec", + "PortalURL", "NavigationalStateComponent"}; } - + public static Test suite() { // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestSpringEngine.class); } - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/FragmentUtil.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/FragmentUtil.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/FragmentUtil.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,9 +19,9 @@ import javax.security.auth.Subject; import org.apache.jetspeed.om.page.ContentPage; +import org.apache.jetspeed.om.page.ContentPageImpl; import org.apache.jetspeed.om.page.Fragment; import org.apache.jetspeed.om.page.Page; -import org.apache.jetspeed.om.page.ContentPageImpl; import org.apache.jetspeed.om.page.psml.PageImpl; import org.apache.jetspeed.request.JetspeedRequestContext; import org.apache.jetspeed.request.RequestContext; @@ -88,9 +88,9 @@ RequestContext a_oRC = new JetspeedRequestContext(request, response, config, null); - + a_oRC.setSubject(new Subject()); - + Page a_oPage = setupPage(); ContentPage a_oContentPage = new ContentPageImpl(a_oPage); @@ -105,11 +105,11 @@ // Prepare some fragments Fragment a_oLayout = buildFragment("layout", "6", "layout", 0, 0); Fragment a_oFrag1 = buildFragment("frag1", "1", "portlet", 0, 0); - Fragment a_oFrag2 = buildFragment("frag2", "2", "portlet", 0, 1); + Fragment a_oFrag2 = buildFragment("frag2", "2", "portlet", 0, 1); Fragment a_oFrag3 = buildFragment("frag3", "3", "portlet", 1, 0); Fragment a_oFrag4 = buildFragment("frag4", "4", "portlet", 1, 1); Fragment a_oFrag5 = buildFragment("frag5", "5", "portlet", 1, 2); - + LocalFragmentImpl a_oLocalLayout = (LocalFragmentImpl) a_oLayout; a_oLocalLayout.addFragment(a_oFrag1); a_oLocalLayout.addFragment(a_oFrag2); @@ -134,17 +134,17 @@ a_oFrag.setId(p_sId); return a_oFrag; } - + public static void debugContentOutput(RequestContext rc) { - MockHttpServletResponse mr = (MockHttpServletResponse) rc.getResponse(); + MockHttpServletResponse mr = (MockHttpServletResponse) rc.getResponse(); String content = mr.getOutputStreamContent(); System.out.println("content = " + content); } - + public static String getContentOutput(RequestContext rc) { - MockHttpServletResponse mr = (MockHttpServletResponse) rc.getResponse(); + MockHttpServletResponse mr = (MockHttpServletResponse) rc.getResponse(); return mr.getOutputStreamContent(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/LocalFragmentImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/LocalFragmentImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/LocalFragmentImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,10 +16,11 @@ */ package org.apache.jetspeed.layout; +import java.util.ArrayList; import java.util.List; + import org.apache.jetspeed.om.page.Fragment; import org.apache.jetspeed.om.page.psml.FragmentImpl; -import java.util.ArrayList; /** * Test for Fragment placement @@ -29,6 +30,7 @@ */ public class LocalFragmentImpl extends FragmentImpl { + private ArrayList m_oFragments = new ArrayList(); private String m_sName = null; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/MockPortletRegistryFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/MockPortletRegistryFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/MockPortletRegistryFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,10 +29,11 @@ /** * @version $Id: MockPortletRegistryFactory.java 598481 2007-11-27 00:47:29Z ate $ - * + * */ public class MockPortletRegistryFactory { + public static PortletRegistry createMockPortletRegistry() { Mock portletRegistryMock; @@ -44,10 +45,10 @@ Mock portletSizesParamMock; Parameter portletSizesParam; - + portletRegistryMock = new Mock(PortletRegistry.class); portletRegistry = (PortletRegistry) portletRegistryMock.proxy(); - + portletDefMock = new Mock(PortletDefinitionComposite.class); portletDef = (PortletDefinitionComposite) portletDefMock.proxy(); @@ -57,24 +58,30 @@ portletSizesParamMock = new Mock(Parameter.class); portletSizesParam = (Parameter) portletSizesParamMock.proxy(); - expectAndReturn(new InvokeAtLeastOnceMatcher(), portletSizesParamMock, "getValue", "33%,66%"); - expectAndReturn(new InvokeAtLeastOnceMatcher(), portletDefInitParamsMock, "get",new Constraint[] {new IsEqual("sizes")}, portletSizesParam); - expectAndReturn(new InvokeAtLeastOnceMatcher(), portletDefMock, "getInitParameterSet", portletDefInitParams); - expectAndReturn(new InvokeAtLeastOnceMatcher(), portletRegistryMock, "getPortletDefinitionByUniqueName",new Constraint[] {new IsEqual("layout")}, portletDef); + expectAndReturn(new InvokeAtLeastOnceMatcher(), portletSizesParamMock, + "getValue", "33%,66%"); + expectAndReturn(new InvokeAtLeastOnceMatcher(), + portletDefInitParamsMock, "get", new Constraint[] + {new IsEqual("sizes")}, portletSizesParam); + expectAndReturn(new InvokeAtLeastOnceMatcher(), portletDefMock, + "getInitParameterSet", portletDefInitParams); + expectAndReturn(new InvokeAtLeastOnceMatcher(), portletRegistryMock, + "getPortletDefinitionByUniqueName", new Constraint[] + {new IsEqual("layout")}, portletDef); return portletRegistry; } - - protected static void expectAndReturn(InvocationMatcher matcher, Mock mock, String methodName, Constraint[] constraints, Object returnValue) + + protected static void expectAndReturn(InvocationMatcher matcher, Mock mock, + String methodName, Constraint[] constraints, Object returnValue) { - mock.expects(matcher).method(methodName) - .with(constraints) - .will(new ReturnStub(returnValue)); + mock.expects(matcher).method(methodName).with(constraints).will( + new ReturnStub(returnValue)); } - - protected static void expectAndReturn(InvocationMatcher matcher, Mock mock, String methodName, Object returnValue) + + protected static void expectAndReturn(InvocationMatcher matcher, Mock mock, + String methodName, Object returnValue) { - mock.expects(matcher).method(methodName) - .withNoArguments() - .will(new ReturnStub(returnValue)); + mock.expects(matcher).method(methodName).withNoArguments().will( + new ReturnStub(returnValue)); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/TestConstraintsAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/TestConstraintsAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/TestConstraintsAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -41,6 +41,7 @@ import org.apache.jetspeed.security.JSSubject; import org.apache.jetspeed.security.impl.RolePrincipalImpl; import org.apache.jetspeed.security.impl.UserPrincipalImpl; + import com.mockrunner.mock.web.MockHttpServletRequest; import com.mockrunner.mock.web.MockHttpServletResponse; import com.mockrunner.mock.web.MockHttpSession; @@ -49,7 +50,7 @@ /** * Test Security Constraints Manipulation - * + * * @author David Sean Taylor * @version $Id: $ */ @@ -59,7 +60,7 @@ private ComponentManager cm; private LayoutValve valve; - + private PageManager pageManager; public static void main(String[] args) @@ -74,22 +75,23 @@ { super.setUp(); - String appRoot = "./"; //PortalTestConstants.JETSPEED_APPLICATION_ROOT; - - MockServletConfig servletConfig = new MockServletConfig(); - ResourceLocatingServletContext servletContent = new ResourceLocatingServletContext(new File(appRoot)); + String appRoot = "./"; // PortalTestConstants.JETSPEED_APPLICATION_ROOT; + + MockServletConfig servletConfig = new MockServletConfig(); + ResourceLocatingServletContext servletContent = new ResourceLocatingServletContext( + new File(appRoot)); servletConfig.setServletContext(servletContent); ServletConfigFactoryBean.setServletConfig(servletConfig); - + // Load the Spring configs String[] bootConfigs = null; String[] appConfigs = - { //"src/webapp/WEB-INF/assembly/layout-api.xml", - "src/test/resources/assembly/test-layout-constraints-api.xml", + { // "src/webapp/WEB-INF/assembly/layout-api.xml", + "src/test/resources/assembly/test-layout-constraints-api.xml", "src/test/resources/assembly/page-manager.xml"}; - - - cm = new SpringComponentManager(bootConfigs, appConfigs, servletContent, "."); + + cm = new SpringComponentManager(bootConfigs, appConfigs, + servletContent, "."); cm.start(); valve = (LayoutValve) cm.getComponent("layoutValve"); pageManager = (PageManager) cm.getComponent("pageManager"); @@ -100,145 +102,179 @@ cm.stop(); } - public void testUpdate() - throws Exception + public void testUpdate() throws Exception { String method = "update-def"; String defName = "users"; - String xml = - "user, managerview,edit"; + String xml = "user, managerview,edit"; runTest(xml, defName, method); PageSecurity pageSecurity = pageManager.getPageSecurity(); - SecurityConstraintsDef def = pageSecurity.getSecurityConstraintsDef(defName); + SecurityConstraintsDef def = pageSecurity + .getSecurityConstraintsDef(defName); assertNotNull("definition " + defName + " not found ", def); - SecurityConstraint constraint = (SecurityConstraint)def.getSecurityConstraints().get(0); + SecurityConstraint constraint = (SecurityConstraint) def + .getSecurityConstraints().get(0); assertNotNull("first constraint for " + defName + " not found ", def); - assertEquals("update failed for constraints " + constraint.getPermissions().toString(), constraint.getPermissions().toString(), "[view, edit]"); + assertEquals("update failed for constraints " + + constraint.getPermissions().toString(), constraint + .getPermissions().toString(), "[view, edit]"); } - public void testAdd() - throws Exception + public void testAdd() throws Exception { String method = "add-def"; String defName = "newone"; - String xml = - "user, managerview,edit"; + String xml = "user, managerview,edit"; runTest(xml, defName, method); PageSecurity pageSecurity = pageManager.getPageSecurity(); - SecurityConstraintsDef def = pageSecurity.getSecurityConstraintsDef(defName); + SecurityConstraintsDef def = pageSecurity + .getSecurityConstraintsDef(defName); assertNotNull("definition " + defName + " not found ", def); - SecurityConstraint constraint = (SecurityConstraint)def.getSecurityConstraints().get(0); + SecurityConstraint constraint = (SecurityConstraint) def + .getSecurityConstraints().get(0); assertNotNull("first constraint for " + defName + " not found ", def); - assertEquals("update failed for constraints " + constraint.getPermissions().toString(), constraint.getPermissions().toString(), "[view, edit]"); + assertEquals("update failed for constraints " + + constraint.getPermissions().toString(), constraint + .getPermissions().toString(), "[view, edit]"); } - - public void testAdds() - throws Exception + + public void testAdds() throws Exception { - String method = "update-def"; + String method = "update-def"; String defName = "users"; - String xml = - "user, manager,anonview,edit,help" + - "accounting,financeview,edit,help" + - "tomcatview" + - "manager,adminview,help" + - ""; - + String xml = "user, manager,anonview,edit,help" + + "accounting,financeview,edit,help" + + "tomcatview" + + "manager,adminview,help" + + ""; + runTest(xml, defName, method); PageSecurity pageSecurity = pageManager.getPageSecurity(); - SecurityConstraintsDef def = pageSecurity.getSecurityConstraintsDef(defName); + SecurityConstraintsDef def = pageSecurity + .getSecurityConstraintsDef(defName); assertNotNull("definition " + defName + " not found ", def); - SecurityConstraint constraint = (SecurityConstraint)def.getSecurityConstraints().get(0); - assertNotNull("first constraint for " + defName + " not found ", constraint); - assertEquals("update failed for constraints " + constraint.getPermissions().toString(), constraint.getPermissions().toString(), "[view, edit, help]"); - assertEquals("update failed for constraints " + constraint.getRoles().toString(), constraint.getRoles().toString(), "[user, manager, anon]"); - - SecurityConstraint constraint2 = (SecurityConstraint)def.getSecurityConstraints().get(1); - assertNotNull("second constraint for " + defName + " not found ", constraint2); - assertEquals("add failed for constraints " + constraint2.getPermissions().toString(), constraint2.getPermissions().toString(), "[view, edit, help]"); - assertEquals("add failed for constraints " + constraint2.getGroups().toString(), constraint2.getGroups().toString(), "[accounting, finance]"); + SecurityConstraint constraint = (SecurityConstraint) def + .getSecurityConstraints().get(0); + assertNotNull("first constraint for " + defName + " not found ", + constraint); + assertEquals("update failed for constraints " + + constraint.getPermissions().toString(), constraint + .getPermissions().toString(), "[view, edit, help]"); + assertEquals("update failed for constraints " + + constraint.getRoles().toString(), constraint.getRoles() + .toString(), "[user, manager, anon]"); - SecurityConstraint constraint3 = (SecurityConstraint)def.getSecurityConstraints().get(2); - assertNotNull("third constraint for " + defName + " not found ", constraint3); - assertEquals("add failed for constraints " + constraint3.getPermissions().toString(), constraint3.getPermissions().toString(), "[view]"); - assertEquals("add failed for constraints " + constraint3.getUsers().toString(), constraint3.getUsers().toString(), "[tomcat]"); + SecurityConstraint constraint2 = (SecurityConstraint) def + .getSecurityConstraints().get(1); + assertNotNull("second constraint for " + defName + " not found ", + constraint2); + assertEquals("add failed for constraints " + + constraint2.getPermissions().toString(), constraint2 + .getPermissions().toString(), "[view, edit, help]"); + assertEquals("add failed for constraints " + + constraint2.getGroups().toString(), constraint2.getGroups() + .toString(), "[accounting, finance]"); - SecurityConstraint constraint4 = (SecurityConstraint)def.getSecurityConstraints().get(3); - assertNotNull("fourth constraint for " + defName + " not found ", constraint4); - assertEquals("add failed for constraints " + constraint4.getPermissions().toString(), constraint4.getPermissions().toString(), "[view, help]"); - assertEquals("add failed for constraints " + constraint4.getUsers().toString(), constraint4.getUsers().toString(), "[manager, admin]"); - + SecurityConstraint constraint3 = (SecurityConstraint) def + .getSecurityConstraints().get(2); + assertNotNull("third constraint for " + defName + " not found ", + constraint3); + assertEquals("add failed for constraints " + + constraint3.getPermissions().toString(), constraint3 + .getPermissions().toString(), "[view]"); + assertEquals("add failed for constraints " + + constraint3.getUsers().toString(), constraint3.getUsers() + .toString(), "[tomcat]"); + + SecurityConstraint constraint4 = (SecurityConstraint) def + .getSecurityConstraints().get(3); + assertNotNull("fourth constraint for " + defName + " not found ", + constraint4); + assertEquals("add failed for constraints " + + constraint4.getPermissions().toString(), constraint4 + .getPermissions().toString(), "[view, help]"); + assertEquals("add failed for constraints " + + constraint4.getUsers().toString(), constraint4.getUsers() + .toString(), "[manager, admin]"); + } - public void testDeletes() - throws Exception + public void testDeletes() throws Exception { - String method = "update-def"; + String method = "update-def"; String defName = "delete3"; - String xml = - "*view"; + String xml = "*view"; runTest(xml, defName, method); PageSecurity pageSecurity = pageManager.getPageSecurity(); - SecurityConstraintsDef def = pageSecurity.getSecurityConstraintsDef(defName); + SecurityConstraintsDef def = pageSecurity + .getSecurityConstraintsDef(defName); assertNotNull("definition " + defName + " not found ", def); - SecurityConstraint constraint = (SecurityConstraint)def.getSecurityConstraints().get(0); + SecurityConstraint constraint = (SecurityConstraint) def + .getSecurityConstraints().get(0); assertNotNull("first constraint for " + defName + " not found ", def); - assertEquals("delete merge failed for constraints " + constraint.getPermissions().toString(), constraint.getPermissions().toString(), "[view]"); - assertEquals("delete merge failed for constraints " + constraint.getUsers().toString(), constraint.getUsers().toString(), "[*]"); - assertTrue("constrainst size should be 1 ", def.getSecurityConstraints().size() == 1); + assertEquals("delete merge failed for constraints " + + constraint.getPermissions().toString(), constraint + .getPermissions().toString(), "[view]"); + assertEquals("delete merge failed for constraints " + + constraint.getUsers().toString(), constraint.getUsers() + .toString(), "[*]"); + assertTrue("constrainst size should be 1 ", def + .getSecurityConstraints().size() == 1); } - public void testDeleteDef() - throws Exception + public void testDeleteDef() throws Exception { - String method = "remove-def"; + String method = "remove-def"; String defName = "deleteme"; String xml = ""; runTest(xml, defName, method); PageSecurity pageSecurity = pageManager.getPageSecurity(); - SecurityConstraintsDef def = pageSecurity.getSecurityConstraintsDef(defName); + SecurityConstraintsDef def = pageSecurity + .getSecurityConstraintsDef(defName); assertNull("definition " + defName + " should be deleted ", def); } - public void testAddGlobal() - throws Exception + public void testAddGlobal() throws Exception { - String method = "add-global"; + String method = "add-global"; String defName = "manager"; String xml = ""; runTest(xml, defName, method); PageSecurity pageSecurity = pageManager.getPageSecurity(); List globals = pageSecurity.getGlobalSecurityConstraintsRefs(); - assertTrue("should have found new global " + defName, globals.contains(defName)); - assertTrue("should have found old global " + defName, globals.contains("admin")); + assertTrue("should have found new global " + defName, globals + .contains(defName)); + assertTrue("should have found old global " + defName, globals + .contains("admin")); } - public void testDeleteGlobal() - throws Exception + public void testDeleteGlobal() throws Exception { - PageSecurity pageSecurity = pageManager.getPageSecurity(); - String method = "add-global"; + PageSecurity pageSecurity = pageManager.getPageSecurity(); + String method = "add-global"; String defName = "public-edit"; - String xml = ""; + String xml = ""; runTest(xml, defName, method); List globals = pageSecurity.getGlobalSecurityConstraintsRefs(); - assertTrue("should have found new global " + defName, globals.contains(defName)); - method = "remove-global"; + assertTrue("should have found new global " + defName, globals + .contains(defName)); + method = "remove-global"; runTest(xml, defName, method); globals = pageSecurity.getGlobalSecurityConstraintsRefs(); - assertFalse("should have not found new global " + defName, globals.contains(defName)); + assertFalse("should have not found new global " + defName, globals + .contains(defName)); } - + public void runTest(String xml, String defName, String method) - throws Exception + throws Exception { MockServletConfig config = new MockServletConfig(); MockServletContext context = new MockServletContext(); @@ -252,32 +288,32 @@ request.setSession(session); MockHttpServletResponse response = new MockHttpServletResponse(); - final RequestContext rc = - new JetspeedRequestContext(request, response, config, null); - + final RequestContext rc = new JetspeedRequestContext(request, response, + config, null); + Set principals = new HashSet(); principals.add(new UserPrincipalImpl("admin")); principals.add(new RolePrincipalImpl("admin")); - Subject subject = new Subject(true, principals, new HashSet(), new HashSet()); - + Subject subject = new Subject(true, principals, new HashSet(), + new HashSet()); + JSSubject.doAsPrivileged(subject, new PrivilegedAction() + { + + public Object run() + { + try { - public Object run() - { - try - { - valve.invoke(rc, null); - return null; - } - catch (PipelineException e) - { - return e; - } - } - }, null); - - + valve.invoke(rc, null); + return null; + } + catch (PipelineException e) + { + return e; + } + } + }, null); + } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/TestLayout.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/TestLayout.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/TestLayout.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,6 +27,7 @@ import org.apache.jetspeed.mocks.ResourceLocatingServletContext; import org.apache.jetspeed.pipeline.PipelineException; import org.apache.jetspeed.request.RequestContext; + import com.mockrunner.mock.web.MockServletConfig; /** @@ -41,7 +42,7 @@ private ComponentManager cm; private LayoutValve valve; - + public static void main(String[] args) { junit.swingui.TestRunner.run(TestLayout.class); @@ -54,21 +55,22 @@ { super.setUp(); - String appRoot = "./"; //PortalTestConstants.JETSPEED_APPLICATION_ROOT; - - MockServletConfig servletConfig = new MockServletConfig(); - ResourceLocatingServletContext servletContent = new ResourceLocatingServletContext(new File(appRoot)); + String appRoot = "./"; // PortalTestConstants.JETSPEED_APPLICATION_ROOT; + + MockServletConfig servletConfig = new MockServletConfig(); + ResourceLocatingServletContext servletContent = new ResourceLocatingServletContext( + new File(appRoot)); servletConfig.setServletContext(servletContent); ServletConfigFactoryBean.setServletConfig(servletConfig); - + // Load the Spring configs String[] bootConfigs = null; String[] appConfigs = - { //"src/webapp/WEB-INF/assembly/layout-api.xml", - "src/test/resources/assembly/test-layout-api.xml"}; - - - cm = new SpringComponentManager(bootConfigs, appConfigs, servletContent, "."); + { // "src/webapp/WEB-INF/assembly/layout-api.xml", + "src/test/resources/assembly/test-layout-api.xml"}; + + cm = new SpringComponentManager(bootConfigs, appConfigs, + servletContent, "."); cm.start(); valve = (LayoutValve) cm.getComponent("layoutValve"); } @@ -80,12 +82,13 @@ public void testNullRequestContext() { - // Get the layout that has a null request context + // Get the layout that has a null request context try { valve.invoke(null, null); TestLayout.fail("should have thrown an exception"); - } catch (PipelineException e) + } + catch (PipelineException e) { TestLayout.assertTrue("detected null request context", true); } @@ -96,12 +99,13 @@ try { // Test the success case - RequestContext rc = FragmentUtil - .setupRequestContext(null, "1234", "0", "0"); + RequestContext rc = FragmentUtil.setupRequestContext(null, "1234", + "0", "0"); valve.invoke(rc, null); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "failure")); - } catch (PipelineException e) + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "failure")); + } + catch (PipelineException e) { TestLayout.fail("unexpected exception"); } @@ -109,14 +113,15 @@ try { // Test the success case - RequestContext rc = FragmentUtil.setupRequestContext("moveabs", "33", "0", - "0"); + RequestContext rc = FragmentUtil.setupRequestContext("moveabs", + "33", "0", "0"); valve.invoke(rc, null); // Take a look at the response to verify a failiure - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "failure")); - } catch (PipelineException e) + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "failure")); + } + catch (PipelineException e) { TestLayout.fail("unexpected exception"); } @@ -124,14 +129,15 @@ try { // Test the success case - RequestContext rc = FragmentUtil.setupRequestContext("moveabs", "1234", - null, "0"); + RequestContext rc = FragmentUtil.setupRequestContext("moveabs", + "1234", null, "0"); valve.invoke(rc, null); // Take a look at the response to verify a failiure - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "failure")); - } catch (PipelineException e) + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "failure")); + } + catch (PipelineException e) { TestLayout.fail("unexpected exception"); } @@ -139,14 +145,15 @@ try { // Test the success case - RequestContext rc = FragmentUtil.setupRequestContext("moveabs", "1234", - "0", null); + RequestContext rc = FragmentUtil.setupRequestContext("moveabs", + "1234", "0", null); valve.invoke(rc, null); // Take a look at the response to verify a failiure - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "failure")); - } catch (PipelineException e) + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "failure")); + } + catch (PipelineException e) { TestLayout.fail("unexpected exception"); } @@ -155,111 +162,116 @@ public void testEasy() { moveSuccess("moveabs", "1", "0", "0", "0", "1", "0", "1"); // Move down - moveSuccess("moveright", "1", "0", "0", "1", "0", "1", "0"); // Straight across + moveSuccess("moveright", "1", "0", "0", "1", "0", "1", "0"); // Straight + // across } - + public void testMoveSuccess() { moveSuccess("moveabs", "1", "0", "0", "0", "0", "-1", "-1"); // Doesn't - // really - // move + // really + // move moveSuccess("moveabs", "1", "0", "0", "0", "1", "0", "1"); // Move down moveSuccess("moveabs", "2", "0", "1", "0", "0", "0", "0"); // Move up moveSuccess("moveabs", "1", "0", "0", "1", "0", "1", "0"); // Move - // right + // right moveSuccess("moveabs", "3", "1", "0", "0", "0", "0", "0"); // Move left moveSuccess("moveabs", "2", "0", "1", "1", "2", "1", "2"); // Move - // right & - // move down + // right & + // move down moveSuccess("moveabs", "3", "1", "0", "0", "1", "0", "1"); // Move left - // & move - // down + // & move + // down moveSuccess("moveabs", "4", "1", "1", "0", "0", "0", "0"); // Move left - // & move up + // & move up moveSuccess("moveabs", "1", "0", "0", "0", "2", "0", "1"); // Move too - // far down, - // should be - // at end of - // row - moveSuccess("moveabs", "2", "0", "1", "0", "2", "-1", "-1"); // Move too - // far down, - // shouldn't - // move + // far down, + // should be + // at end of + // row + moveSuccess("moveabs", "2", "0", "1", "0", "2", "-1", "-1"); // Move + // too + // far down, + // shouldn't + // move moveSuccess("moveabs", "3", "1", "0", "1", "3", "1", "2"); // Move too - // far down, - // should be - // at end of - // row + // far down, + // should be + // at end of + // row moveSuccess("moveabs", "4", "1", "1", "1", "3", "1", "2"); // Move too - // far down, - // should be - // at end of - // row - moveSuccess("moveabs", "5", "1", "2", "1", "3", "-1", "-1"); // Move too - // far down, - // shouldn't - // move + // far down, + // should be + // at end of + // row + moveSuccess("moveabs", "5", "1", "2", "1", "3", "-1", "-1"); // Move + // too + // far down, + // shouldn't + // move moveSuccess("moveabs", "1", "0", "0", "1", "4", "1", "3"); // Move too - // far down, - // should be - // at end of - // row + // far down, + // should be + // at end of + // row moveSuccess("moveabs", "2", "0", "1", "1", "4", "1", "3"); // Move too - // far down, - // should be - // at end of - // row + // far down, + // should be + // at end of + // row moveSuccess("moveleft", "1", "0", "0", "0", "0", "-1", "-1"); // Shouldn't - // move -// Root layout ("6") shouldn't/cannot be moved, so the following test doesn't make sense -// moveSuccess("moveleft", "6", "0", "0", "0", "0", "-1", "-1"); // Shouldn't - // move + // move + // Root layout ("6") shouldn't/cannot be moved, so the following test + // doesn't make sense + // moveSuccess("moveleft", "6", "0", "0", "0", "0", "-1", "-1"); // + // Shouldn't + // move moveSuccess("moveleft", "3", "1", "0", "0", "0", "0", "0"); // Straight - // across + // across moveSuccess("moveleft", "4", "1", "1", "0", "1", "0", "1"); // Straight - // across + // across moveSuccess("moveleft", "5", "1", "2", "0", "2", "0", "2"); // Straight - // across + // across moveSuccess("moveright", "1", "0", "0", "1", "0", "1", "0"); // Straight - // across + // across moveSuccess("moveright", "2", "0", "1", "1", "1", "1", "1"); // Straight - // across + // across moveSuccess("moveright", "3", "1", "0", "2", "0", "-1", "-1"); // Shouldn't - // move + // move moveSuccess("moveright", "4", "1", "1", "2", "0", "-1", "-1"); // Shouldn't - // move + // move moveSuccess("moveright", "5", "1", "2", "2", "0", "-1", "-1"); // Shouldn't - // move + // move moveSuccess("moveup", "2", "0", "1", "0", "0", "0", "0"); // Straight - // across + // across moveSuccess("moveup", "4", "1", "1", "1", "0", "1", "0"); // Straight - // across + // across moveSuccess("moveup", "5", "1", "2", "1", "1", "1", "1"); // Straight - // across + // across moveSuccess("movedown", "1", "0", "0", "0", "1", "0", "1"); // Straight - // across + // across moveSuccess("movedown", "2", "0", "1", "0", "1", "-1", "-1"); // Shouldn't - // move + // move moveSuccess("movedown", "3", "1", "0", "1", "1", "1", "1"); // Straight - // across + // across moveSuccess("movedown", "4", "1", "1", "1", "2", "1", "2"); // Straight - // across + // across moveSuccess("movedown", "5", "1", "2", "1", "2", "-1", "-1"); // Shouldn't - // move + // move } public void testMoveFailure() { moveFailure("moveabs", "bogus", "0", "0", "0", "0"); // non integer - // portlet id + // portlet id moveFailure("moveleft", "0", "0", "0", "0", "0"); // portlet not found // moveFailure("moveabs", "1", "0", "0", "3", "0"); // non existent - // column + // column moveFailure("bogus", "0", "0", "0", "0", "0"); // bogus action moveFailure("moveabs", "1", "0", "0", "a", "0"); // non integer value moveFailure("moveabs", "1", "0", "0", "0", "b"); // non integer value @@ -276,36 +288,40 @@ if (a_sMoveType.equalsIgnoreCase("moveabs")) { - rc = FragmentUtil.setupRequestContext(a_sMoveType, p_sPortletId, - p_sNewCol, p_sNewRow); - } else + rc = FragmentUtil.setupRequestContext(a_sMoveType, + p_sPortletId, p_sNewCol, p_sNewRow); + } + else { - rc = FragmentUtil.setupRequestContext(a_sMoveType, p_sPortletId, null, - null); + rc = FragmentUtil.setupRequestContext(a_sMoveType, + p_sPortletId, null, null); } valve.invoke(rc, null); // Take a look at the response to verify a failiure - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "success")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "success")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "" + a_sMoveType + "")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "" + p_sPortletId + "")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "" + p_sOldCol + "" - + p_sOldRow + "")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "" + p_sExpectedNewCol + "" - + p_sExpectedNewRow + "")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "")); - } catch (PipelineException e) + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "success")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "success")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "" + a_sMoveType + "")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "" + p_sPortletId + "")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "" + p_sOldCol + + "" + p_sOldRow + + "")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "" + p_sExpectedNewCol + + "" + p_sExpectedNewRow + + "")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "")); + } + catch (PipelineException e) { e.printStackTrace(); TestLayout.fail("layout valve failed"); @@ -323,21 +339,23 @@ if (a_sMoveType.equalsIgnoreCase("moveabs")) { - rc = FragmentUtil.setupRequestContext(a_sMoveType, p_sPortletId, - p_sNewCol, p_sNewRow); - } else + rc = FragmentUtil.setupRequestContext(a_sMoveType, + p_sPortletId, p_sNewCol, p_sNewRow); + } + else { - rc = FragmentUtil.setupRequestContext(a_sMoveType, p_sPortletId, null, - null); + rc = FragmentUtil.setupRequestContext(a_sMoveType, + p_sPortletId, null, null); } valve.invoke(rc, null); - //FragmentUtil.debugContentOutput(rc); - - // Take a look at the response to verify a failure - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "failure")); - } catch (PipelineException p) + // FragmentUtil.debugContentOutput(rc); + + // Take a look at the response to verify a failure + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "failure")); + } + catch (PipelineException p) { TestLayout.fail("unexpected exception"); } @@ -349,18 +367,22 @@ if (a_sMoveType.equalsIgnoreCase("moveabs")) { - rc = FragmentUtil.setupRequestContext(a_sMoveType, "1234", "0", "foo"); - } else + rc = FragmentUtil.setupRequestContext(a_sMoveType, "1234", "0", + "foo"); + } + else { - rc = FragmentUtil.setupRequestContext(a_sMoveType, "1234", null, null); + rc = FragmentUtil.setupRequestContext(a_sMoveType, "1234", + null, null); } valve.invoke(rc, null); // Take a look at the response to verify a failiure - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "failure")); - } catch (PipelineException p) + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "failure")); + } + catch (PipelineException p) { TestLayout.fail("unexpected exception"); } @@ -381,32 +403,34 @@ // Test the success case RequestContext rc = null; - rc = FragmentUtil.setupRequestContext("remove", p_sPortletId, null, null); + rc = FragmentUtil.setupRequestContext("remove", p_sPortletId, null, + null); valve.invoke(rc, null); // Take a look at the response to verify a failiure - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "success")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "success")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "" + "remove" + "")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "" + p_sPortletId + "")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "")); - TestLayout.assertTrue("couldn't find value", FragmentUtil.findValue(rc, - "")); - } catch (PipelineException e) + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "success")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "success")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "" + "remove" + "")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "" + p_sPortletId + "")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "")); + TestLayout.assertTrue("couldn't find value", FragmentUtil + .findValue(rc, "")); + } + catch (PipelineException e) { e.printStackTrace(); TestLayout.fail("layout valve failed"); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/TestPortletPlacement.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/TestPortletPlacement.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/layout/TestPortletPlacement.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,12 +32,15 @@ */ public class TestPortletPlacement extends TestCase { + private PortletRegistry portletRegistry; - public void setUp(){ - portletRegistry = MockPortletRegistryFactory.createMockPortletRegistry(); + public void setUp() + { + portletRegistry = MockPortletRegistryFactory + .createMockPortletRegistry(); } - + public void testGetFragmentAt() { // Build a request object and populate it with fragments @@ -45,7 +48,8 @@ try { - PortletPlacementContext ppc = new PortletPlacementContextImpl(requestContext.getPage(),portletRegistry); + PortletPlacementContext ppc = new PortletPlacementContextImpl( + requestContext.getPage(), portletRegistry); int a_iNumCols = ppc.getNumberColumns(); assertEquals(a_iNumCols, 2); @@ -86,7 +90,8 @@ assertEquals(a_oFrag.getId(), "5"); assertEquals(a_oFrag.getName(), "frag5"); - } catch (PortletPlacementException e) + } + catch (PortletPlacementException e) { fail("creating the PortletPlacementManager failed"); } @@ -99,7 +104,8 @@ try { - PortletPlacementContext ppc = new PortletPlacementContextImpl(requestContext.getPage(),portletRegistry); + PortletPlacementContext ppc = new PortletPlacementContextImpl( + requestContext.getPage(), portletRegistry); // Check the fragments Fragment a_oFrag = ppc.getFragmentById("1"); @@ -127,7 +133,8 @@ assertEquals(a_oFrag.getId(), "5"); assertEquals(a_oFrag.getName(), "frag5"); - } catch (PortletPlacementException e) + } + catch (PortletPlacementException e) { fail("creating the PortletPlacementManager failed"); } @@ -139,7 +146,8 @@ try { - PortletPlacementContext ppc = new PortletPlacementContextImpl(requestContext.getPage(),portletRegistry); + PortletPlacementContext ppc = new PortletPlacementContextImpl( + requestContext.getPage(), portletRegistry); Fragment a_oFrag = ppc .getFragmentAtNewCoordinate(new CoordinateImpl(0, 0, 0, 0)); @@ -154,7 +162,8 @@ 0, 0)); assertEquals(a_oFrag.getId(), "2"); assertEquals(a_oFrag.getName(), "frag2"); - } catch (PortletPlacementException e) + } + catch (PortletPlacementException e) { fail("creating the PortletPlacementManager failed"); } @@ -166,13 +175,14 @@ try { - PortletPlacementContext ppc = new PortletPlacementContextImpl(requestContext.getPage(),portletRegistry); + PortletPlacementContext ppc = new PortletPlacementContextImpl( + requestContext.getPage(), portletRegistry); Fragment a_oFrag = ppc .getFragmentAtNewCoordinate(new CoordinateImpl(0, 0, 0, 0)); - Coordinate a_oCoordinate = ppc.moveAbsolute(a_oFrag, new CoordinateImpl( - 0, 0, 0, 1)); + Coordinate a_oCoordinate = ppc.moveAbsolute(a_oFrag, + new CoordinateImpl(0, 0, 0, 1)); assertEquals(a_oCoordinate.getOldCol(), 0); assertEquals(a_oCoordinate.getOldRow(), 0); @@ -189,7 +199,8 @@ 0, 1)); assertEquals(a_oFrag.getId(), "1"); assertEquals(a_oFrag.getName(), "frag1"); - } catch (PortletPlacementException e) + } + catch (PortletPlacementException e) { fail("creating the PortletPlacementManager failed"); } @@ -201,7 +212,8 @@ try { - PortletPlacementContext ppc = new PortletPlacementContextImpl(requestContext.getPage(),portletRegistry); + PortletPlacementContext ppc = new PortletPlacementContextImpl( + requestContext.getPage(), portletRegistry); Fragment a_oFrag = ppc .getFragmentAtNewCoordinate(new CoordinateImpl(0, 0, 0, 1)); @@ -223,7 +235,8 @@ 0, 1)); assertEquals(a_oFrag.getId(), "1"); assertEquals(a_oFrag.getName(), "frag1"); - } catch (PortletPlacementException e) + } + catch (PortletPlacementException e) { fail("creating the PortletPlacementManager failed"); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/pipeline/TestPipeline.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/pipeline/TestPipeline.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/pipeline/TestPipeline.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,18 +27,20 @@ /** * TestPipeline - * + * * @author David Sean Taylor * @version $Id: TestPipeline.java 598476 2007-11-27 00:39:21Z ate $ */ public class TestPipeline extends TestCase { - private Engine engine; + + private Engine engine; + private SpringEngineHelper engineHelper; /** * Tests - * + * * @throws Exception */ public void testPipeline() throws Exception @@ -52,22 +54,25 @@ { valvesMap.put(valves[i].toString(), valves[i]); } - assertNotNull("CapabilityValveImpl", valvesMap.get("CapabilityValveImpl")); + assertNotNull("CapabilityValveImpl", valvesMap + .get("CapabilityValveImpl")); assertNotNull("PortalURLValveImpl", valvesMap.get("PortalURLValveImpl")); assertNotNull("SecurityValve", valvesMap.get("SecurityValve")); assertNotNull("LocalizationValve", valvesMap.get("LocalizationValve")); - assertNotNull("PasswordCredentialValve", valvesMap.get("PasswordCredentialValve")); - assertNotNull("LoginValidationValve", valvesMap.get("LoginValidationValve")); + assertNotNull("PasswordCredentialValve", valvesMap + .get("PasswordCredentialValve")); + assertNotNull("LoginValidationValve", valvesMap + .get("LoginValidationValve")); assertNotNull("ProfilerValve", valvesMap.get("ProfilerValve")); assertNotNull("ContainerValve", valvesMap.get("ContainerValve")); assertNotNull("ActionValveImpl", valvesMap.get("ActionValveImpl")); assertNotNull("ResourceValveImpl", valvesMap.get("ResourceValveImpl")); assertNotNull("DecorationValve", valvesMap.get("DecorationValve")); - assertNotNull("HeaderAggregatorValve", valvesMap.get("HeaderAggregatorValve")); + assertNotNull("HeaderAggregatorValve", valvesMap + .get("HeaderAggregatorValve")); assertNotNull("AggregatorValve", valvesMap.get("AggregatorValve")); assertNotNull("CleanupValveImpl", valvesMap.get("CleanupValveImpl")); - - + assertNotNull(engine.getPipeline("action-pipeline")); assertNotNull(engine.getPipeline("portlet-pipeline")); } @@ -77,7 +82,7 @@ Map context = new HashMap(); engineHelper = new SpringEngineHelper(context); engineHelper.setUp(); - this.engine = (Engine)context.get(SpringEngineHelper.ENGINE_ATTR); + this.engine = (Engine) context.get(SpringEngineHelper.ENGINE_ATTR); } protected void tearDown() throws Exception Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/test/JetspeedTest.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/test/JetspeedTest.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/test/JetspeedTest.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,61 +22,58 @@ import org.apache.jetspeed.engine.Engine; import org.apache.jetspeed.engine.JetspeedEngineConstants; - /** * Tests the Jetspeed Engine. - * + * * @author David Sean Taylor * @since 2.0 * @version $Id: JetspeedTest.java 516448 2007-03-09 16:25:47Z ate $ */ -public abstract class JetspeedTest extends TestCase implements JetspeedEngineConstants +public abstract class JetspeedTest extends TestCase implements + JetspeedEngineConstants { - - - /** * Creates a new instance. */ public JetspeedTest(String testName) { super(testName); - + } /** * Return the Test */ public static Test suite() - { + { return new JetspeedTestSuite(JetspeedTest.class); } protected Engine engine = null; - protected JetspeedTestSuite jsuite; + protected JetspeedTestSuite jsuite; + /** * Setup the test. */ public void setUp() throws Exception { - + super.setUp(); } /** * Override to set your own properties file - * + * */ -// public String getPropertiesFile() -// { -// return jsuite.getPropertiesFile(); -// } - + // public String getPropertiesFile() + // { + // return jsuite.getPropertiesFile(); + // } /** * Override to set your own application root - * + * */ public String getApplicationRoot() { @@ -91,8 +88,4 @@ } - - - - } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/test/JetspeedTestSuite.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/test/JetspeedTestSuite.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/test/JetspeedTestSuite.java 2008-05-16 01:54:54 UTC (rev 940) @@ -47,21 +47,23 @@ * * @author Scott T. Weaver * @version $Id: JetspeedTestSuite.java 517719 2007-03-13 15:05:48Z ate $ - * + * */ public class JetspeedTestSuite extends TestSuite { + protected static Engine engine = null; - private static SpringEngineHelper engineHelper; + private static SpringEngineHelper engineHelper; + /** * */ public JetspeedTestSuite() { super(); - startEngine(getApplicationRoot(), getPropertiesFile()); - + startEngine(getApplicationRoot(), getPropertiesFile()); + } /** @@ -71,8 +73,8 @@ public JetspeedTestSuite(Class arg0, String arg1) { super(arg0, arg1); - startEngine(getApplicationRoot(), getPropertiesFile()); - + startEngine(getApplicationRoot(), getPropertiesFile()); + } /** @@ -81,8 +83,8 @@ public JetspeedTestSuite(Class arg0) { super(arg0); - startEngine(getApplicationRoot(), getPropertiesFile()); - + startEngine(getApplicationRoot(), getPropertiesFile()); + } /** @@ -91,25 +93,26 @@ public JetspeedTestSuite(String arg0) { super(arg0); - startEngine(getApplicationRoot(), getPropertiesFile()); - + startEngine(getApplicationRoot(), getPropertiesFile()); + } - protected static void startEngine(String applicationRoot, String propertiesFilename) + protected static void startEngine(String applicationRoot, + String propertiesFilename) { try { - if (engine != null) - { - return; - } - - Configuration properties = new PropertiesConfiguration(propertiesFilename); + if (engine != null) { return; } - properties.setProperty(JetspeedEngineConstants.APPLICATION_ROOT_KEY, applicationRoot); - //properties.setProperty(WEBAPP_ROOT_KEY, null); + Configuration properties = new PropertiesConfiguration( + propertiesFilename); + + properties.setProperty( + JetspeedEngineConstants.APPLICATION_ROOT_KEY, + applicationRoot); + // properties.setProperty(WEBAPP_ROOT_KEY, null); initializeConfiguration(properties, applicationRoot); - //Mock servletConfigMock = new Mock(ServletConfig.class); + // Mock servletConfigMock = new Mock(ServletConfig.class); MockServletConfig msc = new MockServletConfig(); msc.setServletContext(new MockServletContext()); HashMap context = new HashMap(); @@ -124,6 +127,7 @@ } } + protected static void stopEngine() { try @@ -145,33 +149,42 @@ /** * Override to set your own application root - * + * */ public String getApplicationRoot() { - String applicationRoot = System.getProperty(JetspeedEngineConstants.APPLICATION_ROOT_KEY, PortalTestConstants.PORTAL_WEBAPP_PATH); + String applicationRoot = System.getProperty( + JetspeedEngineConstants.APPLICATION_ROOT_KEY, + PortalTestConstants.PORTAL_WEBAPP_PATH); return applicationRoot; } /** * Override to set your own properties file - * + * */ public String getPropertiesFile() { - String jetspeedProperties = System.getProperty(JetspeedEngineConstants.APPLICATION_ROOT_KEY, PortalTestConstants.PORTAL_WEBAPP_PATH) + "/WEB-INF/conf/jetspeed.properties"; + String jetspeedProperties = System.getProperty( + JetspeedEngineConstants.APPLICATION_ROOT_KEY, + PortalTestConstants.PORTAL_WEBAPP_PATH) + + "/WEB-INF/conf/jetspeed.properties"; return jetspeedProperties; } /* - * Implement this method to override any properties in your TestSuite. - * If you override this method in a derived class, call super.overrideProperties to get these settings + * Implement this method to override any properties in your TestSuite. If + * you override this method in a derived class, call + * super.overrideProperties to get these settings * - * @param properties The base configuration properties for the Jetspeed system. + * @param properties The base configuration properties for the Jetspeed + * system. */ - protected static void initializeConfiguration(Configuration properties, String appRoot) + protected static void initializeConfiguration(Configuration properties, + String appRoot) { - String testPropsPath = appRoot + "/WEB-INF/conf/test/jetspeed.properties"; + String testPropsPath = appRoot + + "/WEB-INF/conf/test/jetspeed.properties"; try { File testFile = new File(testPropsPath); @@ -185,8 +198,10 @@ while (it.hasNext()) { Entry entry = (Entry) it.next(); - //if (entry.getValue() != null && ((String)entry.getValue()).length() > 0) - properties.setProperty((String) entry.getKey(), (String) entry.getValue()); + // if (entry.getValue() != null && + // ((String)entry.getValue()).length() > 0) + properties.setProperty((String) entry.getKey(), + (String) entry.getValue()); } } } @@ -202,7 +217,7 @@ public void run(TestResult arg0) { try - { + { super.run(arg0); } finally @@ -212,15 +227,16 @@ } /** - * @see junit.framework.TestSuite#runTest(junit.framework.Test, junit.framework.TestResult) + * @see junit.framework.TestSuite#runTest(junit.framework.Test, + * junit.framework.TestResult) */ public void runTest(Test arg0, TestResult arg1) { - if(arg0 instanceof JetspeedTest) + if (arg0 instanceof JetspeedTest) { - JetspeedTest jtest = (JetspeedTest) arg0; - jtest.engine = engine; - jtest.jsuite = this; + JetspeedTest jtest = (JetspeedTest) arg0; + jtest.engine = engine; + jtest.jsuite = this; } super.runTest(arg0, arg1); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/testhelpers/SpringEngineHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/testhelpers/SpringEngineHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/testhelpers/SpringEngineHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,15 +34,16 @@ public class SpringEngineHelper extends AbstractTestHelper { - public static final String ENGINE_ATTR = "Engine"; - + + public static final String ENGINE_ATTR = "Engine"; + protected JetspeedTestJNDIComponent jndiDS; - + public SpringEngineHelper(Map context) { super(context); } - + private Engine engine; public void setUp() throws Exception @@ -51,21 +52,25 @@ jndiDS.setup(); PropertiesConfiguration config = new PropertiesConfiguration(); - config.load(new FileInputStream(PortalTestConstants.JETSPEED_PROPERTIES_PATH)); - + config.load(new FileInputStream( + PortalTestConstants.JETSPEED_PROPERTIES_PATH)); + String appRoot = PortalTestConstants.JETSPEED_APPLICATION_ROOT; - - MockServletConfig servletConfig = new MockServletConfig(); - ResourceLocatingServletContext servletContent = new ResourceLocatingServletContext(new File(appRoot)); + + MockServletConfig servletConfig = new MockServletConfig(); + ResourceLocatingServletContext servletContent = new ResourceLocatingServletContext( + new File(appRoot)); servletConfig.setServletContext(servletContent); ServletConfigFactoryBean.setServletConfig(servletConfig); - - SpringComponentManager scm = new SpringComponentManager(new String[] {"/WEB-INF/assembly/boot/datasource.xml"}, new String[] {"/WEB-INF/assembly/*.xml"}, servletContent, appRoot ); - - engine = new JetspeedEngine(config, appRoot, servletConfig, scm ); + + SpringComponentManager scm = new SpringComponentManager(new String[] + {"/WEB-INF/assembly/boot/datasource.xml"}, new String[] + {"/WEB-INF/assembly/*.xml"}, servletContent, appRoot); + + engine = new JetspeedEngine(config, appRoot, servletConfig, scm); Jetspeed.setEngine(engine); engine.start(); - getContext().put(ENGINE_ATTR, engine ); + getContext().put(ENGINE_ATTR, engine); } public void tearDown() throws Exception Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/TestWebXML.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/TestWebXML.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/TestWebXML.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,7 +27,7 @@ */ public class TestWebXML extends TestCase { - + /** * Setup the test. */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/pamanager/TestJetspeedPortletDescriptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/pamanager/TestJetspeedPortletDescriptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/pamanager/TestJetspeedPortletDescriptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,74 +30,87 @@ import org.apache.jetspeed.util.descriptor.ExtendedPortletMetadata; import org.apache.jetspeed.util.descriptor.PortletApplicationDescriptor; - /** * Tests jetspeed-portlet.xml XML-Java mappings - * + * * @author Jeremy Ford * @author David Sean Taylor - * @version $Id: TestJetspeedPortletDescriptor.java 517121 2007-03-12 07:45:49Z ate $ + * @version $Id: TestJetspeedPortletDescriptor.java 517121 2007-03-12 07:45:49Z + * ate $ */ -public class TestJetspeedPortletDescriptor - extends TestCase { - //extends AbstractPrefsSupportedTestCase { - +public class TestJetspeedPortletDescriptor extends TestCase +{ + + // extends AbstractPrefsSupportedTestCase { + private static final String PORTLET_01 = "HelloPortlet"; + private static final String PORTLET_02 = "DisplayRequestPortlet"; + private static final String PORTLET_03 = "PickANumberPortlet"; + private static final String PORTLET_04 = "AttributeScopePortlet"; - + /** * Start the tests. - * - * @param args the arguments. Not used + * + * @param args + * the arguments. Not used */ public static void main(String args[]) { - TestRunner.main(new String[] { TestPortletDescriptor.class.getName()}); + TestRunner.main(new String[] + {TestPortletDescriptor.class.getName()}); } - /** * Creates the test suite. - * - * @return a test suite (TestSuite) that includes all methods - * starting with "test" + * + * @return a test suite (TestSuite) that includes all + * methods starting with "test" */ public static Test suite() { // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestJetspeedPortletDescriptor.class); } - + public void testLoadPortletApplicationTree() throws Exception { System.out.println("Testing loadPortletApplicationTree"); - PortletApplicationDescriptor pad = new PortletApplicationDescriptor(new FileReader("./test/testdata/deploy/portlet.xml"), "unit-test"); - MutablePortletApplication app = pad.createPortletApplication(); + PortletApplicationDescriptor pad = new PortletApplicationDescriptor( + new FileReader("./test/testdata/deploy/portlet.xml"), + "unit-test"); + MutablePortletApplication app = pad.createPortletApplication(); assertNotNull("App is null", app); assertNotNull("Version is null", app.getVersion()); - assertTrue("Version invalid: " + app.getVersion(), app.getVersion().equals("1.0")); + assertTrue("Version invalid: " + app.getVersion(), app.getVersion() + .equals("1.0")); assertNotNull("PA Identifier is null", app.getApplicationIdentifier()); - assertTrue( - "PA Identifier invalid: " + app.getApplicationIdentifier(), + assertTrue("PA Identifier invalid: " + app.getApplicationIdentifier(), app.getApplicationIdentifier().equals("TestRegistry")); - - ExtendedPortletMetadata md = new ExtendedPortletMetadata(new FileReader("./test/testdata/deploy/jetspeed-portlet.xml"), app); + + ExtendedPortletMetadata md = new ExtendedPortletMetadata( + new FileReader("./test/testdata/deploy/jetspeed-portlet.xml"), + app); md.load(); - - PortletDefinitionComposite def1 = (PortletDefinitionComposite)app.getPortletDefinitionByName(PORTLET_01); - PortletDefinitionComposite def2 = (PortletDefinitionComposite)app.getPortletDefinitionByName(PORTLET_02); - PortletDefinitionComposite def3 = (PortletDefinitionComposite)app.getPortletDefinitionByName(PORTLET_03); - PortletDefinitionComposite def4 = (PortletDefinitionComposite)app.getPortletDefinitionByName(PORTLET_04); - + + PortletDefinitionComposite def1 = (PortletDefinitionComposite) app + .getPortletDefinitionByName(PORTLET_01); + PortletDefinitionComposite def2 = (PortletDefinitionComposite) app + .getPortletDefinitionByName(PORTLET_02); + PortletDefinitionComposite def3 = (PortletDefinitionComposite) app + .getPortletDefinitionByName(PORTLET_03); + PortletDefinitionComposite def4 = (PortletDefinitionComposite) app + .getPortletDefinitionByName(PORTLET_04); + Collection titles = app.getMetadata().getFields("title"); Collection def1Titles = def1.getMetadata().getFields("title"); Collection def2Subjects = def2.getMetadata().getFields("subject"); Collection def3Creators = def3.getMetadata().getFields("creator"); Collection def4Field1 = def4.getMetadata().getFields("field1"); Collection def4Fiels2 = def4.getMetadata().getFields("field2"); - + String securityRef = app.getJetspeedSecurityConstraint(); assertEquals(titles.size(), 3); assertEquals(def1Titles.size(), 4); @@ -105,23 +118,26 @@ assertEquals(def3Creators.size(), 4); assertEquals(def4Field1.size(), 3); assertEquals(def4Fiels2.size(), 2); - + // Security Constraints tests assertEquals(securityRef, "admin-only"); assertEquals(def1.getJetspeedSecurityConstraint(), "users-1"); assertEquals(def2.getJetspeedSecurityConstraint(), "users-2"); assertEquals(def3.getJetspeedSecurityConstraint(), "users-4"); assertNull(def4.getJetspeedSecurityConstraint()); - + Collection servicesCollection = app.getJetspeedServices(); assertNotNull("Metadata services is null", servicesCollection); - assertEquals("Expected 2 service definitions", servicesCollection.size(), 2); + assertEquals("Expected 2 service definitions", servicesCollection + .size(), 2); Object[] services = servicesCollection.toArray(); - JetspeedServiceReference service = (JetspeedServiceReference)services[0]; + JetspeedServiceReference service = (JetspeedServiceReference) services[0]; System.out.println("**** service = " + service.getName()); - - assertEquals( ((JetspeedServiceReference)services[0]).getName(), "PortletRegistryComponent"); - assertEquals( ((JetspeedServiceReference)services[1]).getName(), "PortletEntityAccessComponent"); + + assertEquals(((JetspeedServiceReference) services[0]).getName(), + "PortletRegistryComponent"); + assertEquals(((JetspeedServiceReference) services[1]).getName(), + "PortletEntityAccessComponent"); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/pamanager/TestPortletDescriptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/pamanager/TestPortletDescriptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/pamanager/TestPortletDescriptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -56,21 +56,24 @@ /** * TestPortletDescriptor - tests loading the portlet.xml deployment descriptor * into Java objects - * + * * @author David Sean Taylor - * + * * @version $Id: TestPortletDescriptor.java 517719 2007-03-13 15:05:48Z ate $ */ public class TestPortletDescriptor extends AbstractRequestContextTestCase { + /** * Start the tests. - * - * @param args the arguments. Not used + * + * @param args + * the arguments. Not used */ public static void main(String args[]) { - TestRunner.main(new String[] { TestPortletDescriptor.class.getName()}); + TestRunner.main(new String[] + {TestPortletDescriptor.class.getName()}); } public static Test suite() @@ -82,27 +85,28 @@ return new TestSuite(TestPortletDescriptor.class); } - + /* * Overrides the database properties */ - // public void overrideProperties(Configuration properties) - // { - // super.overrideProperties(properties); - // } - + // public void overrideProperties(Configuration properties) + // { + // super.overrideProperties(properties); + // } public void testLoadPortletApplicationTree() throws Exception { System.out.println("Testing loadPortletApplicationTree"); - PortletApplicationDescriptor pad = new PortletApplicationDescriptor(new FileReader("./test/testdata/deploy/portlet.xml"), "unit-test"); + PortletApplicationDescriptor pad = new PortletApplicationDescriptor( + new FileReader("./test/testdata/deploy/portlet.xml"), + "unit-test"); MutablePortletApplication app = pad.createPortletApplication(); assertNotNull("App is null", app); assertNotNull("Version is null", app.getVersion()); - assertTrue("Version invalid: " + app.getVersion(), app.getVersion().equals("1.0")); + assertTrue("Version invalid: " + app.getVersion(), app.getVersion() + .equals("1.0")); assertNotNull("PA Identifier is null", app.getApplicationIdentifier()); - assertTrue( - "PA Identifier invalid: " + app.getApplicationIdentifier(), - app.getApplicationIdentifier().equals("TestRegistry")); + assertTrue("PA Identifier invalid: " + app.getApplicationIdentifier(), + app.getApplicationIdentifier().equals("TestRegistry")); validateUserInfo(app); @@ -112,7 +116,8 @@ int count = 0; while (it.hasNext()) { - PortletDefinitionComposite portlet = (PortletDefinitionComposite) it.next(); + PortletDefinitionComposite portlet = (PortletDefinitionComposite) it + .next(); String identifier = portlet.getPortletIdentifier(); assertNotNull("Portlet.Identifier is null", identifier); if (identifier.equals("HelloPortlet")) @@ -133,24 +138,25 @@ while (it.hasNext()) { UserAttribute userAttribute = (UserAttribute) it.next(); - assertNotNull("User attribute name is null, ", userAttribute.getName()); + assertNotNull("User attribute name is null, ", userAttribute + .getName()); if (userAttribute.getName().equals("user.name.given")) { - assertTrue( - "User attribute description: " + userAttribute.getDescription(), - userAttribute.getDescription().equals("User Given Name")); + assertTrue("User attribute description: " + + userAttribute.getDescription(), userAttribute + .getDescription().equals("User Given Name")); } if (userAttribute.getName().equals("user.name.family")) { - assertTrue( - "User attribute description: " + userAttribute.getDescription(), - userAttribute.getDescription().equals("User Last Name")); + assertTrue("User attribute description: " + + userAttribute.getDescription(), userAttribute + .getDescription().equals("User Last Name")); } if (userAttribute.getName().equals("user.home-info.online.email")) { - assertTrue( - "User attribute description: " + userAttribute.getDescription(), - userAttribute.getDescription().equals("User eMail")); + assertTrue("User attribute description: " + + userAttribute.getDescription(), userAttribute + .getDescription().equals("User eMail")); } } } @@ -159,24 +165,28 @@ { // Portlet Name assertNotNull("Portlet.Name is null", portlet.getName()); - assertTrue("Portlet.Name invalid: " + portlet.getName(), portlet.getName().equals("HelloPortlet")); + assertTrue("Portlet.Name invalid: " + portlet.getName(), portlet + .getName().equals("HelloPortlet")); // Portlet Class assertNotNull("Portlet.Class is null", portlet.getClassName()); - assertTrue( - "Portlet.Class invalid: " + portlet.getClassName(), - portlet.getClassName().equals("org.apache.jetspeed.portlet.helloworld.HelloWorld")); + assertTrue("Portlet.Class invalid: " + portlet.getClassName(), portlet + .getClassName().equals( + "org.apache.jetspeed.portlet.helloworld.HelloWorld")); // Expiration Cache - assertNotNull("Portlet.Expiration is null", portlet.getExpirationCache()); - assertTrue("Portlet.Expiration invalid: " + portlet.getExpirationCache(), portlet.getExpirationCache().equals("-1")); + assertNotNull("Portlet.Expiration is null", portlet + .getExpirationCache()); + assertTrue("Portlet.Expiration invalid: " + + portlet.getExpirationCache(), portlet.getExpirationCache() + .equals("-1")); // Display Name DisplayName displayName = portlet.getDisplayName(Locale.ENGLISH); assertNotNull("Display Name is null", displayName); - assertTrue( - "Portlet.DisplayName invalid: " + displayName.getDisplayName(), - displayName.getDisplayName().equals("HelloWorld Portlet Wrapper")); + assertTrue("Portlet.DisplayName invalid: " + + displayName.getDisplayName(), displayName.getDisplayName() + .equals("HelloWorld Portlet Wrapper")); // Init Parameters ParameterSet paramsList = portlet.getInitParameterSet(); @@ -185,11 +195,14 @@ while (it.hasNext()) { ParameterComposite parameter = (ParameterComposite) it.next(); - assertTrue("InitParam.Name invalid: " + parameter.getName(), parameter.getName().equals("hello")); - assertTrue("InitParam.Value invalid: " + parameter.getValue(), parameter.getValue().equals("Hello Portlet")); - assertTrue( - "InitParam.Description invalid: " + parameter.getDescription(Locale.ENGLISH), - parameter.getDescription(Locale.ENGLISH).getDescription().equals("test init param")); + assertTrue("InitParam.Name invalid: " + parameter.getName(), + parameter.getName().equals("hello")); + assertTrue("InitParam.Value invalid: " + parameter.getValue(), + parameter.getValue().equals("Hello Portlet")); + assertTrue("InitParam.Description invalid: " + + parameter.getDescription(Locale.ENGLISH), parameter + .getDescription(Locale.ENGLISH).getDescription().equals( + "test init param")); count++; } assertTrue("InitParam Count != 1, count = " + count, count == 1); @@ -201,7 +214,8 @@ while (it.hasNext()) { ContentTypeComposite contentType = (ContentTypeComposite) it.next(); - assertTrue("MimeType invalid: " + contentType.getContentType(), contentType.getContentType().equals("text/html")); + assertTrue("MimeType invalid: " + contentType.getContentType(), + contentType.getContentType().equals("text/html")); // Portlet Modes Iterator modesIterator = contentType.getPortletModes(); @@ -211,7 +225,8 @@ modesIterator.next(); modesCount++; } - assertTrue("Portlets Modes Count != 3, count = " + count, modesCount == 3); + assertTrue("Portlets Modes Count != 3, count = " + count, + modesCount == 3); count++; } @@ -224,10 +239,11 @@ while (it.hasNext()) { MutableLanguage info = (MutableLanguage) it.next(); - assertTrue("PortletInfo.Title invalid: " + info.getTitle(), info.getTitle().equals("HelloWorldTitle")); - assertTrue( - "PortletInfo.ShortTitle invalid: " + info.getShortTitle(), - info.getShortTitle().equals("This is the short title")); + assertTrue("PortletInfo.Title invalid: " + info.getTitle(), info + .getTitle().equals("HelloWorldTitle")); + assertTrue("PortletInfo.ShortTitle invalid: " + + info.getShortTitle(), info.getShortTitle().equals( + "This is the short title")); Iterator keywords = info.getKeywords(); assertNotNull("Keywords cannot be null", keywords); int keywordCount = 0; @@ -236,15 +252,18 @@ String keyword = (String) keywords.next(); if (keywordCount == 0) { - assertTrue("PortletInfo.Keywords invalid: + " + keyword, keyword.equals("Test")); + assertTrue("PortletInfo.Keywords invalid: + " + keyword, + keyword.equals("Test")); } else { - assertTrue("PortletInfo.Keywords invalid: + " + keyword, keyword.equals("David")); + assertTrue("PortletInfo.Keywords invalid: + " + keyword, + keyword.equals("David")); } keywordCount++; } - assertTrue("Keywords Count != 2, count = " + count, keywordCount == 2); + assertTrue("Keywords Count != 2, count = " + count, + keywordCount == 2); count++; } @@ -260,15 +279,21 @@ assertNotNull("Preference.Name is null", pref.getName()); if (pref.getName().equals("time-server")) { - assertTrue("Preference.Name invalid: " + pref.getName(), pref.getName().equals("time-server")); - assertTrue("Preference.Modifiable invalid: ", pref.isReadOnly() == false); - validatePreferences(pref, new String[] { "http://timeserver.myco.com", "http://timeserver.foo.com" }); + assertTrue("Preference.Name invalid: " + pref.getName(), pref + .getName().equals("time-server")); + assertTrue("Preference.Modifiable invalid: ", + pref.isReadOnly() == false); + validatePreferences(pref, new String[] + {"http://timeserver.myco.com", "http://timeserver.foo.com"}); } else { - assertTrue("Preference.Name invalid: " + pref.getName(), pref.getName().equals("port")); - assertTrue("Preference.Modifiable invalid: ", pref.isReadOnly() == true); - validatePreferences(pref, new String[] { "404" }); + assertTrue("Preference.Name invalid: " + pref.getName(), pref + .getName().equals("port")); + assertTrue("Preference.Modifiable invalid: ", + pref.isReadOnly() == true); + validatePreferences(pref, new String[] + {"404"}); } count++; } @@ -276,7 +301,8 @@ } - private void validatePreferences(PreferenceComposite pref, String[] expectedValues) + private void validatePreferences(PreferenceComposite pref, + String[] expectedValues) { Iterator values = pref.getValues(); @@ -284,37 +310,39 @@ while (values.hasNext()) { String value = (String) values.next(); - assertTrue("Preference.Value invalid: + " + value + "[" + count + "]", value.equals(expectedValues[count])); + assertTrue("Preference.Value invalid: + " + value + "[" + count + + "]", value.equals(expectedValues[count])); count++; // System.out.println("value = " + value); } - assertTrue("Value Count != expectedCount, count = " + expectedValues.length, count == (expectedValues.length)); + assertTrue("Value Count != expectedCount, count = " + + expectedValues.length, count == (expectedValues.length)); } public void testWritingToDB() throws Exception { - - - MutablePortletApplication app = portletRegistry.getPortletApplication("HW_App"); + + MutablePortletApplication app = portletRegistry + .getPortletApplication("HW_App"); if (app != null) { portletRegistry.removeApplication(app); - + } - PortletApplicationDescriptor pad = new PortletApplicationDescriptor(new FileReader("./test/testdata/deploy/portlet2.xml"), "HW_App"); + PortletApplicationDescriptor pad = new PortletApplicationDescriptor( + new FileReader("./test/testdata/deploy/portlet2.xml"), "HW_App"); app = pad.createPortletApplication(); app.setName("HW_App"); - portletRegistry.registerPortletApplication(app); - + // store.invalidateAll(); - - PortletDefinition pd = portletRegistry.getPortletDefinitionByUniqueName("HW_App::PreferencePortlet"); + PortletDefinition pd = portletRegistry + .getPortletDefinitionByUniqueName("HW_App::PreferencePortlet"); assertNotNull(pd); @@ -334,21 +362,20 @@ assertTrue(count > 0); - - pd = portletRegistry.getPortletDefinitionByUniqueName("HW_App::PickANumberPortlet"); - + pd = portletRegistry + .getPortletDefinitionByUniqueName("HW_App::PickANumberPortlet"); + assertNotNull(pd); - portletRegistry.removeApplication(app); - } public void testInfusingWebXML() throws Exception { File warFile = new File("./test/testdata/deploy/webapp"); - PortletApplicationWar paWar = new PortletApplicationWar(new DirectoryHelper(warFile), "unit-test", "/" ); + PortletApplicationWar paWar = new PortletApplicationWar( + new DirectoryHelper(warFile), "unit-test", "/"); SAXBuilder builder = new SAXBuilder(false); @@ -356,29 +383,35 @@ // allows to deploy the application offline builder.setEntityResolver(new EntityResolver() { - public InputSource resolveEntity(java.lang.String publicId, java.lang.String systemId) - throws SAXException, java.io.IOException + + public InputSource resolveEntity(java.lang.String publicId, + java.lang.String systemId) throws SAXException, + java.io.IOException { if (systemId.equals("http://java.sun.com/dtd/web-app_2_3.dtd")) { - return new InputSource(PortletApplicationWar.class.getResourceAsStream("web-app_2_3.dtd")); + return new InputSource(PortletApplicationWar.class + .getResourceAsStream("web-app_2_3.dtd")); } else return null; } }); - FileReader srcReader = new FileReader("./test/testdata/deploy/webapp/WEB-INF/web.xml"); + FileReader srcReader = new FileReader( + "./test/testdata/deploy/webapp/WEB-INF/web.xml"); FileReader targetReader = null; - Document doc = builder.build(srcReader); + Document doc = builder.build(srcReader); Element root = doc.getRootElement(); try { - Object jetspeedServlet = XPath.selectSingleNode(root, PortletApplicationWar.JETSPEED_SERVLET_XPATH); - Object jetspeedServletMapping = XPath.selectSingleNode(root, PortletApplicationWar.JETSPEED_SERVLET_MAPPING_XPATH); + Object jetspeedServlet = XPath.selectSingleNode(root, + PortletApplicationWar.JETSPEED_SERVLET_XPATH); + Object jetspeedServletMapping = XPath.selectSingleNode(root, + PortletApplicationWar.JETSPEED_SERVLET_MAPPING_XPATH); assertNull(jetspeedServlet); assertNull(jetspeedServletMapping); @@ -390,10 +423,11 @@ Document targetDoc = builder.build(targetReader); - jetspeedServlet = XPath.selectSingleNode(targetDoc, PortletApplicationWar.JETSPEED_SERVLET_XPATH); - jetspeedServletMapping = XPath.selectSingleNode(targetDoc, PortletApplicationWar.JETSPEED_SERVLET_MAPPING_XPATH); + jetspeedServlet = XPath.selectSingleNode(targetDoc, + PortletApplicationWar.JETSPEED_SERVLET_XPATH); + jetspeedServletMapping = XPath.selectSingleNode(targetDoc, + PortletApplicationWar.JETSPEED_SERVLET_MAPPING_XPATH); - assertNotNull(jetspeedServlet); assertNotNull(jetspeedServletMapping); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/pamanager/TestPortletDescriptorSecurityRoles.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/pamanager/TestPortletDescriptorSecurityRoles.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/tools/pamanager/TestPortletDescriptorSecurityRoles.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,31 +37,33 @@ /** * TestPortletDescriptorSecurityRoles - test and validate security roles and * security role references from portlet.xml and web.xml deployment descriptor. - * + * * @author Ate Douma - * + * * @version $Id: TestPortletDescriptorSecurityRoles.java,v 1.4 2004/05/27 - * 19:57:24 weaver Exp $ + * 19:57:24 weaver Exp $ */ -public class TestPortletDescriptorSecurityRoles extends AbstractRequestContextTestCase +public class TestPortletDescriptorSecurityRoles extends + AbstractRequestContextTestCase { /** * Start the tests. - * + * * @param args - * the arguments. Not used + * the arguments. Not used */ - public static void main( String args[] ) + public static void main(String args[]) { - TestRunner.main(new String[]{TestPortletDescriptorSecurityRoles.class.getName()}); + TestRunner.main(new String[] + {TestPortletDescriptorSecurityRoles.class.getName()}); } /** * Creates the test suite. - * + * * @return a test suite (TestSuite) that includes all - * methods starting with "test" + * methods starting with "test" */ public static Test suite() { @@ -72,14 +74,15 @@ public void setUp() throws Exception { super.setUp(); - + } - + public void testSecurityRoles() throws Exception { System.out.println("Testing securityRoles"); File warFile = new File("./test/testdata/deploy/webapp"); - PortletApplicationWar paWar = new PortletApplicationWar(new DirectoryHelper(warFile), "unit-test", "/" ); + PortletApplicationWar paWar = new PortletApplicationWar( + new DirectoryHelper(warFile), "unit-test", "/"); MutablePortletApplication app = paWar.createPortletApp(); assertNotNull("App is null", app); @@ -89,7 +92,8 @@ app.setWebApplicationDefinition(webApp); - PortletDefinition portlet = app.getPortletDefinitionByName("TestPortlet"); + PortletDefinition portlet = app + .getPortletDefinitionByName("TestPortlet"); assertNotNull("TestPortlet is null", portlet); checkWebSecurityRoles(webApp); checkPortletSecurityRoleRefs(portlet); @@ -102,7 +106,8 @@ { validateFailed = true; } - assertTrue("Invalid PortletDescriptor validation result", validateFailed); + assertTrue("Invalid PortletDescriptor validation result", + validateFailed); SecurityRoleImpl role = new SecurityRoleImpl(); role.setRoleName("users.manager"); webApp.addSecurityRole(role); @@ -114,24 +119,25 @@ catch (PortletApplicationException e) { } - assertEquals("Invalid PortletDescriptor validation result", false, validateFailed); + assertEquals("Invalid PortletDescriptor validation result", false, + validateFailed); // persist the app try { - + portletRegistry.registerPortletApplication(app); - + } catch (Exception e) { - String msg = "Unable to register portlet application, " + app.getName() - + ", through the portlet registry: " + e.toString(); - + String msg = "Unable to register portlet application, " + + app.getName() + ", through the portlet registry: " + + e.toString(); + throw new Exception(msg, e); } // clear cache - // read back in app = portletRegistry.getPortletApplication("unit-test"); @@ -144,41 +150,47 @@ catch (PortletApplicationException e) { } - assertEquals("Invalid loaded PortletDescriptor validation result", false, validateFailed); + assertEquals("Invalid loaded PortletDescriptor validation result", + false, validateFailed); // remove the app try { - + portletRegistry.removeApplication(app); - + } catch (Exception e) { - String msg = "Unable to remove portlet application, " + app.getName() - + ", through the portlet portletRegistry: " + e.toString(); + String msg = "Unable to remove portlet application, " + + app.getName() + ", through the portlet portletRegistry: " + + e.toString(); throw new Exception(msg, e); } } - private void checkWebSecurityRoles( MutableWebApplication webApp ) + private void checkWebSecurityRoles(MutableWebApplication webApp) { SecurityRoleSet roles = webApp.getSecurityRoles(); - assertEquals("Invalid number of security role definitions found", 1, roles.size()); + assertEquals("Invalid number of security role definitions found", 1, + roles.size()); SecurityRole role = roles.get("users.admin"); assertNotNull("Role users.admin undefined", role); } - private void checkPortletSecurityRoleRefs( PortletDefinition portlet ) + private void checkPortletSecurityRoleRefs(PortletDefinition portlet) { SecurityRoleRefSet roleRefs = portlet.getInitSecurityRoleRefSet(); - assertEquals("Invalid number of security role references found", 2, roleRefs.size()); + assertEquals("Invalid number of security role references found", 2, + roleRefs.size()); SecurityRoleRef roleRef = roleRefs.get("admin"); assertNotNull("Security Role Ref admin undefined", roleRef); - assertEquals("security Role link expected", "users.admin", roleRef.getRoleLink()); + assertEquals("security Role link expected", "users.admin", roleRef + .getRoleLink()); roleRef = roleRefs.get("users.manager"); assertNotNull("Security Role Ref users.manager undefined", roleRef); - assertNull("Undefined security Role link for users.managers expected", roleRef.getRoleLink()); + assertNull("Undefined security Role link for users.managers expected", + roleRef.getRoleLink()); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/userinfo/MockUserInfoManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/userinfo/MockUserInfoManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/userinfo/MockUserInfoManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,20 +22,24 @@ import org.apache.jetspeed.request.RequestContext; import org.apache.pluto.om.common.ObjectID; - public class MockUserInfoManager implements UserInfoManager { + private Map fake = new HashMap(); - + public MockUserInfoManager() - {} - - /* (non-Javadoc) - * @see org.apache.jetspeed.userinfo.UserInfoManager#getUserInfoMap(org.apache.pluto.om.common.ObjectID, org.apache.jetspeed.request.RequestContext) + { + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.userinfo.UserInfoManager#getUserInfoMap(org.apache.pluto.om.common.ObjectID, + * org.apache.jetspeed.request.RequestContext) */ public Map getUserInfoMap(ObjectID oid, RequestContext context) { return fake; } - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/userinfo/TestUserInfoManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/userinfo/TestUserInfoManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/userinfo/TestUserInfoManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -65,7 +65,8 @@ { super.setUp(); - single = (UserInfoManager) ctx.getBean("org.apache.jetspeed.userinfo.UserInfoManager"); + single = (UserInfoManager) ctx + .getBean("org.apache.jetspeed.userinfo.UserInfoManager"); portletRegistry = (PortletRegistry) ctx.getBean("portletRegistry"); } @@ -97,7 +98,8 @@ private void innerTestSetUserInfoMap(UserInfoManager uim) throws Exception { - PortletApplicationDescriptor pad = new PortletApplicationDescriptor(new FileReader("test/testdata/deploy/portlet.xml"), "unit-test"); + PortletApplicationDescriptor pad = new PortletApplicationDescriptor( + new FileReader("test/testdata/deploy/portlet.xml"), "unit-test"); portletApp = pad.createPortletApplication(); assertNotNull("App is null", portletApp); @@ -108,7 +110,8 @@ } catch (Exception e) { - String msg = "Unable to register portlet application, " + portletApp.getName() + String msg = "Unable to register portlet application, " + + portletApp.getName() + ", through the portlet portletRegistry: " + e.toString(); throw new Exception(msg, e); @@ -125,13 +128,19 @@ initUser(); request = initRequestContext("test"); userInfo = uim.getUserInfoMap(portletApp.getId(), request); - assertNotNull(PortletRequest.USER_INFO + " should not be null", userInfo); - assertEquals("should contain user.name.given", "Test Dude", (String) userInfo.get("user.name.given")); - assertEquals("should contain user.name.family", "Dudley", (String) userInfo.get("user.name.family")); - assertNull("should not contain user.home-info.online.email", userInfo.get("user.home-info.online.email")); + assertNotNull(PortletRequest.USER_INFO + " should not be null", + userInfo); + assertEquals("should contain user.name.given", "Test Dude", + (String) userInfo.get("user.name.given")); + assertEquals("should contain user.name.family", "Dudley", + (String) userInfo.get("user.name.family")); + assertNull("should not contain user.home-info.online.email", userInfo + .get("user.home-info.online.email")); // With linked attributes - ExtendedPortletMetadata extMetaData = new ExtendedPortletMetadata(new FileReader("test/testdata/deploy/jetspeed-portlet.xml"), portletApp); + ExtendedPortletMetadata extMetaData = new ExtendedPortletMetadata( + new FileReader("test/testdata/deploy/jetspeed-portlet.xml"), + portletApp); extMetaData.load(); // persist the app @@ -141,16 +150,20 @@ } catch (Exception e) { - String msg = "Unable to update portlet application, " + portletApp.getName() + String msg = "Unable to update portlet application, " + + portletApp.getName() + ", through the portlet portletRegistry: " + e.toString(); throw new Exception(msg, e); } userInfo = uim.getUserInfoMap(portletApp.getId(), request); - assertNotNull(PortletRequest.USER_INFO + " should not be null", userInfo); - assertEquals("should contain user-name-given", "Test Dude", (String) userInfo.get("user-name-given")); - assertEquals("should contain user-name-family", "Dudley", (String) userInfo.get("user-name-family")); + assertNotNull(PortletRequest.USER_INFO + " should not be null", + userInfo); + assertEquals("should contain user-name-given", "Test Dude", + (String) userInfo.get("user-name-given")); + assertEquals("should contain user-name-family", "Dudley", + (String) userInfo.get("user-name-family")); } /** @@ -185,7 +198,8 @@ } catch (SecurityException sex) { - assertTrue("user exists. should not have thrown an exception.", false); + assertTrue("user exists. should not have thrown an exception.", + false); } Preferences userInfoPrefs = user.getPreferences().node("userinfo"); userInfoPrefs.put("user.name.given", "Test Dude"); @@ -208,7 +222,9 @@ } catch (SecurityException sex) { - System.out.println("could not remove test users. exception caught: " + sex); + System.out + .println("could not remove test users. exception caught: " + + sex); } } @@ -228,8 +244,10 @@ } catch (Exception e) { - String msg = "Unable to remove portlet application, " + portletApp.getName() - + ", through the portlet portletRegistry: " + e.toString(); + String msg = "Unable to remove portlet application, " + + portletApp.getName() + + ", through the portlet portletRegistry: " + + e.toString(); throw new Exception(msg, e); } } @@ -255,8 +273,12 @@ { Properties p = super.getPostProcessProperties(); p.setProperty("supported.portletmode.autoswitch.config", "false"); - p.setProperty("supported.portletmode.autoswitch.edit_defaults", "false"); - p.setProperty("supported.portletmode.autoswitch.config.surrogate.portlet", "j2-admin::CustomConfigModePortlet"); + p + .setProperty("supported.portletmode.autoswitch.edit_defaults", + "false"); + p.setProperty( + "supported.portletmode.autoswitch.config.surrogate.portlet", + "j2-admin::CustomConfigModePortlet"); return p; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/window/TestWindows.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/window/TestWindows.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal/src/test/org/apache/jetspeed/window/TestWindows.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,8 +32,8 @@ import org.apache.jetspeed.container.window.impl.PortletWindowAccessorImpl; import org.apache.jetspeed.om.common.portlet.MutablePortletEntity; import org.apache.jetspeed.om.page.ContentFragment; +import org.apache.jetspeed.om.page.ContentFragmentImpl; import org.apache.jetspeed.om.page.Fragment; -import org.apache.jetspeed.om.page.ContentFragmentImpl; import org.apache.jetspeed.util.JetspeedObjectID; import org.apache.pluto.om.window.PortletWindow; import org.apache.pluto.om.window.PortletWindowList; @@ -49,13 +49,18 @@ /** * @author Scott T. Weaver * -*/ + */ public class TestWindows extends TestCase { + protected PortletWindowAccessor windowAccess; + protected Mock fragMock; + protected Mock entityAccessMock; + protected Mock entityMock; + protected Mock windowListMock; public static Test suite() @@ -79,27 +84,33 @@ fragMock = new Mock(Fragment.class); entityMock = new Mock(MutablePortletEntity.class); windowListMock = new Mock(CompositeWindowList.class); - windowAccess = new PortletWindowAccessorImpl((PortletEntityAccessComponent) entityAccessMock.proxy(), PortletFactoryMock.instance, new HashMapWindowCache(),true); + windowAccess = new PortletWindowAccessorImpl( + (PortletEntityAccessComponent) entityAccessMock.proxy(), + PortletFactoryMock.instance, new HashMapWindowCache(), true); } public void testWindowAccess() throws Exception { List windows = new ArrayList(); - ContentFragment f1 = new ContentFragmentImpl((Fragment) fragMock.proxy(), new HashMap()); + ContentFragment f1 = new ContentFragmentImpl((Fragment) fragMock + .proxy(), new HashMap()); MutablePortletEntity entity = (MutablePortletEntity) entityMock.proxy(); - CompositeWindowList windowList = (CompositeWindowList) windowListMock.proxy(); - entityAccessMock.expects(new InvokeAtLeastOnceMatcher()).method("getPortletEntityForFragment") - .withAnyArguments().will(new ReturnStub(entity)); - fragMock.expects(new InvokeAtLeastOnceMatcher()).method("getId").withNoArguments() - .will(new ReturnStub("frag1")); - entityMock.expects(new InvokeAtLeastOnceMatcher()).method("getPortletWindowList").withNoArguments().will( + CompositeWindowList windowList = (CompositeWindowList) windowListMock + .proxy(); + entityAccessMock.expects(new InvokeAtLeastOnceMatcher()).method( + "getPortletEntityForFragment").withAnyArguments().will( + new ReturnStub(entity)); + fragMock.expects(new InvokeAtLeastOnceMatcher()).method("getId") + .withNoArguments().will(new ReturnStub("frag1")); + entityMock.expects(new InvokeAtLeastOnceMatcher()).method( + "getPortletWindowList").withNoArguments().will( new ReturnStub(windowList)); - entityMock.expects(new InvokeAtLeastOnceMatcher()).method("getId").withNoArguments().will( - new ReturnStub(new JetspeedObjectID("entity1"))); + entityMock.expects(new InvokeAtLeastOnceMatcher()).method("getId") + .withNoArguments().will( + new ReturnStub(new JetspeedObjectID("entity1"))); - windowListMock.expects(new InvokeCountMatcher(4)).method("add").withAnyArguments().will( - new ListAppendStub(windows)); - + windowListMock.expects(new InvokeCountMatcher(4)).method("add") + .withAnyArguments().will(new ListAppendStub(windows)); PortletWindow window = windowAccess.getPortletWindow(f1); assertNotNull(window); @@ -122,39 +133,40 @@ // back the portlet entity's list. We check this through vefirying calls // to our mocks windowAccess.getPortletWindow(f1); - + // Test same remove but via entity - windowAccess.removeWindow(window); + windowAccess.removeWindow(window); - assertNotNull(windowAccess.getPortletWindow(f1)); - - windowListMock.expects(new InvokeOnceMatcher()).method("iterator").withNoArguments().will(new ReturnStub(windows.iterator())); + assertNotNull(windowAccess.getPortletWindow(f1)); -/* - windowAccess.removeWindows(entity); - - windowAccess.getPortletWindow(f1); - // Double that second call bypasses creating a new window - //windowAccess.getPortletWindow(f1); - - windowListMock.verify(); -*/ + windowListMock.expects(new InvokeOnceMatcher()).method("iterator") + .withNoArguments().will(new ReturnStub(windows.iterator())); + + /* + * windowAccess.removeWindows(entity); + * + * windowAccess.getPortletWindow(f1); // Double that second call + * bypasses creating a new window //windowAccess.getPortletWindow(f1); + * + * windowListMock.verify(); + */ } - interface CompositeWindowList extends PortletWindowList, PortletWindowListCtrl + interface CompositeWindowList extends PortletWindowList, + PortletWindowListCtrl { } class ListAppendStub extends CustomStub { - + List list; /** * @param arg0 */ - public ListAppendStub( List list ) + public ListAppendStub(List list) { super("Appends object to a list"); this.list = list; @@ -167,10 +179,10 @@ * * @see org.jmock.core.Stub#invoke(org.jmock.core.Invocation) * @param arg0 - * @return @throws - * java.lang.Throwable + * @return + * @throws java.lang.Throwable */ - public Object invoke( Invocation invocation ) throws Throwable + public Object invoke(Invocation invocation) throws Throwable { list.add(invocation.parameterValues.get(0)); return null; @@ -178,14 +190,18 @@ } /** - * Inline copy of InvokeCountMatcher from latest jMock Development Snapshot: 20050628-175146 - * so we don't need to depend on their SNAPSHOT release anymore but can fallback on their 1.0.1 version. - * (doesn't seem they are going to release a new real version soon as it has been ages since 1.0.1 came out) + * Inline copy of InvokeCountMatcher from latest jMock Development Snapshot: + * 20050628-175146 so we don't need to depend on their SNAPSHOT release + * anymore but can fallback on their 1.0.1 version. (doesn't seem they are + * going to release a new real version soon as it has been ages since 1.0.1 + * came out) + * * @author Ate Douma - * + * */ private static class InvokeCountMatcher implements InvocationMatcher { + private int invocationCount = 0; private int expectedCount; @@ -212,8 +228,9 @@ public StringBuffer describeTo(StringBuffer buffer) { - return buffer.append("expected ").append(expectedCount).append(" times, invoked ").append( - getInvocationCount()).append(" times"); + return buffer.append("expected ").append(expectedCount).append( + " times, invoked ").append(getInvocationCount()).append( + " times"); } public int getInvocationCount() @@ -233,13 +250,17 @@ public void verifyHasBeenInvoked() { - Assert.assertTrue("expected method was not invoked", hasBeenInvoked()); + Assert.assertTrue("expected method was not invoked", + hasBeenInvoked()); } public void verifyHasBeenInvokedExactly(int expectedCount) { - Assert.assertTrue("expected method was not invoked the expected number of times: expected " + expectedCount - + " times, was invoked " + invocationCount + " times", invocationCount == expectedCount); + Assert.assertTrue( + "expected method was not invoked the expected number of times: expected " + + expectedCount + " times, was invoked " + + invocationCount + " times", + invocationCount == expectedCount); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,20 +19,20 @@ import java.util.List; import java.util.Locale; +import org.apache.jetspeed.om.common.GenericMetadata; import org.apache.jetspeed.om.folder.MenuDefinition; -import org.apache.jetspeed.om.common.GenericMetadata; /** - * This abstract class implements the menu definition interface - * in a default manner to allow derived classes to easily describe - * standard menu definitions supported natively by the portal site - * component. + * This abstract class implements the menu definition interface in a default + * manner to allow derived classes to easily describe standard menu definitions + * supported natively by the portal site component. * * @author Randy Watler * @version $Id: StandardMenuDefinitionImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public abstract class StandardMenuDefinitionImpl implements MenuDefinition { + /** * StandardMenuDefinitionImpl - constructor */ @@ -42,7 +42,7 @@ /** * getName - get menu name - * + * * @return menu name */ public String getName() @@ -52,17 +52,20 @@ /** * setName - set menu name - * - * @param name menu name + * + * @param name + * menu name */ public void setName(String name) { - throw new RuntimeException("StandardMenuDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuDefinitionImpl instance immutable"); } /** - * getOptions - get comma separated menu options if not specified as elements - * + * getOptions - get comma separated menu options if not specified as + * elements + * * @return option paths specification */ public String getOptions() @@ -71,18 +74,21 @@ } /** - * setOptions - set comma separated menu options if not specified as elements - * - * @param option option paths specification + * setOptions - set comma separated menu options if not specified as + * elements + * + * @param option + * option paths specification */ public void setOptions(String options) { - throw new RuntimeException("StandardMenuDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuDefinitionImpl instance immutable"); } /** * getDepth - get depth of inclusion for folder menu options - * + * * @return inclusion depth */ public int getDepth() @@ -92,37 +98,41 @@ /** * setDepth - set depth of inclusion for folder menu options - * - * @param depth inclusion depth + * + * @param depth + * inclusion depth */ public void setDepth(int depth) { - throw new RuntimeException("StandardMenuDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuDefinitionImpl instance immutable"); } /** * isPaths - get generate ordered path options for specified options - * + * * @return paths options flag */ public boolean isPaths() { return false; } - + /** * setPaths - set generate ordered path options for specified options - * - * @param paths paths options flag + * + * @param paths + * paths options flag */ public void setPaths(boolean paths) { - throw new RuntimeException("StandardMenuDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuDefinitionImpl instance immutable"); } - + /** * isRegexp - get regexp flag for interpreting specified options - * + * * @return regexp flag */ public boolean isRegexp() @@ -132,17 +142,19 @@ /** * setRegexp - set regexp flag for interpreting specified options - * - * @param regexp regexp flag + * + * @param regexp + * regexp flag */ public void setRegexp(boolean regexp) { - throw new RuntimeException("StandardMenuDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuDefinitionImpl instance immutable"); } /** * getProfile - get profile locator used to filter specified options - * + * * @return profile locator name */ public String getProfile() @@ -152,17 +164,19 @@ /** * setProfile - set profile locator used to filter specified options - * - * @param locatorName profile locator name + * + * @param locatorName + * profile locator name */ public void setProfile(String locatorName) { - throw new RuntimeException("StandardMenuDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuDefinitionImpl instance immutable"); } /** * getOrder - get comma separated regexp ordering patterns for options - * + * * @return ordering patterns list */ public String getOrder() @@ -172,17 +186,19 @@ /** * setOrder - set comma separated regexp ordering patterns for options - * - * @param order ordering patterns list + * + * @param order + * ordering patterns list */ public void setOrder(String order) { - throw new RuntimeException("StandardMenuDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuDefinitionImpl instance immutable"); } /** * getSkin - get skin name for menu - * + * * @return skin name */ public String getSkin() @@ -192,17 +208,19 @@ /** * setSkin - set skin name for menu - * - * @param name skin name + * + * @param name + * skin name */ public void setSkin(String name) { - throw new RuntimeException("StandardMenuDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuDefinitionImpl instance immutable"); } /** * getTitle - get default title for menu - * + * * @return title text */ public String getTitle() @@ -213,17 +231,19 @@ /** * setTitle - set default title for menu - * - * @param title title text + * + * @param title + * title text */ public void setTitle(String title) { - throw new RuntimeException("StandardMenuDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuDefinitionImpl instance immutable"); } /** * getShortTitle - get default short title for menu - * + * * @return short title text */ public String getShortTitle() @@ -234,18 +254,21 @@ /** * setShortTitle - set default short title for menu - * - * @param title short title text + * + * @param title + * short title text */ public void setShortTitle(String title) { - throw new RuntimeException("StandardMenuDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuDefinitionImpl instance immutable"); } /** * getTitle - get locale specific title for menu from metadata - * - * @param locale preferred locale + * + * @param locale + * preferred locale * @return title text */ public String getTitle(Locale locale) @@ -255,27 +278,27 @@ } /** - * getTitle - get locale specific title for menu from metadata - * protocol, with or without falback enabled - * - * @param locale preferred locale - * @param fallback whether to return default title + * getTitle - get locale specific title for menu from metadata protocol, + * with or without falback enabled + * + * @param locale + * preferred locale + * @param fallback + * whether to return default title * @return title text */ protected String getTitle(Locale locale, boolean fallback) { // fallback to getTitle() if enabled - if (fallback) - { - return getTitle(); - } + if (fallback) { return getTitle(); } return null; } /** * getShortTitle - get locale specific short title for menu from metadata - * - * @param locale preferred locale + * + * @param locale + * preferred locale * @return short title text */ public String getShortTitle(Locale locale) @@ -293,7 +316,7 @@ /** * getMetadata - get generic metadata instance for menu - * + * * @return metadata instance */ public GenericMetadata getMetadata() @@ -302,10 +325,9 @@ } /** - * getMenuElements - get ordered list of menu options, - * nested menus, separators, included - * menu, and excluded menu elements - * + * getMenuElements - get ordered list of menu options, nested menus, + * separators, included menu, and excluded menu elements + * * @return element list */ public List getMenuElements() @@ -315,11 +337,13 @@ /** * setMenuElements - set ordered list of menu options - * - * @param elements element list + * + * @param elements + * element list */ public void setMenuElements(List elements) { - throw new RuntimeException("StandardMenuDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuDefinitionImpl instance immutable"); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuExcludeDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuExcludeDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuExcludeDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,15 +19,18 @@ import org.apache.jetspeed.om.folder.MenuExcludeDefinition; /** - * This abstract class implements the menu exclude definition - * interface in a default manner to allow derived classes to - * easily describe standard menu definitions. + * This abstract class implements the menu exclude definition interface in a + * default manner to allow derived classes to easily describe standard menu + * definitions. * * @author Randy Watler - * @version $Id: StandardMenuExcludeDefinitionImpl.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: StandardMenuExcludeDefinitionImpl.java 516448 2007-03-09 + * 16:25:47Z ate $ */ -public abstract class StandardMenuExcludeDefinitionImpl implements MenuExcludeDefinition +public abstract class StandardMenuExcludeDefinitionImpl implements + MenuExcludeDefinition { + /** * StandardMenuExcludeDefinitionImpl - constructor */ @@ -37,7 +40,7 @@ /** * getName - get menu name with options to exclude - * + * * @return menu name */ public String getName() @@ -47,11 +50,13 @@ /** * setName - set menu name with options to exclude - * - * @param name menu name + * + * @param name + * menu name */ public void setName(String name) { - throw new RuntimeException("StandardMenuExcludeDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuExcludeDefinitionImpl instance immutable"); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuIncludeDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuIncludeDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuIncludeDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,14 +19,17 @@ import org.apache.jetspeed.om.folder.MenuIncludeDefinition; /** - * This interface describes the object used to define - * portal site menu included menus. + * This interface describes the object used to define portal site menu included + * menus. * * @author Randy Watler - * @version $Id: StandardMenuIncludeDefinitionImpl.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: StandardMenuIncludeDefinitionImpl.java 516448 2007-03-09 + * 16:25:47Z ate $ */ -public abstract class StandardMenuIncludeDefinitionImpl implements MenuIncludeDefinition +public abstract class StandardMenuIncludeDefinitionImpl implements + MenuIncludeDefinition { + /** * StandardMenuIncludeDefinitionImpl - constructor */ @@ -36,7 +39,7 @@ /** * getName - get menu name to nest or with options to include - * + * * @return menu name */ public String getName() @@ -46,31 +49,35 @@ /** * setName - set menu name to nest or with options to include - * - * @param name menu name + * + * @param name + * menu name */ public void setName(String name) { - throw new RuntimeException("StandardMenuIncludeDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuIncludeDefinitionImpl instance immutable"); } /** * isNest - get nesting for included menu - * + * * @return nest options flag */ public boolean isNest() { return false; } - + /** * setNest - set nesting for included menu - * - * @param nest nest menu flag + * + * @param nest + * nest menu flag */ public void setNest(boolean nest) { - throw new RuntimeException("StandardMenuIncludeDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuIncludeDefinitionImpl instance immutable"); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuOptionsDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuOptionsDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuOptionsDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,15 +19,18 @@ import org.apache.jetspeed.om.folder.MenuOptionsDefinition; /** - * This abstract class implements the menu options definition - * interface in a default manner to allow derived classes to - * easily describe standard menu definitions. + * This abstract class implements the menu options definition interface in a + * default manner to allow derived classes to easily describe standard menu + * definitions. * * @author Randy Watler - * @version $Id: StandardMenuOptionsDefinitionImpl.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: StandardMenuOptionsDefinitionImpl.java 516448 2007-03-09 + * 16:25:47Z ate $ */ -public abstract class StandardMenuOptionsDefinitionImpl implements MenuOptionsDefinition +public abstract class StandardMenuOptionsDefinitionImpl implements + MenuOptionsDefinition { + /** * StandardMenuOptionsDefinitionImpl - constructor */ @@ -37,7 +40,7 @@ /** * getOptions - get comma separated menu options - * + * * @return option paths specification */ public String getOptions() @@ -47,17 +50,19 @@ /** * setOptions - set comma separated menu options - * - * @param options option paths specification + * + * @param options + * option paths specification */ public void setOptions(String options) { - throw new RuntimeException("StandardMenuOptionsDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuOptionsDefinitionImpl instance immutable"); } /** * getDepth - get depth of inclusion for folder options - * + * * @return inclusion depth */ public int getDepth() @@ -67,37 +72,41 @@ /** * setDepth - set depth of inclusion for folder options - * - * @param depth inclusion depth + * + * @param depth + * inclusion depth */ public void setDepth(int depth) { - throw new RuntimeException("StandardMenuOptionsDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuOptionsDefinitionImpl instance immutable"); } /** * isPaths - get generate ordered path options - * + * * @return paths options flag */ public boolean isPaths() { return false; } - + /** * setPaths - set generate ordered path options - * - * @param paths paths options flag + * + * @param paths + * paths options flag */ public void setPaths(boolean paths) { - throw new RuntimeException("StandardMenuOptionsDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuOptionsDefinitionImpl instance immutable"); } - + /** * isRegexp - get regexp flag for interpreting options - * + * * @return regexp flag */ public boolean isRegexp() @@ -107,17 +116,19 @@ /** * setRegexp - set regexp flag for interpreting options - * - * @param regexp regexp flag + * + * @param regexp + * regexp flag */ public void setRegexp(boolean regexp) { - throw new RuntimeException("StandardMenuOptionsDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuOptionsDefinitionImpl instance immutable"); } /** * getProfile - get profile locator used to filter options - * + * * @return profile locator name */ public String getProfile() @@ -127,17 +138,19 @@ /** * setProfile - set profile locator used to filter options - * - * @param locatorName profile locator name + * + * @param locatorName + * profile locator name */ public void setProfile(String locatorName) { - throw new RuntimeException("StandardMenuOptionsDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuOptionsDefinitionImpl instance immutable"); } /** * getOrder - get comma separated regexp ordering patterns - * + * * @return ordering patterns list */ public String getOrder() @@ -147,17 +160,19 @@ /** * setOrder - set comma separated regexp ordering patterns - * - * @param order ordering patterns list + * + * @param order + * ordering patterns list */ public void setOrder(String order) { - throw new RuntimeException("StandardMenuOptionsDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuOptionsDefinitionImpl instance immutable"); } /** * getSkin - get skin name for options - * + * * @return skin name */ public String getSkin() @@ -167,11 +182,13 @@ /** * setSkin - set skin name for options - * - * @param name skin name + * + * @param name + * skin name */ public void setSkin(String name) { - throw new RuntimeException("StandardMenuOptionsDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuOptionsDefinitionImpl instance immutable"); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuSeparatorDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuSeparatorDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/impl/StandardMenuSeparatorDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,19 +18,22 @@ import java.util.Locale; +import org.apache.jetspeed.om.common.GenericMetadata; import org.apache.jetspeed.om.folder.MenuSeparatorDefinition; -import org.apache.jetspeed.om.common.GenericMetadata; /** - * This abstract class implements the menu separator definition - * interface in a default manner to allow derived classes to - * easily describe standard menu definitions. + * This abstract class implements the menu separator definition interface in a + * default manner to allow derived classes to easily describe standard menu + * definitions. * * @author Randy Watler - * @version $Id: StandardMenuSeparatorDefinitionImpl.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: StandardMenuSeparatorDefinitionImpl.java 516448 2007-03-09 + * 16:25:47Z ate $ */ -public abstract class StandardMenuSeparatorDefinitionImpl implements MenuSeparatorDefinition +public abstract class StandardMenuSeparatorDefinitionImpl implements + MenuSeparatorDefinition { + /** * StandardMenuSeparatorDefinitionImpl - constructor */ @@ -40,7 +43,7 @@ /** * getSkin - get skin name for separator - * + * * @return skin name */ public String getSkin() @@ -50,17 +53,19 @@ /** * setSkin - set skin name for separator - * - * @param name skin name + * + * @param name + * skin name */ public void setSkin(String name) { - throw new RuntimeException("StandardMenuSeparatorDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuSeparatorDefinitionImpl instance immutable"); } /** * getTitle - get default title for separator - * + * * @return title text */ public String getTitle() @@ -70,17 +75,19 @@ /** * setTitle - set default title for separator - * - * @param title title text + * + * @param title + * title text */ public void setTitle(String title) { - throw new RuntimeException("StandardMenuSeparatorDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuSeparatorDefinitionImpl instance immutable"); } /** * getText - get default text for separator - * + * * @return text */ public String getText() @@ -90,18 +97,21 @@ /** * setText - set default text for separator - * - * @param text text + * + * @param text + * text */ public void setText(String text) { - throw new RuntimeException("StandardMenuSeparatorDefinitionImpl instance immutable"); + throw new RuntimeException( + "StandardMenuSeparatorDefinitionImpl instance immutable"); } /** * getTitle - get locale specific title for separator from metadata - * - * @param locale preferred locale + * + * @param locale + * preferred locale * @return title text */ public String getTitle(Locale locale) @@ -111,8 +121,9 @@ /** * getText - get locale specific text for separator from metadata - * - * @param locale preferred locale + * + * @param locale + * preferred locale * @return text */ public String getText(Locale locale) @@ -122,7 +133,7 @@ /** * getMetadata - get generic metadata instance for menu - * + * * @return metadata instance */ public GenericMetadata getMetadata() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/proxy/FolderProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/proxy/FolderProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/folder/proxy/FolderProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -49,34 +49,71 @@ import org.apache.jetspeed.request.RequestContext; /** - * This class proxies PSML Folder instances to create a logical view - * of site content using the Dynamic Proxy pattern. + * This class proxies PSML Folder instances to create a logical view of site + * content using the Dynamic Proxy pattern. * * @author Randy Watler * @version $Id: FolderProxy.java 553375 2007-07-05 05:37:00Z taylor $ */ public class FolderProxy extends NodeProxy implements InvocationHandler { + /** * *_METHOD - Folder method constants */ - protected static final Method GET_ALL_METHOD = reflectMethod(Folder.class, "getAll", null); - protected static final Method GET_DEFAULT_PAGE_METHOD = reflectMethod(Folder.class, "getDefaultPage", null); - protected static final Method GET_FOLDERS_METHOD = reflectMethod(Folder.class, "getFolders", null); - protected static final Method GET_FOLDER_METHOD = reflectMethod(Folder.class, "getFolder", new Class[]{String.class}); - protected static final Method GET_LINKS_METHOD = reflectMethod(Folder.class, "getLinks", null); - protected static final Method GET_LINK_METHOD = reflectMethod(Folder.class, "getLink", new Class[]{String.class}); - protected static final Method GET_MENU_DEFINITIONS_METHOD = reflectMethod(Folder.class, "getMenuDefinitions", null); - protected static final Method GET_METADATA_METHOD = reflectMethod(Folder.class, "getMetadata", null); - protected static final Method GET_NAME_METHOD = reflectMethod(Folder.class, "getName", null); - protected static final Method GET_PAGES_METHOD = reflectMethod(Folder.class, "getPages", null); - protected static final Method GET_PAGE_METHOD = reflectMethod(Folder.class, "getPage", new Class[]{String.class}); - protected static final Method GET_PAGE_SECURITY_METHOD = reflectMethod(Folder.class, "getPageSecurity", null); - protected static final Method GET_SHORT_TITLE_LOCALE_METHOD = reflectMethod(Folder.class, "getShortTitle", new Class[]{Locale.class}); - protected static final Method GET_SHORT_TITLE_METHOD = reflectMethod(Folder.class, "getShortTitle", null); - protected static final Method GET_TITLE_LOCALE_METHOD = reflectMethod(Folder.class, "getTitle", new Class[]{Locale.class}); - protected static final Method GET_TITLE_METHOD = reflectMethod(Folder.class, "getTitle", null); + protected static final Method GET_ALL_METHOD = reflectMethod(Folder.class, + "getAll", null); + protected static final Method GET_DEFAULT_PAGE_METHOD = reflectMethod( + Folder.class, "getDefaultPage", null); + + protected static final Method GET_FOLDERS_METHOD = reflectMethod( + Folder.class, "getFolders", null); + + protected static final Method GET_FOLDER_METHOD = reflectMethod( + Folder.class, "getFolder", new Class[] + {String.class}); + + protected static final Method GET_LINKS_METHOD = reflectMethod( + Folder.class, "getLinks", null); + + protected static final Method GET_LINK_METHOD = reflectMethod(Folder.class, + "getLink", new Class[] + {String.class}); + + protected static final Method GET_MENU_DEFINITIONS_METHOD = reflectMethod( + Folder.class, "getMenuDefinitions", null); + + protected static final Method GET_METADATA_METHOD = reflectMethod( + Folder.class, "getMetadata", null); + + protected static final Method GET_NAME_METHOD = reflectMethod(Folder.class, + "getName", null); + + protected static final Method GET_PAGES_METHOD = reflectMethod( + Folder.class, "getPages", null); + + protected static final Method GET_PAGE_METHOD = reflectMethod(Folder.class, + "getPage", new Class[] + {String.class}); + + protected static final Method GET_PAGE_SECURITY_METHOD = reflectMethod( + Folder.class, "getPageSecurity", null); + + protected static final Method GET_SHORT_TITLE_LOCALE_METHOD = reflectMethod( + Folder.class, "getShortTitle", new Class[] + {Locale.class}); + + protected static final Method GET_SHORT_TITLE_METHOD = reflectMethod( + Folder.class, "getShortTitle", null); + + protected static final Method GET_TITLE_LOCALE_METHOD = reflectMethod( + Folder.class, "getTitle", new Class[] + {Locale.class}); + + protected static final Method GET_TITLE_METHOD = reflectMethod( + Folder.class, "getTitle", null); + /** * defaultFolder - default proxy delegate folder instance */ @@ -128,12 +165,14 @@ private boolean linksAggregated; /** - * SearchFolder - data object used hold concrete search folder and - * related search path profile locator name pairs + * SearchFolder - data object used hold concrete search folder and related + * search path profile locator name pairs */ private class SearchFolder { + public Folder folder; + public String locatorName; public SearchFolder(Folder folder, String locatorName) @@ -144,58 +183,75 @@ } /** - * searchFolders - search folder objects along view search paths - * in most to least specific order + * searchFolders - search folder objects along view search paths in most to + * least specific order */ private List searchFolders; /** - * inheritanceFolders - inheritance graph folder list in most to - * least specific order + * inheritanceFolders - inheritance graph folder list in most to least + * specific order */ private List inheritanceFolders; - + /** - * newInstance - creates a new proxy instance that implements the Folder interface - * - * @param view site view owner of this proxy - * @param locatorName name of profile locator associated - * with the proxy delegate - * @param parentFolder view parent proxy folder - * @param folder proxy delegate + * newInstance - creates a new proxy instance that implements the Folder + * interface + * + * @param view + * site view owner of this proxy + * @param locatorName + * name of profile locator associated with the proxy delegate + * @param parentFolder + * view parent proxy folder + * @param folder + * proxy delegate */ - public static Folder newInstance(SiteView view, String locatorName, Folder parentFolder, Folder folder) + public static Folder newInstance(SiteView view, String locatorName, + Folder parentFolder, Folder folder) { - return (Folder)Proxy.newProxyInstance(folder.getClass().getClassLoader(), new Class[]{Folder.class}, new FolderProxy(view, locatorName, parentFolder, folder)); + return (Folder) Proxy.newProxyInstance(folder.getClass() + .getClassLoader(), new Class[] + {Folder.class}, + new FolderProxy(view, locatorName, parentFolder, folder)); } /** * FolderProxy - private constructor used by newInstance() - * - * @param view site view owner of this proxy - * @param locatorName name of profile locator associated - * with the proxy delegate - * @param parentFolder view parent proxy folder - * @param folder proxy delegate + * + * @param view + * site view owner of this proxy + * @param locatorName + * name of profile locator associated with the proxy delegate + * @param parentFolder + * view parent proxy folder + * @param folder + * proxy delegate */ - private FolderProxy(SiteView view, String locatorName, Folder parentFolder, Folder folder) + private FolderProxy(SiteView view, String locatorName, Folder parentFolder, + Folder folder) { - super(view, locatorName, parentFolder, folder.getName(), folder.isHidden()); + super(view, locatorName, parentFolder, folder.getName(), folder + .isHidden()); this.defaultFolder = selectDefaultFromAggregateFolders(folder); this.titledFolder = selectTitledFromAggregateFolders(this.defaultFolder); } - + /** * invoke - method invocation dispatch for this proxy, (defaults to - * invocation of delegate unless method is implemented in this - * proxy handler or should be hidden/stubbed) - * - * @param proxy instance invoked against - * @param method Folder interface method invoked - * @param args method arguments + * invocation of delegate unless method is implemented in this proxy handler + * or should be hidden/stubbed) + * + * @param proxy + * instance invoked against + * @param method + * Folder interface method invoked + * @param args + * method arguments * @throws Throwable */ - public Object invoke(Object proxy, Method m, Object [] args) throws Throwable + public Object invoke(Object proxy, Method m, Object[] args) + throws Throwable { // proxy implementation method dispatch if (m.equals(GET_ALL_METHOD)) @@ -212,7 +268,7 @@ } else if (m.equals(GET_FOLDER_METHOD)) { - return getFolder(proxy, (String)args[0]); + return getFolder(proxy, (String) args[0]); } else if (m.equals(GET_LINKS_METHOD)) { @@ -220,7 +276,7 @@ } else if (m.equals(GET_LINK_METHOD)) { - return getLink(proxy, (String)args[0]); + return getLink(proxy, (String) args[0]); } else if (m.equals(GET_MENU_DEFINITIONS_METHOD)) { @@ -240,11 +296,11 @@ } else if (m.equals(GET_PAGE_METHOD)) { - return getPage(proxy, (String)args[0]); + return getPage(proxy, (String) args[0]); } else if (m.equals(GET_SHORT_TITLE_LOCALE_METHOD)) { - return getShortTitle((Locale)args[0]); + return getShortTitle((Locale) args[0]); } else if (m.equals(GET_SHORT_TITLE_METHOD)) { @@ -252,7 +308,7 @@ } else if (m.equals(GET_TITLE_LOCALE_METHOD)) { - return getTitle((Locale)args[0]); + return getTitle((Locale) args[0]); } else if (m.equals(GET_TITLE_METHOD)) { @@ -282,17 +338,11 @@ { return new Boolean(isHidden()); } - else if (m.equals(TO_STRING_METHOD)) - { - return toString(); - } - + else if (m.equals(TO_STRING_METHOD)) { return toString(); } + // proxy suppression of not implemented or mutable methods - if (m.equals(GET_PAGE_SECURITY_METHOD) || - m.getName().startsWith("set")) - { - throw new RuntimeException("Folder instance is immutable from proxy."); - } + if (m.equals(GET_PAGE_SECURITY_METHOD) || m.getName().startsWith("set")) { throw new RuntimeException( + "Folder instance is immutable from proxy."); } // attempt to invoke method on delegate Folder instance return m.invoke(defaultFolder, args); @@ -300,8 +350,9 @@ /** * getAll - proxy implementation of Folder.getAll() - * - * @param proxy this folder proxy + * + * @param proxy + * this folder proxy * @return list containing sub-folders and documents in folder * @throws DocumentException */ @@ -318,8 +369,9 @@ /** * getDefaultPage - proxy implementation of Folder.getDefaultPage() - * - * @param proxy this folder proxy + * + * @param proxy + * this folder proxy * @return default page name */ public String getDefaultPage(Object proxy) @@ -330,8 +382,9 @@ /** * getFolders - proxy implementation of Folder.getFolders() - * - * @param proxy this folder proxy + * + * @param proxy + * this folder proxy * @return list containing all sub-folders in folder * @throws DocumentException */ @@ -349,39 +402,41 @@ } return folders; } - + /** * getFolder - proxy implementation of Folder.getFolder() - * - * @param proxy this folder proxy - * @param name sub-folder name + * + * @param proxy + * this folder proxy + * @param name + * sub-folder name * @return sub-folder * @throws FolderNotFoundException * @throws DocumentException */ - public Folder getFolder(Object proxy, String name) throws FolderNotFoundException, DocumentException + public Folder getFolder(Object proxy, String name) + throws FolderNotFoundException, DocumentException { // search for folder by name or absolute path from // aggregated folders NodeSet allFolders = getFolders(proxy); if (allFolders != null) { - Folder folder = (Folder)allFolders.get(name); - if (folder != null) - { - return folder; - } + Folder folder = (Folder) allFolders.get(name); + if (folder != null) { return folder; } } - throw new FolderNotFoundException("Folder " + name + " not found at " + getPath()); + throw new FolderNotFoundException("Folder " + name + " not found at " + + getPath()); } /** * getLinks - proxy implementation of Folder.getLinks() - * - * @param proxy this folder proxy + * + * @param proxy + * this folder proxy * @return list containing all links in folder * @throws NodeException - */ + */ public NodeSet getLinks(Object proxy) throws NodeException { // latently subset links by type from aggregated children @@ -396,35 +451,36 @@ } return links; } - + /** * getLink - proxy implementation of Folder.getLink() - * - * @param proxy this folder proxy - * @param name link name including extension + * + * @param proxy + * this folder proxy + * @param name + * link name including extension * @return link * @throws DocumentNotFoundException * @throws NodeException - */ - public Link getLink(Object proxy, String name) throws DocumentNotFoundException, NodeException + */ + public Link getLink(Object proxy, String name) + throws DocumentNotFoundException, NodeException { // search for link by name or absolute path from // aggregated links NodeSet allLinks = getLinks(proxy); if (allLinks != null) { - Link link = (Link)allLinks.get(name); - if (link != null) - { - return link; - } + Link link = (Link) allLinks.get(name); + if (link != null) { return link; } } - throw new DocumentNotFoundException("Link " + name + " not found at " + getPath()); + throw new DocumentNotFoundException("Link " + name + " not found at " + + getPath()); } /** * getName - proxy implementation of Node.getName() - * + * * @return name of folder */ public String getName() @@ -432,17 +488,15 @@ // force root folder name since the folder is // normally aggregated using more specific folders; // otherwise, use concrete default folder name - if (getPath().equals(Folder.PATH_SEPARATOR)) - { - return Folder.PATH_SEPARATOR; - } + if (getPath().equals(Folder.PATH_SEPARATOR)) { return Folder.PATH_SEPARATOR; } return defaultFolder.getName(); } /** * getPages - proxy implementation of Folder.getPages() - * - * @param proxy this folder proxy + * + * @param proxy + * this folder proxy * @return list containing all pages in folder * @throws NodeException */ @@ -460,35 +514,36 @@ } return pages; } - + /** * getPage - proxy implementation of Folder.getPage() - * - * @param proxy this folder proxy - * @param name page name including extension + * + * @param proxy + * this folder proxy + * @param name + * page name including extension * @return page * @throws PageNotFoundException * @throws NodeException */ - public Page getPage(Object proxy, String name) throws PageNotFoundException, NodeException + public Page getPage(Object proxy, String name) + throws PageNotFoundException, NodeException { // search for page by name or absolute path from // aggregated pages NodeSet allPages = getPages(proxy); if (allPages != null) { - Page page = (Page)allPages.get(name); - if (page != null) - { - return page; - } + Page page = (Page) allPages.get(name); + if (page != null) { return page; } } - throw new PageNotFoundException("Page " + name + " not found at " + getPath()); + throw new PageNotFoundException("Page " + name + " not found at " + + getPath()); } /** * getMetadata - proxy implementation of Folder.getMetadata() - * + * * @return metadata */ public GenericMetadata getMetadata() @@ -499,7 +554,7 @@ /** * getTitle - proxy implementation of Folder.getTitle() - * + * * @return default title */ public String getTitle() @@ -510,7 +565,7 @@ /** * getShortTitle - proxy implementation of Folder.getShortTitle() - * + * * @return default short title */ public String getShortTitle() @@ -521,8 +576,9 @@ /** * getTitle - proxy implementation of Folder.getTitle() - * - * @param locale preferred locale + * + * @param locale + * preferred locale * @return title */ public String getTitle(Locale locale) @@ -533,8 +589,9 @@ /** * getShortTitle - proxy implementation of Folder.getShortTitle() - * - * @param locale preferred locale + * + * @param locale + * preferred locale * @return short title */ public String getShortTitle(Locale locale) @@ -545,7 +602,7 @@ /** * getDefaultFolder - get default proxy delegate folder instance - * + * * @return default delegate folder */ public Folder getDefaultFolder() @@ -555,7 +612,7 @@ /** * aggregateMenuDefinitionLocators - aggregate all menu definition locators - * in site view for this folder or page + * in site view for this folder or page */ protected void aggregateMenuDefinitionLocators() { @@ -568,7 +625,7 @@ { // get menu definitions from inheritance folders and // merge into aggregate menu definition locators - Folder folder = (Folder)foldersIter.next(); + Folder folder = (Folder) foldersIter.next(); mergeMenuDefinitionLocators(folder.getMenuDefinitions(), folder); } } @@ -577,16 +634,18 @@ } // aggregate standard menu definition locator defaults - mergeMenuDefinitionLocators(getView().getStandardMenuDefinitionLocators()); + mergeMenuDefinitionLocators(getView() + .getStandardMenuDefinitionLocators()); } /** - * selectDefaultFromAggregateFolders - select most appropriate aggregate concrete - * folder to use generally in site view at - * this proxy folder view path - * - * - * @param defaultFolder default concrete folder + * selectDefaultFromAggregateFolders - select most appropriate aggregate + * concrete folder to use generally in site view at this proxy folder view + * path + * + * + * @param defaultFolder + * default concrete folder * @return selected concrete folder */ private Folder selectDefaultFromAggregateFolders(Folder defaultFolder) @@ -595,7 +654,7 @@ // search paths ordered most to least specific try { - return ((SearchFolder)getSearchFolders().get(0)).folder; + return ((SearchFolder) getSearchFolders().get(0)).folder; } catch (FolderNotFoundException fnfe) { @@ -604,11 +663,12 @@ } /** - * selectTitledFromAggregateFolders - select most appropriate aggregate concrete - * folder with a title to use in site view at - * this proxy folder view path - * - * @param defaultFolder default concrete folder + * selectTitledFromAggregateFolders - select most appropriate aggregate + * concrete folder with a title to use in site view at this proxy folder + * view path + * + * @param defaultFolder + * default concrete folder * @return selected concrete folder */ private Folder selectTitledFromAggregateFolders(Folder defaultFolder) @@ -620,17 +680,17 @@ Iterator foldersIter = getSearchFolders().iterator(); while (foldersIter.hasNext()) { - Folder folder = ((SearchFolder)foldersIter.next()).folder; + Folder folder = ((SearchFolder) foldersIter.next()).folder; String name = folder.getName(); String title = folder.getTitle(); String shortTitle = folder.getShortTitle(); GenericMetadata folderMetadata = folder.getMetadata(); - if (((title != null) && !title.equalsIgnoreCase(name)) || - ((shortTitle != null) && !shortTitle.equalsIgnoreCase(name)) || - ((folderMetadata != null) && (folderMetadata.getFields() != null) && !folderMetadata.getFields().isEmpty())) - { - return folder; - } + if (((title != null) && !title.equalsIgnoreCase(name)) + || ((shortTitle != null) && !shortTitle + .equalsIgnoreCase(name)) + || ((folderMetadata != null) + && (folderMetadata.getFields() != null) && !folderMetadata + .getFields().isEmpty())) { return folder; } } } catch (FolderNotFoundException fnfe) @@ -641,10 +701,10 @@ /** * selectDefaultPageFromAggregateFolders - select most specific default page - * proxy to use in site view at this - * proxy folder view path - * - * @param proxy this folder proxy + * proxy to use in site view at this proxy folder view path + * + * @param proxy + * this folder proxy * @return selected default page name */ private String selectDefaultPageFromAggregateFolders(Object proxy) @@ -658,8 +718,9 @@ Iterator foldersIter = getSearchFolders().iterator(); while (foldersIter.hasNext()) { - // get folder default page name or look for fallback default name - Folder folder = ((SearchFolder)foldersIter.next()).folder; + // get folder default page name or look for fallback default + // name + Folder folder = ((SearchFolder) foldersIter.next()).folder; String defaultPageName = folder.getDefaultPage(); if (defaultPageName != null) { @@ -668,10 +729,7 @@ if (defaultPageName.equals("..")) { // default parent folder - if (getParent() != null) - { - return defaultPageName; - } + if (getParent() != null) { return defaultPageName; } } else { @@ -742,8 +800,9 @@ /** * aggregateChildren - aggregate all children proxies in site view - * - * @param proxy this folder proxy + * + * @param proxy + * this folder proxy * @return list containing sub-folders, pages, and links in folder view */ private NodeSet aggregateChildren(Object proxy) @@ -759,7 +818,7 @@ while (foldersIter.hasNext()) { // aggregate folders - SearchFolder searchFolder = (SearchFolder)foldersIter.next(); + SearchFolder searchFolder = (SearchFolder) foldersIter.next(); Folder folder = searchFolder.folder; String locatorName = searchFolder.locatorName; @@ -768,34 +827,42 @@ Iterator childrenIter = children.iterator(); while (childrenIter.hasNext()) { - Node child = (Node)childrenIter.next(); + Node child = (Node) childrenIter.next(); String childName = child.getName(); // filter profiling property folders; they are // accessed only via SiteView search path // aggregation that directly utilizes the // current view page manager - boolean visible = (!(child instanceof Folder) || (!childName.startsWith(Folder.RESERVED_SUBSITE_FOLDER_PREFIX) && - !childName.startsWith(Folder.RESERVED_FOLDER_PREFIX))); + boolean visible = (!(child instanceof Folder) || (!childName + .startsWith(Folder.RESERVED_SUBSITE_FOLDER_PREFIX) && !childName + .startsWith(Folder.RESERVED_FOLDER_PREFIX))); RequestContext rc = Jetspeed.getCurrentRequestContext(); boolean configureMode = false; if (rc != null) { - if (rc.getPipeline().getName().equals(PortalReservedParameters.CONFIG_PIPELINE_NAME) || - rc.getPipeline().getName().equals(PortalReservedParameters.DESKTOP_CONFIG_PIPELINE_NAME)) + if (rc.getPipeline().getName().equals( + PortalReservedParameters.CONFIG_PIPELINE_NAME) + || rc + .getPipeline() + .getName() + .equals( + PortalReservedParameters.DESKTOP_CONFIG_PIPELINE_NAME)) { configureMode = true; } } - + if (visible || configureMode) { // test child name uniqueness - boolean childUnique = true ; + boolean childUnique = true; Iterator allChildrenIter = allChildren.iterator(); while (childUnique && allChildrenIter.hasNext()) { - childUnique = !childName.equals(((Node)allChildrenIter.next()).getName()); + childUnique = !childName + .equals(((Node) allChildrenIter.next()) + .getName()); } // add uniquely named children proxies @@ -803,15 +870,21 @@ { if (child instanceof Folder) { - allChildren.add(FolderProxy.newInstance(getView(), locatorName, (Folder)proxy, (Folder)child)); + allChildren.add(FolderProxy.newInstance( + getView(), locatorName, (Folder) proxy, + (Folder) child)); } else if (child instanceof Page) { - allChildren.add(PageProxy.newInstance(getView(), locatorName, (Folder)proxy, (Page)child)); + allChildren.add(PageProxy.newInstance( + getView(), locatorName, (Folder) proxy, + (Page) child)); } else if (child instanceof Link) { - allChildren.add(LinkProxy.newInstance(getView(), locatorName, (Folder)proxy, (Link)child)); + allChildren.add(LinkProxy.newInstance( + getView(), locatorName, (Folder) proxy, + (Link) child)); } } } @@ -821,7 +894,7 @@ if (folderDocumentOrder == null) { List documentOrder = folder.getDocumentOrder(); - if ((documentOrder != null) && !documentOrder.isEmpty()) + if ((documentOrder != null) && !documentOrder.isEmpty()) { folderDocumentOrder = documentOrder; } @@ -834,42 +907,35 @@ { final List order = folderDocumentOrder; Comparator comparator = new Comparator() + { + + public int compare(Object proxyNode1, Object proxyNode2) { - public int compare(Object proxyNode1, Object proxyNode2) + // compare names of nodes against order or each other by + // default + String name1 = ((Node) proxyNode1).getName(); + String name2 = ((Node) proxyNode2).getName(); + if (order != null) { - // compare names of nodes against order or each other by default - String name1 = ((Node)proxyNode1).getName(); - String name2 = ((Node)proxyNode2).getName(); - if (order != null) + // compare names against order + int index1 = order.indexOf(name1); + int index2 = order.indexOf(name2); + if ((index1 != -1) || (index2 != -1)) { - // compare names against order - int index1 = order.indexOf(name1); - int index2 = order.indexOf(name2); - if ((index1 != -1) || (index2 != -1)) - { - if ((index1 == -1) && (index2 != -1)) - { - return 1; - } - if ((index1 != -1) && (index2 == -1)) - { - return -1; - } - return index1-index2; - } + if ((index1 == -1) && (index2 != -1)) { return 1; } + if ((index1 != -1) && (index2 == -1)) { return -1; } + return index1 - index2; } - // compare names against each other - return name1.compareTo(name2); } - } ; + // compare names against each other + return name1.compareTo(name2); + } + }; Collections.sort(allChildren, comparator); } // wrap ordered children in new NodeSet - if (!allChildren.isEmpty()) - { - return new NodeSetImpl(allChildren); - } + if (!allChildren.isEmpty()) { return new NodeSetImpl(allChildren); } } catch (FolderNotFoundException fnfe) { @@ -881,9 +947,9 @@ } /** - * getSearchFolders - aggregate all concrete folders in site view - * at this proxy folder view path - * + * getSearchFolders - aggregate all concrete folders in site view at this + * proxy folder view path + * * @return list containing concrete search folders in folder view * @throws FolderNotFoundException */ @@ -899,7 +965,8 @@ while (pathsIter.hasNext()) { // construct folder paths - SiteViewSearchPath searchPath = (SiteViewSearchPath)pathsIter.next(); + SiteViewSearchPath searchPath = (SiteViewSearchPath) pathsIter + .next(); String path = searchPath.toString(); if (!path.equals(Folder.PATH_SEPARATOR)) { @@ -909,7 +976,7 @@ { path = getPath(); } - + // get existing folders from PageManager, create // corresponding search folder objects, and add to // search folders list @@ -918,7 +985,8 @@ Folder folder = getView().getPageManager().getFolder(path); if (folder != null) { - searchFolders.add(new SearchFolder(folder, searchPath.getLocatorName())); + searchFolders.add(new SearchFolder(folder, searchPath + .getLocatorName())); } } catch (NodeException ne) @@ -934,17 +1002,15 @@ } // return search folders - if (!searchFolders.isEmpty()) - { - return searchFolders; - } - throw new FolderNotFoundException("Search folders at " + getPath() + " not found or accessible"); + if (!searchFolders.isEmpty()) { return searchFolders; } + throw new FolderNotFoundException("Search folders at " + getPath() + + " not found or accessible"); } /** - * getInheritanceFolders - aggregate all concrete inheritance folders - * in site view at this proxy folder view path - * + * getInheritanceFolders - aggregate all concrete inheritance folders in + * site view at this proxy folder view path + * * @return list containing concrete inheritance folders in folder view * @throws FolderNotFoundException */ @@ -967,7 +1033,7 @@ else { inheritanceFolders = new ArrayList(searchFolders.size()); - } + } do { // copy ordered search path folders into inheritance @@ -975,24 +1041,22 @@ Iterator foldersIter = searchFolders.iterator(); while (foldersIter.hasNext()) { - inheritanceFolders.add(((SearchFolder)foldersIter.next()).folder); + inheritanceFolders + .add(((SearchFolder) foldersIter.next()).folder); } // get super/parent search paths - folder = (FolderProxy)getNodeProxy(folder.getParent()); + folder = (FolderProxy) getNodeProxy(folder.getParent()); if (folder != null) { searchFolders = folder.getSearchFolders(); } - } - while (folder != null); + } while (folder != null); } // return inheritance folders - if (!inheritanceFolders.isEmpty()) - { - return inheritanceFolders; - } - throw new FolderNotFoundException("Inheritance folders at " + getPath() + " not found or accessible"); + if (!inheritanceFolders.isEmpty()) { return inheritanceFolders; } + throw new FolderNotFoundException("Inheritance folders at " + getPath() + + " not found or accessible"); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/page/proxy/LinkProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/page/proxy/LinkProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/page/proxy/LinkProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,59 +26,76 @@ import org.apache.jetspeed.portalsite.view.SiteView; /** - * This class proxies PSML Link instances to create a logical view - * of site content using the Dynamic Proxy pattern. + * This class proxies PSML Link instances to create a logical view of site + * content using the Dynamic Proxy pattern. * * @author Randy Watler * @version $Id: LinkProxy.java 517121 2007-03-12 07:45:49Z ate $ */ public class LinkProxy extends NodeProxy implements InvocationHandler { + /** * link - proxy delegate link instance */ private Link link; /** - * newInstance - creates a new proxy instance that implements the Link interface - * - * @param view site view owner of this proxy - * @param locatorName name of profile locator associated - * with the proxy delegate - * @param parentFolder view parent proxy folder - * @param link proxy delegate + * newInstance - creates a new proxy instance that implements the Link + * interface + * + * @param view + * site view owner of this proxy + * @param locatorName + * name of profile locator associated with the proxy delegate + * @param parentFolder + * view parent proxy folder + * @param link + * proxy delegate */ - public static Link newInstance(SiteView view, String locatorName, Folder parentFolder, Link link) + public static Link newInstance(SiteView view, String locatorName, + Folder parentFolder, Link link) { - return (Link)Proxy.newProxyInstance(link.getClass().getClassLoader(), new Class[]{Link.class}, new LinkProxy(view, locatorName, parentFolder, link)); + return (Link) Proxy.newProxyInstance(link.getClass().getClassLoader(), + new Class[] + {Link.class}, new LinkProxy(view, locatorName, parentFolder, + link)); } /** * LinkProxy - private constructor used by newInstance() - * - * @param view site view owner of this proxy - * @param locatorName name of profile locator associated - * with the proxy delegate - * @param parentFolder view parent proxy folder - * @param link proxy delegate + * + * @param view + * site view owner of this proxy + * @param locatorName + * name of profile locator associated with the proxy delegate + * @param parentFolder + * view parent proxy folder + * @param link + * proxy delegate */ - private LinkProxy(SiteView view, String locatorName, Folder parentFolder, Link link) + private LinkProxy(SiteView view, String locatorName, Folder parentFolder, + Link link) { super(view, locatorName, parentFolder, link.getName(), link.isHidden()); this.link = link; } - + /** * invoke - method invocation dispatch for this proxy, (defaults to - * invocation of delegate unless method is implemented in this - * proxy handler or should be hidden/stubbed) - * - * @param proxy instance invoked against - * @param method Link interface method invoked - * @param args method arguments + * invocation of delegate unless method is implemented in this proxy handler + * or should be hidden/stubbed) + * + * @param proxy + * instance invoked against + * @param method + * Link interface method invoked + * @param args + * method arguments * @throws Throwable */ - public Object invoke(Object proxy, Method m, Object [] args) throws Throwable + public Object invoke(Object proxy, Method m, Object[] args) + throws Throwable { // proxy implementation method dispatch if (m.equals(GET_PARENT_METHOD)) @@ -101,16 +118,11 @@ { return new Boolean(isHidden()); } - else if (m.equals(TO_STRING_METHOD)) - { - return toString(); - } - + else if (m.equals(TO_STRING_METHOD)) { return toString(); } + // proxy suppression of not implemented or mutable methods - if (m.getName().startsWith("set")) - { - throw new RuntimeException("Link instance is immutable from proxy."); - } + if (m.getName().startsWith("set")) { throw new RuntimeException( + "Link instance is immutable from proxy."); } // attempt to invoke method on delegate Link instance return m.invoke(link, args); @@ -118,7 +130,7 @@ /** * getLink - get proxy delegate link instance - * + * * @return delegate link */ public Link getLink() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/page/proxy/PageProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/page/proxy/PageProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/om/page/proxy/PageProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,18 +27,20 @@ import org.apache.jetspeed.portalsite.view.SiteView; /** - * This class proxies PSML Page instances to create a logical view - * of site content using the Dynamic Proxy pattern. + * This class proxies PSML Page instances to create a logical view of site + * content using the Dynamic Proxy pattern. * * @author Randy Watler * @version $Id: PageProxy.java 517121 2007-03-12 07:45:49Z ate $ */ public class PageProxy extends NodeProxy implements InvocationHandler { + /** * *_METHOD - Page method constants */ - protected static final Method GET_MENU_DEFINITIONS_METHOD = reflectMethod(Page.class, "getMenuDefinitions", null); + protected static final Method GET_MENU_DEFINITIONS_METHOD = reflectMethod( + Page.class, "getMenuDefinitions", null); /** * page - proxy delegate page instance @@ -46,45 +48,61 @@ private Page page; /** - * newInstance - creates a new proxy instance that implements the Page interface - * - * @param view site view owner of this proxy - * @param locatorName name of profile locator associated - * with the proxy delegate - * @param parentFolder view parent proxy folder - * @param page proxy delegate + * newInstance - creates a new proxy instance that implements the Page + * interface + * + * @param view + * site view owner of this proxy + * @param locatorName + * name of profile locator associated with the proxy delegate + * @param parentFolder + * view parent proxy folder + * @param page + * proxy delegate */ - public static Page newInstance(SiteView view, String locatorName, Folder parentFolder, Page page) + public static Page newInstance(SiteView view, String locatorName, + Folder parentFolder, Page page) { - return (Page)Proxy.newProxyInstance(page.getClass().getClassLoader(), new Class[]{Page.class}, new PageProxy(view, locatorName, parentFolder, page)); + return (Page) Proxy.newProxyInstance(page.getClass().getClassLoader(), + new Class[] + {Page.class}, new PageProxy(view, locatorName, parentFolder, + page)); } /** * PageProxy - private constructor used by newInstance() - * - * @param view site view owner of this proxy - * @param locatorName name of profile locator associated - * with the proxy delegate - * @param parentFolder view parent proxy folder - * @param page proxy delegate + * + * @param view + * site view owner of this proxy + * @param locatorName + * name of profile locator associated with the proxy delegate + * @param parentFolder + * view parent proxy folder + * @param page + * proxy delegate */ - private PageProxy(SiteView view, String locatorName, Folder parentFolder, Page page) + private PageProxy(SiteView view, String locatorName, Folder parentFolder, + Page page) { super(view, locatorName, parentFolder, page.getName(), page.isHidden()); this.page = page; } - + /** * invoke - method invocation dispatch for this proxy, (defaults to - * invocation of delegate unless method is implemented in this - * proxy handler or should be hidden/stubbed) - * - * @param proxy instance invoked against - * @param method Page interface method invoked - * @param args method arguments + * invocation of delegate unless method is implemented in this proxy handler + * or should be hidden/stubbed) + * + * @param proxy + * instance invoked against + * @param method + * Page interface method invoked + * @param args + * method arguments * @throws Throwable */ - public Object invoke(Object proxy, Method m, Object [] args) throws Throwable + public Object invoke(Object proxy, Method m, Object[] args) + throws Throwable { // proxy implementation method dispatch if (m.equals(GET_MENU_DEFINITIONS_METHOD)) @@ -115,16 +133,11 @@ { return new Boolean(isHidden()); } - else if (m.equals(TO_STRING_METHOD)) - { - return toString(); - } - + else if (m.equals(TO_STRING_METHOD)) { return toString(); } + // proxy suppression of not implemented or mutable methods - if (m.getName().startsWith("set")) - { - throw new RuntimeException("Page instance is immutable from proxy."); - } + if (m.getName().startsWith("set")) { throw new RuntimeException( + "Page instance is immutable from proxy."); } // attempt to invoke method on delegate Page instance return m.invoke(page, args); @@ -132,7 +145,7 @@ /** * getPage - get proxy delegate page instance - * + * * @return delegate page */ public Page getPage() @@ -142,7 +155,7 @@ /** * aggregateMenuDefinitionLocators - aggregate all menu definition locators - * in site view for this folder or page + * in site view for this folder or page */ protected void aggregateMenuDefinitionLocators() { @@ -152,7 +165,9 @@ // folder menu definitions include standard menu definition // locator defaults mergeMenuDefinitionLocators(page.getMenuDefinitions(), page); - FolderProxy parentFolderProxy = (FolderProxy)Proxy.getInvocationHandler(getParent()); - mergeMenuDefinitionLocators(parentFolderProxy.getMenuDefinitionLocators()); + FolderProxy parentFolderProxy = (FolderProxy) Proxy + .getInvocationHandler(getParent()); + mergeMenuDefinitionLocators(parentFolderProxy + .getMenuDefinitionLocators()); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/page/document/proxy/NodeProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/page/document/proxy/NodeProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/page/document/proxy/NodeProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,9 +19,9 @@ import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; +import java.util.Collections; import java.util.Iterator; import java.util.List; -import java.util.Collections; import org.apache.jetspeed.om.folder.Folder; import org.apache.jetspeed.om.folder.MenuDefinition; @@ -31,25 +31,39 @@ import org.apache.jetspeed.portalsite.view.SiteViewProxy; /** - * This class proxies Node instances to create a logical - * view of site content. + * This class proxies Node instances to create a logical view of site content. * * @author Randy Watler * @version $Id: NodeProxy.java 516448 2007-03-09 16:25:47Z ate $ */ public abstract class NodeProxy extends SiteViewProxy { + /** * *_METHOD - Node method constants */ - protected static final Method EQUALS_METHOD = reflectMethod(Object.class, "equals", new Class[]{Object.class}); - protected static final Method GET_PARENT_METHOD = reflectMethod(Node.class, "getParent", null); - protected static final Method GET_PATH_METHOD = reflectMethod(Node.class, "getPath", null); - protected static final Method GET_URL_METHOD = reflectMethod(Node.class, "getUrl", null); - protected static final Method HASH_CODE_METHOD = reflectMethod(Object.class, "hashCode", null); - protected static final Method IS_HIDDEN_METHOD = reflectMethod(Node.class, "isHidden", null); - protected static final Method TO_STRING_METHOD = reflectMethod(Object.class, "toString", null); + protected static final Method EQUALS_METHOD = reflectMethod(Object.class, + "equals", new Class[] + {Object.class}); + protected static final Method GET_PARENT_METHOD = reflectMethod(Node.class, + "getParent", null); + + protected static final Method GET_PATH_METHOD = reflectMethod(Node.class, + "getPath", null); + + protected static final Method GET_URL_METHOD = reflectMethod(Node.class, + "getUrl", null); + + protected static final Method HASH_CODE_METHOD = reflectMethod( + Object.class, "hashCode", null); + + protected static final Method IS_HIDDEN_METHOD = reflectMethod(Node.class, + "isHidden", null); + + protected static final Method TO_STRING_METHOD = reflectMethod( + Object.class, "toString", null); + /** * parent - view parent proxy folder instance */ @@ -67,13 +81,13 @@ /** * menuDefinitionLocators - menu definitions aggregated by name saved in - * menu definition locators + * menu definition locators */ private List menuDefinitionLocators; /** * menuDefinitionLocatorsAggregated - boolean flag to indicate - * menuDefinitionLocators aggregated + * menuDefinitionLocators aggregated */ private boolean menuDefinitionLocatorsAggregated; @@ -84,22 +98,27 @@ /** * menuDefinitionsAggregated - boolean flag to indicate menuDefinitions - * aggregated from menuDefinitionLocators + * aggregated from menuDefinitionLocators */ private boolean menuDefinitionsAggregated; /** * NodeProxy - constructor - * - * @param view site view owner of this proxy - * @param locatorName profile locator name associated with - * the derived delegate of this proxy in - * the site view - * @param parent view parent proxy folder - * @param name name of node to proxy - * @param hidden hidden status of node to proxy + * + * @param view + * site view owner of this proxy + * @param locatorName + * profile locator name associated with the derived delegate of + * this proxy in the site view + * @param parent + * view parent proxy folder + * @param name + * name of node to proxy + * @param hidden + * hidden status of node to proxy */ - protected NodeProxy(SiteView view, String locatorName, Folder parent, String name, boolean hidden) + protected NodeProxy(SiteView view, String locatorName, Folder parent, + String name, boolean hidden) { super(view, locatorName); this.parent = parent; @@ -123,10 +142,10 @@ this.hidden = hidden; } } - + /** * getParent - proxy implementation of Node.getParent() - * + * * @return parent folder */ public Node getParent() @@ -166,24 +185,27 @@ /** * getMenuDefinitions - proxy implementation of Folder.getMenuDefinitions() - * and Page.getMenuDefinitions() - * + * and Page.getMenuDefinitions() + * * @return definition list */ public List getMenuDefinitions() { // get menu definitions aggregated by name from // aggregated menu definition locators - if (! menuDefinitionsAggregated) + if (!menuDefinitionsAggregated) { List locators = getMenuDefinitionLocators(); if (locators != null) { - menuDefinitions = Collections.synchronizedList(new ArrayList(locators.size())); + menuDefinitions = Collections.synchronizedList(new ArrayList( + locators.size())); Iterator locatorsIter = locators.iterator(); while (locatorsIter.hasNext()) { - menuDefinitions.add(((SiteViewMenuDefinitionLocator)locatorsIter.next()).getMenuDefinition()); + menuDefinitions + .add(((SiteViewMenuDefinitionLocator) locatorsIter + .next()).getMenuDefinition()); } } menuDefinitionsAggregated = true; @@ -193,14 +215,14 @@ /** * getMenuDefinitionLocators - get list of menu definition locators - * aggregated by name for this folder or page - * + * aggregated by name for this folder or page + * * @return definition locator list */ public List getMenuDefinitionLocators() { // get menu definition locators aggregated by name - if (! menuDefinitionLocatorsAggregated) + if (!menuDefinitionLocatorsAggregated) { aggregateMenuDefinitionLocators(); menuDefinitionLocatorsAggregated = true; @@ -210,24 +232,22 @@ /** * getMenuDefinitionLocator - get menu definition locator by name - * - * @param name menu definition name + * + * @param name + * menu definition name * @return menu definition locator */ public SiteViewMenuDefinitionLocator getMenuDefinitionLocator(String name) { // get menu definition locators and find by name List locators = getMenuDefinitionLocators(); - if (locators != null) - { - return findMenuDefinitionLocator(name); - } + if (locators != null) { return findMenuDefinitionLocator(name); } return null; } /** * aggregateMenuDefinitionLocators - aggregate all menu definition locators - * in site view for this folder or page + * in site view for this folder or page */ protected void aggregateMenuDefinitionLocators() { @@ -235,12 +255,14 @@ } /** - * mergeMenuDefinitionLocators - utilty to merge menu definition locator lists - * to be used by derived implementations to aggregate - * menu definition locators - * - * @param definitions list of menu definitions to merge - * @param node page or folder node that defines menu definitions + * mergeMenuDefinitionLocators - utilty to merge menu definition locator + * lists to be used by derived implementations to aggregate menu definition + * locators + * + * @param definitions + * list of menu definitions to merge + * @param node + * page or folder node that defines menu definitions */ protected void mergeMenuDefinitionLocators(List definitions, Node node) { @@ -252,7 +274,8 @@ while (definitionsIter.hasNext()) { // aggregate menu definition by valid name - MenuDefinition definition = (MenuDefinition)definitionsIter.next(); + MenuDefinition definition = (MenuDefinition) definitionsIter + .next(); String definitionName = definition.getName(); if (definitionName != null) { @@ -262,9 +285,13 @@ { if (menuDefinitionLocators == null) { - menuDefinitionLocators = Collections.synchronizedList(new ArrayList(definitions.size() * 2)); + menuDefinitionLocators = Collections + .synchronizedList(new ArrayList(definitions + .size() * 2)); } - menuDefinitionLocators.add(new SiteViewMenuDefinitionLocator(definition, node)); + menuDefinitionLocators + .add(new SiteViewMenuDefinitionLocator( + definition, node)); } } } @@ -272,11 +299,12 @@ } /** - * mergeMenuDefinitionLocators - utilty to merge menu definition locator lists - * to be used by derived implementations to aggregate - * menu definition locators - * - * @param locators list of menu definition locators to merge + * mergeMenuDefinitionLocators - utilty to merge menu definition locator + * lists to be used by derived implementations to aggregate menu definition + * locators + * + * @param locators + * list of menu definition locators to merge */ protected void mergeMenuDefinitionLocators(List locators) { @@ -288,7 +316,8 @@ while (locatorsIter.hasNext()) { // aggregate menu definition by valid name - SiteViewMenuDefinitionLocator locator = (SiteViewMenuDefinitionLocator)locatorsIter.next(); + SiteViewMenuDefinitionLocator locator = (SiteViewMenuDefinitionLocator) locatorsIter + .next(); String definitionName = locator.getName(); // add unique menu definition to end of @@ -297,7 +326,9 @@ { if (menuDefinitionLocators == null) { - menuDefinitionLocators = Collections.synchronizedList(new ArrayList(locators.size() * 2)); + menuDefinitionLocators = Collections + .synchronizedList(new ArrayList( + locators.size() * 2)); } menuDefinitionLocators.add(locator); } @@ -306,9 +337,11 @@ } /** - * menuDefinitionLocatorsContains - contains test for menu definition locators by name - * - * @param name menu definition name + * menuDefinitionLocatorsContains - contains test for menu definition + * locators by name + * + * @param name + * menu definition name * @return contains name result */ private boolean menuDefinitionLocatorsContains(String name) @@ -319,8 +352,9 @@ /** * findMenuDefinitionLocator - find menu definition locator by name - * - * @param name menu definition name + * + * @param name + * menu definition name * @return menu definition locator */ private SiteViewMenuDefinitionLocator findMenuDefinitionLocator(String name) @@ -328,15 +362,14 @@ // find matching menu definition locator by name if ((menuDefinitionLocators != null) && (name != null)) { - synchronized (menuDefinitionLocators) { + synchronized (menuDefinitionLocators) + { Iterator locatorsIter = menuDefinitionLocators.iterator(); while (locatorsIter.hasNext()) { - SiteViewMenuDefinitionLocator locator = (SiteViewMenuDefinitionLocator)locatorsIter.next(); - if (name.equals(locator.getName())) - { - return locator; - } + SiteViewMenuDefinitionLocator locator = (SiteViewMenuDefinitionLocator) locatorsIter + .next(); + if (name.equals(locator.getName())) { return locator; } } } } @@ -346,7 +379,8 @@ /** * equals - proxy implementation of Object.equals() * - * @param object test instance + * @param object + * test instance * @return equals test result */ public boolean equals(Object object) @@ -354,20 +388,15 @@ if (object != null) { // trivial compare - if (object == this) - { - return true; - } + if (object == this) { return true; } // compare as NodeProxy if (!(object instanceof NodeProxy)) { object = getNodeProxy(object); } - if (object instanceof NodeProxy) - { - return path.equals(((NodeProxy)object).path); - } + if (object instanceof NodeProxy) { return path + .equals(((NodeProxy) object).path); } } return false; } @@ -393,10 +422,11 @@ } /** - * getNodeProxy - utility method to access NodeProxy handler - * from Node proxy instance - * - * @param node node proxy instance + * getNodeProxy - utility method to access NodeProxy handler from Node proxy + * instance + * + * @param node + * node proxy instance * @return node proxy invocation handler instance */ public static NodeProxy getNodeProxy(Object node) @@ -404,10 +434,7 @@ if ((node != null) && Proxy.isProxyClass(node.getClass())) { Object nodeProxyHandler = Proxy.getInvocationHandler(node); - if (nodeProxyHandler instanceof NodeProxy) - { - return (NodeProxy)nodeProxyHandler; - } + if (nodeProxyHandler instanceof NodeProxy) { return (NodeProxy) nodeProxyHandler; } } return null; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/page/document/proxy/NodeSetImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/page/document/proxy/NodeSetImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/page/document/proxy/NodeSetImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,15 +25,15 @@ import org.apache.jetspeed.page.document.NodeSet; /** - * This class implements generic NodeSet ordered lists - * used with proxied instances of PSML Folders to create a - * logical view of site content. + * This class implements generic NodeSet ordered lists used with proxied + * instances of PSML Folders to create a logical view of site content. * * @author Randy Watler * @version $Id: NodeSetImpl.java 552972 2007-07-03 20:42:07Z taylor $ */ public class NodeSetImpl implements NodeSet { + /** * nodes - list of proxy nodes */ @@ -41,8 +41,9 @@ /** * NodeSetImpl - construct immutable proxy Node NodeSet list - * - * @param nodes list of proxy Nodes + * + * @param nodes + * list of proxy Nodes */ public NodeSetImpl(List nodes) { @@ -51,8 +52,9 @@ /** * get - return proxy Node by name or path - * - * @param name node name + * + * @param name + * node name * @return Node proxy */ public Node get(String name) @@ -62,29 +64,27 @@ while (nodesIter.hasNext()) { Node node = (Node) nodesIter.next(); - if (node.getName().equals(name) || node.getPath().equals(name)) - { - return node; - } + if (node.getName().equals(name) || node.getPath().equals(name)) { return node; } } return null; } /** * iterator - return iterator over ordered list - * + * * @return proxy NodeSet list iterator */ public Iterator iterator() { return nodes.listIterator(); } - + /** - * subset - construct new NodeSet containing Node proxies - * of the specified type - * - * @param type node type + * subset - construct new NodeSet containing Node proxies of the specified + * type + * + * @param type + * node type * @return proxy NodeSet list */ public NodeSet subset(String type) @@ -106,17 +106,16 @@ } // wrap matching nodes in new NodeSet - if (subsetNodes != null) - return new NodeSetImpl(subsetNodes); + if (subsetNodes != null) return new NodeSetImpl(subsetNodes); return null; } /** - * inclusiveSubset - construct new NodeSet containing Node - * proxies whose name or path matches - * the specified regex pattern - * - * @param regex proxy Node name/path match pattern + * inclusiveSubset - construct new NodeSet containing Node proxies whose + * name or path matches the specified regex pattern + * + * @param regex + * proxy Node name/path match pattern * @return proxy NodeSet list */ public NodeSet inclusiveSubset(String regex) @@ -128,7 +127,8 @@ while (nodesIter.hasNext()) { Node node = (Node) nodesIter.next(); - if (pattern.matcher(node.getName()).matches() || pattern.matcher(node.getPath()).matches()) + if (pattern.matcher(node.getName()).matches() + || pattern.matcher(node.getPath()).matches()) { if (subsetNodes == null) { @@ -139,17 +139,16 @@ } // wrap matching nodes in new NodeSet - if (subsetNodes != null) - return new NodeSetImpl(subsetNodes); + if (subsetNodes != null) return new NodeSetImpl(subsetNodes); return null; } - + /** - * exclusiveSubset - construct new NodeSet containing Node - * proxies whose name or path does not match - * the specified regex pattern - * - * @param regex proxy Node name/path match pattern + * exclusiveSubset - construct new NodeSet containing Node proxies whose + * name or path does not match the specified regex pattern + * + * @param regex + * proxy Node name/path match pattern * @return proxy NodeSet list */ public NodeSet exclusiveSubset(String regex) @@ -161,7 +160,8 @@ while (nodesIter.hasNext()) { Node node = (Node) nodesIter.next(); - if (!pattern.matcher(node.getName()).matches() && !pattern.matcher(node.getPath()).matches()) + if (!pattern.matcher(node.getName()).matches() + && !pattern.matcher(node.getPath()).matches()) { if (subsetNodes == null) { @@ -172,14 +172,13 @@ } // wrap matching nodes in new NodeSet - if (subsetNodes != null) - return new NodeSetImpl(subsetNodes); + if (subsetNodes != null) return new NodeSetImpl(subsetNodes); return null; } /** * size - return size of NodeSet list - * + * * @return size of list */ public int size() @@ -189,8 +188,9 @@ /** * contains - test named Node proxy for existance in NodeSet list - * - * @param node proxy Node + * + * @param node + * proxy Node * @return Node proxy */ public boolean contains(Node node) @@ -199,9 +199,8 @@ } /** - * isEmpty - returns flag indicationg whether NodeSet list is - * empty or not - * + * isEmpty - returns flag indicationg whether NodeSet list is empty or not + * * @return empty flag */ public boolean isEmpty() @@ -211,8 +210,9 @@ /** * add - adds specified proxyNode to the ordered NodeSet list - * - * @param node proxy Node + * + * @param node + * proxy Node */ public void add(Node node) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuElementImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuElementImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuElementImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,22 +24,23 @@ import org.apache.jetspeed.portalsite.MenuElement; /** - * This abstract class implements common features of portal-site - * menu elements constructed and returned to decorators. + * This abstract class implements common features of portal-site menu elements + * constructed and returned to decorators. * * @author Randy Watler * @version $Id: MenuElementImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public abstract class MenuElementImpl implements MenuElement, Cloneable { + /** * parentMenu - parent menu implementation */ private MenuImpl parent; /** - * node - underlying node proxy associated with this - * menu element in the site view + * node - underlying node proxy associated with this menu element in the + * site view */ private Node node; @@ -49,16 +50,16 @@ private String skin; /** - * skinInherited - flag indicating whether skin value - * has been inherited by propagating - * from parent menu + * skinInherited - flag indicating whether skin value has been inherited by + * propagating from parent menu */ private boolean skinInherited; /** * MenuElementImpl - constructor - * - * @param parent containing menu implementation + * + * @param parent + * containing menu implementation */ protected MenuElementImpl(MenuImpl parent) { @@ -67,9 +68,11 @@ /** * MenuElementImpl - node proxy constructor - * - * @param parent containing menu implementation - * @param node menu element node proxy + * + * @param parent + * containing menu implementation + * @param node + * menu element node proxy */ protected MenuElementImpl(MenuImpl parent, Node node) { @@ -79,7 +82,7 @@ /** * clone - clone this instance - * + * * @return unparented copy */ public Object clone() throws CloneNotSupportedException @@ -94,7 +97,7 @@ /** * equals - compare menu element implementations - * + * * @return equals result */ public boolean equals(Object obj) @@ -108,10 +111,11 @@ String name = getName(); if ((url != null) || (name != null)) { - String objUrl = ((MenuElementImpl)obj).getUrl(); - String objName = ((MenuElementImpl)obj).getName(); - return ((((name == null) && (objName == null)) || ((name != null) && name.equals(objName))) && - (((url != null) && url.equals(objUrl)) || ((url == null) && (objUrl == null)))); + String objUrl = ((MenuElementImpl) obj).getUrl(); + String objName = ((MenuElementImpl) obj).getName(); + return ((((name == null) && (objName == null)) || ((name != null) && name + .equals(objName))) && (((url != null) && url + .equals(objUrl)) || ((url == null) && (objUrl == null)))); } } return false; @@ -119,35 +123,35 @@ /** * getElementType - get type of menu element - * - * @return MENU_ELEMENT_TYPE, OPTION_ELEMENT_TYPE, or - * SEPARATOR_ELEMENT_TYPE + * + * @return MENU_ELEMENT_TYPE, OPTION_ELEMENT_TYPE, or SEPARATOR_ELEMENT_TYPE */ public abstract String getElementType(); /** - * getParentMenu - get menu that contains menu element - * + * getParentMenu - get menu that contains menu element + * * @return parent menu - */ + */ public Menu getParentMenu() { return parent; } /** - * setParentMenu - set menu that contains menu element - * - * @param parentMenu parent menu - */ + * setParentMenu - set menu that contains menu element + * + * @param parentMenu + * parent menu + */ protected void setParentMenu(Menu parentMenu) { - parent = (MenuImpl)parentMenu; + parent = (MenuImpl) parentMenu; } /** * getName - get name of menu element used for default title - * + * * @return menu element name */ public String getName() @@ -158,7 +162,7 @@ /** * getUrl - get url of menu element used for comparison - * + * * @return folder, page, or link url */ public String getUrl() @@ -169,90 +173,77 @@ /** * getTitle - get default title for menu element - * + * * @return title text */ public String getTitle() { // return node or default title - if (node != null) - { - return node.getTitle(); - } + if (node != null) { return node.getTitle(); } return getName(); } /** * getShortTitle - get default short title for menu element - * + * * @return short title text */ public String getShortTitle() { // return node or default short title - if (node != null) - { - return node.getShortTitle(); - } + if (node != null) { return node.getShortTitle(); } return getName(); } /** - * getTitle - get locale specific title for menu element - * from metadata - * - * @param locale preferred locale + * getTitle - get locale specific title for menu element from metadata + * + * @param locale + * preferred locale * @return title text */ public String getTitle(Locale locale) { // return node or default title for preferred locale - if (node != null) - { - return node.getTitle(locale); - } + if (node != null) { return node.getTitle(locale); } return getName(); } /** - * getShortTitle - get locale specific short title for menu - * element from metadata - * - * @param locale preferred locale + * getShortTitle - get locale specific short title for menu element from + * metadata + * + * @param locale + * preferred locale * @return short title text */ public String getShortTitle(Locale locale) { // return node or default short title for preferred locale - if (node != null) - { - return node.getShortTitle(locale); - } + if (node != null) { return node.getShortTitle(locale); } return getName(); } /** * getMetadata - get generic metadata for menu element - * + * * @return metadata - */ + */ public GenericMetadata getMetadata() { // return node metadata if (node != null) { GenericMetadata metadata = node.getMetadata(); - if (metadata != null && metadata.getFields() != null && !metadata.getFields().isEmpty()) - { - return metadata; - } + if (metadata != null && metadata.getFields() != null + && !metadata.getFields().isEmpty()) { return metadata; } } return null; } /** * getSkin - get skin name for menu element - * + * * @return skin name */ public String getSkin() @@ -272,21 +263,22 @@ /** * getNode - get menu element node proxy in the site view - * + * * @return node proxy */ protected Node getNode() { return node; - } + } /** * setNode - set menu element node proxy in the site view - * - * @param node node proxy + * + * @param node + * node proxy */ protected void setNode(Node node) { this.node = node; - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -45,48 +45,54 @@ import org.apache.jetspeed.portalsite.view.SiteView; /** - * This class implements the portal-site menu elements - * constructed and returned to decorators. + * This class implements the portal-site menu elements constructed and returned + * to decorators. * * @author Randy Watler * @version $Id: MenuImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class MenuImpl extends MenuElementImpl implements Menu, Cloneable { + /** * definition - menu definition */ private MenuDefinition definition; /** - * elements - ordered list of menu elements that - * make up this instaniated menu + * elements - ordered list of menu elements that make up this instaniated + * menu */ private List elements; /** * elementRelative - flag that indicates whether any relative paths - * dependent on the current page in context were - * referenced while constructing menu elements: - * requires request, not session, caching + * dependent on the current page in context were referenced while + * constructing menu elements: requires request, not session, caching */ private boolean elementRelative; /** * MenuImpl - request/session context dependent constructor - * - * @param parent containing menu implementation - * @param definition menu definition - * @param context request context - * @param menus related menu definition names set + * + * @param parent + * containing menu implementation + * @param definition + * menu definition + * @param context + * request context + * @param menus + * related menu definition names set */ - public MenuImpl(MenuImpl parent, MenuDefinition definition, PortalSiteRequestContextImpl context, Set menus) + public MenuImpl(MenuImpl parent, MenuDefinition definition, + PortalSiteRequestContextImpl context, Set menus) { super(parent); this.definition = definition; // get site view from context - SiteView view = ((PortalSiteSessionContextImpl)context.getSessionContext()).getSiteView(); + SiteView view = ((PortalSiteSessionContextImpl) context + .getSessionContext()).getSiteView(); if (view != null) { // define menu node for titles and metadata if options @@ -97,7 +103,8 @@ { try { - optionProxy = view.getNodeProxy(options, context.getPage(), true, true); + optionProxy = view.getNodeProxy(options, context.getPage(), + true, true); } catch (NodeNotFoundException nnfe) { @@ -114,7 +121,8 @@ // construct menu elements from menu definition // or nested menu definition elements; note that // menu elements override menu options attribute - if ((definition.getMenuElements() == null) || definition.getMenuElements().isEmpty()) + if ((definition.getMenuElements() == null) + || definition.getMenuElements().isEmpty()) { // if options optionProxy is a single folder, force // options to include all folder children if not to @@ -123,13 +131,16 @@ List overrideOptionProxies = null; if (optionProxy != null) { - if ((optionProxy instanceof Folder) && !definition.isPaths() && (definition.getDepth() != 0)) + if ((optionProxy instanceof Folder) + && !definition.isPaths() + && (definition.getDepth() != 0)) { // assemble folder children path using wildcard String folderChildrenPath = null; if (!options.endsWith(Folder.PATH_SEPARATOR)) { - folderChildrenPath = options + Folder.PATH_SEPARATOR + "*"; + folderChildrenPath = options + + Folder.PATH_SEPARATOR + "*"; } else { @@ -141,7 +152,9 @@ List folderChildren = null; try { - folderChildren = view.getNodeProxies(folderChildrenPath, context.getPage(), true, true); + folderChildren = view.getNodeProxies( + folderChildrenPath, context.getPage(), + true, true); } catch (NodeNotFoundException nnfe) { @@ -149,7 +162,8 @@ catch (SecurityException se) { } - if ((folderChildren != null) && !folderChildren.isEmpty()) + if ((folderChildren != null) + && !folderChildren.isEmpty()) { overrideOptionProxies = folderChildren; } @@ -164,13 +178,17 @@ overrideOptionProxies = new ArrayList(1); overrideOptionProxies.add(optionProxy); } - + // set relative element flag if options path is relative - this.elementRelative = (this.elementRelative || !options.startsWith(Folder.PATH_SEPARATOR)); + this.elementRelative = (this.elementRelative || !options + .startsWith(Folder.PATH_SEPARATOR)); } // menu defined only with menu definition options - this.elements = constructMenuElements(context, view, options, overrideOptionProxies, definition.getDepth(), definition.isPaths(), definition.isRegexp(), definition.getProfile(), definition.getOrder()); + this.elements = constructMenuElements(context, view, options, + overrideOptionProxies, definition.getDepth(), + definition.isPaths(), definition.isRegexp(), definition + .getProfile(), definition.getOrder()); } else { @@ -185,7 +203,7 @@ } menuNameReferenced = menus.add(definition.getName()); } - + // process menu elements in chunks between separators: // separators are included only if menu options are // generated after the separator and include/exclude @@ -195,7 +213,8 @@ List separatedElements = null; // process each defined menu element - Iterator menuElementsIter = definition.getMenuElements().iterator(); + Iterator menuElementsIter = definition.getMenuElements() + .iterator(); while (menuElementsIter.hasNext()) { Object menuElement = menuElementsIter.next(); @@ -203,7 +222,7 @@ { // construct menu option elements from definition using // defaults from menu definition as appropriate - MenuOptionsDefinition optionDefinition = (MenuOptionsDefinition)menuElement; + MenuOptionsDefinition optionDefinition = (MenuOptionsDefinition) menuElement; String locatorName = optionDefinition.getProfile(); if (locatorName == null) { @@ -214,7 +233,11 @@ { order = definition.getOrder(); } - List optionsAndMenus = constructMenuElements(context, view, optionDefinition.getOptions(), null, optionDefinition.getDepth(), optionDefinition.isPaths(), optionDefinition.isRegexp(), locatorName, order); + List optionsAndMenus = constructMenuElements(context, + view, optionDefinition.getOptions(), null, + optionDefinition.getDepth(), optionDefinition + .isPaths(), + optionDefinition.isRegexp(), locatorName, order); // append option and menu elements to current separator // elements list @@ -226,16 +249,20 @@ } else { - appendMenuElements(optionsAndMenus, separatedElements); + appendMenuElements(optionsAndMenus, + separatedElements); } } } else if (menuElement instanceof MenuSeparatorDefinition) { - // append current separator and separated option/menu elements + // append current separator and separated option/menu + // elements // to menu elements list if at least one option/menu - // element exists: do not include disassociated separators in menu - if ((separatedElements != null) && !separatedElements.isEmpty()) + // element exists: do not include disassociated + // separators in menu + if ((separatedElements != null) + && !separatedElements.isEmpty()) { if (this.elements == null) { @@ -255,8 +282,9 @@ // construct new separator and reset separator // and separator option/menu elements list - MenuSeparatorDefinition separatorDefinition = (MenuSeparatorDefinition)menuElement; - separator = new MenuSeparatorImpl(this, separatorDefinition); + MenuSeparatorDefinition separatorDefinition = (MenuSeparatorDefinition) menuElement; + separator = new MenuSeparatorImpl(this, + separatorDefinition); if (separatedElements != null) { separatedElements.clear(); @@ -265,10 +293,12 @@ else if (menuElement instanceof MenuDefinition) { // construct nested menu element from definition - MenuDefinition menuDefinition = (MenuDefinition)menuElement; - MenuImpl nestedMenu = new MenuImpl(this, menuDefinition, context, menus); + MenuDefinition menuDefinition = (MenuDefinition) menuElement; + MenuImpl nestedMenu = new MenuImpl(this, + menuDefinition, context, menus); - // append menu element to current separated elements list + // append menu element to current separated elements + // list if (separatedElements == null) { separatedElements = new ArrayList(1); @@ -276,14 +306,16 @@ appendMenuElement(nestedMenu, separatedElements); // set relative element flag if nested menu is relative - this.elementRelative = (this.elementRelative || nestedMenu.isElementRelative()); + this.elementRelative = (this.elementRelative || nestedMenu + .isElementRelative()); } else if (menuElement instanceof MenuIncludeDefinition) { // include or nest referenced menu definition // assuming reference to menu is not cyclic - MenuIncludeDefinition includeDefinition = (MenuIncludeDefinition)menuElement; - if ((menus == null) || !menus.contains(includeDefinition.getName())) + MenuIncludeDefinition includeDefinition = (MenuIncludeDefinition) menuElement; + if ((menus == null) + || !menus.contains(includeDefinition.getName())) { // get named root menu from context, (menu may // not exist in this context so failure to @@ -291,7 +323,8 @@ MenuImpl includeMenu = null; try { - includeMenu = (MenuImpl)context.getMenu(includeDefinition.getName()); + includeMenu = (MenuImpl) context + .getMenu(includeDefinition.getName()); } catch (NodeNotFoundException nnfe) { @@ -309,15 +342,18 @@ try { // clone menu and reparent - includeMenu = (MenuImpl)includeMenu.clone(); + includeMenu = (MenuImpl) includeMenu + .clone(); includeMenu.setParentMenu(this); - // append menu element to current separated elements list + // append menu element to current + // separated elements list if (separatedElements == null) { separatedElements = new ArrayList(1); } - appendMenuElement(includeMenu, separatedElements); + appendMenuElement(includeMenu, + separatedElements); } catch (CloneNotSupportedException cnse) { @@ -328,54 +364,79 @@ // include menu elements if (!includeMenu.isEmpty()) { - Iterator elementsIter = includeMenu.getElements().iterator(); + Iterator elementsIter = includeMenu + .getElements().iterator(); while (elementsIter.hasNext()) { - MenuElementImpl includeElement = (MenuElementImpl)elementsIter.next(); + MenuElementImpl includeElement = (MenuElementImpl) elementsIter + .next(); try { - // clone menu element and reparent - includeElement = (MenuElementImpl)includeElement.clone(); - includeElement.setParentMenu(this); - - // insert separators or options and menus + // clone menu element and + // reparent + includeElement = (MenuElementImpl) includeElement + .clone(); + includeElement + .setParentMenu(this); + + // insert separators or options + // and menus if (includeElement instanceof MenuSeparatorImpl) { - // append current separator and separated option/menu elements - if ((separatedElements != null) && !separatedElements.isEmpty()) + // append current separator + // and separated option/menu + // elements + if ((separatedElements != null) + && !separatedElements + .isEmpty()) { if (this.elements == null) { - int initialSize = separatedElements.size(); + int initialSize = separatedElements + .size(); if (separator != null) { initialSize++; } - this.elements = new ArrayList(initialSize); + this.elements = new ArrayList( + initialSize); } if (separator != null) { - this.elements.add(separator); + this.elements + .add(separator); } - this.elements.addAll(separatedElements); + this.elements + .addAll(separatedElements); } - // reset separator and separator option/menu elements list - // using separator menu element - separator = (MenuSeparatorImpl)includeElement; + // reset separator and + // separator option/menu + // elements list + // using separator menu + // element + separator = (MenuSeparatorImpl) includeElement; if (separatedElements != null) { - separatedElements.clear(); + separatedElements + .clear(); } } else { - // append menu element to current separated elements list + // append menu element to + // current separated + // elements list if (separatedElements == null) { - separatedElements = new ArrayList(includeMenu.getElements().size()); + separatedElements = new ArrayList( + includeMenu + .getElements() + .size()); } - appendMenuElement(includeElement, separatedElements); + appendMenuElement( + includeElement, + separatedElements); } } catch (CloneNotSupportedException cnse) @@ -385,20 +446,25 @@ } } - // set relative element flag if included menu is relative - this.elementRelative = (this.elementRelative || includeMenu.isElementRelative()); + // set relative element flag if included menu is + // relative + this.elementRelative = (this.elementRelative || includeMenu + .isElementRelative()); } } } else if (menuElement instanceof MenuExcludeDefinition) { // exclusion requires current separated elements - if ((separatedElements != null) && !separatedElements.isEmpty()) + if ((separatedElements != null) + && !separatedElements.isEmpty()) { // exclude top level referenced menu definition // options assuming reference to menu is not cyclic - MenuExcludeDefinition excludeDefinition = (MenuExcludeDefinition)menuElement; - if ((menus == null) || !menus.contains(excludeDefinition.getName())) + MenuExcludeDefinition excludeDefinition = (MenuExcludeDefinition) menuElement; + if ((menus == null) + || !menus.contains(excludeDefinition + .getName())) { // get named root menu from context, (menu may // not exist in this context so failure to @@ -406,7 +472,9 @@ MenuImpl excludeMenu = null; try { - excludeMenu = (MenuImpl)context.getMenu(excludeDefinition.getName()); + excludeMenu = (MenuImpl) context + .getMenu(excludeDefinition + .getName()); } catch (NodeNotFoundException nnfe) { @@ -416,12 +484,16 @@ } if (excludeMenu != null) { - // remove referenced menu options from current + // remove referenced menu options from + // current // separated elements list - removeMenuElements(excludeMenu.getElements(), separatedElements); + removeMenuElements(excludeMenu + .getElements(), separatedElements); - // set relative element flag if excluded menu is relative - this.elementRelative = (this.elementRelative || excludeMenu.isElementRelative()); + // set relative element flag if excluded + // menu is relative + this.elementRelative = (this.elementRelative || excludeMenu + .isElementRelative()); } } } @@ -465,24 +537,31 @@ /** * MenuImpl - request/session context dependent constructor - * - * @param definition menu definition - * @param context request context - * @param menus related menu definition names set + * + * @param definition + * menu definition + * @param context + * request context + * @param menus + * related menu definition names set */ - public MenuImpl(MenuDefinition definition, PortalSiteRequestContextImpl context, Set menus) + public MenuImpl(MenuDefinition definition, + PortalSiteRequestContextImpl context, Set menus) { this(null, definition, context, menus); } /** - * appendMenuElement - append to ordered list of unique menu - * option/menu elements + * appendMenuElement - append to ordered list of unique menu option/menu + * elements * - * @param appendMenuElement option/menu element to append - * @param menuElements option/menu element list + * @param appendMenuElement + * option/menu element to append + * @param menuElements + * option/menu element list */ - private void appendMenuElement(MenuElementImpl appendMenuElement, List menuElements) + private void appendMenuElement(MenuElementImpl appendMenuElement, + List menuElements) { // make sure new menu element is unique and // add to menu element list @@ -494,13 +573,15 @@ } } } - + /** - * appendMenuElements - append to ordered list of unique menu - * option/menu elements + * appendMenuElements - append to ordered list of unique menu option/menu + * elements * - * @param appendMenuElements option/menu element list to append - * @param menuElements option/menu element list + * @param appendMenuElements + * option/menu element list to append + * @param menuElements + * option/menu element list */ private void appendMenuElements(List appendMenuElements, List menuElements) { @@ -511,17 +592,20 @@ Iterator elementsIter = appendMenuElements.iterator(); while (elementsIter.hasNext()) { - appendMenuElement((MenuElementImpl)elementsIter.next(), menuElements); + appendMenuElement((MenuElementImpl) elementsIter.next(), + menuElements); } } } - + /** - * removeMenuElements - remove from ordered list of unique menu - * option/menu elements + * removeMenuElements - remove from ordered list of unique menu option/menu + * elements * - * @param removeMenuElements option/menu element list to remove - * @param menuElements option/menu element list + * @param removeMenuElements + * option/menu element list to remove + * @param menuElements + * option/menu element list */ private void removeMenuElements(List removeMenuElements, List menuElements) { @@ -535,22 +619,32 @@ /** * constructMenuElements - construct ordered list of menu elements in - * context/site view using specified element - * selection parameters; also sets up the - * elementRelative flag while constructing the - * menu elements + * context/site view using specified element selection parameters; also sets + * up the elementRelative flag while constructing the menu elements * - * @param context request context - * @param view context site view - * @param options option paths specification - * @param overrideElementProxies override menu element node proxies - * @param depth inclusion depth - * @param paths paths elements flag - * @param regexp regexp flag - * @param locatorName profile locator name - * @param order ordering patterns list + * @param context + * request context + * @param view + * context site view + * @param options + * option paths specification + * @param overrideElementProxies + * override menu element node proxies + * @param depth + * inclusion depth + * @param paths + * paths elements flag + * @param regexp + * regexp flag + * @param locatorName + * profile locator name + * @param order + * ordering patterns list */ - private List constructMenuElements(PortalSiteRequestContextImpl context, SiteView view, String options, List overrideElementProxies, int depth, boolean paths, boolean regexp, String locatorName, String order) + private List constructMenuElements(PortalSiteRequestContextImpl context, + SiteView view, String options, List overrideElementProxies, + int depth, boolean paths, boolean regexp, String locatorName, + String order) { if (options != null) { @@ -559,9 +653,10 @@ List elementProxies = overrideElementProxies; if (elementProxies == null) { - // split multiple comma separated option paths from specified options - String [] optionPaths = options.split(","); - + // split multiple comma separated option paths from specified + // options + String[] optionPaths = options.split(","); + // use regexp processing if specified or simple // path evaluation to retrieve list of proxies from // the site view for the specified options @@ -573,12 +668,15 @@ // get proxies/proxy for path if (regexp) { - // get list of visible proxies for path from view and append - // to list if unique and pass profile locator name filter + // get list of visible proxies for path from view + // and append + // to list if unique and pass profile locator name + // filter List pathProxies = null; try { - pathProxies = view.getNodeProxies(optionPath, context.getPage(), true, true); + pathProxies = view.getNodeProxies(optionPath, + context.getPage(), true, true); } catch (NodeNotFoundException nnfe) { @@ -588,30 +686,40 @@ } if (pathProxies != null) { - Iterator pathProxiesIter = pathProxies.iterator(); + Iterator pathProxiesIter = pathProxies + .iterator(); while (pathProxiesIter.hasNext()) { - Node pathProxy = (Node)pathProxiesIter.next(); - if ((locatorName == null) || locatorName.equals(MenuOptionsDefinition.ANY_PROFILE_LOCATOR) || - locatorName.equals(view.getProfileLocatorName(pathProxy))) + Node pathProxy = (Node) pathProxiesIter + .next(); + if ((locatorName == null) + || locatorName + .equals(MenuOptionsDefinition.ANY_PROFILE_LOCATOR) + || locatorName + .equals(view + .getProfileLocatorName(pathProxy))) { if (elementProxies == null) { elementProxies = new ArrayList(); } - appendMenuElementProxies(pathProxy, elementProxies); + appendMenuElementProxies(pathProxy, + elementProxies); } } } } else { - // get visible proxy for path from view and append to - // list if unique and pass profile locator name filter + // get visible proxy for path from view and append + // to + // list if unique and pass profile locator name + // filter Node pathProxy = null; try { - pathProxy = view.getNodeProxy(optionPath, context.getPage(), true, true); + pathProxy = view.getNodeProxy(optionPath, + context.getPage(), true, true); } catch (NodeNotFoundException nnfe) { @@ -619,43 +727,47 @@ catch (SecurityException se) { } - if ((pathProxy != null) && - ((locatorName == null) || locatorName.equals(MenuOptionsDefinition.ANY_PROFILE_LOCATOR) || - locatorName.equals(view.getProfileLocatorName(pathProxy)))) + if ((pathProxy != null) + && ((locatorName == null) + || locatorName + .equals(MenuOptionsDefinition.ANY_PROFILE_LOCATOR) || locatorName + .equals(view + .getProfileLocatorName(pathProxy)))) { if (elementProxies == null) { elementProxies = new ArrayList(); } - appendMenuElementProxies(pathProxy, elementProxies); + appendMenuElementProxies(pathProxy, + elementProxies); } } // set relative element flag if path is relative - elementRelative = (elementRelative || !optionPath.startsWith(Folder.PATH_SEPARATOR)); + elementRelative = (elementRelative || !optionPath + .startsWith(Folder.PATH_SEPARATOR)); } } // return if no proxies available - if (elementProxies == null) - { - return null; - } + if (elementProxies == null) { return null; } } - + // sort elements proxies using url and/or names if order // specified and more than one element proxy in list if ((order != null) && (elementProxies.size() > 1)) { // create ordered element proxies - List orderedElementProxies = new ArrayList(elementProxies.size()); - + List orderedElementProxies = new ArrayList(elementProxies + .size()); + // split multiple comma separated elements orderings // after converted to regexp pattern - String [] orderings = orderRegexpPattern(order).split(","); - + String[] orderings = orderRegexpPattern(order).split(","); + // copy ordered proxies per ordering - for (int i=0; ((i < orderings.length) && (elementProxies.size() > 1)); i++) + for (int i = 0; ((i < orderings.length) && (elementProxies + .size() > 1)); i++) { String ordering = orderings[i].trim(); if (ordering.length() > 0) @@ -663,15 +775,16 @@ // get ordering pattern and matcher Pattern pattern = Pattern.compile(ordering); Matcher matcher = null; - + // use regular expression to match urls or names of // element proxies; matched proxies are removed and // placed in the ordered elements proxies list Iterator elementProxiesIter = elementProxies.iterator(); while (elementProxiesIter.hasNext()) { - Node elementProxy = (Node)elementProxiesIter.next(); - + Node elementProxy = (Node) elementProxiesIter + .next(); + // get url or name to test ordering match against String test = null; if (ordering.charAt(0) == Folder.PATH_SEPARATOR_CHAR) @@ -682,7 +795,7 @@ { test = elementProxy.getName(); } - + // construct or reset ordering matcher if (matcher == null) { @@ -692,7 +805,7 @@ { matcher.reset(test); } - + // move proxy to ordered list if matched if (matcher.matches()) { @@ -702,52 +815,62 @@ } } } - + // copy remaining unordered proxies orderedElementProxies.addAll(elementProxies); - + // replace element proxies with ordered list elementProxies = orderedElementProxies; } - + // expand paths if single page or folder element proxy // has been specified in elements with no depth expansion - if (paths && (depth == 0) && (elementProxies.size() == 1) && - ((elementProxies.get(0) instanceof Folder) || (elementProxies.get(0) instanceof Page))) + if (paths + && (depth == 0) + && (elementProxies.size() == 1) + && ((elementProxies.get(0) instanceof Folder) || (elementProxies + .get(0) instanceof Page))) { - Node parentNode = ((Node)elementProxies.get(0)).getParent(); + Node parentNode = ((Node) elementProxies.get(0)).getParent(); while (parentNode != null) { elementProxies.add(0, parentNode); parentNode = parentNode.getParent(); } } - + // convert elements proxies into menu elements DefaultMenuOptionsDefinition defaultMenuOptionsDefinition = null; ListIterator elementProxiesIter = elementProxies.listIterator(); while (elementProxiesIter.hasNext()) { - Node elementProxy = (Node)elementProxiesIter.next(); + Node elementProxy = (Node) elementProxiesIter.next(); MenuElement menuElement = null; // convert folders into nested menus if depth specified // with no paths expansion, (negative depth values are // interpreted as complete menu expansion) - if ((elementProxy instanceof Folder) && ((depth < 0) || (depth > 1)) && !paths) + if ((elementProxy instanceof Folder) + && ((depth < 0) || (depth > 1)) && !paths) { // construct menu definition and associated menu - MenuDefinition nestedMenuDefinition = new DefaultMenuDefinition(elementProxy.getUrl(), depth - 1, locatorName); - menuElement = new MenuImpl(this, nestedMenuDefinition, context, null); + MenuDefinition nestedMenuDefinition = new DefaultMenuDefinition( + elementProxy.getUrl(), depth - 1, locatorName); + menuElement = new MenuImpl(this, nestedMenuDefinition, + context, null); } else { - // construct shared default menu option definition and menu option + // construct shared default menu option definition and menu + // option if (defaultMenuOptionsDefinition == null) { - defaultMenuOptionsDefinition = new DefaultMenuOptionsDefinition(options, depth, paths, regexp, locatorName, order); + defaultMenuOptionsDefinition = new DefaultMenuOptionsDefinition( + options, depth, paths, regexp, locatorName, + order); } - menuElement = new MenuOptionImpl(this, elementProxy, defaultMenuOptionsDefinition); + menuElement = new MenuOptionImpl(this, elementProxy, + defaultMenuOptionsDefinition); } // replace element proxy with menu element @@ -764,11 +887,13 @@ } /** - * appendMenuElementProxies - append to ordered list of unique menu - * element proxies + * appendMenuElementProxies - append to ordered list of unique menu element + * proxies * - * @param pathProxy menu element page, folder, or link proxy at path - * @param elementProxies element proxies list + * @param pathProxy + * menu element page, folder, or link proxy at path + * @param elementProxies + * element proxies list */ private void appendMenuElementProxies(Node pathProxy, List elementProxies) { @@ -779,16 +904,16 @@ elementProxies.add(pathProxy); } } - + /** * clone - clone this instance - * + * * @return unparented deep copy */ public Object clone() throws CloneNotSupportedException { // clone this object - MenuImpl copy = (MenuImpl)super.clone(); + MenuImpl copy = (MenuImpl) super.clone(); // clone and reparent copy elements if (copy.elements != null) @@ -797,7 +922,8 @@ copy.elements = new ArrayList(copy.elements.size()); while (elementsIter.hasNext()) { - MenuElementImpl elementCopy = (MenuElementImpl)((MenuElementImpl)elementsIter.next()).clone(); + MenuElementImpl elementCopy = (MenuElementImpl) ((MenuElementImpl) elementsIter + .next()).clone(); elementCopy.setParentMenu(copy); copy.elements.add(elementCopy); } @@ -807,7 +933,7 @@ /** * getElementType - get type of menu element - * + * * @return MENU_ELEMENT_TYPE */ public String getElementType() @@ -817,7 +943,7 @@ /** * getName - get name of menu - * + * * @return menu name */ public String getName() @@ -827,74 +953,63 @@ /** * getTitle - get default title for menu element - * + * * @return title text */ public String getTitle() { // return definition title String title = definition.getTitle(); - if (title != null) - { - return title; - } + if (title != null) { return title; } // return node or default title return super.getTitle(); } /** * getShortTitle - get default short title for menu element - * + * * @return short title text */ public String getShortTitle() { // return definition short title String title = definition.getShortTitle(); - if (title != null) - { - return title; - } + if (title != null) { return title; } // return node or default short title return super.getShortTitle(); } /** - * getTitle - get locale specific title for menu element - * from metadata - * - * @param locale preferred locale + * getTitle - get locale specific title for menu element from metadata + * + * @param locale + * preferred locale * @return title text */ public String getTitle(Locale locale) { // return definition short title for preferred locale String title = definition.getTitle(locale); - if (title != null) - { - return title; - } + if (title != null) { return title; } // return node or default title for preferred locale return super.getTitle(locale); } /** - * getShortTitle - get locale specific short title for menu - * element from metadata - * - * @param locale preferred locale + * getShortTitle - get locale specific short title for menu element from + * metadata + * + * @param locale + * preferred locale * @return short title text */ public String getShortTitle(Locale locale) { // return definition short title for preferred locale String title = definition.getShortTitle(locale); - if (title != null) - { - return title; - } + if (title != null) { return title; } // return node or default short title for preferred locale return super.getShortTitle(locale); @@ -902,17 +1017,15 @@ /** * getMetadata - get generic metadata for menu element - * + * * @return metadata - */ + */ public GenericMetadata getMetadata() { // return definition metadata GenericMetadata metadata = definition.getMetadata(); - if ((metadata != null) && (metadata.getFields() != null) && !metadata.getFields().isEmpty()) - { - return metadata; - } + if ((metadata != null) && (metadata.getFields() != null) + && !metadata.getFields().isEmpty()) { return metadata; } // return node metadata return super.getMetadata(); @@ -920,7 +1033,7 @@ /** * getSkin - get skin name for menu element - * + * * @return skin name */ public String getSkin() @@ -935,49 +1048,41 @@ } /** - * getUrl - get url of top level folder that defined - * menu options; only available for menus - * defined without multiple options, nested - * menus, or separators - * + * getUrl - get url of top level folder that defined menu options; only + * available for menus defined without multiple options, nested menus, or + * separators + * * @return folder url */ public String getUrl() { // return url of node associated with menu // option if defined - if (getNode() != null) - { - return getNode().getUrl(); - } + if (getNode() != null) { return getNode().getUrl(); } return null; } /** - * isHidden - get hidden state of folder that defined - * menu options; only available for menus - * defined without multiple options, nested - * menus, or separators - * + * isHidden - get hidden state of folder that defined menu options; only + * available for menus defined without multiple options, nested menus, or + * separators + * * @return hidden state */ public boolean isHidden() { // return hidden state of node associated with // menu option if defined - if (getNode() != null) - { - return getNode().isHidden(); - } + if (getNode() != null) { return getNode().isHidden(); } return false; } /** - * isSelected - return true if an option or nested - * menu within this menu are selected by - * the specified request context - * - * @param context request context + * isSelected - return true if an option or nested menu within this menu are + * selected by the specified request context + * + * @param context + * request context * @return selected state */ public boolean isSelected(PortalSiteRequestContext context) @@ -987,10 +1092,9 @@ } /** - * getElements - get ordered list of menu elements that - * are members of this menu; possibly contains - * options, nested menus, or separators - * + * getElements - get ordered list of menu elements that are members of this + * menu; possibly contains options, nested menus, or separators + * * @return menu elements list */ public List getElements() @@ -1000,7 +1104,7 @@ /** * isEmpty - get empty state of list of menu elements - * + * * @return menu elements list empty state */ public boolean isEmpty() @@ -1010,9 +1114,9 @@ /** * isElementRelative - get flag that indicates whether any relative paths - * dependent on the current page in context were - * referenced while constructing menu elements - * + * dependent on the current page in context were referenced while + * constructing menu elements + * * @return relative element status */ public boolean isElementRelative() @@ -1021,10 +1125,9 @@ } /** - * getSelectedElement - return selected option or nested - * menu within this menu selected by - * the specified request context - * + * getSelectedElement - return selected option or nested menu within this + * menu selected by the specified request context + * * @return selected menu element */ public MenuElement getSelectedElement(PortalSiteRequestContext context) @@ -1036,35 +1139,32 @@ Iterator elementsIter = elements.iterator(); while (elementsIter.hasNext()) { - MenuElement element = (MenuElement)elementsIter.next(); - + MenuElement element = (MenuElement) elementsIter.next(); + // test element selected boolean selected = false; if (element instanceof MenuOption) { - selected = ((MenuOption)element).isSelected(context); + selected = ((MenuOption) element).isSelected(context); } else if (element instanceof Menu) { - selected = ((Menu)element).isSelected(context); + selected = ((Menu) element).isSelected(context); } - + // return selected element - if (selected) - { - return element; - } + if (selected) { return element; } } } return null; } /** - * orderRegexpPattern - tests for and converts simple order wildcard - * and character class regular exressions to - * perl5/standard java pattern syntax - * - * @param regexp - candidate order regular expression + * orderRegexpPattern - tests for and converts simple order wildcard and + * character class regular exressions to perl5/standard java pattern syntax + * + * @param regexp - + * candidate order regular expression * @return - converted pattern */ private static String orderRegexpPattern(String regexp) @@ -1076,43 +1176,42 @@ char regexpChar = regexp.charAt(i); switch (regexpChar) { + case '*': + case '.': + case '?': + case '[': + if (pattern == null) + { + pattern = new StringBuffer(regexp.length() * 2); + pattern.append(regexp.substring(0, i)); + } + switch (regexpChar) + { case '*': + pattern.append("[^" + Folder.PATH_SEPARATOR + "]*"); + break; case '.': + pattern.append("\\."); + break; case '?': + pattern.append("[^" + Folder.PATH_SEPARATOR + "]"); + break; case '[': - if (pattern == null) - { - pattern = new StringBuffer(regexp.length()*2); - pattern.append(regexp.substring(0, i)); - } - switch (regexpChar) - { - case '*': - pattern.append("[^"+Folder.PATH_SEPARATOR+"]*"); - break; - case '.': - pattern.append("\\."); - break; - case '?': - pattern.append("[^"+Folder.PATH_SEPARATOR+"]"); - break; - case '[': - pattern.append('['); - break; - } + pattern.append('['); break; - default: - if (pattern != null) - { - pattern.append(regexpChar); - } - break; + } + break; + default: + if (pattern != null) + { + pattern.append(regexpChar); + } + break; } } // return converted pattern - if (pattern != null) - return pattern.toString(); + if (pattern != null) return pattern.toString(); return regexp; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuOptionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuOptionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuOptionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,14 +26,16 @@ import org.apache.jetspeed.portalsite.PortalSiteRequestContext; /** - * This class implements the portal-site menu option - * elements constructed and returned to decorators. + * This class implements the portal-site menu option elements constructed and + * returned to decorators. * * @author Randy Watler * @version $Id: MenuOptionImpl.java 537314 2007-05-11 23:08:36Z taylor $ */ -public class MenuOptionImpl extends MenuElementImpl implements MenuOption, Cloneable +public class MenuOptionImpl extends MenuElementImpl implements MenuOption, + Cloneable { + /** * definition - menu option definition */ @@ -41,12 +43,16 @@ /** * MenuOptionImpl - constructor - * - * @param parent containing menu implementation - * @param node menu option node proxy - * @param definition menu option definition + * + * @param parent + * containing menu implementation + * @param node + * menu option node proxy + * @param definition + * menu option definition */ - public MenuOptionImpl(MenuImpl parent, Node node, MenuOptionsDefinition definition) + public MenuOptionImpl(MenuImpl parent, Node node, + MenuOptionsDefinition definition) { super(parent, node); this.definition = definition; @@ -54,7 +60,7 @@ /** * getElementType - get type of menu element - * + * * @return OPTION_ELEMENT_TYPE */ public String getElementType() @@ -64,9 +70,8 @@ /** * getType - get type of menu option - * - * @return FOLDER_OPTION_TYPE, PAGE_OPTION_TYPE, or - * LINK_OPTION_TYPE + * + * @return FOLDER_OPTION_TYPE, PAGE_OPTION_TYPE, or LINK_OPTION_TYPE */ public String getType() { @@ -80,16 +85,13 @@ { return LINK_OPTION_TYPE; } - else if (node instanceof Folder) - { - return FOLDER_OPTION_TYPE; - } + else if (node instanceof Folder) { return FOLDER_OPTION_TYPE; } return null; } /** * getSkin - get skin name for menu element - * + * * @return skin name */ public String getSkin() @@ -102,15 +104,15 @@ Node node = getNode(); if (node instanceof Page) { - skin = ((Page)node).getSkin(); + skin = ((Page) node).getSkin(); } else if (node instanceof Link) { - skin = ((Link)node).getSkin(); + skin = ((Link) node).getSkin(); } else if (node instanceof Folder) { - skin = ((Folder)node).getSkin(); + skin = ((Folder) node).getSkin(); } } if (skin == null) @@ -122,7 +124,7 @@ /** * getUrl - get url of menu option - * + * * @return folder, page, or link url */ public String getUrl() @@ -132,39 +134,33 @@ /** * getTarget - get target for url of menu option - * + * * @return url target */ public String getTarget() { // only link nodes support target Node node = getNode(); - if (node instanceof Link) - { - return ((Link)node).getTarget(); - } + if (node instanceof Link) { return ((Link) node).getTarget(); } return null; } /** * getDefaultPage - get default page for a folder (if folder) of menu option - * + * * @return url target */ public String getDefaultPage() { // only link nodes support target Node node = getNode(); - if (node instanceof Folder) - { - return ((Folder)node).getDefaultPage(); - } + if (node instanceof Folder) { return ((Folder) node).getDefaultPage(); } return null; } - + /** * isHidden - get hidden state of menu option - * + * * @return hidden state */ public boolean isHidden() @@ -173,10 +169,11 @@ } /** - * isSelected - return true if menu option is selected by - * the specified request context - * - * @param context request context + * isSelected - return true if menu option is selected by the specified + * request context + * + * @param context + * request context * @return selected state */ public boolean isSelected(PortalSiteRequestContext context) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuSeparatorImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuSeparatorImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/MenuSeparatorImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,14 +23,16 @@ import org.apache.jetspeed.portalsite.MenuSeparator; /** - * This class implements the portal-site menu separator - * elements constructed and returned to decorators. + * This class implements the portal-site menu separator elements constructed and + * returned to decorators. * * @author Randy Watler * @version $Id: MenuSeparatorImpl.java 516448 2007-03-09 16:25:47Z ate $ */ -public class MenuSeparatorImpl extends MenuElementImpl implements MenuSeparator, Cloneable +public class MenuSeparatorImpl extends MenuElementImpl implements + MenuSeparator, Cloneable { + /** * definition - menu separator definition */ @@ -38,9 +40,11 @@ /** * MenuSeparatorImpl - constructor - * - * @param parent containing menu implementation - * @param definition menu separator definition + * + * @param parent + * containing menu implementation + * @param definition + * menu separator definition */ public MenuSeparatorImpl(MenuImpl parent, MenuSeparatorDefinition definition) { @@ -50,7 +54,7 @@ /** * getElementType - get type of menu element - * + * * @return SEPARATOR_ELEMENT_TYPE */ public String getElementType() @@ -60,17 +64,14 @@ /** * getTitle - get default title for menu element - * + * * @return title text */ public String getTitle() { // return definition title String title = definition.getTitle(); - if (title != null) - { - return title; - } + if (title != null) { return title; } // return node or default title return super.getTitle(); @@ -78,7 +79,7 @@ /** * getText - get default text for menu separator - * + * * @return text */ public String getText() @@ -88,30 +89,27 @@ } /** - * getTitle - get locale specific title for menu element - * from metadata - * - * @param locale preferred locale + * getTitle - get locale specific title for menu element from metadata + * + * @param locale + * preferred locale * @return title text */ public String getTitle(Locale locale) { // return definition short title for preferred locale String title = definition.getTitle(locale); - if (title != null) - { - return title; - } + if (title != null) { return title; } // return node or default title for preferred locale return super.getTitle(locale); } /** - * getText - get locale specific text for menu separator - * from metadata - * - * @param locale preferred locale + * getText - get locale specific text for menu separator from metadata + * + * @param locale + * preferred locale * @return text */ public String getText(Locale locale) @@ -122,17 +120,15 @@ /** * getMetadata - get generic metadata for menu element - * + * * @return metadata - */ + */ public GenericMetadata getMetadata() { // return definition metadata GenericMetadata metadata = definition.getMetadata(); - if ((metadata != null) && (metadata.getFields() != null) && !metadata.getFields().isEmpty()) - { - return metadata; - } + if ((metadata != null) && (metadata.getFields() != null) + && !metadata.getFields().isEmpty()) { return metadata; } // return node metadata return super.getMetadata(); @@ -140,7 +136,7 @@ /** * getSkin - get skin name for menu element - * + * * @return skin name */ public String getSkin() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/PortalSiteImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/PortalSiteImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/PortalSiteImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,6 +28,7 @@ */ public class PortalSiteImpl implements PortalSite { + /** * pageManager - PageManager component */ @@ -35,8 +36,9 @@ /** * PortalSiteImpl - component constructor - * - * @param pageManager PageManager component instance + * + * @param pageManager + * PageManager component instance */ public PortalSiteImpl(PageManager pageManager) { @@ -45,7 +47,7 @@ /** * newSessionContext - create a new session context instance - * + * * @return new session context instance */ public PortalSiteSessionContext newSessionContext() @@ -55,7 +57,7 @@ /** * getPageManager - return PageManager component instance - * + * * @return PageManager instance */ public PageManager getPageManager() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/PortalSiteRequestContextImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/PortalSiteRequestContextImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/PortalSiteRequestContextImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,13 +17,13 @@ package org.apache.jetspeed.portalsite.impl; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.Collections; import org.apache.jetspeed.om.folder.Folder; import org.apache.jetspeed.om.page.Page; @@ -38,14 +38,16 @@ import org.apache.jetspeed.portalsite.view.SiteViewMenuDefinitionLocator; /** - * This class encapsulates managed request state for and - * interface to the portal-site component. + * This class encapsulates managed request state for and interface to the + * portal-site component. * * @author Randy Watler - * @version $Id: PortalSiteRequestContextImpl.java 517121 2007-03-12 07:45:49Z ate $ + * @version $Id: PortalSiteRequestContextImpl.java 517121 2007-03-12 07:45:49Z + * ate $ */ public class PortalSiteRequestContextImpl implements PortalSiteRequestContext { + /** * sessionContext - component session state/interface */ @@ -57,14 +59,14 @@ private Map requestProfileLocators; /** - * requestFallback - flag indicating whether request should fallback to root folder - * if locators do not select a page or access is forbidden + * requestFallback - flag indicating whether request should fallback to root + * folder if locators do not select a page or access is forbidden */ private boolean requestFallback; /** - * useHistory - flag indicating whether to use visited page - * history to select default page per site folder + * useHistory - flag indicating whether to use visited page history to + * select default page per site folder */ private boolean useHistory; @@ -114,23 +116,29 @@ private Set pageMenuDefinitionNames; /** - * menuDefinitionLocatorCache - cached menu definition locators for - * relative menus valid for request + * menuDefinitionLocatorCache - cached menu definition locators for relative + * menus valid for request */ private Map menuDefinitionLocatorCache; /** * PortalSiteRequestContextImpl - constructor - * - * @param sessionContext session context - * @param requestProfileLocators request profile locators - * @param requestFallback flag specifying whether to fallback to root folder - * if locators do not select a page or access is forbidden - * @param useHistory flag indicating whether to use visited page - * history to select default page per site folder + * + * @param sessionContext + * session context + * @param requestProfileLocators + * request profile locators + * @param requestFallback + * flag specifying whether to fallback to root folder if locators + * do not select a page or access is forbidden + * @param useHistory + * flag indicating whether to use visited page history to select + * default page per site folder */ - public PortalSiteRequestContextImpl(PortalSiteSessionContextImpl sessionContext, Map requestProfileLocators, - boolean requestFallback, boolean useHistory) + public PortalSiteRequestContextImpl( + PortalSiteSessionContextImpl sessionContext, + Map requestProfileLocators, boolean requestFallback, + boolean useHistory) { this.sessionContext = sessionContext; this.requestProfileLocators = requestProfileLocators; @@ -140,32 +148,40 @@ /** * PortalSiteRequestContextImpl - constructor - * - * @param sessionContext session context - * @param requestProfileLocators request profile locators - * @param requestFallback flag specifying whether to fallback to root folder - * if locators do not select a page or access is forbidden + * + * @param sessionContext + * session context + * @param requestProfileLocators + * request profile locators + * @param requestFallback + * flag specifying whether to fallback to root folder if locators + * do not select a page or access is forbidden */ - public PortalSiteRequestContextImpl(PortalSiteSessionContextImpl sessionContext, Map requestProfileLocators, - boolean requestFallback) + public PortalSiteRequestContextImpl( + PortalSiteSessionContextImpl sessionContext, + Map requestProfileLocators, boolean requestFallback) { this(sessionContext, requestProfileLocators, requestFallback, true); } /** * PortalSiteRequestContextImpl - constructor - * - * @param sessionContext session context - * @param requestProfileLocators request profile locators + * + * @param sessionContext + * session context + * @param requestProfileLocators + * request profile locators */ - public PortalSiteRequestContextImpl(PortalSiteSessionContextImpl sessionContext, Map requestProfileLocators) + public PortalSiteRequestContextImpl( + PortalSiteSessionContextImpl sessionContext, + Map requestProfileLocators) { this(sessionContext, requestProfileLocators, true, true); } /** * getSessionContext - get component session context - * + * * @return component session context */ public PortalSiteSessionContext getSessionContext() @@ -175,7 +191,7 @@ /** * getLocators - get profile locators by locator names - * + * * @return request profile locators */ public Map getLocators() @@ -184,24 +200,28 @@ } /** - * getManagedPage - get request profiled concrete page instance - * as managed by the page manager - * + * getManagedPage - get request profiled concrete page instance as managed + * by the page manager + * * @return managed page - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ public Page getManagedPage() throws NodeNotFoundException { - return sessionContext.getManagedPage(getPage()); + return sessionContext.getManagedPage(getPage()); } /** * getPage - get request profiled page proxy - * + * * @return page proxy - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ public Page getPage() throws NodeNotFoundException { @@ -210,37 +230,38 @@ // cached in this context if (requestPage == null) { - requestPage = sessionContext.selectRequestPage(requestProfileLocators, requestFallback, useHistory); + requestPage = sessionContext.selectRequestPage( + requestProfileLocators, requestFallback, useHistory); } return requestPage; } /** * getFolder - get folder proxy relative to request profiled page - * + * * @return page folder proxy - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ public Folder getFolder() throws NodeNotFoundException { // return parent folder of request page Page page = getPage(); - if (page != null) - { - return (Folder)page.getParent(); - } + if (page != null) { return (Folder) page.getParent(); } return null; } /** - * getSiblingPages - get node set of sibling page proxies relative - * to request profiled page, (includes profiled - * page proxy) - * + * getSiblingPages - get node set of sibling page proxies relative to + * request profiled page, (includes profiled page proxy) + * * @return sibling page proxies - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ public NodeSet getSiblingPages() throws NodeNotFoundException { @@ -259,7 +280,8 @@ } catch (NodeException ne) { - NodeNotFoundException nnfe = new NodeNotFoundException("Sibling pages not found."); + NodeNotFoundException nnfe = new NodeNotFoundException( + "Sibling pages not found."); nnfe.initCause(ne); throw nnfe; } @@ -269,12 +291,14 @@ } /** - * getParentFolder - get parent folder proxy relative to request - * profiled page - * + * getParentFolder - get parent folder proxy relative to request profiled + * page + * * @return parent folder proxy or null - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ public Folder getParentFolder() throws NodeNotFoundException { @@ -283,23 +307,21 @@ if (folder != null) { // access, filter hidden, and return - Folder parent = (Folder)folder.getParent(); - if ((parent != null) && !parent.isHidden()) - { - return parent; - } + Folder parent = (Folder) folder.getParent(); + if ((parent != null) && !parent.isHidden()) { return parent; } } return null; } /** - * getSiblingFolders - get node set of sibling folder proxies relative - * to request profiled page, (includes profiled - * page folder proxy) - * + * getSiblingFolders - get node set of sibling folder proxies relative to + * request profiled page, (includes profiled page folder proxy) + * * @return sibling folder proxies - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ public NodeSet getSiblingFolders() throws NodeNotFoundException { @@ -318,7 +340,8 @@ } catch (NodeException ne) { - NodeNotFoundException nnfe = new NodeNotFoundException("Sibling folders not found."); + NodeNotFoundException nnfe = new NodeNotFoundException( + "Sibling folders not found."); nnfe.initCause(ne); throw nnfe; } @@ -329,10 +352,12 @@ /** * getRootFolder - get root profiled folder proxy - * + * * @return parent folder proxy - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ public Folder getRootFolder() throws NodeNotFoundException { @@ -341,18 +366,21 @@ // cached in this context if (requestRootFolder == null) { - requestRootFolder = sessionContext.getRequestRootFolder(requestProfileLocators); + requestRootFolder = sessionContext + .getRequestRootFolder(requestProfileLocators); } return requestRootFolder; } /** - * getRootLinks - get node set of link proxies relative to - * profiled root folder - * + * getRootLinks - get node set of link proxies relative to profiled root + * folder + * * @return root link proxies - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ public NodeSet getRootLinks() throws NodeNotFoundException { @@ -371,7 +399,8 @@ } catch (NodeException ne) { - NodeNotFoundException nnfe = new NodeNotFoundException("Root links not found."); + NodeNotFoundException nnfe = new NodeNotFoundException( + "Root links not found."); nnfe.initCause(ne); throw nnfe; } @@ -382,7 +411,7 @@ /** * getStandardMenuNames - get set of available standard menu names - * + * * @return menu names set */ public Set getStandardMenuNames() @@ -392,12 +421,14 @@ } /** - * getCustomMenuNames - get set of custom menu names available as - * defined for the request profiled page and folder - * + * getCustomMenuNames - get set of custom menu names available as defined + * for the request profiled page and folder + * * @return menu names set - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ public Set getCustomMenuNames() throws NodeNotFoundException { @@ -408,18 +439,21 @@ // current request page if not previously cached // in this context Set standardMenuNames = sessionContext.getStandardMenuNames(); - if ((page != null) && (standardMenuNames != null) && (pageMenuDefinitionNames == null)) + if ((page != null) && (standardMenuNames != null) + && (pageMenuDefinitionNames == null)) { List locators = sessionContext.getMenuDefinitionLocators(page); if (locators != null) { // get custom definition names - pageMenuDefinitionNames = Collections.synchronizedSet(new HashSet(locators.size())); + pageMenuDefinitionNames = Collections + .synchronizedSet(new HashSet(locators.size())); Iterator locatorsIter = locators.iterator(); while (locatorsIter.hasNext()) { // get definition name; filter standard menu names - String definitionName = ((SiteViewMenuDefinitionLocator)locatorsIter.next()).getName(); + String definitionName = ((SiteViewMenuDefinitionLocator) locatorsIter + .next()).getName(); if (!standardMenuNames.contains(definitionName)) { pageMenuDefinitionNames.add(definitionName); @@ -428,20 +462,24 @@ } else { - pageMenuDefinitionNames = Collections.synchronizedSet(new HashSet(0)); + pageMenuDefinitionNames = Collections + .synchronizedSet(new HashSet(0)); } } return pageMenuDefinitionNames; } /** - * getMenu - get instantiated menu available for the request - * profiled page and folder - * - * @param name menu definition name + * getMenu - get instantiated menu available for the request profiled page + * and folder + * + * @param name + * menu definition name * @return menu instance - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ public Menu getMenu(String name) throws NodeNotFoundException { @@ -451,16 +489,19 @@ } /** - * getMenu - get instantiated menu available for the request - * profiled page and folder, avoiding cyclic - * menu definition loops by propagating related menu - * names set from menu construction - * - * @param name menu definition name - * @param names set of related menu definition names + * getMenu - get instantiated menu available for the request profiled page + * and folder, avoiding cyclic menu definition loops by propagating related + * menu names set from menu construction + * + * @param name + * menu definition name + * @param names + * set of related menu definition names * @return menu instance - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ public Menu getMenu(String name, Set names) throws NodeNotFoundException { @@ -469,17 +510,16 @@ if ((page != null) && (name != null)) { // get menu definition locator - SiteViewMenuDefinitionLocator locator = sessionContext.getMenuDefinitionLocator(page, name); + SiteViewMenuDefinitionLocator locator = sessionContext + .getMenuDefinitionLocator(page, name); if (locator != null) { // lookup and return cached relative/request menus if (menuDefinitionLocatorCache != null) { - MenuImpl menu = (MenuImpl)menuDefinitionLocatorCache.get(locator); - if (menu != null) - { - return menu; - } + MenuImpl menu = (MenuImpl) menuDefinitionLocatorCache + .get(locator); + if (menu != null) { return menu; } } // lookup and return cached absolute/session menus @@ -489,18 +529,17 @@ // menus for display purposes if (sessionContext.getMenuDefinitionLocatorCache() != null) { - MenuImpl menu = (MenuImpl)sessionContext.getMenuDefinitionLocatorCache().get(locator); - if (menu != null) - { - return menu; - } + MenuImpl menu = (MenuImpl) sessionContext + .getMenuDefinitionLocatorCache().get(locator); + if (menu != null) { return menu; } } // construct new menu from menu definition in locator // using current request context and propagating related // names set to detect cyclic menu definitions - MenuImpl menu = new MenuImpl(locator.getMenuDefinition(), this, names); - + MenuImpl menu = new MenuImpl(locator.getMenuDefinition(), this, + names); + // determine whether menu definition locator is // relative/request, based on hidden page, or // absolute/session cachable and cache accordingly @@ -509,7 +548,8 @@ // cache relative menu for request if (menuDefinitionLocatorCache == null) { - menuDefinitionLocatorCache = Collections.synchronizedMap(new HashMap(8)); + menuDefinitionLocatorCache = Collections + .synchronizedMap(new HashMap(8)); } menuDefinitionLocatorCache.put(locator, menu); } @@ -518,9 +558,12 @@ // cache absolute menu for session if (sessionContext.getMenuDefinitionLocatorCache() == null) { - sessionContext.setMenuDefinitionLocatorCache(Collections.synchronizedMap(new HashMap(8))); + sessionContext + .setMenuDefinitionLocatorCache(Collections + .synchronizedMap(new HashMap(8))); } - sessionContext.getMenuDefinitionLocatorCache().put(locator, menu); + sessionContext.getMenuDefinitionLocatorCache().put(locator, + menu); } // return new cached menu @@ -531,9 +574,11 @@ } /** - * filterHiddenNodes - utility to filter hidden node proxies out of node sets - * - * @param nodes proxy node set to filter + * filterHiddenNodes - utility to filter hidden node proxies out of node + * sets + * + * @param nodes + * proxy node set to filter * @return input or filtered proxy node set */ private static NodeSet filterHiddenNodes(NodeSet nodes) @@ -546,7 +591,7 @@ while (nodesIter.hasNext()) { // test hidden status of individual node proxies - Node node = (Node)nodesIter.next(); + Node node = (Node) nodesIter.next(); if (node.isHidden()) { // if not copying, create new node set @@ -557,7 +602,7 @@ Iterator copyIter = nodes.iterator(); while (copyIter.hasNext()) { - Node copyNode = (Node)copyIter.next(); + Node copyNode = (Node) copyIter.next(); if (copyNode != node) { filteredNodes.add(copyNode); @@ -578,10 +623,7 @@ // return filteredNodes node proxies if generated // in new immutable proxy node set - if (filteredNodes != null) - { - return new NodeSetImpl(filteredNodes); - } + if (filteredNodes != null) { return new NodeSetImpl(filteredNodes); } } return nodes; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/PortalSiteSessionContextImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/PortalSiteSessionContextImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/impl/PortalSiteSessionContextImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -51,33 +51,36 @@ import org.apache.jetspeed.security.UserPrincipal; /** - * This class encapsulates managed session state for and - * interface to the portal-site component and subscribes - * to page manager and session events to flush stale state. - * - * Note that is object is Serializable since it is designed - * to be cached in the session. However, because this object - * is cached only for these two reasons: - * - * 1. a performance optimization to reuse SiteViews, and - * 2. to hold optional folder page history, - * - * this object need not be relocatable between J2 instances. - * Consequently, all data members are marked transient and - * the isValid() method is used to test whether this object - * is a valid context for the session or if it was - * transferred from another server or the persistent session - * store and needs to be discarded. + * This class encapsulates managed session state for and interface to the + * portal-site component and subscribes to page manager and session events to + * flush stale state. * + * Note that is object is Serializable since it is designed to be cached in the + * session. However, because this object is cached only for these two reasons: + * + * 1. a performance optimization to reuse SiteViews, and 2. to hold optional + * folder page history, + * + * this object need not be relocatable between J2 instances. Consequently, all + * data members are marked transient and the isValid() method is used to test + * whether this object is a valid context for the session or if it was + * transferred from another server or the persistent session store and needs to + * be discarded. + * * @author Randy Watler - * @version $Id: PortalSiteSessionContextImpl.java 553375 2007-07-05 05:37:00Z taylor $ + * @version $Id: PortalSiteSessionContextImpl.java 553375 2007-07-05 05:37:00Z + * taylor $ */ -public class PortalSiteSessionContextImpl implements PortalSiteSessionContext, PageManagerEventListener, HttpSessionActivationListener, HttpSessionBindingListener, Serializable +public class PortalSiteSessionContextImpl implements PortalSiteSessionContext, + PageManagerEventListener, HttpSessionActivationListener, + HttpSessionBindingListener, Serializable { + /** * log - logging instance */ - private final static Log log = LogFactory.getLog(PortalSiteSessionContextImpl.class); + private final static Log log = LogFactory + .getLog(PortalSiteSessionContextImpl.class); /** * pageManager - PageManager component @@ -100,25 +103,25 @@ private transient SiteView siteView; /** - * folderPageHistory - map of last page visited by folder + * folderPageHistory - map of last page visited by folder */ private transient Map folderPageHistory; /** - * menuDefinitionLocatorCache - cached menu definition locators for - * absolute menus valid for session + * menuDefinitionLocatorCache - cached menu definition locators for absolute + * menus valid for session */ private transient Map menuDefinitionLocatorCache; /** - * subscribed - flag that indicates whether this context - * is subscribed as event listeners + * subscribed - flag that indicates whether this context is subscribed as + * event listeners */ private transient boolean subscribed; /** - * stale - flag that indicates whether the state - * managed by this context is stale + * stale - flag that indicates whether the state managed by this context is + * stale */ private transient boolean stale; @@ -127,11 +130,12 @@ * */ private transient String pipeline = ""; - + /** * PortalSiteSessionContextImpl - constructor - * - * @param pageManager PageManager component instance + * + * @param pageManager + * PageManager component instance */ public PortalSiteSessionContextImpl(PageManager pageManager) { @@ -140,64 +144,85 @@ } /** - * newRequestContext - create a new request context instance with fallback and history - * - * @param requestProfileLocators request profile locators + * newRequestContext - create a new request context instance with fallback + * and history + * + * @param requestProfileLocators + * request profile locators * @return new request context instance */ public PortalSiteRequestContext newRequestContext(Map requestProfileLocators) { - return new PortalSiteRequestContextImpl(this, requestProfileLocators, true, true); + return new PortalSiteRequestContextImpl(this, requestProfileLocators, + true, true); } /** * newRequestContext - create a new request context instance with history - * - * @param requestProfileLocators request profile locators - * @param requestFallback flag specifying whether to fallback to root folder - * if locators do not select a page or access is forbidden + * + * @param requestProfileLocators + * request profile locators + * @param requestFallback + * flag specifying whether to fallback to root folder if locators + * do not select a page or access is forbidden * @return new request context instance */ - public PortalSiteRequestContext newRequestContext(Map requestProfileLocators, boolean requestFallback) + public PortalSiteRequestContext newRequestContext( + Map requestProfileLocators, boolean requestFallback) { - return new PortalSiteRequestContextImpl(this, requestProfileLocators, requestFallback, true); + return new PortalSiteRequestContextImpl(this, requestProfileLocators, + requestFallback, true); } /** * newRequestContext - create a new request context instance - * - * @param requestProfileLocators request profile locators - * @param requestFallback flag specifying whether to fallback to root folder - * if locators do not select a page or access is forbidden - * @param useHistory flag indicating whether to use visited page - * history to select default page per site folder + * + * @param requestProfileLocators + * request profile locators + * @param requestFallback + * flag specifying whether to fallback to root folder if locators + * do not select a page or access is forbidden + * @param useHistory + * flag indicating whether to use visited page history to select + * default page per site folder * @return new request context instance */ - public PortalSiteRequestContext newRequestContext(Map requestProfileLocators, boolean requestFallback, boolean useHistory) + public PortalSiteRequestContext newRequestContext( + Map requestProfileLocators, boolean requestFallback, + boolean useHistory) { - return new PortalSiteRequestContextImpl(this, requestProfileLocators, requestFallback, useHistory); + return new PortalSiteRequestContextImpl(this, requestProfileLocators, + requestFallback, useHistory); } /** * selectRequestPage - select page proxy for request given profile locators - * - * @param requestProfileLocators map of profile locators for request - * @param requestFallback flag specifying whether to fallback to root folder - * if locators do not select a page or access is forbidden - * @param useHistory flag indicating whether to use visited page - * history to select default page per site folder + * + * @param requestProfileLocators + * map of profile locators for request + * @param requestFallback + * flag specifying whether to fallback to root folder if locators + * do not select a page or access is forbidden + * @param useHistory + * flag indicating whether to use visited page history to select + * default page per site folder * @return selected page proxy for request - * @throws NodeNotFoundException if not found - * @throws SecurityException if view access not granted + * @throws NodeNotFoundException + * if not found + * @throws SecurityException + * if view access not granted */ - public Page selectRequestPage(Map requestProfileLocators, boolean requestFallback, boolean useHistory) throws NodeNotFoundException + public Page selectRequestPage(Map requestProfileLocators, + boolean requestFallback, boolean useHistory) + throws NodeNotFoundException { // validate and update session profile locators if modified if (updateSessionProfileLocators(requestProfileLocators)) { // extract page request path from the locators String requestPath = Folder.PATH_SEPARATOR; - ProfileLocator locator = (ProfileLocator)requestProfileLocators.get(ProfileLocator.PAGE_LOCATOR); + ProfileLocator locator = (ProfileLocator) requestProfileLocators + .get(ProfileLocator.PAGE_LOCATOR); if (locator != null) { // use 'page' locator to determine request page by executing @@ -210,10 +235,11 @@ // all locators should have identical request paths, (do // not execute profile locator though to determine path: // simply use the request path) - locator = (ProfileLocator)requestProfileLocators.values().iterator().next(); + locator = (ProfileLocator) requestProfileLocators.values() + .iterator().next(); requestPath = locator.getRequestPath(); } - + // attempt to select request page or folder using // profile locators and site view; if fallback // enabled, fallback on missing node or access @@ -229,35 +255,35 @@ } catch (NodeNotFoundException nnfe) { - if (!requestFallback || requestPath.equals(Folder.PATH_SEPARATOR)) - { - throw nnfe; - } + if (!requestFallback + || requestPath.equals(Folder.PATH_SEPARATOR)) { throw nnfe; } fallbackException = nnfe; } catch (SecurityException se) { - if (!requestFallback || requestPath.equals(Folder.PATH_SEPARATOR)) - { - throw se; - } + if (!requestFallback + || requestPath.equals(Folder.PATH_SEPARATOR)) { throw se; } fallbackException = se; } // compute fallback request path - if (requestFallback && !requestPath.equals(Folder.PATH_SEPARATOR)) + if (requestFallback + && !requestPath.equals(Folder.PATH_SEPARATOR)) { // compute parent folder fallback request path String fallbackRequestPath = requestPath; while (fallbackRequestPath.endsWith(Folder.PATH_SEPARATOR)) { - fallbackRequestPath = fallbackRequestPath.substring(0, fallbackRequestPath.length()-1); + fallbackRequestPath = fallbackRequestPath.substring(0, + fallbackRequestPath.length() - 1); } - int folderIndex = fallbackRequestPath.lastIndexOf(Folder.PATH_SEPARATOR); + int folderIndex = fallbackRequestPath + .lastIndexOf(Folder.PATH_SEPARATOR); if (folderIndex >= 2) { // fallback to parent folder - fallbackRequestPath = fallbackRequestPath.substring(0, folderIndex); + fallbackRequestPath = fallbackRequestPath.substring(0, + folderIndex); } else { @@ -271,16 +297,23 @@ // log fallback if (log.isDebugEnabled()) { - log.debug("Missing/forbidden page selection fallback: request path=" + requestPath + ", attempting fallback request path=" + fallbackRequestPath, fallbackException); + log + .debug( + "Missing/forbidden page selection fallback: request path=" + + requestPath + + ", attempting fallback request path=" + + fallbackRequestPath, + fallbackException); } - + // clear all history entries for fallback // request path in advance to make fallback // page selection more predictable - Iterator folderIter = getFolderPageHistory().keySet().iterator(); + Iterator folderIter = getFolderPageHistory().keySet() + .iterator(); while (folderIter.hasNext()) { - Folder folder = (Folder)folderIter.next(); + Folder folder = (Folder) folderIter.next(); if (folder.getUrl().equals(fallbackRequestPath)) { folderIter.remove(); @@ -297,21 +330,21 @@ // fallback attempts complete: no page found for user break; } - } - while (true); + } while (true); } // no request page available - throw new NodeNotFoundException("No request page available in site view."); + throw new NodeNotFoundException( + "No request page available in site view."); } /** - * getRequestPathFromLocator - execute profile locator to extract - * request path using locator rules; this - * is request specific and is not part of - * the site view - * - * @param locator profile locator to execute + * getRequestPathFromLocator - execute profile locator to extract request + * path using locator rules; this is request specific and is not part of the + * site view + * + * @param locator + * profile locator to execute * @return request path from profile locator */ private String getRequestPathFromLocator(ProfileLocator locator) @@ -325,7 +358,8 @@ Iterator locatorIter = locator.iterator(); if (locatorIter.hasNext()) { - ProfileLocatorProperty [] properties = (ProfileLocatorProperty []) locatorIter.next(); + ProfileLocatorProperty[] properties = (ProfileLocatorProperty[]) locatorIter + .next(); for (int i = 0; (i < properties.length); i++) { if (!properties[i].isControl() && !properties[i].isNavigation()) @@ -349,7 +383,11 @@ } else if (basePath.endsWith(Page.DOCUMENT_TYPE)) { - basePath = basePath.substring(0, basePath.lastIndexOf(Folder.PATH_SEPARATOR)+1); + basePath = basePath + .substring( + 0, + basePath + .lastIndexOf(Folder.PATH_SEPARATOR) + 1); } else if (!basePath.endsWith(Folder.PATH_SEPARATOR)) { @@ -359,7 +397,8 @@ // make sure path ends in page extension // if folder not explicitly specified - if (!path.endsWith(Folder.PATH_SEPARATOR) && !path.endsWith(Page.DOCUMENT_TYPE)) + if (!path.endsWith(Folder.PATH_SEPARATOR) + && !path.endsWith(Page.DOCUMENT_TYPE)) { path += Page.DOCUMENT_TYPE; } @@ -369,19 +408,28 @@ if (!path.equals(requestPath)) { // if modified request path ends with default page, - // strip default page from path to allow folder level - // defaulting to take place: locator should not force + // strip default page from path to allow folder + // level + // defaulting to take place: locator should not + // force // selection of default page when selection of the // folder is implied by use in locator page/path - if (path.endsWith(Folder.PATH_SEPARATOR + Folder.FALLBACK_DEFAULT_PAGE)) + if (path.endsWith(Folder.PATH_SEPARATOR + + Folder.FALLBACK_DEFAULT_PAGE)) { - path = path.substring(0, path.length() - Folder.FALLBACK_DEFAULT_PAGE.length()); + path = path + .substring(0, path.length() + - Folder.FALLBACK_DEFAULT_PAGE + .length()); } - + // log modified page request - if (log.isDebugEnabled() && !path.equals(requestPath)) + if (log.isDebugEnabled() + && !path.equals(requestPath)) { - log.debug("Request page modified by profile locator: request path=" + path); + log + .debug("Request page modified by profile locator: request path=" + + path); } } return path; @@ -395,18 +443,22 @@ } /** - * selectRequestPage - select page proxy for request for specified - * path given profile locators and site view - * associated with this context - * - * @param requestPath request path - * @param useHistory flag indicating whether to use visited page - * history to select default page per site folder + * selectRequestPage - select page proxy for request for specified path + * given profile locators and site view associated with this context + * + * @param requestPath + * request path + * @param useHistory + * flag indicating whether to use visited page history to select + * default page per site folder * @return selected page proxy for request - * @throws NodeNotFoundException if not found - * @throws SecurityException if view access not granted + * @throws NodeNotFoundException + * if not found + * @throws SecurityException + * if view access not granted */ - private Page selectRequestPage(String requestPath, boolean useHistory) throws NodeNotFoundException + private Page selectRequestPage(String requestPath, boolean useHistory) + throws NodeNotFoundException { // save access exceptions SecurityException accessException = null; @@ -420,7 +472,7 @@ { requestPath = Folder.PATH_SEPARATOR; } - + // log page request if (log.isDebugEnabled()) { @@ -434,17 +486,21 @@ try { // try page or folder request url - requestNode = view.getNodeProxy(requestPath, null, false, false); + requestNode = view + .getNodeProxy(requestPath, null, false, false); } catch (NodeNotFoundException nnfe) { // if request path ends with default page, strip from // request url to retry for folder default - if (requestPath.endsWith(Folder.PATH_SEPARATOR + Folder.FALLBACK_DEFAULT_PAGE)) + if (requestPath.endsWith(Folder.PATH_SEPARATOR + + Folder.FALLBACK_DEFAULT_PAGE)) { // retry folder request url - requestPath = requestPath.substring(0, requestPath.length() - Folder.FALLBACK_DEFAULT_PAGE.length()); - requestNode = view.getNodeProxy(requestPath, null, true, false); + requestPath = requestPath.substring(0, requestPath.length() + - Folder.FALLBACK_DEFAULT_PAGE.length()); + requestNode = view.getNodeProxy(requestPath, null, true, + false); } else { @@ -452,12 +508,12 @@ throw nnfe; } } - + // invoke default page logic to determine folder page if (requestNode instanceof Folder) { - Folder requestFolder = (Folder)requestNode; - + Folder requestFolder = (Folder) requestNode; + // support subfolders specified as default pages; // find highest subfolder with a default page that // specifies a default folder, (not a default page). @@ -469,13 +525,16 @@ // do not follow broken default folders Folder defaultRequestFolder = requestFolder; // follow default folders to parent folders - while ((defaultRequestFolder != null) && (defaultFolderName != null) && - defaultFolderName.equals("..")) + while ((defaultRequestFolder != null) + && (defaultFolderName != null) + && defaultFolderName.equals("..")) { - defaultRequestFolder = (Folder)defaultRequestFolder.getParent(); + defaultRequestFolder = (Folder) defaultRequestFolder + .getParent(); if (defaultRequestFolder != null) { - defaultFolderName = defaultRequestFolder.getDefaultPage(); + defaultFolderName = defaultRequestFolder + .getDefaultPage(); } else { @@ -483,11 +542,16 @@ } } // follow default folders to subfolders - while ((defaultRequestFolder != null) && (defaultFolderName != null) && - !defaultFolderName.endsWith(Page.DOCUMENT_TYPE) && !defaultFolderName.equals("..")) + while ((defaultRequestFolder != null) + && (defaultFolderName != null) + && !defaultFolderName + .endsWith(Page.DOCUMENT_TYPE) + && !defaultFolderName.equals("..")) { - defaultRequestFolder = defaultRequestFolder.getFolder(defaultFolderName); - defaultFolderName = defaultRequestFolder.getDefaultPage(); + defaultRequestFolder = defaultRequestFolder + .getFolder(defaultFolderName); + defaultFolderName = defaultRequestFolder + .getDefaultPage(); } // use default request folder if (defaultRequestFolder != null) @@ -518,9 +582,11 @@ try { requestFolderPages = requestFolder.getPages(); - while (((requestFolderPages == null) || requestFolderPages.isEmpty()) && (requestFolder.getParent() != null)) + while (((requestFolderPages == null) || requestFolderPages + .isEmpty()) + && (requestFolder.getParent() != null)) { - requestFolder = (Folder)requestFolder.getParent(); + requestFolder = (Folder) requestFolder.getParent(); requestFolderPages = requestFolder.getPages(); } } @@ -534,7 +600,8 @@ accessException = se; } } - if ((requestFolder != null) && (requestFolderPages != null) && !requestFolderPages.isEmpty()) + if ((requestFolder != null) && (requestFolderPages != null) + && !requestFolderPages.isEmpty()) { Page requestPage = null; @@ -544,18 +611,23 @@ // occur in multiple site views if (useHistory) { - requestPage = (Page)getFolderPageHistory().get(requestFolder); - if ((requestPage != null) && requestFolderPages.contains(requestPage)) + requestPage = (Page) getFolderPageHistory().get( + requestFolder); + if ((requestPage != null) + && requestFolderPages.contains(requestPage)) { // log selected request page if (log.isDebugEnabled()) { - log.debug("Selected folder historical page: path=" + view.getManagedPage(requestPage).getPath()); + log + .debug("Selected folder historical page: path=" + + view.getManagedPage( + requestPage).getPath()); } return requestPage; } } - + // get default page for folder proxy if more than one // page is available to choose from if (requestFolderPages.size() > 1) @@ -569,19 +641,24 @@ } try { - // save last visited non-hidden page for folder proxy + // save last visited non-hidden page for folder + // proxy // path, (proxies are hashed by their path), and // return default page - requestPage = requestFolder.getPage(defaultPageName); + requestPage = requestFolder + .getPage(defaultPageName); if (!requestPage.isHidden()) { - getFolderPageHistory().put(requestFolder, requestPage); + getFolderPageHistory().put(requestFolder, + requestPage); } - + // log selected request page if (log.isDebugEnabled()) { - log.debug("Selected folder default page: path=" + view.getManagedPage(requestPage).getPath()); + log.debug("Selected folder default page: path=" + + view.getManagedPage(requestPage) + .getPath()); } return requestPage; } @@ -596,12 +673,12 @@ accessException = se; } } - + // default page not available, select first page // proxy in request folder; save last visited // non-hidden page for folder proxy path, (proxies // are hashed by their path), and return default page - requestPage = (Page)requestFolderPages.iterator().next(); + requestPage = (Page) requestFolderPages.iterator().next(); if (!requestPage.isHidden()) { getFolderPageHistory().put(requestFolder, requestPage); @@ -610,50 +687,55 @@ // log selected request page if (log.isDebugEnabled()) { - log.debug("Selected first folder page, path=" + view.getManagedPage(requestPage).getPath()); + log.debug("Selected first folder page, path=" + + view.getManagedPage(requestPage).getPath()); } return requestPage; } } else if (requestNode instanceof Page) { - Page requestPage = (Page)requestNode; - + Page requestPage = (Page) requestNode; + // save last visited non-hidden page for folder proxy // path, (proxies are hashed by their path), and // return matched page - Folder requestFolder = (Folder)requestPage.getParent(); + Folder requestFolder = (Folder) requestPage.getParent(); if (!requestPage.isHidden()) { - getFolderPageHistory().put(requestFolder, requestPage); + getFolderPageHistory().put(requestFolder, requestPage); } // log selected request page if (log.isDebugEnabled()) { - log.debug("Selected page, path=" + view.getManagedPage(requestPage).getPath()); + log.debug("Selected page, path=" + + view.getManagedPage(requestPage).getPath()); } return requestPage; } } - + // no page matched or accessible - if (accessException != null) - { - throw accessException; - } - throw new NodeNotFoundException("No page matched " + requestPath + " request in site view."); + if (accessException != null) { throw accessException; } + throw new NodeNotFoundException("No page matched " + requestPath + + " request in site view."); } - + /** - * getRequestRootFolder - select root folder proxy for given profile locators - * - * @param requestProfileLocators map of profile locators for request + * getRequestRootFolder - select root folder proxy for given profile + * locators + * + * @param requestProfileLocators + * map of profile locators for request * @return root folder proxy for request - * @throws NodeNotFoundException if not found - * @throws SecurityException if view access not granted + * @throws NodeNotFoundException + * if not found + * @throws SecurityException + * if view access not granted */ - public Folder getRequestRootFolder(Map requestProfileLocators) throws NodeNotFoundException + public Folder getRequestRootFolder(Map requestProfileLocators) + throws NodeNotFoundException { // validate and update session profile locators if modified if (updateSessionProfileLocators(requestProfileLocators)) @@ -668,25 +750,29 @@ } // no root folder available - throw new NodeNotFoundException("No root folder available in site view."); + throw new NodeNotFoundException( + "No root folder available in site view."); } /** * updateSessionProfileLocators - detect modification of and update cached - * session profile locators - * - * @param requestProfileLocators map of profile locators for request + * session profile locators + * + * @param requestProfileLocators + * map of profile locators for request * @return profile locators validation flag */ private boolean updateSessionProfileLocators(Map requestProfileLocators) { // request profile locators are required - if ((requestProfileLocators != null) && !requestProfileLocators.isEmpty()) + if ((requestProfileLocators != null) + && !requestProfileLocators.isEmpty()) { // get current user principal; ignore derivative // changes in role and group principals String currentUserPrincipal = null; - Subject subject = JSSubject.getSubject(AccessController.getContext()); + Subject subject = JSSubject.getSubject(AccessController + .getContext()); if (subject != null) { Iterator principals = subject.getPrincipals().iterator(); @@ -715,10 +801,10 @@ boolean updated = false; synchronized (this) { - userUpdate = (((userPrincipal == null) && (currentUserPrincipal != null)) || - ((userPrincipal != null) && !userPrincipal.equals(currentUserPrincipal))); - locatorsUpdate = ((profileLocators == null) || - !locatorsEquals(profileLocators, requestProfileLocators)); + userUpdate = (((userPrincipal == null) && (currentUserPrincipal != null)) || ((userPrincipal != null) && !userPrincipal + .equals(currentUserPrincipal))); + locatorsUpdate = ((profileLocators == null) || !locatorsEquals( + profileLocators, requestProfileLocators)); if (stale || userUpdate || locatorsUpdate) { // reset cached session profile locators, view, @@ -759,16 +845,19 @@ { debug.append("Updated stale"); } - debug.append(" context: user=" + userPrincipal + ", profileLocators=("); + debug.append(" context: user=" + userPrincipal + + ", profileLocators=("); if (profileLocators != null) { boolean firstEntry = true; - Iterator entriesIter = profileLocators.entrySet().iterator(); + Iterator entriesIter = profileLocators.entrySet() + .iterator(); while (entriesIter.hasNext()) { - Map.Entry entry = (Map.Entry)entriesIter.next(); - String locatorName = (String)entry.getKey(); - ProfileLocator locator = (ProfileLocator)entry.getValue(); + Map.Entry entry = (Map.Entry) entriesIter.next(); + String locatorName = (String) entry.getKey(); + ProfileLocator locator = (ProfileLocator) entry + .getValue(); if (!firstEntry) { debug.append(","); @@ -821,14 +910,15 @@ } /** - * getSiteView - lookup and/or create site view for - * profile locators of this context - * + * getSiteView - lookup and/or create site view for profile locators of this + * context + * * @return site view instance */ public SiteView getSiteView() { - if ((siteView == null) && (pageManager != null) && (profileLocators != null)) + if ((siteView == null) && (pageManager != null) + && (profileLocators != null)) { // create new site view siteView = new SiteView(pageManager, profileLocators); @@ -836,7 +926,8 @@ // log site view creation if (log.isDebugEnabled()) { - log.debug("Created site view: search paths=" + siteView.getSearchPathsString()); + log.debug("Created site view: search paths=" + + siteView.getSearchPathsString()); } } return siteView; @@ -844,7 +935,7 @@ /** * getPageManager - return PageManager component instance - * + * * @return PageManager instance */ public PageManager getPageManager() @@ -853,15 +944,14 @@ } /** - * isValid - return flag indicating whether this context instance - * is valid or if it is stale after being persisted and - * reloaded as session state - * + * isValid - return flag indicating whether this context instance is valid + * or if it is stale after being persisted and reloaded as session state + * * @return valid context status */ public boolean isValid() { - // existant transient page manager implies valid context + // existant transient page manager implies valid context return (pageManager != null); } @@ -875,78 +965,71 @@ /** * getStandardMenuNames - get set of available standard menu names - * + * * @return menu names set */ public Set getStandardMenuNames() { // return standard menu names defined for site view SiteView view = getSiteView(); - if (view != null) - { - return view.getStandardMenuNames(); - } + if (view != null) { return view.getStandardMenuNames(); } return null; } /** * getMenuDefinitionLocators - get list of node proxy menu definition - * locators from site view - * - * @param node site view node proxy + * locators from site view + * + * @param node + * site view node proxy * @return definition locator list */ public List getMenuDefinitionLocators(Node node) { // return menu definition locators for node in site view SiteView view = getSiteView(); - if (view != null) - { - return view.getMenuDefinitionLocators(node); - } + if (view != null) { return view.getMenuDefinitionLocators(node); } return null; } /** - * getMenuDefinitionLocator - get named node proxy menu definition - * locator from site view - * - * @param node site view node proxy - * @param name menu definition name + * getMenuDefinitionLocator - get named node proxy menu definition locator + * from site view + * + * @param node + * site view node proxy + * @param name + * menu definition name * @return menu definition locator */ - public SiteViewMenuDefinitionLocator getMenuDefinitionLocator(Node node, String name) + public SiteViewMenuDefinitionLocator getMenuDefinitionLocator(Node node, + String name) { // return named menu definition locator for node in site view SiteView view = getSiteView(); - if (view != null) - { - return view.getMenuDefinitionLocator(node, name); - } + if (view != null) { return view.getMenuDefinitionLocator(node, name); } return null; } /** * getManagedPage - get concrete page instance from page proxy - * - * @param page page proxy + * + * @param page + * page proxy * @return managed page */ public Page getManagedPage(Page page) { // return managed page in site view SiteView view = getSiteView(); - if (view != null) - { - return view.getManagedPage(page); - } + if (view != null) { return view.getManagedPage(page); } return null; } /** - * getMenuDefinitionLocatorCache - get menu definition locators cache - * for absolute menus - * + * getMenuDefinitionLocatorCache - get menu definition locators cache for + * absolute menus + * * @return menu definition locators cache */ public Map getMenuDefinitionLocatorCache() @@ -955,9 +1038,9 @@ } /** - * setMenuDefinitionLocatorCache - set menu definition locators cache - * for absolute menus - * + * setMenuDefinitionLocatorCache - set menu definition locators cache for + * absolute menus + * * @return menu definition locators cache */ public void setMenuDefinitionLocatorCache(Map cache) @@ -966,51 +1049,45 @@ } /** - * locatorsEquals - test profile locator maps for equivalence - * ignoring request specifics - * - * @param locators0 request profile locator map - * @param locators1 request profile locator map + * locatorsEquals - test profile locator maps for equivalence ignoring + * request specifics + * + * @param locators0 + * request profile locator map + * @param locators1 + * request profile locator map * @return boolean flag indicating equivalence */ private static boolean locatorsEquals(Map locators0, Map locators1) { // trivial comparison - if (locators0 == locators1) - { - return true; - } + if (locators0 == locators1) { return true; } // compare locator map sizes - if (locators0.size() != locators1.size()) - { - return false; - } + if (locators0.size() != locators1.size()) { return false; } // compare locator map entries Iterator entriesIter = locators0.entrySet().iterator(); if (entriesIter.hasNext()) { - Map.Entry entry = (Map.Entry)entriesIter.next(); - ProfileLocator locator0 = (ProfileLocator)entry.getValue(); - ProfileLocator locator1 = (ProfileLocator)locators1.get(entry.getKey()); - if (locator1 == null) - { - return false; - } + Map.Entry entry = (Map.Entry) entriesIter.next(); + ProfileLocator locator0 = (ProfileLocator) entry.getValue(); + ProfileLocator locator1 = (ProfileLocator) locators1.get(entry + .getKey()); + if (locator1 == null) { return false; } // compare locators using the most specific, // (i.e. first), locator properties array // returned by the locator iterator - ProfileLocatorProperty [] properties0 = (ProfileLocatorProperty [])locator0.iterator().next(); - ProfileLocatorProperty [] properties1 = (ProfileLocatorProperty [])locator1.iterator().next(); + ProfileLocatorProperty[] properties0 = (ProfileLocatorProperty[]) locator0 + .iterator().next(); + ProfileLocatorProperty[] properties1 = (ProfileLocatorProperty[]) locator1 + .iterator().next(); if ((properties0 != null) || (properties1 != null)) { - if ((properties0 == null) || (properties1 == null) || (properties0.length != properties1.length)) - { - return false; - } - + if ((properties0 == null) || (properties1 == null) + || (properties0.length != properties1.length)) { return false; } + // compare ordered locator properties for (int i = 0, limit = properties0.length; (i < limit); i++) { @@ -1019,15 +1096,19 @@ // control or navigation properties; otherwise they are // assumed to contain variable request paths that should // be treated as equivalent - if (!properties0[i].getName().equals(properties1[i].getName()) || - (properties0[i].isControl() && !properties1[i].isControl()) || - (properties0[i].isNavigation() && !properties1[i].isNavigation()) || - ((properties0[i].isControl() || properties0[i].isNavigation()) && - (((properties0[i].getValue() == null) && (properties1[i].getValue() != null)) || - ((properties0[i].getValue() != null) && !properties0[i].getValue().equals(properties1[i].getValue()))))) - { - return false; - } + if (!properties0[i].getName().equals( + properties1[i].getName()) + || (properties0[i].isControl() && !properties1[i] + .isControl()) + || (properties0[i].isNavigation() && !properties1[i] + .isNavigation()) + || ((properties0[i].isControl() || properties0[i] + .isNavigation()) && (((properties0[i] + .getValue() == null) && (properties1[i] + .getValue() != null)) || ((properties0[i] + .getValue() != null) && !properties0[i] + .getValue().equals( + properties1[i].getValue()))))) { return false; } } } } @@ -1036,87 +1117,63 @@ /** * locatorRequestPath - extract request specific path from profile locator - * using request path from locator - * - * @param locator request profile locator + * using request path from locator + * + * @param locator + * request profile locator * @return request path - - private static String locatorRequestPath(ProfileLocator locator) - { - // use request path in locator as default - return locatorRequestPath(locator, locator.getRequestPath()); - } - */ + * + * private static String locatorRequestPath(ProfileLocator locator) { // use + * request path in locator as default return locatorRequestPath(locator, + * locator.getRequestPath()); } + */ /** * locatorRequestPath - extract request specific path from profile locator - * - * @param locator request profile locator - * @param requestPath request path + * + * @param locator + * request profile locator + * @param requestPath + * request path * @return request path - - private static String locatorRequestPath(ProfileLocator locator, String requestPath) - { - // search locator using the most specific, - // (i.e. first), locator properties array - // returned by the locator iterator and return - // first valued property that is not a control - // or navigation type - ProfileLocatorProperty [] properties = (ProfileLocatorProperty [])locator.iterator().next(); - for (int i = 0, limit = properties.length; (i < limit); i++) - { - if (!properties[i].isControl() && !properties[i].isNavigation() && (properties[i].getValue() != null)) - { - // use specified locator path - String locatorPath = properties[i].getValue(); + * + * private static String locatorRequestPath(ProfileLocator locator, String + * requestPath) { // search locator using the most specific, // (i.e. + * first), locator properties array // returned by the locator iterator and + * return // first valued property that is not a control // or navigation + * type ProfileLocatorProperty [] properties = (ProfileLocatorProperty + * [])locator.iterator().next(); for (int i = 0, limit = properties.length; + * (i < limit); i++) { if (!properties[i].isControl() && + * !properties[i].isNavigation() && (properties[i].getValue() != null)) { // + * use specified locator path String locatorPath = properties[i].getValue(); // + * return specified locatorPath if absolute if + * (locatorPath.startsWith(Folder.PATH_SEPARATOR)) { return locatorPath; } // + * page names and relative paths are assumed relative to // request path and + * that any locator paths with no url // separator should have the page + * extension appended // get default page if page path null if + * ((locatorPath.indexOf(Folder.PATH_SEPARATOR) == -1) && + * !locatorPath.endsWith(Page.DOCUMENT_TYPE)) { locatorPath += + * Page.DOCUMENT_TYPE; } // append locator path to request path, replacing // + * requested pages and preserving requested folders boolean + * rootFolderRequest = requestPath.equals(Folder.PATH_SEPARATOR); boolean + * folderRequest = (!requestPath.endsWith(Page.DOCUMENT_TYPE)); int + * lastSeparatorIndex = requestPath.lastIndexOf(Folder.PATH_SEPARATOR_CHAR); + * if ((lastSeparatorIndex > 0) && (!folderRequest || + * requestPath.endsWith(Folder.PATH_SEPARATOR))) { // append locator to + * request path base path return requestPath.substring(0, + * lastSeparatorIndex) + Folder.PATH_SEPARATOR + locatorPath; } else if + * (!rootFolderRequest && folderRequest) { // append locator to request path + * root folder return requestPath + Folder.PATH_SEPARATOR + locatorPath; } + * else { // use root folder locator return Folder.PATH_SEPARATOR + + * locatorPath; } } } return requestPath; } + */ - // return specified locatorPath if absolute - if (locatorPath.startsWith(Folder.PATH_SEPARATOR)) - { - return locatorPath; - } - - // page names and relative paths are assumed relative to - // request path and that any locator paths with no url - // separator should have the page extension appended - // get default page if page path null - if ((locatorPath.indexOf(Folder.PATH_SEPARATOR) == -1) && !locatorPath.endsWith(Page.DOCUMENT_TYPE)) - { - locatorPath += Page.DOCUMENT_TYPE; - } - - // append locator path to request path, replacing - // requested pages and preserving requested folders - boolean rootFolderRequest = requestPath.equals(Folder.PATH_SEPARATOR); - boolean folderRequest = (!requestPath.endsWith(Page.DOCUMENT_TYPE)); - int lastSeparatorIndex = requestPath.lastIndexOf(Folder.PATH_SEPARATOR_CHAR); - if ((lastSeparatorIndex > 0) && (!folderRequest || requestPath.endsWith(Folder.PATH_SEPARATOR))) - { - // append locator to request path base path - return requestPath.substring(0, lastSeparatorIndex) + Folder.PATH_SEPARATOR + locatorPath; - } - else if (!rootFolderRequest && folderRequest) - { - // append locator to request path root folder - return requestPath + Folder.PATH_SEPARATOR + locatorPath; - } - else - { - // use root folder locator - return Folder.PATH_SEPARATOR + locatorPath; - } - } - } - return requestPath; - } - */ - /** - * newNode - invoked when the definition of a node is - * created by the page manager or when the - * node creation is otherwise detected - * - * @param node new managed node if known + * newNode - invoked when the definition of a node is created by the page + * manager or when the node creation is otherwise detected + * + * @param node + * new managed node if known */ public void newNode(Node node) { @@ -1125,11 +1182,11 @@ } /** - * updatedNode - invoked when the definition of a node is - * updated by the page manager or when the - * node modification is otherwise detected - * - * @param node updated managed node if known + * updatedNode - invoked when the definition of a node is updated by the + * page manager or when the node modification is otherwise detected + * + * @param node + * updated managed node if known */ public void updatedNode(Node node) { @@ -1144,21 +1201,23 @@ { if (node != null) { - log.debug("Page manager update event, (node=" + node.getPath() + "): set session context state stale"); + log.debug("Page manager update event, (node=" + node.getPath() + + "): set session context state stale"); } else { - log.debug("Page manager update event: set session context state stale"); + log + .debug("Page manager update event: set session context state stale"); } } } /** - * removedNode - invoked when the definition of a node is - * removed by the page manager or when the - * node removal is otherwise detected - * - * @param node removed managed node if known + * removedNode - invoked when the definition of a node is removed by the + * page manager or when the node removal is otherwise detected + * + * @param node + * removed managed node if known */ public void removedNode(Node node) { @@ -1167,10 +1226,11 @@ } /** - * sessionDidActivate - notification that the session has just - * been activated - * - * @param event session activation event + * sessionDidActivate - notification that the session has just been + * activated + * + * @param event + * session activation event */ public void sessionDidActivate(HttpSessionEvent event) { @@ -1183,15 +1243,17 @@ // log activation event if (log.isDebugEnabled()) { - log.debug("Session activation event: set session context state stale"); + log + .debug("Session activation event: set session context state stale"); } } - + /** - * sessionWillPassivate - notification that the session is about - * to be passivated - * - * @param event session activation event + * sessionWillPassivate - notification that the session is about to be + * passivated + * + * @param event + * session activation event */ public void sessionWillPassivate(HttpSessionEvent event) { @@ -1201,15 +1263,17 @@ // log activation event if (log.isDebugEnabled()) { - log.debug("Session deactivation event: clear session context state"); + log + .debug("Session deactivation event: clear session context state"); } } /** - * valueBound - notifies this context that it is being bound to - * a session and identifies the session - * - * @param event session binding event + * valueBound - notifies this context that it is being bound to a session + * and identifies the session + * + * @param event + * session binding event */ public void valueBound(HttpSessionBindingEvent event) { @@ -1229,12 +1293,13 @@ log.debug("Session bound event: setup page manager listener"); } } - + /** - * valueUnbound - notifies this context that it is being unbound - * from a session and identifies the session - * - * @param event session binding event + * valueUnbound - notifies this context that it is being unbound from a + * session and identifies the session + * + * @param event + * session binding event */ public void valueUnbound(HttpSessionBindingEvent event) { @@ -1254,24 +1319,25 @@ // log binding event if (log.isDebugEnabled()) { - log.debug("Session unbound event: clear page manager listener and session context state"); + log + .debug("Session unbound event: clear page manager listener and session context state"); } } - private Map getFolderPageHistory() + private Map getFolderPageHistory() { - if (folderPageHistory == null) + if (folderPageHistory == null) { - folderPageHistory = new HashMap(); - } - return folderPageHistory; - } - + folderPageHistory = new HashMap(); + } + return folderPageHistory; + } + public void setPipeline(String pipeline) { this.pipeline = pipeline; } - + public String getPipeline() { return this.pipeline; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/DefaultMenuDefinition.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/DefaultMenuDefinition.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/DefaultMenuDefinition.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,15 +19,15 @@ import org.apache.jetspeed.om.folder.impl.StandardMenuDefinitionImpl; /** - * This class provides a menu definition for default menus - * constructed from folders within menus with depth expansion - * specified. + * This class provides a menu definition for default menus constructed from + * folders within menus with depth expansion specified. * * @author Randy Watler * @version $Id: DefaultMenuDefinition.java 516448 2007-03-09 16:25:47Z ate $ */ public class DefaultMenuDefinition extends StandardMenuDefinitionImpl { + /** * options - options path specification for menu */ @@ -55,8 +55,9 @@ } /** - * getOptions - get comma separated menu options if not specified as elements - * + * getOptions - get comma separated menu options if not specified as + * elements + * * @return option paths specification */ public String getOptions() @@ -66,7 +67,7 @@ /** * getDepth - get depth of inclusion for folder menu options - * + * * @return inclusion depth */ public int getDepth() @@ -76,7 +77,7 @@ /** * getProfile - get profile locator used to filter specified options - * + * * @return profile locator name */ public String getProfile() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/DefaultMenuOptionsDefinition.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/DefaultMenuOptionsDefinition.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/DefaultMenuOptionsDefinition.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,14 +19,17 @@ import org.apache.jetspeed.om.folder.impl.StandardMenuOptionsDefinitionImpl; /** - * This class provides a menu options definition for options - * constructed directly from menu definitions. + * This class provides a menu options definition for options constructed + * directly from menu definitions. * * @author Randy Watler - * @version $Id: DefaultMenuOptionsDefinition.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: DefaultMenuOptionsDefinition.java 516448 2007-03-09 16:25:47Z + * ate $ */ -public class DefaultMenuOptionsDefinition extends StandardMenuOptionsDefinitionImpl +public class DefaultMenuOptionsDefinition extends + StandardMenuOptionsDefinitionImpl { + /** * options - options path specification for menu */ @@ -60,7 +63,8 @@ /** * DefaultMenuOptionsDefinition - constructor */ - public DefaultMenuOptionsDefinition(String options, int depth, boolean paths, boolean regexp, String locatorName, String order) + public DefaultMenuOptionsDefinition(String options, int depth, + boolean paths, boolean regexp, String locatorName, String order) { super(); this.options = options; @@ -72,8 +76,9 @@ } /** - * getOptions - get comma separated menu options if not specified as elements - * + * getOptions - get comma separated menu options if not specified as + * elements + * * @return option paths specification */ public String getOptions() @@ -83,7 +88,7 @@ /** * getDepth - get depth of inclusion for folder menu options - * + * * @return inclusion depth */ public int getDepth() @@ -93,17 +98,17 @@ /** * isPaths - get generate ordered path options - * + * * @return paths options flag */ public boolean isPaths() { return paths; } - + /** * isRegexp - get regexp flag for interpreting options - * + * * @return regexp flag */ public boolean isRegexp() @@ -113,7 +118,7 @@ /** * getProfile - get profile locator used to filter specified options - * + * * @return profile locator name */ public String getProfile() @@ -123,7 +128,7 @@ /** * getOrder - get comma separated regexp ordering patterns - * + * * @return ordering patterns list */ public String getOrder() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardBackMenuDefinition.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardBackMenuDefinition.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardBackMenuDefinition.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,14 +25,14 @@ import org.apache.jetspeed.portalsite.view.SiteView; /** - * This class provides a menu definition for the standard - * back menu. + * This class provides a menu definition for the standard back menu. * * @author Randy Watler * @version $Id: StandardBackMenuDefinition.java 516448 2007-03-09 16:25:47Z ate $ */ public class StandardBackMenuDefinition extends StandardMenuDefinitionImpl { + /** * StandardBackMenuDefinition - constructor */ @@ -43,7 +43,7 @@ /** * getName - get menu name - * + * * @return menu name */ public String getName() @@ -52,8 +52,9 @@ } /** - * getOptions - get comma separated menu options if not specified as elements - * + * getOptions - get comma separated menu options if not specified as + * elements + * * @return option paths specification */ public String getOptions() @@ -64,7 +65,7 @@ /** * getSkin - get skin name for menu element - * + * * @return skin name */ public String getSkin() @@ -74,7 +75,7 @@ /** * getTitle - get default title for menu - * + * * @return title text */ public String getTitle() @@ -84,27 +85,26 @@ } /** - * getTitle - get locale specific title for menu from metadata - * protocol, with or without falback enabled - * - * @param locale preferred locale - * @param fallback whether to return default title + * getTitle - get locale specific title for menu from metadata protocol, + * with or without falback enabled + * + * @param locale + * preferred locale + * @param fallback + * whether to return default title * @return title text */ protected String getTitle(Locale locale, boolean fallback) { // use specified locale or fallback if locale specific title not defined String title = getMenuTitleText(locale, getTitleResourceKey()); - if (title != null) - { - return title; - } + if (title != null) { return title; } return super.getTitle(locale, fallback); } /** * getTitleResourceKey - get resource key used to lookup menu titles - * + * * @return resource key */ protected String getTitleResourceKey() @@ -113,11 +113,13 @@ } /** - * getMenuTitleText - lookup resource bundle based on locale - * and use to extract menu title text - * - * @param locale preferred locale - * @param key message key for text + * getMenuTitleText - lookup resource bundle based on locale and use to + * extract menu title text + * + * @param locale + * preferred locale + * @param key + * message key for text */ protected String getMenuTitleText(Locale locale, String key) { @@ -127,13 +129,17 @@ ResourceBundle bundle = null; if (locale != null) { - bundle = ResourceBundle.getBundle("org.apache.jetspeed.portalsite.menu.resources.MenuTitles",locale); + bundle = ResourceBundle + .getBundle( + "org.apache.jetspeed.portalsite.menu.resources.MenuTitles", + locale); } else { - bundle = ResourceBundle.getBundle("org.apache.jetspeed.portalsite.menu.resources.MenuTitles"); + bundle = ResourceBundle + .getBundle("org.apache.jetspeed.portalsite.menu.resources.MenuTitles"); } - + // lookup and return keyed message return bundle.getString(key); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardBreadcrumbsMenuDefinition.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardBreadcrumbsMenuDefinition.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardBreadcrumbsMenuDefinition.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,14 +19,16 @@ import org.apache.jetspeed.portalsite.view.SiteView; /** - * This class provides a menu definition for the standard - * breadcrumbs menu. + * This class provides a menu definition for the standard breadcrumbs menu. * * @author Randy Watler - * @version $Id: StandardBreadcrumbsMenuDefinition.java 517121 2007-03-12 07:45:49Z ate $ + * @version $Id: StandardBreadcrumbsMenuDefinition.java 517121 2007-03-12 + * 07:45:49Z ate $ */ -public class StandardBreadcrumbsMenuDefinition extends StandardBackMenuDefinition +public class StandardBreadcrumbsMenuDefinition extends + StandardBackMenuDefinition { + /** * StandardBreadcrumbsMenuDefinition - constructor */ @@ -37,7 +39,7 @@ /** * getName - get menu name - * + * * @return menu name */ public String getName() @@ -46,8 +48,9 @@ } /** - * getOptions - get comma separated menu options if not specified as elements - * + * getOptions - get comma separated menu options if not specified as + * elements + * * @return option paths specification */ public String getOptions() @@ -58,17 +61,17 @@ /** * isPaths - get generate ordered path options for specified options - * + * * @return paths options flag */ public boolean isPaths() { return true; } - + /** * getTitleResourceKey - get resource key used to lookup menu titles - * + * * @return resource key */ protected String getTitleResourceKey() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardNavigationsMenuDefinition.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardNavigationsMenuDefinition.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardNavigationsMenuDefinition.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,17 +31,19 @@ import org.apache.jetspeed.portalsite.view.SiteView; /** - * This class provides a menu definition for the standard - * navigations menu. + * This class provides a menu definition for the standard navigations menu. * * @author Randy Watler - * @version $Id: StandardNavigationsMenuDefinition.java 568811 2007-08-23 03:00:37Z woonsan $ + * @version $Id: StandardNavigationsMenuDefinition.java 568811 2007-08-23 + * 03:00:37Z woonsan $ */ -public class StandardNavigationsMenuDefinition extends StandardMenuDefinitionImpl +public class StandardNavigationsMenuDefinition extends + StandardMenuDefinitionImpl { + /** - * menuElements - ordered polymorphic list of menu option, nested - * menu, separator, include, and exclude definitions + * menuElements - ordered polymorphic list of menu option, nested menu, + * separator, include, and exclude definitions */ private List menuElements; @@ -55,7 +57,7 @@ /** * getName - get menu name - * + * * @return menu name */ public String getName() @@ -64,10 +66,9 @@ } /** - * getMenuElements - get ordered list of menu options, - * nested menus, separators, included - * menu, and excluded menu elements - * + * getMenuElements - get ordered list of menu options, nested menus, + * separators, included menu, and excluded menu elements + * * @return element list */ public synchronized List getMenuElements() @@ -77,118 +78,129 @@ { menuElements = new ArrayList(4); menuElements.add(new StandardMenuSeparatorDefinitionImpl() + { + + /** + * getText - get default text for separator + * + * @return text + */ + public String getText() { - /** - * getText - get default text for separator - * - * @return text - */ - public String getText() - { - // use locale defaults - return getMenuSeparatorText(null, "menu.separator.folders"); - } + // use locale defaults + return getMenuSeparatorText(null, "menu.separator.folders"); + } - /** - * getText - get locale specific text for separator from metadata - * - * @param locale preferred locale - * @return text - */ - public String getText(Locale locale) - { - // use specified locale - return getMenuSeparatorText(locale, "menu.separator.folders"); - } - }); + /** + * getText - get locale specific text for separator from + * metadata + * + * @param locale + * preferred locale + * @return text + */ + public String getText(Locale locale) + { + // use specified locale + return getMenuSeparatorText(locale, + "menu.separator.folders"); + } + }); menuElements.add(new StandardMenuOptionsDefinitionImpl() + { + + /** + * getOptions - get comma separated menu options + * + * @return option paths specification + */ + public String getOptions() { - /** - * getOptions - get comma separated menu options - * - * @return option paths specification - */ - public String getOptions() - { - return "." + Folder.PATH_SEPARATOR + "*" + Folder.PATH_SEPARATOR; - } + return "." + Folder.PATH_SEPARATOR + "*" + + Folder.PATH_SEPARATOR; + } - /** - * isRegexp - get regexp flag for interpreting option - * - * @return regexp flag - */ - public boolean isRegexp() - { - return true; - } - }); + /** + * isRegexp - get regexp flag for interpreting option + * + * @return regexp flag + */ + public boolean isRegexp() + { + return true; + } + }); menuElements.add(new StandardMenuIncludeDefinitionImpl() + { + + /** + * getName - get menu name to nest or with options to include + * + * @return menu name + */ + public String getName() { - /** - * getName - get menu name to nest or with options to include - * - * @return menu name - */ - public String getName() - { - return SiteView.CUSTOM_PAGE_NAVIGATIONS_MENU_NAME; - } - }); + return SiteView.CUSTOM_PAGE_NAVIGATIONS_MENU_NAME; + } + }); menuElements.add(new StandardMenuSeparatorDefinitionImpl() + { + + /** + * getText - get default text for separator + * + * @return text + */ + public String getText() { - /** - * getText - get default text for separator - * - * @return text - */ - public String getText() - { - // use locale defaults - return getMenuSeparatorText(null, "menu.separator.links"); - } + // use locale defaults + return getMenuSeparatorText(null, "menu.separator.links"); + } - /** - * getText - get locale specific text for separator from metadata - * - * @param locale preferred locale - * @return text - */ - public String getText(Locale locale) - { - // use specified locale - return getMenuSeparatorText(locale, "menu.separator.links"); - } - }); + /** + * getText - get locale specific text for separator from + * metadata + * + * @param locale + * preferred locale + * @return text + */ + public String getText(Locale locale) + { + // use specified locale + return getMenuSeparatorText(locale, "menu.separator.links"); + } + }); menuElements.add(new StandardMenuOptionsDefinitionImpl() + { + + /** + * getOptions - get comma separated menu options + * + * @return option paths specification + */ + public String getOptions() { - /** - * getOptions - get comma separated menu options - * - * @return option paths specification - */ - public String getOptions() - { - return Folder.PATH_SEPARATOR + "*" + Link.DOCUMENT_TYPE; - } + return Folder.PATH_SEPARATOR + "*" + Link.DOCUMENT_TYPE; + } - /** - * isRegexp - get regexp flag for interpreting option - * - * @return regexp flag - */ - public boolean isRegexp() - { - return true; - } - }); + /** + * isRegexp - get regexp flag for interpreting option + * + * @return regexp flag + */ + public boolean isRegexp() + { + return true; + } + }); } return menuElements; } /** * getSkin - get skin name for menu element - * + * * @return skin name */ public String getSkin() @@ -197,11 +209,13 @@ } /** - * getMenuSeparatorText - lookup resource bundle based on locale - * and use to extract menu separator text - * - * @param locale preferred locale - * @param key message key for text + * getMenuSeparatorText - lookup resource bundle based on locale and use to + * extract menu separator text + * + * @param locale + * preferred locale + * @param key + * message key for text */ protected String getMenuSeparatorText(Locale locale, String key) { @@ -211,13 +225,17 @@ ResourceBundle bundle = null; if (locale != null) { - bundle = ResourceBundle.getBundle("org.apache.jetspeed.portalsite.menu.resources.MenuSeparators",locale); + bundle = ResourceBundle + .getBundle( + "org.apache.jetspeed.portalsite.menu.resources.MenuSeparators", + locale); } else { - bundle = ResourceBundle.getBundle("org.apache.jetspeed.portalsite.menu.resources.MenuSeparators"); + bundle = ResourceBundle + .getBundle("org.apache.jetspeed.portalsite.menu.resources.MenuSeparators"); } - + // lookup and return keyed message return bundle.getString(key); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardPagesMenuDefinition.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardPagesMenuDefinition.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/menu/StandardPagesMenuDefinition.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,14 +21,15 @@ import org.apache.jetspeed.portalsite.view.SiteView; /** - * This class provides a menu definition for the standard - * pages menu. + * This class provides a menu definition for the standard pages menu. * * @author Randy Watler - * @version $Id: StandardPagesMenuDefinition.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: StandardPagesMenuDefinition.java 516448 2007-03-09 16:25:47Z + * ate $ */ public class StandardPagesMenuDefinition extends StandardMenuDefinitionImpl { + /** * StandardPagesMenuDefinition - constructor */ @@ -39,7 +40,7 @@ /** * getName - get menu name - * + * * @return menu name */ public String getName() @@ -48,8 +49,9 @@ } /** - * getOptions - get comma separated menu options if not specified as elements - * + * getOptions - get comma separated menu options if not specified as + * elements + * * @return option paths specification */ public String getOptions() @@ -59,7 +61,7 @@ /** * isRegexp - get regexp flag for interpreting specified option - * + * * @return regexp flag */ public boolean isRegexp() @@ -69,7 +71,7 @@ /** * getSkin - get skin name for menu element - * + * * @return skin name */ public String getSkin() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteView.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteView.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteView.java 2008-05-16 01:54:54 UTC (rev 940) @@ -49,13 +49,15 @@ */ public class SiteView { + /** * CURRENT_PAGE_PATH - expression used to match the current page */ public final static String CURRENT_PAGE_PATH = "~"; /** - * ALT_CURRENT_PAGE_PATH - alternate expression used to match the current page + * ALT_CURRENT_PAGE_PATH - alternate expression used to match the current + * page */ public final static String ALT_CURRENT_PAGE_PATH = "@"; @@ -63,8 +65,11 @@ * STANDARD_*_MENU_NAME - standard menu names */ public final static String STANDARD_BACK_MENU_NAME = "back"; + public final static String STANDARD_BREADCRUMBS_MENU_NAME = "breadcrumbs"; + public final static String STANDARD_PAGES_MENU_NAME = "pages"; + public final static String STANDARD_NAVIGATIONS_MENU_NAME = "navigations"; /** @@ -85,15 +90,25 @@ } /** - * STANDARD_MENU_DEFINITION_LOCATORS - list of standard menu definition locators + * STANDARD_MENU_DEFINITION_LOCATORS - list of standard menu definition + * locators */ - private final static List STANDARD_MENU_DEFINITION_LOCATORS = new ArrayList(4); + private final static List STANDARD_MENU_DEFINITION_LOCATORS = new ArrayList( + 4); static { - STANDARD_MENU_DEFINITION_LOCATORS.add(new SiteViewMenuDefinitionLocator(new StandardBackMenuDefinition())); - STANDARD_MENU_DEFINITION_LOCATORS.add(new SiteViewMenuDefinitionLocator(new StandardBreadcrumbsMenuDefinition())); - STANDARD_MENU_DEFINITION_LOCATORS.add(new SiteViewMenuDefinitionLocator(new StandardPagesMenuDefinition())); - STANDARD_MENU_DEFINITION_LOCATORS.add(new SiteViewMenuDefinitionLocator(new StandardNavigationsMenuDefinition())); + STANDARD_MENU_DEFINITION_LOCATORS + .add(new SiteViewMenuDefinitionLocator( + new StandardBackMenuDefinition())); + STANDARD_MENU_DEFINITION_LOCATORS + .add(new SiteViewMenuDefinitionLocator( + new StandardBreadcrumbsMenuDefinition())); + STANDARD_MENU_DEFINITION_LOCATORS + .add(new SiteViewMenuDefinitionLocator( + new StandardPagesMenuDefinition())); + STANDARD_MENU_DEFINITION_LOCATORS + .add(new SiteViewMenuDefinitionLocator( + new StandardNavigationsMenuDefinition())); } /** @@ -102,8 +117,8 @@ private PageManager pageManager; /** - * searchPaths - validated list of ordered search path objects - * where paths have no trailing folder separator + * searchPaths - validated list of ordered search path objects where paths + * have no trailing folder separator */ private List searchPaths; @@ -119,10 +134,11 @@ /** * SiteView - validating constructor - * - * @param pageManager PageManager component instance - * @param searchPaths list of search paths in string or search path - * object form + * + * @param pageManager + * PageManager component instance + * @param searchPaths + * list of search paths in string or search path object form */ public SiteView(PageManager pageManager, List searchPaths) { @@ -141,10 +157,11 @@ String path = pathObject.toString().trim(); if (path.length() > 0) { - pathObject = new SiteViewSearchPath(ProfileLocator.PAGE_LOCATOR, path); + pathObject = new SiteViewSearchPath( + ProfileLocator.PAGE_LOCATOR, path); } } - SiteViewSearchPath searchPath = (SiteViewSearchPath)pathObject; + SiteViewSearchPath searchPath = (SiteViewSearchPath) pathObject; if (this.searchPaths.indexOf(searchPath) == -1) { try @@ -152,7 +169,7 @@ if (this.pageManager.getFolder(searchPath.toString()) != null) { this.searchPaths.add(searchPath); - + // construct search paths as string if (searchPathsStringBuffer.length() == 0) { @@ -182,7 +199,8 @@ // save search paths as string if (this.searchPaths.isEmpty()) { - this.searchPaths.add(new SiteViewSearchPath(ProfileLocator.PAGE_LOCATOR, Folder.PATH_SEPARATOR)); + this.searchPaths.add(new SiteViewSearchPath( + ProfileLocator.PAGE_LOCATOR, Folder.PATH_SEPARATOR)); this.searchPathsString = Folder.PATH_SEPARATOR; } else @@ -194,29 +212,33 @@ { // root search path with no aggregation this.searchPaths = new ArrayList(1); - this.searchPaths.add(new SiteViewSearchPath(ProfileLocator.PAGE_LOCATOR, Folder.PATH_SEPARATOR)); + this.searchPaths.add(new SiteViewSearchPath( + ProfileLocator.PAGE_LOCATOR, Folder.PATH_SEPARATOR)); this.searchPathsString = Folder.PATH_SEPARATOR; } } /** * SiteView - validating constructor - * - * @param pageManager PageManager component instance - * @param searchPaths array of search paths + * + * @param pageManager + * PageManager component instance + * @param searchPaths + * array of search paths */ - public SiteView(PageManager pageManager, String [] searchPaths) + public SiteView(PageManager pageManager, String[] searchPaths) { this(pageManager, makeSearchPathList(searchPaths)); } /** * makeSearchPathList - construct from array - * - * @param searchPaths array of search paths + * + * @param searchPaths + * array of search paths * @return search path list */ - private static List makeSearchPathList(String [] searchPaths) + private static List makeSearchPathList(String[] searchPaths) { if ((searchPaths != null) && (searchPaths.length > 0)) { @@ -232,9 +254,11 @@ /** * SiteView - validating constructor - * - * @param pageManager PageManager component instance - * @param searchPaths string of comma separated search paths + * + * @param pageManager + * PageManager component instance + * @param searchPaths + * string of comma separated search paths */ public SiteView(PageManager pageManager, String searchPaths) { @@ -243,30 +267,35 @@ /** * makeSearchPathList - construct from string - * - * @param searchPaths string of comma separated search paths + * + * @param searchPaths + * string of comma separated search paths * @return search path list */ private static List makeSearchPathList(String searchPaths) { - return ((searchPaths != null) ? makeSearchPathList(searchPaths.split(",")) : null); + return ((searchPaths != null) ? makeSearchPathList(searchPaths + .split(",")) : null); } /** * SiteView - validating constructor - * - * @param pageManager PageManager component instance - * @param locator profile locator search specification + * + * @param pageManager + * PageManager component instance + * @param locator + * profile locator search specification */ public SiteView(PageManager pageManager, ProfileLocator locator) { this(pageManager, makeSearchPathList(locator)); } - + /** * makeSearchPathList - construct from profile locator - * - * @param locator profile locator search specification + * + * @param locator + * profile locator search specification * @return search path list */ private static List makeSearchPathList(ProfileLocator locator) @@ -274,26 +303,30 @@ if (locator != null) { // generate and return locator search paths - return mergeSearchPathList(ProfileLocator.PAGE_LOCATOR, locator, new ArrayList(8)); + return mergeSearchPathList(ProfileLocator.PAGE_LOCATOR, locator, + new ArrayList(8)); } return null; } /** * SiteView - validating constructor - * - * @param pageManager PageManager component instance - * @param locators map of named profile locator search specifications + * + * @param pageManager + * PageManager component instance + * @param locators + * map of named profile locator search specifications */ public SiteView(PageManager pageManager, Map locators) { this(pageManager, makeSearchPathList(locators)); } - + /** * makeSearchPathList - construct from profile locators - * - * @param locators map of named profile locator search specifications + * + * @param locators + * map of named profile locator search specifications * @return search path list */ private static List makeSearchPathList(Map locators) @@ -305,22 +338,26 @@ // having priority, (all other named locators are processed // subsequent to 'page' in unspecified order). List searchPaths = new ArrayList(8 * locators.size()); - ProfileLocator pageLocator = (ProfileLocator)locators.get(ProfileLocator.PAGE_LOCATOR); + ProfileLocator pageLocator = (ProfileLocator) locators + .get(ProfileLocator.PAGE_LOCATOR); if (pageLocator != null) { // add priority 'page' locator search paths - mergeSearchPathList(ProfileLocator.PAGE_LOCATOR, pageLocator, searchPaths); + mergeSearchPathList(ProfileLocator.PAGE_LOCATOR, pageLocator, + searchPaths); } if ((pageLocator == null) || (locators.size() > 1)) { Iterator locatorNameIter = locators.keySet().iterator(); while (locatorNameIter.hasNext()) { - String locatorName = (String)locatorNameIter.next(); + String locatorName = (String) locatorNameIter.next(); if (!locatorName.equals(ProfileLocator.PAGE_LOCATOR)) { // add alternate locator search paths - mergeSearchPathList(locatorName, (ProfileLocator)locators.get(locatorName), searchPaths); + mergeSearchPathList(locatorName, + (ProfileLocator) locators.get(locatorName), + searchPaths); } } } @@ -328,16 +365,20 @@ } return null; } - + /** * mergeSearchPathList - append search paths from profile locator - * - * @param locatorName name of profile locator - * @param locator profile locator search specification - * @param searchPaths list of search paths to merge into + * + * @param locatorName + * name of profile locator + * @param locator + * profile locator search specification + * @param searchPaths + * list of search paths to merge into * @return search path list */ - private static List mergeSearchPathList(String locatorName, ProfileLocator locator, List searchPaths) + private static List mergeSearchPathList(String locatorName, + ProfileLocator locator, List searchPaths) { // generate profile locator search paths with locator // names to be used later for node identification and @@ -369,7 +410,8 @@ int skipProfileLocatorIterations = -1; // form locator properties into a complete path - ProfileLocatorProperty [] properties = (ProfileLocatorProperty []) locatorIter.next(); + ProfileLocatorProperty[] properties = (ProfileLocatorProperty[]) locatorIter + .next(); for (int i = 0; (i < properties.length); i++) { if (properties[i].isNavigation()) @@ -386,26 +428,34 @@ pathRoot = properties[i].getValue(); if (!pathRoot.startsWith(Folder.PATH_SEPARATOR)) { - pathRoot = Folder.PATH_SEPARATOR + pathRoot; + pathRoot = Folder.PATH_SEPARATOR + pathRoot; } if (!pathRoot.endsWith(Folder.PATH_SEPARATOR)) { - pathRoot += Folder.PATH_SEPARATOR; + pathRoot += Folder.PATH_SEPARATOR; } if (!pathRoot.equals(Folder.PATH_SEPARATOR)) { int folderIndex = 1; do { - if (!pathRoot.regionMatches(folderIndex, Folder.RESERVED_SUBSITE_FOLDER_PREFIX, 0, Folder.RESERVED_SUBSITE_FOLDER_PREFIX.length())) + if (!pathRoot.regionMatches(folderIndex, + Folder.RESERVED_SUBSITE_FOLDER_PREFIX, + 0, + Folder.RESERVED_SUBSITE_FOLDER_PREFIX + .length())) { - pathRoot = pathRoot.substring(0, folderIndex) + Folder.RESERVED_SUBSITE_FOLDER_PREFIX + pathRoot.substring(folderIndex); + pathRoot = pathRoot.substring(0, + folderIndex) + + Folder.RESERVED_SUBSITE_FOLDER_PREFIX + + pathRoot.substring(folderIndex); } - folderIndex = pathRoot.indexOf(Folder.PATH_SEPARATOR, folderIndex) + 1; - } - while ((folderIndex != -1) && (folderIndex != pathRoot.length())); + folderIndex = pathRoot.indexOf( + Folder.PATH_SEPARATOR, folderIndex) + 1; + } while ((folderIndex != -1) + && (folderIndex != pathRoot.length())); } - + // reset locator paths using new prefix pathDepth = 0; paths.clear(); @@ -420,7 +470,8 @@ } else { - // make sure multiple trailing null valued properties are + // make sure multiple trailing null valued properties + // are // ignored if more than one is present by advancing // the profile locator iterator skipProfileLocatorIterations++; @@ -433,48 +484,63 @@ { // fold control names to lower case; preserve // value case as provided by profiler - String propertyName = properties[i].getName().toLowerCase(); + String propertyName = properties[i].getName() + .toLowerCase(); String propertyValue = properties[i].getValue(); - // detect duplicate control names which indicates multiple - // values: must duplicate locator paths for each value; different - // control values are simply appended to all locator paths + // detect duplicate control names which indicates + // multiple + // values: must duplicate locator paths for each value; + // different + // control values are simply appended to all locator + // paths if (propertyName.equals(lastPropertyName)) { - // duplicate last locator paths set, stripping last matching - // control value from each, appending new value, and adding new + // duplicate last locator paths set, stripping last + // matching + // control value from each, appending new value, and + // adding new // valued set to collection of paths - ArrayList multipleValuePaths = new ArrayList(lastPathsCount); + ArrayList multipleValuePaths = new ArrayList( + lastPathsCount); Iterator pathsIter = paths.iterator(); for (int count = 0; (pathsIter.hasNext() && (count < lastPathsCount)); count++) { - StringBuffer path = (StringBuffer) pathsIter.next(); - StringBuffer multipleValuePath = new StringBuffer(path.toString()); - multipleValuePath.setLength(multipleValuePath.length() - lastPropertyValueLength - 1); + StringBuffer path = (StringBuffer) pathsIter + .next(); + StringBuffer multipleValuePath = new StringBuffer( + path.toString()); + multipleValuePath.setLength(multipleValuePath + .length() + - lastPropertyValueLength - 1); multipleValuePath.append(propertyValue); - multipleValuePath.append(Folder.PATH_SEPARATOR_CHAR); + multipleValuePath + .append(Folder.PATH_SEPARATOR_CHAR); multipleValuePaths.add(multipleValuePath); } paths.addAll(multipleValuePaths); // make sure trailing multiple valued properties are // ignored by advancing the profile locator iterator - // which is reset for each unique property value sets + // which is reset for each unique property value + // sets skipProfileLocatorIterations++; } else { - // construct locator path folders with control properties + // construct locator path folders with control + // properties Iterator pathsIter = paths.iterator(); while (pathsIter.hasNext()) { - StringBuffer path = (StringBuffer) pathsIter.next(); + StringBuffer path = (StringBuffer) pathsIter + .next(); path.append(Folder.RESERVED_FOLDER_PREFIX); path.append(propertyName); path.append(Folder.PATH_SEPARATOR_CHAR); path.append(propertyValue); path.append(Folder.PATH_SEPARATOR_CHAR); } - + // reset last locator property vars pathDepth++; lastPathsCount = paths.size(); @@ -487,7 +553,8 @@ } else { - // make sure multiple trailing null valued properties are + // make sure multiple trailing null valued properties + // are // ignored along with the last property values if more // than one is present by advancing the profile locator // iterator @@ -502,9 +569,10 @@ skipProfileLocatorIterations++; } } - + // if required, advance profile locator iterations - for (int skip = skipProfileLocatorIterations; ((skip > 0) && (locatorIter.hasNext())); skip--) + for (int skip = skipProfileLocatorIterations; ((skip > 0) && (locatorIter + .hasNext())); skip--) { locatorIter.next(); } @@ -520,7 +588,8 @@ } if ((pathDepth == 1) && !navigatedPathRoot) { - locatorSearchPaths.add(addLocatorSearchPathsAt++, new StringBuffer(pathRoot)); + locatorSearchPaths.add(addLocatorSearchPathsAt++, + new StringBuffer(pathRoot)); } // reset locator search path ordering since navigated root @@ -530,11 +599,12 @@ { addLocatorSearchPathsAt = 0; } - + // if end of locator path group and have not navigated to // a new root path or there are no more locator iterations, // insert the paths into the search path results - if (((pathDepth <= 1) && !navigatedPathRoot) || !locatorIter.hasNext()) + if (((pathDepth <= 1) && !navigatedPathRoot) + || !locatorIter.hasNext()) { // add locator paths to unique search paths preserving // search order; move non-unique paths to end of search @@ -543,12 +613,14 @@ Iterator locatorSearchPathsIter = locatorSearchPaths.iterator(); while (locatorSearchPathsIter.hasNext()) { - SiteViewSearchPath searchPath = new SiteViewSearchPath(locatorName, locatorSearchPathsIter.next().toString()); + SiteViewSearchPath searchPath = new SiteViewSearchPath( + locatorName, locatorSearchPathsIter.next() + .toString()); // test search path uniqueness int existsAt = searchPaths.indexOf(searchPath); if (existsAt != -1) { - if (existsAt < (searchPaths.size()-1)) + if (existsAt < (searchPaths.size() - 1)) { // push existing search path to end of paths searchPaths.add(searchPaths.remove(existsAt)); @@ -571,17 +643,18 @@ /** * SiteView - basic constructor - * - * @param pageManager PageManager component instance + * + * @param pageManager + * PageManager component instance */ public SiteView(PageManager pageManager) { - this(pageManager, (List)null); + this(pageManager, (List) null); } /** * getPageManager - return PageManager component instance - * + * * @return PageManager instance */ public PageManager getPageManager() @@ -590,9 +663,8 @@ } /** - * getSearchPaths - return ordered search paths list that - * defines this view - * + * getSearchPaths - return ordered search paths list that defines this view + * * @return search paths list */ public List getSearchPaths() @@ -602,7 +674,7 @@ /** * getSearchPathsString - return search paths as string - * + * * @return search paths list as comma separated string */ public String getSearchPathsString() @@ -612,10 +684,12 @@ /** * getRootFolderProxy - create and return root folder proxy instance - * + * * @return root folder proxy - * @throws FolderNotFoundException if not found - * @throws SecurityException if view access not granted + * @throws FolderNotFoundException + * if not found + * @throws SecurityException + * if view access not granted */ public Folder getRootFolderProxy() throws FolderNotFoundException { @@ -627,24 +701,28 @@ // the folder and profile locator name of the root // folder proxy in the view is the locator name of the // first search path since search paths are valid - SiteViewSearchPath searchPath = (SiteViewSearchPath)searchPaths.get(0); + SiteViewSearchPath searchPath = (SiteViewSearchPath) searchPaths + .get(0); String path = searchPath.toString(); String locatorName = searchPath.getLocatorName(); // get concrete root folder from page manager // and construct proxy Folder rootFolder = pageManager.getFolder(path); - rootFolderProxy = FolderProxy.newInstance(this, locatorName, null, rootFolder); + rootFolderProxy = FolderProxy.newInstance(this, locatorName, + null, rootFolder); } catch (NodeException ne) { - FolderNotFoundException fnfe = new FolderNotFoundException("Root folder not found"); + FolderNotFoundException fnfe = new FolderNotFoundException( + "Root folder not found"); fnfe.initCause(ne); throw fnfe; } catch (NodeNotFoundException nnfe) { - FolderNotFoundException fnfe = new FolderNotFoundException("Root folder not found"); + FolderNotFoundException fnfe = new FolderNotFoundException( + "Root folder not found"); fnfe.initCause(nnfe); throw fnfe; } @@ -653,18 +731,26 @@ } /** - * getNodeProxy - get single folder, page, or link proxy - * at relative or absolute path - * - * @param path single node path - * @param currentNode current folder or page for relative paths or null - * @param onlyViewable node required to be viewable - * @param onlyVisible node required to be visible, (or current) + * getNodeProxy - get single folder, page, or link proxy at relative or + * absolute path + * + * @param path + * single node path + * @param currentNode + * current folder or page for relative paths or null + * @param onlyViewable + * node required to be viewable + * @param onlyVisible + * node required to be visible, (or current) * @return folder, page, or link node proxy - * @throws NodeNotFoundException if not found - * @throws SecurityException if view access not granted + * @throws NodeNotFoundException + * if not found + * @throws SecurityException + * if view access not granted */ - public Node getNodeProxy(String path, Node currentNode, boolean onlyViewable, boolean onlyVisible) throws NodeNotFoundException + public Node getNodeProxy(String path, Node currentNode, + boolean onlyViewable, boolean onlyVisible) + throws NodeNotFoundException { // determine current folder and page String currentPath = path; @@ -672,16 +758,17 @@ Page currentPage = null; if (currentNode instanceof Page) { - currentPage = (Page)currentNode; - currentFolder = (Folder)currentPage.getParent(); + currentPage = (Page) currentNode; + currentFolder = (Folder) currentPage.getParent(); } else if (currentNode instanceof Folder) { - currentFolder = (Folder)currentNode; + currentFolder = (Folder) currentNode; } // match current page path - if (currentPath.equals(CURRENT_PAGE_PATH) || currentPath.equals(ALT_CURRENT_PAGE_PATH)) + if (currentPath.equals(CURRENT_PAGE_PATH) + || currentPath.equals(ALT_CURRENT_PAGE_PATH)) { // return current page if specified, (assume viewable) return currentPage; @@ -699,8 +786,9 @@ currentFolder = getRootFolderProxy(); } - // search for path based on current folder - while ((currentPath.length() > 0) && !currentPath.equals(Folder.PATH_SEPARATOR)) + // search for path based on current folder + while ((currentPath.length() > 0) + && !currentPath.equals(Folder.PATH_SEPARATOR)) { // parse relative sub-folder from path int separatorIndex = currentPath.indexOf(Folder.PATH_SEPARATOR); @@ -709,17 +797,18 @@ // isolate sub-folder and continue search // using remaining paths String subfolder = currentPath.substring(0, separatorIndex); - currentPath = currentPath.substring(separatorIndex+1); + currentPath = currentPath.substring(separatorIndex + 1); if (subfolder.equals("..")) { // adjust current folder if parent exists if (currentFolder.getParent() != null) { - currentFolder = (Folder)currentFolder.getParent(); + currentFolder = (Folder) currentFolder.getParent(); } else { - throw new NodeNotFoundException("Specified path " + path + " not found."); + throw new NodeNotFoundException("Specified path " + + path + " not found."); } } else if (!subfolder.equals(".")) @@ -732,13 +821,15 @@ } catch (NodeException ne) { - NodeNotFoundException nnfe = new NodeNotFoundException("Specified path " + path + " not found."); + NodeNotFoundException nnfe = new NodeNotFoundException( + "Specified path " + path + " not found."); nnfe.initCause(ne); throw nnfe; } catch (NodeNotFoundException nnfe) { - NodeNotFoundException nnfeWrapper = new NodeNotFoundException("Specified path " + path + " not found."); + NodeNotFoundException nnfeWrapper = new NodeNotFoundException( + "Specified path " + path + " not found."); nnfeWrapper.initCause(nnfe); throw nnfeWrapper; } @@ -755,45 +846,48 @@ if (children != null) { Node node = children.get(currentPath); - if ((node != null) && (!onlyVisible || !node.isHidden() || (node == currentPage)) && - (!onlyViewable || isProxyViewable(node, onlyVisible))) - { - return node; - } + if ((node != null) + && (!onlyVisible || !node.isHidden() || (node == currentPage)) + && (!onlyViewable || isProxyViewable(node, + onlyVisible))) { return node; } } } catch (NodeException ne) { - NodeNotFoundException nnfe = new NodeNotFoundException("Specified path " + path + " not found."); + NodeNotFoundException nnfe = new NodeNotFoundException( + "Specified path " + path + " not found."); nnfe.initCause(ne); throw nnfe; } - throw new NodeNotFoundException("Specified path " + path + " not found or viewable/visible."); + throw new NodeNotFoundException("Specified path " + path + + " not found or viewable/visible."); } } // path maps to current folder; return if viewable/visible // or visibility not required - if ((!onlyVisible || !currentFolder.isHidden()) && - (!onlyViewable || isProxyViewable(currentFolder, onlyVisible))) - { - return currentFolder; - } - throw new NodeNotFoundException("Specified path " + path + " not found or viewable/visible."); + if ((!onlyVisible || !currentFolder.isHidden()) + && (!onlyViewable || isProxyViewable(currentFolder, onlyVisible))) { return currentFolder; } + throw new NodeNotFoundException("Specified path " + path + + " not found or viewable/visible."); } /** - * getNodeProxies - get folder, page, or link proxies at - * relative or absolute path using simple path - * wildcards and character classes - * - * @param regexpPath regular expression node path - * @param currentNode current folder or page for relative paths or null - * @param onlyViewable nodes required to be viewable flag - * @param onlyVisible node required to be visible, (or current) + * getNodeProxies - get folder, page, or link proxies at relative or + * absolute path using simple path wildcards and character classes + * + * @param regexpPath + * regular expression node path + * @param currentNode + * current folder or page for relative paths or null + * @param onlyViewable + * nodes required to be viewable flag + * @param onlyVisible + * node required to be visible, (or current) * @return list of folder, page, or link node proxies */ - public List getNodeProxies(String regexpPath, Node currentNode, boolean onlyViewable, boolean onlyVisible) + public List getNodeProxies(String regexpPath, Node currentNode, + boolean onlyViewable, boolean onlyVisible) { // determine current folder and page String currentRegexpPath = regexpPath; @@ -801,16 +895,17 @@ Page currentPage = null; if (currentNode instanceof Page) { - currentPage = (Page)currentNode; - currentFolder = (Folder)currentPage.getParent(); + currentPage = (Page) currentNode; + currentFolder = (Folder) currentPage.getParent(); } else if (currentNode instanceof Folder) { - currentFolder = (Folder)currentNode; + currentFolder = (Folder) currentNode; } // match current page path - if (currentRegexpPath.equals(CURRENT_PAGE_PATH) || currentRegexpPath.equals(ALT_CURRENT_PAGE_PATH)) + if (currentRegexpPath.equals(CURRENT_PAGE_PATH) + || currentRegexpPath.equals(ALT_CURRENT_PAGE_PATH)) { if (currentPage != null) { @@ -849,23 +944,27 @@ } } - // search for path based on current folder - while ((currentRegexpPath.length() > 0) && !currentRegexpPath.equals(Folder.PATH_SEPARATOR)) + // search for path based on current folder + while ((currentRegexpPath.length() > 0) + && !currentRegexpPath.equals(Folder.PATH_SEPARATOR)) { // parse relative sub-folder from path - int separatorIndex = currentRegexpPath.indexOf(Folder.PATH_SEPARATOR); + int separatorIndex = currentRegexpPath + .indexOf(Folder.PATH_SEPARATOR); if (separatorIndex != -1) { // isolate sub-folder and continue search // using remaining paths - String subfolder = currentRegexpPath.substring(0, separatorIndex); - currentRegexpPath = currentRegexpPath.substring(separatorIndex+1); + String subfolder = currentRegexpPath.substring(0, + separatorIndex); + currentRegexpPath = currentRegexpPath + .substring(separatorIndex + 1); if (subfolder.equals("..")) { // adjust current folder if parent exists if (currentFolder.getParent() != null) { - currentFolder = (Folder)currentFolder.getParent(); + currentFolder = (Folder) currentFolder.getParent(); } else { @@ -884,28 +983,40 @@ NodeSet subfolders = currentFolder.getFolders(); if (subfolders != null) { - subfolders = subfolders.inclusiveSubset(subfolderPattern); + subfolders = subfolders + .inclusiveSubset(subfolderPattern); if (subfolders != null) { - // recursively process sub-folders if more than - // one match, access single sub-folder, or return + // recursively process sub-folders if more + // than + // one match, access single sub-folder, or + // return // null if nonexistent if (subfolders.size() > 1) { - // recursively process matching sub-folders + // recursively process matching + // sub-folders List proxies = null; - Iterator subfoldersIter = subfolders.iterator(); + Iterator subfoldersIter = subfolders + .iterator(); while (subfoldersIter.hasNext()) { - currentFolder = (Folder)subfoldersIter.next(); - List subfolderProxies = getNodeProxies(currentRegexpPath, currentFolder, onlyViewable, onlyVisible); - if ((subfolderProxies != null) && !subfolderProxies.isEmpty()) + currentFolder = (Folder) subfoldersIter + .next(); + List subfolderProxies = getNodeProxies( + currentRegexpPath, + currentFolder, + onlyViewable, onlyVisible); + if ((subfolderProxies != null) + && !subfolderProxies + .isEmpty()) { if (proxies == null) { proxies = new ArrayList(); } - proxies.addAll(subfolderProxies); + proxies + .addAll(subfolderProxies); } } return proxies; @@ -913,7 +1024,8 @@ else if (subfolders.size() == 1) { // access single sub-folder - currentFolder = (Folder)subfolders.iterator().next(); + currentFolder = (Folder) subfolders + .iterator().next(); } else { @@ -970,7 +1082,8 @@ if (pathPattern != null) { // copy children matching remaining path pattern as - // page, folder, or link proxies if viewable/visible or + // page, folder, or link proxies if viewable/visible + // or // visibilty not required children = children.inclusiveSubset(pathPattern); if ((children != null) && !children.isEmpty()) @@ -979,13 +1092,15 @@ Iterator childrenIter = children.iterator(); while (childrenIter.hasNext()) { - Node child = (Node)childrenIter.next(); - if ((!onlyVisible || !child.isHidden() || (child == currentPage)) && - (!onlyViewable || isProxyViewable(child, onlyVisible))) + Node child = (Node) childrenIter.next(); + if ((!onlyVisible || !child.isHidden() || (child == currentPage)) + && (!onlyViewable || isProxyViewable( + child, onlyVisible))) { if (proxies == null) { - proxies = new ArrayList(children.size()); + proxies = new ArrayList(children + .size()); } proxies.add(child); } @@ -999,8 +1114,10 @@ // node proxy; return null if not found or not // viewable and visiblity is required Node child = children.get(currentRegexpPath); - if ((child != null) && (!onlyVisible || !child.isHidden() || (child == currentPage)) && - (!onlyViewable || isProxyViewable(child, onlyVisible))) + if ((child != null) + && (!onlyVisible || !child.isHidden() || (child == currentPage)) + && (!onlyViewable || isProxyViewable(child, + onlyVisible))) { List proxies = new ArrayList(1); proxies.add(currentFolder); @@ -1008,7 +1125,7 @@ } } } - + } catch (NodeException ne) { @@ -1024,8 +1141,8 @@ // path maps to current folder; return if viewable/visible // or visibility not required - if ((!onlyVisible || !currentFolder.isHidden()) && - (!onlyViewable || isProxyViewable(currentFolder, onlyVisible))) + if ((!onlyVisible || !currentFolder.isHidden()) + && (!onlyViewable || isProxyViewable(currentFolder, onlyVisible))) { List proxies = new ArrayList(1); proxies.add(currentFolder); @@ -1035,11 +1152,11 @@ } /** - * pathRegexpPattern - tests for and converts simple path wildcard - * and character class regular exressions to - * perl5/standard java pattern syntax - * - * @param regexp - candidate path regular expression + * pathRegexpPattern - tests for and converts simple path wildcard and + * character class regular exressions to perl5/standard java pattern syntax + * + * @param regexp - + * candidate path regular expression * @return - converted pattern or null if no regular expression */ private static String pathRegexpPattern(String regexp) @@ -1051,51 +1168,52 @@ char regexpChar = regexp.charAt(i); switch (regexpChar) { + case '*': + case '.': + case '?': + case '[': + if (pattern == null) + { + pattern = new StringBuffer(regexp.length() * 2); + pattern.append(regexp.substring(0, i)); + } + switch (regexpChar) + { case '*': + pattern.append(".*"); + break; case '.': + pattern.append("\\."); + break; case '?': + pattern.append('.'); + break; case '[': - if (pattern == null) - { - pattern = new StringBuffer(regexp.length()*2); - pattern.append(regexp.substring(0, i)); - } - switch (regexpChar) - { - case '*': - pattern.append(".*"); - break; - case '.': - pattern.append("\\."); - break; - case '?': - pattern.append('.'); - break; - case '[': - pattern.append('['); - break; - } + pattern.append('['); break; - default: - if (pattern != null) - { - pattern.append(regexpChar); - } - break; + } + break; + default: + if (pattern != null) + { + pattern.append(regexpChar); + } + break; } } // return converted pattern or null if not a regular expression - if (pattern != null) - return pattern.toString(); + if (pattern != null) return pattern.toString(); return null; } /** * isProxyViewable - tests for node proxy visibility in view - * - * @param nodeProxy test node proxy - * @param onlyVisible nodes required to be visible + * + * @param nodeProxy + * test node proxy + * @param onlyVisible + * nodes required to be visible * @return - viewable flag */ private static boolean isProxyViewable(Node nodeProxy, boolean onlyVisible) @@ -1113,11 +1231,9 @@ Iterator childrenIter = children.iterator(); while (childrenIter.hasNext()) { - Node child = (Node)childrenIter.next(); - if ((!onlyVisible || !child.isHidden()) && isProxyViewable(child, onlyVisible)) - { - return true; - } + Node child = (Node) childrenIter.next(); + if ((!onlyVisible || !child.isHidden()) + && isProxyViewable(child, onlyVisible)) { return true; } } } } @@ -1134,7 +1250,7 @@ /** * getStandardMenuNames - get set of available standard menu names - * + * * @return menu names set */ public Set getStandardMenuNames() @@ -1144,9 +1260,9 @@ } /** - * getStandardMenuDefinitionLocators - get list of available standard - * menu definition locators - * + * getStandardMenuDefinitionLocators - get list of available standard menu + * definition locators + * * @return menu definition locators list */ public List getStandardMenuDefinitionLocators() @@ -1156,12 +1272,12 @@ } /** - * getMenuDefinitionLocators - get list of view node proxy menu - * definition locators; implemented here - * to hide view proxy manipulation from - * more general portal site implementation - * - * @param node node proxy + * getMenuDefinitionLocators - get list of view node proxy menu definition + * locators; implemented here to hide view proxy manipulation from more + * general portal site implementation + * + * @param node + * node proxy * @return definition locator list */ public List getMenuDefinitionLocators(Node node) @@ -1169,70 +1285,63 @@ // access node proxy from specified node and // return associated definition locators NodeProxy nodeProxy = NodeProxy.getNodeProxy(node); - if (nodeProxy != null) - { - return nodeProxy.getMenuDefinitionLocators(); - } + if (nodeProxy != null) { return nodeProxy.getMenuDefinitionLocators(); } return null; } /** - * getMenuDefinitionLocator - get named view node proxy menu - * definition locator; implemented here - * to hide view proxy manipulation from - * more general portal site implementation - * - * @param node node proxy - * @param name menu definition name + * getMenuDefinitionLocator - get named view node proxy menu definition + * locator; implemented here to hide view proxy manipulation from more + * general portal site implementation + * + * @param node + * node proxy + * @param name + * menu definition name * @return menu definition locator */ - public SiteViewMenuDefinitionLocator getMenuDefinitionLocator(Node node, String name) + public SiteViewMenuDefinitionLocator getMenuDefinitionLocator(Node node, + String name) { // access node proxy from specified node and // return associated definition locators NodeProxy nodeProxy = NodeProxy.getNodeProxy(node); - if (nodeProxy != null) - { - return nodeProxy.getMenuDefinitionLocator(name); - } + if (nodeProxy != null) { return nodeProxy + .getMenuDefinitionLocator(name); } return null; } /** * getProfileLocatorName - get view node proxy profile locator name; - * implemented here to hide view proxy manipulation - * from more general portal site implementation - * - * @param node node proxy + * implemented here to hide view proxy manipulation from more general portal + * site implementation + * + * @param node + * node proxy * @return profile locator name */ public String getProfileLocatorName(Node node) { SiteViewProxy siteViewProxy = SiteViewProxy.getSiteViewProxy(node); - if (siteViewProxy != null) - { - return siteViewProxy.getLocatorName(); - } + if (siteViewProxy != null) { return siteViewProxy.getLocatorName(); } return null; } /** - * getManagedPage - get concrete page instance from page proxy; - * implemented here to hide view proxy manipulation - * from more general portal site implementation - * - * @param page page proxy + * getManagedPage - get concrete page instance from page proxy; implemented + * here to hide view proxy manipulation from more general portal site + * implementation + * + * @param page + * page proxy * @return managed page */ public Page getManagedPage(Page page) { // access page proxy from specified page and // return associated delegate managed page - PageProxy pageProxy = (PageProxy)NodeProxy.getNodeProxy(page); - if (pageProxy != null) - { - return pageProxy.getPage(); - } + PageProxy pageProxy = (PageProxy) NodeProxy.getNodeProxy(page); + if (pageProxy != null) { return pageProxy.getPage(); } return null; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteViewMenuDefinitionLocator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteViewMenuDefinitionLocator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteViewMenuDefinitionLocator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,19 +20,20 @@ import org.apache.jetspeed.page.document.Node; /** - * This class represents a menu definition locator that is - * comprised of the menu name, (the full definition is saved - * here from convenience), and concrete path of the - * defining folder or page. + * This class represents a menu definition locator that is comprised of the menu + * name, (the full definition is saved here from convenience), and concrete path + * of the defining folder or page. * * @author Randy Watler - * @version $Id: SiteViewMenuDefinitionLocator.java 517121 2007-03-12 07:45:49Z ate $ + * @version $Id: SiteViewMenuDefinitionLocator.java 517121 2007-03-12 07:45:49Z + * ate $ */ public class SiteViewMenuDefinitionLocator { + /** - * locator - locator string defined for menu containing - * menu name and concrete path of defining node + * locator - locator string defined for menu containing menu name and + * concrete path of defining node */ private String locator; @@ -43,11 +44,14 @@ /** * SiteViewMenuDefinitionLocator - custom menu definition constructor - * - * @param menuDefinition custom menu definition - * @param definingNode defining page or folder + * + * @param menuDefinition + * custom menu definition + * @param definingNode + * defining page or folder */ - public SiteViewMenuDefinitionLocator(MenuDefinition menuDefinition, Node definingNode) + public SiteViewMenuDefinitionLocator(MenuDefinition menuDefinition, + Node definingNode) { this.menuDefinition = menuDefinition; this.locator = definingNode.getPath() + "|" + menuDefinition.getName(); @@ -55,8 +59,9 @@ /** * SiteViewMenuDefinitionLocator - standard menu definition constructor - * - * @param menuDefinition standard menu definition + * + * @param menuDefinition + * standard menu definition */ public SiteViewMenuDefinitionLocator(MenuDefinition menuDefinition) { @@ -66,7 +71,7 @@ /** * toString - return locator - * + * * @return search path */ public String toString() @@ -76,21 +81,18 @@ /** * equals - compare as string to locator - * + * * @return equals result */ public boolean equals(Object obj) { - if (obj instanceof String) - { - return locator.equals(obj); - } + if (obj instanceof String) { return locator.equals(obj); } return locator.equals(obj.toString()); } /** * hashCode - return search path hash code - * + * * @return hash code */ public int hashCode() @@ -100,7 +102,7 @@ /** * getMenuDefinition - return menu definition - * + * * @return menu definition */ public MenuDefinition getMenuDefinition() @@ -110,7 +112,7 @@ /** * getName - return name of menu definition - * + * * @return menu definition name */ public String getName() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteViewProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteViewProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteViewProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,33 +20,33 @@ import java.lang.reflect.Proxy; /** - * This class is the base class for all site content - * proxy implementations. + * This class is the base class for all site content proxy implementations. * * @author Randy Watler * @version $Id: SiteViewProxy.java 516448 2007-03-09 16:25:47Z ate $ */ public abstract class SiteViewProxy { + /** * view - site view this proxy is part of */ private SiteView view; /** - * locatorName - name of profile locator name associated - * with the derived delegate of this proxy - * in the site view + * locatorName - name of profile locator name associated with the derived + * delegate of this proxy in the site view */ private String locatorName; /** * SiteViewProxy - constructor - * - * @param view site view owner of this proxy - * @param locatorName profile locator name associated with - * the derived delegate of this proxy in - * the site view + * + * @param view + * site view owner of this proxy + * @param locatorName + * profile locator name associated with the derived delegate of + * this proxy in the site view */ protected SiteViewProxy(SiteView view, String locatorName) { @@ -56,7 +56,7 @@ /** * getView - return site view for this proxy - * + * * @return site view */ public SiteView getView() @@ -65,10 +65,9 @@ } /** - * getLocatorName - return profile locator name associated - * with the derived delegate of this proxy in - * the site view - * + * getLocatorName - return profile locator name associated with the derived + * delegate of this proxy in the site view + * * @return profile locator name */ public String getLocatorName() @@ -78,12 +77,16 @@ /** * reflectMethod - trap method reflection exceptions utility function - * - * @param methodClass class or interface - * @param methodName method name - * @param methodArgs array of type, class, or interface parameter types + * + * @param methodClass + * class or interface + * @param methodName + * method name + * @param methodArgs + * array of type, class, or interface parameter types */ - protected static Method reflectMethod(Class methodClass, String methodName, Class [] methodArgs) + protected static Method reflectMethod(Class methodClass, String methodName, + Class[] methodArgs) { // trap reflection exceptions try @@ -92,17 +95,20 @@ } catch (NoSuchMethodException nsme) { - RuntimeException rte = new RuntimeException("SiteViewProxy.reflectMethod(): unexpected reflection exception for: " + methodClass.getName() + "." + methodName); + RuntimeException rte = new RuntimeException( + "SiteViewProxy.reflectMethod(): unexpected reflection exception for: " + + methodClass.getName() + "." + methodName); rte.initCause(nsme); throw rte; } } /** - * getSiteViewProxy - utility method to access SiteViewProxy handler - * from a proxy instance - * - * @param proxy proxy instance + * getSiteViewProxy - utility method to access SiteViewProxy handler from a + * proxy instance + * + * @param proxy + * proxy instance * @return site view invocation handler instance */ public static SiteViewProxy getSiteViewProxy(Object proxy) @@ -110,10 +116,7 @@ if ((proxy != null) && Proxy.isProxyClass(proxy.getClass())) { Object proxyHandler = Proxy.getInvocationHandler(proxy); - if (proxyHandler instanceof SiteViewProxy) - { - return (SiteViewProxy)proxyHandler; - } + if (proxyHandler instanceof SiteViewProxy) { return (SiteViewProxy) proxyHandler; } } return null; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteViewSearchPath.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteViewSearchPath.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/java/org/apache/jetspeed/portalsite/view/SiteViewSearchPath.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,16 +19,16 @@ import org.apache.jetspeed.om.folder.Folder; /** - * This class represents a search path along with a profile - * locator name used to construct the logical site view. The - * profiler locator name is uses to identify and group - * located nodes within the view. + * This class represents a search path along with a profile locator name used to + * construct the logical site view. The profiler locator name is uses to + * identify and group located nodes within the view. * * @author Randy Watler * @version $Id: SiteViewSearchPath.java 517121 2007-03-12 07:45:49Z ate $ */ public class SiteViewSearchPath { + /** * locatorName - profile locator name */ @@ -41,17 +41,20 @@ /** * SiteViewSearchPath - validating constructor that strips any trailing - * folder separator from search path - * - * @param locatorName profile locator name - * @param searchPath search path + * folder separator from search path + * + * @param locatorName + * profile locator name + * @param searchPath + * search path */ public SiteViewSearchPath(String locatorName, String searchPath) { this.locatorName = locatorName; - if (searchPath.endsWith(Folder.PATH_SEPARATOR) && !searchPath.equals(Folder.PATH_SEPARATOR)) + if (searchPath.endsWith(Folder.PATH_SEPARATOR) + && !searchPath.equals(Folder.PATH_SEPARATOR)) { - this.searchPath = searchPath.substring(0, searchPath.length()-1); + this.searchPath = searchPath.substring(0, searchPath.length() - 1); } else { @@ -61,7 +64,7 @@ /** * toString - return search path - * + * * @return search path */ public String toString() @@ -71,21 +74,18 @@ /** * equals - compare as string to search path - * + * * @return equals result */ public boolean equals(Object obj) { - if (obj instanceof String) - { - return searchPath.equals(obj); - } + if (obj instanceof String) { return searchPath.equals(obj); } return searchPath.equals(obj.toString()); } /** * hashCode - return search path hash code - * + * * @return hash code */ public int hashCode() @@ -95,7 +95,7 @@ /** * getLocatorName - return profile locator name - * + * * @return profile locator name */ public String getLocatorName() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/test/org/apache/jetspeed/portalsite/TestPortalSite.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/test/org/apache/jetspeed/portalsite/TestPortalSite.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portal-site/src/test/org/apache/jetspeed/portalsite/TestPortalSite.java 2008-05-16 01:54:54 UTC (rev 940) @@ -42,12 +42,13 @@ /** * TestPortalSite - * + * * @author Randy Watler * @version $Id: TestPortalSite.java 598577 2007-11-27 09:55:10Z woonsan $ */ public class TestPortalSite extends AbstractSpringTestCase { + /** * pageManager - PageManager component */ @@ -57,13 +58,15 @@ * portalSite - PortalSite component */ private PortalSite portalSite; - + /** * default locale */ private Locale defaultLocale; - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception @@ -75,7 +78,9 @@ Locale.setDefault(Locale.ENGLISH); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception @@ -86,17 +91,19 @@ /** * Start the tests. - * - * @param args the arguments. Not used + * + * @param args + * the arguments. Not used */ public static void main(String args[]) { - junit.awtui.TestRunner.main(new String[] {TestPortalSite.class.getName()}); + junit.awtui.TestRunner.main(new String[] + {TestPortalSite.class.getName()}); } /** * Define test suite. - * + * * @return the test suite */ public static Test suite() @@ -107,17 +114,18 @@ /** * Define configuration paths. - * + * * @return array of paths. */ protected String[] getConfigurations() { - return new String[] {"/JETSPEED-INF/spring/test-spring.xml"}; + return new String[] + {"/JETSPEED-INF/spring/test-spring.xml"}; } /** * testPageManagerSetup - Test PageManager test configuration - * + * * @throws Exception */ public void testPageManagerSetup() throws Exception @@ -127,10 +135,10 @@ assertNotNull(rootFolder); Page rootPage0 = pageManager.getPage("/page0.psml"); assertNotNull(rootPage0); - assertEquals(rootFolder.getPage("page0.psml"), rootPage0); - Link rootLink0 = pageManager.getLink("/link0.link"); + assertEquals(rootFolder.getPage("page0.psml"), rootPage0); + Link rootLink0 = pageManager.getLink("/link0.link"); assertNotNull(rootLink0); - assertEquals(rootFolder.getLink("link0.link"), rootLink0); + assertEquals(rootFolder.getLink("link0.link"), rootLink0); } public void testRelativeNavigations() throws Exception @@ -142,8 +150,9 @@ locator.add("user", true, false, "joe"); locator.add("page", false, false, "home"); SiteView profileView = new SiteView(pageManager, locator); - assertEquals("/_hostname/dash/_user/joe,/_hostname/dash,/", profileView.getSearchPathsString()); - + assertEquals("/_hostname/dash/_user/joe,/_hostname/dash,/", profileView + .getSearchPathsString()); + locator = new JetspeedProfileLocator(); locator.init(null, "/"); locator.add("hostname", true, false, "dash"); @@ -153,11 +162,13 @@ locator.add("role", true, false, "user"); locator.add("page", false, false, "home"); profileView = new SiteView(pageManager, locator); - assertEquals("/_hostname/dash/_user/joe,/_hostname/dash/_role/user,/_hostname/dash,/", profileView.getSearchPathsString()); - + assertEquals( + "/_hostname/dash/_user/joe,/_hostname/dash/_role/user,/_hostname/dash,/", + profileView.getSearchPathsString()); + locator = new JetspeedProfileLocator(); - //locator.init(null, "/__subsite-root"); - locator.init(null, "/"); + // locator.init(null, "/__subsite-root"); + locator.init(null, "/"); locator.add("navigation", false, true, "subsite-root"); locator.add("hostname", true, false, "localhost"); locator.add("user", true, false, "sublocal"); @@ -166,12 +177,14 @@ locator.add("role", true, false, "somerole"); locator.add("path", false, false, "home"); profileView = new SiteView(pageManager, locator); - assertEquals("/__subsite-root/_hostname/localhost/_user/sublocal,/__subsite-root/_hostname/localhost/_role/somerole,/__subsite-root/_hostname/localhost,/__subsite-root", profileView.getSearchPathsString()); + assertEquals( + "/__subsite-root/_hostname/localhost/_user/sublocal,/__subsite-root/_hostname/localhost/_role/somerole,/__subsite-root/_hostname/localhost,/__subsite-root", + profileView.getSearchPathsString()); } - + /** * testSiteView - Test SiteView operation - * + * * @throws Exception */ public void testSiteView() throws Exception @@ -186,25 +199,26 @@ assertEquals("/", extractFileSystemPathFromId(rootFolderProxy.getId())); assertEquals(4, rootFolderProxy.getFolders().size()); Iterator foldersIter = rootFolderProxy.getFolders().iterator(); - assertEquals("folder0", ((Folder)foldersIter.next()).getName()); - assertEquals("folder1", ((Folder)foldersIter.next()).getName()); - assertEquals("folder2", ((Folder)foldersIter.next()).getName()); - assertEquals("folder3", ((Folder)foldersIter.next()).getName()); + assertEquals("folder0", ((Folder) foldersIter.next()).getName()); + assertEquals("folder1", ((Folder) foldersIter.next()).getName()); + assertEquals("folder2", ((Folder) foldersIter.next()).getName()); + assertEquals("folder3", ((Folder) foldersIter.next()).getName()); assertEquals(4, rootFolderProxy.getPages().size()); Iterator pagesIter = rootFolderProxy.getPages().iterator(); - assertEquals("page2.psml", ((Page)pagesIter.next()).getName()); - assertEquals("page1.psml", ((Page)pagesIter.next()).getName()); - assertEquals("page0.psml", ((Page)pagesIter.next()).getName()); - assertEquals("hidden.psml", ((Page)pagesIter.next()).getName()); + assertEquals("page2.psml", ((Page) pagesIter.next()).getName()); + assertEquals("page1.psml", ((Page) pagesIter.next()).getName()); + assertEquals("page0.psml", ((Page) pagesIter.next()).getName()); + assertEquals("hidden.psml", ((Page) pagesIter.next()).getName()); assertEquals(2, rootFolderProxy.getLinks().size()); Iterator linksIter = rootFolderProxy.getLinks().iterator(); - assertEquals("link1.link", ((Link)linksIter.next()).getName()); - assertEquals("link0.link", ((Link)linksIter.next()).getName()); + assertEquals("link1.link", ((Link) linksIter.next()).getName()); + assertEquals("link0.link", ((Link) linksIter.next()).getName()); Page rootPage0Proxy = rootFolderProxy.getPage("page0.psml"); assertNotNull(rootPage0Proxy); assertEquals(rootFolderProxy, rootPage0Proxy.getParent()); assertEquals("page0.psml", rootPage0Proxy.getName()); - assertEquals("/page0.psml", extractFileSystemPathFromId(rootPage0Proxy.getId())); + assertEquals("/page0.psml", extractFileSystemPathFromId(rootPage0Proxy + .getId())); Page rootHiddenProxy = rootFolderProxy.getPage("hidden.psml"); assertNotNull(rootHiddenProxy); assertEquals("hidden.psml", rootHiddenProxy.getName()); @@ -213,54 +227,67 @@ assertNotNull(rootLink0Proxy); assertEquals(rootFolderProxy, rootLink0Proxy.getParent()); assertEquals("link0.link", rootLink0Proxy.getName()); - assertEquals("/link0.link", extractFileSystemPathFromId(rootLink0Proxy.getId())); + assertEquals("/link0.link", extractFileSystemPathFromId(rootLink0Proxy + .getId())); Folder rootFolder0Proxy = rootFolderProxy.getFolder("folder0"); assertNotNull(rootFolder0Proxy); assertEquals(rootFolderProxy, rootFolder0Proxy.getParent()); assertEquals(1, rootFolder0Proxy.getPages().size()); assertEquals(null, rootFolder0Proxy.getLinks()); assertEquals("folder0", rootFolder0Proxy.getName()); - assertEquals("/folder0", extractFileSystemPathFromId(rootFolder0Proxy.getId())); + assertEquals("/folder0", extractFileSystemPathFromId(rootFolder0Proxy + .getId())); Page folder0Page0Proxy = rootFolder0Proxy.getPage("page0.psml"); assertNotNull(folder0Page0Proxy); assertEquals(rootFolder0Proxy, folder0Page0Proxy.getParent()); assertEquals("page0.psml", folder0Page0Proxy.getName()); - assertEquals("/folder0/page0.psml", extractFileSystemPathFromId(folder0Page0Proxy.getId())); + assertEquals("/folder0/page0.psml", + extractFileSystemPathFromId(folder0Page0Proxy.getId())); // test SiteView access by path - Folder rootFolderProxyByPath = (Folder)baseView.getNodeProxy("/", null, false, false); + Folder rootFolderProxyByPath = (Folder) baseView.getNodeProxy("/", + null, false, false); assertNotNull(rootFolderProxyByPath); assertEquals(rootFolderProxy, rootFolderProxyByPath); - Folder rootFolder0ProxyByPath = (Folder)baseView.getNodeProxy("/folder0/", null, false, false); + Folder rootFolder0ProxyByPath = (Folder) baseView.getNodeProxy( + "/folder0/", null, false, false); assertNotNull(rootFolder0ProxyByPath); assertEquals(rootFolder0Proxy, rootFolder0ProxyByPath); - Page folder0Page0ProxyByPath = (Page)baseView.getNodeProxy("/folder0/page0.psml", null, false, false); + Page folder0Page0ProxyByPath = (Page) baseView.getNodeProxy( + "/folder0/page0.psml", null, false, false); assertNotNull(folder0Page0ProxyByPath); assertEquals(folder0Page0Proxy, folder0Page0ProxyByPath); - folder0Page0ProxyByPath = (Page)baseView.getNodeProxy("page0.psml", rootFolder0Proxy, false, false); + folder0Page0ProxyByPath = (Page) baseView.getNodeProxy("page0.psml", + rootFolder0Proxy, false, false); assertNotNull(folder0Page0ProxyByPath); assertEquals(folder0Page0Proxy, folder0Page0ProxyByPath); - List rootPageProxiesByPath = baseView.getNodeProxies("/page?.psml", null, false, false); + List rootPageProxiesByPath = baseView.getNodeProxies("/page?.psml", + null, false, false); assertNotNull(rootPageProxiesByPath); - assertEquals(3,rootPageProxiesByPath.size()); + assertEquals(3, rootPageProxiesByPath.size()); assertTrue(rootPageProxiesByPath.contains(rootPage0Proxy)); - List rootFolderProxiesByPath = baseView.getNodeProxies("/*/", null, false, false); + List rootFolderProxiesByPath = baseView.getNodeProxies("/*/", null, + false, false); assertNotNull(rootFolderProxiesByPath); - assertEquals(4,rootFolderProxiesByPath.size()); + assertEquals(4, rootFolderProxiesByPath.size()); assertTrue(rootFolderProxiesByPath.contains(rootFolder0Proxy)); - List folderPageProxiesByPath = baseView.getNodeProxies("*/p*[0-9].psml", rootFolderProxy, false, false); + List folderPageProxiesByPath = baseView.getNodeProxies( + "*/p*[0-9].psml", rootFolderProxy, false, false); assertNotNull(folderPageProxiesByPath); - assertEquals(2,folderPageProxiesByPath.size()); + assertEquals(2, folderPageProxiesByPath.size()); assertTrue(folderPageProxiesByPath.contains(folder0Page0Proxy)); // test aggregating SiteView - SiteView aggregateView = new SiteView(pageManager, "/_user/user,/_role/role0,/_group/group,/"); - assertEquals("/_user/user,/_role/role0,/_group/group,/", aggregateView.getSearchPathsString()); + SiteView aggregateView = new SiteView(pageManager, + "/_user/user,/_role/role0,/_group/group,/"); + assertEquals("/_user/user,/_role/role0,/_group/group,/", aggregateView + .getSearchPathsString()); rootFolderProxy = aggregateView.getRootFolderProxy(); assertNotNull(rootFolderProxy); assertEquals("/", rootFolderProxy.getName()); assertEquals("user root", rootFolderProxy.getTitle()); - assertEquals("/_user/user", extractFileSystemPathFromId(rootFolderProxy.getId())); + assertEquals("/_user/user", extractFileSystemPathFromId(rootFolderProxy + .getId())); assertEquals(4, rootFolderProxy.getFolders().size()); assertEquals(4, rootFolderProxy.getPages().size()); assertEquals(2, rootFolderProxy.getLinks().size()); @@ -268,48 +295,59 @@ assertNotNull(rootPage0Proxy); assertEquals(rootFolderProxy, rootPage0Proxy.getParent()); assertEquals("page0.psml", rootPage0Proxy.getName()); - assertEquals("/page0.psml", extractFileSystemPathFromId(rootPage0Proxy.getId())); + assertEquals("/page0.psml", extractFileSystemPathFromId(rootPage0Proxy + .getId())); List rootPage0ProxyMenus = rootPage0Proxy.getMenuDefinitions(); assertNotNull(rootPage0ProxyMenus); - assertEquals(2 + aggregateView.getStandardMenuNames().size(), rootPage0ProxyMenus.size()); + assertEquals(2 + aggregateView.getStandardMenuNames().size(), + rootPage0ProxyMenus.size()); Iterator menusIter = rootPage0ProxyMenus.iterator(); - MenuDefinition rootPage0ProxyTopMenu = (MenuDefinition)menusIter.next(); + MenuDefinition rootPage0ProxyTopMenu = (MenuDefinition) menusIter + .next(); assertEquals("top", rootPage0ProxyTopMenu.getName()); assertEquals("/", rootPage0ProxyTopMenu.getOptions()); assertEquals(2, rootPage0ProxyTopMenu.getDepth()); assertEquals("dhtml-pull-down", rootPage0ProxyTopMenu.getSkin()); - MenuDefinition rootPage0ProxyBreadCrumbMenu = (MenuDefinition)menusIter.next(); + MenuDefinition rootPage0ProxyBreadCrumbMenu = (MenuDefinition) menusIter + .next(); assertEquals("bread-crumbs", rootPage0ProxyBreadCrumbMenu.getName()); assertEquals("./", rootPage0ProxyBreadCrumbMenu.getOptions()); assertEquals(true, rootPage0ProxyBreadCrumbMenu.isPaths()); for (int i = 0; (i < aggregateView.getStandardMenuNames().size()); i++) { - assertTrue(aggregateView.getStandardMenuNames().contains(((MenuDefinition)menusIter.next()).getName())); + assertTrue(aggregateView.getStandardMenuNames().contains( + ((MenuDefinition) menusIter.next()).getName())); } Page rootPage2Proxy = rootFolderProxy.getPage("page2.psml"); assertNotNull(rootPage2Proxy); assertEquals(rootFolderProxy, rootPage2Proxy.getParent()); assertEquals("page2.psml", rootPage2Proxy.getName()); - assertEquals("/_user/user/page2.psml", extractFileSystemPathFromId(rootPage2Proxy.getId())); + assertEquals("/_user/user/page2.psml", + extractFileSystemPathFromId(rootPage2Proxy.getId())); List rootPage2ProxyMenus = rootPage2Proxy.getMenuDefinitions(); assertNotNull(rootPage2ProxyMenus); - assertEquals(2 + aggregateView.getStandardMenuNames().size(), rootPage2ProxyMenus.size()); + assertEquals(2 + aggregateView.getStandardMenuNames().size(), + rootPage2ProxyMenus.size()); menusIter = rootPage2ProxyMenus.iterator(); - MenuDefinition rootPage2ProxyTopMenu = (MenuDefinition)menusIter.next(); + MenuDefinition rootPage2ProxyTopMenu = (MenuDefinition) menusIter + .next(); assertEquals("top", rootPage2ProxyTopMenu.getName()); assertEquals("/", rootPage2ProxyTopMenu.getOptions()); assertEquals(1, rootPage2ProxyTopMenu.getDepth()); - MenuDefinition rootPage2ProxyBreadCrumbMenu = (MenuDefinition)menusIter.next(); + MenuDefinition rootPage2ProxyBreadCrumbMenu = (MenuDefinition) menusIter + .next(); assertEquals("bread-crumbs", rootPage2ProxyBreadCrumbMenu.getName()); for (int i = 0; (i < aggregateView.getStandardMenuNames().size()); i++) { - assertTrue(aggregateView.getStandardMenuNames().contains(((MenuDefinition)menusIter.next()).getName())); + assertTrue(aggregateView.getStandardMenuNames().contains( + ((MenuDefinition) menusIter.next()).getName())); } rootLink0Proxy = rootFolderProxy.getLink("link0.link"); assertNotNull(rootLink0Proxy); assertEquals(rootFolderProxy, rootLink0Proxy.getParent()); assertEquals("link0.link", rootLink0Proxy.getName()); - assertEquals("/_group/group/link0.link", extractFileSystemPathFromId(rootLink0Proxy.getId())); + assertEquals("/_group/group/link0.link", + extractFileSystemPathFromId(rootLink0Proxy.getId())); rootFolder0Proxy = rootFolderProxy.getFolder("folder0"); assertNotNull(rootFolder0Proxy); assertEquals(rootFolderProxy, rootFolder0Proxy.getParent()); @@ -318,12 +356,14 @@ assertEquals(null, rootFolder0Proxy.getFolders()); assertEquals("folder0", rootFolder0Proxy.getName()); assertEquals("folder0", rootFolder0Proxy.getTitle()); - assertEquals("/folder0", extractFileSystemPathFromId(rootFolder0Proxy.getId())); + assertEquals("/folder0", extractFileSystemPathFromId(rootFolder0Proxy + .getId())); folder0Page0Proxy = rootFolder0Proxy.getPage("page0.psml"); assertNotNull(folder0Page0Proxy); assertEquals(rootFolder0Proxy, folder0Page0Proxy.getParent()); assertEquals("page0.psml", folder0Page0Proxy.getName()); - assertEquals("/folder0/page0.psml", extractFileSystemPathFromId(folder0Page0Proxy.getId())); + assertEquals("/folder0/page0.psml", + extractFileSystemPathFromId(folder0Page0Proxy.getId())); Folder rootFolder1Proxy = rootFolderProxy.getFolder("folder1"); assertNotNull(rootFolder1Proxy); assertEquals(rootFolderProxy, rootFolder1Proxy.getParent()); @@ -332,7 +372,8 @@ assertEquals(null, rootFolder1Proxy.getFolders()); assertEquals("folder1", rootFolder1Proxy.getName()); assertEquals("group folder1", rootFolder1Proxy.getTitle()); - assertEquals("/_user/user/folder1", extractFileSystemPathFromId(rootFolder1Proxy.getId())); + assertEquals("/_user/user/folder1", + extractFileSystemPathFromId(rootFolder1Proxy.getId())); // test degenerate aggregating SiteView aggregateView = new SiteView(pageManager, "/__subsite-root"); @@ -341,7 +382,8 @@ assertNotNull(rootFolderProxy); assertEquals("/", rootFolderProxy.getName()); assertEquals("subsite root", rootFolderProxy.getTitle()); - assertEquals("/__subsite-root", extractFileSystemPathFromId(rootFolderProxy.getId())); + assertEquals("/__subsite-root", + extractFileSystemPathFromId(rootFolderProxy.getId())); assertEquals(null, rootFolderProxy.getFolders()); assertEquals(1, rootFolderProxy.getPages().size()); assertEquals(1, rootFolderProxy.getLinks().size()); @@ -365,14 +407,16 @@ locator.add("language", true, false, "en"); locator.add("country", true, false, "US"); profileView = new SiteView(pageManager, locator); - assertEquals("/_user/user/_mediatype/html,/_user/user,/", profileView.getSearchPathsString()); + assertEquals("/_user/user/_mediatype/html,/_user/user,/", profileView + .getSearchPathsString()); locator = new JetspeedProfileLocator(); locator.init(null, "/"); locator.add("page", false, false, "default-page"); locator.add("role", true, false, "role0"); locator.add("role", true, false, "role1"); profileView = new SiteView(pageManager, locator); - assertEquals("/_role/role0,/_role/role1,/", profileView.getSearchPathsString()); + assertEquals("/_role/role0,/_role/role1,/", profileView + .getSearchPathsString()); locator = new JetspeedProfileLocator(); locator.init(null, "/"); locator.add("user", true, false, "user"); @@ -382,7 +426,8 @@ locator.add("group", true, false, "group"); locator.add("page", false, false, "default-page"); profileView = new SiteView(pageManager, locator); - assertEquals("/_user/user,/_role/role0,/_group/group,/", profileView.getSearchPathsString()); + assertEquals("/_user/user,/_role/role0,/_group/group,/", profileView + .getSearchPathsString()); locator = new JetspeedProfileLocator(); locator.init(null, "/"); @@ -390,8 +435,9 @@ locator.add("user", true, false, "joe"); locator.add("page", false, false, "home"); profileView = new SiteView(pageManager, locator); - assertEquals("/_hostname/dash/_user/joe,/_hostname/dash,/", profileView.getSearchPathsString()); - + assertEquals("/_hostname/dash/_user/joe,/_hostname/dash,/", profileView + .getSearchPathsString()); + locator = new JetspeedProfileLocator(); locator.init(null, "/"); locator.add("navigation", false, true, "subsite-root"); @@ -410,40 +456,50 @@ locator.add("group", true, false, "group"); locators.put("alternate-locator-name", locator); profileView = new SiteView(pageManager, locators); - assertEquals("/_role/role0,/_role/role1,/_user/user,/_group/group,/", profileView.getSearchPathsString()); + assertEquals("/_role/role0,/_role/role1,/_user/user,/_group/group,/", + profileView.getSearchPathsString()); rootFolderProxy = profileView.getRootFolderProxy(); assertNotNull(rootFolderProxy); assertEquals("/", rootFolderProxy.getName()); assertEquals("user root", rootFolderProxy.getTitle()); - assertEquals("/_role/role0", extractFileSystemPathFromId(rootFolderProxy.getId())); - assertEquals(ProfileLocator.PAGE_LOCATOR, extractLocatorNameFromProxy(rootFolderProxy)); + assertEquals("/_role/role0", + extractFileSystemPathFromId(rootFolderProxy.getId())); + assertEquals(ProfileLocator.PAGE_LOCATOR, + extractLocatorNameFromProxy(rootFolderProxy)); rootPage2Proxy = rootFolderProxy.getPage("page2.psml"); assertNotNull(rootPage2Proxy); assertEquals("page2.psml", rootPage2Proxy.getName()); - assertEquals("/_role/role0/page2.psml", extractFileSystemPathFromId(rootPage2Proxy.getId())); - assertEquals(ProfileLocator.PAGE_LOCATOR, extractLocatorNameFromProxy(rootPage2Proxy)); + assertEquals("/_role/role0/page2.psml", + extractFileSystemPathFromId(rootPage2Proxy.getId())); + assertEquals(ProfileLocator.PAGE_LOCATOR, + extractLocatorNameFromProxy(rootPage2Proxy)); rootFolder1Proxy = rootFolderProxy.getFolder("folder1"); assertNotNull(rootFolder1Proxy); assertEquals("folder1", rootFolder1Proxy.getName()); assertEquals("group folder1", rootFolder1Proxy.getTitle()); - assertEquals("/_user/user/folder1", extractFileSystemPathFromId(rootFolder1Proxy.getId())); - assertEquals("alternate-locator-name", extractLocatorNameFromProxy(rootFolder1Proxy)); + assertEquals("/_user/user/folder1", + extractFileSystemPathFromId(rootFolder1Proxy.getId())); + assertEquals("alternate-locator-name", + extractLocatorNameFromProxy(rootFolder1Proxy)); Page folder1Page1Proxy = rootFolder1Proxy.getPage("page1.psml"); assertNotNull(folder1Page1Proxy); assertEquals("page1.psml", folder1Page1Proxy.getName()); - assertEquals("/_group/group/folder1/page1.psml", extractFileSystemPathFromId(folder1Page1Proxy.getId())); - assertEquals("alternate-locator-name", extractLocatorNameFromProxy(folder1Page1Proxy)); + assertEquals("/_group/group/folder1/page1.psml", + extractFileSystemPathFromId(folder1Page1Proxy.getId())); + assertEquals("alternate-locator-name", + extractLocatorNameFromProxy(folder1Page1Proxy)); } /** * testPortalSiteSetup - Test PortalSite test configuration - * + * * @throws Exception */ public void testPotalSiteSetup() throws Exception { assertNotNull(portalSite); - PortalSiteSessionContext sessionContext = portalSite.newSessionContext(); + PortalSiteSessionContext sessionContext = portalSite + .newSessionContext(); assertNotNull(sessionContext); JetspeedProfileLocator locator = new JetspeedProfileLocator(); locator.init(null, "/"); @@ -455,58 +511,80 @@ locator.add("group", true, false, "group"); Map locators = new HashMap(); locators.put(ProfileLocator.PAGE_LOCATOR, locator); - PortalSiteRequestContext requestContext = sessionContext.newRequestContext(locators); + PortalSiteRequestContext requestContext = sessionContext + .newRequestContext(locators); assertNotNull(requestContext); Page requestPageProxy = requestContext.getPage(); assertNotNull(requestPageProxy); assertEquals("page2.psml", requestPageProxy.getName()); - assertEquals("/_user/user/page2.psml", extractFileSystemPathFromId(requestPageProxy.getId())); + assertEquals("/_user/user/page2.psml", + extractFileSystemPathFromId(requestPageProxy.getId())); Folder requestFolderProxy = requestContext.getFolder(); assertNotNull(requestFolderProxy); assertEquals("/", requestFolderProxy.getName()); - assertEquals("/_user/user", extractFileSystemPathFromId(requestFolderProxy.getId())); + assertEquals("/_user/user", + extractFileSystemPathFromId(requestFolderProxy.getId())); NodeSet requestSiblingPageProxies = requestContext.getSiblingPages(); assertNotNull(requestSiblingPageProxies); assertEquals(3, requestSiblingPageProxies.size()); assertNotNull(requestSiblingPageProxies.get("page0.psml")); - assertEquals("/page0.psml", extractFileSystemPathFromId(requestSiblingPageProxies.get("page0.psml").getId())); + assertEquals("/page0.psml", + extractFileSystemPathFromId(requestSiblingPageProxies.get( + "page0.psml").getId())); assertNotNull(requestSiblingPageProxies.get("page1.psml")); - assertEquals("/page1.psml", extractFileSystemPathFromId(requestSiblingPageProxies.get("page1.psml").getId())); + assertEquals("/page1.psml", + extractFileSystemPathFromId(requestSiblingPageProxies.get( + "page1.psml").getId())); assertNotNull(requestSiblingPageProxies.get("page2.psml")); - assertEquals("/_user/user/page2.psml", extractFileSystemPathFromId(requestSiblingPageProxies.get("page2.psml").getId())); + assertEquals("/_user/user/page2.psml", + extractFileSystemPathFromId(requestSiblingPageProxies.get( + "page2.psml").getId())); Folder requestParentFolderProxy = requestContext.getParentFolder(); assertNull(requestParentFolderProxy); - NodeSet requestSiblingFolderProxies = requestContext.getSiblingFolders(); + NodeSet requestSiblingFolderProxies = requestContext + .getSiblingFolders(); assertNotNull(requestSiblingFolderProxies); assertEquals(3, requestSiblingFolderProxies.size()); assertNotNull(requestSiblingFolderProxies.get("folder0")); - assertEquals("/folder0", extractFileSystemPathFromId(requestSiblingFolderProxies.get("folder0").getId())); + assertEquals("/folder0", + extractFileSystemPathFromId(requestSiblingFolderProxies.get( + "folder0").getId())); assertNotNull(requestSiblingFolderProxies.get("folder1")); - assertEquals("/_user/user/folder1", extractFileSystemPathFromId(requestSiblingFolderProxies.get("folder1").getId())); + assertEquals("/_user/user/folder1", + extractFileSystemPathFromId(requestSiblingFolderProxies.get( + "folder1").getId())); assertNotNull(requestSiblingFolderProxies.get("folder2")); - assertEquals("/folder2", extractFileSystemPathFromId(requestSiblingFolderProxies.get("folder2").getId())); + assertEquals("/folder2", + extractFileSystemPathFromId(requestSiblingFolderProxies.get( + "folder2").getId())); Folder requestRootFolderProxy = requestContext.getRootFolder(); assertNotNull(requestRootFolderProxy); assertEquals("/", requestRootFolderProxy.getName()); - assertEquals("/_user/user", extractFileSystemPathFromId(requestRootFolderProxy.getId())); + assertEquals("/_user/user", + extractFileSystemPathFromId(requestRootFolderProxy.getId())); NodeSet requestRootLinkProxies = requestContext.getRootLinks(); assertNotNull(requestRootLinkProxies); assertEquals(2, requestRootLinkProxies.size()); assertNotNull(requestRootLinkProxies.get("link0.link")); - assertEquals("/_group/group/link0.link", extractFileSystemPathFromId(requestRootLinkProxies.get("link0.link").getId())); + assertEquals("/_group/group/link0.link", + extractFileSystemPathFromId(requestRootLinkProxies.get( + "link0.link").getId())); assertNotNull(requestRootLinkProxies.get("link1.link")); - assertEquals("/link1.link", extractFileSystemPathFromId(requestRootLinkProxies.get("link1.link").getId())); + assertEquals("/link1.link", + extractFileSystemPathFromId(requestRootLinkProxies.get( + "link1.link").getId())); } /** * testPortalSiteRequests - Test PortalSite request path logic - * + * * @throws Exception */ public void testPotalSiteRequests() throws Exception { assertNotNull(portalSite); - PortalSiteSessionContext sessionContext = portalSite.newSessionContext(); + PortalSiteSessionContext sessionContext = portalSite + .newSessionContext(); assertNotNull(sessionContext); JetspeedProfileLocator locator = new JetspeedProfileLocator(); locator.init(null, "/"); @@ -514,12 +592,14 @@ locator.add("user", true, false, "user"); Map locators = new HashMap(); locators.put(ProfileLocator.PAGE_LOCATOR, locator); - PortalSiteRequestContext requestContext = sessionContext.newRequestContext(locators); + PortalSiteRequestContext requestContext = sessionContext + .newRequestContext(locators); assertNotNull(requestContext); Page requestPageProxy = requestContext.getPage(); assertNotNull(requestPageProxy); assertEquals("page2.psml", requestPageProxy.getName()); - assertEquals("/_user/user/page2.psml", extractFileSystemPathFromId(requestPageProxy.getId())); + assertEquals("/_user/user/page2.psml", + extractFileSystemPathFromId(requestPageProxy.getId())); locator = new JetspeedProfileLocator(); locator.init(null, "/"); @@ -532,7 +612,8 @@ requestPageProxy = requestContext.getPage(); assertNotNull(requestPageProxy); assertEquals("page2.psml", requestPageProxy.getName()); - assertEquals("/_user/user/page2.psml", extractFileSystemPathFromId(requestPageProxy.getId())); + assertEquals("/_user/user/page2.psml", + extractFileSystemPathFromId(requestPageProxy.getId())); locator = new JetspeedProfileLocator(); locator.init(null, "/"); @@ -545,7 +626,8 @@ requestPageProxy = requestContext.getPage(); assertNotNull(requestPageProxy); assertEquals("page1.psml", requestPageProxy.getName()); - assertEquals("/page1.psml", extractFileSystemPathFromId(requestPageProxy.getId())); + assertEquals("/page1.psml", + extractFileSystemPathFromId(requestPageProxy.getId())); locator = new JetspeedProfileLocator(); locator.init(null, "/"); @@ -558,7 +640,8 @@ requestPageProxy = requestContext.getPage(); assertNotNull(requestPageProxy); assertEquals("page0.psml", requestPageProxy.getName()); - assertEquals("/_user/user/folder1/page0.psml", extractFileSystemPathFromId(requestPageProxy.getId())); + assertEquals("/_user/user/folder1/page0.psml", + extractFileSystemPathFromId(requestPageProxy.getId())); locator = new JetspeedProfileLocator(); locator.init(null, "/"); @@ -571,7 +654,8 @@ requestPageProxy = requestContext.getPage(); assertNotNull(requestPageProxy); assertEquals("page0.psml", requestPageProxy.getName()); - assertEquals("/folder0/page0.psml", extractFileSystemPathFromId(requestPageProxy.getId())); + assertEquals("/folder0/page0.psml", + extractFileSystemPathFromId(requestPageProxy.getId())); locator = new JetspeedProfileLocator(); locator.init(null, "/"); @@ -582,18 +666,20 @@ requestPageProxy = requestContext.getPage(); assertNotNull(requestPageProxy); assertEquals("page1.psml", requestPageProxy.getName()); - assertEquals("/folder3/default-folder1/page1.psml", extractFileSystemPathFromId(requestPageProxy.getId())); + assertEquals("/folder3/default-folder1/page1.psml", + extractFileSystemPathFromId(requestPageProxy.getId())); } /** * testPortalSiteMenus - Test PortalSite menu generation - * + * * @throws Exception */ public void testPotalSiteMenus() throws Exception { assertNotNull(portalSite); - PortalSiteSessionContext sessionContext = portalSite.newSessionContext(); + PortalSiteSessionContext sessionContext = portalSite + .newSessionContext(); assertNotNull(sessionContext); // first request at / @@ -611,7 +697,8 @@ locator.init(null, "/"); locator.add("group", true, false, "group"); locators.put("group", locator); - PortalSiteRequestContext requestContext = sessionContext.newRequestContext(locators); + PortalSiteRequestContext requestContext = sessionContext + .newRequestContext(locators); assertNotNull(requestContext); Set customMenuNames = requestContext.getCustomMenuNames(); assertNotNull(customMenuNames); @@ -634,67 +721,86 @@ Iterator menuElementsIter = topMenuElements.iterator(); while (menuElementsIter.hasNext()) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.MENU_ELEMENT_TYPE) && element.getTitle().equals("folder0")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType().equals(MenuElement.MENU_ELEMENT_TYPE) + && element.getTitle().equals("folder0")) { assertTrue(element instanceof Menu); - assertEquals("/folder0", ((Menu)element).getUrl()); - assertTrue(((Menu)element).getParentMenu() == topMenu); - assertFalse(((Menu)element).isEmpty()); - List elements = ((Menu)element).getElements(); + assertEquals("/folder0", ((Menu) element).getUrl()); + assertTrue(((Menu) element).getParentMenu() == topMenu); + assertFalse(((Menu) element).isEmpty()); + List elements = ((Menu) element).getElements(); assertNotNull(elements); assertEquals(1, elements.size()); assertTrue(elements.get(0) instanceof MenuOption); - assertEquals("/folder0/page0.psml", ((MenuOption)elements.get(0)).getUrl()); + assertEquals("/folder0/page0.psml", ((MenuOption) elements + .get(0)).getUrl()); assertEquals("dhtml-pull-down", element.getSkin()); } - else if (element.getElementType().equals(MenuElement.MENU_ELEMENT_TYPE) && element.getTitle().equals("group folder1")) + else if (element.getElementType().equals( + MenuElement.MENU_ELEMENT_TYPE) + && element.getTitle().equals("group folder1")) { assertTrue(element instanceof Menu); - assertEquals("/folder1", ((Menu)element).getUrl()); - assertTrue(((Menu)element).getParentMenu() == topMenu); - assertFalse(((Menu)element).isEmpty()); - List elements = ((Menu)element).getElements(); + assertEquals("/folder1", ((Menu) element).getUrl()); + assertTrue(((Menu) element).getParentMenu() == topMenu); + assertFalse(((Menu) element).isEmpty()); + List elements = ((Menu) element).getElements(); assertNotNull(elements); assertEquals(2, elements.size()); assertTrue(elements.get(0) instanceof MenuOption); - assertEquals("/folder1/page0.psml", ((MenuOption)elements.get(0)).getTitle()); + assertEquals("/folder1/page0.psml", ((MenuOption) elements + .get(0)).getTitle()); assertTrue(elements.get(1) instanceof MenuOption); - assertEquals("/folder1/page1.psml", ((MenuOption)elements.get(1)).getTitle()); + assertEquals("/folder1/page1.psml", ((MenuOption) elements + .get(1)).getTitle()); } - else if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/page2.psml")) + else if (element.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/page2.psml")) { assertTrue(element instanceof MenuOption); - assertEquals("/page2.psml", ((MenuOption)element).getUrl()); - assertEquals(MenuOption.PAGE_OPTION_TYPE, ((MenuOption)element).getType()); + assertEquals("/page2.psml", ((MenuOption) element).getUrl()); + assertEquals(MenuOption.PAGE_OPTION_TYPE, + ((MenuOption) element).getType()); } - else if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/page1.psml")) + else if (element.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/page1.psml")) { assertTrue(element instanceof MenuOption); - assertEquals("/page1.psml", ((MenuOption)element).getUrl()); + assertEquals("/page1.psml", ((MenuOption) element).getUrl()); } - else if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/page0.psml")) + else if (element.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/page0.psml")) { assertTrue(element instanceof MenuOption); - assertEquals("/page0.psml", ((MenuOption)element).getUrl()); + assertEquals("/page0.psml", ((MenuOption) element).getUrl()); } - else if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/link1.link")) + else if (element.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/link1.link")) { assertTrue(element instanceof MenuOption); - assertEquals("http://link1", ((MenuOption)element).getUrl()); - assertEquals("top", ((MenuOption)element).getTarget()); - assertEquals(MenuOption.LINK_OPTION_TYPE, ((MenuOption)element).getType()); + assertEquals("http://link1", ((MenuOption) element).getUrl()); + assertEquals("top", ((MenuOption) element).getTarget()); + assertEquals(MenuOption.LINK_OPTION_TYPE, + ((MenuOption) element).getType()); } - else if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/link0.link")) + else if (element.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/link0.link")) { assertTrue(element instanceof MenuOption); - assertEquals("http://link0", ((MenuOption)element).getUrl()); - assertNull(((MenuOption)element).getTarget()); + assertEquals("http://link0", ((MenuOption) element).getUrl()); + assertNull(((MenuOption) element).getTarget()); assertEquals("dhtml-pull-down", element.getSkin()); } else { - fail("Unexpected menu element type/title: "+element.getElementType()+"/"+element.getTitle()); + fail("Unexpected menu element type/title: " + + element.getElementType() + "/" + element.getTitle()); } } assertTrue(topMenu.isSelected(requestContext)); @@ -702,10 +808,10 @@ assertNotNull(selected); assertEquals(MenuElement.OPTION_ELEMENT_TYPE, selected.getElementType()); assertTrue(selected instanceof MenuOption); - assertEquals("/page2.psml", ((MenuOption)selected).getUrl()); + assertEquals("/page2.psml", ((MenuOption) selected).getUrl()); assertEquals("/page2.psml", selected.getTitle()); assertEquals("dhtml-pull-down", selected.getSkin()); - assertFalse(((MenuImpl)topMenu).isElementRelative()); + assertFalse(((MenuImpl) topMenu).isElementRelative()); Menu breadCrumbsMenu = requestContext.getMenu("bread-crumbs"); assertNotNull(breadCrumbsMenu); assertEquals("bread-crumbs", breadCrumbsMenu.getName()); @@ -715,9 +821,10 @@ assertNotNull(breadCrumbsElements); assertEquals(1, breadCrumbsElements.size()); assertTrue(breadCrumbsElements.get(0) instanceof MenuOption); - assertEquals("/", ((MenuOption)breadCrumbsElements.get(0)).getUrl()); - assertEquals(MenuOption.FOLDER_OPTION_TYPE, ((MenuOption)breadCrumbsElements.get(0)).getType()); - assertTrue(((MenuImpl)breadCrumbsMenu).isElementRelative()); + assertEquals("/", ((MenuOption) breadCrumbsElements.get(0)).getUrl()); + assertEquals(MenuOption.FOLDER_OPTION_TYPE, + ((MenuOption) breadCrumbsElements.get(0)).getType()); + assertTrue(((MenuImpl) breadCrumbsMenu).isElementRelative()); // second request at /folder0 locator = new JetspeedProfileLocator(); @@ -749,11 +856,14 @@ assertNotNull(breadCrumbsElements); assertEquals(2, breadCrumbsElements.size()); assertTrue(breadCrumbsElements.get(0) instanceof MenuOption); - assertEquals("/", ((MenuOption)breadCrumbsElements.get(0)).getUrl()); - assertEquals(MenuOption.FOLDER_OPTION_TYPE, ((MenuOption)breadCrumbsElements.get(0)).getType()); - assertEquals("/folder0", ((MenuOption)breadCrumbsElements.get(1)).getUrl()); - assertEquals(MenuOption.FOLDER_OPTION_TYPE, ((MenuOption)breadCrumbsElements.get(1)).getType()); - assertTrue(((MenuImpl)breadCrumbsMenu2).isElementRelative()); + assertEquals("/", ((MenuOption) breadCrumbsElements.get(0)).getUrl()); + assertEquals(MenuOption.FOLDER_OPTION_TYPE, + ((MenuOption) breadCrumbsElements.get(0)).getType()); + assertEquals("/folder0", ((MenuOption) breadCrumbsElements.get(1)) + .getUrl()); + assertEquals(MenuOption.FOLDER_OPTION_TYPE, + ((MenuOption) breadCrumbsElements.get(1)).getType()); + assertTrue(((MenuImpl) breadCrumbsMenu2).isElementRelative()); Menu hiddenMenu = requestContext.getMenu("override-hidden"); assertNotNull(hiddenMenu); assertTrue(hiddenMenu.isEmpty()); @@ -786,7 +896,7 @@ assertNotNull(backMenu); assertTrue(backMenu.isEmpty()); assertNull(backMenu.getElements()); - assertTrue(((MenuImpl)backMenu).isElementRelative()); + assertTrue(((MenuImpl) backMenu).isElementRelative()); assertEquals("back", backMenu.getName()); assertEquals("Back to", backMenu.getTitle()); assertEquals("Back to", backMenu.getShortTitle()); @@ -798,7 +908,8 @@ assertNotNull(breadcrumbsMenu); assertFalse(breadcrumbsMenu.isEmpty()); assertEquals("You are here:", breadcrumbsMenu.getTitle()); - assertEquals("\u73fe\u5728\u30d1\u30b9\uff1a", breadcrumbsMenu.getTitle(Locale.JAPANESE)); + assertEquals("\u73fe\u5728\u30d1\u30b9\uff1a", breadcrumbsMenu + .getTitle(Locale.JAPANESE)); navigationsMenu = requestContext.getMenu("navigations"); assertNotNull(navigationsMenu); assertFalse(navigationsMenu.isEmpty()); @@ -808,45 +919,61 @@ menuElementsIter = navigationsElements.iterator(); while (menuElementsIter.hasNext()) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.SEPARATOR_ELEMENT_TYPE) && - (element instanceof MenuSeparator) && - ((MenuSeparator)element).getText().equals("Folders")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType().equals( + MenuElement.SEPARATOR_ELEMENT_TYPE) + && (element instanceof MenuSeparator) + && ((MenuSeparator) element).getText().equals("Folders")) { } - else if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("folder0")) + else if (element.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("folder0")) { assertTrue(element instanceof MenuOption); - assertEquals(MenuOption.FOLDER_OPTION_TYPE, ((MenuOption)element).getType()); + assertEquals(MenuOption.FOLDER_OPTION_TYPE, + ((MenuOption) element).getType()); } - else if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("group folder1")) + else if (element.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("group folder1")) { assertTrue(element instanceof MenuOption); - assertEquals(MenuOption.FOLDER_OPTION_TYPE, ((MenuOption)element).getType()); + assertEquals(MenuOption.FOLDER_OPTION_TYPE, + ((MenuOption) element).getType()); } - else if (element.getElementType().equals(MenuElement.SEPARATOR_ELEMENT_TYPE) && - (element instanceof MenuSeparator) && - ((MenuSeparator)element).getText().equals("Additional Links")) + else if (element.getElementType().equals( + MenuElement.SEPARATOR_ELEMENT_TYPE) + && (element instanceof MenuSeparator) + && ((MenuSeparator) element).getText().equals( + "Additional Links")) { } - else if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/link1.link")) + else if (element.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/link1.link")) { assertTrue(element instanceof MenuOption); - assertEquals(MenuOption.LINK_OPTION_TYPE, ((MenuOption)element).getType()); + assertEquals(MenuOption.LINK_OPTION_TYPE, + ((MenuOption) element).getType()); } - else if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/link0.link")) + else if (element.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/link0.link")) { assertTrue(element instanceof MenuOption); - assertEquals(MenuOption.LINK_OPTION_TYPE, ((MenuOption)element).getType()); + assertEquals(MenuOption.LINK_OPTION_TYPE, + ((MenuOption) element).getType()); assertEquals("left-navigations", element.getSkin()); } else { - fail("Unexpected menu element type/title: "+element.getElementType()+"/"+element.getTitle()); + fail("Unexpected menu element type/title: " + + element.getElementType() + "/" + element.getTitle()); } } assertEquals("left-navigations", navigationsMenu.getSkin()); - assertTrue(((MenuImpl)navigationsMenu).isElementRelative()); + assertTrue(((MenuImpl) navigationsMenu).isElementRelative()); Menu pagesMenu = requestContext.getMenu("pages"); assertNotNull(pagesMenu); assertFalse(pagesMenu.isEmpty()); @@ -856,31 +983,39 @@ menuElementsIter = pagesElements.iterator(); while (menuElementsIter.hasNext()) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/page2.psml")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType() + .equals(MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/page2.psml")) { assertTrue(element instanceof MenuOption); - assertEquals("/page2.psml", ((MenuOption)element).getUrl()); - assertEquals(MenuOption.PAGE_OPTION_TYPE, ((MenuOption)element).getType()); + assertEquals("/page2.psml", ((MenuOption) element).getUrl()); + assertEquals(MenuOption.PAGE_OPTION_TYPE, + ((MenuOption) element).getType()); } - else if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/page1.psml")) + else if (element.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/page1.psml")) { assertTrue(element instanceof MenuOption); - assertEquals("/page1.psml", ((MenuOption)element).getUrl()); + assertEquals("/page1.psml", ((MenuOption) element).getUrl()); } - else if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/page0.psml")) + else if (element.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/page0.psml")) { assertTrue(element instanceof MenuOption); - assertEquals("/page0.psml", ((MenuOption)element).getUrl()); + assertEquals("/page0.psml", ((MenuOption) element).getUrl()); assertEquals("tabs", element.getSkin()); } else { - fail("Unexpected menu element type/title: "+element.getElementType()+"/"+element.getTitle()); + fail("Unexpected menu element type/title: " + + element.getElementType() + "/" + element.getTitle()); } } assertEquals("tabs", pagesMenu.getSkin()); - assertTrue(((MenuImpl)pagesMenu).isElementRelative()); + assertTrue(((MenuImpl) pagesMenu).isElementRelative()); // new request at /folder1 locator = new JetspeedProfileLocator(); @@ -910,222 +1045,291 @@ assertEquals("custom", customMenu.getName()); assertEquals("Top Menu", customMenu.getTitle()); assertEquals("Haut", customMenu.getTitle(Locale.FRENCH)); - menuElementsIter = customElements.iterator(); + menuElementsIter = customElements.iterator(); for (int i = 0; ((i < 2) && menuElementsIter.hasNext()); i++) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/link0.link")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType() + .equals(MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/link0.link")) { assertTrue(element instanceof MenuOption); - assertEquals("http://link0", ((MenuOption)element).getUrl()); - assertEquals(MenuOption.LINK_OPTION_TYPE, ((MenuOption)element).getType()); + assertEquals("http://link0", ((MenuOption) element).getUrl()); + assertEquals(MenuOption.LINK_OPTION_TYPE, + ((MenuOption) element).getType()); } - else if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/folder1/page1.psml")) + else if (element.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/folder1/page1.psml")) { assertTrue(element instanceof MenuOption); - assertEquals("/folder1/page1.psml", ((MenuOption)element).getUrl()); - assertEquals(MenuOption.PAGE_OPTION_TYPE, ((MenuOption)element).getType()); + assertEquals("/folder1/page1.psml", ((MenuOption) element) + .getUrl()); + assertEquals(MenuOption.PAGE_OPTION_TYPE, + ((MenuOption) element).getType()); } else { - fail("Unexpected menu element type/title: "+element.getElementType()+"/"+element.getTitle()); - } + fail("Unexpected menu element type/title: " + + element.getElementType() + "/" + element.getTitle()); + } } if (menuElementsIter.hasNext()) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.MENU_ELEMENT_TYPE) && element.getTitle().equals("user root")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType().equals(MenuElement.MENU_ELEMENT_TYPE) + && element.getTitle().equals("user root")) { - assertFalse(((Menu)element).isEmpty()); - List nestedElements = ((Menu)element).getElements(); + assertFalse(((Menu) element).isEmpty()); + List nestedElements = ((Menu) element).getElements(); assertEquals(6, nestedElements.size()); Iterator nestedElementsIter = nestedElements.iterator(); if (nestedElementsIter.hasNext()) { - MenuElement nestedElement = (MenuElement)nestedElementsIter.next(); - if (nestedElement.getElementType().equals(MenuElement.SEPARATOR_ELEMENT_TYPE) && - (nestedElement instanceof MenuSeparator) && - ((MenuSeparator)nestedElement).getText().equals("=== Current Page ===")) + MenuElement nestedElement = (MenuElement) nestedElementsIter + .next(); + if (nestedElement.getElementType().equals( + MenuElement.SEPARATOR_ELEMENT_TYPE) + && (nestedElement instanceof MenuSeparator) + && ((MenuSeparator) nestedElement).getText() + .equals("=== Current Page ===")) { } else { - fail("Unexpected nested menu element type/title: "+nestedElement.getElementType()+"/"+nestedElement.getTitle()); - } + fail("Unexpected nested menu element type/title: " + + nestedElement.getElementType() + "/" + + nestedElement.getTitle()); + } } if (nestedElementsIter.hasNext()) { - MenuElement nestedElement = (MenuElement)nestedElementsIter.next(); - if (nestedElement.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && - nestedElement.getTitle().equals("/folder1/page1.psml")) + MenuElement nestedElement = (MenuElement) nestedElementsIter + .next(); + if (nestedElement.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && nestedElement.getTitle().equals( + "/folder1/page1.psml")) { assertTrue(nestedElement instanceof MenuOption); - assertEquals("/folder1/page1.psml", ((MenuOption)nestedElement).getUrl()); - assertEquals(MenuOption.PAGE_OPTION_TYPE, ((MenuOption)nestedElement).getType()); + assertEquals("/folder1/page1.psml", + ((MenuOption) nestedElement).getUrl()); + assertEquals(MenuOption.PAGE_OPTION_TYPE, + ((MenuOption) nestedElement).getType()); } else { - fail("Unexpected nested menu element type/title: "+nestedElement.getElementType()+"/"+nestedElement.getTitle()); - } + fail("Unexpected nested menu element type/title: " + + nestedElement.getElementType() + "/" + + nestedElement.getTitle()); + } } if (nestedElementsIter.hasNext()) { - MenuElement nestedElement = (MenuElement)nestedElementsIter.next(); - if (nestedElement.getElementType().equals(MenuElement.SEPARATOR_ELEMENT_TYPE) && - (nestedElement instanceof MenuSeparator) && - ((MenuSeparator)nestedElement).getText().equals("=== Top Pages ===")) + MenuElement nestedElement = (MenuElement) nestedElementsIter + .next(); + if (nestedElement.getElementType().equals( + MenuElement.SEPARATOR_ELEMENT_TYPE) + && (nestedElement instanceof MenuSeparator) + && ((MenuSeparator) nestedElement).getText() + .equals("=== Top Pages ===")) { assertEquals("Top Pages", nestedElement.getTitle()); } else { - fail("Unexpected nested menu element type/title: "+nestedElement.getElementType()+"/"+nestedElement.getTitle()); - } + fail("Unexpected nested menu element type/title: " + + nestedElement.getElementType() + "/" + + nestedElement.getTitle()); + } } for (int i = 0; ((i < 3) && nestedElementsIter.hasNext()); i++) { - MenuElement nestedElement = (MenuElement)nestedElementsIter.next(); - if (nestedElement.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && - nestedElement.getTitle().equals("/page2.psml")) + MenuElement nestedElement = (MenuElement) nestedElementsIter + .next(); + if (nestedElement.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && nestedElement.getTitle().equals("/page2.psml")) { assertTrue(nestedElement instanceof MenuOption); - assertEquals("/page2.psml", ((MenuOption)nestedElement).getUrl()); - assertEquals(MenuOption.PAGE_OPTION_TYPE, ((MenuOption)nestedElement).getType()); + assertEquals("/page2.psml", + ((MenuOption) nestedElement).getUrl()); + assertEquals(MenuOption.PAGE_OPTION_TYPE, + ((MenuOption) nestedElement).getType()); } - else if (nestedElement.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && - nestedElement.getTitle().equals("/page1.psml")) + else if (nestedElement.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && nestedElement.getTitle().equals("/page1.psml")) { assertTrue(nestedElement instanceof MenuOption); - assertEquals("/page1.psml", ((MenuOption)nestedElement).getUrl()); - assertEquals(MenuOption.PAGE_OPTION_TYPE, ((MenuOption)nestedElement).getType()); + assertEquals("/page1.psml", + ((MenuOption) nestedElement).getUrl()); + assertEquals(MenuOption.PAGE_OPTION_TYPE, + ((MenuOption) nestedElement).getType()); } - else if (nestedElement.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && - nestedElement.getTitle().equals("/page0.psml")) + else if (nestedElement.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && nestedElement.getTitle().equals("/page0.psml")) { assertTrue(nestedElement instanceof MenuOption); - assertEquals("/page0.psml", ((MenuOption)nestedElement).getUrl()); - assertEquals(MenuOption.PAGE_OPTION_TYPE, ((MenuOption)nestedElement).getType()); + assertEquals("/page0.psml", + ((MenuOption) nestedElement).getUrl()); + assertEquals(MenuOption.PAGE_OPTION_TYPE, + ((MenuOption) nestedElement).getType()); } else { - fail("Unexpected nested menu element type/title: "+nestedElement.getElementType()+"/"+nestedElement.getTitle()); - } + fail("Unexpected nested menu element type/title: " + + nestedElement.getElementType() + "/" + + nestedElement.getTitle()); + } } } else { - fail("Unexpected menu element type/title: "+element.getElementType()+"/"+element.getTitle()); - } + fail("Unexpected menu element type/title: " + + element.getElementType() + "/" + element.getTitle()); + } } if (menuElementsIter.hasNext()) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.SEPARATOR_ELEMENT_TYPE) && - (element instanceof MenuSeparator) && - ((MenuSeparator)element).getText().equals("=== More Options ===")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType().equals( + MenuElement.SEPARATOR_ELEMENT_TYPE) + && (element instanceof MenuSeparator) + && ((MenuSeparator) element).getText().equals( + "=== More Options ===")) { } else { - fail("Unexpected menu element type/title: "+element.getElementType()+"/"+element.getTitle()); - } + fail("Unexpected menu element type/title: " + + element.getElementType() + "/" + element.getTitle()); + } } for (int i = 0; ((i < 4) && menuElementsIter.hasNext()); i++) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/link1.link")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType() + .equals(MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/link1.link")) { assertTrue(element instanceof MenuOption); - assertEquals("http://link1", ((MenuOption)element).getUrl()); - assertEquals(MenuOption.LINK_OPTION_TYPE, ((MenuOption)element).getType()); + assertEquals("http://link1", ((MenuOption) element).getUrl()); + assertEquals(MenuOption.LINK_OPTION_TYPE, + ((MenuOption) element).getType()); } - else if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/page2.psml")) + else if (element.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/page2.psml")) { assertTrue(element instanceof MenuOption); - assertEquals("/page2.psml", ((MenuOption)element).getUrl()); - assertEquals(MenuOption.PAGE_OPTION_TYPE, ((MenuOption)element).getType()); + assertEquals("/page2.psml", ((MenuOption) element).getUrl()); + assertEquals(MenuOption.PAGE_OPTION_TYPE, + ((MenuOption) element).getType()); } - else if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/page1.psml")) + else if (element.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/page1.psml")) { assertTrue(element instanceof MenuOption); - assertEquals("/page1.psml", ((MenuOption)element).getUrl()); - assertEquals(MenuOption.PAGE_OPTION_TYPE, ((MenuOption)element).getType()); + assertEquals("/page1.psml", ((MenuOption) element).getUrl()); + assertEquals(MenuOption.PAGE_OPTION_TYPE, + ((MenuOption) element).getType()); } - else if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/folder1/page1.psml")) + else if (element.getElementType().equals( + MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/folder1/page1.psml")) { assertTrue(element instanceof MenuOption); - assertEquals("/folder1/page1.psml", ((MenuOption)element).getUrl()); - assertEquals(MenuOption.PAGE_OPTION_TYPE, ((MenuOption)element).getType()); + assertEquals("/folder1/page1.psml", ((MenuOption) element) + .getUrl()); + assertEquals(MenuOption.PAGE_OPTION_TYPE, + ((MenuOption) element).getType()); } else { - fail("Unexpected menu element type/title: "+element.getElementType()+"/"+element.getTitle()); - } + fail("Unexpected menu element type/title: " + + element.getElementType() + "/" + element.getTitle()); + } } if (menuElementsIter.hasNext()) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.SEPARATOR_ELEMENT_TYPE) && - (element instanceof MenuSeparator) && - ((MenuSeparator)element).getText().equals("=== Standard Menus ===")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType().equals( + MenuElement.SEPARATOR_ELEMENT_TYPE) + && (element instanceof MenuSeparator) + && ((MenuSeparator) element).getText().equals( + "=== Standard Menus ===")) { } else { - fail("Unexpected menu element type/title: "+element.getElementType()+"/"+element.getTitle()); - } + fail("Unexpected menu element type/title: " + + element.getElementType() + "/" + element.getTitle()); + } } if (menuElementsIter.hasNext()) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("user root")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType() + .equals(MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("user root")) { assertTrue(element instanceof MenuOption); - assertEquals("/", ((MenuOption)element).getUrl()); - assertEquals(MenuOption.FOLDER_OPTION_TYPE, ((MenuOption)element).getType()); + assertEquals("/", ((MenuOption) element).getUrl()); + assertEquals(MenuOption.FOLDER_OPTION_TYPE, + ((MenuOption) element).getType()); } else { - fail("Unexpected menu element type/title: "+element.getElementType()+"/"+element.getTitle()); - } + fail("Unexpected menu element type/title: " + + element.getElementType() + "/" + element.getTitle()); + } } if (menuElementsIter.hasNext()) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.MENU_ELEMENT_TYPE) && element.getTitle().equals("navigations")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType().equals(MenuElement.MENU_ELEMENT_TYPE) + && element.getTitle().equals("navigations")) { assertTrue(element instanceof Menu); - assertEquals("navigations", ((Menu)element).getName()); + assertEquals("navigations", ((Menu) element).getName()); } else { - fail("Unexpected menu element type/title: "+element.getElementType()+"/"+element.getTitle()); - } + fail("Unexpected menu element type/title: " + + element.getElementType() + "/" + element.getTitle()); + } } if (menuElementsIter.hasNext()) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.MENU_ELEMENT_TYPE) && element.getTitle().equals("pages")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType().equals(MenuElement.MENU_ELEMENT_TYPE) + && element.getTitle().equals("pages")) { assertTrue(element instanceof Menu); - assertEquals("pages", ((Menu)element).getName()); + assertEquals("pages", ((Menu) element).getName()); } else { - fail("Unexpected menu element type/title: "+element.getElementType()+"/"+element.getTitle()); - } + fail("Unexpected menu element type/title: " + + element.getElementType() + "/" + element.getTitle()); + } } } /** - * testPortalSiteHiddenPageMenus - Test PortalSite menu generation for hidden pages - * + * testPortalSiteHiddenPageMenus - Test PortalSite menu generation for + * hidden pages + * * @throws Exception */ public void testPotalSiteHiddenPageMenus() throws Exception { assertNotNull(portalSite); - PortalSiteSessionContext sessionContext = portalSite.newSessionContext(); + PortalSiteSessionContext sessionContext = portalSite + .newSessionContext(); assertNotNull(sessionContext); // first request at /: hidden page suppressed @@ -1134,7 +1338,8 @@ locator.add("user", true, false, "user"); Map locators = new HashMap(); locators.put(ProfileLocator.PAGE_LOCATOR, locator); - PortalSiteRequestContext requestContext = sessionContext.newRequestContext(locators); + PortalSiteRequestContext requestContext = sessionContext + .newRequestContext(locators); assertNotNull(requestContext); Menu topMenu = requestContext.getMenu("top"); assertNotNull(topMenu); @@ -1145,8 +1350,10 @@ boolean hiddenElement = false; while (menuElementsIter.hasNext()) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/hidden.psml")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType() + .equals(MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/hidden.psml")) { hiddenElement = true; } @@ -1161,8 +1368,10 @@ hiddenElement = false; while (menuElementsIter.hasNext()) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/hidden.psml")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType() + .equals(MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/hidden.psml")) { hiddenElement = true; } @@ -1186,8 +1395,10 @@ hiddenElement = false; while (menuElementsIter.hasNext()) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/hidden.psml")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType() + .equals(MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/hidden.psml")) { hiddenElement = true; } @@ -1202,8 +1413,10 @@ hiddenElement = false; while (menuElementsIter.hasNext()) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/hidden.psml")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType() + .equals(MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/hidden.psml")) { hiddenElement = true; } @@ -1227,8 +1440,10 @@ hiddenElement = false; while (menuElementsIter.hasNext()) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/hidden.psml")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType() + .equals(MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/hidden.psml")) { hiddenElement = true; } @@ -1243,8 +1458,10 @@ hiddenElement = false; while (menuElementsIter.hasNext()) { - MenuElement element = (MenuElement)menuElementsIter.next(); - if (element.getElementType().equals(MenuElement.OPTION_ELEMENT_TYPE) && element.getTitle().equals("/hidden.psml")) + MenuElement element = (MenuElement) menuElementsIter.next(); + if (element.getElementType() + .equals(MenuElement.OPTION_ELEMENT_TYPE) + && element.getTitle().equals("/hidden.psml")) { hiddenElement = true; } @@ -1253,28 +1470,31 @@ } /** - * extractFileSystemPathFromId - utility to convert proxy ids to file system paths - * - * @param id proxy node id + * extractFileSystemPathFromId - utility to convert proxy ids to file system + * paths + * + * @param id + * proxy node id * @return files system path */ private String extractFileSystemPathFromId(String id) { - if ((id != null) && !id.equals(Folder.PATH_SEPARATOR) && id.endsWith(Folder.PATH_SEPARATOR)) - { - return id.substring(0, id.length() - 1); - } + if ((id != null) && !id.equals(Folder.PATH_SEPARATOR) + && id.endsWith(Folder.PATH_SEPARATOR)) { return id.substring(0, + id.length() - 1); } return id; } /** - * extractLocatorNameFromProxy - utility to access profile locator name from proxy - * - * @param proxy site view node proxy + * extractLocatorNameFromProxy - utility to access profile locator name from + * proxy + * + * @param proxy + * site view node proxy * @return locator name */ private String extractLocatorNameFromProxy(Object proxy) throws Exception { - return ((NodeProxy)Proxy.getInvocationHandler(proxy)).getLocatorName(); + return ((NodeProxy) Proxy.getInvocationHandler(proxy)).getLocatorName(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portlet-factory/src/java/org/apache/jetspeed/factory/JetspeedPortletFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portlet-factory/src/java/org/apache/jetspeed/factory/JetspeedPortletFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portlet-factory/src/java/org/apache/jetspeed/factory/JetspeedPortletFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -43,111 +43,126 @@ * JetspeedPortletFactory *

        *

        - * + * *

        + * * @author Scott T. Weaver * @version $Id: JetspeedPortletFactory.java 593513 2007-11-09 12:48:34Z woonsan $ - * + * */ public class JetspeedPortletFactory implements PortletFactory { private Map portletCache; + private Map validatorCache; - - private static final Log log = LogFactory.getLog(JetspeedPortletFactory.class); + + private static final Log log = LogFactory + .getLog(JetspeedPortletFactory.class); + private final Map classLoaderMap; - + /** - * Flag whether this factory will create proxy instances for actual portlet instances or not. + * Flag whether this factory will create proxy instances for actual portlet + * instances or not. */ private boolean portletProxyUsed; - + /** - * Flag whether the instantiated proxy will switch edit_defaults mode to edit mode automatically or not. + * Flag whether the instantiated proxy will switch edit_defaults mode to + * edit mode automatically or not. */ private boolean autoSwitchEditDefaultsModeToEditMode; - + /** - * Flag whether the instantiated proxy will switch config mode to built-in config edit page or not. + * Flag whether the instantiated proxy will switch config mode to built-in + * config edit page or not. */ private boolean autoSwitchConfigMode; - + private String customConfigModePortletUniqueName; - + public JetspeedPortletFactory() { this(false, false); } - - public JetspeedPortletFactory(boolean autoSwitchConfigMode, boolean autoSwitchEditDefaultsModeToEditMode) + + public JetspeedPortletFactory(boolean autoSwitchConfigMode, + boolean autoSwitchEditDefaultsModeToEditMode) { - this.portletCache = Collections.synchronizedMap(new HashMap()); + this.portletCache = Collections.synchronizedMap(new HashMap()); this.validatorCache = Collections.synchronizedMap(new HashMap()); classLoaderMap = Collections.synchronizedMap(new HashMap()); - + this.autoSwitchConfigMode = autoSwitchConfigMode; this.autoSwitchEditDefaultsModeToEditMode = autoSwitchEditDefaultsModeToEditMode; - + this.portletProxyUsed = (this.autoSwitchConfigMode || this.autoSwitchEditDefaultsModeToEditMode); } - + public void setPortletProxyUsed(boolean portletProxyUsed) { this.portletProxyUsed = portletProxyUsed; } - + public boolean getPortletProxyUsed() { return this.portletProxyUsed; } - - public void setCustomConfigModePortletUniqueName(String customConfigModePortletUniqueName) + + public void setCustomConfigModePortletUniqueName( + String customConfigModePortletUniqueName) { this.customConfigModePortletUniqueName = customConfigModePortletUniqueName; } - + public String getCustomConfigModePortletUniqueName() { return this.customConfigModePortletUniqueName; } public void registerPortletApplication(PortletApplication pa, ClassLoader cl) + { + synchronized (classLoaderMap) { - synchronized (classLoaderMap) - { - unregisterPortletApplication(pa); - classLoaderMap.put(pa.getId(), cl); - } + unregisterPortletApplication(pa); + classLoaderMap.put(pa.getId(), cl); + } } - + public void unregisterPortletApplication(PortletApplication pa) { synchronized (classLoaderMap) { synchronized (portletCache) { - ClassLoader cl = (ClassLoader) classLoaderMap.remove(pa.getId()); + ClassLoader cl = (ClassLoader) classLoaderMap + .remove(pa.getId()); if (cl != null) { - ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader(); + ClassLoader currentContextClassLoader = Thread + .currentThread().getContextClassLoader(); - Iterator portletDefinitions = pa.getPortletDefinitions().iterator(); + Iterator portletDefinitions = pa.getPortletDefinitions() + .iterator(); while (portletDefinitions.hasNext()) { - PortletDefinition pd = (PortletDefinition) portletDefinitions.next(); + PortletDefinition pd = (PortletDefinition) portletDefinitions + .next(); String pdId = pd.getId().toString(); Portlet portlet = (Portlet) portletCache.remove(pdId); if (portlet != null) { try { - Thread.currentThread().setContextClassLoader(cl); + Thread.currentThread() + .setContextClassLoader(cl); portlet.destroy(); } finally { - Thread.currentThread().setContextClassLoader(currentContextClassLoader); + Thread.currentThread().setContextClassLoader( + currentContextClassLoader); } } validatorCache.remove(pdId); @@ -156,48 +171,57 @@ } } } - + public PreferencesValidator getPreferencesValidator(PortletDefinition pd) { PreferencesValidator validator = null; try { String pdId = pd.getId().toString(); - + synchronized (validatorCache) { - validator = (PreferencesValidator)validatorCache.get(pdId); - if ( validator == null ) + validator = (PreferencesValidator) validatorCache.get(pdId); + if (validator == null) { - String className = ((PortletDefinitionComposite)pd).getPreferenceValidatorClassname(); - if ( className != null ) + String className = ((PortletDefinitionComposite) pd) + .getPreferenceValidatorClassname(); + if (className != null) { - PortletApplication pa = (PortletApplication)pd.getPortletApplicationDefinition(); - ClassLoader paCl = (ClassLoader)classLoaderMap.get(pa.getId()); - if ( paCl == null ) - { - throw new UnavailableException("Portlet Application "+pa.getName()+" not available"); - } - - ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader(); + PortletApplication pa = (PortletApplication) pd + .getPortletApplicationDefinition(); + ClassLoader paCl = (ClassLoader) classLoaderMap.get(pa + .getId()); + if (paCl == null) { throw new UnavailableException( + "Portlet Application " + pa.getName() + + " not available"); } + + ClassLoader currentContextClassLoader = Thread + .currentThread().getContextClassLoader(); try { Class clazz = paCl.loadClass(className); try { - Thread.currentThread().setContextClassLoader(paCl); - validator = (PreferencesValidator)clazz.newInstance(); + Thread.currentThread().setContextClassLoader( + paCl); + validator = (PreferencesValidator) clazz + .newInstance(); validatorCache.put(pdId, validator); } finally { - Thread.currentThread().setContextClassLoader(currentContextClassLoader); + Thread.currentThread().setContextClassLoader( + currentContextClassLoader); } } catch (Exception e) { - String msg = "Cannot create PreferencesValidator instance "+className+" for Portlet "+pd.getName(); - log.error(msg,e); + String msg = "Cannot create PreferencesValidator instance " + + className + + " for Portlet " + + pd.getName(); + log.error(msg, e); } } } @@ -211,89 +235,107 @@ } /** - * Gets a portlet by either creating it or returning a handle to it from the portlet 'cache' + * Gets a portlet by either creating it or returning a handle to it from the + * portlet 'cache' * - * @param portletDefinition The definition of the portlet - * @return PortletInstance + * @param portletDefinition + * The definition of the portlet + * @return PortletInstance * @throws PortletException */ - public PortletInstance getPortletInstance( ServletContext servletContext, PortletDefinition pd ) throws PortletException + public PortletInstance getPortletInstance(ServletContext servletContext, + PortletDefinition pd) throws PortletException { PortletInstance portlet = null; String pdId = pd.getId().toString(); - PortletApplication pa = (PortletApplication)pd.getPortletApplicationDefinition(); + PortletApplication pa = (PortletApplication) pd + .getPortletApplicationDefinition(); try - { - synchronized (portletCache) - { - portlet = (PortletInstance)portletCache.get(pdId); - if (null != portlet) + { + synchronized (portletCache) { - return portlet; - } - - ClassLoader paCl = (ClassLoader)classLoaderMap.get(pa.getId()); - if ( paCl == null ) - { - throw new UnavailableException("Portlet Application "+pa.getName()+" not available"); - } - - ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader(); - - try - { - Class clazz = paCl.loadClass(pd.getClassName()); - try - { - Thread.currentThread().setContextClassLoader(paCl); - // wrap new Portlet inside PortletInstance which ensures the destroy - // method will wait for all its invocation threads to complete - // and thereby releasing all its ClassLoader locks as needed for local portlets. - - if (this.portletProxyUsed && !PortletObjectProxy.isPortletObjectProxied()) + portlet = (PortletInstance) portletCache.get(pdId); + if (null != portlet) { return portlet; } + + ClassLoader paCl = (ClassLoader) classLoaderMap.get(pa.getId()); + if (paCl == null) { throw new UnavailableException( + "Portlet Application " + pa.getName() + + " not available"); } + + ClassLoader currentContextClassLoader = Thread.currentThread() + .getContextClassLoader(); + + try { - portlet = new JetspeedPortletProxyInstance(pd.getName(), (Portlet)clazz.newInstance(), this.autoSwitchEditDefaultsModeToEditMode, this.autoSwitchConfigMode, this.customConfigModePortletUniqueName); + Class clazz = paCl.loadClass(pd.getClassName()); + try + { + Thread.currentThread().setContextClassLoader(paCl); + // wrap new Portlet inside PortletInstance which ensures + // the destroy + // method will wait for all its invocation threads to + // complete + // and thereby releasing all its ClassLoader locks as + // needed for local portlets. + + if (this.portletProxyUsed + && !PortletObjectProxy.isPortletObjectProxied()) + { + portlet = new JetspeedPortletProxyInstance(pd + .getName(), (Portlet) clazz.newInstance(), + this.autoSwitchEditDefaultsModeToEditMode, + this.autoSwitchConfigMode, + this.customConfigModePortletUniqueName); + } + else + { + portlet = new JetspeedPortletInstance(pd.getName(), + (Portlet) clazz.newInstance()); + } + } + finally + { + Thread.currentThread().setContextClassLoader( + currentContextClassLoader); + } } - else + catch (Exception e) { - portlet = new JetspeedPortletInstance(pd.getName(), (Portlet)clazz.newInstance()); + String msg = "Cannot create Portlet instance " + + pd.getClassName() + " for Portlet Application " + + pa.getName(); + log.error(msg, e); + throw new UnavailableException(msg); } + + PortletContext portletContext = PortalAccessor + .createPortletContext(servletContext, pa); + PortletConfig portletConfig = PortalAccessor + .createPortletConfig(portletContext, pd); + + try + { + try + { + Thread.currentThread().setContextClassLoader(paCl); + portlet.init(portletConfig); + } + finally + { + Thread.currentThread().setContextClassLoader( + currentContextClassLoader); + } + } + catch (PortletException e1) + { + log.error("Failed to initialize Portlet " + + pd.getClassName() + " for Portlet Application " + + pa.getName(), e1); + throw e1; + } + portletCache.put(pdId, portlet); } - finally - { - Thread.currentThread().setContextClassLoader(currentContextClassLoader); - } - } - catch (Exception e) - { - String msg = "Cannot create Portlet instance "+pd.getClassName()+" for Portlet Application "+pa.getName(); - log.error(msg,e); - throw new UnavailableException(msg); - } - - PortletContext portletContext = PortalAccessor.createPortletContext(servletContext, pa); - PortletConfig portletConfig = PortalAccessor.createPortletConfig(portletContext, pd); - - try - { - try - { - Thread.currentThread().setContextClassLoader(paCl); - portlet.init(portletConfig); - } - finally - { - Thread.currentThread().setContextClassLoader(currentContextClassLoader); - } - } - catch (PortletException e1) - { - log.error("Failed to initialize Portlet "+pd.getClassName()+" for Portlet Application "+pa.getName(), e1); - throw e1; - } - portletCache.put(pdId, portlet); - } } catch (PortletException pe) { @@ -301,39 +343,41 @@ } catch (Throwable e) { - log.error("PortletFactory: Failed to load portlet "+pd.getClassName(), e); - throw new UnavailableException( "Failed to load portlet " + pd.getClassName() +": "+e.toString()); + log.error("PortletFactory: Failed to load portlet " + + pd.getClassName(), e); + throw new UnavailableException("Failed to load portlet " + + pd.getClassName() + ": " + e.toString()); } return portlet; } - + public void updatePortletConfig(PortletDefinition pd) { if (pd != null) { - //System.out.println("$$$$ updating portlet config for " + pd.getName()); + // System.out.println("$$$$ updating portlet config for " + + // pd.getName()); String key = pd.getId().toString(); - PortletInstance instance = (PortletInstance)portletCache.get(key); + PortletInstance instance = (PortletInstance) portletCache.get(key); if (instance != null) { - JetspeedPortletConfig config = (JetspeedPortletConfig)instance.getConfig(); + JetspeedPortletConfig config = (JetspeedPortletConfig) instance + .getConfig(); config.setPortletDefinition(pd); } } } - + public ClassLoader getPortletApplicationClassLoader(PortletApplication pa) { synchronized (classLoaderMap) { - if ( pa != null ) - { - return (ClassLoader)classLoaderMap.get(pa.getId()); + if (pa != null) { return (ClassLoader) classLoaderMap.get(pa + .getId()); } + return null; } - return null; - } } - + public boolean isPortletApplicationRegistered(PortletApplication pa) { return getPortletApplicationClassLoader(pa) != null; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portlet-factory/src/java/org/apache/jetspeed/factory/JetspeedPortletInstance.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portlet-factory/src/java/org/apache/jetspeed/factory/JetspeedPortletInstance.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portlet-factory/src/java/org/apache/jetspeed/factory/JetspeedPortletInstance.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,93 +27,94 @@ import javax.portlet.RenderResponse; import javax.portlet.UnavailableException; -import org.apache.jetspeed.factory.PortletInstance; - /** * JetspeedPortletInstance * * @author Ate Douma * @version $Id: JetspeedPortletInstance.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class JetspeedPortletInstance implements PortletInstance { - private Portlet portlet; - private PortletConfig config; - private boolean destroyed; - private final String portletName; - - public JetspeedPortletInstance(String portletName, Portlet portlet) - { - this.portletName = portletName; - this.portlet = portlet; - } - - private void checkAvailable() throws UnavailableException - { - if ( destroyed ) - { - throw new UnavailableException("Portlet "+portletName+" no longer available"); - } - } - - public void destroy() - { - if (!destroyed) - { - destroyed = true; - if ( config != null ) - { - // Portlet really has been put into service, now destroy it. - portlet.destroy(); - } - } - } - - public boolean equals(Object obj) - { - return portlet.equals(obj); - } - - public int hashCode() - { - return portlet.hashCode(); - } - - public void init(PortletConfig config) throws PortletException - { - portlet.init(config); - this.config = config; - } - - public PortletConfig getConfig() - { - return config; - } - - public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException - { - checkAvailable(); - portlet.processAction(request, response); - } - - public void render(RenderRequest request, RenderResponse response) throws PortletException, IOException - { - checkAvailable(); - portlet.render(request, response); - } - - public String toString() - { - return portlet.toString(); - } + private Portlet portlet; -/** - * @return Returns the portlet. - */ -public Portlet getRealPortlet() -{ - return portlet; + private PortletConfig config; + + private boolean destroyed; + + private final String portletName; + + public JetspeedPortletInstance(String portletName, Portlet portlet) + { + this.portletName = portletName; + this.portlet = portlet; + } + + private void checkAvailable() throws UnavailableException + { + if (destroyed) { throw new UnavailableException("Portlet " + + portletName + " no longer available"); } + } + + public void destroy() + { + if (!destroyed) + { + destroyed = true; + if (config != null) + { + // Portlet really has been put into service, now destroy it. + portlet.destroy(); + } + } + } + + public boolean equals(Object obj) + { + return portlet.equals(obj); + } + + public int hashCode() + { + return portlet.hashCode(); + } + + public void init(PortletConfig config) throws PortletException + { + portlet.init(config); + this.config = config; + } + + public PortletConfig getConfig() + { + return config; + } + + public void processAction(ActionRequest request, ActionResponse response) + throws PortletException, IOException + { + checkAvailable(); + portlet.processAction(request, response); + } + + public void render(RenderRequest request, RenderResponse response) + throws PortletException, IOException + { + checkAvailable(); + portlet.render(request, response); + } + + public String toString() + { + return portlet.toString(); + } + + /** + * @return Returns the portlet. + */ + public Portlet getRealPortlet() + { + return portlet; + } } -} Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portlet-factory/src/java/org/apache/jetspeed/factory/JetspeedPortletProxyInstance.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portlet-factory/src/java/org/apache/jetspeed/factory/JetspeedPortletProxyInstance.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/portlet-factory/src/java/org/apache/jetspeed/factory/JetspeedPortletProxyInstance.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,13 +24,20 @@ * JetspeedPortletProxyInstance * * @author Woonsan Ko - * @version $Id: JetspeedPortletProxyInstance.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: JetspeedPortletProxyInstance.java 516448 2007-03-09 16:25:47Z + * ate $ + * */ public class JetspeedPortletProxyInstance extends JetspeedPortletInstance { - public JetspeedPortletProxyInstance(String portletName, Portlet portlet, boolean autoSwitchEditDefaultsModeToEditMode, boolean autoSwitchConfigMode, String customConfigModePortletUniqueName) + + public JetspeedPortletProxyInstance(String portletName, Portlet portlet, + boolean autoSwitchEditDefaultsModeToEditMode, + boolean autoSwitchConfigMode, + String customConfigModePortletUniqueName) { - super(portletName, (Portlet) PortletObjectProxy.createProxy(portlet, autoSwitchEditDefaultsModeToEditMode, autoSwitchConfigMode, customConfigModePortletUniqueName)); + super(portletName, (Portlet) PortletObjectProxy.createProxy(portlet, + autoSwitchEditDefaultsModeToEditMode, autoSwitchConfigMode, + customConfigModePortletUniqueName)); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/NodeImplProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/NodeImplProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/NodeImplProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,155 +17,154 @@ package org.apache.jetspeed.prefs.impl; - import java.sql.Timestamp; import java.util.Collection; import org.apache.jetspeed.prefs.om.Node; -public class NodeImplProxy implements Node +public class NodeImplProxy implements Node { + private Node node = null; + private boolean dirty = false; + private static PersistenceBrokerPreferencesProvider provider; - protected Object clone() throws CloneNotSupportedException - { - return super.clone(); - } + { + return super.clone(); + } - public Timestamp getCreationDate() - { - return getNode().getCreationDate(); - } + public Timestamp getCreationDate() + { + return getNode().getCreationDate(); + } - public String getFullPath() - { - return getNode().getFullPath(); - } + public String getFullPath() + { + return getNode().getFullPath(); + } - public Timestamp getModifiedDate() - { - return getNode().getModifiedDate(); - } + public Timestamp getModifiedDate() + { + return getNode().getModifiedDate(); + } - public long getNodeId() - { - return getNode().getNodeId(); - } + public long getNodeId() + { + return getNode().getNodeId(); + } - public Collection getNodeKeys() - { - return getNode().getNodeKeys(); - } + public Collection getNodeKeys() + { + return getNode().getNodeKeys(); + } - public String getNodeName() - { - return getNode().getNodeName(); - } + public String getNodeName() + { + return getNode().getNodeName(); + } - public Collection getNodeProperties() - { - return getNode().getNodeProperties(); - } + public Collection getNodeProperties() + { + return getNode().getNodeProperties(); + } - public int getNodeType() - { - return getNode().getNodeType(); - } + public int getNodeType() + { + return getNode().getNodeType(); + } - public Long getParentNodeId() - { - return getNode().getParentNodeId(); - } + public Long getParentNodeId() + { + return getNode().getParentNodeId(); + } - public void setCreationDate(Timestamp creationDate) - { - getNode().setCreationDate(creationDate); - } + public void setCreationDate(Timestamp creationDate) + { + getNode().setCreationDate(creationDate); + } - public void setFullPath(String fullPath) - { - getNode().setFullPath(fullPath); - } + public void setFullPath(String fullPath) + { + getNode().setFullPath(fullPath); + } - public void setModifiedDate(Timestamp modifiedDate) - { - getNode().setModifiedDate(modifiedDate); - } + public void setModifiedDate(Timestamp modifiedDate) + { + getNode().setModifiedDate(modifiedDate); + } - public void setNodeId(long nodeId) - { - getNode().setNodeId(nodeId); - } + public void setNodeId(long nodeId) + { + getNode().setNodeId(nodeId); + } - public void setNodeKeys(Collection nodeKeys) - { - getNode().setNodeKeys(nodeKeys); - } + public void setNodeKeys(Collection nodeKeys) + { + getNode().setNodeKeys(nodeKeys); + } - public void setNodeName(String nodeName) - { - getNode().setNodeName(nodeName); - - } + public void setNodeName(String nodeName) + { + getNode().setNodeName(nodeName); - public void setNodeProperties(Collection nodeProperties) - { - getNode().setNodeProperties(nodeProperties); - } + } - public void setNodeType(int nodeType) - { - getNode().setNodeType(nodeType); - } + public void setNodeProperties(Collection nodeProperties) + { + getNode().setNodeProperties(nodeProperties); + } - public void setParentNodeId(Long parentNodeId) - { - getNode().setParentNodeId(parentNodeId); - } + public void setNodeType(int nodeType) + { + getNode().setNodeType(nodeType); + } - public NodeImplProxy(Node node) + public void setParentNodeId(Long parentNodeId) { + getNode().setParentNodeId(parentNodeId); + } + + public NodeImplProxy(Node node) + { this.node = node; } public static void setProvider(PersistenceBrokerPreferencesProvider p) { - provider = p; + provider = p; } - - public Node getNode() + + public Node getNode() { - if (dirty) - reset(); + if (dirty) reset(); return node; } - protected void invalidate() { this.dirty = true; } - + public void setNode(Node node) { - this.node = node; + this.node = node; } + protected void reset() { - try - { - provider.redoNode(this,node.getFullPath(), node.getNodeType()); - dirty = false; - } - catch (Exception e) - { - e.printStackTrace(); - node = null; - } + try + { + provider.redoNode(this, node.getFullPath(), node.getNodeType()); + dirty = false; + } + catch (Exception e) + { + e.printStackTrace(); + node = null; + } } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PersistenceBrokerPreferencesProvider.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PersistenceBrokerPreferencesProvider.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PersistenceBrokerPreferencesProvider.java 2008-05-16 01:54:54 UTC (rev 940) @@ -487,15 +487,15 @@ NodeCache key = new NodeCache(hit); getPersistenceBrokerTemplate().store(hit.getNode()); // avoid racing - // condition - // with the db - // and with - // cluster - // notification + // condition + // with the db + // and with + // cluster + // notification // do the db first preferenceCache.remove(key.getCacheKey()); // not sure we should - // actually do that, could - // also just update the node + // actually do that, could + // also just update the node addToCache(key); } @@ -512,12 +512,12 @@ { getPersistenceBrokerTemplate().delete( ((NodeImplProxy) node).getNode()); // avoid race conditions - // - do this first + // - do this first } else getPersistenceBrokerTemplate().delete(node); // avoid race - // conditions - do - // this first + // conditions - do + // this first if (node instanceof NodeImplProxy) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/om/impl/NodeImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/om/impl/NodeImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/om/impl/NodeImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,6 +34,7 @@ */ public class NodeImpl implements Node { + /** The serial version uid. */ private static final long serialVersionUID = -5367800007757021163L; @@ -75,12 +76,17 @@ *
      • Full path.
      • *
      * - * @param parentNodeId The parent node id. - * @param nodeName The node name. - * @param nodeType The node type. - * @param fullPath The full path. + * @param parentNodeId + * The parent node id. + * @param nodeName + * The node name. + * @param nodeType + * The node type. + * @param fullPath + * The full path. */ - public NodeImpl(Long parentNodeId, String nodeName, int nodeType, String fullPath) + public NodeImpl(Long parentNodeId, String nodeName, int nodeType, + String fullPath) { this.parentNodeId = parentNodeId; this.nodeName = nodeName; @@ -240,7 +246,8 @@ public boolean equals(Object o) { - return fullPath != null && o != null && o instanceof NodeImpl && ((NodeImpl) o).fullPath != null + return fullPath != null && o != null && o instanceof NodeImpl + && ((NodeImpl) o).fullPath != null && fullPath.equals(((NodeImpl) o).fullPath); } @@ -253,10 +260,13 @@ */ public String toString() { - String toStringNode = "[[parentNodeId, " + this.parentNodeId + "], " + "[nodeName, " + this.nodeName + "], " - + "[fullPath, " + this.fullPath + "], " + "[nodeType, " + this.nodeType + "], " + "[nodeKeys, " - + this.nodeKeys + "], " + "[nodeProperties, " + this.nodeProperties + "], " + "[creationDate, " - + this.creationDate + "], " + "[modifiedDate, " + this.modifiedDate + "]]"; + String toStringNode = "[[parentNodeId, " + this.parentNodeId + "], " + + "[nodeName, " + this.nodeName + "], " + "[fullPath, " + + this.fullPath + "], " + "[nodeType, " + this.nodeType + "], " + + "[nodeKeys, " + this.nodeKeys + "], " + "[nodeProperties, " + + this.nodeProperties + "], " + "[creationDate, " + + this.creationDate + "], " + "[modifiedDate, " + + this.modifiedDate + "]]"; return toStringNode; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/om/impl/PropertyImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/om/impl/PropertyImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/om/impl/PropertyImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,6 +32,7 @@ */ public class PropertyImpl implements Property { + /** The serial version uid. */ private static final long serialVersionUID = 7037975617489867366L; @@ -56,9 +57,12 @@ * Property constructor given a property key id, node id and the appropriate * value. * - * @param nodeId The node id. - * @param propertyName The property name. - * @param valueObject The value object. + * @param nodeId + * The node id. + * @param propertyName + * The property name. + * @param valueObject + * The value object. */ public PropertyImpl(long nodeId, String propertyName, Object valueObject) { @@ -127,7 +131,8 @@ } /** - * @param propertyName The propertyName to set. + * @param propertyName + * The propertyName to set. */ public void setPropertyName(String propertyName) { @@ -179,8 +184,10 @@ */ public String toString() { - String toStringProperty = "[[nodeId, " + this.nodeId + "], " + "[propertyValue, " + getPropertyValue() + "], " - + "[creationDate, " + this.creationDate + "], " + "[modifiedDate, " + this.modifiedDate + "]]"; + String toStringProperty = "[[nodeId, " + this.nodeId + "], " + + "[propertyValue, " + getPropertyValue() + "], " + + "[creationDate, " + this.creationDate + "], " + + "[modifiedDate, " + this.modifiedDate + "]]"; return toStringProperty; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/util/test/AbstractPrefsSupportedTestCase.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/util/test/AbstractPrefsSupportedTestCase.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/util/test/AbstractPrefsSupportedTestCase.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,22 +25,25 @@ *

      * * @author Scott T. Weaver - * @version $Id: AbstractPrefsSupportedTestCase.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: AbstractPrefsSupportedTestCase.java 516448 2007-03-09 16:25:47Z + * ate $ */ -public class AbstractPrefsSupportedTestCase extends DatasourceEnabledSpringTestCase +public class AbstractPrefsSupportedTestCase extends + DatasourceEnabledSpringTestCase { + protected PreferencesProvider prefsProvider; protected String[] getConfigurations() { return new String[] - { "prefs.xml", "transaction.xml", "cache.xml" }; + {"prefs.xml", "transaction.xml", "cache.xml"}; } protected String[] getBootConfigurations() { return new String[] - { "boot/datasource.xml" }; + {"boot/datasource.xml"}; } protected void setUp() throws Exception Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestNodePreferences.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestNodePreferences.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestNodePreferences.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,6 +28,7 @@ public class TestNodePreferences extends DatasourceEnabledSpringTestCase { + private PreferencesProvider provider; /** @@ -35,8 +36,8 @@ */ public void setUp() throws Exception { - super.setUp(); - provider = (PreferencesProvider) ctx.getBean("prefsProvider"); + super.setUp(); + provider = (PreferencesProvider) ctx.getBean("prefsProvider"); } /** @@ -55,22 +56,26 @@ // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestNodePreferences.class); } - /** *

      * Test node and whether children exist under a given node. *

      */ - String [] users = { "guest", "david", "admin" }; + String[] users = + {"guest", "david", "admin"}; + int ENTITY_SIZE = 50; + int PREF_SIZE = 20; + boolean reset = false; + boolean disableReads = false; - + public void testNodes() { - if (1 == 1) return ; // disable this test, its a performance test + if (1 == 1) return; // disable this test, its a performance test assertNotNull("provider is null", provider); Node entityRoot = null; try @@ -80,8 +85,9 @@ assertNotNull("root node is null", root); if (!provider.nodeExists("/portlet_entity", 0)) { - entityRoot = provider.createNode(root, "portlet_entity", 0, "/portlet_entity"); - assertNotNull("entity-root node is null", entityRoot); + entityRoot = provider.createNode(root, "portlet_entity", 0, + "/portlet_entity"); + assertNotNull("entity-root node is null", entityRoot); } else { @@ -89,11 +95,12 @@ { Node pe = provider.getNode("/portlet_entity", 0); provider.removeNode(root, pe); - entityRoot = provider.createNode(root, "portlet_entity", 0, "/portlet_entity"); + entityRoot = provider.createNode(root, "portlet_entity", 0, + "/portlet_entity"); assertNotNull("entity-root node is null", entityRoot); } else - hasBeenPopulated = true; + hasBeenPopulated = true; } if (entityRoot == null) entityRoot = provider.getNode("/portlet_entity", 0); @@ -102,37 +109,47 @@ for (int ix = 0; ix < ENTITY_SIZE; ix++) { String path = "/portlet_entity/" + ix; - Node entity = provider.createNode(entityRoot, new Integer(ix).toString(), 0, path); + Node entity = provider.createNode(entityRoot, new Integer( + ix).toString(), 0, path); assertNotNull(path, entity); for (int iy = 0; iy < users.length; iy++) { - String uPath = "/portlet_entity/" + ix + "/" + users[iy]; - Node uEntity = provider.createNode(entity, users[iy], 0, uPath); + String uPath = "/portlet_entity/" + ix + "/" + + users[iy]; + Node uEntity = provider.createNode(entity, users[iy], + 0, uPath); assertNotNull(uPath, uEntity); String pPath = uPath + "/preferences"; - Node pEntity = provider.createNode(uEntity, "preferences", 0, pPath); + Node pEntity = provider.createNode(uEntity, + "preferences", 0, pPath); assertNotNull(pPath, pEntity); for (int iz = 0; iz < PREF_SIZE; iz++) { String zPath = pPath + "/pref-" + iz; - Node zEntity = provider.createNode(pEntity, "pref-" + iz, 0, zPath); + Node zEntity = provider.createNode(pEntity, "pref-" + + iz, 0, zPath); assertNotNull(zPath, zEntity); // size node - Node size = provider.createNode(zEntity, "size", 0, zPath + "/size" ); - assertNotNull(zPath + "/size", size); + Node size = provider.createNode(zEntity, "size", 0, + zPath + "/size"); + assertNotNull(zPath + "/size", size); // values node - Node values = provider.createNode(zEntity, "values", 0, zPath + "/values" ); - assertNotNull(values + "/values", values); + Node values = provider.createNode(zEntity, + "values", 0, zPath + "/values"); + assertNotNull(values + "/values", values); // size property - Property sizeProp = provider.createProperty(size, "size", "1"); + Property sizeProp = provider.createProperty(size, + "size", "1"); size.getNodeProperties().add(sizeProp); provider.storeNode(size); // values property - Property valueProp = provider.createProperty(values, "0", new Integer(iz + 1000).toString()); + Property valueProp = provider.createProperty( + values, "0", new Integer(iz + 1000) + .toString()); values.getNodeProperties().add(valueProp); provider.storeNode(values); } - } + } } } // Test for data using both new and old paths @@ -146,7 +163,8 @@ for (int iz = 0; iz < PREF_SIZE; iz++) { Node n; - String key = "/portlet_entity/" + ix + "/" + users[iy] + "/preferences/pref-" + iz; + String key = "/portlet_entity/" + ix + "/" + + users[iy] + "/preferences/pref-" + iz; n = provider.getNode(key, 0); assertNotNull("null pref: " + key, n); Collection c = provider.getChildren(n); @@ -154,32 +172,41 @@ Iterator it = c.iterator(); while (it.hasNext()) { - Node child = (Node)it.next(); + Node child = (Node) it.next(); if (child.getNodeName().equals("size")) { - Object props[] = child.getNodeProperties().toArray(); - assertTrue("props isa ", (props[0] instanceof Property)); - Property p = (Property)props[0]; + Object props[] = child.getNodeProperties() + .toArray(); + assertTrue("props isa ", + (props[0] instanceof Property)); + Property p = (Property) props[0]; String size = p.getPropertyValue(); - assertTrue("child size name ", "size".equals(p.getPropertyName())); - assertTrue("child size value ", "1".equals(size)); + assertTrue("child size name ", "size" + .equals(p.getPropertyName())); + assertTrue("child size value ", "1" + .equals(size)); } else if (child.getNodeName().equals("values")) { - Object props[] = child.getNodeProperties().toArray(); - assertTrue("props isa ", (props[0] instanceof Property)); - Property p = (Property)props[0]; + Object props[] = child.getNodeProperties() + .toArray(); + assertTrue("props isa ", + (props[0] instanceof Property)); + Property p = (Property) props[0]; String value = p.getPropertyValue(); - assertTrue("child value name ", "0".equals(p.getPropertyName())); - assertTrue("child value value ", new Integer(iz + 1000).toString().equals(value)); + assertTrue("child value name ", "0" + .equals(p.getPropertyName())); + assertTrue("child value value ", + new Integer(iz + 1000).toString() + .equals(value)); } - + } } } } long end = System.currentTimeMillis(); - System.out.println("Retrieval time total: " + (end - start)); + System.out.println("Retrieval time total: " + (end - start)); } } catch (Exception e) @@ -195,6 +222,6 @@ protected String[] getConfigurations() { return new String[] - { "prefs.xml", "transaction.xml", "cache.xml" }; + {"prefs.xml", "transaction.xml", "cache.xml"}; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestPreferences.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestPreferences.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestPreferences.java 2008-05-16 01:54:54 UTC (rev 940) @@ -40,7 +40,7 @@ public void setUp() throws Exception { super.setUp(); - + // Make sure we are starting with a clean slate clearChildren(Preferences.userRoot()); clearChildren(Preferences.systemRoot()); @@ -62,7 +62,7 @@ // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestPreferences.class); } - + /** *

      * Test user root. @@ -74,7 +74,8 @@ Preferences prefs = Preferences.userRoot(); if (null != prefs) { - assertTrue("expected user root == '/', " + prefs.absolutePath(), prefs.absolutePath().equals("/")); + assertTrue("expected user root == '/', " + prefs.absolutePath(), + prefs.absolutePath().equals("/")); } else { @@ -92,7 +93,8 @@ Preferences prefs = Preferences.systemRoot(); if (null != prefs) { - assertTrue("expected system root == '/', " + prefs.absolutePath(), prefs.absolutePath().equals("/")); + assertTrue("expected system root == '/', " + prefs.absolutePath(), + prefs.absolutePath().equals("/")); } else { @@ -114,8 +116,8 @@ String[] childrenNames = prefs.childrenNames(); if (childrenNames.length > 0) { - assertTrue("expected no children, " + childrenNames.length + ", " + childrenNames[0], - childrenNames.length == 0); + assertTrue("expected no children, " + childrenNames.length + + ", " + childrenNames[0], childrenNames.length == 0); } } catch (BackingStoreException bse) @@ -127,19 +129,21 @@ // 1. The node does not exist. Create it. Preferences prefs0 = Preferences.userRoot().node("/an1/san1"); assertNotNull("should not be null", prefs0); - assertTrue("expected node == /an1/san1, " + prefs0.absolutePath(), prefs0.absolutePath().equals("/an1/san1")); + assertTrue("expected node == /an1/san1, " + prefs0.absolutePath(), + prefs0.absolutePath().equals("/an1/san1")); // 2. If node exists. Get it. Preferences prefs1 = Preferences.userRoot().node("/an1/san1"); assertNotNull("should not be null", prefs1); - assertTrue("expected node == /an1/san1, " + prefs1.absolutePath(), prefs1.absolutePath().equals("/an1/san1")); + assertTrue("expected node == /an1/san1, " + prefs1.absolutePath(), + prefs1.absolutePath().equals("/an1/san1")); // Relative path. Preferences prefs3 = Preferences.userRoot().node("/an1"); Preferences prefs4 = prefs3.node("rn1/srn1"); assertNotNull("should not be null", prefs4); - assertTrue("expected node == /an1/rn1/srn1, " + prefs4.absolutePath(), prefs4.absolutePath().equals( - "/an1/rn1/srn1")); + assertTrue("expected node == /an1/rn1/srn1, " + prefs4.absolutePath(), + prefs4.absolutePath().equals("/an1/rn1/srn1")); try { @@ -165,16 +169,19 @@ /** *

      - * Test adding properties to a property set node and get property keys for a given node. + * Test adding properties to a property set node and get property keys for a + * given node. *

      * * @throws Exception */ public void testPropertyAndPropertyKeys() throws Exception { - // 1. Current node does not have any property associated to it. We are adding + // 1. Current node does not have any property associated to it. We are + // adding // a property at the user root level. - // No property has been defined nor added to the node. This should return + // No property has been defined nor added to the node. This should + // return // the property value Preferences pref0 = Preferences.userRoot(); try @@ -182,8 +189,8 @@ String[] propertyKeys = pref0.keys(); if (propertyKeys.length > 0) { - assertTrue("expected no children, " + propertyKeys.length + ", " + propertyKeys[0], - propertyKeys.length == 0); + assertTrue("expected no children, " + propertyKeys.length + + ", " + propertyKeys[0], propertyKeys.length == 0); } } catch (BackingStoreException bse) @@ -196,7 +203,8 @@ assertTrue("should be prop == true.", prop.equals("true")); // 2. Current node has properties associated to it. - Preferences pref1 = Preferences.userRoot().node("/user/principal1/propertyset1"); + Preferences pref1 = Preferences.userRoot().node( + "/user/principal1/propertyset1"); pref1.put("propertyName0", "true"); String prop1 = pref1.get("propertyName0", null); assertTrue("expected prop1 == true, " + prop1, prop1.equals("true")); @@ -254,7 +262,9 @@ try { removeNode.childrenNames(); - assertFalse("An IllegalStateException should have been thrown by the AbtractPreferences class", true); + assertFalse( + "An IllegalStateException should have been thrown by the AbtractPreferences class", + true); } catch (IllegalStateException e) { @@ -291,6 +301,6 @@ protected String[] getConfigurations() { return new String[] - { "prefs.xml", "transaction.xml", "cache.xml" }; + {"prefs.xml", "transaction.xml", "cache.xml"}; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestPreferencesNoPropManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestPreferencesNoPropManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestPreferencesNoPropManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /* * Created on Oct 21, 2004 * @@ -32,9 +32,11 @@ *

      * * @author Scott T. Weaver - * @version $Id: TestPreferencesNoPropManager.java 516881 2007-03-11 10:34:21Z ate $ + * @version $Id: TestPreferencesNoPropManager.java 516881 2007-03-11 10:34:21Z + * ate $ */ -public class TestPreferencesNoPropManager extends AbstractPrefsSupportedTestCase +public class TestPreferencesNoPropManager extends + AbstractPrefsSupportedTestCase { /** @@ -69,8 +71,8 @@ /** *

      - * Legacy test from the times where we add a property manager. The property manager is - * since gone, but the test still tests the prefs implementation. + * Legacy test from the times where we add a property manager. The property + * manager is since gone, but the test still tests the prefs implementation. *

      * * @throws Exception @@ -97,6 +99,6 @@ protected String[] getConfigurations() { return new String[] - { "prefs.xml", "transaction.xml", "cache.xml" }; + {"prefs.xml", "transaction.xml", "cache.xml"}; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestPreferencesProvider.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestPreferencesProvider.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/test/org/apache/jetspeed/prefs/TestPreferencesProvider.java 2008-05-16 01:54:54 UTC (rev 940) @@ -35,6 +35,7 @@ */ public class TestPreferencesProvider extends DatasourceEnabledSpringTestCase { + private PreferencesProvider provider; /** @@ -69,13 +70,15 @@ public void testLookupProperty() throws Exception { - Preferences info = Preferences.userRoot().node("/user/dynamite/userinfo"); + Preferences info = Preferences.userRoot().node( + "/user/dynamite/userinfo"); info.put("user.name.family", "Dynamite"); info.put("user.name.given", "Napolean"); info.put("user.email", "napolean ¡÷ dynamite.xxx"); info.flush(); - Iterator result = provider.lookupPreference("userinfo", "user.email", "napolean ¡÷ dynamite.xxx").iterator(); + Iterator result = provider.lookupPreference("userinfo", "user.email", + "napolean ¡÷ dynamite.xxx").iterator(); int count = 0; while (result.hasNext()) { @@ -89,16 +92,19 @@ String value = prop.getPropertyValue(); if ("user.name.family".equals(name)) { - assertTrue("family name wrong " + value, "Dynamite".equals(value)); + assertTrue("family name wrong " + value, "Dynamite" + .equals(value)); } else if ("user.name.given".equals(name)) { - assertTrue("given name wrong " + value, "Napolean".equals(value)); + assertTrue("given name wrong " + value, "Napolean" + .equals(value)); } else if ("user.email".equals(name)) { - assertTrue("email is wrong " + value, "napolean ¡÷ dynamite.xxx".equals(value)); - } + assertTrue("email is wrong " + value, + "napolean ¡÷ dynamite.xxx".equals(value)); + } else { assertTrue("bad property name " + name, false); @@ -131,6 +137,7 @@ */ protected String[] getConfigurations() { - return new String[] { "prefs.xml", "transaction.xml", "cache.xml" }; + return new String[] + {"prefs.xml", "transaction.xml", "cache.xml"}; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/impl/JetspeedProfilerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/impl/JetspeedProfilerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/impl/JetspeedProfilerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -54,34 +54,38 @@ * @author David Sean Taylor * @version $Id: JetspeedProfilerImpl.java 553647 2007-07-05 21:42:04Z taylor $ */ -public class JetspeedProfilerImpl extends InitablePersistenceBrokerDaoSupport +public class JetspeedProfilerImpl extends InitablePersistenceBrokerDaoSupport implements Profiler, BeanFactoryAware { + /** The default rule. */ public final static String DEFAULT_RULE = "j1"; - + /** Commons logging */ - protected final static Log log = LogFactory.getLog(JetspeedProfilerImpl.class); + protected final static Log log = LogFactory + .getLog(JetspeedProfilerImpl.class); /** - * This is the princapl that is used if there are no principal to rule associations for the current principal + * This is the princapl that is used if there are no principal to rule + * associations for the current principal */ - public final static Principal DEFAULT_RULE_PRINCIPAL = new UserPrincipalImpl("*"); + public final static Principal DEFAULT_RULE_PRINCIPAL = new UserPrincipalImpl( + "*"); /** The default locator class implementation */ private String locatorBean = "ProfileLocator"; /** The default principalRule association class implementation */ private Class prRuleClass; - + private String principalRuleBean = "PrincipalRule"; - + /** The base (abstract) profilingRule class implementation */ private String profilingRuleStandardBean = "StandardProfilingRule"; - + /** The base (abstract) profilingRule class implementation */ - private String profilingRuleFallbackBean = "RoleFallbackProfilingRule"; - + private String profilingRuleFallbackBean = "RoleFallbackProfilingRule"; + /** The base (abstract) profilingRule class implementation */ private Class profilingRuleClass = AbstractProfilingRule.class; @@ -294,7 +298,8 @@ pr.setProfilingRule(rule); principalRules.put(makePrincipalRuleKey(principal.getName(), locatorName), pr); - } else + } + else { // Get the associated rule rule = pr.getProfilingRule(); @@ -316,7 +321,8 @@ { PrincipalRule tempRule = createPrincipalRule(); this.prRuleClass = tempRule.getClass(); - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } @@ -567,8 +573,9 @@ { getPersistenceBrokerTemplate().delete(rule); rulesPerPrincipal.remove(rule.getPrincipalName()); - String key = this.makePrincipalRuleKey(rule.getPrincipalName(), rule.getLocatorName()); - principalRules.remove(key); + String key = this.makePrincipalRuleKey(rule.getPrincipalName(), rule + .getLocatorName()); + principalRules.remove(key); } /* @@ -599,7 +606,8 @@ { this.locatorBean = beanName; } - } catch (Exception e) + } + catch (Exception e) { String msg = "Exception in setting locatorbeanName : " + e.getLocalizedMessage(); @@ -611,7 +619,8 @@ { this.principalRuleBean = beanName; } - } catch (Exception e) + } + catch (Exception e) { String msg = "Exception in setting principalRulebeanName : " + e.getLocalizedMessage(); @@ -623,7 +632,8 @@ { this.profilingRuleStandardBean = beanName; } - } catch (Exception e) + } + catch (Exception e) { String msg = "Exception in setting profilingRuleStandardbeanName : " + e.getLocalizedMessage(); @@ -635,7 +645,8 @@ { this.profilingRuleFallbackBean = beanName; } - } catch (Exception e) + } + catch (Exception e) { String msg = "Exception in setting profilingRuleFallback : " + e.getLocalizedMessage(); @@ -661,7 +672,8 @@ return (ProfilingRule) beanFactory.getBean( this.profilingRuleFallbackBean, ProfilingRule.class); - } catch (BeansException e) + } + catch (BeansException e) { throw new ClassNotFoundException("Spring failed to create the " + (standard ? "standard" : "fallback") @@ -682,7 +694,8 @@ this.locatorBean, ProfileLocator.class); locator.init(this, context.getPath()); return locator; - } catch (Exception e) + } + catch (Exception e) { log.error("Failed to create locator for " + this.locatorBean + " error : " + e.getLocalizedMessage()); @@ -702,7 +715,8 @@ PrincipalRule principalRule = (PrincipalRule) beanFactory.getBean( this.principalRuleBean, PrincipalRule.class); return principalRule; - } catch (Exception e) + } + catch (Exception e) { log.error("Failed to create principalRule for " + principalRuleBean + " error : " + e.getLocalizedMessage()); @@ -724,7 +738,8 @@ RuleCriterion ruleCriterion = (RuleCriterion) beanFactory.getBean( this.ruleCriterionBean, RuleCriterion.class); return ruleCriterion; - } catch (Exception e) + } + catch (Exception e) { log.error("Failed to create principalRule for " + ruleCriterionBean + " error : " + e.getLocalizedMessage()); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/AbstractProfilingRule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/AbstractProfilingRule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/AbstractProfilingRule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,6 +20,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; + import org.apache.jetspeed.profiler.ProfileLocator; import org.apache.jetspeed.profiler.Profiler; import org.apache.jetspeed.profiler.rules.ProfileResolvers; @@ -30,46 +31,57 @@ /** * ProfilingRuleImpl - * + * * @author David Sean Taylor * @version $Id: AbstractProfilingRule.java 605772 2007-12-20 01:14:31Z taylor $ */ public abstract class AbstractProfilingRule implements ProfilingRule { - private static final long serialVersionUID = 1; + + private static final long serialVersionUID = 1; + protected Collection criteria = new RemovalAwareCollection(); + protected String id; + protected String title; + protected String ojbConcreteClass; - - /** Map of profile locators kept around for reuse TODO: evict entries after max size reached */ + + /** + * Map of profile locators kept around for reuse TODO: evict entries after + * max size reached + */ protected Map locators = Collections.synchronizedMap(new HashMap()); - - /** Map of resolver rules for criteria. The map goes from criterion name to resolver class */ + + /** + * Map of resolver rules for criteria. The map goes from criterion name to + * resolver class + */ protected ProfileResolvers resolvers; public AbstractProfilingRule() - { + { } - - public AbstractProfilingRule(ProfileResolvers resolvers) + + public AbstractProfilingRule(ProfileResolvers resolvers) { this.resolvers = resolvers; } - - + protected ProfileLocator getLocatorFromCache(String key) { - return (ProfileLocator)locators.get(key); + return (ProfileLocator) locators.get(key); } - - + protected void addLocatorToCache(String key, ProfileLocator locator) { locators.put(key, locator); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.ProfilingRule#getResolver(java.lang.String) */ public RuleCriterionResolver getResolver(String name) @@ -81,81 +93,96 @@ { return resolvers.get(RuleCriterionResolver.REQUEST); } - - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.ProfilingRule#apply(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.Profiler) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.ProfilingRule#apply(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.Profiler) */ - public abstract ProfileLocator apply(RequestContext context, Profiler service); - - /* (non-Javadoc) + public abstract ProfileLocator apply(RequestContext context, + Profiler service); + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.ProfilingRule#getRuleCriterion() */ public Collection getRuleCriteria() { return criteria; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.ProfilingRule#getId() */ public String getId() { - return this.id; + return this.id; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.ProfilingRule#setId(java.lang.String) */ public void setId(String id) { this.id = id; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.ProfilingRule#getTitle() */ public String getTitle() { return this.title; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.ProfilingRule#setTitle(java.lang.String) */ public void setTitle(String title) { - this.title = title; + this.title = title; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.ProfilingRule#getClassname() */ public String getClassname() { return this.ojbConcreteClass; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.ProfilingRule#setClassname(java.lang.String) */ public void setClassname(String classname) { this.ojbConcreteClass = classname; } - + public String toString() { if (id != null) { return id; } - else if (title != null) - { - return title; - } + else if (title != null) { return title; } return this.getClass().toString(); } - + /** * @return Returns the resolvers. */ @@ -163,15 +190,14 @@ { return resolvers; } + /** - * @param resolvers The resolvers to set. + * @param resolvers + * The resolvers to set. */ public void setResolvers(ProfileResolvers resolvers) { this.resolvers = resolvers; } - - - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/CountryCriterionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/CountryCriterionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/CountryCriterionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,42 +21,41 @@ import org.apache.jetspeed.request.RequestContext; /** - * CountryCriterionResolver - * Resolve Rules: - * 1. Request Parameter (Standard) - * 2. Locale.CountryCode - * + * CountryCriterionResolver Resolve Rules: 1. Request Parameter (Standard) 2. + * Locale.CountryCode + * * @author David Sean Taylor * @version $Id: CountryCriterionResolver.java 516448 2007-03-09 16:25:47Z ate $ */ -public class CountryCriterionResolver - extends StandardResolver - implements RuleCriterionResolver +public class CountryCriterionResolver extends StandardResolver implements + RuleCriterionResolver { - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.rules.RuleCriterion) - */ + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.rules.RuleCriterion) + */ public String resolve(RequestContext context, RuleCriterion criterion) { // look for override String value = super.resolve(context, criterion); - if (value != null) - { - return value.toUpperCase(); - } - + if (value != null) { return value.toUpperCase(); } + String country = context.getLocale().getCountry(); - if (country != null) - country = country.toUpperCase(); + if (country != null) country = country.toUpperCase(); return country; - } - - /* (non-Javadoc) + } + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#isControl() */ public boolean isControl(RuleCriterion criterion) { return true; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/DomainCriterionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/DomainCriterionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/DomainCriterionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -72,7 +72,8 @@ if (idx != -1) { domain = servername.substring(idx + 1, servername.length()); - } else + } + else { // maybe there is no domain // testing for IPv6 IP Address @@ -82,7 +83,8 @@ // TODO resolving IP Address? // no domain is available domain = ""; - } else + } + else { // no domain is available domain = ""; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/GroupCriterionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/GroupCriterionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/GroupCriterionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,49 +26,52 @@ import org.apache.jetspeed.security.GroupPrincipal; /** - * Standard Jetspeed-1 Group resolver. - * It first looks at the value in the criterion record. - * If it is null, it then falls back to a request parameter. - * If it is null it gives up and returns null allowing subclasses - * to continue processing. - * + * Standard Jetspeed-1 Group resolver. It first looks at the value in the + * criterion record. If it is null, it then falls back to a request parameter. + * If it is null it gives up and returns null allowing subclasses to continue + * processing. + * * @author David Sean Taylor * @version $Id: GroupCriterionResolver.java 516448 2007-03-09 16:25:47Z ate $ */ -public class GroupCriterionResolver - extends StandardResolver - implements RuleCriterionResolver +public class GroupCriterionResolver extends StandardResolver implements + RuleCriterionResolver { - protected final static Log log = LogFactory.getLog(UserCriterionResolver.class); - - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.rules.RuleCriterion) - */ - public String resolve(RequestContext context, RuleCriterion criterion) - { - String value = super.resolve(context, criterion); - if (value != null) - { - return value; - } - - Subject subject = context.getSubject(); - if (subject == null) - { - String msg = "Invalid (null) Subject in request pipeline"; - log.error(msg); - return null; - } - return resolvePrincipals(context, criterion, subject, GroupPrincipal.class); - } - - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#isControl() - */ - public boolean isControl(RuleCriterion criterion) - { - return true; - } - + protected final static Log log = LogFactory + .getLog(UserCriterionResolver.class); + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.rules.RuleCriterion) + */ + public String resolve(RequestContext context, RuleCriterion criterion) + { + String value = super.resolve(context, criterion); + if (value != null) { return value; } + + Subject subject = context.getSubject(); + if (subject == null) + { + String msg = "Invalid (null) Subject in request pipeline"; + log.error(msg); + return null; + } + + return resolvePrincipals(context, criterion, subject, + GroupPrincipal.class); + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#isControl() + */ + public boolean isControl(RuleCriterion criterion) + { + return true; + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/GroupRoleUserCriterionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/GroupRoleUserCriterionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/GroupRoleUserCriterionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,31 +22,34 @@ import org.apache.jetspeed.request.RequestContext; /** - * Standard Jetspeed-1 Group/Role/User resolver. - * First looking for a group request parameter, then a role request parameter, - * then a user request parameter. If none are found, then it uses the - * current user's principal. + * Standard Jetspeed-1 Group/Role/User resolver. First looking for a group + * request parameter, then a role request parameter, then a user request + * parameter. If none are found, then it uses the current user's principal. * - * If it is null, it then falls back to a request parameter. - * If it is null it gives up and returns null allowing subclasses - * to continue processing. + * If it is null, it then falls back to a request parameter. If it is null it + * gives up and returns null allowing subclasses to continue processing. * * Since there is no 1:1 value for a combination rule of group, the criterion's * value is ignored. - * + * * @author David Sean Taylor - * @version $Id: GroupRoleUserCriterionResolver.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: GroupRoleUserCriterionResolver.java 516448 2007-03-09 16:25:47Z + * ate $ */ -public class GroupRoleUserCriterionResolver - extends UserCriterionResolver - implements RuleCriterionResolver -{ - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.rules.RuleCriterion) - */ +public class GroupRoleUserCriterionResolver extends UserCriterionResolver + implements RuleCriterionResolver +{ + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.rules.RuleCriterion) + */ public String resolve(RequestContext context, RuleCriterion criterion) { - String value = context.getRequestParameter(ProfilingRule.STANDARD_GROUP); + String value = context + .getRequestParameter(ProfilingRule.STANDARD_GROUP); if (value != null) { criterion.setName(ProfilingRule.STANDARD_GROUP); @@ -55,15 +58,13 @@ value = context.getRequestParameter(ProfilingRule.STANDARD_ROLE); if (value != null) { - criterion.setName(ProfilingRule.STANDARD_ROLE); + criterion.setName(ProfilingRule.STANDARD_ROLE); return value; } - // use the User Criterion to resolve it + // use the User Criterion to resolve it criterion.setName(ProfilingRule.STANDARD_USER); return super.resolve(context, criterion); - } - - - + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/HardCodedResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/HardCodedResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/HardCodedResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,14 +22,19 @@ /** * HardCodedResolver - * + * * @author David Sean Taylor * @version $Id: HardCodedResolver.java 516448 2007-03-09 16:25:47Z ate $ */ -public class HardCodedResolver extends StandardResolver implements RuleCriterionResolver +public class HardCodedResolver extends StandardResolver implements + RuleCriterionResolver { - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.rules.RuleCriterion) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.rules.RuleCriterion) */ public String resolve(RequestContext context, RuleCriterion criterion) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/HostnameCriterionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/HostnameCriterionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/HostnameCriterionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,8 +29,9 @@ public class HostnameCriterionResolver extends StandardResolver implements RuleCriterionResolver { + boolean useDotPrefix = false; - + public HostnameCriterionResolver(boolean usePrefix) { super(); @@ -59,13 +60,14 @@ public String resolve(RequestContext context, RuleCriterion criterion) { - String serverName = context.getRequest().getServerName(); + String serverName = context.getRequest().getServerName(); if (useDotPrefix) { int idx = serverName.indexOf("."); if (idx != -1) { - // SUFFIX: hostname = servername.substring(idx + 1, servername.length()); + // SUFFIX: hostname = servername.substring(idx + 1, + // servername.length()); serverName = serverName.substring(0, idx); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/LanguageCriterionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/LanguageCriterionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/LanguageCriterionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,39 +22,39 @@ /** * LanguageCriterionResolver - * + * * @author David Sean Taylor * @version $Id: LanguageCriterionResolver.java 516448 2007-03-09 16:25:47Z ate $ */ -public class LanguageCriterionResolver - extends StandardResolver - implements RuleCriterionResolver +public class LanguageCriterionResolver extends StandardResolver implements + RuleCriterionResolver { - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.rules.RuleCriterion) - */ + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.rules.RuleCriterion) + */ public String resolve(RequestContext context, RuleCriterion criterion) { // look for override String value = super.resolve(context, criterion); - if (value != null) - { - return value.toLowerCase(); - } - + if (value != null) { return value.toLowerCase(); } + String language = context.getLocale().getLanguage(); - if (language != null) - language = language.toLowerCase(); + if (language != null) language = language.toLowerCase(); return language; - } - - /* (non-Javadoc) + } + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#isControl() */ public boolean isControl(RuleCriterion criterion) { return true; } - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/MediatypeCriterionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/MediatypeCriterionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/MediatypeCriterionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,35 +22,37 @@ /** * MediatypeCriterionResolver - * + * * @author David Sean Taylor * @version $Id: MediatypeCriterionResolver.java 516448 2007-03-09 16:25:47Z ate $ */ -public class MediatypeCriterionResolver - extends StandardResolver - implements RuleCriterionResolver +public class MediatypeCriterionResolver extends StandardResolver implements + RuleCriterionResolver { - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.rules.RuleCriterion) - */ + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.rules.RuleCriterion) + */ public String resolve(RequestContext context, RuleCriterion criterion) { // look for override String value = super.resolve(context, criterion); - if (value != null) - { - return value; - } - - return context.getMediaType(); - } - - /* (non-Javadoc) + if (value != null) { return value; } + + return context.getMediaType(); + } + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#isControl() */ public boolean isControl(RuleCriterion criterion) { return true; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/NavigationCriterionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/NavigationCriterionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/NavigationCriterionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,16 +19,17 @@ import org.apache.jetspeed.profiler.rules.RuleCriterion; import org.apache.jetspeed.profiler.rules.RuleCriterionResolver; - /** * NavigationCriterionResolver * * @author David Sean Taylor - * @version $Id: NavigationCriterionResolver.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: NavigationCriterionResolver.java 516448 2007-03-09 16:25:47Z + * ate $ */ public class NavigationCriterionResolver extends HardCodedResolver implements RuleCriterionResolver { + public boolean isNavigation(RuleCriterion criterion) { return true; @@ -38,5 +39,5 @@ { return false; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/PathResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/PathResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/PathResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,21 +23,25 @@ /** * PathResolver - * + * * @author David Sean Taylor * @version $Id: PathResolver.java 516448 2007-03-09 16:25:47Z ate $ */ public class PathResolver implements RuleCriterionResolver { - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.rules.RuleCriterion) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.rules.RuleCriterion) */ public String resolve(RequestContext context, RuleCriterion criterion) - { + { String path = null; Page page = context.getPage(); - - if(page != null) + + if (page != null) { path = page.getId(); } @@ -45,7 +49,7 @@ { path = context.getPath(); } - + if ((path == null) || path.equals("/")) { path = criterion.getValue(); @@ -53,17 +57,19 @@ return path; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#isControl() */ public boolean isControl(RuleCriterion criterion) { return false; } - + public boolean isNavigation(RuleCriterion criterion) { return false; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/PathSessionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/PathSessionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/PathSessionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,20 +24,24 @@ /** * PathSessionResolver - * + * * @author David Sean Taylor * @version $Id: PathSessionResolver.java 516448 2007-03-09 16:25:47Z ate $ */ public class PathSessionResolver implements RuleCriterionResolver { - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.rules.RuleCriterion) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.rules.RuleCriterion) */ public String resolve(RequestContext context, RuleCriterion criterion) - { + { String path = null; Page page = context.getPage(); - + if (page != null) { path = page.getId(); @@ -45,64 +49,62 @@ else { path = context.getPath(); - if (path != null) - path = mapPath(context, path); + if (path != null) path = mapPath(context, path); } - + if ((path == null) || path.equals("/")) { String key = this.getClass() + "." + criterion.getName(); - path = (String)context.getSessionAttribute(key); + path = (String) context.getSessionAttribute(key); if (path == null) { path = criterion.getValue(); } } - return path; + return path; } - + private String mapPath(RequestContext context, String originalPath) { String path = originalPath; - if (path.endsWith(".psml")) + if (path.endsWith(".psml")) { return originalPath; } + for (int ix = 0; ix < REGEX_MAP.length; ix++) { - return originalPath; - } - for (int ix=0; ix < REGEX_MAP.length; ix++) - { if (path.matches(REGEX_MAP[ix][0])) { path = REGEX_MAP[ix][1]; context.setPath(path); - context.setAttribute(PortalReservedParameters.PATH_ATTRIBUTE, originalPath); + context.setAttribute(PortalReservedParameters.PATH_ATTRIBUTE, + originalPath); break; - } + } } return path; } - + // TODO: configure this information externally and live static String[][] REGEX_MAP = - { - {".*\\.(...|....)", "/Public/content.psml"} -// {".*\\.html", "/Public/content.psml"}, -// {".*\\.pdf", "/Public/content.psml"}, -// {"/_content.*", "/Public/content.psml"} -// {"/data/*", "/Public/content2.psml"}, + { + {".*\\.(...|....)", "/Public/content.psml"} + // {".*\\.html", "/Public/content.psml"}, + // {".*\\.pdf", "/Public/content.psml"}, + // {"/_content.*", "/Public/content.psml"} + // {"/data/*", "/Public/content2.psml"}, }; - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#isControl() */ public boolean isControl(RuleCriterion criterion) { return false; } - + public boolean isNavigation(RuleCriterion criterion) { return false; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/PrincipalRuleImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/PrincipalRuleImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/PrincipalRuleImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,51 +21,62 @@ /** * PrincipalRuleImpl - * + * * @author David Sean Taylor * @version $Id: PrincipalRuleImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class PrincipalRuleImpl implements PrincipalRule { + private String principalName; + private String ruleId; + private ProfilingRule profilingRule; + private String locatorName; - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.PrincipalRule#getPrincipalName() */ public String getPrincipalName() { return this.principalName; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.PrincipalRule#setPrincipalName(java.lang.String) */ public void setPrincipalName(String name) { this.principalName = name; } - - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.PrincipalRule#getProfilingRule() */ public ProfilingRule getProfilingRule() { - return this.profilingRule; + return this.profilingRule; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.PrincipalRule#setProfilingRule(org.apache.jetspeed.profiler.rules.ProfilingRule) */ public void setProfilingRule(ProfilingRule rule) { - this.profilingRule = rule; + this.profilingRule = rule; this.ruleId = rule.getId(); } - + /** * @return Returns the locatorName. */ @@ -73,8 +84,10 @@ { return locatorName; } + /** - * @param locatorName The locatorName to set. + * @param locatorName + * The locatorName to set. */ public void setLocatorName(String locatorName) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/ProfileResolversImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/ProfileResolversImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/ProfileResolversImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,30 +23,31 @@ import org.apache.jetspeed.profiler.rules.RuleCriterionResolver; /** - * Profile Resolvers - * + * Profile Resolvers + * * @author David Sean Taylor * @version $Id: $ */ public class ProfileResolversImpl implements ProfileResolvers, Serializable { + private Map resolvers; - + public ProfileResolversImpl(Map resolvers) { this.resolvers = resolvers; } - + public RuleCriterionResolver get(String resolverName) { - return (RuleCriterionResolver)resolvers.get(resolverName); + return (RuleCriterionResolver) resolvers.get(resolverName); } - + /** * return the map of resolver */ public Map getResolvers() { - return resolvers; + return resolvers; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RequestSessionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RequestSessionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RequestSessionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,27 +22,32 @@ /** * RequestSessionResolver - * + * * @author David Sean Taylor * @version $Id: RequestSessionResolver.java 516448 2007-03-09 16:25:47Z ate $ */ -public class RequestSessionResolver extends StandardResolver implements RuleCriterionResolver +public class RequestSessionResolver extends StandardResolver implements + RuleCriterionResolver { - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.rules.RuleCriterion) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.rules.RuleCriterion) */ public String resolve(RequestContext context, RuleCriterion criterion) { String value = context.getRequestParameter(criterion.getName()); if (value == null) { - value = (String)context.getSessionAttribute(criterion.getName()); + value = (String) context.getSessionAttribute(criterion.getName()); if (value == null) { value = criterion.getValue(); } } - return value; + return value; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RoleComboCriterionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RoleComboCriterionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RoleComboCriterionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,31 +26,30 @@ import org.apache.jetspeed.security.RolePrincipal; /** - * Role combo resolver - * Combines all roles into one string - * Example: roles = a,b,c + * Role combo resolver Combines all roles into one string Example: roles = a,b,c * RoleCombo = a-b-c - * + * * @author David Sean Taylor * @version $Id: RoleCriterionResolver.java 187756 2004-10-15 22:58:43Z ate $ */ -public class RoleComboCriterionResolver - extends StandardResolver - implements RuleCriterionResolver +public class RoleComboCriterionResolver extends StandardResolver implements + RuleCriterionResolver { - protected final static Log log = LogFactory.getLog(UserCriterionResolver.class); - - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.rules.RuleCriterion) - */ + + protected final static Log log = LogFactory + .getLog(UserCriterionResolver.class); + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.rules.RuleCriterion) + */ public String resolve(RequestContext context, RuleCriterion criterion) { String value = super.resolve(context, criterion); - if (value != null) - { - return value; - } - + if (value != null) { return value; } + Subject subject = context.getSubject(); if (subject == null) { @@ -58,17 +57,19 @@ log.error(msg); return null; } - - return combinePrincipals(context, criterion, subject, RolePrincipal.class); - } - - /* (non-Javadoc) + + return combinePrincipals(context, criterion, subject, + RolePrincipal.class); + } + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#isControl() */ public boolean isControl(RuleCriterion criterion) { return true; } - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RoleCriterionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RoleCriterionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RoleCriterionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,32 +26,32 @@ import org.apache.jetspeed.security.RolePrincipal; /** - * Standard Jetspeed-1 Role resolver (not role-based fallback). - * It first looks at the value in the criterion record. - * If it is null, it then falls back to a request parameter. - * If it is null it gives up and returns null allowing subclasses - * to continue processing. - * + * Standard Jetspeed-1 Role resolver (not role-based fallback). It first looks + * at the value in the criterion record. If it is null, it then falls back to a + * request parameter. If it is null it gives up and returns null allowing + * subclasses to continue processing. + * * @author David Sean Taylor * @version $Id: RoleCriterionResolver.java 516448 2007-03-09 16:25:47Z ate $ */ -public class RoleCriterionResolver - extends StandardResolver - implements RuleCriterionResolver +public class RoleCriterionResolver extends StandardResolver implements + RuleCriterionResolver { - protected final static Log log = LogFactory.getLog(UserCriterionResolver.class); - - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.rules.RuleCriterion) - */ + + protected final static Log log = LogFactory + .getLog(UserCriterionResolver.class); + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.rules.RuleCriterion) + */ public String resolve(RequestContext context, RuleCriterion criterion) { String value = super.resolve(context, criterion); - if (value != null) - { - return value; - } - + if (value != null) { return value; } + Subject subject = context.getSubject(); if (subject == null) { @@ -59,17 +59,19 @@ log.error(msg); return null; } - - return resolvePrincipals(context, criterion, subject, RolePrincipal.class); - } - - /* (non-Javadoc) + + return resolvePrincipals(context, criterion, subject, + RolePrincipal.class); + } + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#isControl() */ public boolean isControl(RuleCriterion criterion) { return true; } - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RoleFallbackProfilingRule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RoleFallbackProfilingRule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RoleFallbackProfilingRule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,46 +31,51 @@ /** * RoleFallbackProfilingRule - * + * * @author David Sean Taylor * @version $Id: RoleFallbackProfilingRule.java 517121 2007-03-12 07:45:49Z ate $ */ -public class RoleFallbackProfilingRule - extends AbstractProfilingRule - implements ProfilingRule +public class RoleFallbackProfilingRule extends AbstractProfilingRule implements + ProfilingRule { - protected final static Log log = LogFactory.getLog(RoleFallbackProfilingRule.class); + + protected final static Log log = LogFactory + .getLog(RoleFallbackProfilingRule.class); + private final static long serialVersionUID = 1L; - + public RoleFallbackProfilingRule() - { + { this.setClassname(this.getClass().getName()); } - - public RoleFallbackProfilingRule(ProfileResolvers resolvers) + + public RoleFallbackProfilingRule(ProfileResolvers resolvers) { super(resolvers); this.setClassname(this.getClass().getName()); } - - - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.ProfilingRule#apply(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.Profiler) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.ProfilingRule#apply(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.Profiler) */ public ProfileLocator apply(RequestContext context, Profiler service) { StringBuffer key = new StringBuffer(); int count = 0; - + // first pass, build the key Iterator criteria = this.getRuleCriteria().iterator(); while (criteria.hasNext()) { - RuleCriterion criterion = (RuleCriterion)criteria.next(); + RuleCriterion criterion = (RuleCriterion) criteria.next(); if (criterion.getType() == null) { - log.warn("Invalid criterion provided - type null on rule " + this); + log.warn("Invalid criterion provided - type null on rule " + + this); } RuleCriterionResolver resolver = getResolver(criterion.getType()); if (resolver == null) @@ -78,10 +83,11 @@ resolver = getDefaultResolver(); } String value = resolver.resolve(context, criterion); - if (value != null && (resolver instanceof RoleCriterionResolver || - resolver instanceof GroupCriterionResolver)) + if (value != null + && (resolver instanceof RoleCriterionResolver || resolver instanceof GroupCriterionResolver)) { - StringTokenizer tokenizer = new StringTokenizer(value, StandardResolver.VALUE_DELIMITER); + StringTokenizer tokenizer = new StringTokenizer(value, + StandardResolver.VALUE_DELIMITER); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); @@ -104,27 +110,27 @@ { key.append(ProfileLocator.PATH_SEPARATOR); } - count++; + count++; } // try to get the profile locator from the cache, // request path and key sufficient to generate unique key String requestPath = context.getPath(); - String locatorKey = ((requestPath != null) ? requestPath : "/") + ProfileLocator.PATH_SEPARATOR + key.toString(); - ProfileLocator locator = getLocatorFromCache(locatorKey); - if (locator != null) - { - return locator; - } - - // second pass, build the locator object + String locatorKey = ((requestPath != null) ? requestPath : "/") + + ProfileLocator.PATH_SEPARATOR + key.toString(); + ProfileLocator locator = getLocatorFromCache(locatorKey); + if (locator != null) { return locator; } + + // second pass, build the locator object locator = service.createLocator(context); criteria = this.getRuleCriteria().iterator(); while (criteria.hasNext()) { - RuleCriterion criterion = (RuleCriterion)criteria.next(); + RuleCriterion criterion = (RuleCriterion) criteria.next(); if (criterion.getType() == null) { - log.warn("Invalid criterion provided - name or type null on rule " + this); + log + .warn("Invalid criterion provided - name or type null on rule " + + this); } RuleCriterionResolver resolver = getResolver(criterion.getType()); if (resolver != null) @@ -132,25 +138,26 @@ String value = resolver.resolve(context, criterion); boolean isControl = resolver.isControl(criterion); boolean isNavigation = resolver.isNavigation(criterion); - if (value != null && (resolver instanceof RoleCriterionResolver || - resolver instanceof GroupCriterionResolver)) + if (value != null + && (resolver instanceof RoleCriterionResolver || resolver instanceof GroupCriterionResolver)) + { + StringTokenizer tokenizer = new StringTokenizer(value, + StandardResolver.VALUE_DELIMITER); + while (tokenizer.hasMoreTokens()) { - StringTokenizer tokenizer = new StringTokenizer(value, StandardResolver.VALUE_DELIMITER); - while (tokenizer.hasMoreTokens()) - { - String token = tokenizer.nextToken(); - locator.add(criterion, isControl, isNavigation, token); - } + String token = tokenizer.nextToken(); + locator.add(criterion, isControl, isNavigation, token); } - else - { - locator.add(criterion, isControl, isNavigation, value); - } - } - } - + } + else + { + locator.add(criterion, isControl, isNavigation, value); + } + } + } + addLocatorToCache(locatorKey, locator); - return locator; - + return locator; + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RuleCriterionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RuleCriterionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/RuleCriterionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,20 +20,27 @@ /** * RuleCriterionImpl - * + * * @author David Sean Taylor * @version $Id: RuleCriterionImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class RuleCriterionImpl implements RuleCriterion { + private String id; + private String ruleId; + private String type; + private String name = null; + private String value; + private int fallbackType = RuleCriterion.FALLBACK_CONTINUE; + private int fallbackOrder; - + public RuleCriterionImpl() { } @@ -47,60 +54,64 @@ this.fallbackOrder = master.getFallbackOrder(); this.fallbackType = master.getFallbackType(); } + /** - * two objects of type RuleCriterion should be considered equal if their name and type are the same + * two objects of type RuleCriterion should be considered equal if their + * name and type are the same * */ - public boolean equals(Object o) + public boolean equals(Object o) { - if (this == o) return true; - if ((o == null) || (!(o instanceof RuleCriterion))) - return false; - RuleCriterion r = (RuleCriterion)o; - if (this.name != null) - { - if (!(this.name.equals(r.getName()))) - return false; - } - else - if (r.getName() != null) - return false; - if (this.type != null) - { - if (!(this.type.equals(r.getType()))) - return false; - } - else - if (r.getType() != null) - return false; - return true; - + if (this == o) return true; + if ((o == null) || (!(o instanceof RuleCriterion))) return false; + RuleCriterion r = (RuleCriterion) o; + if (this.name != null) + { + if (!(this.name.equals(r.getName()))) return false; + } + else if (r.getName() != null) return false; + if (this.type != null) + { + if (!(this.type.equals(r.getType()))) return false; + } + else if (r.getType() != null) return false; + return true; + } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterion#getType() */ public String getType() { return this.type; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterion#setType(java.lang.String) */ public void setType(String type) { this.type = type; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterion#getName() */ public String getName() { return this.name; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterion#setName(java.lang.String) */ public void setName(String name) @@ -108,7 +119,9 @@ this.name = name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterion#getRuleId() */ public String getRuleId() @@ -116,7 +129,9 @@ return ruleId; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterion#setRuleId(java.lang.String) */ public void setRuleId(String ruleId) @@ -124,7 +139,9 @@ this.ruleId = ruleId; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterion#getFallbackOrder() */ public int getFallbackOrder() @@ -132,7 +149,9 @@ return fallbackOrder; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterion#getValue() */ public String getValue() @@ -140,7 +159,9 @@ return value; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterion#setFallbackOrder(int) */ public void setFallbackOrder(int i) @@ -148,7 +169,9 @@ fallbackOrder = i; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterion#setValue(java.lang.String) */ public void setValue(String value) @@ -156,7 +179,9 @@ this.value = value; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterion#getFallbackType() */ public int getFallbackType() @@ -164,7 +189,9 @@ return fallbackType; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterion#setFallbackType(int) */ public void setFallbackType(int i) @@ -172,5 +199,4 @@ fallbackType = i; } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/SessionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/SessionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/SessionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,23 +22,29 @@ /** * SessionResolver - * + * * @author David Sean Taylor * @version $Id: $ */ -public class SessionResolver extends StandardResolver implements RuleCriterionResolver +public class SessionResolver extends StandardResolver implements + RuleCriterionResolver { - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.rules.RuleCriterion) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.rules.RuleCriterion) */ public String resolve(RequestContext context, RuleCriterion criterion) { - String value = (String)context.getSessionAttribute(criterion.getName()); + String value = (String) context + .getSessionAttribute(criterion.getName()); if (value == null) { value = criterion.getValue(); } - return value; + return value; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/StandardProfilingRule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/StandardProfilingRule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/StandardProfilingRule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,46 +29,52 @@ import org.apache.jetspeed.request.RequestContext; /** - * StandardProfilingRule applies the standard Jetspeed-1 profiling rules. - * The result is an ordered list of Profile Locator name/value pairs. + * StandardProfilingRule applies the standard Jetspeed-1 profiling rules. The + * result is an ordered list of Profile Locator name/value pairs. * * @author David Sean Taylor * @version $Id: StandardProfilingRule.java 516448 2007-03-09 16:25:47Z ate $ */ -public class StandardProfilingRule - extends AbstractProfilingRule - implements ProfilingRule +public class StandardProfilingRule extends AbstractProfilingRule implements + ProfilingRule { - protected final static Log log = LogFactory.getLog(StandardProfilingRule.class); - private static final long serialVersionUID = 1; - + + protected final static Log log = LogFactory + .getLog(StandardProfilingRule.class); + + private static final long serialVersionUID = 1; + public StandardProfilingRule() - { + { this.setClassname(this.getClass().getName()); } - - public StandardProfilingRule(ProfileResolvers resolvers) + + public StandardProfilingRule(ProfileResolvers resolvers) { super(resolvers); this.setClassname(this.getClass().getName()); } - - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.ProfilingRule#apply(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.Profiler) - */ + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.ProfilingRule#apply(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.Profiler) + */ public ProfileLocator apply(RequestContext context, Profiler service) { StringBuffer key = new StringBuffer(); int count = 0; - + // first pass, build the key Iterator criteria = this.getRuleCriteria().iterator(); while (criteria.hasNext()) { - RuleCriterion criterion = (RuleCriterion)criteria.next(); + RuleCriterion criterion = (RuleCriterion) criteria.next(); if (criterion.getType() == null) { - log.warn("Invalid criterion provided - type null on rule " + this); + log.warn("Invalid criterion provided - type null on rule " + + this); } RuleCriterionResolver resolver = getResolver(criterion.getType()); if (resolver == null) @@ -83,43 +89,40 @@ { key.append(ProfileLocator.PATH_SEPARATOR); } - count++; + count++; } - + // try to get the profile locator from the cache, // request path and key sufficient to generate unique key String requestPath = context.getPath(); - String locatorKey = ((requestPath != null) ? requestPath : "/") + ProfileLocator.PATH_SEPARATOR + key.toString(); - ProfileLocator locator = getLocatorFromCache(locatorKey); - if (locator != null) - { - return locator; - } - - // second pass, build the locator object + String locatorKey = ((requestPath != null) ? requestPath : "/") + + ProfileLocator.PATH_SEPARATOR + key.toString(); + ProfileLocator locator = getLocatorFromCache(locatorKey); + if (locator != null) { return locator; } + + // second pass, build the locator object locator = service.createLocator(context); criteria = this.getRuleCriteria().iterator(); while (criteria.hasNext()) { - RuleCriterion criterion = (RuleCriterion)criteria.next(); + RuleCriterion criterion = (RuleCriterion) criteria.next(); if (criterion.getType() == null) { - log.warn("Invalid criterion provided - type null on rule " + this); + log.warn("Invalid criterion provided - type null on rule " + + this); } RuleCriterionResolver resolver = getResolver(criterion.getType()); if (resolver != null) { String value = resolver.resolve(context, criterion); boolean isControl = resolver.isControl(criterion); - boolean isNavigation = resolver.isNavigation(criterion); + boolean isNavigation = resolver.isNavigation(criterion); locator.add(criterion, isControl, isNavigation, value); - } - } - + } + } + addLocatorToCache(locatorKey, locator); - return locator; + return locator; } - + } - - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/StandardResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/StandardResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/StandardResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,22 +27,26 @@ import org.apache.jetspeed.security.SecurityHelper; /** - * Standard Jetspeed-1 style resolver for criterion. - * It first looks at the value in the request parameters. - * If it is null, it then falls back to the criterion record.. - * If it is null it gives up and returns null allowing subclasses - * to continue processing. - * + * Standard Jetspeed-1 style resolver for criterion. It first looks at the value + * in the request parameters. If it is null, it then falls back to the criterion + * record.. If it is null it gives up and returns null allowing subclasses to + * continue processing. + * * @author David Sean Taylor * @version $Id: StandardResolver.java 516448 2007-03-09 16:25:47Z ate $ */ public class StandardResolver implements RuleCriterionResolver { + public static final String VALUE_DELIMITER = ","; + public static final String COMBO_DELIMITER = "-"; - - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.rules.RuleCriterion) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.rules.RuleCriterion) */ public String resolve(RequestContext context, RuleCriterion criterion) { @@ -51,19 +55,18 @@ { value = criterion.getValue(); } - return value; + return value; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#isControl() */ public boolean isControl(RuleCriterion criterion) { - if (criterion.getName().equals(RuleCriterionResolver.PATH) || - criterion.getName().equals(RuleCriterionResolver.PAGE)) - { - return false; - } + if (criterion.getName().equals(RuleCriterionResolver.PATH) + || criterion.getName().equals(RuleCriterionResolver.PAGE)) { return false; } return true; } @@ -71,15 +74,17 @@ { return false; } - - protected String resolvePrincipals(RequestContext context, RuleCriterion criterion, Subject subject, Class classe) + + protected String resolvePrincipals(RequestContext context, + RuleCriterion criterion, Subject subject, Class classe) { StringBuffer result = new StringBuffer(); - Iterator principals = SecurityHelper.getPrincipals(subject, classe).iterator(); + Iterator principals = SecurityHelper.getPrincipals(subject, classe) + .iterator(); int count = 0; while (principals.hasNext()) { - Principal principal = (Principal)principals.next(); + Principal principal = (Principal) principals.next(); if (count > 0) { result.append(VALUE_DELIMITER); @@ -87,21 +92,20 @@ result.append(principal.getName()); count++; } - if (count == 0) - { - return null; - } - return result.toString(); + if (count == 0) { return null; } + return result.toString(); } - protected String combinePrincipals(RequestContext context, RuleCriterion criterion, Subject subject, Class classe) + protected String combinePrincipals(RequestContext context, + RuleCriterion criterion, Subject subject, Class classe) { StringBuffer result = new StringBuffer(); - Iterator principals = SecurityHelper.getPrincipals(subject, classe).iterator(); + Iterator principals = SecurityHelper.getPrincipals(subject, classe) + .iterator(); int count = 0; while (principals.hasNext()) { - Principal principal = (Principal)principals.next(); + Principal principal = (Principal) principals.next(); if (count > 0) { result.append(COMBO_DELIMITER); @@ -109,11 +113,8 @@ result.append(principal.getName()); count++; } - if (count == 0) - { - return null; - } - return result.toString(); + if (count == 0) { return null; } + return result.toString(); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/UserAgentCriterionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/UserAgentCriterionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/UserAgentCriterionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,28 +20,24 @@ import org.apache.jetspeed.profiler.rules.RuleCriterionResolver; import org.apache.jetspeed.request.RequestContext; - /** * UserAgentCriterionResolver * * @author David Sean Taylor * @version $Id: UserAgentCriterionResolver.java 516448 2007-03-09 16:25:47Z ate $ */ -public class UserAgentCriterionResolver - extends StandardResolver - implements RuleCriterionResolver +public class UserAgentCriterionResolver extends StandardResolver implements + RuleCriterionResolver { + public String resolve(RequestContext context, RuleCriterion criterion) { // look for override String value = super.resolve(context, criterion); - if (value != null) - { - return value; - } + if (value != null) { return value; } return context.getCapabilityMap().getClient().getName(); - } - + } + public boolean isControl(RuleCriterion criterion) { return true; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/UserAttributeResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/UserAttributeResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/UserAttributeResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,37 +25,38 @@ import org.apache.jetspeed.request.RequestContext; /** - * Looks in the Portlet API User Attributes for given named attribute + * Looks in the Portlet API User Attributes for given named attribute * * @author David Sean Taylor * @version $Id: UserAttributeResolver.java 516448 2007-03-09 16:25:47Z ate $ */ -public class UserAttributeResolver - extends - StandardResolver - implements +public class UserAttributeResolver extends StandardResolver implements RuleCriterionResolver { - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.rules.RuleCriterion) - */ + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.rules.RuleCriterion) + */ public String resolve(RequestContext context, RuleCriterion criterion) { - Object object = context.getRequest().getAttribute(PortletRequest.USER_INFO); + Object object = context.getRequest().getAttribute( + PortletRequest.USER_INFO); if (object != null && object instanceof Map) { - Map map = (Map)object; - String attribute = (String)map.get(criterion.getName()); - if (attribute != null) - { - return attribute; - } + Map map = (Map) object; + String attribute = (String) map.get(criterion.getName()); + if (attribute != null) { return attribute; } return criterion.getValue(); } return null; - } - - /* (non-Javadoc) + } + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#isControl() */ public boolean isControl(RuleCriterion criterion) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/UserCriterionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/UserCriterionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/java/org/apache/jetspeed/profiler/rules/impl/UserCriterionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,32 +29,32 @@ import org.apache.jetspeed.security.UserPrincipal; /** - * Standard Jetspeed-1 User resolver. - * It first looks at the value in the criterion record. - * If it is null, it then falls back to a request parameter. - * If it is null it gives up and returns null allowing subclasses - * to continue processing. + * Standard Jetspeed-1 User resolver. It first looks at the value in the + * criterion record. If it is null, it then falls back to a request parameter. + * If it is null it gives up and returns null allowing subclasses to continue + * processing. * * @author David Sean Taylor * @version $Id: UserCriterionResolver.java 516448 2007-03-09 16:25:47Z ate $ */ -public class UserCriterionResolver - extends StandardResolver - implements RuleCriterionResolver +public class UserCriterionResolver extends StandardResolver implements + RuleCriterionResolver { - protected final static Log log = LogFactory.getLog(UserCriterionResolver.class); - - /* (non-Javadoc) - * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, org.apache.jetspeed.profiler.rules.RuleCriterion) - */ + + protected final static Log log = LogFactory + .getLog(UserCriterionResolver.class); + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#resolve(org.apache.jetspeed.request.RequestContext, + * org.apache.jetspeed.profiler.rules.RuleCriterion) + */ public String resolve(RequestContext context, RuleCriterion criterion) { String value = super.resolve(context, criterion); - if (value != null) - { - return value; - } - + if (value != null) { return value; } + Subject subject = context.getSubject(); if (subject == null) { @@ -62,22 +62,21 @@ log.error(msg); return null; } - - Principal principal = SecurityHelper.getPrincipal(subject, UserPrincipal.class); - if (principal != null) - { - return principal.getName(); - } + + Principal principal = SecurityHelper.getPrincipal(subject, + UserPrincipal.class); + if (principal != null) { return principal.getName(); } return null; - } - - /* (non-Javadoc) + } + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.profiler.rules.RuleCriterionResolver#isControl() */ public boolean isControl(RuleCriterion criterion) { return true; } - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/test/org/apache/jetspeed/profiler/TestProfiler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/test/org/apache/jetspeed/profiler/TestProfiler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/profiler/src/test/org/apache/jetspeed/profiler/TestProfiler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -51,18 +51,24 @@ */ public class TestProfiler extends DatasourceEnabledSpringTestCase { + private Profiler profiler = null; + private ProfileResolvers resolvers = null; - + protected static final Properties TEST_PROPS = new Properties(); static { TEST_PROPS.put("defaultRule", "j1"); TEST_PROPS.put("anonymousUser", "anon"); - TEST_PROPS.put("locator.impl", "org.apache.jetspeed.profiler.impl.JetspeedProfileLocator"); - TEST_PROPS.put("principalRule.impl", "org.apache.jetspeed.profiler.rules.impl.PrincipalRuleImpl"); - TEST_PROPS.put("profilingRule.impl", "org.apache.jetspeed.profiler.rules.impl.AbstractProfilingRule"); + TEST_PROPS.put("locator.impl", + "org.apache.jetspeed.profiler.impl.JetspeedProfileLocator"); + TEST_PROPS.put("principalRule.impl", + "org.apache.jetspeed.profiler.rules.impl.PrincipalRuleImpl"); + TEST_PROPS + .put("profilingRule.impl", + "org.apache.jetspeed.profiler.rules.impl.AbstractProfilingRule"); } /* @@ -84,17 +90,18 @@ public static void main(String args[]) { junit.awtui.TestRunner.main(new String[] - { TestProfiler.class.getName() }); + {TestProfiler.class.getName()}); } - protected void setUp() throws Exception { super.setUp(); this.profiler = (Profiler) ctx.getBean("profiler"); - JetspeedProfilerImpl profilerImpl = (JetspeedProfilerImpl) ctx.getBean("profilerImpl"); + JetspeedProfilerImpl profilerImpl = (JetspeedProfilerImpl) ctx + .getBean("profilerImpl"); assertNotNull("profiler not found ", profiler); - ProfileResolvers resolvers = (ProfileResolvers) ctx.getBean("ProfileResolvers"); + ProfileResolvers resolvers = (ProfileResolvers) ctx + .getBean("ProfileResolvers"); assertNotNull("resolvers not found ", resolvers); profilerImpl.setDefaultRule(JetspeedProfilerImpl.DEFAULT_RULE); } @@ -115,30 +122,17 @@ private static final String DEFAULT_PAGE = "default-page"; - private static final String URF_CRITERIA [] = - { - "user", - "navigation", - "role", - "path.session" - }; + private static final String URF_CRITERIA[] = + {"user", "navigation", "role", "path.session"}; - private static final String URCF_CRITERIA [] = - { - "user", - "navigation", - "rolecombo", - "path.session" - }; + private static final String URCF_CRITERIA[] = + {"user", "navigation", "rolecombo", "path.session"}; - - - public void testUserRoleFallback() - throws Exception + public void testUserRoleFallback() throws Exception { assertNotNull("profiler service is null", profiler); System.out.println("START: running test user role fallback..."); - + // make sure rule is set correctly ProfilingRule rule = profiler.getRule("user-role-fallback"); assertNotNull("rule is null ", rule); @@ -146,30 +140,35 @@ int ix = 0; while (c.hasNext()) { - RuleCriterion rc = (RuleCriterion)c.next(); - assertTrue("criterion type check " + rc.getType(), rc.getType().equals(URF_CRITERIA[ix])); + RuleCriterion rc = (RuleCriterion) c.next(); + assertTrue("criterion type check " + rc.getType(), rc.getType() + .equals(URF_CRITERIA[ix])); System.out.println(rc.getType()); ix++; } - + // test applying it RequestContext context = new MockRequestContext(); Subject subject = createSubject(); - context.setPath("/homepage.psml"); + context.setPath("/homepage.psml"); context.setSubject(subject); ProfileLocator locator = rule.apply(context, profiler); System.out.println("locator = " + locator); - assertTrue("locator string " + locator.toString(), locator.toString().equals("/homepage.psml:user:david:navigation:/:role:ATP:role:NB:role:ATP-NB:page:/homepage.psml")); - + assertTrue( + "locator string " + locator.toString(), + locator + .toString() + .equals( + "/homepage.psml:user:david:navigation:/:role:ATP:role:NB:role:ATP-NB:page:/homepage.psml")); + System.out.println("COMPLETED: running test user role fallback."); } - public void testUserRoleComboFallback() - throws Exception + public void testUserRoleComboFallback() throws Exception { assertNotNull("profiler service is null", profiler); System.out.println("START: running test user rolecombo fallback..."); - + // make sure rule is set correctly ProfilingRule rule = profiler.getRule("user-rolecombo-fallback"); assertNotNull("rule is null ", rule); @@ -177,35 +176,42 @@ int ix = 0; while (c.hasNext()) { - RuleCriterion rc = (RuleCriterion)c.next(); - assertTrue("criterion type check " + rc.getType(), rc.getType().equals(URCF_CRITERIA[ix])); + RuleCriterion rc = (RuleCriterion) c.next(); + assertTrue("criterion type check " + rc.getType(), rc.getType() + .equals(URCF_CRITERIA[ix])); System.out.println(rc.getType()); ix++; } - + // test applying it RequestContext context = new MockRequestContext(); Subject subject = createSubject2(); - context.setPath("/homepage.psml"); + context.setPath("/homepage.psml"); context.setSubject(subject); ProfileLocator locator = rule.apply(context, profiler); System.out.println("locator = " + locator); - assertTrue("locator string " + locator.toString(), locator.toString().equals("/homepage.psml:user:david:navigation:/:role:ATP-NB:page:/homepage.psml")); - + assertTrue( + "locator string " + locator.toString(), + locator + .toString() + .equals( + "/homepage.psml:user:david:navigation:/:role:ATP-NB:page:/homepage.psml")); + System.out.println("COMPLETED: running test user role fallback."); } - + protected Subject createSubject() { Set principals = new PrincipalsSet(); Set publicCredentials = new HashSet(); Set privateCredentials = new HashSet(); - + principals.add(new UserPrincipalImpl("david")); principals.add(new RolePrincipalImpl("ATP")); - principals.add(new RolePrincipalImpl("NB")); - principals.add(new RolePrincipalImpl("ATP-NB")); - Subject subject = new Subject(true, principals, publicCredentials, privateCredentials); + principals.add(new RolePrincipalImpl("NB")); + principals.add(new RolePrincipalImpl("ATP-NB")); + Subject subject = new Subject(true, principals, publicCredentials, + privateCredentials); return subject; } @@ -214,14 +220,15 @@ Set principals = new PrincipalsSet(); Set publicCredentials = new HashSet(); Set privateCredentials = new HashSet(); - + principals.add(new UserPrincipalImpl("david")); principals.add(new RolePrincipalImpl("ATP")); - principals.add(new RolePrincipalImpl("NB")); - Subject subject = new Subject(true, principals, publicCredentials, privateCredentials); + principals.add(new RolePrincipalImpl("NB")); + Subject subject = new Subject(true, principals, publicCredentials, + privateCredentials); return subject; } - + /** * Tests * @@ -234,14 +241,17 @@ // Test Default Rule ProfilingRule rule = profiler.getDefaultRule(); assertNotNull("Default profiling rule is null", rule); - assertTrue("default rule unexpected, = " + rule.getId(), rule.getId().equals(DEFAULT_RULE)); - assertTrue("default rule class not mapped", rule instanceof StandardProfilingRule); + assertTrue("default rule unexpected, = " + rule.getId(), rule.getId() + .equals(DEFAULT_RULE)); + assertTrue("default rule class not mapped", + rule instanceof StandardProfilingRule); // Test anonymous principal-rule - ProfilingRule anonRule = profiler.getRuleForPrincipal(new UserPrincipalImpl("anon"), - ProfileLocator.PAGE_LOCATOR); + ProfilingRule anonRule = profiler.getRuleForPrincipal( + new UserPrincipalImpl("anon"), ProfileLocator.PAGE_LOCATOR); assertNotNull("anonymous rule is null", anonRule); - assertTrue("anonymous rule is j1", anonRule.getId().equals(DEFAULT_RULE)); + assertTrue("anonymous rule is j1", anonRule.getId() + .equals(DEFAULT_RULE)); // Test Retrieving All Rules int standardCount = 0; @@ -252,13 +262,15 @@ rule = (ProfilingRule) rules.next(); if (rule.getId().equals(DEFAULT_RULE)) { - assertTrue("standard rule class not mapped", rule instanceof StandardProfilingRule); + assertTrue("standard rule class not mapped", + rule instanceof StandardProfilingRule); checkStandardCriteria(rule); standardCount++; } else if (rule.getId().equals(FALLBACK_RULE)) { - assertTrue("role fallback rule class not mapped", rule instanceof RoleFallbackProfilingRule); + assertTrue("role fallback rule class not mapped", + rule instanceof RoleFallbackProfilingRule); checkFallbackCriteria(rule); fallbackCount++; } @@ -269,8 +281,10 @@ } } - assertTrue("didnt find expected number of standard rules, expected = " + EXPECTED_STANDARD, standardCount == 1); - assertTrue("didnt find expected number of fallback rules, expected = " + EXPECTED_FALLBACK, fallbackCount == 1); + assertTrue("didnt find expected number of standard rules, expected = " + + EXPECTED_STANDARD, standardCount == 1); + assertTrue("didnt find expected number of fallback rules, expected = " + + EXPECTED_FALLBACK, fallbackCount == 1); } @@ -288,39 +302,52 @@ switch (count) { case 0: - assertTrue("criteria name " + criterion.getName(), criterion.getName().equals( - ProfilingRule.STANDARD_PAGE)); + assertTrue("criteria name " + criterion.getName(), criterion + .getName().equals(ProfilingRule.STANDARD_PAGE)); assertNotNull("criteria value", criterion.getValue()); - assertTrue("criteria value", criterion.getValue().equals(DEFAULT_PAGE)); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_STOP); + assertTrue("criteria value", criterion.getValue().equals( + DEFAULT_PAGE)); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_STOP); break; case 1: - assertTrue("criteria name", criterion.getName().equals(ProfilingRule.STANDARD_USER)); + assertTrue("criteria name", criterion.getName().equals( + ProfilingRule.STANDARD_USER)); assertNull("criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_STOP); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_STOP); break; case 2: - assertTrue("criteria name", criterion.getName().equals(ProfilingRule.STANDARD_MEDIATYPE)); + assertTrue("criteria name", criterion.getName().equals( + ProfilingRule.STANDARD_MEDIATYPE)); assertNull("criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); break; case 3: - assertTrue("criteria name", criterion.getName().equals(ProfilingRule.STANDARD_LANGUAGE)); + assertTrue("criteria name", criterion.getName().equals( + ProfilingRule.STANDARD_LANGUAGE)); assertNull("criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); break; case 4: - assertTrue("criteria name", criterion.getName().equals(ProfilingRule.STANDARD_COUNTRY)); + assertTrue("criteria name", criterion.getName().equals( + ProfilingRule.STANDARD_COUNTRY)); assertNull("criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); break; } count++; } } - - private void checkFallbackCriteria(ProfilingRule rule) { Collection criteriaCollection = rule.getRuleCriteria(); @@ -335,30 +362,46 @@ switch (count) { case 0: - assertTrue("fallback criteria name", criterion.getName().equals(ProfilingRule.STANDARD_ROLE)); + assertTrue("fallback criteria name", criterion.getName() + .equals(ProfilingRule.STANDARD_ROLE)); assertNull("fallback criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_LOOP); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_LOOP); break; case 1: - assertTrue("fallback criteria name", criterion.getName().equals(ProfilingRule.STANDARD_PAGE)); + assertTrue("fallback criteria name", criterion.getName() + .equals(ProfilingRule.STANDARD_PAGE)); assertNotNull("fallback criteria value", criterion.getValue()); - assertTrue("fallback criteria value", criterion.getValue().equals(DEFAULT_PAGE)); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_STOP); + assertTrue("fallback criteria value", criterion.getValue() + .equals(DEFAULT_PAGE)); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_STOP); break; case 2: - assertTrue("fallback criteria name", criterion.getName().equals(ProfilingRule.STANDARD_MEDIATYPE)); + assertTrue("fallback criteria name", criterion.getName() + .equals(ProfilingRule.STANDARD_MEDIATYPE)); assertNull("fallback criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); break; case 3: - assertTrue("fallback criteria name", criterion.getName().equals(ProfilingRule.STANDARD_LANGUAGE)); + assertTrue("fallback criteria name", criterion.getName() + .equals(ProfilingRule.STANDARD_LANGUAGE)); assertNull("fallback criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); break; case 4: - assertTrue("fallback criteria name", criterion.getName().equals(ProfilingRule.STANDARD_COUNTRY)); + assertTrue("fallback criteria name", criterion.getName() + .equals(ProfilingRule.STANDARD_COUNTRY)); assertNull("fallback criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); break; } count++; @@ -379,37 +422,47 @@ params.put("page", "default-other"); params.put("path", "/sports/football/nfl/chiefs"); - ProfileLocator locator = profiler.getProfile(request, ProfileLocator.PAGE_LOCATOR); + ProfileLocator locator = profiler.getProfile(request, + ProfileLocator.PAGE_LOCATOR); assertNotNull("rule test on getProfile returned null", locator); String path = locator.getLocatorPath(); System.out.println("locator = " + path); - assertTrue("locator key value unexpected: " + path, path - .equals("page:default-other:user:anon:mediatype:HTML:language:en:country:US")); + assertTrue( + "locator key value unexpected: " + path, + path + .equals("page:default-other:user:anon:mediatype:HTML:language:en:country:US")); // test fallback Iterator fallback = locator.iterator(); int count = 0; while (fallback.hasNext()) { - ProfileLocatorProperty[] locatorProperties = (ProfileLocatorProperty[]) fallback.next(); - assertTrue("locatorProperties is not null", (locatorProperties != null)); + ProfileLocatorProperty[] locatorProperties = (ProfileLocatorProperty[]) fallback + .next(); + assertTrue("locatorProperties is not null", + (locatorProperties != null)); String locatorPath = locator.getLocatorPath(locatorProperties); switch (count) { case 0: - assertTrue("locatorPath[0]: " + locatorPath, locatorPath - .equals("page:default-other:user:anon:mediatype:HTML:language:en:country:US")); + assertTrue( + "locatorPath[0]: " + locatorPath, + locatorPath + .equals("page:default-other:user:anon:mediatype:HTML:language:en:country:US")); break; case 1: - assertTrue("locatorPath[1]: " + locatorPath, locatorPath - .equals("page:default-other:user:anon:mediatype:HTML:language:en")); + assertTrue( + "locatorPath[1]: " + locatorPath, + locatorPath + .equals("page:default-other:user:anon:mediatype:HTML:language:en")); break; case 2: assertTrue("locatorPath[2]: " + locatorPath, locatorPath .equals("page:default-other:user:anon:mediatype:HTML")); break; case 3: - assertTrue("locatorPath[3]: " + locatorPath, locatorPath.equals("page:default-other:user:anon")); + assertTrue("locatorPath[3]: " + locatorPath, locatorPath + .equals("page:default-other:user:anon")); break; } @@ -426,10 +479,13 @@ count = 0; while (fallback.hasNext()) { - ProfileLocatorProperty[] locatorProperties = (ProfileLocatorProperty[]) fallback.next(); - assertTrue("locatorProperties is not null", (locatorProperties != null)); + ProfileLocatorProperty[] locatorProperties = (ProfileLocatorProperty[]) fallback + .next(); + assertTrue("locatorProperties is not null", + (locatorProperties != null)); String locatorPath = locator.getLocatorPath(locatorProperties); - assertTrue("locatorPath: " + locatorPath, locatorPath.equals("page:test")); + assertTrue("locatorPath: " + locatorPath, locatorPath + .equals("page:test")); System.out.println("Simple Test: path = " + locatorPath); count++; @@ -461,7 +517,8 @@ request.setMediaType("HTML"); request.setMimeType("text/html"); - ProfileLocator locator = profiler.getProfile(request, ProfileLocator.PAGE_LOCATOR); + ProfileLocator locator = profiler.getProfile(request, + ProfileLocator.PAGE_LOCATOR); assertNotNull("rule test on getProfile returned null", locator); System.out.println("page = " + locator.getValue("page")); } @@ -476,17 +533,20 @@ assertNotNull("rule test on getProfile returned null", locator); String path = locator.getLocatorPath(); System.out.println("locator = " + path); - assertTrue("locator path: " + path, path.equals("path:/football/nfl/chiefs")); + assertTrue("locator path: " + path, path + .equals("path:/football/nfl/chiefs")); } public void testGetLocatorNames() throws Exception { assertNotNull("profiler service is null", profiler); - String[] result = profiler.getLocatorNamesForPrincipal(new UserPrincipalImpl("guest")); + String[] result = profiler + .getLocatorNamesForPrincipal(new UserPrincipalImpl("guest")); for (int ix = 0; ix < result.length; ix++) { System.out.println("$$$ result = " + result[ix]); - assertTrue("locator name = " + result[ix], result[ix].equals("page")); + assertTrue("locator name = " + result[ix], result[ix] + .equals("page")); } } @@ -495,7 +555,8 @@ System.out.println("Maintenance tests commencing...."); assertNotNull("profiler service is null", profiler); ProfilingRule rule = new StandardProfilingRule(resolvers); - rule.setClassname("org.apache.jetspeed.profiler.rules.impl.StandardProfilingRule"); + rule + .setClassname("org.apache.jetspeed.profiler.rules.impl.StandardProfilingRule"); rule.setId("testmo"); rule.setTitle("The Grand Title"); profiler.storeProfilingRule(rule); @@ -508,7 +569,8 @@ ProfilingRule rule3 = profiler.getRule("testmo"); assertNotNull("rule couldnt be retrieved", rule3); - assertTrue("rule title is bad", rule3.getTitle().equals(rule2.getTitle())); + assertTrue("rule title is bad", rule3.getTitle().equals( + rule2.getTitle())); profiler.deleteProfilingRule(rule); ProfilingRule rule4 = profiler.getRule("testmo"); @@ -519,18 +581,16 @@ protected String[] getConfigurations() { - return new String[]{"profiler.xml", "transaction.xml"}; + return new String[] + {"profiler.xml", "transaction.xml"}; } - - - protected RuleCriterion addRuleCriterion(ProfilingRule rule, - String criterionName, String criterionType, String criterionValue,int fallbackOrder, int fallbackType) - throws Exception + protected RuleCriterion addRuleCriterion(ProfilingRule rule, + String criterionName, String criterionType, String criterionValue, + int fallbackOrder, int fallbackType) throws Exception { assertTrue("ProfilingRule is not null", (rule != null)); - RuleCriterion c = profiler.createRuleCriterion(); assertTrue("RuleCriterion is not null", (c != null)); c.setFallbackOrder(fallbackOrder); @@ -542,9 +602,7 @@ rule.getRuleCriteria().add(c); return c; } - - - + private void createStandardCriteria(ProfilingRule rule) throws Exception { RuleCriterion criterion; @@ -555,46 +613,68 @@ switch (count) { case 0: - - criterion = this.addRuleCriterion(rule,ProfilingRule.STANDARD_PAGE, "type-" + count, DEFAULT_PAGE, count, RuleCriterion.FALLBACK_STOP); - assertTrue("criteria name " + criterion.getName(), criterion.getName().equals( - ProfilingRule.STANDARD_PAGE)); + + criterion = this.addRuleCriterion(rule, + ProfilingRule.STANDARD_PAGE, "type-" + count, + DEFAULT_PAGE, count, RuleCriterion.FALLBACK_STOP); + assertTrue("criteria name " + criterion.getName(), criterion + .getName().equals(ProfilingRule.STANDARD_PAGE)); assertNotNull("criteria value", criterion.getValue()); - assertTrue("criteria value", criterion.getValue().equals(DEFAULT_PAGE)); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_STOP); + assertTrue("criteria value", criterion.getValue().equals( + DEFAULT_PAGE)); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_STOP); break; case 1: - criterion = this.addRuleCriterion(rule,ProfilingRule.STANDARD_USER, "type-" + count, null, count, RuleCriterion.FALLBACK_STOP); - assertTrue("criteria name", criterion.getName().equals(ProfilingRule.STANDARD_USER)); + criterion = this.addRuleCriterion(rule, + ProfilingRule.STANDARD_USER, "type-" + count, null, + count, RuleCriterion.FALLBACK_STOP); + assertTrue("criteria name", criterion.getName().equals( + ProfilingRule.STANDARD_USER)); assertNull("criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_STOP); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_STOP); break; case 2: - criterion = this.addRuleCriterion(rule,ProfilingRule.STANDARD_MEDIATYPE, "type-" + count, null, count, RuleCriterion.FALLBACK_CONTINUE); - assertTrue("criteria name", criterion.getName().equals(ProfilingRule.STANDARD_MEDIATYPE)); + criterion = this.addRuleCriterion(rule, + ProfilingRule.STANDARD_MEDIATYPE, "type-" + count, + null, count, RuleCriterion.FALLBACK_CONTINUE); + assertTrue("criteria name", criterion.getName().equals( + ProfilingRule.STANDARD_MEDIATYPE)); assertNull("criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); break; case 3: - criterion = this.addRuleCriterion(rule,ProfilingRule.STANDARD_LANGUAGE, "type-" + count, null, count, RuleCriterion.FALLBACK_CONTINUE); - assertTrue("criteria name", criterion.getName().equals(ProfilingRule.STANDARD_LANGUAGE)); + criterion = this.addRuleCriterion(rule, + ProfilingRule.STANDARD_LANGUAGE, "type-" + count, null, + count, RuleCriterion.FALLBACK_CONTINUE); + assertTrue("criteria name", criterion.getName().equals( + ProfilingRule.STANDARD_LANGUAGE)); assertNull("criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); break; case 4: - criterion = this.addRuleCriterion(rule,ProfilingRule.STANDARD_COUNTRY, "type-" + count, null, count, RuleCriterion.FALLBACK_CONTINUE); - assertTrue("criteria name", criterion.getName().equals(ProfilingRule.STANDARD_COUNTRY)); + criterion = this.addRuleCriterion(rule, + ProfilingRule.STANDARD_COUNTRY, "type-" + count, null, + count, RuleCriterion.FALLBACK_CONTINUE); + assertTrue("criteria name", criterion.getName().equals( + ProfilingRule.STANDARD_COUNTRY)); assertNull("criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); break; } } } - - - private void createFallbackCriteria(ProfilingRule rule) throws Exception { RuleCriterion criterion; @@ -606,40 +686,66 @@ switch (count) { case 0: - criterion = this.addRuleCriterion(rule,ProfilingRule.STANDARD_ROLE, "type-" + count, null, count, RuleCriterion.FALLBACK_LOOP); - assertTrue("fallback criteria name", criterion.getName().equals(ProfilingRule.STANDARD_ROLE)); + criterion = this.addRuleCriterion(rule, + ProfilingRule.STANDARD_ROLE, "type-" + count, null, + count, RuleCriterion.FALLBACK_LOOP); + assertTrue("fallback criteria name", criterion.getName() + .equals(ProfilingRule.STANDARD_ROLE)); assertNull("fallback criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_LOOP); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_LOOP); break; case 1: - criterion = this.addRuleCriterion(rule,ProfilingRule.STANDARD_PAGE, "type-" + count, DEFAULT_PAGE, count, RuleCriterion.FALLBACK_STOP); - assertTrue("fallback criteria name", criterion.getName().equals(ProfilingRule.STANDARD_PAGE)); + criterion = this.addRuleCriterion(rule, + ProfilingRule.STANDARD_PAGE, "type-" + count, + DEFAULT_PAGE, count, RuleCriterion.FALLBACK_STOP); + assertTrue("fallback criteria name", criterion.getName() + .equals(ProfilingRule.STANDARD_PAGE)); assertNotNull("fallback criteria value", criterion.getValue()); - assertTrue("fallback criteria value", criterion.getValue().equals(DEFAULT_PAGE)); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_STOP); + assertTrue("fallback criteria value", criterion.getValue() + .equals(DEFAULT_PAGE)); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_STOP); break; case 2: - criterion = this.addRuleCriterion(rule,ProfilingRule.STANDARD_MEDIATYPE, "type-" + count, null, count, RuleCriterion.FALLBACK_CONTINUE); - assertTrue("fallback criteria name", criterion.getName().equals(ProfilingRule.STANDARD_MEDIATYPE)); + criterion = this.addRuleCriterion(rule, + ProfilingRule.STANDARD_MEDIATYPE, "type-" + count, + null, count, RuleCriterion.FALLBACK_CONTINUE); + assertTrue("fallback criteria name", criterion.getName() + .equals(ProfilingRule.STANDARD_MEDIATYPE)); assertNull("fallback criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); break; case 3: - criterion = this.addRuleCriterion(rule,ProfilingRule.STANDARD_LANGUAGE, "type-" + count, null, count, RuleCriterion.FALLBACK_CONTINUE); - assertTrue("fallback criteria name", criterion.getName().equals(ProfilingRule.STANDARD_LANGUAGE)); + criterion = this.addRuleCriterion(rule, + ProfilingRule.STANDARD_LANGUAGE, "type-" + count, null, + count, RuleCriterion.FALLBACK_CONTINUE); + assertTrue("fallback criteria name", criterion.getName() + .equals(ProfilingRule.STANDARD_LANGUAGE)); assertNull("fallback criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); break; case 4: - criterion = this.addRuleCriterion(rule,ProfilingRule.STANDARD_COUNTRY, "type-" + count, null, count, RuleCriterion.FALLBACK_CONTINUE); - assertTrue("fallback criteria name", criterion.getName().equals(ProfilingRule.STANDARD_COUNTRY)); + criterion = this.addRuleCriterion(rule, + ProfilingRule.STANDARD_COUNTRY, "type-" + count, null, + count, RuleCriterion.FALLBACK_CONTINUE); + assertTrue("fallback criteria name", criterion.getName() + .equals(ProfilingRule.STANDARD_COUNTRY)); assertNull("fallback criteria value", criterion.getValue()); - assertTrue("fallback type", criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); + assertTrue( + "fallback type", + criterion.getFallbackType() == RuleCriterion.FALLBACK_CONTINUE); break; } } } - + /** * Tests * @@ -650,30 +756,29 @@ assertNotNull("profiler service is null", profiler); String ruleId1 = "j1-test"; String ruleId2 = "j2-test"; - - + // create org.apache.jetspeed.profiler.rules.impl.StandardProfilingRule ProfilingRule rule = profiler.createProfilingRule(true); assertNotNull("rule is null ", rule); rule.setId(ruleId1); rule.setTitle("Test Rule 1"); this.createStandardCriteria(rule); - + profiler.storeProfilingRule(rule); - //Check + // Check ProfilingRule rule2 = profiler.getRule(ruleId1); assertNotNull("default rule couldnt be added", rule2); assertTrue("default rule id bad", rule.getId().equals(rule2.getId())); - + rule = profiler.createProfilingRule(false); assertNotNull("rule is null ", rule); rule.setId(ruleId2); rule.setTitle("Test Rule 2"); - + this.createFallbackCriteria(rule); profiler.storeProfilingRule(rule); - //Check + // Check rule2 = profiler.getRule(ruleId2); assertNotNull("fallback rule couldnt be added", rule2); assertTrue("fallback rule id bad", rule.getId().equals(rule2.getId())); @@ -687,13 +792,15 @@ rule = (ProfilingRule) rules.next(); if (rule.getId().equals(ruleId1)) { - assertTrue("standard rule class not mapped", rule instanceof StandardProfilingRule); + assertTrue("standard rule class not mapped", + rule instanceof StandardProfilingRule); checkStandardCriteria(rule); standardCount++; } else if (rule.getId().equals(ruleId2)) { - assertTrue("role fallback rule class not mapped", rule instanceof RoleFallbackProfilingRule); + assertTrue("role fallback rule class not mapped", + rule instanceof RoleFallbackProfilingRule); checkFallbackCriteria(rule); fallbackCount++; } @@ -704,8 +811,10 @@ } } - assertTrue("didnt find expected number of standard rules, expected = " + EXPECTED_STANDARD, standardCount == 1); - assertTrue("didnt find expected number of fallback rules, expected = " + EXPECTED_FALLBACK, fallbackCount == 1); + assertTrue("didnt find expected number of standard rules, expected = " + + EXPECTED_STANDARD, standardCount == 1); + assertTrue("didnt find expected number of fallback rules, expected = " + + EXPECTED_FALLBACK, fallbackCount == 1); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/dao/InitablePersistenceBrokerDaoSupport.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/dao/InitablePersistenceBrokerDaoSupport.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/dao/InitablePersistenceBrokerDaoSupport.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,16 +28,20 @@ * InitablePersistenceBrokerDaoSupport *

      *

      - * + * *

      + * * @author Scott T. Weaver - * @version $Id: InitablePersistenceBrokerDaoSupport.java 224631 2005-07-24 17:03:46Z taylor $ - * + * @version $Id: InitablePersistenceBrokerDaoSupport.java 224631 2005-07-24 + * 17:03:46Z taylor $ + * */ -public class InitablePersistenceBrokerDaoSupport extends PersistenceBrokerDaoSupport +public class InitablePersistenceBrokerDaoSupport extends + PersistenceBrokerDaoSupport { protected String repositoryPath; + /** * */ @@ -45,17 +49,17 @@ { super(); this.repositoryPath = repositoryPath; - + } - - + /** * *

      * init *

      - * Loads the correct repository descriptor for InitablePersistenceBrokerDaoSupport - * + * Loads the correct repository descriptor for + * InitablePersistenceBrokerDaoSupport + * * @see org.springframework.orm.ojb.support.PersistenceBrokerDaoSupport * @throws Exception */ @@ -63,10 +67,13 @@ { MetadataManager metaManager = MetadataManager.getInstance(); RepositoryPersistor persistor = new RepositoryPersistor(); - URL descriptorUrl = getClass().getClassLoader().getResource(repositoryPath); + URL descriptorUrl = getClass().getClassLoader().getResource( + repositoryPath); - logger.info("Merging OJB respository "+descriptorUrl+" for DAO class "+getClass().getName()); - DescriptorRepository repo = persistor.readDescriptorRepository(descriptorUrl.openStream()); + logger.info("Merging OJB respository " + descriptorUrl + + " for DAO class " + getClass().getName()); + DescriptorRepository repo = persistor + .readDescriptorRepository(descriptorUrl.openStream()); metaManager.mergeDescriptorRepository(repo); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/BoundDBCPDatasourceComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/BoundDBCPDatasourceComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/BoundDBCPDatasourceComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,16 +20,18 @@ import org.apache.jetspeed.components.jndi.JNDIComponent; - /** * Bound DBCP Data Source - * + * * @author Scott Weaver - * @version $Id: BoundDBCPDatasourceComponent.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: BoundDBCPDatasourceComponent.java 516448 2007-03-09 16:25:47Z + * ate $ */ public class BoundDBCPDatasourceComponent extends DBCPDatasourceComponent { + private JNDIComponent jndi; + private String bindName; /** @@ -42,64 +44,68 @@ * @param maxWait * @param whenExhausted * @param autoCommit - * @param bindName JNDI name to bind this javax.sql.DataSource - * created by this class to. - * @param jndi JNDIComponent we will use to bind. + * @param bindName + * JNDI name to bind this javax.sql.DataSource + * created by this class to. + * @param jndi + * JNDIComponent we will use to bind. */ - public BoundDBCPDatasourceComponent(String user, String password, String driverName, String connectURI, - int maxActive, int maxWait, byte whenExhausted, boolean autoCommit, String bindName, JNDIComponent jndi) + public BoundDBCPDatasourceComponent(String user, String password, + String driverName, String connectURI, int maxActive, int maxWait, + byte whenExhausted, boolean autoCommit, String bindName, + JNDIComponent jndi) { - super(user, password, driverName, connectURI, maxActive, maxWait, whenExhausted, autoCommit); - if(jndi == null) - { - throw new IllegalArgumentException("jndi argument cannot be null for BoundDBCPDatasourceComponent"); - } - - if(bindName == null) - { - throw new IllegalArgumentException("bindName argument cannot be null for BoundDBCPDatasourceComponent"); - } - + super(user, password, driverName, connectURI, maxActive, maxWait, + whenExhausted, autoCommit); + if (jndi == null) { throw new IllegalArgumentException( + "jndi argument cannot be null for BoundDBCPDatasourceComponent"); } + + if (bindName == null) { throw new IllegalArgumentException( + "bindName argument cannot be null for BoundDBCPDatasourceComponent"); } + this.jndi = jndi; this.bindName = bindName; } + /** - * Same as {@link DBCPDatasourceComponent#start()} - * but also binds these javax.sql.DataSource - * created to the bindName. + * Same as {@link DBCPDatasourceComponent#start()} but also binds these + * javax.sql.DataSource created to the bindName. * * @see org.picocontainer.Startable#start() */ public void start() - { + { super.start(); try { - jndi.bindObject("comp/env/jdbc/"+bindName, getDatasource()); - jndi.bindObject("jdbc/"+bindName, getDatasource()); + jndi.bindObject("comp/env/jdbc/" + bindName, getDatasource()); + jndi.bindObject("jdbc/" + bindName, getDatasource()); } catch (NamingException e) { - IllegalStateException ise = new IllegalStateException("Naming exception "+e.toString()); + IllegalStateException ise = new IllegalStateException( + "Naming exception " + e.toString()); ise.initCause(e); throw ise; } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.picocontainer.Startable#stop() */ public void stop() - { + { try { - jndi.unbindObject("comp/env/jdbc/"+bindName); + jndi.unbindObject("comp/env/jdbc/" + bindName); jndi.unbindObject("jdbc/" + bindName); } catch (NamingException e) { - throw new IllegalStateException("Naming exception "+e.toString()); + throw new IllegalStateException("Naming exception " + e.toString()); } super.stop(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/DBCPDatasourceComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/DBCPDatasourceComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/DBCPDatasourceComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,86 +37,93 @@ /** *

      * DBCPDatasourceComponent - *

      - * - * - * @ + *

      @ * @author Scott T. Weaver * @author Ate Douma * @version $Id$ - * + * */ public class DBCPDatasourceComponent implements DatasourceComponent { - private static final Log log = LogFactory.getLog(DBCPDatasourceComponent.class); + private static final Log log = LogFactory + .getLog(DBCPDatasourceComponent.class); protected PoolingDataSource dataSource; - //protected DataSource dataSource; - + + // protected DataSource dataSource; + private String user; - + private String password; - + private String driverName; - - private String connectURI; - + + private String connectURI; + private int maxActive; - + private int maxWait; - + private byte whenExhausted; - + private PoolableConnectionFactory dsConnectionFactory; + /** * * Creates a simple commons DBCP connection pool using the following * parameters. *

      - * If you need to bind the datasource of this component to - * JNDI please @see org.apache.jetspeed.components.jndi.JNDIComponent - *

      + * If you need to bind the datasource of this component to JNDI please * - * @param user User name that will be used to connect to the DB - * @param password Password that will be used to connect to the DB - * @param driverName Fully qualified driver to be used by the connection pool - * @param connectURI Fully qualified URI to the DB. - * @param maxActive Maximum active connection - * @param maxWait if whenExhausted is set to GenericObjectPool.WHEN_EXHAUSTED_BLOCK - * the length of time to block while waiting for a connection to become - * available. - * @param whenExhausted GenericObjectPool.WHEN_EXHAUSTED_BLOCK, GenericObjectPool.WHEN_EXHAUSTED_GROW or - * GenericObjectPool.WHEN_EXHAUSTED_FAIL. @see org.apache.commons.pooling.GenericObjectPool - * for more information on these settings - * @param autoCommit Whether or not this datasource will autocommit - * @throws ClassNotFoundException If the driverName could not be - * located within any classloaders. + * @see org.apache.jetspeed.components.jndi.JNDIComponent + *

      + * + * @param user + * User name that will be used to connect to the DB + * @param password + * Password that will be used to connect to the DB + * @param driverName + * Fully qualified driver to be used by the connection pool + * @param connectURI + * Fully qualified URI to the DB. + * @param maxActive + * Maximum active connection + * @param maxWait + * if whenExhausted is set to + * GenericObjectPool.WHEN_EXHAUSTED_BLOCK the length of time to + * block while waiting for a connection to become available. + * @param whenExhausted + * GenericObjectPool.WHEN_EXHAUSTED_BLOCK, + * GenericObjectPool.WHEN_EXHAUSTED_GROW or + * GenericObjectPool.WHEN_EXHAUSTED_FAIL. + * @see org.apache.commons.pooling.GenericObjectPool for more information on + * these settings + * @param autoCommit + * Whether or not this datasource will autocommit + * @throws ClassNotFoundException + * If the driverName could not be located within + * any classloaders. */ - public DBCPDatasourceComponent( - String user, - String password, - String driverName, - String connectURI, - int maxActive, - int maxWait, - byte whenExhausted, - boolean autoCommit) - + public DBCPDatasourceComponent(String user, String password, + String driverName, String connectURI, int maxActive, int maxWait, + byte whenExhausted, boolean autoCommit) + { log.info("Setting up data source pooling for " + driverName); log.info("Max active connnections set to: " + maxActive); - log.info("Pool is set to \"" + whenExhausted + "\" when all connections are exhausted."); - - this.user = user; - this.password = password; - this.driverName = driverName; - this.connectURI = connectURI; - this.maxActive = maxActive; - this.maxWait = maxWait; + log.info("Pool is set to \"" + whenExhausted + + "\" when all connections are exhausted."); + + this.user = user; + this.password = password; + this.driverName = driverName; + this.connectURI = connectURI; + this.maxActive = maxActive; + this.maxWait = maxWait; } /** @@ -126,10 +133,11 @@ *

      * *

      - * returns the datasource created by this component + * returns the datasource created by this component *

      + * * @return - * + * */ public DataSource getDatasource() { @@ -141,29 +149,34 @@ try { - log.info("Attempting to start DBCPCDatasourceComponent."); + log.info("Attempting to start DBCPCDatasourceComponent."); Class.forName(driverName); - + // Validate the connection before we go any further try { - Connection conn = DriverManager.getConnection(connectURI, user, password); + Connection conn = DriverManager.getConnection(connectURI, user, + password); conn.close(); } - catch(Exception e) + catch (Exception e) { - log.error("Unable to obtain a connection database via URI: "+connectURI, e); + log.error("Unable to obtain a connection database via URI: " + + connectURI, e); throw e; } - - ObjectPool connectionPool = new GenericObjectPool(null, maxActive, whenExhausted, maxWait); - - ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, user, password); - - dsConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); - - dataSource = new PoolingDataSource(connectionPool); - + + ObjectPool connectionPool = new GenericObjectPool(null, maxActive, + whenExhausted, maxWait); + + ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( + connectURI, user, password); + + dsConnectionFactory = new PoolableConnectionFactory( + connectionFactory, connectionPool, null, null, false, true); + + dataSource = new PoolingDataSource(connectionPool); + log.info("DBCPCDatasourceComponent successfuly started!"); } catch (Throwable e) @@ -171,8 +184,8 @@ CharArrayWriter caw = new CharArrayWriter(); e.printStackTrace(new PrintWriter(caw)); String msg = "Unable to start DBCPCDatasourceComponent: "; - log.error(msg+e.toString(), e); - throw new IllegalStateException(msg+caw.toString()); + log.error(msg + e.toString(), e); + throw new IllegalStateException(msg + caw.toString()); } } @@ -183,7 +196,8 @@ log.info("Stopping DBCPCDatasourceComponent"); dsConnectionFactory.getPool().close(); - // Support for using an embedded Derby database multiple times from one JVM + // Support for using an embedded Derby database multiple times from + // one JVM // by properly shutting it down after each (test) run if (driverName.equals("org.apache.derby.jdbc.EmbeddedDriver")) { @@ -191,26 +205,29 @@ int parIndex = connectURI.indexOf(";"); if (parIndex > -1) { - shutDownURI = connectURI.substring(0, parIndex)+";shutdown=true"; + shutDownURI = connectURI.substring(0, parIndex) + + ";shutdown=true"; } else { - shutDownURI = connectURI+";shutdown=true"; + shutDownURI = connectURI + ";shutdown=true"; } - Class dc = Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); - Driver driver = (Driver)dc.newInstance(); + Class dc = Class + .forName("org.apache.derby.jdbc.EmbeddedDriver"); + Driver driver = (Driver) dc.newInstance(); Properties info = new Properties(); - info.put( "user", user ); - info.put( "password", password ); - + info.put("user", user); + info.put("password", password); + driver.connect(shutDownURI, info); } } catch (Exception e) { - IllegalStateException ise = - new IllegalStateException("Unable to sfaely shutdown the DBCPConnection pool: " + e.toString()); + IllegalStateException ise = new IllegalStateException( + "Unable to sfaely shutdown the DBCPConnection pool: " + + e.toString()); ise.initCause(e); try { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/DatasourceComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/DatasourceComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/DatasourceComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,16 +21,14 @@ /** *

      * DatasourceComponent - *

      - * - * - * @ + *

      @ * @author Scott T. Weaver * @version $ $ - * + * */ public interface DatasourceComponent { + /** * *

      @@ -38,10 +36,11 @@ *

      * *

      - * returns the datasource created by this component + * returns the datasource created by this component *

      + * * @return - * + * */ public abstract DataSource getDatasource(); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/SchemaAwareDataSourceProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/SchemaAwareDataSourceProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/datasource/SchemaAwareDataSourceProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -36,8 +36,10 @@ */ public class SchemaAwareDataSourceProxy extends TransactionAwareDataSourceProxy { - private static final Log log = LogFactory.getLog(SchemaAwareDataSourceProxy.class); + private static final Log log = LogFactory + .getLog(SchemaAwareDataSourceProxy.class); + private String schemaSql = null; public void setSchemaSql(String schemaSql) @@ -53,7 +55,8 @@ { if (log.isDebugEnabled()) { - log.debug("Setting schema by executing sql '" + schemaSql + "' on connection " + con); + log.debug("Setting schema by executing sql '" + schemaSql + + "' on connection " + con); } Statement stmt = con.createStatement(); @@ -64,7 +67,8 @@ } catch (Exception e) { - log.error("Error executing table schema setting sql: '" + schemaSql + "'.", e); + log.error("Error executing table schema setting sql: '" + + schemaSql + "'.", e); } finally { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/JNDIComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/JNDIComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/JNDIComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,24 +22,22 @@ /** *

      * JNDIComponent - *

      - * - * - * @ + *

      @ * @author Scott T. Weaver * @version $ $ - * + * */ public interface JNDIComponent { - Context getRootContext(); - - void bindToCurrentThread() throws NamingException; - - void unbindFromCurrentThread() throws NamingException; - - void bindObject(String bindToName, Object obj) throws NamingException; - - void unbindObject(String name) throws NamingException; + Context getRootContext(); + + void bindToCurrentThread() throws NamingException; + + void unbindFromCurrentThread() throws NamingException; + + void bindObject(String bindToName, Object obj) throws NamingException; + + void unbindObject(String name) throws NamingException; + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/JetspeedTestJNDIComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/JetspeedTestJNDIComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/JetspeedTestJNDIComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,31 +22,38 @@ /** * JetspeedDSTestJNDIComponent *

      - * Uses TyrexJNDIComponent to define a jetspeed Datasource for testing purposes only. + * Uses TyrexJNDIComponent to define a jetspeed Datasource for testing purposes + * only. *

      + * * @author Scott T. Weaver * @author Ate Douma * @version $Id$ */ public class JetspeedTestJNDIComponent { + public static final String JNDI_DS_NAME = "jetspeed"; - + protected BoundDBCPDatasourceComponent datasourceComponent; + protected JNDIComponent jndi; - + public void setup() throws Exception { jndi = new TyrexJNDIComponent(); String url = System.getProperty("org.apache.jetspeed.database.url"); - String driver = System.getProperty("org.apache.jetspeed.database.driver"); + String driver = System + .getProperty("org.apache.jetspeed.database.driver"); String user = System.getProperty("org.apache.jetspeed.database.user"); - String password = System.getProperty("org.apache.jetspeed.database.password"); - datasourceComponent = new BoundDBCPDatasourceComponent(user, password, driver, url, 20, 5000, - GenericObjectPool.WHEN_EXHAUSTED_GROW, true, JNDI_DS_NAME, jndi); + String password = System + .getProperty("org.apache.jetspeed.database.password"); + datasourceComponent = new BoundDBCPDatasourceComponent(user, password, + driver, url, 20, 5000, GenericObjectPool.WHEN_EXHAUSTED_GROW, + true, JNDI_DS_NAME, jndi); datasourceComponent.start(); } - + public void tearDown() throws Exception { jndi.unbindFromCurrentThread(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/SpringJNDIStarter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/SpringJNDIStarter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/SpringJNDIStarter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,129 +18,144 @@ /** *

      - * Helper class to establish a jndi based datasource for commandline and maven based applications - * - *

      + * Helper class to establish a jndi based datasource for commandline and maven + * based applications * - * - * @ + *

      @ * @author Hajo Birthelmer * @version $ $ - * + * */ - import java.util.Map; import org.apache.commons.pool.impl.GenericObjectPool; import org.apache.jetspeed.components.SpringComponentManager; import org.apache.jetspeed.components.datasource.BoundDBCPDatasourceComponent; -import org.apache.jetspeed.components.jndi.JNDIComponent; -import org.apache.jetspeed.components.jndi.TyrexJNDIComponent; public class SpringJNDIStarter { - public static final String JNDI_DS_NAME = "jetspeed"; - public static final String DATASOURCE_DRIVER = "org.apache.jetspeed.database.driver".intern(); - public static final String DATASOURCE_URL = "org.apache.jetspeed.database.url".intern(); - public static final String DATASOURCE_USERNAME = "org.apache.jetspeed.database.user".intern(); - public static final String DATASOURCE_PASSWORD = "org.apache.jetspeed.database.password".intern(); + public static final String JNDI_DS_NAME = "jetspeed"; + public static final String DATASOURCE_DRIVER = "org.apache.jetspeed.database.driver" + .intern(); - - - private final Map context; - - protected BoundDBCPDatasourceComponent datasourceComponent; - protected JNDIComponent jndi; - String appRoot = null; - String[] bootConfig = null; - String[] appConfig = null; - SpringComponentManager scm = null; - - - /** - * - * Create an instance with a given context and the usual SpringComponent arguments - * @param context - * @param appRoot root directory of the application - * @param bootConfig (string-)list of files to process on boot - * @param appConfig (string-)list of files to process as configuration - */ - public SpringJNDIStarter(Map context,String appRoot, String[] bootConfig, String[] appConfig) - { - this.context = context; - this.appRoot = appRoot; - this.bootConfig = bootConfig; - this.appConfig = appConfig; - } + public static final String DATASOURCE_URL = "org.apache.jetspeed.database.url" + .intern(); -/** - * The main startup routine. - * Establishes a JNDI connection based on the following System parameters: - *

      org.apache.jetspeed.database.url - *

      org.apache.jetspeed.database.driver - *

      org.apache.jetspeed.database.user - *

      org.apache.jetspeed.database.password - * @throws Exception - */ + public static final String DATASOURCE_USERNAME = "org.apache.jetspeed.database.user" + .intern(); + + public static final String DATASOURCE_PASSWORD = "org.apache.jetspeed.database.password" + .intern(); + + private final Map context; + + protected BoundDBCPDatasourceComponent datasourceComponent; + + protected JNDIComponent jndi; + + String appRoot = null; + + String[] bootConfig = null; + + String[] appConfig = null; + + SpringComponentManager scm = null; + + /** + * + * Create an instance with a given context and the usual SpringComponent + * arguments + * + * @param context + * @param appRoot + * root directory of the application + * @param bootConfig + * (string-)list of files to process on boot + * @param appConfig + * (string-)list of files to process as configuration + */ + public SpringJNDIStarter(Map context, String appRoot, String[] bootConfig, + String[] appConfig) + { + this.context = context; + this.appRoot = appRoot; + this.bootConfig = bootConfig; + this.appConfig = appConfig; + } + + /** + * The main startup routine. Establishes a JNDI connection based on the + * following System parameters: + *

      + * org.apache.jetspeed.database.url + *

      + * org.apache.jetspeed.database.driver + *

      + * org.apache.jetspeed.database.user + *

      + * org.apache.jetspeed.database.password + * + * @throws Exception + */ public void setUp() throws Exception { - setupJNDI(); - scm = new SpringComponentManager(bootConfig, appConfig, appRoot ); - } + setupJNDI(); + scm = new SpringComponentManager(bootConfig, appConfig, appRoot); + } public void tearDown() throws Exception { - try - { - datasourceComponent.stop(); - } - catch (Exception e) - { - System.out.println("datasourceComponent stop failed with " + e.getLocalizedMessage()); - e.printStackTrace(); - } - try - { - scm.stop(); - } - catch (Exception e) - { - System.out.println("SpringComponentManager stop failed with " + e.getLocalizedMessage()); - e.printStackTrace(); - } - - try - { - jndi.unbindFromCurrentThread(); - } - catch (Exception e) - { - System.out.println("JNDI unbindFromCurrentThread failed with " + e.getLocalizedMessage()); - e.printStackTrace(); - } + try + { + datasourceComponent.stop(); + } + catch (Exception e) + { + System.out.println("datasourceComponent stop failed with " + + e.getLocalizedMessage()); + e.printStackTrace(); + } + try + { + scm.stop(); + } + catch (Exception e) + { + System.out.println("SpringComponentManager stop failed with " + + e.getLocalizedMessage()); + e.printStackTrace(); + } + + try + { + jndi.unbindFromCurrentThread(); + } + catch (Exception e) + { + System.out.println("JNDI unbindFromCurrentThread failed with " + + e.getLocalizedMessage()); + e.printStackTrace(); + } } - + String getProperty(String name) { - String s = null; - try - { - if (context != null) - s = (String) context.get(name); - } - catch (Exception e) - { - e.printStackTrace(); - } - if (s == null) - s = System.getProperty(name); - return s; + String s = null; + try + { + if (context != null) s = (String) context.get(name); + } + catch (Exception e) + { + e.printStackTrace(); + } + if (s == null) s = System.getProperty(name); + return s; } - - + public void setupJNDI() throws Exception { jndi = new TyrexJNDIComponent(); @@ -148,20 +163,20 @@ String driver = getProperty("org.apache.jetspeed.database.driver"); String user = getProperty("org.apache.jetspeed.database.user"); String password = getProperty("org.apache.jetspeed.database.password"); - datasourceComponent = new BoundDBCPDatasourceComponent(user, password, driver, url, 20, 5000, - GenericObjectPool.WHEN_EXHAUSTED_GROW, true, JNDI_DS_NAME, jndi); + datasourceComponent = new BoundDBCPDatasourceComponent(user, password, + driver, url, 20, 5000, GenericObjectPool.WHEN_EXHAUSTED_GROW, + true, JNDI_DS_NAME, jndi); datasourceComponent.start(); } - public SpringComponentManager getComponentManager() - { - return scm; - } + public SpringComponentManager getComponentManager() + { + return scm; + } public Map getContext() { return context; } - - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/TyrexJNDIComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/TyrexJNDIComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/jndi/TyrexJNDIComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * Created on Feb 4, 2004 * @@ -40,9 +40,10 @@ *

      * *

      + * * @author Scott T. Weaver * @version $Id: TyrexJNDIComponent.java 516881 2007-03-11 10:34:21Z ate $ - * + * */ public class TyrexJNDIComponent implements JNDIComponent { @@ -60,21 +61,21 @@ // Construct a non-shared memory context Hashtable env = new Hashtable(); - env.put(Context.INITIAL_CONTEXT_FACTORY, "tyrex.naming.MemoryContextFactory"); + env.put(Context.INITIAL_CONTEXT_FACTORY, + "tyrex.naming.MemoryContextFactory"); rootJNDIContext = new MemoryContext(null); rootJNDIContext.createSubcontext("jdbc"); ctx = rootJNDIContext.createSubcontext("comp"); ctx = ctx.createSubcontext("env"); ctx = ctx.createSubcontext("jdbc"); - // Associate the memory context with a new - // runtime context and associate the runtime context - // with the current thread + // Associate the memory context with a new + // runtime context and associate the runtime context + // with the current thread bindToCurrentThread(); log.info("JNDI successfully initiallized"); } - /** * @see org.apache.jetspeed.cps.jndi.JNDIService#getRootContext() @@ -89,29 +90,32 @@ */ public void bindToCurrentThread() throws NamingException { - RuntimeContext runCtx = RuntimeContext.newRuntimeContext(rootJNDIContext, null); + RuntimeContext runCtx = RuntimeContext.newRuntimeContext( + rootJNDIContext, null); RuntimeContext.setRuntimeContext(runCtx); } - + /** - * + * *

      * bindObject *

      * - * @see org.apache.jetspeed.cps.jndi.JNDIComponent#bindObject(java.lang.String, java.lang.Object) + * @see org.apache.jetspeed.cps.jndi.JNDIComponent#bindObject(java.lang.String, + * java.lang.Object) * @param bindToName * @param obj * @throws NamingException */ - public void bindObject(String bindToName, Object obj) throws NamingException - { - log.debug("Binding "+obj+" to name "+bindToName); - Context ctx = getRootContext(); - ctx.bind(bindToName, obj); - } + public void bindObject(String bindToName, Object obj) + throws NamingException + { + log.debug("Binding " + obj + " to name " + bindToName); + Context ctx = getRootContext(); + ctx.bind(bindToName, obj); + } - /** + /** *

      * unbindFromCurrentThread *

      @@ -121,18 +125,20 @@ */ public void unbindFromCurrentThread() throws NamingException { - RuntimeContext.unsetRuntimeContext(); - RuntimeContext.cleanup(Thread.currentThread()); + RuntimeContext.unsetRuntimeContext(); + RuntimeContext.cleanup(Thread.currentThread()); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.components.jndi.JNDIComponent#unbindObject(java.lang.String) */ - public void unbindObject( String name ) throws NamingException + public void unbindObject(String name) throws NamingException { - log.debug("Unbinding name "+name); - Context ctx = getRootContext(); - ctx.unbind(name); + log.debug("Unbinding name " + name); + Context ctx = getRootContext(); + ctx.unbind(name); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionManagerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionManagerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionManagerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -47,101 +47,129 @@ /** * Manages Connection ressources. This class is a replacement for the default - * ConnectionManagerImpl that comes with OJB. It differs from this class only - * in its way to get a connection factory. The default OJB class always uses - * the class configured in OJB.properties. This implementation looks up the - * factory configured for the given JCD first and uses the default factory - * class only if no class is configured in the JCD. - * + * ConnectionManagerImpl that comes with OJB. It differs from this class only in + * its way to get a connection factory. The default OJB class always uses the + * class configured in OJB.properties. This implementation looks up the factory + * configured for the given JCD first and uses the default factory class only if + * no class is configured in the JCD. + * * @see ConnectionManagerIF * @author Thomas Mahler * @version $Id$ */ public class ConnectionManagerImpl implements ConnectionManagerIF { + // We cannot derive from OBJ's ConnectionManagerIF because member // variables are private - + private Logger log = LoggerFactory.getLogger(ConnectionManagerImpl.class); private PersistenceBroker broker = null; + private ConnectionFactory connectionFactory; + private JdbcConnectionDescriptor jcd; + private Platform platform; + private Connection con = null; + private PBKey pbKey; + private boolean originalAutoCommitState; + private boolean isInLocalTransaction; + private boolean batchMode; + private BatchConnection batchCon = null; - private static Map connectionFactories = Collections.synchronizedMap(new HashMap()); - + private static Map connectionFactories = Collections + .synchronizedMap(new HashMap()); + public ConnectionManagerImpl(PersistenceBroker broker) { this.broker = broker; this.pbKey = broker.getPBKey(); - this.jcd = MetadataManager.getInstance().connectionRepository().getDescriptor(pbKey); - ConnectionPoolDescriptor cpd = jcd.getConnectionPoolDescriptor(); + this.jcd = MetadataManager.getInstance().connectionRepository() + .getDescriptor(pbKey); + ConnectionPoolDescriptor cpd = jcd.getConnectionPoolDescriptor(); if (cpd != null && cpd.getConnectionFactory() != null) { - connectionFactory = (ConnectionFactory)connectionFactories.get(cpd.getConnectionFactory()); - if ( connectionFactory == null ) + connectionFactory = (ConnectionFactory) connectionFactories.get(cpd + .getConnectionFactory()); + if (connectionFactory == null) { try { - if (Boolean.valueOf(this.jcd.getAttribute("org.apache.jetspeed.engineScoped", "false")).booleanValue()) { - ClassLoader cl = Thread.currentThread().getContextClassLoader(); + if (Boolean.valueOf( + this.jcd + .getAttribute( + "org.apache.jetspeed.engineScoped", + "false")).booleanValue()) + { + ClassLoader cl = Thread.currentThread() + .getContextClassLoader(); try { - Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); - connectionFactory = (ConnectionFactory) - ClassHelper.newInstance (cpd.getConnectionFactory(), true); - connectionFactories.put(cpd.getConnectionFactory(), connectionFactory); + Thread.currentThread().setContextClassLoader( + this.getClass().getClassLoader()); + connectionFactory = (ConnectionFactory) ClassHelper + .newInstance(cpd.getConnectionFactory(), + true); + connectionFactories.put(cpd.getConnectionFactory(), + connectionFactory); } finally { Thread.currentThread().setContextClassLoader(cl); - connectionFactories.put(cpd.getConnectionFactory(), connectionFactory); + connectionFactories.put(cpd.getConnectionFactory(), + connectionFactory); } } else { - connectionFactory = (ConnectionFactory) - ClassHelper.newInstance (cpd.getConnectionFactory(), true); + connectionFactory = (ConnectionFactory) ClassHelper + .newInstance(cpd.getConnectionFactory(), true); } } catch (InstantiationException e) { - String err = "Can't instantiate class " + cpd.getConnectionFactory(); + String err = "Can't instantiate class " + + cpd.getConnectionFactory(); log.error(err, e); - throw (IllegalStateException)(new IllegalStateException(err)).initCause(e); + throw (IllegalStateException) (new IllegalStateException( + err)).initCause(e); } catch (IllegalAccessException e) { - String err = "Can't instantiate class " + cpd.getConnectionFactory(); + String err = "Can't instantiate class " + + cpd.getConnectionFactory(); log.error(err, e); - throw (IllegalStateException)(new IllegalStateException(err)).initCause(e); + throw (IllegalStateException) (new IllegalStateException( + err)).initCause(e); } } } - else - { - this.connectionFactory = ConnectionFactoryFactory.getInstance().createConnectionFactory(); + else + { + this.connectionFactory = ConnectionFactoryFactory.getInstance() + .createConnectionFactory(); } this.platform = PlatformFactory.getPlatformFor(jcd); /* - by default batch mode is not enabled and after use of a PB - instance, before instance was returned to pool, batch mode - was set to false again (PB implementation close method) - Be carefully in modify this behaviour, changes could cause - unexpected behaviour - */ + * by default batch mode is not enabled and after use of a PB instance, + * before instance was returned to pool, batch mode was set to false + * again (PB implementation close method) Be carefully in modify this + * behaviour, changes could cause unexpected behaviour + */ setBatchMode(false); } /** - * Returns the associated {@link org.apache.ojb.broker.metadata.JdbcConnectionDescriptor} + * Returns the associated + * {@link org.apache.ojb.broker.metadata.JdbcConnectionDescriptor} */ public JdbcConnectionDescriptor getConnectionDescriptor() { @@ -158,37 +186,41 @@ * {@link org.apache.ojb.broker.accesslayer.ConnectionFactory}. *

      * PB#beginTransaction() opens a single jdbc connection via - * PB#serviceConnectionManager().localBegin(). - * If you call PB#serviceConnectionManager().getConnection() later - * it returns the already opened connection. - * The PB instance will release the used connection during - * PB#commitTransaction() or PB#abortTransaction() or PB#close(). + * PB#serviceConnectionManager().localBegin(). If you call + * PB#serviceConnectionManager().getConnection() later it returns the + * already opened connection. The PB instance will release the used + * connection during PB#commitTransaction() or PB#abortTransaction() or + * PB#close(). *

      *

      - * NOTE: Never call Connection.close() on the connection requested from the ConnectionManager. - * Cleanup of used connection is done by OJB itself. If you need to release a used connection - * call {@link #releaseConnection()}. + * NOTE: Never call Connection.close() on the connection requested from the + * ConnectionManager. Cleanup of used connection is done by OJB itself. If + * you need to release a used connection call {@link #releaseConnection()}. *

      */ public Connection getConnection() throws LookupException { /* - if the connection is not null and we are not in a local tx, we check - the connection state and release "dead" connections. - if connection is in local tx we do nothing, the dead connection will cause - an exception and PB instance have to handle rollback - */ - if(con != null && !isInLocalTransaction() && !isAlive(con)) + * if the connection is not null and we are not in a local tx, we check + * the connection state and release "dead" connections. if connection is + * in local tx we do nothing, the dead connection will cause an + * exception and PB instance have to handle rollback + */ + if (con != null && !isInLocalTransaction() && !isAlive(con)) { releaseConnection(); } if (con == null) { - if (Boolean.valueOf(this.jcd.getAttribute("org.apache.jetspeed.engineScoped", "false")).booleanValue()) { + if (Boolean.valueOf( + this.jcd.getAttribute("org.apache.jetspeed.engineScoped", + "false")).booleanValue()) + { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { - Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); + Thread.currentThread().setContextClassLoader( + this.getClass().getClassLoader()); con = this.connectionFactory.lookupConnection(jcd); } finally @@ -200,8 +232,10 @@ { con = this.connectionFactory.lookupConnection(jcd); } - - if (con == null) throw new PersistenceBrokerException("Cannot get connection for " + jcd); + + if (con == null) + throw new PersistenceBrokerException( + "Cannot get connection for " + jcd); if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE) { try @@ -210,10 +244,14 @@ } catch (SQLException e) { - throw new PersistenceBrokerException("Cannot request autoCommit state on the connection", e); + throw new PersistenceBrokerException( + "Cannot request autoCommit state on the connection", + e); } } - if (log.isDebugEnabled()) log.debug("Request new connection from ConnectionFactory: " + con); + if (log.isDebugEnabled()) + log.debug("Request new connection from ConnectionFactory: " + + con); } if (isBatchMode()) @@ -235,10 +273,8 @@ */ public void localBegin() { - if (this.isInLocalTransaction) - { - throw new TransactionInProgressException("Connection is already in transaction"); - } + if (this.isInLocalTransaction) { throw new TransactionInProgressException( + "Connection is already in transaction"); } Connection connection = null; try { @@ -251,10 +287,12 @@ */ throw new PersistenceBrokerException("Can't lookup a connection", e); } - if (log.isDebugEnabled()) log.debug("localBegin was called for con " + connection); + if (log.isDebugEnabled()) + log.debug("localBegin was called for con " + connection); if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE) { - if (log.isDebugEnabled()) log.debug("Try to change autoCommit state to 'false'"); + if (log.isDebugEnabled()) + log.debug("Try to change autoCommit state to 'false'"); platform.changeAutoCommitState(jcd, connection, false); } this.isInLocalTransaction = true; @@ -266,10 +304,8 @@ public void localCommit() { if (log.isDebugEnabled()) log.debug("commit was called"); - if (!this.isInLocalTransaction) - { - throw new TransactionNotInProgressException("Not in transaction, call begin() before commit()"); - } + if (!this.isInLocalTransaction) { throw new TransactionNotInProgressException( + "Not in transaction, call begin() before commit()"); } try { if (batchCon != null) @@ -283,9 +319,13 @@ } catch (SQLException e) { - log.error("Commit on underlying connection failed, try to rollback connection", e); + log + .error( + "Commit on underlying connection failed, try to rollback connection", + e); this.localRollback(); - throw new TransactionAbortedException("Commit on connection failed", e); + throw new TransactionAbortedException( + "Commit on connection failed", e); } finally { @@ -300,14 +340,13 @@ */ public void localRollback() { - log.info("Rollback was called, do rollback on current connection " + con); - if (!this.isInLocalTransaction) - { - throw new PersistenceBrokerException("Not in transaction, cannot abort"); - } + log.info("Rollback was called, do rollback on current connection " + + con); + if (!this.isInLocalTransaction) { throw new PersistenceBrokerException( + "Not in transaction, cannot abort"); } try { - //truncate the local transaction + // truncate the local transaction this.isInLocalTransaction = false; if (batchCon != null) { @@ -326,12 +365,12 @@ { try { - restoreAutoCommitState(); - } - catch(OJBRuntimeException ignore) + restoreAutoCommitState(); + } + catch (OJBRuntimeException ignore) { - // Ignore or log exception - } + // Ignore or log exception + } releaseConnection(); } } @@ -344,7 +383,9 @@ try { if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE - && originalAutoCommitState == true && con != null && !con.isClosed()) + && originalAutoCommitState == true + && con != null + && !con.isClosed()) { platform.changeAutoCommitState(jcd, con, true); } @@ -352,7 +393,8 @@ catch (SQLException e) { // should never be reached - throw new OJBRuntimeException("Restore of connection autocommit state failed", e); + throw new OJBRuntimeException( + "Restore of connection autocommit state failed", e); } } @@ -367,7 +409,8 @@ } catch (SQLException e) { - log.error("IsAlive check failed, running connection was invalid!!", e); + log.error("IsAlive check failed, running connection was invalid!!", + e); return false; } } @@ -378,19 +421,19 @@ } /** - * Release connection to the {@link org.apache.ojb.broker.accesslayer.ConnectionFactory}, make - * sure that you call the method in either case, it's the only way to free the connection. + * Release connection to the + * {@link org.apache.ojb.broker.accesslayer.ConnectionFactory}, make sure + * that you call the method in either case, it's the only way to free the + * connection. */ public void releaseConnection() { - if (this.con == null) + if (this.con == null) { return; } + if (isInLocalTransaction()) { - return; - } - if(isInLocalTransaction()) - { - log.error("Release connection: connection is in local transaction, missing 'localCommit' or" + - " 'localRollback' call - try to rollback the connection"); + log + .error("Release connection: connection is in local transaction, missing 'localCommit' or" + + " 'localRollback' call - try to rollback the connection"); localRollback(); } else @@ -402,7 +445,8 @@ } /** - * Returns the underlying used {@link org.apache.ojb.broker.accesslayer.ConnectionFactory} + * Returns the underlying used + * {@link org.apache.ojb.broker.accesslayer.ConnectionFactory} * implementation. */ public ConnectionFactory getUnderlyingConnectionFactory() @@ -411,22 +455,21 @@ } /** - * Sets the batch mode on or off - this - * switch only works if you set attribute batch-mode - * in jdbc-connection-descriptor true and your database - * support batch mode. - * - * @param mode the batch mode + * Sets the batch mode on or off - this switch only works if you set + * attribute batch-mode in + * jdbc-connection-descriptor true and your database support + * batch mode. + * + * @param mode + * the batch mode */ public void setBatchMode(boolean mode) { /* - arminw: - if batch mode was set 'false' in repository, - never enable it. - There are many users having weird problems - when batch mode was enabled behind the scenes - */ + * arminw: if batch mode was set 'false' in repository, never enable it. + * There are many users having weird problems when batch mode was + * enabled behind the scenes + */ batchMode = mode && jcd.getBatchMode(); } @@ -457,8 +500,8 @@ } /** - * Execute batch if the number of statements in it - * exceeded the limit (if the batch mode where used). + * Execute batch if the number of statements in it exceeded the limit (if + * the batch mode where used). */ public void executeBatchIfNecessary() throws OJBBatchUpdateException { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionRepositoryEntry.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionRepositoryEntry.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/ConnectionRepositoryEntry.java 2008-05-16 01:54:54 UTC (rev 940) @@ -44,91 +44,103 @@ import org.springframework.beans.factory.InitializingBean; /** - * A JavaBean that configures an entry in OJB's ConnectionRepository - * according to its properties. If a JCD alias is not specified, it defaults - * to the bean's name in the Spring configuration. If the JDBC connection - * descriptor already exists (e.g. because it has been defined in OJB's - * configuration) the properties are merged into the existing descriptor - * (see note about "platform" below), else the JDBC connection descriptor - * is created.

      + * A JavaBean that configures an entry in OJB's ConnectionRepository according + * to its properties. If a JCD alias is not specified, it defaults to the bean's + * name in the Spring configuration. If the JDBC connection descriptor already + * exists (e.g. because it has been defined in OJB's configuration) the + * properties are merged into the existing descriptor (see note about "platform" + * below), else the JDBC connection descriptor is created. + *

      * - * If a JNDI name is set, the bean automatically configures a JDBC connection - * descriptor with a connection factory of type - * ConnectionFactoryManagedImpl, else it uses - * ConectionFactoryDBCPImpl. This may be overridden my setting - * the connection factory property explicitly.

      + * If a JNDI name is set, the bean automatically configures a JDBC connection + * descriptor with a connection factory of type + * ConnectionFactoryManagedImpl, else it uses + * ConectionFactoryDBCPImpl. This may be overridden my setting + * the connection factory property explicitly. + *

      * - * Properties "driverClassName", "url", "username" and "password" are used - * only if no JNDI name is set, i.e. if the connection factory uses the - * driver to create data sources.

      + * Properties "driverClassName", "url", "username" and "password" are used only + * if no JNDI name is set, i.e. if the connection factory uses the driver to + * create data sources. + *

      * - * The bean derives the RDBMS platform setting from the configured - * data source or database driver using OJB's JdbcMetadataUtils - * class. At least until OJB 1.0.3, however, this class does not properly - * distinguish the platforms "Oracle" and "Oracle9i"; it always assigns - * "Oracle". In case of "Oracle", this bean therefore opens a connection, - * obtains the version information from the database server and adjusts the - * platform accordingly. This behaviour may be overridden by setting the - * platform property of the bean explicitly. Note that the - * attribute "platform" of an already existing JCD is ignored. An already - * existing JCD stems most likely from a configuration file "repository.xml". - * As the DTD for "repository.xml" ("repository.dtd") defines a default - * value for attribute "platform" ("Hsqldb"), it is in general impossible - * to find out whether the platform attribute of an existing JCD has been set - * explicitly or has simply assumed its default value. - * + * The bean derives the RDBMS platform setting from the configured data source + * or database driver using OJB's JdbcMetadataUtils class. At + * least until OJB 1.0.3, however, this class does not properly distinguish the + * platforms "Oracle" and "Oracle9i"; it always assigns "Oracle". In case of + * "Oracle", this bean therefore opens a connection, obtains the version + * information from the database server and adjusts the platform accordingly. + * This behaviour may be overridden by setting the platform + * property of the bean explicitly. Note that the attribute "platform" of an + * already existing JCD is ignored. An already existing JCD stems most likely + * from a configuration file "repository.xml". As the DTD for "repository.xml" + * ("repository.dtd") defines a default value for attribute "platform" + * ("Hsqldb"), it is in general impossible to find out whether the platform + * attribute of an existing JCD has been set explicitly or has simply assumed + * its default value. + * * @author Michael Lipp * @version $Id$ */ -public class ConnectionRepositoryEntry - extends BasicDataSource - implements BeanNameAware, InitializingBean +public class ConnectionRepositoryEntry extends BasicDataSource implements + BeanNameAware, InitializingBean { - private static final Log log = LogFactory.getLog(ConnectionRepositoryEntry.class); - + + private static final Log log = LogFactory + .getLog(ConnectionRepositoryEntry.class); + // general properties private String jcdAlias = null; + private String platform = null; + private String connectionFactoryClass = null; + // properties for obtaining data source from JNDI private String jndiName = null; - // properties for creating independant data source + + // properties for creating independant data source private String driverClassName = null; + private String url = null; + private String username = null; + private String password = null; + private boolean jetspeedEngineScoped = true; - private DataSource externalDs; + private DataSource externalDs; public ConnectionRepositoryEntry() { super(); } - + /** * @see org.springframework.beans.factory.BeanNameAware#setBeanName(java.lang.String) */ - public void setBeanName(String beanName) + public void setBeanName(String beanName) { // Use the bean's name as fallback if a JCD alias is not set // explicitly - if (jcdAlias == null) + if (jcdAlias == null) { jcdAlias = beanName; } } - + /** * @return Returns the jcdAlias. */ - public String getJcdAlias() + public String getJcdAlias() { return jcdAlias; } - + /** - * @param jcdAlias The jcdAlias to set. + * @param jcdAlias + * The jcdAlias to set. */ public void setJcdAlias(String jcdAlias) { @@ -138,15 +150,16 @@ /** * @return Returns the jndiName. */ - public String getJndiName() + public String getJndiName() { return jndiName; } /** - * @param jndiName The jndiName to set. + * @param jndiName + * The jndiName to set. */ - public void setJndiName(String jndiName) + public void setJndiName(String jndiName) { this.jndiName = jndiName; } @@ -154,15 +167,16 @@ /** * @return Returns the driverClassName. */ - public String getDriverClassName() + public String getDriverClassName() { - return driverClassName; + return driverClassName; } /** - * @param driverClassName The driverClassName to set. + * @param driverClassName + * The driverClassName to set. */ - public void setDriverClassName(String driverClassName) + public void setDriverClassName(String driverClassName) { super.setDriverClassName(driverClassName); this.driverClassName = driverClassName; @@ -171,15 +185,16 @@ /** * @return Returns the password. */ - public String getPassword() + public String getPassword() { return password; } /** - * @param password The password to set. + * @param password + * The password to set. */ - public void setPassword(String password) + public void setPassword(String password) { super.setPassword(password); this.password = password; @@ -188,15 +203,16 @@ /** * @return Returns the url. */ - public String getUrl() + public String getUrl() { return url; } /** - * @param url The url to set. + * @param url + * The url to set. */ - public void setUrl(String url) + public void setUrl(String url) { super.setUrl(url); this.url = url; @@ -205,35 +221,38 @@ /** * @return Returns the username. */ - public String getUsername() + public String getUsername() { return username; } /** - * @param username The username to set. + * @param username + * The username to set. */ - public void setUsername(String username) + public void setUsername(String username) { super.setUsername(username); this.username = username; } - + /** * @return Returns the platform. */ - public String getPlatform() + public String getPlatform() { return platform; } /** * Set the platform attribute of the JCD. Setting this property overrides - * the value derived from the data source or database driver. - * @param platform The platform to set. + * the value derived from the data source or database driver. + * + * @param platform + * The platform to set. */ - public void setPlatform(String platform) - { + public void setPlatform(String platform) + { this.platform = platform; } @@ -241,28 +260,30 @@ * @see setJetspeedEngineScoped * @return Returns if Jetspeed engine's ENC is used for JNDI lookups. */ - public boolean isJetspeedEngineScoped() + public boolean isJetspeedEngineScoped() { return jetspeedEngineScoped; } /** - * Sets the attribute "org.apache.jetspeed.engineScoped" - * of the JDBC connection descriptor to "true" or - * "false". If set, JNDI lookups of the connection will - * be done using the environment naming context (ENC) of the Jetspeed - * engine. - * @param jetspeedEngineScoped whether to use Jetspeed engine's ENC. + * Sets the attribute "org.apache.jetspeed.engineScoped" of + * the JDBC connection descriptor to "true" or "false". + * If set, JNDI lookups of the connection will be done using the environment + * naming context (ENC) of the Jetspeed engine. + * + * @param jetspeedEngineScoped + * whether to use Jetspeed engine's ENC. */ - public void setJetspeedEngineScoped(boolean jetspeedEngineScoped) + public void setJetspeedEngineScoped(boolean jetspeedEngineScoped) { this.jetspeedEngineScoped = jetspeedEngineScoped; } - public void afterPropertiesSet () throws Exception + public void afterPropertiesSet() throws Exception { // Try to find JCD - ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); + ConnectionRepository cr = MetadataManager.getInstance() + .connectionRepository(); JdbcConnectionDescriptor jcd = cr.getDescriptor(new PBKey(jcdAlias)); if (jcd == null) { @@ -275,41 +296,49 @@ platform = null; } DataSource ds = null; - JdbcMetadataUtils jdbcMetadataUtils = new JdbcMetadataUtils (); + JdbcMetadataUtils jdbcMetadataUtils = new JdbcMetadataUtils(); if (jndiName != null) { // using "preconfigured" data source - if (connectionFactoryClass == null) + if (connectionFactoryClass == null) { - connectionFactoryClass = ConnectionFactoryManagedImpl.class.getName (); + connectionFactoryClass = ConnectionFactoryManagedImpl.class + .getName(); } Context initialContext = new InitialContext(); ds = (DataSource) initialContext.lookup(jndiName); externalDs = ds; - jcd.setDatasourceName(jndiName); - } - else + jcd.setDatasourceName(jndiName); + } + else { // have to get data source ourselves - if (connectionFactoryClass == null) + if (connectionFactoryClass == null) { - connectionFactoryClass = ConnectionFactoryDBCPImpl.class.getName (); + connectionFactoryClass = ConnectionFactoryDBCPImpl.class + .getName(); } jcd.setDriver(driverClassName); Map conData = jdbcMetadataUtils.parseConnectionUrl(url); jcd.setDbms(platform); - jcd.setProtocol((String)conData.get(JdbcMetadataUtils.PROPERTY_PROTOCOL)); - jcd.setSubProtocol((String)conData.get(JdbcMetadataUtils.PROPERTY_SUBPROTOCOL)); - jcd.setDbAlias((String)conData.get(JdbcMetadataUtils.PROPERTY_DBALIAS)); + jcd.setProtocol((String) conData + .get(JdbcMetadataUtils.PROPERTY_PROTOCOL)); + jcd.setSubProtocol((String) conData + .get(JdbcMetadataUtils.PROPERTY_SUBPROTOCOL)); + jcd.setDbAlias((String) conData + .get(JdbcMetadataUtils.PROPERTY_DBALIAS)); jcd.setUserName(username); jcd.setPassWord(password); - // Wrapping the connection factory in a DataSource introduces a bit - // of redundancy (url is parsed again and platform determined again). - // But although JdbcMetadataUtils exposes the methods used in - // fillJCDFromDataSource as public (and these do not require a DataSource) - // the method itself does more than is made available by the exposed methods. + // Wrapping the connection factory in a DataSource introduces a bit + // of redundancy (url is parsed again and platform determined + // again). + // But although JdbcMetadataUtils exposes the methods used in + // fillJCDFromDataSource as public (and these do not require a + // DataSource) + // the method itself does more than is made available by the exposed + // methods. // ds = new MinimalDataSource (jcd); - ds = this; + ds = this; } ConnectionPoolDescriptor cpd = jcd.getConnectionPoolDescriptor(); if (cpd == null) @@ -321,25 +350,33 @@ cpd.setConnectionFactory(conFacCls); jdbcMetadataUtils.fillJCDFromDataSource(jcd, ds, null, null); - - if (platform == null && JdbcMetadataUtils.PLATFORM_ORACLE.equals(jcd.getDbms())) { + + if (platform == null + && JdbcMetadataUtils.PLATFORM_ORACLE.equals(jcd.getDbms())) + { // Postprocess to find Oracle version. - updateOraclePlatform (jcd, ds); + updateOraclePlatform(jcd, ds); } // if platform has explicitly been set, the value takes precedence - if (platform != null) { - if (!platform.equals(jcd.getDbms())) { - log.warn ("Automatically derived RDBMS platform \"" + jcd.getDbms() - + "\" differs from explicitly set platform \"" + platform + "\""); + if (platform != null) + { + if (!platform.equals(jcd.getDbms())) + { + log.warn("Automatically derived RDBMS platform \"" + + jcd.getDbms() + + "\" differs from explicitly set platform \"" + + platform + "\""); } jcd.setDbms(platform); - } else { + } + else + { platform = jcd.getDbms(); } - + // special attributes - jcd.addAttribute("org.apache.jetspeed.engineScoped", - Boolean.toString(jetspeedEngineScoped)); + jcd.addAttribute("org.apache.jetspeed.engineScoped", Boolean + .toString(jetspeedEngineScoped)); } /** @@ -347,35 +384,41 @@ * @throws LookupException * @throws IllegalAccessException * @throws InstantiationException - * throws SQLException + * throws SQLException */ - private void updateOraclePlatform(JdbcConnectionDescriptor jcd, DataSource ds) - throws LookupException, IllegalAccessException, InstantiationException, SQLException + private void updateOraclePlatform(JdbcConnectionDescriptor jcd, + DataSource ds) throws LookupException, IllegalAccessException, + InstantiationException, SQLException { Connection con = null; - try + try { con = ds.getConnection(); DatabaseMetaData metaData = con.getMetaData(); int rdbmsVersion = 0; - try + try { // getDatabaseMajorVersion exists since 1.4, so it may // not be defined for the driver used. rdbmsVersion = metaData.getDatabaseMajorVersion(); - } catch (Throwable t) { + } + catch (Throwable t) + { String dbVersion = metaData.getDatabaseProductVersion(); String relKey = "Release"; String major = dbVersion; int startPos = dbVersion.indexOf(relKey); if (startPos < 0) { - log.warn ("Cannot determine Oracle version, no \"Release\" in procuct version: \"" + dbVersion + "\""); + log + .warn("Cannot determine Oracle version, no \"Release\" in procuct version: \"" + + dbVersion + "\""); return; } startPos += relKey.length(); int dotPos = dbVersion.indexOf('.', startPos); - if (dotPos > 0) { + if (dotPos > 0) + { major = dbVersion.substring(startPos, dotPos).trim(); } try @@ -384,80 +427,97 @@ } catch (NumberFormatException e) { - log.warn ("Cannot determine Oracle version, product version \"" + dbVersion + "\" not layed out as \"... Release N.M.....\""); + log + .warn("Cannot determine Oracle version, product version \"" + + dbVersion + + "\" not layed out as \"... Release N.M.....\""); return; } if (log.isDebugEnabled()) { - log.debug ("Extracted Oracle major version " + rdbmsVersion + " from product version \"" + dbVersion + "\""); + log.debug("Extracted Oracle major version " + rdbmsVersion + + " from product version \"" + dbVersion + "\""); } } - if (rdbmsVersion >= 9) { + if (rdbmsVersion >= 9) + { jcd.setDbms(JdbcMetadataUtils.PLATFORM_ORACLE9I); } } finally { - if (con != null) { - con.close (); + if (con != null) + { + con.close(); } } } /** - * a minimal DataSource implementation that satisfies the requirements - * of JdbcMetadataUtil. + * a minimal DataSource implementation that satisfies the requirements of + * JdbcMetadataUtil. */ - private class MinimalDataSource implements DataSource + private class MinimalDataSource implements DataSource { + private JdbcConnectionDescriptor jcd = null; - + /** * Create a new instance using the given JCD. */ - public MinimalDataSource (JdbcConnectionDescriptor jcd) + public MinimalDataSource(JdbcConnectionDescriptor jcd) { this.jcd = jcd; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.sql.DataSource#getConnection() */ - public Connection getConnection() throws SQLException { - // Use JDBC DriverManager as we may not rely on JCD to be sufficiently + public Connection getConnection() throws SQLException + { + // Use JDBC DriverManager as we may not rely on JCD to be + // sufficiently // initialized to use any of the ConnectionFactories. - try { - // loads the driver - NB call to newInstance() added to force initialisation + try + { + // loads the driver - NB call to newInstance() added to force + // initialisation ClassHelper.getClass(jcd.getDriver(), true); - String url = jcd.getProtocol() + ":" + jcd.getSubProtocol() + ":" + jcd.getDbAlias(); + String url = jcd.getProtocol() + ":" + jcd.getSubProtocol() + + ":" + jcd.getDbAlias(); if (jcd.getUserName() == null) { return DriverManager.getConnection(url); } else { - return DriverManager.getConnection(url, jcd.getUserName(), jcd.getPassWord()); + return DriverManager.getConnection(url, jcd.getUserName(), + jcd.getPassWord()); } } catch (ClassNotFoundException e) { - throw (IllegalStateException) - (new IllegalStateException (e.getMessage ())).initCause (e); + throw (IllegalStateException) (new IllegalStateException(e + .getMessage())).initCause(e); } } - + /** - * @see javax.sql.DataSource#getConnection(java.lang.String, java.lang.String) + * @see javax.sql.DataSource#getConnection(java.lang.String, + * java.lang.String) */ public Connection getConnection(String username, String password) - throws SQLException { - return getConnection (); + throws SQLException + { + return getConnection(); } /** * @see javax.sql.DataSource#getLoginTimeout() */ - public int getLoginTimeout() throws SQLException + public int getLoginTimeout() throws SQLException { return 0; } @@ -465,45 +525,50 @@ /** * @see javax.sql.DataSource#getLogWriter() */ - public PrintWriter getLogWriter() throws SQLException { + public PrintWriter getLogWriter() throws SQLException + { return null; } /** * @see javax.sql.DataSource#setLoginTimeout(int) */ - public void setLoginTimeout(int seconds) throws SQLException { + public void setLoginTimeout(int seconds) throws SQLException + { } /** * @see javax.sql.DataSource#setLogWriter(java.io.PrintWriter) */ - public void setLogWriter(PrintWriter out) throws SQLException { + public void setLogWriter(PrintWriter out) throws SQLException + { } } - - public Connection getConnection() throws SQLException { - if(externalDs != null) - { - return externalDs.getConnection(); - } - else - { - return super.getConnection(); - } - } - - public Connection getConnection(String username, String password) - throws SQLException { - - if(externalDs != null) - { - return externalDs.getConnection(username, password); - } - else - { - return super.getConnection(username, password); - } - } + public Connection getConnection() throws SQLException + { + if (externalDs != null) + { + return externalDs.getConnection(); + } + else + { + return super.getConnection(); + } + } + + public Connection getConnection(String username, String password) + throws SQLException + { + + if (externalDs != null) + { + return externalDs.getConnection(username, password); + } + else + { + return super.getConnection(username, password); + } + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/DatabasePlatformConfigurator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/DatabasePlatformConfigurator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/rdbms/ojb/DatabasePlatformConfigurator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,32 +32,35 @@ import org.apache.ojb.broker.metadata.MetadataManager; /** - * Dynamically configures Database Platform for OJB by looking at the connection string - * and figuring out the OJB platform using an OJB metadata utility - * Its important to get this right otherwise you will be sending the wrong (most likely HSQL) - * flavor of SQL statements to the backend database. + * Dynamically configures Database Platform for OJB by looking at the connection + * string and figuring out the OJB platform using an OJB metadata utility Its + * important to get this right otherwise you will be sending the wrong (most + * likely HSQL) flavor of SQL statements to the backend database. * * @author David Sean Taylor * @version $Id: $ - * + * */ public class DatabasePlatformConfigurator { - private static final Log log = LogFactory.getLog(DatabasePlatformConfigurator.class); - + + private static final Log log = LogFactory + .getLog(DatabasePlatformConfigurator.class); + private DataSource ds; + private String jcdAlias; - + public DatabasePlatformConfigurator(DataSource ds, String jndiName) { this.ds = ds; this.jcdAlias = jndiName; } - - public void init() - throws Exception + + public void init() throws Exception { - ConnectionRepository cr = MetadataManager.getInstance().connectionRepository(); + ConnectionRepository cr = MetadataManager.getInstance() + .connectionRepository(); JdbcConnectionDescriptor jcd = cr.getDescriptor(new PBKey(jcdAlias)); if (jcd == null) { @@ -65,55 +68,58 @@ jcd.setJcdAlias(jcdAlias); cr.addDescriptor(jcd); } - - JdbcMetadataUtils jdbcMetadataUtils = new JdbcMetadataUtils (); + + JdbcMetadataUtils jdbcMetadataUtils = new JdbcMetadataUtils(); jdbcMetadataUtils.fillJCDFromDataSource(jcd, ds, null, null); String platform = jcd.getDbms(); - if (JdbcMetadataUtils.PLATFORM_ORACLE.equals(platform)) + if (JdbcMetadataUtils.PLATFORM_ORACLE.equals(platform)) { // Postprocess to find Oracle version. - platform = updateOraclePlatform (jcd, ds, platform); + platform = updateOraclePlatform(jcd, ds, platform); } // if platform has explicitly been set, the value takes precedence - if (platform != null) + if (platform != null) { - if (!platform.equals(jcd.getDbms())) + if (!platform.equals(jcd.getDbms())) { - log.warn ("Automatically derived RDBMS platform \"" + jcd.getDbms() - + "\" differs from explicitly set platform \"" + platform + "\""); + log.warn("Automatically derived RDBMS platform \"" + + jcd.getDbms() + + "\" differs from explicitly set platform \"" + + platform + "\""); } jcd.setDbms(platform); - } - else + } + else { platform = jcd.getDbms(); } System.out.println("##### platform = " + platform); } - + /** * @param jcd * @throws LookupException * @throws IllegalAccessException * @throws InstantiationException - * throws SQLException + * throws SQLException */ - private String updateOraclePlatform(JdbcConnectionDescriptor jcd, DataSource ds, String platform) - throws LookupException, IllegalAccessException, InstantiationException, SQLException + private String updateOraclePlatform(JdbcConnectionDescriptor jcd, + DataSource ds, String platform) throws LookupException, + IllegalAccessException, InstantiationException, SQLException { Connection con = null; - try + try { con = ds.getConnection(); DatabaseMetaData metaData = con.getMetaData(); int rdbmsVersion = 0; - try + try { // getDatabaseMajorVersion exists since 1.4, so it may // not be defined for the driver used. rdbmsVersion = metaData.getDatabaseMajorVersion(); - } - catch (Throwable t) + } + catch (Throwable t) { String dbVersion = metaData.getDatabaseProductVersion(); String relKey = "Release"; @@ -121,12 +127,15 @@ int startPos = dbVersion.indexOf(relKey); if (startPos < 0) { - log.warn ("Cannot determine Oracle version, no \"Release\" in procuct version: \"" + dbVersion + "\""); + log + .warn("Cannot determine Oracle version, no \"Release\" in procuct version: \"" + + dbVersion + "\""); return platform; } startPos += relKey.length(); int dotPos = dbVersion.indexOf('.', startPos); - if (dotPos > 0) { + if (dotPos > 0) + { major = dbVersion.substring(startPos, dotPos).trim(); } try @@ -135,15 +144,19 @@ } catch (NumberFormatException e) { - log.warn ("Cannot determine Oracle version, product version \"" + dbVersion + "\" not layed out as \"... Release N.M.....\""); + log + .warn("Cannot determine Oracle version, product version \"" + + dbVersion + + "\" not layed out as \"... Release N.M.....\""); return platform; } if (log.isDebugEnabled()) { - log.debug ("Extracted Oracle major version " + rdbmsVersion + " from product version \"" + dbVersion + "\""); + log.debug("Extracted Oracle major version " + rdbmsVersion + + " from product version \"" + dbVersion + "\""); } } - if (rdbmsVersion >= 9) + if (rdbmsVersion >= 9) { jcd.setDbms(JdbcMetadataUtils.PLATFORM_ORACLE9I); return JdbcMetadataUtils.PLATFORM_ORACLE9I; @@ -151,13 +164,12 @@ } finally { - if (con != null) + if (con != null) { - con.close (); + con.close(); } } return platform; } - - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/util/DatasourceEnabledSpringTestCase.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/util/DatasourceEnabledSpringTestCase.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/util/DatasourceEnabledSpringTestCase.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,16 +24,20 @@ * DatasourceEnabledSpringTestCase *

      *

      - * + * *

      + * * @author Scott T. Weaver - * @version $Id: DatasourceEnabledSpringTestCase.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: DatasourceEnabledSpringTestCase.java 516448 2007-03-09 + * 16:25:47Z ate $ + * */ -public abstract class DatasourceEnabledSpringTestCase extends AbstractSpringTestCase +public abstract class DatasourceEnabledSpringTestCase extends + AbstractSpringTestCase { + protected JetspeedTestJNDIComponent jndiDS; - + /** * @see junit.framework.TestCase#setUp() */ @@ -41,7 +45,7 @@ { jndiDS = new JetspeedTestJNDIComponent(); jndiDS.setup(); - super.setUp(); + super.setUp(); } /** @@ -56,7 +60,7 @@ protected String[] getBootConfigurations() { return new String[] - { "boot/datasource.xml"}; + {"boot/datasource.xml"}; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/util/DatasourceTestCase.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/util/DatasourceTestCase.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/java/org/apache/jetspeed/components/util/DatasourceTestCase.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,7 +25,7 @@ /** * @author Scott T. Weaver - * + * */ public class DatasourceTestCase extends TestCase { @@ -35,7 +35,7 @@ protected JNDIComponent jndi; /** - * + * */ public DatasourceTestCase() { @@ -60,11 +60,14 @@ super.setUp(); jndi = new TyrexJNDIComponent(); String url = System.getProperty("org.apache.jetspeed.database.url"); - String driver = System.getProperty("org.apache.jetspeed.database.driver"); + String driver = System + .getProperty("org.apache.jetspeed.database.driver"); String user = System.getProperty("org.apache.jetspeed.database.user"); - String password = System.getProperty("org.apache.jetspeed.database.password"); - datasourceComponent = new BoundDBCPDatasourceComponent(user, password, driver, url, 20, 5000, - GenericObjectPool.WHEN_EXHAUSTED_GROW, true, "jetspeed", jndi); + String password = System + .getProperty("org.apache.jetspeed.database.password"); + datasourceComponent = new BoundDBCPDatasourceComponent(user, password, + driver, url, 20, 5000, GenericObjectPool.WHEN_EXHAUSTED_GROW, + true, "jetspeed", jndi); datasourceComponent.start(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/test/org/apache/jetspeed/components/TestRDBMS.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/test/org/apache/jetspeed/components/TestRDBMS.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rdbms/src/test/org/apache/jetspeed/components/TestRDBMS.java 2008-05-16 01:54:54 UTC (rev 940) @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.jetspeed.components; + import java.sql.Connection; import javax.naming.InitialContext; @@ -27,6 +28,7 @@ import org.apache.jetspeed.components.datasource.DBCPDatasourceComponent; import org.apache.jetspeed.components.datasource.DatasourceComponent; import org.apache.jetspeed.components.util.DatasourceTestCase; + /** *

      * TestJNDIComponent @@ -34,15 +36,17 @@ * * @author Scott T. Weaver * @version $ $ - * + * */ public class TestRDBMS extends DatasourceTestCase { + public static Test suite() { // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestRDBMS.class); } + /** * Defines the testcase name for JUnit. * @@ -53,13 +57,14 @@ { super(name); } - + public void testDBCP_1() throws Exception { - assertTrue(DatasourceComponent.class.isAssignableFrom(DBCPDatasourceComponent.class)); + assertTrue(DatasourceComponent.class + .isAssignableFrom(DBCPDatasourceComponent.class)); InitialContext context = new InitialContext(); - //look up from jndi + // look up from jndi assertNotNull(context.lookup("java:/jdbc/jetspeed")); assertNotNull(datasourceComponent); DataSource ds = datasourceComponent.getDatasource(); @@ -69,8 +74,7 @@ assertFalse(conn.isClosed()); conn.close(); (datasourceComponent).stop(); - - + try { context.lookup("java:/jdbc/jetspeed"); @@ -78,13 +82,9 @@ } catch (NamingException e) { - + } - - - + } - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletentity/PersistenceBrokerPortletEntityAccess.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletentity/PersistenceBrokerPortletEntityAccess.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletentity/PersistenceBrokerPortletEntityAccess.java 2008-05-16 01:54:54 UTC (rev 940) @@ -53,71 +53,79 @@ *

      * * @author Scott T. Weaver - * @version $Id: PersistenceBrokerPortletEntityAccess.java,v 1.5 2005/04/29 13:59:08 weaver Exp $ - * + * @version $Id: PersistenceBrokerPortletEntityAccess.java,v 1.5 2005/04/29 + * 13:59:08 weaver Exp $ + * */ -public class PersistenceBrokerPortletEntityAccess extends PersistenceBrokerDaoSupport - implements - PortletEntityAccessComponent +public class PersistenceBrokerPortletEntityAccess extends + PersistenceBrokerDaoSupport implements PortletEntityAccessComponent { + private PortletRegistry registry; + private PortletWindowAccessor windowAccessor = null; - - // 2006-08-22: by default, do not merge preferences from the shared preferences area - // up until this point, all preferences were shared. With JS2-449, preferences are now + + // 2006-08-22: by default, do not merge preferences from the shared + // preferences area + // up until this point, all preferences were shared. With JS2-449, + // preferences are now // stored 'per user'. The username is stored in the preferences FULL_PATH - // To turn on mergeSharedPreferences configure this property to true + // To turn on mergeSharedPreferences configure this property to true // in your Spring configuration boolean mergeSharedPreferences = false; - + /** * * @param registry */ - public PersistenceBrokerPortletEntityAccess( PortletRegistry registry ) + public PersistenceBrokerPortletEntityAccess(PortletRegistry registry) { super(); - this.registry = registry; + this.registry = registry; PortletEntityImpl.registry = registry; } - public PersistenceBrokerPortletEntityAccess(PortletRegistry registry, RequestContextComponent rcc) + public PersistenceBrokerPortletEntityAccess(PortletRegistry registry, + RequestContextComponent rcc) { super(); - this.registry = registry; + this.registry = registry; PortletEntityImpl.registry = registry; PortletEntityImpl.rcc = rcc; } - public PersistenceBrokerPortletEntityAccess(PortletRegistry registry, RequestContextComponent rcc, PageManager pageManager) + public PersistenceBrokerPortletEntityAccess(PortletRegistry registry, + RequestContextComponent rcc, PageManager pageManager) { super(); - this.registry = registry; + this.registry = registry; PortletEntityImpl.registry = registry; PortletEntityImpl.rcc = rcc; PortletEntityImpl.pm = pageManager; } - - public PersistenceBrokerPortletEntityAccess(PortletRegistry registry, RequestContextComponent rcc, PageManager pageManager, boolean mergeSharedPreferences) + + public PersistenceBrokerPortletEntityAccess(PortletRegistry registry, + RequestContextComponent rcc, PageManager pageManager, + boolean mergeSharedPreferences) { super(); - this.registry = registry; + this.registry = registry; PortletEntityImpl.registry = registry; PortletEntityImpl.rcc = rcc; PortletEntityImpl.pm = pageManager; this.mergeSharedPreferences = mergeSharedPreferences; } - + public void setEntityAccessProxy(PortletEntityAccessComponent proxy) { PortletEntityImpl.pac = proxy; } - + public void setPageManager(PageManager pageManager) { PortletEntityImpl.pm = pageManager; } - + /** * *

      @@ -128,28 +136,28 @@ * java.lang.String) * @param fragment * @param principal - * @return @throws - * PortletEntityNotGeneratedException + * @return + * @throws PortletEntityNotGeneratedException */ - public MutablePortletEntity generateEntityFromFragment( ContentFragment fragment, String principal ) + public MutablePortletEntity generateEntityFromFragment( + ContentFragment fragment, String principal) throws PortletEntityNotGeneratedException { - PortletDefinition pd = registry.getPortletDefinitionByUniqueName(fragment.getName()); + PortletDefinition pd = registry + .getPortletDefinitionByUniqueName(fragment.getName()); ObjectID entityKey = generateEntityKey(fragment, principal); MutablePortletEntity portletEntity = null; if (pd != null) { portletEntity = newPortletEntityInstance(pd); - if (portletEntity == null) - { - throw new PortletEntityNotGeneratedException("Failed to create Portlet Entity for " - + fragment.getName()); - } + if (portletEntity == null) { throw new PortletEntityNotGeneratedException( + "Failed to create Portlet Entity for " + fragment.getName()); } } else { - String msg = "Failed to retrieve Portlet Definition for " + fragment.getName(); + String msg = "Failed to retrieve Portlet Definition for " + + fragment.getName(); logger.warn(msg); portletEntity = new PortletEntityImpl(fragment); fragment.overrideRenderedContent(msg); @@ -168,11 +176,11 @@ * * @see org.apache.jetspeed.components.portletentity.PortletEntityAccessComponent#generateEntityFromFragment(org.apache.jetspeed.om.page.Fragment) * @param fragment - * @return @throws - * PortletEntityNotGeneratedException + * @return + * @throws PortletEntityNotGeneratedException */ - public MutablePortletEntity generateEntityFromFragment( ContentFragment fragment ) - throws PortletEntityNotGeneratedException + public MutablePortletEntity generateEntityFromFragment( + ContentFragment fragment) throws PortletEntityNotGeneratedException { return generateEntityFromFragment(fragment, null); } @@ -189,7 +197,7 @@ * @param principal * @return */ - public ObjectID generateEntityKey( Fragment fragment, String principal ) + public ObjectID generateEntityKey(Fragment fragment, String principal) { StringBuffer key = new StringBuffer(); if (principal != null && principal.length() > 0) @@ -211,19 +219,21 @@ * @param portletDefinition * @return */ - public Collection getPortletEntities( PortletDefinition portletDefinition ) + public Collection getPortletEntities(PortletDefinition portletDefinition) { Criteria c = new Criteria(); - String appName = ((MutablePortletApplication) portletDefinition.getPortletApplicationDefinition()).getName(); + String appName = ((MutablePortletApplication) portletDefinition + .getPortletApplicationDefinition()).getName(); String portletName = portletDefinition.getName(); c.addEqualTo("appName", appName); c.addEqualTo("portletName", portletName); - return getPersistenceBrokerTemplate().getCollectionByQuery(QueryFactory.newQuery(PortletEntityImpl.class, c)); + return getPersistenceBrokerTemplate().getCollectionByQuery( + QueryFactory.newQuery(PortletEntityImpl.class, c)); } - - public Collection getPortletEntities( String portletUniqueName ) - { + + public Collection getPortletEntities(String portletUniqueName) + { String[] split = portletUniqueName.split("::"); String appName = split[0]; String portletName = split[1]; @@ -231,31 +241,35 @@ c.addEqualTo("appName", appName); c.addEqualTo("portletName", portletName); - return getPersistenceBrokerTemplate().getCollectionByQuery(QueryFactory.newQuery(PortletEntityImpl.class, c)); + return getPersistenceBrokerTemplate().getCollectionByQuery( + QueryFactory.newQuery(PortletEntityImpl.class, c)); } - public MutablePortletEntity getPortletEntity( ObjectID id ) + public MutablePortletEntity getPortletEntity(ObjectID id) { try { return getPortletEntity(id, null); } // This exception is only thrown if a Fragment has been passed into the - // getPortletEntity() method. This should never happen. + // getPortletEntity() method. This should never happen. catch (PortletEntityNotStoredException e) { - IllegalStateException ise = new IllegalStateException("Unexepected error while retrieving portlet entity "+id); + IllegalStateException ise = new IllegalStateException( + "Unexepected error while retrieving portlet entity " + id); ise.initCause(e); throw ise; } } - protected MutablePortletEntity getPortletEntity(ObjectID id, ContentFragment fragment) throws PortletEntityNotStoredException + protected MutablePortletEntity getPortletEntity(ObjectID id, + ContentFragment fragment) throws PortletEntityNotStoredException { Criteria c = new Criteria(); c.addEqualTo("id", id.toString()); Query q = QueryFactory.newQuery(PortletEntityImpl.class, c); - MutablePortletEntity portletEntity = (MutablePortletEntity) getPersistenceBrokerTemplate().getObjectByQuery(q); + MutablePortletEntity portletEntity = (MutablePortletEntity) getPersistenceBrokerTemplate() + .getObjectByQuery(q); if (portletEntity == null) { return null; @@ -263,79 +277,96 @@ else { String portletUniqueName = portletEntity.getPortletUniqueName(); - PortletDefinitionComposite parentPortletDef = registry.getPortletDefinitionByUniqueName(portletUniqueName); - if(parentPortletDef != null) + PortletDefinitionComposite parentPortletDef = registry + .getPortletDefinitionByUniqueName(portletUniqueName); + if (parentPortletDef != null) { - //Indication that the fragment has changed the portlet it references. - if(fragment != null && !portletUniqueName.equals(fragment.getName())) + // Indication that the fragment has changed the portlet it + // references. + if (fragment != null + && !portletUniqueName.equals(fragment.getName())) { - parentPortletDef = registry.getPortletDefinitionByUniqueName(fragment.getName()); - ((PortletEntityCtrl)portletEntity).setPortletDefinition(parentPortletDef); + parentPortletDef = registry + .getPortletDefinitionByUniqueName(fragment + .getName()); + ((PortletEntityCtrl) portletEntity) + .setPortletDefinition(parentPortletDef); storePortletEntity(portletEntity); } else { - ((PortletEntityCtrl)portletEntity).setPortletDefinition(parentPortletDef); + ((PortletEntityCtrl) portletEntity) + .setPortletDefinition(parentPortletDef); } } - else if(fragment != null && parentPortletDef == null) + else if (fragment != null && parentPortletDef == null) { - // If we have no porlet definition but have a fragment, we see if the + // If we have no porlet definition but have a fragment, we see + // if the // unique name has changed and access the portlet definition // using that unique name. - parentPortletDef = registry.getPortletDefinitionByUniqueName(fragment.getName()); - if ( parentPortletDef != null) + parentPortletDef = registry + .getPortletDefinitionByUniqueName(fragment.getName()); + if (parentPortletDef != null) { - ((PortletEntityCtrl)portletEntity).setPortletDefinition(parentPortletDef); + ((PortletEntityCtrl) portletEntity) + .setPortletDefinition(parentPortletDef); storePortletEntity(portletEntity); } } - - if(parentPortletDef == null) + + if (parentPortletDef == null) { - final String msg = "Portlet "+portletUniqueName+" not found"; + final String msg = "Portlet " + portletUniqueName + + " not found"; String content = fragment.getOverriddenContent(); if (content == null || !content.equals(msg)) { fragment.overrideRenderedContent(msg); logger.error(msg); } - } - - return portletEntity; + } + + return portletEntity; } } - public MutablePortletEntity getPortletEntity( String id ) + public MutablePortletEntity getPortletEntity(String id) { ObjectID oid = JetspeedObjectID.createFromString(id); return getPortletEntity(oid); } - public MutablePortletEntity getPortletEntityForFragment( ContentFragment fragment, String principal ) throws PortletEntityNotStoredException + public MutablePortletEntity getPortletEntityForFragment( + ContentFragment fragment, String principal) + throws PortletEntityNotStoredException { - return getPortletEntity(generateEntityKey(fragment, principal), fragment); + return getPortletEntity(generateEntityKey(fragment, principal), + fragment); } - public MutablePortletEntity getPortletEntityForFragment( ContentFragment fragment ) throws PortletEntityNotStoredException + public MutablePortletEntity getPortletEntityForFragment( + ContentFragment fragment) throws PortletEntityNotStoredException { return getPortletEntity(generateEntityKey(fragment, null), fragment); } - public MutablePortletEntity newPortletEntityInstance( PortletDefinition portletDefinition ) + public MutablePortletEntity newPortletEntityInstance( + PortletDefinition portletDefinition) { - return newPortletEntityInstance(portletDefinition, autoGenerateID(portletDefinition)); + return newPortletEntityInstance(portletDefinition, + autoGenerateID(portletDefinition)); } - public MutablePortletEntity newPortletEntityInstance(PortletDefinition portletDefinition, String id) + public MutablePortletEntity newPortletEntityInstance( + PortletDefinition portletDefinition, String id) { PortletEntityImpl portletEntity = new PortletEntityImpl(); portletEntity.setPortletDefinition(portletDefinition); portletEntity.setId(id); return portletEntity; } - - + public void removeFromCache(PortletEntity entity) { if (windowAccessor != null) @@ -349,7 +380,8 @@ } } - public void removePortletEntities( PortletDefinition portletDefinition ) throws PortletEntityNotDeletedException + public void removePortletEntities(PortletDefinition portletDefinition) + throws PortletEntityNotDeletedException { Iterator entities = getPortletEntities(portletDefinition).iterator(); while (entities.hasNext()) @@ -360,21 +392,25 @@ } - public void removePortletEntity( PortletEntity portletEntity ) throws PortletEntityNotDeletedException + public void removePortletEntity(PortletEntity portletEntity) + throws PortletEntityNotDeletedException { - PreferenceSet prefsSet = portletEntity.getPreferenceSet(); + PreferenceSet prefsSet = portletEntity.getPreferenceSet(); getPersistenceBrokerTemplate().delete(portletEntity); - - if(prefsSet instanceof PrefsPreferenceSetImpl) + + if (prefsSet instanceof PrefsPreferenceSetImpl) { try { - ((PrefsPreferenceSetImpl)prefsSet).clear(); + ((PrefsPreferenceSetImpl) prefsSet).clear(); removeFromCache(portletEntity); } catch (BackingStoreException e) { - throw new PortletEntityNotDeletedException("Failed to remove preferences for portlet entity "+portletEntity.getId()+". "+e.getMessage(), e); + throw new PortletEntityNotDeletedException( + "Failed to remove preferences for portlet entity " + + portletEntity.getId() + ". " + + e.getMessage(), e); } } } @@ -383,35 +419,39 @@ *

      * updatePortletEntity *

      - * - * Updates portlet definition associated with the portlet - * entity to match the fragment configuration - * + * + * Updates portlet definition associated with the portlet entity to match + * the fragment configuration + * * @param portletEntity - * @param fragment - * @throws PortletEntityNotStoredException + * @param fragment + * @throws PortletEntityNotStoredException */ - public void updatePortletEntity(PortletEntity portletEntity, ContentFragment fragment) throws PortletEntityNotStoredException + public void updatePortletEntity(PortletEntity portletEntity, + ContentFragment fragment) throws PortletEntityNotStoredException { // validate portlet entity id - if (!fragment.getId().equals(portletEntity.getId().toString())) - { - throw new PortletEntityNotStoredException("Fragment and PortletEntity ids do not match, update skipped: " + fragment.getId() + " != " + portletEntity.getId() ); - } + if (!fragment.getId().equals(portletEntity.getId().toString())) { throw new PortletEntityNotStoredException( + "Fragment and PortletEntity ids do not match, update skipped: " + + fragment.getId() + " != " + portletEntity.getId()); } // update portlet definition from fragment - PortletDefinition pd = registry.getPortletDefinitionByUniqueName(fragment.getName()); + PortletDefinition pd = registry + .getPortletDefinitionByUniqueName(fragment.getName()); if (pd != null) { - ((PortletEntityImpl)portletEntity).setPortletDefinition(pd); + ((PortletEntityImpl) portletEntity).setPortletDefinition(pd); } else { - throw new PortletEntityNotStoredException("Fragment PortletDefinition not found: " + fragment.getName() ); + throw new PortletEntityNotStoredException( + "Fragment PortletDefinition not found: " + + fragment.getName()); } } - public void storePortletEntity( PortletEntity portletEntity ) throws PortletEntityNotStoredException + public void storePortletEntity(PortletEntity portletEntity) + throws PortletEntityNotStoredException { try { @@ -433,35 +473,39 @@ * @param prefSet * @throws IOException */ - public void storePreferenceSet( PreferenceSet prefSet, PortletEntity entity ) throws IOException + public void storePreferenceSet(PreferenceSet prefSet, PortletEntity entity) + throws IOException { try - { + { getPersistenceBrokerTemplate().store(entity); if (prefSet != null && prefSet instanceof PrefsPreferenceSetImpl) { - ((PrefsPreferenceSetImpl)prefSet).flush(); - } + ((PrefsPreferenceSetImpl) prefSet).flush(); + } } catch (Exception e) { String msg = "Failed to store portlet entity:" + e.toString(); IOException ioe = new IOException(msg); - ioe.initCause(e); + ioe.initCause(e); throw ioe; } } - + protected String autoGenerateID(PortletDefinition pd) { - String appName = ((MutablePortletApplication)pd.getPortletApplicationDefinition()).getName(); + String appName = ((MutablePortletApplication) pd + .getPortletApplicationDefinition()).getName(); String portletName = pd.getName(); - return appName+"::"+portletName+"::"+new UID().toString(); + return appName + "::" + portletName + "::" + new UID().toString(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.components.portletentity.PortletEntityAccessComponent#isMergeSharedPreferences() */ public boolean isMergeSharedPreferences() @@ -469,5 +513,4 @@ return this.mergeSharedPreferences; } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletentity/PortletEntityImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletentity/PortletEntityImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletentity/PortletEntityImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -68,29 +68,46 @@ * @author Scott T. Weaver * @version $Id: PortletEntityImpl.java,v 1.9 2005/04/29 13:59:08 weaver Exp $ */ -public class PortletEntityImpl implements MutablePortletEntity, PrincipalAware, RemovalAware, RenderTrackable -{ +public class PortletEntityImpl implements MutablePortletEntity, PrincipalAware, + RemovalAware, RenderTrackable +{ + private long oid; + private JetspeedObjectID id; - protected static PortletEntityAccessComponent pac; + + protected static PortletEntityAccessComponent pac; + protected static PortletRegistry registry; + protected static RequestContextComponent rcc; + protected static PageManager pm; - + protected PrefsPreferenceSetImpl pagePreferenceSet; + protected Map perPrincipalPrefs = new HashMap(); + protected Map originalValues; + private PortletApplicationEntity applicationEntity = null; + private PortletWindowList portletWindows = new PortletWindowListImpl(); - private PortletDefinitionComposite portletDefinition = null; + + private PortletDefinitionComposite portletDefinition = null; + protected String portletName; + protected String appName; + private boolean dirty = false; + private Fragment fragment; - + protected transient int timeoutCount = 0; + protected transient long expiration = 0; - + public PortletEntityImpl(Fragment fragment) { setFragment(fragment); @@ -102,6 +119,7 @@ } public static final String NO_PRINCIPAL = "no-principal"; + public static final String ENTITY_DEFAULT_PRINCIPAL = "entity-default"; public ObjectID getId() @@ -114,7 +132,7 @@ return oid; } - public void setId( String id ) + public void setId(String id) { this.id = JetspeedObjectID.createFromString(id); } @@ -143,14 +161,17 @@ public PreferenceSet getPreferenceSet(Principal principal) { - PrefsPreferenceSetImpl preferenceSet = (PrefsPreferenceSetImpl) perPrincipalPrefs.get(principal); + PrefsPreferenceSetImpl preferenceSet = (PrefsPreferenceSetImpl) perPrincipalPrefs + .get(principal); try { if (preferenceSet == null || !dirty) { - String prefNodePath = MutablePortletEntity.PORTLET_ENTITY_ROOT + "/" + getId() +"/"+ principal.getName() +"/" + String prefNodePath = MutablePortletEntity.PORTLET_ENTITY_ROOT + + "/" + getId() + "/" + principal.getName() + "/" + PrefsPreference.PORTLET_PREFERENCES_ROOT; - Preferences prefNode = Preferences.userRoot().node(prefNodePath); + Preferences prefNode = Preferences.userRoot() + .node(prefNodePath); preferenceSet = new PrefsPreferenceSetImpl(prefNode); perPrincipalPrefs.put(principal, preferenceSet); if (pac.isMergeSharedPreferences()) @@ -170,34 +191,39 @@ } return preferenceSet; } - + private PreferenceSet getPreferenceSetFromPage() { PrefsPreferenceSetImpl preferenceSet = this.pagePreferenceSet; - + try { if (preferenceSet == null || !dirty) { - String prefNodePath = MutablePortletEntity.PORTLET_ENTITY_ROOT + "/" + - getId() +"/"+ PrefsPreference.PORTLET_PREFERENCES_ROOT; + String prefNodePath = MutablePortletEntity.PORTLET_ENTITY_ROOT + + "/" + getId() + "/" + + PrefsPreference.PORTLET_PREFERENCES_ROOT; - Preferences prefNode = Preferences.systemRoot().node(prefNodePath); + Preferences prefNode = Preferences.systemRoot().node( + prefNodePath); preferenceSet = new PrefsPreferenceSetImpl(prefNode); this.pagePreferenceSet = preferenceSet; - + List fragmentPreferences = this.fragment.getPreferences(); - + if (fragmentPreferences != null) { - for (Iterator it = fragmentPreferences.iterator(); it.hasNext(); ) + for (Iterator it = fragmentPreferences.iterator(); it + .hasNext();) { - FragmentPreference preference = (FragmentPreference) it.next(); + FragmentPreference preference = (FragmentPreference) it + .next(); List preferenceValues = preference.getValueList(); - preferenceSet.add(preference.getName(), preferenceValues); + preferenceSet.add(preference.getName(), + preferenceValues); } } - + backupValues(preferenceSet); dirty = true; } @@ -211,30 +237,30 @@ } return preferenceSet; } - + private void mergePreferencesSet(PrefsPreferenceSetImpl userPrefSet) - throws BackingStoreException + throws BackingStoreException { - String sharedNodePath = MutablePortletEntity.PORTLET_ENTITY_ROOT + "/" + - getId() +"/"+ NO_PRINCIPAL +"/" + - PrefsPreference.PORTLET_PREFERENCES_ROOT; - Preferences sharedNode = Preferences.userRoot().node(sharedNodePath); - if (sharedNode == null) - return; - PrefsPreferenceSetImpl sharedSet = new PrefsPreferenceSetImpl(sharedNode); - if (sharedSet.size() == 0) - return; + String sharedNodePath = MutablePortletEntity.PORTLET_ENTITY_ROOT + "/" + + getId() + "/" + NO_PRINCIPAL + "/" + + PrefsPreference.PORTLET_PREFERENCES_ROOT; + Preferences sharedNode = Preferences.userRoot().node(sharedNodePath); + if (sharedNode == null) return; + PrefsPreferenceSetImpl sharedSet = new PrefsPreferenceSetImpl( + sharedNode); + if (sharedSet.size() == 0) return; Set names = userPrefSet.getNames(); Iterator sharedPrefs = sharedSet.iterator(); int index = 0; while (sharedPrefs.hasNext()) { PrefsPreference sharedPref = (PrefsPreference) sharedPrefs.next(); -// this seems limiting, removing if (names.contains(sharedPref.getName())) + // this seems limiting, removing if + // (names.contains(sharedPref.getName())) List prefs = Arrays.asList(sharedPref.getValueArray()); userPrefSet.add(sharedPref.getName(), prefs); index++; - } + } } /** @@ -242,9 +268,9 @@ * backupValues *

      * - * + * */ - protected void backupValues( PreferenceSet preferenceSet ) + protected void backupValues(PreferenceSet preferenceSet) { originalValues = new HashMap(); Iterator itr = preferenceSet.iterator(); @@ -263,25 +289,27 @@ public PortletDefinition getPortletDefinition() { // there are cases when jetspeed gets initialized before - // all of the portlet web apps have. In this event, premature + // all of the portlet web apps have. In this event, premature // access to the portal would cause portlet entities to be cached - // with their associated window without there corresponding PortletDefinition + // with their associated window without there corresponding + // PortletDefinition // (becuase the PortletApplication has yet to be registered). - if(this.portletDefinition == null) + if (this.portletDefinition == null) { - PortletDefinition pd = registry.getPortletDefinitionByIdentifier(getPortletUniqueName()); - if ( pd != null ) + PortletDefinition pd = registry + .getPortletDefinitionByIdentifier(getPortletUniqueName()); + if (pd != null) { - // only store a really found PortletDefinition - // to prevent an IllegalArgumentException to be thrown - setPortletDefinition(pd); + // only store a really found PortletDefinition + // to prevent an IllegalArgumentException to be thrown + setPortletDefinition(pd); } else { return null; } - } - + } + // Wrap the portlet defintion every request thread // JS2-852: don't use thread local RequestContext rc = rcc.getRequestContext(); @@ -289,16 +317,17 @@ PortletDefinition fpd = null; if (rc != null) { - fpd= (PortletDefinition)rc.getAttribute(entityFragmentKey); + fpd = (PortletDefinition) rc.getAttribute(entityFragmentKey); } if (fpd == null) { - fpd = new FragmentPortletDefinition(this.portletDefinition, fragment); + fpd = new FragmentPortletDefinition(this.portletDefinition, + fragment); if (rc != null) { rc.setAttribute(entityFragmentKey, fpd); } - } + } return fpd; } @@ -317,7 +346,7 @@ *

      * store *

      - * + * */ public void store() throws IOException { @@ -331,16 +360,15 @@ store(currentUser); } } - + public void store(Principal principal) throws IOException { - if (pac == null) - { - throw new IllegalStateException("You must call PortletEntityImpl.setPorteltEntityDao() before " - + "invoking PortletEntityImpl.store()."); - } + if (pac == null) { throw new IllegalStateException( + "You must call PortletEntityImpl.setPorteltEntityDao() before " + + "invoking PortletEntityImpl.store()."); } - PreferenceSet preferenceSet = (PreferenceSet)perPrincipalPrefs.get(principal); + PreferenceSet preferenceSet = (PreferenceSet) perPrincipalPrefs + .get(principal); pac.storePreferenceSet(preferenceSet, this); dirty = false; if (preferenceSet != null) @@ -348,37 +376,35 @@ backupValues(preferenceSet); } } - + private void storeToPage() throws IOException { - if (pm == null) - { - throw new IllegalStateException("You must set pageManager before " - + "invoking PortletEntityImpl.store()."); - } - + if (pm == null) { throw new IllegalStateException( + "You must set pageManager before " + + "invoking PortletEntityImpl.store()."); } + PreferenceSet preferenceSet = this.pagePreferenceSet; List preferences = new ArrayList(); - - for (Iterator it = preferenceSet.iterator(); it.hasNext(); ) + + for (Iterator it = preferenceSet.iterator(); it.hasNext();) { Preference pref = (Preference) it.next(); - + FragmentPreference preference = pm.newFragmentPreference(); preference.setName(pref.getName()); List preferenceValues = new ArrayList(); - - for (Iterator iterVals = pref.getValues(); iterVals.hasNext(); ) + + for (Iterator iterVals = pref.getValues(); iterVals.hasNext();) { preferenceValues.add(iterVals.next()); } - + preference.setValueList(preferenceValues); preferences.add(preference); } - + this.fragment.setPreferences(preferences); - + try { pm.updatePage(rcc.getRequestContext().getPage()); @@ -386,7 +412,7 @@ catch (Exception e) { } - + dirty = false; if (preferenceSet != null) { @@ -399,12 +425,13 @@ *

      * reset *

      - * + * */ public void reset() throws IOException { - PrefsPreferenceSetImpl preferenceSet = (PrefsPreferenceSetImpl) perPrincipalPrefs.get(getPrincipal()); + PrefsPreferenceSetImpl preferenceSet = (PrefsPreferenceSetImpl) perPrincipalPrefs + .get(getPrincipal()); try { if (originalValues != null && preferenceSet != null) @@ -416,7 +443,8 @@ PrefsPreference pref = (PrefsPreference) prefs.next(); if (originalValues.containsKey(pref.getName())) { - pref.setValues((String[]) originalValues.get(pref.getName())); + pref.setValues((String[]) originalValues.get(pref + .getName())); } else { @@ -431,7 +459,8 @@ String key = (String) keys.next(); if (preferenceSet.get(key) == null) { - preferenceSet.add(key, Arrays.asList((String[]) originalValues.get(key))); + preferenceSet.add(key, Arrays + .asList((String[]) originalValues.get(key))); } } } @@ -455,7 +484,7 @@ return toString(0); } - public String toString( int indent ) + public String toString(int indent) { StringBuffer buffer = new StringBuffer(1000); StringUtils.newLine(buffer, indent); @@ -469,7 +498,7 @@ buffer.append("'"); StringUtils.newLine(buffer, indent); buffer.append("definition-id='"); - if(portletDefinition != null) + if (portletDefinition != null) { buffer.append(portletDefinition.getId().toString()); } @@ -480,7 +509,7 @@ buffer.append("'"); StringUtils.newLine(buffer, indent); - //buffer.append(((PreferenceSetImpl)preferences).toString(indent)); + // buffer.append(((PreferenceSetImpl)preferences).toString(indent)); StringUtils.newLine(buffer, indent); buffer.append("}"); @@ -490,7 +519,7 @@ /** * @see org.apache.pluto.om.entity.PortletEntity#getDescription(java.util.Locale) */ - public Description getDescription( Locale arg0 ) + public Description getDescription(Locale arg0) { return portletDefinition.getDescription(arg0); } @@ -501,25 +530,28 @@ *

      * * @param composite - * + * */ - public void setPortletDefinition( PortletDefinition composite ) + public void setPortletDefinition(PortletDefinition composite) { - if(composite != null) + if (composite != null) { portletDefinition = (PortletDefinitionComposite) composite; - // if the portletDefinition is modified, clear threadlocal fragmentPortletDefinition cache + // if the portletDefinition is modified, clear threadlocal + // fragmentPortletDefinition cache RequestContext rc = rcc.getRequestContext(); if (rc != null) { rc.getRequest().removeAttribute(getEntityFragmentKey()); } - this.appName = ((MutablePortletApplication)portletDefinition.getPortletApplicationDefinition()).getName(); + this.appName = ((MutablePortletApplication) portletDefinition + .getPortletApplicationDefinition()).getName(); this.portletName = portletDefinition.getName(); } else { - throw new IllegalArgumentException("Cannot pass a null PortletDefinition to a PortletEntity."); + throw new IllegalArgumentException( + "Cannot pass a null PortletDefinition to a PortletEntity."); } } @@ -528,15 +560,9 @@ */ public Principal getPrincipal() { - if (rcc == null) - { - return new PortletEntityUserPrincipal(NO_PRINCIPAL); - } + if (rcc == null) { return new PortletEntityUserPrincipal(NO_PRINCIPAL); } RequestContext rc = rcc.getRequestContext(); - if (rc == null) - { - return new PortletEntityUserPrincipal(NO_PRINCIPAL); - } + if (rc == null) { return new PortletEntityUserPrincipal(NO_PRINCIPAL); } Principal principal = rc.getUserPrincipal(); if (principal == null) { @@ -547,9 +573,10 @@ class PortletEntityUserPrincipal implements Principal { + String name; - protected PortletEntityUserPrincipal( String name ) + protected PortletEntityUserPrincipal(String name) { this.name = name; } @@ -576,12 +603,13 @@ * @param obj * @return */ - public boolean equals( Object obj ) + public boolean equals(Object obj) { if (obj != null && obj instanceof Principal) { Principal p = (Principal) obj; - return name != null && p.getName() != null && name.equals(p.getName()); + return name != null && p.getName() != null + && name.equals(p.getName()); } else { @@ -601,7 +629,7 @@ { if (name != null) { - return (getClass().getName()+ ":" + name).hashCode(); + return (getClass().getName() + ":" + name).hashCode(); } else { @@ -622,53 +650,58 @@ return name; } } + /** *

      * postRemoval *

      - * + * * @see org.apache.jetspeed.components.persistence.store.RemovalAware#postRemoval(org.apache.jetspeed.components.persistence.store.PersistenceStore) * @param store - * @throws {@link org.apache.jetspeed.persistence.store.PersistenceStoreRuntimeExcpetion} - * if the removal of the {@link java.util.prefs.Preference} related to this entity fails + * @throws + * {@link org.apache.jetspeed.persistence.store.PersistenceStoreRuntimeExcpetion} + * if the removal of the {@link java.util.prefs.Preference} + * related to this entity fails */ - public void postRemoval( PersistenceStore store ) + public void postRemoval(PersistenceStore store) { - } + /** *

      * preRemoval *

      - * not implemented. - * + * not implemented. + * * @see org.apache.jetspeed.components.persistence.store.RemovalAware#preRemoval(org.apache.jetspeed.components.persistence.store.PersistenceStore) * @param store */ - public void preRemoval( PersistenceStore store ) + public void preRemoval(PersistenceStore store) { - String rootForEntity = MutablePortletEntity.PORTLET_ENTITY_ROOT + "/" + getId(); + String rootForEntity = MutablePortletEntity.PORTLET_ENTITY_ROOT + "/" + + getId(); try { - if(Preferences.userRoot().nodeExists(rootForEntity)) + if (Preferences.userRoot().nodeExists(rootForEntity)) { Preferences.userRoot().node(rootForEntity).removeNode(); } } catch (BackingStoreException e) - { + { throw new PersistenceStoreRuntimeExcpetion(e.toString(), e); - } + } } + public String getPortletUniqueName() { - if(this.appName != null && this.portletName != null) + if (this.appName != null && this.portletName != null) { - return this.appName+"::"+this.portletName; + return this.appName + "::" + this.portletName; } - else if(fragment != null) + else if (fragment != null) { return fragment.getName(); } @@ -681,7 +714,8 @@ public void setFragment(Fragment fragment) { this.fragment = fragment; - // if the fragment is set, clear threadlocal fragmentPortletDefinition cache + // if the fragment is set, clear threadlocal fragmentPortletDefinition + // cache RequestContext rc = rcc.getRequestContext(); if (rc != null) { @@ -693,27 +727,27 @@ { return timeoutCount; } - + public synchronized void incrementRenderTimeoutCount() { timeoutCount++; } - + public synchronized void setExpiration(long expiration) { this.expiration = expiration; } - + public long getExpiration() { return this.expiration; } - + public void success() { timeoutCount = 0; } - + public void setRenderTimeoutCount(int timeoutCount) { this.timeoutCount = timeoutCount; @@ -722,40 +756,44 @@ private boolean isEditDefaultsMode() { boolean editDefaultsMode = false; - + PortletWindow curWindow = null; - + if (this.portletWindows != null) { try { - curWindow = (PortletWindow) this.portletWindows.iterator().next(); + curWindow = (PortletWindow) this.portletWindows.iterator() + .next(); } catch (Exception e) { } } - + if (rcc != null) { RequestContext context = rcc.getRequestContext(); - + try { - PortletMode curMode = context.getPortalURL().getNavigationalState().getMode(curWindow); - editDefaultsMode = (JetspeedActions.EDIT_DEFAULTS_MODE.equals(curMode)); + PortletMode curMode = context.getPortalURL() + .getNavigationalState().getMode(curWindow); + editDefaultsMode = (JetspeedActions.EDIT_DEFAULTS_MODE + .equals(curMode)); } catch (Exception e) { } - } + } return editDefaultsMode; } - + protected String getEntityFragmentKey() { - String entityId = (this.getId() == null) ? "-unknown-entity" : this.getId().toString(); - return "org.apache.jetspeed" + entityId ; + String entityId = (this.getId() == null) ? "-unknown-entity" : this + .getId().toString(); + return "org.apache.jetspeed" + entityId; } - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/MutablePortletApplicationProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/MutablePortletApplicationProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/MutablePortletApplicationProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,12 +23,16 @@ import org.apache.jetspeed.om.common.portlet.MutablePortletApplication; -public class MutablePortletApplicationProxy implements InvocationHandler, PortletApplicationProxy +public class MutablePortletApplicationProxy implements InvocationHandler, + PortletApplicationProxy { + private MutablePortletApplication app = null; + private static PortletRegistry registry; + private String name; - + public MutablePortletApplicationProxy(MutablePortletApplication app) { this.app = app; @@ -39,12 +43,12 @@ { registry = r; } - + public static MutablePortletApplication createProxy( MutablePortletApplication app) { Class[] proxyInterfaces = new Class[] - { MutablePortletApplication.class, PortletApplicationProxy.class}; + {MutablePortletApplication.class, PortletApplicationProxy.class}; MutablePortletApplication proxy = (MutablePortletApplication) Proxy .newProxyInstance(MutablePortletApplication.class .getClassLoader(), proxyInterfaces, @@ -56,21 +60,21 @@ { this.app = null; } - + public void setRealApplication(MutablePortletApplication app) { this.app = app; } - + public MutablePortletApplication getRealApplication() { return app; } - + public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { - try + try { if (m.getName().equals("getRealApplication")) { @@ -78,7 +82,7 @@ } else if (m.getName().equals("setRealApplication")) { - setRealApplication((MutablePortletApplication)args[0]); + setRealApplication((MutablePortletApplication) args[0]); return null; } else @@ -89,8 +93,8 @@ } return m.invoke(app, args); } - } - catch (InvocationTargetException e) + } + catch (InvocationTargetException e) { throw e.getTargetException(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PersistenceBrokerPortletRegistry.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PersistenceBrokerPortletRegistry.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PersistenceBrokerPortletRegistry.java 2008-05-16 01:54:54 UTC (rev 940) @@ -54,13 +54,15 @@ *

      * * @author Scott T. Weaver - * @version $Id: PersistenceBrokerPortletRegistry.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: PersistenceBrokerPortletRegistry.java 516448 2007-03-09 + * 16:25:47Z ate $ + * */ -public class PersistenceBrokerPortletRegistry - extends InitablePersistenceBrokerDaoSupport - implements PortletRegistry, JetspeedCacheEventListener +public class PersistenceBrokerPortletRegistry extends + InitablePersistenceBrokerDaoSupport implements PortletRegistry, + JetspeedCacheEventListener { + /** * The separator used to create a unique portlet name as * {portletApplication}::{portlet} @@ -68,24 +70,32 @@ static final String PORTLET_UNIQUE_NAME_SEPARATOR = "::"; private JetspeedCache applicationOidCache = null; + private JetspeedCache portletOidCache = null; + private JetspeedCache applicationNameCache = null; + private JetspeedCache portletNameCache = null; - private Map nameCache = new HashMap(); // work in progress (switch to JetspeedCache) + + private Map nameCache = new HashMap(); // work in progress (switch to + + // JetspeedCache) + private List listeners = new ArrayList(); - + // for testing purposes only: no need for the portletFactory then public PersistenceBrokerPortletRegistry(String repositoryPath) { this(repositoryPath, null, null, null, null, null); } - + /** - * + * */ - public PersistenceBrokerPortletRegistry(String repositoryPath, PortletFactory portletFactory, - JetspeedCache applicationOidCache, JetspeedCache portletOidCache, - JetspeedCache applicationNameCache, JetspeedCache portletNameCache) + public PersistenceBrokerPortletRegistry(String repositoryPath, + PortletFactory portletFactory, JetspeedCache applicationOidCache, + JetspeedCache portletOidCache, JetspeedCache applicationNameCache, + JetspeedCache portletNameCache) { super(repositoryPath); PortletDefinitionImpl.setPortletRegistry(this); @@ -95,14 +105,17 @@ this.applicationNameCache = applicationNameCache; this.portletNameCache = portletNameCache; MutablePortletApplicationProxy.setRegistry(this); - RegistryApplicationCache.cacheInit(this, applicationOidCache, applicationNameCache, listeners); - RegistryPortletCache.cacheInit(this, portletOidCache, portletNameCache, listeners); + RegistryApplicationCache.cacheInit(this, applicationOidCache, + applicationNameCache, listeners); + RegistryPortletCache.cacheInit(this, portletOidCache, portletNameCache, + listeners); this.applicationNameCache.addEventListener(this, false); - this.portletNameCache.addEventListener(this, false); + this.portletNameCache.addEventListener(this, false); } - - public Language createLanguage( Locale locale, String title, String shortTitle, String description, - Collection keywords ) throws RegistryException + + public Language createLanguage(Locale locale, String title, + String shortTitle, String description, Collection keywords) + throws RegistryException { try { @@ -118,7 +131,7 @@ throw new RegistryException("Unable to create language object."); } } - + public Collection getAllPortletDefinitions() { Criteria c = new Criteria(); @@ -128,12 +141,14 @@ return list; } - public MutablePortletApplication getPortletApplication( ObjectID id ) + public MutablePortletApplication getPortletApplication(ObjectID id) { Criteria c = new Criteria(); c.addEqualTo("id", new Long(id.toString())); - MutablePortletApplication app = (MutablePortletApplication) getPersistenceBrokerTemplate().getObjectByQuery( - QueryFactory.newQuery(PortletApplicationDefinitionImpl.class, c)); + MutablePortletApplication app = (MutablePortletApplication) getPersistenceBrokerTemplate() + .getObjectByQuery( + QueryFactory.newQuery( + PortletApplicationDefinitionImpl.class, c)); postLoad(app); return app; } @@ -142,18 +157,23 @@ { Criteria c = new Criteria(); c.addEqualTo("name", name); - MutablePortletApplication app = (MutablePortletApplication) getPersistenceBrokerTemplate().getObjectByQuery( - QueryFactory.newQuery(PortletApplicationDefinitionImpl.class, c)); + MutablePortletApplication app = (MutablePortletApplication) getPersistenceBrokerTemplate() + .getObjectByQuery( + QueryFactory.newQuery( + PortletApplicationDefinitionImpl.class, c)); postLoad(app); return app; } - public MutablePortletApplication getPortletApplicationByIdentifier( String identifier ) + public MutablePortletApplication getPortletApplicationByIdentifier( + String identifier) { Criteria c = new Criteria(); c.addEqualTo("applicationIdentifier", identifier); - MutablePortletApplication app = (MutablePortletApplication) getPersistenceBrokerTemplate().getObjectByQuery( - QueryFactory.newQuery(PortletApplicationDefinitionImpl.class, c)); + MutablePortletApplication app = (MutablePortletApplication) getPersistenceBrokerTemplate() + .getObjectByQuery( + QueryFactory.newQuery( + PortletApplicationDefinitionImpl.class, c)); postLoad(app); return app; } @@ -162,17 +182,20 @@ { Criteria c = new Criteria(); Collection list = getPersistenceBrokerTemplate().getCollectionByQuery( - QueryFactory.newQuery(PortletApplicationDefinitionImpl.class, c)); + QueryFactory + .newQuery(PortletApplicationDefinitionImpl.class, c)); postLoadColl(list); return list; } - public PortletDefinitionComposite getPortletDefinitionByIdentifier( String identifier ) + public PortletDefinitionComposite getPortletDefinitionByIdentifier( + String identifier) { Criteria c = new Criteria(); c.addEqualTo("portletIdentifier", identifier); - PortletDefinitionComposite def = (PortletDefinitionComposite) getPersistenceBrokerTemplate().getObjectByQuery( - QueryFactory.newQuery(PortletDefinitionImpl.class, c)); + PortletDefinitionComposite def = (PortletDefinitionComposite) getPersistenceBrokerTemplate() + .getObjectByQuery( + QueryFactory.newQuery(PortletDefinitionImpl.class, c)); if (def != null && def.getPortletApplicationDefinition() == null) { final String msg = "getPortletDefinitionByIdentifier() returned a PortletDefinition that has no parent PortletApplication."; @@ -183,7 +206,8 @@ return def; } - public PortletDefinitionComposite getPortletDefinitionByUniqueName( String name ) + public PortletDefinitionComposite getPortletDefinitionByUniqueName( + String name) { String appName = PortletRegistryHelper.parseAppName(name); String portletName = PortletRegistryHelper.parsePortletName(name); @@ -192,8 +216,9 @@ c.addEqualTo("app.name", appName); c.addEqualTo("name", portletName); - PortletDefinitionComposite def = (PortletDefinitionComposite) getPersistenceBrokerTemplate().getObjectByQuery( - QueryFactory.newQuery(PortletDefinitionImpl.class, c)); + PortletDefinitionComposite def = (PortletDefinitionComposite) getPersistenceBrokerTemplate() + .getObjectByQuery( + QueryFactory.newQuery(PortletDefinitionImpl.class, c)); if (def != null && def.getPortletApplicationDefinition() == null) { final String msg = "getPortletDefinitionByIdentifier() returned a PortletDefinition that has no parent PortletApplication."; @@ -204,59 +229,66 @@ return def; } - public boolean portletApplicationExists( String appIdentity ) + public boolean portletApplicationExists(String appIdentity) { return getPortletApplicationByIdentifier(appIdentity) != null; } - - public boolean namedPortletApplicationExists( String appName ) + + public boolean namedPortletApplicationExists(String appName) { return getPortletApplication(appName) != null; } - public boolean portletDefinitionExists( String portletName, MutablePortletApplication app ) + public boolean portletDefinitionExists(String portletName, + MutablePortletApplication app) { - return getPortletDefinitionByUniqueName(app.getName() + "::" + portletName) != null; + return getPortletDefinitionByUniqueName(app.getName() + "::" + + portletName) != null; } - public boolean portletDefinitionExists( String portletIdentity ) + public boolean portletDefinitionExists(String portletIdentity) { return getPortletDefinitionByIdentifier(portletIdentity) != null; } - public void registerPortletApplication( PortletApplicationDefinition newApp ) throws RegistryException + public void registerPortletApplication(PortletApplicationDefinition newApp) + throws RegistryException { getPersistenceBrokerTemplate().store(newApp); } - public void removeApplication( PortletApplicationDefinition app ) throws RegistryException + public void removeApplication(PortletApplicationDefinition app) + throws RegistryException { getPersistenceBrokerTemplate().delete(app); - - String appNodePath = MutablePortletApplication.PREFS_ROOT + "/" +((MutablePortletApplication)app).getName(); + + String appNodePath = MutablePortletApplication.PREFS_ROOT + "/" + + ((MutablePortletApplication) app).getName(); try { - if(Preferences.systemRoot().nodeExists(appNodePath)) - { + if (Preferences.systemRoot().nodeExists(appNodePath)) + { Preferences node = Preferences.systemRoot().node(appNodePath); - // log.info("Removing Application preference node "+node.absolutePath()); + // log.info("Removing Application preference node + // "+node.absolutePath()); node.removeNode(); } } catch (BackingStoreException e) { - throw new RegistryException(e.toString(), e); + throw new RegistryException(e.toString(), e); } } - public void updatePortletApplication( PortletApplicationDefinition app ) throws RegistryException + public void updatePortletApplication(PortletApplicationDefinition app) + throws RegistryException { getPersistenceBrokerTemplate().store(app); } - private void postLoad( Object obj ) + private void postLoad(Object obj) { if (obj != null) { @@ -275,7 +307,7 @@ } - private void postLoadColl( Collection coll ) + private void postLoadColl(Collection coll) { if (coll != null && !coll.isEmpty()) @@ -310,7 +342,8 @@ } - public void savePortletDefinition( PortletDefinition portlet ) throws FailedToStorePortletDefinitionException + public void savePortletDefinition(PortletDefinition portlet) + throws FailedToStorePortletDefinitionException { try { @@ -318,8 +351,8 @@ } catch (DataAccessException e) { - - throw new FailedToStorePortletDefinitionException(portlet, e); + + throw new FailedToStorePortletDefinitionException(portlet, e); } } @@ -328,65 +361,77 @@ { Criteria c = new Criteria(); c.addEqualTo("id", new Long(id.toString())); - PortletDefinitionComposite portlet = (PortletDefinitionComposite) getPersistenceBrokerTemplate().getObjectByQuery( - QueryFactory.newQuery(PortletDefinitionImpl.class, c)); - + PortletDefinitionComposite portlet = (PortletDefinitionComposite) getPersistenceBrokerTemplate() + .getObjectByQuery( + QueryFactory.newQuery(PortletDefinitionImpl.class, c)); + postLoad(portlet); return portlet; } - - public void notifyElementAdded(JetspeedCache cache, boolean local, Object key, Object element) + + public void notifyElementAdded(JetspeedCache cache, boolean local, + Object key, Object element) { } - public void notifyElementChanged(JetspeedCache cache, boolean local, Object key, Object element) + public void notifyElementChanged(JetspeedCache cache, boolean local, + Object key, Object element) { } - public void notifyElementEvicted(JetspeedCache cache, boolean local, Object key, Object element) + public void notifyElementEvicted(JetspeedCache cache, boolean local, + Object key, Object element) { - //notifyElementRemoved(cache,local,key,element); + // notifyElementRemoved(cache,local,key,element); } - public void notifyElementExpired(JetspeedCache cache, boolean local, Object key, Object element) + public void notifyElementExpired(JetspeedCache cache, boolean local, + Object key, Object element) { - //notifyElementRemoved(cache,local,key,element); + // notifyElementRemoved(cache,local,key,element); } - public void notifyElementRemoved(JetspeedCache cache, boolean local, Object key, Object element) - { - + public void notifyElementRemoved(JetspeedCache cache, boolean local, + Object key, Object element) + { + if (cache == this.portletNameCache) { - //System.out.println("%%% portlet remote removed " + key); - RegistryPortletCache.cacheRemoveQuiet((String)key, (RegistryCacheObjectWrapper)element); - PortletDefinitionComposite pd = this.getPortletDefinitionByUniqueName((String)key); + // System.out.println("%%% portlet remote removed " + key); + RegistryPortletCache.cacheRemoveQuiet((String) key, + (RegistryCacheObjectWrapper) element); + PortletDefinitionComposite pd = this + .getPortletDefinitionByUniqueName((String) key); if (listeners != null) { - for (int ix=0; ix < listeners.size(); ix++) + for (int ix = 0; ix < listeners.size(); ix++) { - RegistryEventListener listener = (RegistryEventListener)listeners.get(ix); + RegistryEventListener listener = (RegistryEventListener) listeners + .get(ix); listener.portletRemoved(pd); - } - } + } + } } else { - //System.out.println("%%% PA remote removed " + key); - RegistryApplicationCache.cacheRemoveQuiet((String) key, (RegistryCacheObjectWrapper)element); - MutablePortletApplication pa = this.getPortletApplication((String)key); + // System.out.println("%%% PA remote removed " + key); + RegistryApplicationCache.cacheRemoveQuiet((String) key, + (RegistryCacheObjectWrapper) element); + MutablePortletApplication pa = this + .getPortletApplication((String) key); if (listeners != null) { - for (int ix=0; ix < listeners.size(); ix++) + for (int ix = 0; ix < listeners.size(); ix++) { - RegistryEventListener listener = (RegistryEventListener)listeners.get(ix); + RegistryEventListener listener = (RegistryEventListener) listeners + .get(ix); listener.applicationRemoved(pa); - } + } } - + } } - + public void addRegistryListener(RegistryEventListener listener) { this.listeners.add(listener); @@ -396,5 +441,5 @@ { this.listeners.remove(listener); } - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PortletApplicationProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PortletApplicationProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PortletApplicationProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,6 +20,8 @@ public interface PortletApplicationProxy { + void setRealApplication(MutablePortletApplication app); + MutablePortletApplication getRealApplication(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PortletDefinitionCompositeProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PortletDefinitionCompositeProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PortletDefinitionCompositeProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,10 +25,13 @@ public class PortletDefinitionCompositeProxy implements InvocationHandler { + private PortletDefinitionComposite def = null; + private static PortletRegistry registry; + private String name; - + public PortletDefinitionCompositeProxy(PortletDefinitionComposite def) { this.def = def; @@ -39,12 +42,12 @@ { registry = r; } - + public static PortletDefinitionComposite createProxy( PortletDefinitionComposite def) { Class[] proxyInterfaces = new Class[] - { PortletDefinitionComposite.class}; + {PortletDefinitionComposite.class}; PortletDefinitionComposite proxy = (PortletDefinitionComposite) Proxy .newProxyInstance(PortletDefinitionComposite.class .getClassLoader(), proxyInterfaces, @@ -56,29 +59,29 @@ { this.def = null; } - + protected void setRealDefinition(PortletDefinitionComposite d) { this.def = d; } - + protected PortletDefinitionComposite getRealApplication() { return def; } - + public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { - try + try { if (def == null) { def = registry.getPortletDefinitionByUniqueName(name); } return m.invoke(def, args); - } - catch (InvocationTargetException e) + } + catch (InvocationTargetException e) { throw e.getTargetException(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PortletRegistryHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PortletRegistryHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/PortletRegistryHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,18 +16,23 @@ */ package org.apache.jetspeed.components.portletregistry; - /** - *

      Helper class for the portlet registry.

      + *

      + * Helper class for the portlet registry. + *

      + * * @author David Le Strat */ public class PortletRegistryHelper { /** - *

      Parses the portlet application name from the portlet - * unique name.

      - * @param uniqueName The portlet unique name. + *

      + * Parses the portlet application name from the portlet unique name. + *

      + * + * @param uniqueName + * The portlet unique name. */ public static String parseAppName(String uniqueName) { @@ -36,9 +41,12 @@ } /** - *

      Parses the portlet name from the portlet - * unique name.

      - * @param uniqueName The portlet unique name. + *

      + * Parses the portlet name from the portlet unique name. + *

      + * + * @param uniqueName + * The portlet unique name. */ public static String parsePortletName(String uniqueName) { @@ -47,8 +55,11 @@ } /** - *

      Utility method to split the unique name given the - * PORTLET_UNIQUE_NAME_SEPARATOR.

      + *

      + * Utility method to split the unique name given the + * PORTLET_UNIQUE_NAME_SEPARATOR. + *

      + * * @param uniqueName * @return */ @@ -57,17 +68,15 @@ int split = 0; if (null != uniqueName) { - split = uniqueName.indexOf(PersistenceBrokerPortletRegistry.PORTLET_UNIQUE_NAME_SEPARATOR); + split = uniqueName + .indexOf(PersistenceBrokerPortletRegistry.PORTLET_UNIQUE_NAME_SEPARATOR); } - if (split < 1) - { - throw new IllegalArgumentException( + if (split < 1) { throw new IllegalArgumentException( "The unique portlet name, \"" - + uniqueName - + "\"; is not well formed. No " - + PersistenceBrokerPortletRegistry.PORTLET_UNIQUE_NAME_SEPARATOR - + " delimiter was found."); - } + + uniqueName + + "\"; is not well formed. No " + + PersistenceBrokerPortletRegistry.PORTLET_UNIQUE_NAME_SEPARATOR + + " delimiter was found."); } return split; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/RegistryApplicationCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/RegistryApplicationCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/RegistryApplicationCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,23 +29,28 @@ import org.apache.ojb.broker.cache.ObjectCache; /** - * OJB cache + * OJB cache * * @author dtaylor - * + * */ public class RegistryApplicationCache implements ObjectCache { + private static JetspeedCache oidCache; - private static JetspeedCache nameCache; + + private static JetspeedCache nameCache; + private static PortletRegistry registry; + private static List listeners = null; public RegistryApplicationCache(PersistenceBroker broker, Properties props) { } - - public synchronized static void cacheInit(PortletRegistry r, JetspeedCache o, JetspeedCache n, List l) + + public synchronized static void cacheInit(PortletRegistry r, + JetspeedCache o, JetspeedCache n, List l) { registry = r; oidCache = o; @@ -56,111 +61,120 @@ public Object lookup(Identity oid) { return cacheLookup(oid); - } + } + public synchronized static Object cacheLookup(Identity oid) { CacheElement element = oidCache.get(oid); - if (element != null) - { - return element.getContent(); - } + if (element != null) { return element.getContent(); } return null; - } - - /* (non-Javadoc) - * @see org.apache.ojb.broker.cache.ObjectCache#cache(org.apache.ojb.broker.Identity, java.lang.Object) + } + + /* + * (non-Javadoc) + * + * @see org.apache.ojb.broker.cache.ObjectCache#cache(org.apache.ojb.broker.Identity, + * java.lang.Object) */ public void cache(Identity oid, Object obj) { cacheAdd(oid, obj); } + public synchronized static void cacheAdd(Identity oid, Object obj) - { + { oidCache.remove(oid); CacheElement entry = new EhCacheElementImpl(oid, obj); oidCache.put(entry); - - MutablePortletApplication pa = (MutablePortletApplication)obj; - DistributedCacheObject wrapper = new RegistryCacheObjectWrapper(oid, pa.getName()); + + MutablePortletApplication pa = (MutablePortletApplication) obj; + DistributedCacheObject wrapper = new RegistryCacheObjectWrapper(oid, pa + .getName()); nameCache.remove(pa.getName()); CacheElement nameEntry = nameCache.createElement(pa.getName(), wrapper); nameCache.put(nameEntry); - + if (listeners != null) - { - for (int ix=0; ix < listeners.size(); ix++) + { + for (int ix = 0; ix < listeners.size(); ix++) { - RegistryEventListener listener = (RegistryEventListener)listeners.get(ix); - listener.applicationUpdated((MutablePortletApplication)obj); + RegistryEventListener listener = (RegistryEventListener) listeners + .get(ix); + listener.applicationUpdated((MutablePortletApplication) obj); } } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.ojb.broker.cache.ObjectCache#clear() */ public void clear() { cacheClear(); } + public synchronized static void cacheClear() { oidCache.clear(); nameCache.clear(); } - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.ojb.broker.cache.ObjectCache#remove(org.apache.ojb.broker.Identity) */ public void remove(Identity oid) { cacheRemove(oid); } + /** * cacheRemove - * + * * Remove identified object from object and node caches. - * - * @param oid object identity + * + * @param oid + * object identity */ public synchronized static void cacheRemove(Identity oid) { - MutablePortletApplication pd = (MutablePortletApplication)cacheLookup(oid); - if (pd == null) - return; - + MutablePortletApplication pd = (MutablePortletApplication) cacheLookup(oid); + if (pd == null) return; + oidCache.remove(oid); nameCache.remove(pd.getName()); - + if (listeners != null) { - for (int ix=0; ix < listeners.size(); ix++) + for (int ix = 0; ix < listeners.size(); ix++) { - RegistryEventListener listener = (RegistryEventListener)listeners.get(ix); + RegistryEventListener listener = (RegistryEventListener) listeners + .get(ix); listener.applicationRemoved(pd); - } + } } } - public synchronized static void cacheRemoveQuiet(String key, RegistryCacheObjectWrapper w) + public synchronized static void cacheRemoveQuiet(String key, + RegistryCacheObjectWrapper w) { RegistryCacheObjectWrapper wrapper = w; if (wrapper == null) { - wrapper = (RegistryCacheObjectWrapper)nameCache.get(key); - if (wrapper == null) - return; + wrapper = (RegistryCacheObjectWrapper) nameCache.get(key); + if (wrapper == null) return; } - Identity oid = wrapper.getId(); - - MutablePortletApplication pd = (MutablePortletApplication)cacheLookup(oid); - if (pd == null) - return; - + Identity oid = wrapper.getId(); + + MutablePortletApplication pd = (MutablePortletApplication) cacheLookup(oid); + if (pd == null) return; + oidCache.removeQuiet(oid); - nameCache.removeQuiet(pd.getName()); + nameCache.removeQuiet(pd.getName()); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/RegistryCacheObjectWrapper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/RegistryCacheObjectWrapper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/RegistryCacheObjectWrapper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,40 +21,43 @@ import org.apache.ojb.broker.Identity; /** - * OJB cache + * OJB cache * * @author dtaylor - * + * */ public class RegistryCacheObjectWrapper implements DistributedCacheObject { + /** The serial uid. */ private static final long serialVersionUID = 1853381807991868844L; + Identity id = null; + String key = null;; - public RegistryCacheObjectWrapper(Identity id, String key) { - //System.out.println(this.getClass().getName() + "-" + "NodeCache - fullpath=" + fullpath); + // System.out.println(this.getClass().getName() + "-" + "NodeCache - + // fullpath=" + fullpath); this.key = key; this.id = id; } - public Identity getId() { - //System.out.println(this.getClass().getName() + "-" +"getNode=" + node.getFullPath()); + // System.out.println(this.getClass().getName() + "-" +"getNode=" + + // node.getFullPath()); return id; } public void setIdentity(Identity id) { - // System.out.println(this.getClass().getName() + "-" +"setFullpath=" + node.getFullPath()); + // System.out.println(this.getClass().getName() + "-" +"setFullpath=" + + // node.getFullPath()); this.id = id; } - public boolean equals(Object obj) { if (obj != null && obj instanceof RegistryCacheObjectWrapper) @@ -80,30 +83,30 @@ return key; } - public void notifyChange(int action) { switch (action) { - case CacheElement.ActionAdded: -// System.out.println("CacheObjectAdded =" + this.getKey()); - break; - case CacheElement.ActionChanged: -// System.out.println("CacheObjectChanged =" + this.getKey()); - break; - case CacheElement.ActionRemoved: -// System.out.println("CacheObjectRemoved =" + this.getKey()); - break; - case CacheElement.ActionEvicted: -// System.out.println("CacheObjectEvicted =" + this.getKey()); - break; - case CacheElement.ActionExpired: -// System.out.println("CacheObjectExpired =" + this.getKey()); - break; - default: - System.out.println("CacheObject -UNKOWN OPRERATION =" + this.getKey()); - return; + case CacheElement.ActionAdded: + // System.out.println("CacheObjectAdded =" + this.getKey()); + break; + case CacheElement.ActionChanged: + // System.out.println("CacheObjectChanged =" + this.getKey()); + break; + case CacheElement.ActionRemoved: + // System.out.println("CacheObjectRemoved =" + this.getKey()); + break; + case CacheElement.ActionEvicted: + // System.out.println("CacheObjectEvicted =" + this.getKey()); + break; + case CacheElement.ActionExpired: + // System.out.println("CacheObjectExpired =" + this.getKey()); + break; + default: + System.out.println("CacheObject -UNKOWN OPRERATION =" + + this.getKey()); + return; } return; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/RegistryPortletCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/RegistryPortletCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/portletregistry/RegistryPortletCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,23 +29,28 @@ import org.apache.ojb.broker.cache.ObjectCache; /** - * OJB cache + * OJB cache * * @author dtaylor - * + * */ public class RegistryPortletCache implements ObjectCache { + private static JetspeedCache oidCache; + private static JetspeedCache nameCache; + private static PortletRegistry registry; + private static List listeners = null; - + public RegistryPortletCache(PersistenceBroker broker, Properties props) { } - - public synchronized static void cacheInit(PortletRegistry r, JetspeedCache o, JetspeedCache n, List l) + + public synchronized static void cacheInit(PortletRegistry r, + JetspeedCache o, JetspeedCache n, List l) { registry = r; oidCache = o; @@ -56,110 +61,120 @@ public Object lookup(Identity oid) { return cacheLookup(oid); - } + } + public synchronized static Object cacheLookup(Identity oid) { CacheElement element = oidCache.get(oid); - if (element != null) - { - return element.getContent(); - } + if (element != null) { return element.getContent(); } return null; - } - - /* (non-Javadoc) - * @see org.apache.ojb.broker.cache.ObjectCache#cache(org.apache.ojb.broker.Identity, java.lang.Object) + } + + /* + * (non-Javadoc) + * + * @see org.apache.ojb.broker.cache.ObjectCache#cache(org.apache.ojb.broker.Identity, + * java.lang.Object) */ public void cache(Identity oid, Object obj) { cacheAdd(oid, obj); } + public synchronized static void cacheAdd(Identity oid, Object obj) { oidCache.remove(oid); CacheElement entry = new EhCacheElementImpl(oid, obj); oidCache.put(entry); - - PortletDefinitionComposite pd = (PortletDefinitionComposite)obj; - DistributedCacheObject wrapper = new RegistryCacheObjectWrapper(oid, pd.getUniqueName()); + + PortletDefinitionComposite pd = (PortletDefinitionComposite) obj; + DistributedCacheObject wrapper = new RegistryCacheObjectWrapper(oid, pd + .getUniqueName()); nameCache.remove(pd.getUniqueName()); - CacheElement nameEntry = nameCache.createElement(pd.getUniqueName(), wrapper); + CacheElement nameEntry = nameCache.createElement(pd.getUniqueName(), + wrapper); nameCache.put(nameEntry); - + if (listeners != null) - { - for (int ix=0; ix < listeners.size(); ix++) + { + for (int ix = 0; ix < listeners.size(); ix++) { - RegistryEventListener listener = (RegistryEventListener)listeners.get(ix); - listener.portletUpdated((PortletDefinitionComposite)obj); + RegistryEventListener listener = (RegistryEventListener) listeners + .get(ix); + listener.portletUpdated((PortletDefinitionComposite) obj); } } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.ojb.broker.cache.ObjectCache#clear() */ public void clear() { cacheClear(); } + public synchronized static void cacheClear() { oidCache.clear(); nameCache.clear(); } - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.ojb.broker.cache.ObjectCache#remove(org.apache.ojb.broker.Identity) */ public void remove(Identity oid) { cacheRemove(oid); } + /** * cacheRemove - * + * * Remove identified object from object and node caches. - * - * @param oid object identity + * + * @param oid + * object identity */ public synchronized static void cacheRemove(Identity oid) { - PortletDefinitionComposite pd = (PortletDefinitionComposite)cacheLookup(oid); - if (pd == null) - return; - + PortletDefinitionComposite pd = (PortletDefinitionComposite) cacheLookup(oid); + if (pd == null) return; + oidCache.remove(oid); nameCache.remove(pd.getUniqueName()); - + if (listeners != null) { - for (int ix=0; ix < listeners.size(); ix++) + for (int ix = 0; ix < listeners.size(); ix++) { - RegistryEventListener listener = (RegistryEventListener)listeners.get(ix); + RegistryEventListener listener = (RegistryEventListener) listeners + .get(ix); listener.portletRemoved(pd); - } + } } } - public synchronized static void cacheRemoveQuiet(String key, RegistryCacheObjectWrapper w) + public synchronized static void cacheRemoveQuiet(String key, + RegistryCacheObjectWrapper w) { RegistryCacheObjectWrapper wrapper = w; if (wrapper == null) { - wrapper = (RegistryCacheObjectWrapper)nameCache.get(key); - if (wrapper == null) - return; + wrapper = (RegistryCacheObjectWrapper) nameCache.get(key); + if (wrapper == null) return; } Identity oid = wrapper.getId(); - PortletDefinitionComposite pd = (PortletDefinitionComposite)cacheLookup(oid); - if (pd == null) - return; - - oidCache.removeQuiet(oid); - nameCache.removeQuiet(pd.getUniqueName()); + PortletDefinitionComposite pd = (PortletDefinitionComposite) cacheLookup(oid); + if (pd == null) return; + + oidCache.removeQuiet(oid); + nameCache.removeQuiet(pd.getUniqueName()); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/util/RegistrySupportedTestCase.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/util/RegistrySupportedTestCase.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/components/util/RegistrySupportedTestCase.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /* * Created on May 26, 2004 * @@ -33,40 +33,49 @@ /** * @author Scott T. Weaver - * + * */ -public abstract class RegistrySupportedTestCase extends AbstractPrefsSupportedTestCase +public abstract class RegistrySupportedTestCase extends + AbstractPrefsSupportedTestCase { protected PortletRegistry portletRegistry; + protected PortletEntityAccessComponent entityAccess; - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception - { + { super.setUp(); portletRegistry = (PortletRegistry) ctx.getBean("portletRegistry"); - entityAccess = (PortletEntityAccessComponent) ctx.getBean("portletEntityAccess"); - } - + entityAccess = (PortletEntityAccessComponent) ctx + .getBean("portletEntityAccess"); + } + protected String[] getConfigurations() { String[] confs = super.getConfigurations(); List confList = new ArrayList(Arrays.asList(confs)); confList.add("jetspeed-base.xml"); confList.add("page-manager.xml"); - confList.add("registry.xml"); + confList.add("registry.xml"); return (String[]) confList.toArray(new String[1]); } - + protected Properties getPostProcessProperties() { Properties p = super.getPostProcessProperties(); p.setProperty("supported.portletmode.autoswitch.config", "false"); - p.setProperty("supported.portletmode.autoswitch.edit_defaults", "false"); - p.setProperty("supported.portletmode.autoswitch.config.surrogate.portlet", "j2-admin::CustomConfigModePortlet"); + p + .setProperty("supported.portletmode.autoswitch.edit_defaults", + "false"); + p.setProperty( + "supported.portletmode.autoswitch.config.surrogate.portlet", + "j2-admin::CustomConfigModePortlet"); return p; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DescriptionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DescriptionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DescriptionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,41 +18,35 @@ import java.util.Locale; -import org.apache.jetspeed.util.JetspeedLocale; import org.apache.jetspeed.om.common.MutableDescription; +import org.apache.jetspeed.util.JetspeedLocale; /** - * DescriptionImpl - *
      - * Basic Implementation of the MutableDescription - * interface. + * DescriptionImpl
      + * Basic Implementation of the MutableDescription interface. * * @see org.apache.jetspeed.om.common.MutableDescription * * @author Scott T. Weaver * @version $Id: DescriptionImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public abstract class DescriptionImpl implements MutableDescription +public abstract class DescriptionImpl implements MutableDescription { private String description; + private Locale locale; - - protected long parentId; - - protected long id; - /** - * Tells OJB which class to use to materialize. - */ - protected String ojbConcreteClass = DescriptionImpl.class.getName(); - - + protected long parentId; + protected long id; + /** + * Tells OJB which class to use to materialize. + */ + protected String ojbConcreteClass = DescriptionImpl.class.getName(); - public DescriptionImpl() { super(); @@ -65,7 +59,7 @@ this(); this.locale = locale; this.description = description; - + } /** Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DescriptionSetImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DescriptionSetImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DescriptionSetImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,16 +29,18 @@ /** * BaseDescriptionSet * - * Supports + * Supports * * @author Scott T. Weaver * @version $Id: DescriptionSetImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public class DescriptionSetImpl implements MutableDescriptionSet, Serializable +public class DescriptionSetImpl implements MutableDescriptionSet, Serializable { + /** Specifies the type Description we are storing */ protected String descriptionType; + protected Collection innerCollection; /** @@ -47,7 +49,7 @@ public DescriptionSetImpl() { super(); - this.innerCollection = new ArrayList(); + this.innerCollection = new ArrayList(); } /** @@ -55,12 +57,9 @@ */ public DescriptionSetImpl(Collection c) { - this.innerCollection = c; + this.innerCollection = c; } - - - public DescriptionSetImpl(String descriptionType) { super(); @@ -73,10 +72,8 @@ */ public Description get(Locale arg0) { - if (arg0 == null) - { - throw new IllegalArgumentException("The Locale argument cannot be null"); - } + if (arg0 == null) { throw new IllegalArgumentException( + "The Locale argument cannot be null"); } // TODO: This may cause concurrent modification exceptions Iterator itr = iterator(); @@ -94,7 +91,9 @@ { fallBack = desc; } - else if (fallBack == null && desc.getLocale().equals(JetspeedLocale.getDefaultLocale())) + else if (fallBack == null + && desc.getLocale().equals( + JetspeedLocale.getDefaultLocale())) { fallBack = desc; } @@ -106,7 +105,7 @@ * @see org.apache.jetspeed.om.common.MutableDescriptionSet#addDescription(java.lang.String) */ public void addDescription(Description description) - { + { innerCollection.add(description); } @@ -114,7 +113,7 @@ * @see org.apache.pluto.om.common.DescriptionSet#iterator() */ public Iterator iterator() - { + { return innerCollection.iterator(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DisplayNameImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DisplayNameImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DisplayNameImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,30 +18,32 @@ import java.util.Locale; +import org.apache.jetspeed.om.common.MutableDisplayName; import org.apache.jetspeed.util.JetspeedLocale; -import org.apache.jetspeed.om.common.MutableDisplayName; /** * DisplayNameImpl * * @author Scott T. Weaver * @version $Id: DisplayNameImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public abstract class DisplayNameImpl implements MutableDisplayName { + private String displayName; + private Locale locale; - /** - * Tells OJB which class to use to materialize. - */ - protected String ojbConcreteClass = DisplayNameImpl.class.getName(); - - protected long parentId; - - protected long id; - - + + /** + * Tells OJB which class to use to materialize. + */ + protected String ojbConcreteClass = DisplayNameImpl.class.getName(); + + protected long parentId; + + protected long id; + public DisplayNameImpl() { super(); @@ -51,14 +53,16 @@ /** * - * @param locale Locale of this DisaplyName. - * @param name The actual text of the display name. + * @param locale + * Locale of this DisaplyName. + * @param name + * The actual text of the display name. */ public DisplayNameImpl(Locale locale, String name) { this(); this.locale = locale; - this.displayName = name; + this.displayName = name; } /** Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DisplayNameSetImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DisplayNameSetImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DisplayNameSetImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,36 +25,34 @@ import org.apache.jetspeed.om.common.MutableDisplayNameSet; import org.apache.jetspeed.util.JetspeedLocale; import org.apache.pluto.om.common.DisplayName; + /** * DisplayNameSetImpl * * @author Scott T. Weaver * @version $Id: DisplayNameSetImpl.java 517121 2007-03-12 07:45:49Z ate $ - * + * */ -public class DisplayNameSetImpl implements MutableDisplayNameSet, Serializable +public class DisplayNameSetImpl implements MutableDisplayNameSet, Serializable { /** Specifies the type Description we are storing */ protected String displayNameType; - - protected Collection innerCollection; + protected Collection innerCollection; - - public DisplayNameSetImpl() { - super(); + super(); this.innerCollection = new ArrayList(); } - - public DisplayNameSetImpl(Collection collection) - { - super(); - this.innerCollection = collection; - } + public DisplayNameSetImpl(Collection collection) + { + super(); + this.innerCollection = collection; + } + /** * @see org.apache.pluto.om.common.DisplayNameSet#get(java.util.Locale) */ @@ -70,11 +68,14 @@ { return aDName; } - else if (aDName.getLocale().getLanguage().equals(arg0.getLanguage())) + else if (aDName.getLocale().getLanguage() + .equals(arg0.getLanguage())) { fallBack = aDName; } - else if (fallBack == null && aDName.getLocale().equals(JetspeedLocale.getDefaultLocale())) + else if (fallBack == null + && aDName.getLocale().equals( + JetspeedLocale.getDefaultLocale())) { fallBack = aDName; } @@ -85,10 +86,8 @@ public void addDisplayName(DisplayName name) { - if (name == null) - { - throw new IllegalArgumentException("DisplayName argument cannot be null"); - } + if (name == null) { throw new IllegalArgumentException( + "DisplayName argument cannot be null"); } add(name); } @@ -113,7 +112,7 @@ * @see org.apache.pluto.om.common.DisplayNameSet#iterator() */ public Iterator iterator() - { + { return this.innerCollection.iterator(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DublinCoreImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DublinCoreImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/DublinCoreImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.jetspeed.om.impl; + import java.util.Collection; import java.util.Locale; @@ -22,44 +23,57 @@ import org.apache.jetspeed.om.common.GenericMetadata; /** - * DublinCoreImpl - *
      - * Implementation that allows retrieving information according to the - * Dublin Core specification - * (http://www.dublincore.org) + * DublinCoreImpl
      Implementation that allows retrieving information + * according to the Dublin Core specification (http://www.dublincore.org) * * @author Jeremy Ford * @version $Id: DublinCoreImpl.java 517719 2007-03-13 15:05:48Z ate $ - * + * */ public class DublinCoreImpl implements DublinCore { + public static final String TITLE = "title"; + public static final String CONTRIBUTOR = "contributor"; + public static final String COVERAGE = "coverage"; + public static final String CREATOR = "creator"; + public static final String DESCRIPTION = "description"; + public static final String FORMAT = "format"; + public static final String IDENTIFIER = "identifier"; + public static final String LANGUAGE = "language"; + public static final String PUBLISHER = "publisher"; + public static final String RELATION = "relation"; + public static final String RIGHT = "right"; + public static final String SOURCE = "source"; + public static final String SUBJECT = "subject"; + public static final String TYPE = "type"; - + GenericMetadata metadata = null; - + /** * @param md */ - public DublinCoreImpl(GenericMetadata md) { - + public DublinCoreImpl(GenericMetadata md) + { + this.metadata = md; } - /** + /** * @return Returns the titles */ public Collection getTitles() @@ -67,8 +81,9 @@ return metadata.getFields(TITLE); } - /** - * @param titles The titles to set + /** + * @param titles + * The titles to set */ public void setTitles(Collection titles) { @@ -78,281 +93,376 @@ /** * @return Returns the contributors. */ - public Collection getContributors() { + public Collection getContributors() + { return metadata.getFields(CONTRIBUTOR); } /** - * @param contributors The contributors to set. + * @param contributors + * The contributors to set. */ - public void setContributors(Collection contributors) { + public void setContributors(Collection contributors) + { metadata.setFields(CONTRIBUTOR, contributors); } /** * @return Returns the coverages. */ - public Collection getCoverages() { + public Collection getCoverages() + { return metadata.getFields(COVERAGE); } /** - * @param coverages The coverages to set. + * @param coverages + * The coverages to set. */ - public void setCoverages(Collection coverages) { + public void setCoverages(Collection coverages) + { metadata.setFields(COVERAGE, coverages); } /** * @return Returns the creators. */ - public Collection getCreators() { + public Collection getCreators() + { return metadata.getFields(CREATOR); } /** - * @param creators The creators to set. + * @param creators + * The creators to set. */ - public void setCreators(Collection creators) { + public void setCreators(Collection creators) + { metadata.setFields(CREATOR, creators); } /** * @return Returns the descriptions. */ - public Collection getDescriptions() { + public Collection getDescriptions() + { return metadata.getFields(DESCRIPTION); } /** - * @param descriptions The descriptions to set. + * @param descriptions + * The descriptions to set. */ - public void setDescriptions(Collection descriptions) { + public void setDescriptions(Collection descriptions) + { metadata.setFields(DESCRIPTION, descriptions); } /** * @return Returns the formats. */ - public Collection getFormats() { + public Collection getFormats() + { return metadata.getFields(FORMAT); } /** - * @param formats The formats to set. + * @param formats + * The formats to set. */ - public void setFormats(Collection formats) { + public void setFormats(Collection formats) + { metadata.setFields(FORMAT, formats); } /** * @return Returns the identifiers. */ - public Collection getIdentifiers() { + public Collection getIdentifiers() + { return metadata.getFields(IDENTIFIER); } /** - * @param identifiers The identifiers to set. + * @param identifiers + * The identifiers to set. */ - public void setIdentifiers(Collection identifiers) { + public void setIdentifiers(Collection identifiers) + { metadata.setFields(IDENTIFIER, identifiers); } /** * @return Returns the languages. */ - public Collection getLanguages() { + public Collection getLanguages() + { return metadata.getFields(LANGUAGE); } /** - * @param languages The languages to set. + * @param languages + * The languages to set. */ - public void setLanguages(Collection languages) { + public void setLanguages(Collection languages) + { metadata.setFields(LANGUAGE, languages); } /** * @return Returns the publishers. */ - public Collection getPublishers() { + public Collection getPublishers() + { return metadata.getFields(PUBLISHER); } /** - * @param publishers The publishers to set. + * @param publishers + * The publishers to set. */ - public void setPublishers(Collection publishers) { + public void setPublishers(Collection publishers) + { metadata.setFields(PUBLISHER, publishers); } /** * @return Returns the relations. */ - public Collection getRelations() { + public Collection getRelations() + { return metadata.getFields(RELATION); } /** - * @param relations The relations to set. + * @param relations + * The relations to set. */ - public void setRelations(Collection relations) { + public void setRelations(Collection relations) + { metadata.setFields(RELATION, relations); } /** * @return Returns the rights. */ - public Collection getRights() { + public Collection getRights() + { return metadata.getFields(RIGHT); } /** - * @param rights The rights to set. + * @param rights + * The rights to set. */ - public void setRights(Collection rights) { + public void setRights(Collection rights) + { metadata.setFields(RIGHT, rights); } /** * @return Returns the sources. */ - public Collection getSources() { + public Collection getSources() + { return metadata.getFields(SOURCE); } /** - * @param sources The sources to set. + * @param sources + * The sources to set. */ - public void setSources(Collection sources) { + public void setSources(Collection sources) + { metadata.setFields(SOURCE, sources); } /** * @return Returns the subjects. */ - public Collection getSubjects() { + public Collection getSubjects() + { return metadata.getFields(SUBJECT); } /** - * @param subjects The subjects to set. + * @param subjects + * The subjects to set. */ - public void setSubjects(Collection subjects) { + public void setSubjects(Collection subjects) + { metadata.setFields(SUBJECT, subjects); } /** * @return Returns the types. */ - public Collection getTypes() { + public Collection getTypes() + { return metadata.getFields(TYPE); } /** - * @param types The types to set. + * @param types + * The types to set. */ - public void setTypes(Collection types) { + public void setTypes(Collection types) + { metadata.setFields(TYPE, types); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.DublinCore#addContributor(java.util.Locale, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.DublinCore#addContributor(java.util.Locale, + * java.lang.String) */ - public void addContributor(Locale locale, String contributor) { + public void addContributor(Locale locale, String contributor) + { metadata.addField(locale, CONTRIBUTOR, contributor); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.DublinCore#addCoverage(java.util.Locale, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.DublinCore#addCoverage(java.util.Locale, + * java.lang.String) */ - public void addCoverage(Locale locale, String coverage) { + public void addCoverage(Locale locale, String coverage) + { metadata.addField(locale, COVERAGE, coverage); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.DublinCore#addCreator(java.util.Locale, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.DublinCore#addCreator(java.util.Locale, + * java.lang.String) */ - public void addCreator(Locale locale, String creator) { + public void addCreator(Locale locale, String creator) + { metadata.addField(locale, CREATOR, creator); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.DublinCore#addDescription(java.util.Locale, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.DublinCore#addDescription(java.util.Locale, + * java.lang.String) */ - public void addDescription(Locale locale, String description) { + public void addDescription(Locale locale, String description) + { metadata.addField(locale, DESCRIPTION, description); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.DublinCore#addFormat(java.util.Locale, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.DublinCore#addFormat(java.util.Locale, + * java.lang.String) */ - public void addFormat(Locale locale, String format) { + public void addFormat(Locale locale, String format) + { metadata.addField(locale, FORMAT, format); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.DublinCore#addIdentifier(java.util.Locale, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.DublinCore#addIdentifier(java.util.Locale, + * java.lang.String) */ - public void addIdentifier(Locale locale, String identifier) { + public void addIdentifier(Locale locale, String identifier) + { metadata.addField(locale, IDENTIFIER, identifier); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.DublinCore#addLanguage(java.util.Locale, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.DublinCore#addLanguage(java.util.Locale, + * java.lang.String) */ - public void addLanguage(Locale locale, String language) { + public void addLanguage(Locale locale, String language) + { metadata.addField(locale, LANGUAGE, language); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.DublinCore#addPublisher(java.util.Locale, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.DublinCore#addPublisher(java.util.Locale, + * java.lang.String) */ - public void addPublisher(Locale locale, String publisher) { + public void addPublisher(Locale locale, String publisher) + { metadata.addField(locale, PUBLISHER, publisher); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.DublinCore#addRelation(java.util.Locale, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.DublinCore#addRelation(java.util.Locale, + * java.lang.String) */ - public void addRelation(Locale locale, String relation) { + public void addRelation(Locale locale, String relation) + { metadata.addField(locale, RELATION, relation); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.DublinCore#addRight(java.util.Locale, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.DublinCore#addRight(java.util.Locale, + * java.lang.String) */ - public void addRight(Locale locale, String right) { + public void addRight(Locale locale, String right) + { metadata.addField(locale, RIGHT, right); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.DublinCore#addSource(java.util.Locale, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.DublinCore#addSource(java.util.Locale, + * java.lang.String) */ - public void addSource(Locale locale, String source) { + public void addSource(Locale locale, String source) + { metadata.addField(locale, SOURCE, source); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.DublinCore#addSubject(java.util.Locale, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.DublinCore#addSubject(java.util.Locale, + * java.lang.String) */ - public void addSubject(Locale locale, String subject) { + public void addSubject(Locale locale, String subject) + { metadata.addField(locale, SUBJECT, subject); - + } - - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.DublinCore#addDisplayName(java.util.Locale, java.lang.String) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.DublinCore#addDisplayName(java.util.Locale, + * java.lang.String) */ - public void addTitle(Locale locale, String title) { + public void addTitle(Locale locale, String title) + { metadata.addField(locale, TITLE, title); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.DublinCore#addType(java.util.Locale, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.DublinCore#addType(java.util.Locale, + * java.lang.String) */ - public void addType(Locale locale, String type) { + public void addType(Locale locale, String type) + { metadata.addField(locale, TYPE, type); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/GenericMetadataImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/GenericMetadataImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/GenericMetadataImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,24 +26,25 @@ import org.apache.jetspeed.om.common.LocalizedField; /** - * GenericMetadataImpl - *
      - * Implementation that allows retrieving localized information + * GenericMetadataImpl
      Implementation that allows retrieving localized + * information * * @author Jeremy Ford * @version $Id: GenericMetadataImpl.java 551866 2007-06-29 12:15:40Z ate $ - * + * */ public abstract class GenericMetadataImpl implements GenericMetadata -{ +{ + private Collection fields = null; + private transient MultiValueMap fieldMap = null; - + private MultiValueMap getFieldMap(boolean create) { if (fieldMap == null && create) { - synchronized(this) + synchronized (this) { if (fieldMap == null) { @@ -54,9 +55,11 @@ return fieldMap; } - - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.GenericMetadata#addField(java.util.Locale, java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.GenericMetadata#addField(java.util.Locale, + * java.lang.String, java.lang.String) */ public void addField(Locale locale, String name, String value) { @@ -64,36 +67,43 @@ field.setName(name); field.setValue(value); field.setLocale(locale); - + addField(field); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.GenericMetadata#addField(org.apache.jetspeed.om.common.LocalizedField) */ public void addField(LocalizedField field) { - if(fields == null) + if (fields == null) { fields = new ArrayList(); } - + fields.add(field); getFieldMap(true).put(field.getName(), field); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.GenericMetadata#getFields(java.lang.String) */ public Collection getFields(String name) { - //TODO: return an immutable version? + // TODO: return an immutable version? MultiValueMap fieldMap = getFieldMap(false); - return (Collection)(fieldMap !=null ? fieldMap.get(name) : null); + return (Collection) (fieldMap != null ? fieldMap.get(name) : null); } - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.GenericMetadata#setFields(java.lang.String, java.util.Collection) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.GenericMetadata#setFields(java.lang.String, + * java.util.Collection) */ public void setFields(String name, Collection values) { @@ -102,38 +112,44 @@ { fieldMap.remove(name); } - + Iterator fieldIter = fields.iterator(); - while(fieldIter.hasNext()) + while (fieldIter.hasNext()) { - LocalizedField field = (LocalizedField)fieldIter.next(); - if(field != null && field.getName() != null && field.getName().equals(name)) + LocalizedField field = (LocalizedField) fieldIter.next(); + if (field != null && field.getName() != null + && field.getName().equals(name)) { fieldIter.remove(); } } - - if(values != null) - { + + if (values != null) + { Iterator iter = values.iterator(); - while(iter.hasNext()) + while (iter.hasNext()) { - LocalizedField field = (LocalizedField)iter.next(); + LocalizedField field = (LocalizedField) iter.next(); getFieldMap(true).put(field.getName(), field); } - + fields.addAll(values); } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.GenericMetadata#getFields() */ - public Collection getFields() { + public Collection getFields() + { return fields; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.GenericMetadata#setFields(java.util.Collection) */ public void setFields(Collection fields) @@ -145,23 +161,25 @@ { fieldMap.clear(); } - - if(fields != null) - { + + if (fields != null) + { Iterator fieldIter = fields.iterator(); - while(fieldIter.hasNext()) + while (fieldIter.hasNext()) { - LocalizedField field = (LocalizedField)fieldIter.next(); + LocalizedField field = (LocalizedField) fieldIter.next(); if (field.getName() != null) { getFieldMap(true).put(field.getName(), field); } } } - + } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.GenericMetadata#copyFields(java.util.Collection) */ public void copyFields(Collection fields) @@ -194,27 +212,28 @@ Iterator fieldIter = fields.iterator(); while (fieldIter.hasNext()) { - LocalizedField field = (LocalizedField)fieldIter.next(); + LocalizedField field = (LocalizedField) fieldIter.next(); if (!this.fields.contains(field)) { - addField(field.getLocale(), field.getName(), field.getValue()); + addField(field.getLocale(), field.getName(), field + .getValue()); } } } - + // update field map MultiValueMap fieldMap = getFieldMap(false); if (fieldMap != null) { fieldMap.clear(); } - + if (this.fields != null) - { + { Iterator fieldIter = this.fields.iterator(); while (fieldIter.hasNext()) { - LocalizedField field = (LocalizedField)fieldIter.next(); + LocalizedField field = (LocalizedField) fieldIter.next(); getFieldMap(true).put(field.getName(), field); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/JetspeedServiceReferenceImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/JetspeedServiceReferenceImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/JetspeedServiceReferenceImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.om.impl; import org.apache.jetspeed.om.common.JetspeedServiceReference; @@ -25,20 +25,25 @@ */ public class JetspeedServiceReferenceImpl implements JetspeedServiceReference { + private String name; + private long appId; + private long id; - + public JetspeedServiceReferenceImpl() - { + { } - + public JetspeedServiceReferenceImpl(String name) { this.name = name; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.JetspeedServiceReference#getName() */ public String getName() @@ -46,7 +51,9 @@ return name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.JetspeedServiceReference#setName(java.lang.String) */ public void setName(String name) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/LanguageImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/LanguageImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/LanguageImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -49,19 +49,28 @@ * @author Scott T. Weaver * @author Ate Douma * @version $Id: LanguageImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public class LanguageImpl extends ResourceBundle implements MutableLanguage, Serializable +public class LanguageImpl extends ResourceBundle implements MutableLanguage, + Serializable { + public static final String JAVAX_PORTLET_KEYWORDS = "javax.portlet.keywords"; + public static final String JAVAX_PORTLET_SHORT_TITLE = "javax.portlet.short-title"; + public static final String JAVAX_PORTLET_TITLE = "javax.portlet.title"; private Set keys; + private String title; + private String shortTitle; + private Locale locale; + private String keywordStr; + private Collection keywords; /** @@ -80,12 +89,12 @@ keys.add(JAVAX_PORTLET_KEYWORDS); this.locale = JetspeedLocale.getDefaultLocale(); } - + public Enumeration getKeys() { return Collections.enumeration(keys); } - + protected Object handleGetObject(String key) { if (key.equals(JAVAX_PORTLET_TITLE)) @@ -96,53 +105,53 @@ { return getShortTitle(); } - else if (key.equals(JAVAX_PORTLET_KEYWORDS)) - { - return getKeywordStr(); - } + else if (key.equals(JAVAX_PORTLET_KEYWORDS)) { return getKeywordStr(); } return null; } - - private String getStringValue(ResourceBundle bundle, String key, String defaultValue) + + private String getStringValue(ResourceBundle bundle, String key, + String defaultValue) { String value = defaultValue; try { - value = (String)bundle.getObject(key); + value = (String) bundle.getObject(key); } catch (MissingResourceException mre) - { + { } catch (ClassCastException cce) - { + { } return value; } - + public void setResourceBundle(ResourceBundle bundle) { - if ( parent == null && bundle != null ) + if (parent == null && bundle != null) { Enumeration parentKeys = bundle.getKeys(); - while ( parentKeys.hasMoreElements() ) + while (parentKeys.hasMoreElements()) { keys.add(parentKeys.nextElement()); } setParent(bundle); } } - + public void loadDefaults() { ResourceBundle bundle = getParentResourceBundle(); - if ( bundle != null ) + if (bundle != null) { setTitle(getStringValue(bundle, JAVAX_PORTLET_TITLE, getTitle())); - setShortTitle(getStringValue(bundle, JAVAX_PORTLET_SHORT_TITLE, getShortTitle())); - setKeywords(getStringValue(bundle, JAVAX_PORTLET_KEYWORDS, getKeywordStr())); + setShortTitle(getStringValue(bundle, JAVAX_PORTLET_SHORT_TITLE, + getShortTitle())); + setKeywords(getStringValue(bundle, JAVAX_PORTLET_KEYWORDS, + getKeywordStr())); } } - + /** * @see org.apache.pluto.om.common.Language#getLocale() */ @@ -172,10 +181,7 @@ */ public Iterator getKeywords() { - if ( keywords == null ) - { - return Collections.EMPTY_LIST.iterator(); - } + if (keywords == null) { return Collections.EMPTY_LIST.iterator(); } return keywords.iterator(); } @@ -187,16 +193,16 @@ return this; } - + public ResourceBundle getParentResourceBundle() { return parent; } - + /** * @see org.apache.pluto.om.common.LanguageCtrl#setLocale(java.util.Locale) */ - public void setLocale( Locale locale ) + public void setLocale(Locale locale) { this.locale = locale; } @@ -204,7 +210,7 @@ /** * @see org.apache.pluto.om.common.LanguageCtrl#setTitle(java.lang.String) */ - public void setTitle( String title ) + public void setTitle(String title) { this.title = title; } @@ -212,7 +218,7 @@ /** * @see org.apache.pluto.om.common.LanguageCtrl#setShortTitle(java.lang.String) */ - public void setShortTitle( String shortTitle ) + public void setShortTitle(String shortTitle) { this.shortTitle = shortTitle; } @@ -220,11 +226,11 @@ /** * @see org.apache.jetspeed.om.common.LanguageComposite#setKeywords(java.util.Collection) */ - public void setKeywords( Collection keywords ) + public void setKeywords(Collection keywords) { this.keywords = keywords; } - + public void setKeywords(String keywordStr) { if (keywords == null) @@ -235,7 +241,7 @@ { keywords.clear(); } - if ( keywordStr == null ) + if (keywordStr == null) { keywordStr = ""; } @@ -246,12 +252,12 @@ } this.keywordStr = keywordStr; } - + public String getKeywordStr() { - if ( keywordStr == null ) + if (keywordStr == null) { - keywordStr = StringUtils.join(getKeywords(),","); + keywordStr = StringUtils.join(getKeywords(), ","); } return keywordStr; } @@ -259,12 +265,10 @@ /** * @see java.lang.Object#equals(java.lang.Object) */ - public boolean equals( Object obj ) + public boolean equals(Object obj) { - if (obj != null && obj instanceof Language) - { - return obj.hashCode() == this.hashCode(); - } + if (obj != null && obj instanceof Language) { return obj.hashCode() == this + .hashCode(); } return false; } @@ -276,7 +280,8 @@ { HashCodeBuilder hasher = new HashCodeBuilder(19, 79); Locale locale = getLocale(); - hasher.append(locale.getCountry()).append(locale.getLanguage()).append(locale.getVariant()); + hasher.append(locale.getCountry()).append(locale.getLanguage()).append( + locale.getVariant()); return hasher.toHashCode(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/LanguageSetImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/LanguageSetImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/LanguageSetImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -39,27 +39,29 @@ * @author Scott T. Weaver * @author Ate Douma * @version $Id: LanguageSetImpl.java 553014 2007-07-03 23:10:53Z ate $ - * + * */ public class LanguageSetImpl implements LanguageSet, Serializable, Support { + private transient ClassLoader classLoader = null; private String resources; + protected Collection innerCollection; /** * * @param wrappedSet */ - public LanguageSetImpl( Collection collection ) + public LanguageSetImpl(Collection collection) { super(); this.innerCollection = collection; } public LanguageSetImpl() - { + { this(Collections.synchronizedList(new ArrayList())); } @@ -92,42 +94,46 @@ /** * @see org.apache.pluto.om.common.LanguageSet#get(java.util.Locale) */ - public Language get( Locale locale ) + public Language get(Locale locale) { LanguageImpl fallback = null; - synchronized(innerCollection) + synchronized (innerCollection) { Iterator searchItr = innerCollection.iterator(); while (searchItr.hasNext()) { - LanguageImpl lang = (LanguageImpl)searchItr.next(); - + LanguageImpl lang = (LanguageImpl) searchItr.next(); + if (lang.getLocale().equals(locale)) { - if (resources != null && lang.getParentResourceBundle() == null) + if (resources != null + && lang.getParentResourceBundle() == null) { - lang.setResourceBundle(loadResourceBundle(lang.getLocale())); + lang.setResourceBundle(loadResourceBundle(lang + .getLocale())); } return lang; } - else if (lang.getLocale().getLanguage().equals(locale.getLanguage())) + else if (lang.getLocale().getLanguage().equals( + locale.getLanguage())) { fallback = lang; } - + } } - if ( fallback == null ) + if (fallback == null) { - if ( getDefaultLocale().equals(locale) ) + if (getDefaultLocale().equals(locale)) { // no default language stored yet LanguageImpl defaultLanguage = new LanguageImpl(); defaultLanguage.setLocale(locale); - - if ( resources != null ) + + if (resources != null) { - defaultLanguage.setResourceBundle(loadResourceBundle(locale)); + defaultLanguage + .setResourceBundle(loadResourceBundle(locale)); defaultLanguage.loadDefaults(); innerCollection.add(defaultLanguage); return defaultLanguage; @@ -135,18 +141,18 @@ } else { - fallback = (LanguageImpl)get(getDefaultLocale()); + fallback = (LanguageImpl) get(getDefaultLocale()); } } - + LanguageImpl language = new LanguageImpl(); language.setLocale(locale); language.setTitle(fallback.getTitle()); language.setShortTitle(fallback.getShortTitle()); language.setKeywords(fallback.getKeywordStr()); - if ( resources != null ) + if (resources != null) { - language.setResourceBundle(loadResourceBundle(locale)); + language.setResourceBundle(loadResourceBundle(locale)); } language.loadDefaults(); innerCollection.add(language); @@ -157,11 +163,11 @@ * @see org.apache.pluto.om.common.LanguageSet#getDefaultLocale() */ public Locale getDefaultLocale() - { + { return JetspeedLocale.getDefaultLocale(); } - public boolean add( Object o ) + public boolean add(Object o) { if (o instanceof Language) { @@ -200,7 +206,7 @@ /** * @param collection */ - public void setInnerCollection( Collection collection ) + public void setInnerCollection(Collection collection) { innerCollection = collection; } @@ -213,7 +219,7 @@ /** * @param string */ - public void setResources( String string ) + public void setResources(String string) { resources = string; } @@ -223,22 +229,23 @@ * * @see org.apache.jetspeed.om.common.Support#postLoad(java.lang.Object) */ - public void postLoad( Object parameter ) throws Exception + public void postLoad(Object parameter) throws Exception { Iterator iter = ((Collection) parameter).iterator(); LanguageImpl language; while (iter.hasNext()) { - language = (LanguageImpl)get((Locale)iter.next()); + language = (LanguageImpl) get((Locale) iter.next()); // load available resource bundle values language.loadDefaults(); } - // ensure default locale language is created and available resource bundle values are loaded - language = (LanguageImpl)get(getDefaultLocale()); + // ensure default locale language is created and available resource + // bundle values are loaded + language = (LanguageImpl) get(getDefaultLocale()); language.loadDefaults(); } - protected ResourceBundle loadResourceBundle( Locale locale ) + protected ResourceBundle loadResourceBundle(Locale locale) { ResourceBundle resourceBundle = null; try @@ -247,12 +254,14 @@ { if (classLoader != null) { - resourceBundle = ResourceBundle.getBundle(resources, locale, classLoader); + resourceBundle = ResourceBundle.getBundle(resources, + locale, classLoader); } else { - resourceBundle = ResourceBundle.getBundle(resources, locale, Thread.currentThread() - .getContextClassLoader()); + resourceBundle = ResourceBundle.getBundle(resources, + locale, Thread.currentThread() + .getContextClassLoader()); } } } @@ -269,7 +278,7 @@ * * @param loader */ - public void setClassLoader( ClassLoader loader ) + public void setClassLoader(ClassLoader loader) { classLoader = loader; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/LocalizedFieldImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/LocalizedFieldImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/LocalizedFieldImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.jetspeed.om.impl; + import java.util.Locale; import org.apache.jetspeed.om.common.LocalizedField; @@ -23,35 +24,40 @@ import org.apache.pluto.om.common.ObjectID; /** - * LocalizedFieldImpl - *
      - * Implementation that represents a string value and the locale of that string + * LocalizedFieldImpl
      Implementation that represents a string value and + * the locale of that string * * @author Jeremy Ford * @version $Id: LocalizedFieldImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class LocalizedFieldImpl implements LocalizedField { + protected String value; + protected String name; + protected Locale locale; - + protected long parentId; + protected JetspeedLongObjectID id; - + public LocalizedFieldImpl() { - + } - + public LocalizedFieldImpl(Locale locale, String value) { this.locale = locale; this.value = value; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.LocalizedField#getLocale() */ public Locale getLocale() @@ -59,15 +65,19 @@ return locale; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.LocalizedField#setLocale(java.util.Locale) */ public void setLocale(Locale locale) { - this.locale = locale; + this.locale = locale; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.LocalizedField#getValue() */ public String getValue() @@ -75,12 +85,14 @@ return value; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.LocalizedField#setValue(java.lang.String) */ public void setValue(String value) { - this.value = value; + this.value = value; } /** @@ -93,7 +105,7 @@ public void setLanguage(String language) { - if (language != null) + if (language != null) { String[] localeArray = language.split("[-|_]"); String country = ""; @@ -120,14 +132,13 @@ public String getLanguage() { - if (this.locale != null) - { - return this.locale.toString(); - } + if (this.locale != null) { return this.locale.toString(); } return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.LocalizedField#getName() */ public String getName() @@ -135,35 +146,42 @@ return name; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.LocalizedField#setName(java.lang.String) */ public void setName(String name) { - this.name = name; + this.name = name; } - + public String toString() { return "Name: " + name + " Value: " + value + " Locale: " + locale; } - + public boolean equals(Object o) { boolean result = false; - - if(o instanceof LocalizedFieldImpl && o != null) + + if (o instanceof LocalizedFieldImpl && o != null) { - LocalizedFieldImpl localField = (LocalizedFieldImpl)o; - - result = (this.name == null) ? (localField.name == null) : (this.name.equals(localField.name)); - result = result && ((this.value == null) ? (localField.value == null) : (this.value.equals(localField.value))); - result = result && ((this.locale == null) ? (localField.locale == null) : (this.locale.equals(localField.locale))); + LocalizedFieldImpl localField = (LocalizedFieldImpl) o; + + result = (this.name == null) ? (localField.name == null) + : (this.name.equals(localField.name)); + result = result + && ((this.value == null) ? (localField.value == null) + : (this.value.equals(localField.value))); + result = result + && ((this.locale == null) ? (localField.locale == null) + : (this.locale.equals(localField.locale))); } - + return result; } - + /** * @see java.lang.Object#hashCode() */ @@ -171,9 +189,10 @@ { HashCodeBuilder hasher = new HashCodeBuilder(27, 101); hasher.append(name).append(value); - if(locale != null) - { - hasher.append(locale.getCountry()).append(locale.getLanguage()).append(locale.getVariant()); + if (locale != null) + { + hasher.append(locale.getCountry()).append(locale.getLanguage()) + .append(locale.getVariant()); } return hasher.toHashCode(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ParameterDescriptionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ParameterDescriptionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ParameterDescriptionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,13 +23,15 @@ * * @author Scott T. Weaver * @version $Id: ParameterDescriptionImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class ParameterDescriptionImpl extends DescriptionImpl { - /** - * Tells OJB which class to use to materialize. - */ - protected String ojbConcreteClass = ParameterDescriptionImpl.class.getName(); + /** + * Tells OJB which class to use to materialize. + */ + protected String ojbConcreteClass = ParameterDescriptionImpl.class + .getName(); + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ParameterImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ParameterImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ParameterImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,7 +31,6 @@ import org.apache.pluto.om.common.Description; import org.apache.pluto.om.common.DescriptionSet; - /** * @author Scott T. Weaver */ @@ -39,7 +38,9 @@ { private String name; + private String value; + private String description; protected long parameterId; @@ -47,8 +48,10 @@ protected long parentId; private Collection descriptions; - private DescriptionSetImpl descCollWrapper = new DescriptionSetImpl(DescriptionImpl.TYPE_PARAMETER); - + + private DescriptionSetImpl descCollWrapper = new DescriptionSetImpl( + DescriptionImpl.TYPE_PARAMETER); + private static final Log log = LogFactory.getLog(ParameterImpl.class); /** @@ -92,10 +95,11 @@ { if (obj != null && obj.getClass().equals(getClass())) { - ParameterImpl p = (ParameterImpl) obj; + ParameterImpl p = (ParameterImpl) obj; boolean sameParent = (p.parentId == parentId); - boolean sameName = (name != null && p.getName() != null && name.equals(p.getName())); - return sameParent && sameName; + boolean sameName = (name != null && p.getName() != null && name + .equals(p.getName())); + return sameParent && sameName; } return false; @@ -116,10 +120,8 @@ */ public Description getDescription(Locale arg0) { - if (descriptions != null) - { - return new DescriptionSetImpl(descriptions).get(arg0); - } + if (descriptions != null) { return new DescriptionSetImpl(descriptions) + .get(arg0); } return null; } @@ -133,26 +135,28 @@ } /** - * @see org.apache.jetspeed.om.common.ParameterComposite#addDescription(java.util.Locale, java.lang.String) + * @see org.apache.jetspeed.om.common.ParameterComposite#addDescription(java.util.Locale, + * java.lang.String) */ public void addDescription(Locale locale, String desc) { if (descriptions == null) { - descriptions = new ArrayList(); + descriptions = new ArrayList(); } descCollWrapper.setInnerCollection(descriptions); try { MutableDescription descObj = new ParameterDescriptionImpl(); - - descObj.setLocale(locale); - descObj.setDescription(desc); - descCollWrapper.addDescription(descObj); + + descObj.setLocale(locale); + descObj.setDescription(desc); + descCollWrapper.addDescription(descObj); } catch (Exception e) { - String msg = "Unable to instantiate Description implementor, " + e.toString(); + String msg = "Unable to instantiate Description implementor, " + + e.toString(); log.error(msg, e); throw new IllegalStateException(msg); } @@ -178,13 +182,14 @@ */ public void setDescription(String desc) { -// System.out.println("Setting description..." + desc); + // System.out.println("Setting description..." + desc); addDescription(JetspeedLocale.getDefaultLocale(), desc); -// System.out.println("Description Set " + desc); + // System.out.println("Description Set " + desc); } /** - * Remove when Castor is mapped correctly + * Remove when Castor is mapped correctly + * * @deprecated * @return */ @@ -193,10 +198,7 @@ Description desc = getDescription(JetspeedLocale.getDefaultLocale()); - if (desc != null) - { - return desc.getDescription(); - } + if (desc != null) { return desc.getDescription(); } return null; } @@ -209,7 +211,7 @@ if (descriptions != null) { descCollWrapper.setInnerCollection(descriptions); - } + } return descCollWrapper; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ParameterSetImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ParameterSetImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ParameterSetImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,7 +21,6 @@ import java.util.Collection; import java.util.Iterator; -//TODO: import org.apache.jetspeed.exception.JetspeedRuntimeException; import org.apache.jetspeed.om.common.ParameterComposite; import org.apache.pluto.om.common.Parameter; import org.apache.pluto.om.common.ParameterSet; @@ -33,10 +32,12 @@ * * @author Scott T. Weaver * @version $Id: ParameterSetImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public abstract class ParameterSetImpl implements ParameterSet, ParameterSetCtrl, Serializable +public abstract class ParameterSetImpl implements ParameterSet, + ParameterSetCtrl, Serializable { + protected Collection innerCollection; /** @@ -71,17 +72,15 @@ while (itr.hasNext()) { Parameter p = (Parameter) itr.next(); - if (p.getName().equals(name)) - { - return p; - } + if (p.getName().equals(name)) { return p; } } return null; } /** - * @see org.apache.pluto.om.common.ParameterSetCtrl#add(java.lang.String, java.lang.String) + * @see org.apache.pluto.om.common.ParameterSetCtrl#add(java.lang.String, + * java.lang.String) */ public Parameter add(String name, String value) { @@ -126,11 +125,10 @@ } /** - * @see java.util.Collection#add(java.lang.Object) - * NOTE:
      This method will effectively convert any class - * implementing the org.apache.jetspeed.common.ParameterComposite - * that is NOT of the type returned by the getParameterClass() method it is - * to converted to the correct Parameter implementation. + * @see java.util.Collection#add(java.lang.Object) NOTE:
      This + * method will effectively convert any class implementing the org.apache.jetspeed.common.ParameterComposite + * that is NOT of the type returned by the getParameterClass() + * method it is to converted to the correct Parameter implementation. */ public boolean add(Object o) { @@ -150,8 +148,7 @@ } /** - * Creates a Parameter class this Collection will be working with. - *
      + * Creates a Parameter class this Collection will be working with.
      */ protected abstract ParameterComposite newParameterInstance(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletAppDescriptionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletAppDescriptionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletAppDescriptionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,14 +23,15 @@ * * @author Scott T. Weaver * @version $Id: PortletAppDescriptionImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class PortletAppDescriptionImpl extends DescriptionImpl { - /** - * Tells OJB which class to use to materialize. - */ - protected String ojbConcreteClass = PortletAppDescriptionImpl.class.getName(); - + /** + * Tells OJB which class to use to materialize. + */ + protected String ojbConcreteClass = PortletAppDescriptionImpl.class + .getName(); + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletDescriptionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletDescriptionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletDescriptionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * Created on Jan 22, 2004 * @@ -29,21 +29,14 @@ * * @author Scott T. Weaver * @version $Id: PortletDescriptionImpl.java 516881 2007-03-11 10:34:21Z ate $ - * + * */ public class PortletDescriptionImpl extends DescriptionImpl { - /** - * Tells OJB which class to use to materialize. - */ - protected String ojbConcreteClass = PortletDescriptionImpl.class.getName(); - - + /** + * Tells OJB which class to use to materialize. + */ + protected String ojbConcreteClass = PortletDescriptionImpl.class.getName(); - - - - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletDisplayNameImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletDisplayNameImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletDisplayNameImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * Created on Jan 21, 2004 * @@ -22,10 +22,6 @@ */ package org.apache.jetspeed.om.impl; - - - - /** *

      * PortletDisplayNameImpl @@ -33,13 +29,14 @@ * * @author Scott T. Weaver * @version $Id: PortletDisplayNameImpl.java 516881 2007-03-11 10:34:21Z ate $ - * + * */ public class PortletDisplayNameImpl extends DisplayNameImpl { - /** - * Tells OJB which class to use to materialize. - */ - protected String ojbConcreteClass = PortletDisplayNameImpl.class.getName(); - + + /** + * Tells OJB which class to use to materialize. + */ + protected String ojbConcreteClass = PortletDisplayNameImpl.class.getName(); + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletEntityDescriptionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletEntityDescriptionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletEntityDescriptionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,13 +22,16 @@ *

      * * @author Scott T. Weaver - * @version $Id: PortletEntityDescriptionImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: PortletEntityDescriptionImpl.java 516448 2007-03-09 16:25:47Z + * ate $ + * */ public class PortletEntityDescriptionImpl extends DescriptionImpl { - /** - * Tells OJB which class to use to materialize. - */ - protected String ojbConcreteClass = PortletEntityDescriptionImpl.class.getName(); + + /** + * Tells OJB which class to use to materialize. + */ + protected String ojbConcreteClass = PortletEntityDescriptionImpl.class + .getName(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletInitParameterImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletInitParameterImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletInitParameterImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,7 +16,6 @@ */ package org.apache.jetspeed.om.impl; - /** * Parameter implementation suitable for use within PortletDefinitions. * @@ -24,13 +23,15 @@ * * @author Scott T. Weaver * @version $Id: PortletInitParameterImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class PortletInitParameterImpl extends ParameterImpl { + /** * Tells OJB which class to use to materialize. */ - protected String ojbConcreteClass = PortletInitParameterImpl.class.getName(); + protected String ojbConcreteClass = PortletInitParameterImpl.class + .getName(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletParameterSetImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletParameterSetImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PortletParameterSetImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,7 +26,7 @@ * * @author Scott T. Weaver * @version $Id: PortletParameterSetImpl.java 517121 2007-03-12 07:45:49Z ate $ - * + * */ public class PortletParameterSetImpl extends ParameterSetImpl { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PreferenceDescriptionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PreferenceDescriptionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/PreferenceDescriptionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * Created on Jan 22, 2004 * @@ -29,12 +29,14 @@ * * @author Scott T. Weaver * @version $Id: PreferenceDescriptionImpl.java 516881 2007-03-11 10:34:21Z ate $ - * + * */ public class PreferenceDescriptionImpl extends DescriptionImpl { - /** - * Tells OJB which class to use to materialize. - */ - protected String ojbConcreteClass = PreferenceDescriptionImpl.class.getName(); + + /** + * Tells OJB which class to use to materialize. + */ + protected String ojbConcreteClass = PreferenceDescriptionImpl.class + .getName(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/SecurityRoleRefDescriptionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/SecurityRoleRefDescriptionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/SecurityRoleRefDescriptionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,14 +22,17 @@ *

      * * @author Scott T. Weaver - * @version $Id: SecurityRoleRefDescriptionImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: SecurityRoleRefDescriptionImpl.java 516448 2007-03-09 16:25:47Z + * ate $ + * */ public class SecurityRoleRefDescriptionImpl extends DescriptionImpl { - /** - * Tells OJB which class to use to materialize. - */ - protected String ojbConcreteClass = SecurityRoleRefDescriptionImpl.class.getName(); + /** + * Tells OJB which class to use to materialize. + */ + protected String ojbConcreteClass = SecurityRoleRefDescriptionImpl.class + .getName(); + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/SecurityRoleRefImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/SecurityRoleRefImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/SecurityRoleRefImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -35,18 +35,25 @@ * * @author Scott T. Weaver * @version $Id: SecurityRoleRefImpl.java 517124 2007-03-12 08:10:25Z ate $ - * + * */ -public class SecurityRoleRefImpl implements SecurityRoleRefComposite, Serializable +public class SecurityRoleRefImpl implements SecurityRoleRefComposite, + Serializable { protected long id; + protected long portletId; + private String link; + private String name; + private Collection descriptions; - private DescriptionSetImpl descCollWrapper = new DescriptionSetImpl(DescriptionImpl.TYPE_SEC_ROLE_REF); + private DescriptionSetImpl descCollWrapper = new DescriptionSetImpl( + DescriptionImpl.TYPE_SEC_ROLE_REF); + /** * @see org.apache.pluto.om.common.SecurityRoleRef#getRoleLink() */ @@ -87,14 +94,16 @@ if (obj != null && obj instanceof SecurityRoleRef) { SecurityRoleRef aRef = (SecurityRoleRef) obj; - //TODO: Because of a bug in OJB 1.0.rc4 fields seems not have been set - // before this object is put into a HashMap. - // Therefore, for the time being, check against null values is - // required. - // Once 1.0rc5 or higher can be used the following line should be - // used again. - //return this.getRoleName().equals(aRef.getRoleName()); - return getRoleName() != null && getRoleName().equals(aRef.getRoleName()); + // TODO: Because of a bug in OJB 1.0.rc4 fields seems not have been + // set + // before this object is put into a HashMap. + // Therefore, for the time being, check against null values is + // required. + // Once 1.0rc5 or higher can be used the following line should be + // used again. + // return this.getRoleName().equals(aRef.getRoleName()); + return getRoleName() != null + && getRoleName().equals(aRef.getRoleName()); } return false; @@ -136,16 +145,17 @@ descCollWrapper.setInnerCollection(descriptions); descCollWrapper.addDescription(description); } - + /** - * @see org.apache.jetspeed.om.common.MutableDescriptionSet#addDescription(java.util.Locale, java.lang.String) + * @see org.apache.jetspeed.om.common.MutableDescriptionSet#addDescription(java.util.Locale, + * java.lang.String) */ public void addDescription(Locale locale, String description) { SecurityRoleRefDescriptionImpl descImpl = new SecurityRoleRefDescriptionImpl(); descImpl.setDescription(description); descImpl.setLocale(locale); - + addDescription(descImpl); } @@ -154,7 +164,8 @@ */ public void setDescriptionSet(DescriptionSet descriptions) { - this.descriptions = ((DescriptionSetImpl) descriptions).getInnerCollection(); + this.descriptions = ((DescriptionSetImpl) descriptions) + .getInnerCollection(); } @@ -167,9 +178,8 @@ */ public void setDescription(String arg0) { - MutableDescription descObj =new SecurityRoleRefDescriptionImpl(); - - + MutableDescription descObj = new SecurityRoleRefDescriptionImpl(); + descObj.setLocale(JetspeedLocale.getDefaultLocale()); descObj.setDescription(arg0); addDescription(descObj); @@ -183,7 +193,7 @@ if (descriptions != null) { descCollWrapper.setInnerCollection(descriptions); - } + } return descCollWrapper; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/SecurityRoleRefSetImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/SecurityRoleRefSetImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/SecurityRoleRefSetImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,9 +32,10 @@ * * @author Scott T. Weaver * @version $Id: SecurityRoleRefSetImpl.java 517121 2007-03-12 07:45:49Z ate $ - * + * */ -public class SecurityRoleRefSetImpl implements SecurityRoleRefSet, SecurityRoleRefSetCtrl, Serializable +public class SecurityRoleRefSetImpl implements SecurityRoleRefSet, + SecurityRoleRefSetCtrl, Serializable { protected Collection innerCollection; @@ -57,22 +58,21 @@ Iterator itr = innerCollection.iterator(); while (itr.hasNext()) { - SecurityRoleRef roleRef = (SecurityRoleRef) itr.next(); - if (roleRef.getRoleName().equals(name)) - { - return roleRef; - } + SecurityRoleRef roleRef = (SecurityRoleRef) itr.next(); + if (roleRef.getRoleName().equals(name)) { return roleRef; } } return null; } /** - * @see org.apache.pluto.om.common.SecurityRoleRefSetCtrl#add(java.lang.String, java.lang.String, java.lang.String) + * @see org.apache.pluto.om.common.SecurityRoleRefSetCtrl#add(java.lang.String, + * java.lang.String, java.lang.String) */ - public SecurityRoleRef add(String roleName, String roleLink, String description) + public SecurityRoleRef add(String roleName, String roleLink, + String description) { - // TODO Fix me. We should try not to directly use implementation classes + // TODO Fix me. We should try not to directly use implementation classes SecurityRoleRefImpl newRef = new SecurityRoleRefImpl(); newRef.setRoleName(roleName); newRef.setRoleLink(roleLink); @@ -96,11 +96,11 @@ public SecurityRoleRef remove(String name) { SecurityRoleRef roleRef = get(name); - if(roleRef != null) + if (roleRef != null) { - innerCollection.remove(roleRef); + innerCollection.remove(roleRef); } - + return roleRef; } @@ -118,9 +118,9 @@ */ public boolean add(Object o) { - if(innerCollection.contains(o)) + if (innerCollection.contains(o)) { - remove(o); + remove(o); } return innerCollection.add(o); } @@ -134,9 +134,11 @@ } /** - * @see org.apache.pluto.om.common.SecurityRoleRefSetCtrl#add(java.lang.String, java.lang.String, org.apache.pluto.om.common.DescriptionSet) + * @see org.apache.pluto.om.common.SecurityRoleRefSetCtrl#add(java.lang.String, + * java.lang.String, org.apache.pluto.om.common.DescriptionSet) */ - public SecurityRoleRef add(String roleName, String roleLink, DescriptionSet descriptions) + public SecurityRoleRef add(String roleName, String roleLink, + DescriptionSet descriptions) { SecurityRoleRefImpl newRef = new SecurityRoleRefImpl(); newRef.setRoleName(roleName); @@ -150,7 +152,7 @@ * @see java.util.Collection#addAll(java.util.Collection) */ public boolean addAll(Collection c) - { + { return innerCollection.addAll(c); } @@ -167,7 +169,7 @@ * @see java.util.Collection#contains(java.lang.Object) */ public boolean contains(Object o) - { + { return innerCollection.contains(o); } @@ -175,7 +177,7 @@ * @see java.util.Collection#containsAll(java.util.Collection) */ public boolean containsAll(Collection c) - { + { return innerCollection.containsAll(c); } @@ -183,7 +185,7 @@ * @see java.util.Collection#isEmpty() */ public boolean isEmpty() - { + { return innerCollection.isEmpty(); } @@ -191,7 +193,7 @@ * @see java.util.Collection#iterator() */ public Iterator iterator() - { + { return innerCollection.iterator(); } @@ -199,7 +201,7 @@ * @see java.util.Collection#removeAll(java.util.Collection) */ public boolean removeAll(Collection c) - { + { return innerCollection.removeAll(c); } @@ -207,7 +209,7 @@ * @see java.util.Collection#retainAll(java.util.Collection) */ public boolean retainAll(Collection c) - { + { return innerCollection.retainAll(c); } @@ -215,7 +217,7 @@ * @see java.util.Collection#size() */ public int size() - { + { return innerCollection.size(); } @@ -223,7 +225,7 @@ * @see java.util.Collection#toArray() */ public Object[] toArray() - { + { return innerCollection.toArray(); } @@ -231,7 +233,7 @@ * @see java.util.Collection#toArray(java.lang.Object[]) */ public Object[] toArray(Object[] a) - { + { return innerCollection.toArray(a); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ServletInitParameterImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ServletInitParameterImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ServletInitParameterImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,21 +16,22 @@ */ package org.apache.jetspeed.om.impl; - /** - * - * ServletInitParameterImpl - * Parameter implementation suitable for use within ServletDefinitions. * + * ServletInitParameterImpl Parameter implementation suitable for use within + * ServletDefinitions. + * * @author Scott T. Weaver * @version $Id: ServletInitParameterImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class ServletInitParameterImpl extends ParameterImpl { + /** * Tells OJB which class to use to materialize. */ - protected String ojbConcreteClass = PortletInitParameterImpl.class.getName(); + protected String ojbConcreteClass = PortletInitParameterImpl.class + .getName(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ServletParameterSetImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ServletParameterSetImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/ServletParameterSetImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,14 +18,13 @@ import org.apache.jetspeed.om.common.ParameterComposite; - /** * * ServletParameterSetImpl * * @author Scott T. Weaver * @version $Id: ServletParameterSetImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class ServletParameterSetImpl extends ParameterSetImpl { @@ -46,7 +45,8 @@ } catch (Exception e) { - throw new IllegalStateException("Instance class unable to be configured " + e.toString()); + throw new IllegalStateException( + "Instance class unable to be configured " + e.toString()); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/UserAttributeImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/UserAttributeImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/UserAttributeImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,7 +19,9 @@ import org.apache.jetspeed.om.common.UserAttribute; /** - *

      User attribute implementation.

      + *

      + * User attribute implementation. + *

      * * @author David Le Strat */ @@ -28,25 +30,33 @@ /** The application id. */ protected long appId; + protected long id; - + /** - *

      Default constructor.

      + *

      + * Default constructor. + *

      */ public UserAttributeImpl() { } /** - *

      User attribute constructor given a name and description.

      - * @param The user attribute name. - * @param The user attribute description. + *

      + * User attribute constructor given a name and description. + *

      + * + * @param The + * user attribute name. + * @param The + * user attribute description. */ - public UserAttributeImpl(String name, String description) - { - this.name = name; - this.description = description; - } + public UserAttributeImpl(String name, String description) + { + this.name = name; + this.description = description; + } private String name; @@ -85,12 +95,16 @@ } /** - *

      Convert {@link UserAttribute} to String.

      + *

      + * Convert {@link UserAttribute} to String. + *

      + * * @return String value of UserAttribute. */ public String toString() { - String userAttribute = "[[name, " + this.name + "], [description, " + this.description + "]]"; + String userAttribute = "[[name, " + this.name + "], [description, " + + this.description + "]]"; return userAttribute; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/UserAttributeRefImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/UserAttributeRefImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/UserAttributeRefImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,7 +20,9 @@ import org.apache.jetspeed.om.common.UserAttributeRef; /** - *

      User attribute ref implementation.

      + *

      + * User attribute ref implementation. + *

      * * @author David Le Strat */ @@ -29,36 +31,49 @@ /** The application id. */ protected long appId; - protected long id; - + + protected long id; + /** - *

      Default constructor.

      + *

      + * Default constructor. + *

      */ public UserAttributeRefImpl() { } /** - *

      User attribute ref constructor given a name and name link.

      - * @param The user attribute ref name. - * @param The user attribute ref name link. + *

      + * User attribute ref constructor given a name and name link. + *

      + * + * @param The + * user attribute ref name. + * @param The + * user attribute ref name link. */ - public UserAttributeRefImpl(String name, String nameLink) - { - this.name = name; - this.nameLink = nameLink; - } + public UserAttributeRefImpl(String name, String nameLink) + { + this.name = name; + this.nameLink = nameLink; + } - /** - *

      User attribute ref constructor given a {@link UserAttribute}.

      - * @param The user attribute ref name. - * @param The user attribute ref name link. - */ - public UserAttributeRefImpl(UserAttribute userAttribute) - { - this.name = userAttribute.getName(); - this.description = userAttribute.getDescription(); - } + /** + *

      + * User attribute ref constructor given a {@link UserAttribute}. + *

      + * + * @param The + * user attribute ref name. + * @param The + * user attribute ref name link. + */ + public UserAttributeRefImpl(UserAttribute userAttribute) + { + this.name = userAttribute.getName(); + this.description = userAttribute.getDescription(); + } private String name; @@ -115,12 +130,16 @@ } /** - *

      Convert {@link UserAttributeRef} to String.

      + *

      + * Convert {@link UserAttributeRef} to String. + *

      + * * @return String value of UserAttributeRef. */ public String toString() { - String userAttributeRef = "[[name, " + this.name + "], [name-link, " + this.nameLink + "]]"; + String userAttributeRef = "[[name, " + this.name + "], [name-link, " + + this.nameLink + "]]"; return userAttributeRef; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/WebAppDescriptionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/WebAppDescriptionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/WebAppDescriptionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,20 +25,15 @@ * * @author Scott T. Weaver * @version $Id: WebAppDescriptionImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public class WebAppDescriptionImpl extends DescriptionImpl implements Serializable +public class WebAppDescriptionImpl extends DescriptionImpl implements + Serializable { - /** - * Tells OJB which class to use to materialize. - */ - protected String ojbConcreteClass = WebAppDescriptionImpl.class.getName(); - - + /** + * Tells OJB which class to use to materialize. + */ + protected String ojbConcreteClass = WebAppDescriptionImpl.class.getName(); - - - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/WebAppDisplayNameImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/WebAppDisplayNameImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/impl/WebAppDisplayNameImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * Created on Jan 21, 2004 * @@ -29,14 +29,14 @@ * * @author Scott T. Weaver * @version $Id: WebAppDisplayNameImpl.java 516881 2007-03-11 10:34:21Z ate $ - * + * */ public class WebAppDisplayNameImpl extends DisplayNameImpl { - /** - * Tells OJB which class to use to materialize. - */ - protected String ojbConcreteClass = WebAppDisplayNameImpl.class.getName(); - + /** + * Tells OJB which class to use to materialize. + */ + protected String ojbConcreteClass = WebAppDisplayNameImpl.class.getName(); + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/ContentTypeImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/ContentTypeImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/ContentTypeImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,16 +33,18 @@ * * @author Scott T. Weaver * @version $Id: ContentTypeImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class ContentTypeImpl implements ContentTypeComposite, Serializable { private String contentType; + protected Collection portletModes; + /** - * field that represents a FK relationship to the parent portlet. - * Required by some O/R tools like OJB. + * field that represents a FK relationship to the parent portlet. Required + * by some O/R tools like OJB. */ protected long portletId; @@ -106,7 +108,9 @@ return hasher.toHashCode(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.portlet.ContentTypeComposite#addPortletMode(javax.portlet.PortletMode) */ public void addPortletMode(PortletMode mode) @@ -129,7 +133,9 @@ portletModes = modes; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.portlet.ContentTypeComposite#supportsPortletMode(javax.portlet.PortletMode) */ public boolean supportsPortletMode(PortletMode mode) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/ContentTypeSetImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/ContentTypeSetImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/ContentTypeSetImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,9 +27,10 @@ import org.apache.pluto.om.portlet.ContentType; /** - * @author Scott T. Weaver + * @author Scott T. Weaver */ -public class ContentTypeSetImpl implements ContentTypeSetComposite, Serializable +public class ContentTypeSetImpl implements ContentTypeSetComposite, + Serializable { protected Collection innerCollection; @@ -46,26 +47,20 @@ public boolean supportsPortletMode(PortletMode mode) { - // Always support "VIEW". Some portlet vendors do not indicate view + // Always support "VIEW". Some portlet vendors do not indicate view // in the deployment descriptor. - if(mode.equals(PortletMode.VIEW)) - { - return true; - } - + if (mode.equals(PortletMode.VIEW)) { return true; } + Iterator itr = innerCollection.iterator(); while (itr.hasNext()) { ContentType p = (ContentType) itr.next(); - if (p.supportsPortletMode(mode)) - { - return true; - } + if (p.supportsPortletMode(mode)) { return true; } } - + return false; } - + /** * @see org.apache.pluto.om.portlet.ContentTypeSet#get(java.lang.String) */ @@ -75,10 +70,7 @@ while (itr.hasNext()) { ContentType p = (ContentType) itr.next(); - if (p.getContentType().equals(contentType)) - { - return p; - } + if (p.getContentType().equals(contentType)) { return p; } } return null; @@ -90,7 +82,7 @@ public boolean add(Object o) { ContentType cType = (ContentType) o; - + return innerCollection.add(cType); } @@ -100,7 +92,7 @@ public boolean remove(Object o) { ContentType cType = (ContentType) o; - + return innerCollection.remove(cType); } @@ -116,7 +108,7 @@ * @see org.apache.pluto.om.portlet.ContentTypeSet#iterator() */ public Iterator iterator() - { + { return innerCollection.iterator(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/CustomPortletModeImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/CustomPortletModeImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/CustomPortletModeImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.om.portlet.impl; import javax.portlet.PortletMode; @@ -22,16 +22,17 @@ public class CustomPortletModeImpl implements CustomPortletMode { + /** The application id. */ - protected long appId; + protected long appId; - protected long id; + protected long id; - protected String customName; + protected String customName; - protected String mappedName; + protected String mappedName; - protected String description; + protected String description; protected transient PortletMode customMode; @@ -46,10 +47,9 @@ if (customName == null) { throw new IllegalArgumentException("CustomName is required"); - } else if (this.customName != null) - { - throw new IllegalStateException("CustomName already set"); } + else if (this.customName != null) { throw new IllegalStateException( + "CustomName already set"); } this.customName = customName.toLowerCase(); } @@ -63,7 +63,8 @@ if (this.mappedName != null || this.mappedMode != null) { throw new IllegalArgumentException("MappedName already set"); - } else if (mappedName != null) + } + else if (mappedName != null) { this.mappedName = mappedName.toLowerCase(); } @@ -85,7 +86,8 @@ if (mappedName != null) { mappedMode = new PortletMode(mappedName); - } else + } + else { mappedMode = getCustomMode(); } @@ -106,7 +108,8 @@ public boolean equals(Object object) { if (object instanceof CustomPortletModeImpl) - return customName.equals(((CustomPortletModeImpl) object).customName); + return customName + .equals(((CustomPortletModeImpl) object).customName); else return false; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/CustomWindowStateImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/CustomWindowStateImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/CustomWindowStateImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.om.portlet.impl; import javax.portlet.WindowState; @@ -22,16 +22,17 @@ public class CustomWindowStateImpl implements CustomWindowState { + /** The application id. */ - protected long appId; + protected long appId; - protected long id; + protected long id; - protected String customName; + protected String customName; - protected String mappedName; + protected String mappedName; - protected String description; + protected String description; protected transient WindowState customState; @@ -47,10 +48,8 @@ { throw new IllegalArgumentException("CustomName is required"); } - else if ( this.customName != null ) - { - throw new IllegalStateException("CustomName already set"); - } + else if (this.customName != null) { throw new IllegalStateException( + "CustomName already set"); } this.customName = customName.toLowerCase(); } @@ -61,11 +60,11 @@ public void setMappedName(String mappedName) { - if ( this.mappedName != null || this.mappedState != null ) + if (this.mappedName != null || this.mappedState != null) { throw new IllegalArgumentException("MappedName already set"); } - else if ( mappedName != null ) + else if (mappedName != null) { this.mappedName = mappedName.toLowerCase(); } @@ -87,7 +86,8 @@ if (mappedName != null) { mappedState = new WindowState(mappedName); - } else + } + else { mappedState = getCustomState(); } @@ -108,7 +108,8 @@ public boolean equals(Object object) { if (object instanceof CustomWindowStateImpl) - return customName.equals(((CustomWindowStateImpl) object).customName); + return customName + .equals(((CustomWindowStateImpl) object).customName); else return false; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/FragmentPortletDefinition.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/FragmentPortletDefinition.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/FragmentPortletDefinition.java 2008-05-16 01:54:54 UTC (rev 940) @@ -45,21 +45,23 @@ import org.apache.pluto.om.servlet.ServletDefinition; /** - * Per-request wrapper for a PortletDefinition that allows for - * the supplementaton of psml-based portlet Preferences. - * The Preferences are transparently accessed as default Preferences in - * the exact same way default Preferences that are provided via the portelt.xml - * are. + * Per-request wrapper for a PortletDefinition that allows for the + * supplementaton of psml-based portlet Preferences. The Preferences are + * transparently accessed as default Preferences in the exact same way default + * Preferences that are provided via the portelt.xml are. * * @author Scott T. Weaver - * + * */ public class FragmentPortletDefinition implements PortletDefinitionComposite { + private final PortletDefinitionComposite portletDefinition; + private final Fragment fragment; - - public FragmentPortletDefinition(PortletDefinitionComposite portletDefinition, Fragment fragment) + + public FragmentPortletDefinition( + PortletDefinitionComposite portletDefinition, Fragment fragment) { this.portletDefinition = portletDefinition; this.fragment = fragment; @@ -90,14 +92,17 @@ portletDefinition.addDisplayName(locale, displayName); } - public ParameterComposite addInitParameter(String name, String value, DescriptionSet description) + public ParameterComposite addInitParameter(String name, String value, + DescriptionSet description) { return portletDefinition.addInitParameter(name, value, description); } - public ParameterComposite addInitParameter(String name, String value, String description, Locale locale) + public ParameterComposite addInitParameter(String name, String value, + String description, Locale locale) { - return portletDefinition.addInitParameter(name, value, description, locale); + return portletDefinition.addInitParameter(name, value, description, + locale); } public ParameterComposite addInitParameter(String name, String value) @@ -110,7 +115,8 @@ portletDefinition.addLanguage(lang); } - public void addLanguage(String title, String shortTitle, String keywords, Locale locale) + public void addLanguage(String title, String shortTitle, String keywords, + Locale locale) { portletDefinition.addLanguage(title, shortTitle, keywords, locale); } @@ -227,7 +233,9 @@ public PreferenceSet getPreferenceSet() { - return new FragmentPortletPreferenceSet((PreferenceSetComposite) portletDefinition.getPreferenceSet(), fragment); + return new FragmentPortletPreferenceSet( + (PreferenceSetComposite) portletDefinition.getPreferenceSet(), + fragment); } public String getPreferenceValidatorClassname() @@ -339,7 +347,7 @@ { portletDefinition.store(); } - + public String getJetspeedSecurityConstraint() { return portletDefinition.getJetspeedSecurityConstraint(); @@ -349,5 +357,5 @@ { portletDefinition.setJetspeedSecurityConstraint(constraint); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletApplicationDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletApplicationDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletApplicationDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -47,22 +47,25 @@ import org.apache.pluto.om.servlet.WebApplicationDefinition; /** - * + * * @author Paul Spencer * @author Scott T. Weaver - * @version $Id: PortletApplicationDefinitionImpl.java 553014 2007-07-03 23:10:53Z ate $ + * @version $Id: PortletApplicationDefinitionImpl.java 553014 2007-07-03 + * 23:10:53Z ate $ * @since 1.0 */ -public class PortletApplicationDefinitionImpl implements MutablePortletApplication, Serializable, Support -{ +public class PortletApplicationDefinitionImpl implements + MutablePortletApplication, Serializable, Support +{ + /** - * Unique id of the application. This serves as the primary key in database + * Unique id of the application. This serves as the primary key in database * and in any caching of this object. */ private Long id; - + private JetspeedLongObjectID oid; - + /** Holds value of property name. */ private String name; @@ -74,15 +77,16 @@ /** WebApplication property */ private transient WebApplicationDefinition webApplication; + /** PK of this Portlet Application's Web Application */ protected long webApplicationId; - + /** Metadata property */ private Collection metadataFields = null; /** Metadata property */ private Collection services = new ArrayList(); - + /** Description */ private String description; @@ -90,34 +94,41 @@ /** User attribute refs collection. */ private Collection userAttributeRefs; - + /** User attributes collection. */ private Collection userAttributes; - + private PortletDefinitionListImpl listWrapper = new PortletDefinitionListImpl(); private int applicationType = MutablePortletApplication.WEBAPP; - + private String checksum = "0"; + private long checksumLong = -1; - + private List customPortletModes; + private List customWindowStates; - + private String jetspeedSecurityConstraint = null; - + private transient Map supportedCustomModes; + private transient Map supportedCustomStates; + private transient Map mappedCustomModes; - private transient Map mappedCustomStates; + + private transient Map mappedCustomStates; + private transient Collection supportedPortletModes; + private transient Collection supportedWindowStates; - + /** Creates a new instance of BaseApplication */ public PortletApplicationDefinitionImpl() { portlets = new ArrayList(); - userAttributes = new ArrayList(); + userAttributes = new ArrayList(); userAttributeRefs = new ArrayList(); customPortletModes = new ArrayList(); customWindowStates = new ArrayList(); @@ -128,7 +139,7 @@ */ public ObjectID getId() { - if ( oid == null && id != null ) + if (oid == null && id != null) { oid = new JetspeedLongObjectID(id); } @@ -213,7 +224,7 @@ */ public void addPortletDefinition(PortletDefinition pd) { - ((PortletDefinitionComposite) pd).setPortletApplicationDefinition(this); + ((PortletDefinitionComposite) pd).setPortletApplicationDefinition(this); portlets.add(pd); } @@ -230,7 +241,7 @@ */ public PortletDefinition getPortletDefinitionByName(String name) { - listWrapper.setInnerCollection(portlets); + listWrapper.setInnerCollection(portlets); return listWrapper.get(name); } @@ -239,10 +250,11 @@ */ public void setPortletDefinitionList(PortletDefinitionList portlets) { - this.portlets = ((PortletDefinitionListImpl) portlets).getInnerCollection(); + this.portlets = ((PortletDefinitionListImpl) portlets) + .getInnerCollection(); } - /** + /** * @see org.apache.jetspeed.om.common.portlet.MutablePortletApplication#setUserAttributeRefs(java.util.Collection) */ public void setUserAttributeRefs(Collection userAttributeRefs) @@ -250,7 +262,7 @@ this.userAttributeRefs = userAttributeRefs; } - /** + /** * @see org.apache.jetspeed.om.common.portlet.MutablePortletApplication#getUserAttributeRefs() */ public Collection getUserAttributeRefs() @@ -258,7 +270,7 @@ return this.userAttributeRefs; } - /** + /** * @see org.apache.jetspeed.om.common.portlet.MutablePortletApplication#addUserAttributeRef(org.apache.jetspeed.om.common.UserAttributeRef) */ public void addUserAttributeRef(UserAttributeRef userAttributeRef) @@ -266,16 +278,17 @@ userAttributeRefs.add(userAttributeRef); } - /** + /** * @see org.apache.jetspeed.om.common.portlet.MutablePortletApplication#addUserAttribute(org.apache.jetspeed.om.common.UserAttribute) */ public void addUserAttribute(UserAttribute userAttribute) { userAttributes.add(userAttribute); } - - /** - * @see org.apache.jetspeed.om.common.portlet.MutablePortletApplication#addUserAttribute(java.lang.String, java.lang.String) + + /** + * @see org.apache.jetspeed.om.common.portlet.MutablePortletApplication#addUserAttribute(java.lang.String, + * java.lang.String) */ public void addUserAttribute(String userName, String description) { @@ -284,8 +297,8 @@ userAttribute.setDescription(description); userAttributes.add(userAttribute); } - - /** + + /** * @see org.apache.jetspeed.om.common.portlet.MutablePortletApplication#setUserAttributes(java.util.Collection) */ public void setUserAttributes(Collection userAttributes) @@ -293,7 +306,7 @@ this.userAttributes = userAttributes; } - /** + /** * @see org.apache.jetspeed.om.common.portlet.MutablePortletApplication#getUserAttributes() */ public Collection getUserAttributes() @@ -338,14 +351,14 @@ */ public GenericMetadata getMetadata() { - if(metadataFields == null) + if (metadataFields == null) { metadataFields = new ArrayList(); } - - GenericMetadata metadata = new PortletApplicationMetadataImpl(); - metadata.setFields(metadataFields); - + + GenericMetadata metadata = new PortletApplicationMetadataImpl(); + metadata.setFields(metadataFields); + return metadata; } @@ -354,7 +367,7 @@ */ public void setMetadata(GenericMetadata metadata) { - this.metadataFields = metadata.getFields(); + this.metadataFields = metadata.getFields(); } /** @@ -373,15 +386,19 @@ this.metadataFields = metadataFields; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.portlet.PortletApplication#getJetspeedServices() */ public Collection getJetspeedServices() { return services; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.portlet.MutablePortletApplication#addJetspeedService(org.apache.jetspeed.om.common.JetspeedServiceReference) */ public void addJetspeedService(JetspeedServiceReference service) @@ -391,20 +408,22 @@ public long getChecksum() { - if(checksumLong == -1) + if (checksumLong == -1) { checksumLong = Long.parseLong(checksum); } return checksumLong; } - + public void setChecksum(long checksum) { this.checksumLong = checksum; this.checksum = Long.toString(checksum); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.Support#postLoad(java.lang.Object) */ public void postLoad(Object parameter) throws Exception @@ -420,20 +439,20 @@ { return customPortletModes; } - + public void addCustomPortletMode(CustomPortletMode customPortletMode) { // clear transient cache supportedPortletModes = null; supportedCustomModes = null; mappedCustomModes = null; - - if ( !customPortletModes.contains(customPortletMode) ) + + if (!customPortletModes.contains(customPortletMode)) { customPortletModes.add(customPortletMode); } } - + public void setCustomPortletModes(Collection customPortletModes) { // clear transient cache @@ -442,26 +461,24 @@ mappedCustomModes = null; this.customPortletModes.clear(); - - if ( customPortletModes != null ) + + if (customPortletModes != null) { this.customPortletModes.addAll(customPortletModes); } } - + public PortletMode getMappedPortletMode(PortletMode mode) { - if ( JetspeedActions.getStandardPortletModes().contains(mode) ) + if (JetspeedActions.getStandardPortletModes().contains(mode)) { return mode; } - else if ( getSupportedPortletModes().contains(mode) ) - { - return (PortletMode)mappedCustomModes.get(mode); - } + else if (getSupportedPortletModes().contains(mode)) { return (PortletMode) mappedCustomModes + .get(mode); } return null; } - + public PortletMode getCustomPortletMode(PortletMode mode) { if (JetspeedActions.getStandardPortletModes().contains(mode)) @@ -472,30 +489,36 @@ { // make sure transient cache is setup getSupportedPortletModes(); - return (PortletMode)supportedCustomModes.get(mode); + return (PortletMode) supportedCustomModes.get(mode); } - return null; + return null; } - + public Collection getSupportedPortletModes() { - if ( supportedPortletModes == null ) + if (supportedPortletModes == null) { - ArrayList list = new ArrayList(JetspeedActions.getStandardPortletModes()); + ArrayList list = new ArrayList(JetspeedActions + .getStandardPortletModes()); supportedCustomModes = new HashMap(); mappedCustomModes = new HashMap(); - - if ( customPortletModes.size() > 0 ) + + if (customPortletModes.size() > 0) { Iterator iter = customPortletModes.iterator(); - while ( iter.hasNext() ) + while (iter.hasNext()) { - CustomPortletMode customMode = (CustomPortletMode)iter.next(); - if ( !list.contains(customMode.getCustomMode()) && JetspeedActions.getExtendedPortletModes().contains(customMode.getMappedMode()) ) + CustomPortletMode customMode = (CustomPortletMode) iter + .next(); + if (!list.contains(customMode.getCustomMode()) + && JetspeedActions.getExtendedPortletModes() + .contains(customMode.getMappedMode())) { list.add(customMode.getCustomMode()); - supportedCustomModes.put(customMode.getMappedMode(), customMode.getCustomMode()); - mappedCustomModes.put(customMode.getCustomMode(), customMode.getMappedMode()); + supportedCustomModes.put(customMode.getMappedMode(), + customMode.getCustomMode()); + mappedCustomModes.put(customMode.getCustomMode(), + customMode.getMappedMode()); } } } @@ -503,25 +526,25 @@ } return supportedPortletModes; } - + public Collection getCustomWindowStates() { return customWindowStates; } - + public void addCustomWindowState(CustomWindowState customWindowState) { // clear transient cache supportedWindowStates = null; supportedCustomStates = null; mappedCustomStates = null; - - if ( !customWindowStates.contains(customWindowState) ) + + if (!customWindowStates.contains(customWindowState)) { customWindowStates.add(customWindowState); } } - + public void setCustomWindowStates(Collection customWindowStates) { // clear transient cache @@ -531,25 +554,23 @@ this.customWindowStates.clear(); - if ( customWindowStates != null ) + if (customWindowStates != null) { this.customWindowStates.addAll(customWindowStates); } } - + public WindowState getMappedWindowState(WindowState state) { - if (JetspeedActions.getStandardWindowStates().contains(state) ) + if (JetspeedActions.getStandardWindowStates().contains(state)) { return state; } - else if ( getSupportedWindowStates().contains(state) ) - { - return (WindowState)mappedCustomStates.get(state); - } + else if (getSupportedWindowStates().contains(state)) { return (WindowState) mappedCustomStates + .get(state); } return null; } - + public WindowState getCustomWindowState(WindowState state) { if (JetspeedActions.getStandardWindowStates().contains(state)) @@ -560,30 +581,36 @@ { // make sure transient cache is setup getSupportedWindowStates(); - return (WindowState)supportedCustomStates.get(state); + return (WindowState) supportedCustomStates.get(state); } - return null; + return null; } - + public Collection getSupportedWindowStates() { - if ( supportedWindowStates == null ) + if (supportedWindowStates == null) { - ArrayList list = new ArrayList(JetspeedActions.getStandardWindowStates()); + ArrayList list = new ArrayList(JetspeedActions + .getStandardWindowStates()); supportedCustomStates = new HashMap(); mappedCustomStates = new HashMap(); - - if ( customWindowStates.size() > 0 ) + + if (customWindowStates.size() > 0) { Iterator iter = customWindowStates.iterator(); - while ( iter.hasNext() ) + while (iter.hasNext()) { - CustomWindowState customState = (CustomWindowState)iter.next(); - if ( !list.contains(customState.getCustomState()) && JetspeedActions.getExtendedWindowStates().contains(customState.getMappedState()) ) + CustomWindowState customState = (CustomWindowState) iter + .next(); + if (!list.contains(customState.getCustomState()) + && JetspeedActions.getExtendedWindowStates() + .contains(customState.getMappedState())) { list.add(customState.getCustomState()); - supportedCustomStates.put(customState.getMappedState(),customState.getCustomState()); - mappedCustomStates.put(customState.getCustomState(),customState.getMappedState()); + supportedCustomStates.put(customState.getMappedState(), + customState.getCustomState()); + mappedCustomStates.put(customState.getCustomState(), + customState.getMappedState()); } } } @@ -592,7 +619,9 @@ return supportedWindowStates; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#getJetspeedSecurityConstraint() */ public String getJetspeedSecurityConstraint() @@ -600,14 +629,16 @@ return this.jetspeedSecurityConstraint; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#setJetspeedSecurityConstraint(java.lang.String) */ public void setJetspeedSecurityConstraint(String constraint) { this.jetspeedSecurityConstraint = constraint; } - + public boolean isLayoutApplication() { if (this.getMetadata() != null) @@ -615,12 +646,9 @@ Collection c = this.getMetadata().getFields("layout-app"); if (c != null) { - if (!c.isEmpty()) - { - return true; - } + if (!c.isEmpty()) { return true; } } } return false; - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletApplicationLocalizedFieldImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletApplicationLocalizedFieldImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletApplicationLocalizedFieldImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,8 +25,9 @@ * PortletApplication specific class for LocalizedFields * * @author Jeremy Ford - * @version $Id: PortletApplicationLocalizedFieldImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: PortletApplicationLocalizedFieldImpl.java 516448 2007-03-09 + * 16:25:47Z ate $ + * */ public class PortletApplicationLocalizedFieldImpl extends LocalizedFieldImpl { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletApplicationMetadataImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletApplicationMetadataImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletApplicationMetadataImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,13 +28,18 @@ * PortletApplication specific class for Metadata * * @author Jeremy Ford - * @version $Id: PortletApplicationMetadataImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: PortletApplicationMetadataImpl.java 516448 2007-03-09 16:25:47Z + * ate $ + * */ public class PortletApplicationMetadataImpl extends GenericMetadataImpl { - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.GenericMetadata#addField(java.util.Locale, java.lang.String, java.lang.String) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.GenericMetadata#addField(java.util.Locale, + * java.lang.String, java.lang.String) */ public void addField(Locale locale, String name, String value) { @@ -42,14 +47,17 @@ field.setName(name); field.setValue(value); field.setLocale(locale); - + addField(field); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.GenericMetadata#createLocalizedField() */ - public LocalizedField createLocalizedField() { + public LocalizedField createLocalizedField() + { return new PortletApplicationLocalizedFieldImpl(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -82,58 +82,83 @@ * * @author Scott T. Weaver * @version $Id: PortletDefinitionImpl.java 517124 2007-03-12 08:10:25Z ate $ - * + * */ -public class PortletDefinitionImpl implements PortletDefinitionComposite, PreferencesValidatorFactory, Serializable, Support +public class PortletDefinitionImpl implements PortletDefinitionComposite, + PreferencesValidatorFactory, Serializable, Support { + /** - * This is a static instance of the PortletREgistry that can be used by - * all instances of the PortletDefinitionImpl to support the + * This is a static instance of the PortletREgistry that can be used by all + * instances of the PortletDefinitionImpl to support the * PortletDefintionCtrl.store() method. * */ protected static PortletRegistry registry; - protected static PortletFactory portletFactory; - + + protected static PortletFactory portletFactory; + private Long id; + private JetspeedLongObjectID oid; + private String className; + private String name; + private String portletIdentifier; + private Collection languageSet = null; + private LanguageSetImpl langListWrapper = new LanguageSetImpl(); + private Collection parameterSet; + private ParameterSetImpl paramListWrapper = new PortletParameterSetImpl(); + private Collection securityRoleRefSet; + private SecurityRoleRefSetImpl secListWrapper = new SecurityRoleRefSetImpl(); + /** User attribute set. * */ - //private Collection userAttributeSet; + // private Collection userAttributeSet; /** User attribute ref set. * */ - //private Collection userAttributeRefSet; + // private Collection userAttributeRefSet; private String preferenceValidatorClassname; + private Collection displayNames; + private DisplayNameSetImpl DNListWrapper = new DisplayNameSetImpl(); + private Collection descriptions; - private DescriptionSetImpl descListWrapper = new DescriptionSetImpl(DescriptionImpl.TYPE_PORTLET); + + private DescriptionSetImpl descListWrapper = new DescriptionSetImpl( + DescriptionImpl.TYPE_PORTLET); + private String resourceBundle; + private ArrayList supportedLocales; private Collection contentTypes; + private ContentTypeSetImpl ctListWrapper = new ContentTypeSetImpl(); + protected List portletEntities; /** PortletApplicationDefinition this PortletDefinition belongs to */ private MutablePortletApplication app; protected long appId; + private String expirationCache; /** Metadata property */ private Collection metadataFields = null; + private PrefsPreferenceSetImpl preferenceSet; private String jetspeedSecurityConstraint = null; - + public PortletDefinitionImpl() { super(); @@ -141,14 +166,15 @@ { parameterSet = new ArrayList(); securityRoleRefSet = new ArrayList(); - //userAttributeSet = new ArrayList(); - //userAttributeRefSet = new ArrayList(); + // userAttributeSet = new ArrayList(); + // userAttributeRefSet = new ArrayList(); contentTypes = new ArrayList(); - supportedLocales= new ArrayList(); + supportedLocales = new ArrayList(); } catch (RuntimeException e) { -// System.out.println("Failed to fully construct Portlet Definition"); + // System.out.println("Failed to fully construct Portlet + // Definition"); e.printStackTrace(); } } @@ -158,7 +184,7 @@ */ public ObjectID getId() { - if ( oid == null && id != null ) + if (oid == null && id != null) { oid = new JetspeedLongObjectID(id); } @@ -186,12 +212,12 @@ */ public LanguageSet getLanguageSet() { - if ( languageSet != null ) + if (languageSet != null) { langListWrapper.setInnerCollection(languageSet); } langListWrapper.setClassLoader(getPortletClassLoader()); - + return langListWrapper; } @@ -222,12 +248,10 @@ { if (preferenceSet == null) { - - if(app == null) - { - throw new IllegalStateException("Portlet Application must be defined before preferences can be accessed"); - } - + + if (app == null) { throw new IllegalStateException( + "Portlet Application must be defined before preferences can be accessed"); } + Preferences prefNode = PrefsPreference.createPrefenceNode(this); preferenceSet = new PrefsPreferenceSetImpl(prefNode, this); } @@ -246,7 +270,7 @@ /** * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#setPreferenceSet(org.apache.pluto.om.common.PreferenceSet) */ - public void setPreferenceSet( PreferenceSet preferences ) + public void setPreferenceSet(PreferenceSet preferences) { this.preferenceSet = (PrefsPreferenceSetImpl) preferences; } @@ -290,17 +314,15 @@ */ public ClassLoader getPortletClassLoader() { - if ( portletFactory != null ) - { - return portletFactory.getPortletApplicationClassLoader(app); - } + if (portletFactory != null) { return portletFactory + .getPortletApplicationClassLoader(app); } return null; } /** * @see org.apache.pluto.om.portlet.PortletDefinitionCtrl#setId(java.lang.String) */ - public void setId( String oid ) + public void setId(String oid) { throw new UnsupportedOperationException(); } @@ -308,7 +330,7 @@ /** * @see org.apache.pluto.om.portlet.PortletDefinitionCtrl#setClassName(java.lang.String) */ - public void setClassName( String className ) + public void setClassName(String className) { this.className = className; } @@ -316,7 +338,7 @@ /** * @see org.apache.pluto.om.portlet.PortletDefinitionCtrl#setName(java.lang.String) */ - public void setName( String name ) + public void setName(String name) { this.name = name; } @@ -324,16 +346,16 @@ /** * @see org.apache.pluto.om.portlet.PortletDefinitionCtrl#setPortletClassLoader(java.lang.ClassLoader) */ - public void setPortletClassLoader( ClassLoader loader ) + public void setPortletClassLoader(ClassLoader loader) { - // no-op: ClassLoader is only stored in the PortletFactory - ; + // no-op: ClassLoader is only stored in the PortletFactory + ; } /** * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addLanguage(org.apache.pluto.om.common.Language) */ - public void addLanguage( Language lang ) + public void addLanguage(Language lang) { if (languageSet == null) { @@ -342,49 +364,54 @@ langListWrapper.setInnerCollection(languageSet); langListWrapper.add(lang); } - + /** - * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addLanguage(java.lang.String, java.lang.String, java.lang.String, java.util.Locale) + * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addLanguage(java.lang.String, + * java.lang.String, java.lang.String, java.util.Locale) */ - public void addLanguage(String title, String shortTitle, String keywords, Locale locale) + public void addLanguage(String title, String shortTitle, String keywords, + Locale locale) { LanguageImpl lang = new LanguageImpl(); lang.setTitle(title); lang.setShortTitle(shortTitle); lang.setKeywords(keywords); lang.setLocale(locale); - + addLanguage(lang); } /** * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#setContentTypeSet(org.apache.pluto.om.portlet.ContentTypeSet) */ - public void setContentTypeSet( ContentTypeSet contentTypes ) + public void setContentTypeSet(ContentTypeSet contentTypes) { - this.contentTypes = ((ContentTypeSetImpl) contentTypes).getInnerCollection(); + this.contentTypes = ((ContentTypeSetImpl) contentTypes) + .getInnerCollection(); } /** * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#setInitParameterSet(org.apache.pluto.om.common.ParameterSet) */ - public void setInitParameterSet( ParameterSet parameters ) + public void setInitParameterSet(ParameterSet parameters) { - this.parameterSet = ((ParameterSetImpl) parameters).getInnerCollection(); + this.parameterSet = ((ParameterSetImpl) parameters) + .getInnerCollection(); } /** * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#setInitSecurityRoleRefSet(org.apache.pluto.om.common.SecurityRoleRefSet) */ - public void setInitSecurityRoleRefSet( SecurityRoleRefSet securityRefs ) + public void setInitSecurityRoleRefSet(SecurityRoleRefSet securityRefs) { - this.securityRoleRefSet = ((SecurityRoleRefSetImpl) securityRefs).getInnerCollection(); + this.securityRoleRefSet = ((SecurityRoleRefSetImpl) securityRefs) + .getInnerCollection(); } /** * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#setLanguageSet(org.apache.pluto.om.common.LanguageSet) */ - public void setLanguageSet( LanguageSet languages ) + public void setLanguageSet(LanguageSet languages) { this.languageSet = ((LanguageSetImpl) languages).getInnerCollection(); } @@ -395,38 +422,38 @@ /* * public void addUserAttribute(UserAttribute userAttribute) { * this.userAttributeSet.add(userAttribute); } - * + * *//** - * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#setUserAttributeSet(java.util.Collection) - */ + * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#setUserAttributeSet(java.util.Collection) + */ /* * public void setUserAttributeSet(Collection userAttributeSet) { * this.userAttributeSet = userAttributeSet; } - * + * *//** - * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#getUserAttributeSet() - */ + * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#getUserAttributeSet() + */ /* * public Collection getUserAttributeSet() { return this.userAttributeSet; } - * + * *//** - * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addUserAttributeRef(org.apache.jetspeed.om.common.UserAttributeRef) - */ + * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addUserAttributeRef(org.apache.jetspeed.om.common.UserAttributeRef) + */ /* * public void addUserAttributeRef(UserAttributeRef userAttributeRef) { * System.out.println("_______IN addUserAttributeRef"); * this.userAttributeRefSet.add(userAttributeRef); } - * + * *//** - * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#setUserAttributeSet(java.util.Collection) - */ + * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#setUserAttributeSet(java.util.Collection) + */ /* * public void setUserAttributeRefSet(Collection userAttributeRefSet) { * this.userAttributeRefSet = userAttributeRefSet; } - * + * *//** - * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#getUserAttributeRefSet() - */ + * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#getUserAttributeRefSet() + */ /* * public Collection getUserAttributeRefSet() { return * this.userAttributeRefSet; } @@ -435,7 +462,8 @@ * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#setInitParameter(java.lang.String, * java.lang.String, java.lang.String) */ - public ParameterComposite addInitParameter( String name, String value, DescriptionSet description ) + public ParameterComposite addInitParameter(String name, String value, + DescriptionSet description) { ParameterComposite pc = addInitParameter(name, value); pc.setDescriptionSet(description); @@ -446,14 +474,15 @@ * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addInitParameter(java.lang.String, * java.lang.String, java.lang.String, java.util.Locale) */ - public ParameterComposite addInitParameter( String name, String value, String description, Locale locale ) + public ParameterComposite addInitParameter(String name, String value, + String description, Locale locale) { ParameterComposite param = addInitParameter(name, value); param.addDescription(locale, description); return param; } - public void addInitParameter( Parameter parameter ) + public void addInitParameter(Parameter parameter) { parameterSet.add(parameter); } @@ -462,7 +491,7 @@ * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#setInitParameter(java.lang.String, * java.lang.String) */ - public ParameterComposite addInitParameter( String name, String value ) + public ParameterComposite addInitParameter(String name, String value) { paramListWrapper.setInnerCollection(parameterSet); return (ParameterComposite) paramListWrapper.add(name, value); @@ -471,7 +500,7 @@ /** * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#setExpirationCache(java.lang.String) */ - public void setExpirationCache( String cache ) + public void setExpirationCache(String cache) { expirationCache = cache; } @@ -479,21 +508,22 @@ /** * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addContentType(org.apache.pluto.om.portlet.ContentType) */ - public void addContentType( ContentType cType ) + public void addContentType(ContentType cType) { ctListWrapper.setInnerCollection(contentTypes); ctListWrapper.addContentType(cType); } - + /** - * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addContentType(java.lang.String, java.lang.String[]) + * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addContentType(java.lang.String, + * java.lang.String[]) */ public void addContentType(String contentType, Collection modes) { ContentTypeImpl ct = new ContentTypeImpl(); ct.setContentType(contentType); ct.setPortletModes(modes); - + addContentType(ct); } @@ -501,12 +531,13 @@ * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addPreference(java.lang.String, * java.util.Collection) */ - public PreferenceComposite addPreference( String name, String[] values ) + public PreferenceComposite addPreference(String name, String[] values) { - return (PreferenceComposite) ((PrefsPreferenceSetImpl) getPreferenceSet()).add(name, Arrays.asList(values)); + return (PreferenceComposite) ((PrefsPreferenceSetImpl) getPreferenceSet()) + .add(name, Arrays.asList(values)); } - public void setPortletIdentifier( String portletIdentifier ) + public void setPortletIdentifier(String portletIdentifier) { this.portletIdentifier = portletIdentifier; } @@ -519,7 +550,7 @@ /** * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#setPortletApplicationDefinition(org.apache.pluto.om.portlet.PortletApplicationDefinition) */ - public void setPortletApplicationDefinition( PortletApplicationDefinition pad ) + public void setPortletApplicationDefinition(PortletApplicationDefinition pad) { app = (MutablePortletApplication) pad; } @@ -527,18 +558,16 @@ /** * @see java.lang.Object#equals(java.lang.Object) */ - public boolean equals( Object obj ) + public boolean equals(Object obj) { if (obj != null && obj.getClass().equals(getClass())) { PortletDefinitionImpl pd = (PortletDefinitionImpl) obj; boolean sameId = (id != null && pd.id != null && id.equals(pd.id)); - if (sameId) - { - return true; - } + if (sameId) { return true; } boolean sameAppId = (appId == pd.appId); - boolean sameName = (pd.getName() != null && name != null && pd.getName().equals(name)); + boolean sameName = (pd.getName() != null && name != null && pd + .getName().equals(name)); return sameName && sameAppId; } return false; @@ -553,9 +582,9 @@ hasher.append(name); if (app != null) { - if ( getId() != null ) + if (getId() != null) { - hasher.append(getId().toString()); + hasher.append(getId().toString()); } hasher.append(app.getName()); } @@ -581,7 +610,7 @@ /** * @see org.apache.pluto.om.portlet.PortletDefinition#getDescription(java.util.Locale) */ - public Description getDescription( Locale arg0 ) + public Description getDescription(Locale arg0) { if (descriptions != null) { @@ -594,7 +623,7 @@ /** * @see org.apache.pluto.om.portlet.PortletDefinition#getDisplayName(java.util.Locale) */ - public DisplayName getDisplayName( Locale arg0 ) + public DisplayName getDisplayName(Locale arg0) { if (displayNames != null) { @@ -607,7 +636,7 @@ /** * @see org.apache.pluto.om.portlet.PortletDefinitionCtrl#setDescriptions(org.apache.pluto.om.common.DescriptionSet) */ - public void setDescriptions( DescriptionSet arg0 ) + public void setDescriptions(DescriptionSet arg0) { this.descriptions = ((DescriptionSetImpl) arg0).getInnerCollection(); } @@ -615,7 +644,7 @@ /** * @see org.apache.pluto.om.portlet.PortletDefinitionCtrl#setDisplayNames(org.apache.pluto.om.common.DisplayNameSet) */ - public void setDisplayNames( DisplayNameSet arg0 ) + public void setDisplayNames(DisplayNameSet arg0) { this.displayNames = ((DisplayNameSetImpl) arg0).getInnerCollection(); } @@ -628,13 +657,10 @@ * @return Localized text string of the display name or null * if no DisplayName exists for this locale */ - public String getDisplayNameText( Locale locale ) + public String getDisplayNameText(Locale locale) { DisplayName dn = getDisplayName(locale); - if (dn != null) - { - return dn.getDisplayName(); - } + if (dn != null) { return dn.getDisplayName(); } return null; } @@ -646,16 +672,13 @@ * @return Localized text string of the display name or null * if no Description exists for this locale */ - public String getDescriptionText( Locale locale ) + public String getDescriptionText(Locale locale) { Description desc = getDescription(locale); - if (desc != null) - { - return desc.getDescription(); - } + if (desc != null) { return desc.getDescription(); } return null; } - + public DescriptionSet getDescriptionSet() { return this.descListWrapper; @@ -665,7 +688,7 @@ * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addDescription(java.util.Locale, * java.lang.String) */ - public void addDescription( Locale locale, String description ) + public void addDescription(Locale locale, String description) { if (descriptions == null) { @@ -678,7 +701,7 @@ descListWrapper.addDescription(descObj); } - public void addDescription( Description description ) + public void addDescription(Description description) { if (descriptions == null) { @@ -692,7 +715,7 @@ * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addDisplayName(java.util.Locale, * java.lang.String) */ - public void addDisplayName( Locale locale, String displayName ) + public void addDisplayName(Locale locale, String displayName) { if (displayNames == null) { @@ -705,7 +728,7 @@ DNListWrapper.addDisplayName(dn); } - public void addDisplayName( DisplayName displayName ) + public void addDisplayName(DisplayName displayName) { if (displayNames == null) { @@ -714,10 +737,10 @@ DNListWrapper.setInnerCollection(displayNames); DNListWrapper.addDisplayName(displayName); } - + public DisplayNameSet getDisplayNameSet() { - if ( displayNames != null ) + if (displayNames != null) { DNListWrapper.setInnerCollection(displayNames); } @@ -735,7 +758,7 @@ */ public void store() throws IOException { - if(registry != null) + if (registry != null) { try { @@ -743,14 +766,16 @@ } catch (RegistryException e) { - IOException ioe = new IOException("Failed to store portlet definition: "+e.getMessage()); + IOException ioe = new IOException( + "Failed to store portlet definition: " + e.getMessage()); ioe.initCause(e); } } else { - throw new IllegalStateException("The portlet registry for PortletDefinitionImpl has not been set. "+ - "Please invoke PortletDefinitionImpl.setPortletRegistry before invoking the store() method."); + throw new IllegalStateException( + "The portlet registry for PortletDefinitionImpl has not been set. " + + "Please invoke PortletDefinitionImpl.setPortletRegistry before invoking the store() method."); } } @@ -772,9 +797,9 @@ *

      * * @param string - * + * */ - public void setPreferenceValidatorClassname( String string ) + public void setPreferenceValidatorClassname(String string) { preferenceValidatorClassname = string; } @@ -783,7 +808,7 @@ * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addPreference(org.apache.pluto.om.common.Preference) * @param preference */ - public void addPreference( Preference preference ) + public void addPreference(Preference preference) { Iterator valueItr = preference.getValues(); ArrayList list = new ArrayList(); @@ -792,8 +817,8 @@ list.add(valueItr.next()); } - PreferenceComposite newPref = (PreferenceComposite) ((PreferenceSetComposite) getPreferenceSet()).add( - preference.getName(), list); + PreferenceComposite newPref = (PreferenceComposite) ((PreferenceSetComposite) getPreferenceSet()) + .add(preference.getName(), list); Iterator descItr = newPref.getDescriptions(); while (descItr.hasNext()) @@ -807,23 +832,24 @@ /** * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addSecurityRoleRef(org.apache.pluto.om.common.SecurityRoleRef) */ - public void addSecurityRoleRef( SecurityRoleRef securityRef ) + public void addSecurityRoleRef(SecurityRoleRef securityRef) { secListWrapper.setInnerCollection(securityRoleRefSet); secListWrapper.add(securityRef); } - + /** - * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addSecurityRoleRef(java.lang.String, java.lang.String) + * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#addSecurityRoleRef(java.lang.String, + * java.lang.String) */ public SecurityRoleRef addSecurityRoleRef(String roleName, String roleLink) { SecurityRoleRefImpl ref = new SecurityRoleRefImpl(); ref.setRoleName(roleName); ref.setRoleLink(roleLink); - + addSecurityRoleRef(ref); - + return ref; } @@ -846,7 +872,7 @@ /** * @see org.apache.jetspeed.om.common.portlet.MutablePortletApplication#setMetadata(org.apache.jetspeed.om.common.GenericMetadata) */ - public void setMetadata( GenericMetadata metadata ) + public void setMetadata(GenericMetadata metadata) { this.metadataFields = metadata.getFields(); } @@ -862,11 +888,11 @@ /** * @param collection */ - protected void setMetadataFields( Collection metadataFields ) + protected void setMetadataFields(Collection metadataFields) { this.metadataFields = metadataFields; } - + /** * @return */ @@ -882,7 +908,7 @@ { resourceBundle = string; } - + public Collection getSupportedLocales() { return supportedLocales; @@ -904,10 +930,13 @@ localeDef[i] = ""; } } - supportedLocales.add(new Locale(localeDef[0], localeDef[1], localeDef[2])); + supportedLocales.add(new Locale(localeDef[0], localeDef[1], + localeDef[2])); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.Support#postLoad(java.lang.Object) */ public void postLoad(Object parameter) throws Exception @@ -916,13 +945,14 @@ { langListWrapper.setResources(resourceBundle); } - + if (parameter instanceof ClassLoader) { // newly created PD from portlet.xml langListWrapper.setClassLoader((ClassLoader) parameter); // create supported locale languages and - // retrieve title, shortTitle and keywords from resourceBundle if defined + // retrieve title, shortTitle and keywords from resourceBundle if + // defined langListWrapper.postLoad(this.supportedLocales); } else @@ -931,7 +961,7 @@ langListWrapper.setClassLoader(getPortletClassLoader()); } } - + public static void setPortletRegistry(PortletRegistry registry) { PortletDefinitionImpl.registry = registry; @@ -944,14 +974,14 @@ public PreferencesValidator getPreferencesValidator() { - if ( portletFactory != null ) - { - return portletFactory.getPreferencesValidator(this); - } + if (portletFactory != null) { return portletFactory + .getPreferencesValidator(this); } return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#getJetspeedSecurityConstraint() */ public String getJetspeedSecurityConstraint() @@ -959,7 +989,9 @@ return this.jetspeedSecurityConstraint; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite#setJetspeedSecurityConstraint(java.lang.String) */ public void setJetspeedSecurityConstraint(String constraint) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionListImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionListImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionListImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,8 +21,6 @@ import java.util.Collection; import java.util.Iterator; - - import org.apache.pluto.om.common.ObjectID; import org.apache.pluto.om.portlet.PortletDefinition; import org.apache.pluto.om.portlet.PortletDefinitionList; @@ -33,9 +31,10 @@ * * @author Scott T. Weaver * @version $Id: PortletDefinitionListImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public class PortletDefinitionListImpl implements PortletDefinitionList, Serializable +public class PortletDefinitionListImpl implements PortletDefinitionList, + Serializable { protected Collection innerCollection; @@ -72,21 +71,21 @@ while (itr.hasNext()) { PortletDefinition pd = (PortletDefinition) itr.next(); - if (pd.getId().equals(id)) - { - return pd; - } + if (pd.getId().equals(id)) { return pd; } } return null; } /** - * Retrieves a PortletDefinition from this - * collection by the PortletDefinitions proper name - * @param name Proper name of PortletDefinition to locate. - * @return PortletDefinition matching name or null - * if no PortletDefinition within this PortletApplication has that name. + * Retrieves a PortletDefinition from this collection by the + * PortletDefinitions proper name + * + * @param name + * Proper name of PortletDefinition to locate. + * @return PortletDefinition matching name or + * null if no PortletDefinition within this + * PortletApplication has that name. */ public PortletDefinition get(String name) { @@ -94,10 +93,7 @@ while (itr.hasNext()) { PortletDefinition pd = (PortletDefinition) itr.next(); - if (pd.getName().equals(name)) - { - return pd; - } + if (pd.getName().equals(name)) { return pd; } } return null; @@ -108,7 +104,7 @@ */ public boolean add(Object o) { - PortletDefinition pd = (PortletDefinition) o; + PortletDefinition pd = (PortletDefinition) o; return innerCollection.add(pd); } @@ -117,7 +113,7 @@ */ public boolean remove(Object o) { - PortletDefinition pd = (PortletDefinition) o; + PortletDefinition pd = (PortletDefinition) o; return innerCollection.remove(pd); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionLocalizedFieldImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionLocalizedFieldImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionLocalizedFieldImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,8 +25,9 @@ * PortletDefinition specific class for LocalizedFields * * @author Jeremy Ford - * @version $Id: PortletDefinitionLocalizedFieldImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: PortletDefinitionLocalizedFieldImpl.java 516448 2007-03-09 + * 16:25:47Z ate $ + * */ public class PortletDefinitionLocalizedFieldImpl extends LocalizedFieldImpl { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionMetadataImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionMetadataImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/portlet/impl/PortletDefinitionMetadataImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,19 +22,22 @@ import org.apache.jetspeed.om.impl.GenericMetadataImpl; /** - * PortletDefinitionMetadataImpl - *
      - * PortletDefinition specific class for Metadata + * PortletDefinitionMetadataImpl
      PortletDefinition specific class for + * Metadata * * @author Jeremy Ford - * @version $Id: PortletDefinitionMetadataImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: PortletDefinitionMetadataImpl.java 516448 2007-03-09 16:25:47Z + * ate $ + * */ public class PortletDefinitionMetadataImpl extends GenericMetadataImpl { - /* (non-Javadoc) - * @see org.apache.jetspeed.om.common.GenericMetadata#addField(java.util.Locale, java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.om.common.GenericMetadata#addField(java.util.Locale, + * java.lang.String, java.lang.String) */ public void addField(Locale locale, String name, String value) { @@ -42,14 +45,17 @@ field.setName(name); field.setValue(value); field.setLocale(locale); - + addField(field); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.common.GenericMetadata#createLocalizedField() */ - public LocalizedField createLocalizedField() { + public LocalizedField createLocalizedField() + { return new PortletDefinitionLocalizedFieldImpl(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/preference/impl/FragmentPortletPreferenceSet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/preference/impl/FragmentPortletPreferenceSet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/preference/impl/FragmentPortletPreferenceSet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,26 +29,28 @@ import org.apache.pluto.om.common.Preference; /** - * This is a per-request wrapper for a PreferenceSet that allows - * the use of fragment-specified Preferences within a portlet instance - * in a page. + * This is a per-request wrapper for a PreferenceSet that allows the use of + * fragment-specified Preferences within a portlet instance in a page. * * @author Scott T. Weaver - * + * */ public class FragmentPortletPreferenceSet implements PreferenceSetComposite { + private final PreferenceSetComposite preferenceSet; + private final Map prefs; - - public FragmentPortletPreferenceSet(PreferenceSetComposite preferenceSet, Fragment fragment) + + public FragmentPortletPreferenceSet(PreferenceSetComposite preferenceSet, + Fragment fragment) { // save mutable preference set and read only fragment this.preferenceSet = preferenceSet; // construct merged portlet definition prefs map; // note that user specific preferences accessed via // the portlet entity should override these defaults - int prefsSize = preferenceSet.size() + 1; + int prefsSize = preferenceSet.size() + 1; if (fragment != null && fragment.getPreferences() != null) { prefsSize += fragment.getPreferences().size(); @@ -57,18 +59,18 @@ // add global portlet definition defaults to prefs Iterator iterator = preferenceSet.iterator(); - while(iterator.hasNext()) + while (iterator.hasNext()) { Preference pref = (Preference) iterator.next(); prefs.put(pref.getName(), pref); - } + } // add/override global portlet definition defaults // using more specific fragment preferences if (fragment != null && fragment.getPreferences() != null) { - Iterator itr = fragment.getPreferences().iterator(); - while(itr.hasNext()) + Iterator itr = fragment.getPreferences().iterator(); + while (itr.hasNext()) { Preference pref = (Preference) itr.next(); prefs.put(pref.getName(), pref); @@ -77,7 +79,7 @@ } public Preference add(String arg0, List arg1) - { + { Preference pref = preferenceSet.add(arg0, arg1); prefs.put(arg0, pref); return pref; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/preference/impl/PrefsPreference.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/preference/impl/PrefsPreference.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/preference/impl/PrefsPreference.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,84 +32,87 @@ import org.apache.jetspeed.om.impl.PreferenceDescriptionImpl; import org.apache.pluto.om.common.Description; - public class PrefsPreference implements PreferenceComposite { + protected static final String VALUES_PATH = "values"; + protected static final String VALUES_SIZE = "size"; - + public static final String PORTLET_PREFERENCES_ROOT = "preferences"; + protected static final String LOCALE_TOKEN = "_"; + protected Preferences prefValueNode; + protected Preferences prefValueSizeNode; + protected Preferences prefNode; + protected String name; - public static final String[] DEFAULT_OPEN_NODES = new String[] {MutablePortletEntity.PORTLET_ENTITY_ROOT, PortletDefinitionComposite.PORTLETS_PREFS_ROOT}; - - + public static final String[] DEFAULT_OPEN_NODES = new String[] + {MutablePortletEntity.PORTLET_ENTITY_ROOT, + PortletDefinitionComposite.PORTLETS_PREFS_ROOT}; + public PrefsPreference(Preferences prefNode, String name) { super(); this.prefNode = prefNode; - if(prefNode == null) - { - throw new IllegalArgumentException("prefNode cannot be null for PrefsPreferences(Preference)."); - } - + if (prefNode == null) { throw new IllegalArgumentException( + "prefNode cannot be null for PrefsPreferences(Preference)."); } + this.name = name; - if(this.name == null) - { - throw new IllegalArgumentException("Preference does requires a \"name\" property."); - } - + if (this.name == null) { throw new IllegalArgumentException( + "Preference does requires a \"name\" property."); } + this.prefValueNode = prefNode.node(VALUES_PATH); this.prefValueSizeNode = prefNode.node(VALUES_SIZE); } - + public PrefsPreference(PortletDefinitionComposite portlet, String name) { this(createPrefenceNode(portlet).node(name), name); } - private int getPrefValueSize(boolean store) { int size = prefValueSizeNode.getInt(VALUES_SIZE, -1); - if ( size == -1 ) + if (size == -1) { // prefSizeNode doesn't exist - // if values exists (upgrading issue), determine from number of values keys + // if values exists (upgrading issue), determine from number of + // values keys try { size = prefValueNode.keys().length; } catch (BackingStoreException e) { - String msg = "Preference backing store failed: "+e.toString(); + String msg = "Preference backing store failed: " + e.toString(); IllegalStateException ise = new IllegalStateException(msg); ise.initCause(e); throw ise; } if (store) { - prefValueSizeNode.putInt(VALUES_SIZE,size); + prefValueSizeNode.putInt(VALUES_SIZE, size); } } return size; } - + /** *

      * addDescription *

      * * @see org.apache.jetspeed.om.common.preference.PreferenceComposite#addDescription(java.util.Locale, - * java.lang.String) + * java.lang.String) * @param locale * @param Description */ - public void addDescription( Locale locale, String description ) + public void addDescription(Locale locale, String description) { String localePath = locale.toString(); prefNode.node("description").put(localePath, description); @@ -124,7 +127,7 @@ * @param locale * @return */ - public Description getDescription( Locale locale ) + public Description getDescription(Locale locale) { String localePath = locale.toString(); String value = prefNode.node("description").get(localePath, null); @@ -144,24 +147,24 @@ * @param index * @return */ - public String getValueAt( int index ) + public String getValueAt(int index) { return prefValueNode.get(String.valueOf(index), null); } - + public void removeValueAt(int index) { int size; - if (index > -1 && index < (size = getPrefValueSize(true)) ) + if (index > -1 && index < (size = getPrefValueSize(true))) { - String[] values = new String[size-1]; + String[] values = new String[size - 1]; for (int i = 0; i < index; i++) { - values[i] = prefValueNode.get(String.valueOf(i),null); + values[i] = prefValueNode.get(String.valueOf(i), null); } - for ( int i = index+1; i < size; i++) + for (int i = index + 1; i < size; i++) { - values[i] = prefValueNode.get(String.valueOf(i),null); + values[i] = prefValueNode.get(String.valueOf(i), null); } setValues(values); } @@ -175,18 +178,18 @@ *

      * * @see org.apache.jetspeed.om.common.preference.PreferenceComposite#setValueAt(int, - * java.lang.String) + * java.lang.String) * @param index * @param value */ - public void setValueAt( int index, String value ) + public void setValueAt(int index, String value) { - if ( index > -1 ) + if (index > -1) { int size = getPrefValueSize(true); - if ( index < size ) + if (index < size) { - if ( value != null ) + if (value != null) { prefValueNode.put(String.valueOf(index), value); } @@ -197,13 +200,13 @@ } else { - prefValueSizeNode.putInt(VALUES_SIZE, index+1); - if ( value != null ) + prefValueSizeNode.putInt(VALUES_SIZE, index + 1); + if (value != null) { - prefValueNode.put(String.valueOf(index),value); + prefValueNode.put(String.valueOf(index), value); } } - + } else throw new IndexOutOfBoundsException(); @@ -217,14 +220,14 @@ * @see org.apache.jetspeed.om.common.preference.PreferenceComposite#addValue(java.lang.String) * @param value */ - public void addValue( String value ) + public void addValue(String value) { - int size = getPrefValueSize(true); - prefValueSizeNode.putInt(VALUES_SIZE, size+1); - if ( value != null ) - { - prefValueNode.put(String.valueOf(size),value); - } + int size = getPrefValueSize(true); + prefValueSizeNode.putInt(VALUES_SIZE, size + 1); + if (value != null) + { + prefValueNode.put(String.valueOf(size), value); + } } /** @@ -241,7 +244,7 @@ String[] values = new String[size]; for (int i = 0; i < size; i++) { - values[i] = prefValueNode.get(String.valueOf(i),null); + values[i] = prefValueNode.get(String.valueOf(i), null); } return values; } @@ -254,7 +257,7 @@ * @see org.apache.jetspeed.om.common.preference.PreferenceComposite#setValues(java.lang.String[]) * @param stringValues */ - public void setValues( String[] stringValues ) + public void setValues(String[] stringValues) { try { @@ -271,7 +274,7 @@ } catch (BackingStoreException e) { - String msg = "Preference backing store failed: "+e.toString(); + String msg = "Preference backing store failed: " + e.toString(); IllegalStateException ise = new IllegalStateException(msg); ise.initCause(e); throw ise; @@ -300,7 +303,7 @@ * @see org.apache.jetspeed.om.common.preference.PreferenceComposite#setType(java.lang.String) * @param string */ - public void setType( String string ) + public void setType(String string) { // TODO Auto-generated method stub @@ -314,7 +317,7 @@ * @see org.apache.pluto.om.common.PreferenceCtrl#setName(java.lang.String) * @param arg0 */ - public void setName( String name ) + public void setName(String name) { this.name = name; @@ -328,7 +331,7 @@ * @see org.apache.pluto.om.common.PreferenceCtrl#setValues(java.util.List) * @param arg0 */ - public void setValues( List arg0 ) + public void setValues(List arg0) { if (arg0 != null) { @@ -345,15 +348,15 @@ * @see org.apache.pluto.om.common.PreferenceCtrl#setReadOnly(java.lang.String) * @param arg0 */ - public void setReadOnly( String readOnly ) + public void setReadOnly(String readOnly) { prefNode.put("read_only", readOnly); } - - public void setReadOnly( boolean readOnly ) + + public void setReadOnly(boolean readOnly) { - if(readOnly) + if (readOnly) { prefNode.put("read_only", "true"); } @@ -400,7 +403,8 @@ */ public boolean isReadOnly() { - return Boolean.valueOf(prefNode.get("read_only", "false")).booleanValue(); + return Boolean.valueOf(prefNode.get("read_only", "false")) + .booleanValue(); } /** @@ -416,7 +420,7 @@ return getPrefValueSize(false) > 0; } - protected Locale parseLocal( String localString ) + protected Locale parseLocal(String localString) { StringTokenizer lcTk = new StringTokenizer(localString, LOCALE_TOKEN); String lang = null; @@ -440,26 +444,26 @@ return new Locale(lang, country, variant); } - - + /** *

      * clone *

      * * @see java.lang.Object#clone() - * @return @throws - * java.lang.CloneNotSupportedException + * @return + * @throws java.lang.CloneNotSupportedException */ public String[] cloneValues() { - String[] clonedValues; - synchronized (prefValueNode) + String[] clonedValues; + synchronized (prefValueNode) { String[] currentValues = getValueArray(); clonedValues = new String[currentValues.length]; - System.arraycopy(currentValues, 0, clonedValues, 0, currentValues.length); + System.arraycopy(currentValues, 0, clonedValues, 0, + currentValues.length); } return clonedValues; @@ -474,7 +478,7 @@ * @param obj * @return */ - public boolean equals( Object obj ) + public boolean equals(Object obj) { if (obj != null && obj instanceof PrefsPreference && name != null) { @@ -498,8 +502,8 @@ * @return */ public int hashCode() - { - return (getClass().getName()+"::"+name).hashCode(); + { + return (getClass().getName() + "::" + name).hashCode(); } /** @@ -512,21 +516,22 @@ */ public String toString() { - return "Preference{"+name+"} values="+getValueArray().toString(); + return "Preference{" + name + "} values=" + getValueArray().toString(); } - + /** - * + * */ public void flush() throws BackingStoreException { prefValueNode.flush(); } + /** *

      * getDescriptions *

      - * + * * @see org.apache.jetspeed.om.common.preference.PreferenceComposite#getDescriptions() * @return */ @@ -535,10 +540,10 @@ try { Preferences descNode = prefNode.node("description"); - + String[] keys = descNode.keys(); ArrayList descs = new ArrayList(keys.length); - for(int i=0; i < keys.length; i++) + for (int i = 0; i < keys.length; i++) { PreferenceDescriptionImpl desc = new PreferenceDescriptionImpl(); String localeKey = keys[i]; @@ -548,18 +553,18 @@ desc.setLanguage(locale.getLanguage()); descs.add(desc); } - + return descs.iterator(); } catch (BackingStoreException e) { - String msg = "Preference backing store failed: "+e.toString(); + String msg = "Preference backing store failed: " + e.toString(); IllegalStateException ise = new IllegalStateException(msg); ise.initCause(e); throw ise; } } - + /** * *

      @@ -567,22 +572,24 @@ *

      * * Creates a Preferences object for this portlet - * + * * @param portlet * @return */ - - public static Preferences createPrefenceNode(PortletDefinitionComposite portlet) + + public static Preferences createPrefenceNode( + PortletDefinitionComposite portlet) { - MutablePortletApplication app = (MutablePortletApplication) portlet.getPortletApplicationDefinition(); - if(app == null) - { - throw new IllegalArgumentException("createPrefencePath() requires a PortletDefinition whose Application is not null."); - } - String portletDefPrefPath = MutablePortletApplication.PREFS_ROOT + "/" + app.getName() + "/" - + PortletDefinitionComposite.PORTLETS_PREFS_ROOT + "/" + portlet.getName() + "/" - + PrefsPreference.PORTLET_PREFERENCES_ROOT; - + MutablePortletApplication app = (MutablePortletApplication) portlet + .getPortletApplicationDefinition(); + if (app == null) { throw new IllegalArgumentException( + "createPrefencePath() requires a PortletDefinition whose Application is not null."); } + String portletDefPrefPath = MutablePortletApplication.PREFS_ROOT + "/" + + app.getName() + "/" + + PortletDefinitionComposite.PORTLETS_PREFS_ROOT + "/" + + portlet.getName() + "/" + + PrefsPreference.PORTLET_PREFERENCES_ROOT; + return Preferences.systemRoot().node(portletDefPrefPath); } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/preference/impl/PrefsPreferenceSetImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/preference/impl/PrefsPreferenceSetImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/preference/impl/PrefsPreferenceSetImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -35,46 +35,54 @@ /** * @author Scott T. Weaver * - * + * */ public class PrefsPreferenceSetImpl implements PreferenceSetComposite { + protected Preferences prefsRootNode; + protected PreferenceSetComposite defaults; + protected PreferencesValidatorFactory validatorFactory; /** * @param portletEntity - * PortletEntity for which to build the PreferenceSet for. + * PortletEntity for which to build the PreferenceSet for. * @throws BackingStoreException - * if an error is encountered while accessing the Preferences - * backing store. + * if an error is encountered while accessing the Preferences + * backing store. */ - public PrefsPreferenceSetImpl( Preferences prefsRootNode ) throws BackingStoreException + public PrefsPreferenceSetImpl(Preferences prefsRootNode) + throws BackingStoreException { super(); this.prefsRootNode = prefsRootNode; } - + /** * @param portletEntity - * PortletEntity for which to build the PreferenceSet for. + * PortletEntity for which to build the PreferenceSet for. * @param validatorFactory - * Factory for providing access to a PreferencesValidator instance + * Factory for providing access to a PreferencesValidator + * instance * @throws BackingStoreException - * if an error is encountered while accessing the Preferences - * backing store. + * if an error is encountered while accessing the Preferences + * backing store. */ - public PrefsPreferenceSetImpl( Preferences prefsRootNode, PreferencesValidatorFactory validatorFactory ) throws BackingStoreException + public PrefsPreferenceSetImpl(Preferences prefsRootNode, + PreferencesValidatorFactory validatorFactory) + throws BackingStoreException { this(prefsRootNode); this.validatorFactory = validatorFactory; } - public PrefsPreferenceSetImpl( Preferences prefsRootNode, PreferenceSetComposite defaults) throws BackingStoreException + public PrefsPreferenceSetImpl(Preferences prefsRootNode, + PreferenceSetComposite defaults) throws BackingStoreException { - this(prefsRootNode); + this(prefsRootNode); this.defaults = defaults; } @@ -90,15 +98,16 @@ { try { - if(defaults != null) + if (defaults != null) { - Set names = defaults.getNames(); - names.addAll(new HashSet(Arrays.asList(prefsRootNode.childrenNames()))); - return names; + Set names = defaults.getNames(); + names.addAll(new HashSet(Arrays.asList(prefsRootNode + .childrenNames()))); + return names; } else { - return new HashSet(Arrays.asList(prefsRootNode.childrenNames())); + return new HashSet(Arrays.asList(prefsRootNode.childrenNames())); } } catch (BackingStoreException e) @@ -119,7 +128,7 @@ * @param arg0 * @return */ - public Preference get( String key ) + public Preference get(String key) { try { @@ -128,18 +137,18 @@ { pref = new PrefsPreference(prefsRootNode.node(key), key); } - else if(defaults != null) + else if (defaults != null) { pref = defaults.get(key); } - + return pref; } catch (IllegalStateException ise) { // node has been removed return null; - } + } catch (BackingStoreException e) { String msg = "Preference backing store failed: " + e.toString(); @@ -159,10 +168,8 @@ */ public PreferencesValidator getPreferencesValidator() { - if ( validatorFactory != null ) - { - return validatorFactory.getPreferencesValidator(); - } + if (validatorFactory != null) { return validatorFactory + .getPreferencesValidator(); } return null; } @@ -172,16 +179,17 @@ *

      * * @see org.apache.pluto.om.common.PreferenceSetCtrl#add(java.lang.String, - * java.util.List) + * java.util.List) * @param name * @param values * @return */ - public Preference add( String name, List values ) + public Preference add(String name, List values) { Iterator valuesItr = values.iterator(); - PrefsPreference pref = new PrefsPreference(prefsRootNode.node(name), name); + PrefsPreference pref = new PrefsPreference(prefsRootNode.node(name), + name); while (valuesItr.hasNext()) { pref.addValue((String) valuesItr.next()); @@ -198,7 +206,7 @@ * @see org.apache.pluto.om.common.PreferenceSetCtrl#remove(org.apache.pluto.om.common.Preference) * @param arg0 */ - public void remove( Preference pref ) + public void remove(Preference pref) { remove(pref.getName()); } @@ -212,14 +220,13 @@ * @param arg0 * @return */ - public Preference remove( String key ) + public Preference remove(String key) { try { - Preferences nodeToRemove = prefsRootNode.node(key); - - if (nodeToRemove == null) - return null; + Preferences nodeToRemove = prefsRootNode.node(key); + + if (nodeToRemove == null) return null; PrefsPreference pref = new PrefsPreference(nodeToRemove, key); nodeToRemove.removeNode(); return pref; @@ -234,19 +241,19 @@ } /** - * + * */ public void flush() throws BackingStoreException { prefsRootNode.flush(); } - + /** * *

      * clear *

      - * + * * @throws BackingStoreException */ public void clear() throws BackingStoreException @@ -267,12 +274,12 @@ try { int length = prefsRootNode.childrenNames().length; - - if(defaults != null) + + if (defaults != null) { length += defaults.size(); } - + return length; } catch (IllegalStateException ise) @@ -303,9 +310,13 @@ protected class PortletPrefsIterator implements Iterator { + int beginSize = 0; + int pointer; + String[] childrenNames; + protected PrefsPreference currentPref; protected PortletPrefsIterator() @@ -314,32 +325,31 @@ try { childrenNames = prefsRootNode.childrenNames(); - if (childrenNames != null) - beginSize = childrenNames.length; - - if(defaults != null) + if (childrenNames != null) beginSize = childrenNames.length; + + if (defaults != null) { Vector v = new Vector(); Iterator itr = defaults.getNames().iterator(); - while( itr.hasNext()) + while (itr.hasNext()) { String name = (String) itr.next(); - if(!arrayContains(childrenNames, name)) + if (!arrayContains(childrenNames, name)) { - v.add(name); + v.add(name); } } int j = v.size(); - if (j>0) + if (j > 0) { - int i = childrenNames.length; - String[] tempArray = new String[j+i]; + int i = childrenNames.length; + String[] tempArray = new String[j + i]; System.arraycopy(childrenNames, 0, tempArray, 0, i); for (int x = 0; x < j; x++) - tempArray[i+x] = (String)v.get(x); + tempArray[i + x] = (String) v.get(x); childrenNames = tempArray; - beginSize = i+j; + beginSize = i + j; } } pointer = 0; @@ -348,7 +358,7 @@ { // node has been removed childrenNames = new String[0]; - } + } catch (BackingStoreException e) { String msg = "Preference backing store failed: " + e.toString(); @@ -369,14 +379,15 @@ */ public boolean hasNext() { - try - { - return pointer < beginSize; - } - catch (Exception e) - { - throw new ConcurrentModificationException("Underlying PreferenceSet has changed."); - } + try + { + return pointer < beginSize; + } + catch (Exception e) + { + throw new ConcurrentModificationException( + "Underlying PreferenceSet has changed."); + } } /** @@ -389,16 +400,17 @@ */ public Object next() { - try - { - currentPref = (PrefsPreference) get(childrenNames[pointer]); - pointer++; - return currentPref; - } - catch (Exception e) - { - throw new ConcurrentModificationException("Underlying PreferenceSet has changed."); - } + try + { + currentPref = (PrefsPreference) get(childrenNames[pointer]); + pointer++; + return currentPref; + } + catch (Exception e) + { + throw new ConcurrentModificationException( + "Underlying PreferenceSet has changed."); + } } /** @@ -407,32 +419,27 @@ *

      * * @see java.util.Iterator#remove() - * + * */ public void remove() { - if (currentPref == null) - { - throw new IllegalStateException(" next() must be called at least once before invoking remove()."); - } + if (currentPref == null) { throw new IllegalStateException( + " next() must be called at least once before invoking remove()."); } PrefsPreferenceSetImpl.this.remove(currentPref); beginSize--; } } - + protected boolean arrayContains(String[] array, String value) { - for(int i=0; iAte Douma * @version $Id: SecurityRoleImpl.java 516881 2007-03-11 10:34:21Z ate $ */ -public class SecurityRoleImpl implements SecurityRole, MutableSecurityRole, Serializable { +public class SecurityRoleImpl implements SecurityRole, MutableSecurityRole, + Serializable +{ protected long webAppId; @@ -38,75 +40,89 @@ /** * Default constructor. */ - public SecurityRoleImpl() { + public SecurityRoleImpl() + { } /** * @see org.apache.pluto.om.common.SecurityRole#getDescription() */ - public String getDescription() { + public String getDescription() + { return description; } /** * @see org.apache.pluto.om.common.SecurityRole#getRoleName() */ - public String getRoleName() { + public String getRoleName() + { return roleName; } /** * @see org.apache.jetspeed.om.common.servlet.MutableSecurityRole#setDescription(java.lang.String) */ - public void setDescription(String description) { + public void setDescription(String description) + { this.description = description; } /** * @see org.apache.jetspeed.om.common.servlet.MutableSecurityRole#setRoleName(java.lang.String) */ - public void setRoleName(String roleName) { + public void setRoleName(String roleName) + { this.roleName = roleName; } /** * Convert {@link SecurityRole}to String. - * + * * @return String value of SecurityRole. */ - public String toString() { - String securityRole = "[[roleName, " + this.roleName + "], [description, " + this.description + "]]"; + public String toString() + { + String securityRole = "[[roleName, " + this.roleName + + "], [description, " + this.description + "]]"; return securityRole; } - + /** * @see java.lang.Object#equals(java.lang.Object) */ - public boolean equals(Object obj) { - if ( obj != null && obj instanceof SecurityRoleImpl ) { - //TODO: Because of a bug in OJB 1.0.rc4 fields seems not have been set - // before this object is put into a HashMap. - // Therefore, for the time being, check against null values is - // required. - // Once 1.0rc5 or higher can be used the following line should be - // used again. - //return getRoleName().equals(((SecurityRoleImpl)obj).getRoleName()); - return getRoleName() != null && getRoleName().equals(((SecurityRoleImpl)obj).getRoleName()); + public boolean equals(Object obj) + { + if (obj != null && obj instanceof SecurityRoleImpl) + { + // TODO: Because of a bug in OJB 1.0.rc4 fields seems not have been + // set + // before this object is put into a HashMap. + // Therefore, for the time being, check against null values is + // required. + // Once 1.0rc5 or higher can be used the following line should be + // used again. + // return + // getRoleName().equals(((SecurityRoleImpl)obj).getRoleName()); + return getRoleName() != null + && getRoleName().equals( + ((SecurityRoleImpl) obj).getRoleName()); } return false; } - /** + /** * @see java.lang.Object#hashCode() */ - public int hashCode() { - //TODO: Because of a bug in OJB 1.0.rc4 fields seems not have been set - // before this object is put into a HashMap. - // Therefore, for the time being, check against null values is - // required. - // Once 1.0rc5 or higher can be used the following line should be - // used again. - //return getRoleName().hashCode(); + public int hashCode() + { + // TODO: Because of a bug in OJB 1.0.rc4 fields seems not have been set + // before this object is put into a HashMap. + // Therefore, for the time being, check against null values is + // required. + // Once 1.0rc5 or higher can be used the following line should be + // used again. + // return getRoleName().hashCode(); return getRoleName() != null ? getRoleName().hashCode() : 0; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/servlet/impl/SecurityRoleSetImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/servlet/impl/SecurityRoleSetImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/servlet/impl/SecurityRoleSetImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,31 +26,37 @@ import org.apache.pluto.om.common.SecurityRoleSet; /** - * + * * SecurityRoleRefSetImpl - * + * * @author Ate Douma * @version $Id: SecurityRoleSetImpl.java 517121 2007-03-12 07:45:49Z ate $ - * + * */ -public class SecurityRoleSetImpl implements SecurityRoleSet, MutableSecurityRoleSet, Serializable { +public class SecurityRoleSetImpl implements SecurityRoleSet, + MutableSecurityRoleSet, Serializable +{ protected Collection innerCollection; - public SecurityRoleSetImpl() { + public SecurityRoleSetImpl() + { innerCollection = new ArrayList(); } - public SecurityRoleSetImpl(Collection collection) { + public SecurityRoleSetImpl(Collection collection) + { innerCollection = collection; } /** * @see org.apache.pluto.om.common.SecurityRoleSet#get(java.lang.String) */ - public SecurityRole get(String name) { + public SecurityRole get(String name) + { Iterator itr = innerCollection.iterator(); - while (itr.hasNext()) { + while (itr.hasNext()) + { SecurityRole role = (SecurityRole) itr.next(); if (role.getRoleName().equals(name)) { return role; } } @@ -61,10 +67,11 @@ /** * @see org.apache.jetspeed.om.common.servlet.MutableSecurityRoleSet#add(org.apache.pluto.om.common.SecurityRole) */ - public SecurityRole add(SecurityRole securityRole) { - if ( innerCollection.contains(securityRole)) { - throw new IllegalArgumentException("SecurityRole "+securityRole.getRoleName()+" already defined."); - } + public SecurityRole add(SecurityRole securityRole) + { + if (innerCollection.contains(securityRole)) { throw new IllegalArgumentException( + "SecurityRole " + securityRole.getRoleName() + + " already defined."); } innerCollection.add(securityRole); return securityRole; } @@ -72,7 +79,8 @@ /** * @see java.util.Collection#add(java.lang.Object) */ - public boolean add(Object o) { + public boolean add(Object o) + { SecurityRole role = (SecurityRole) o; add(role); return true; @@ -81,17 +89,20 @@ /** * @see java.util.Collection#remove(java.lang.Object) */ - public boolean remove(Object o) { + public boolean remove(Object o) + { return innerCollection.remove(o); } /** * @see java.util.Collection#addAll(java.util.Collection) */ - public boolean addAll(Collection c) { + public boolean addAll(Collection c) + { // enforce unique role names in collection by adding them individually Iterator itr = c.iterator(); - while ( itr.hasNext() ) { + while (itr.hasNext()) + { add(itr.next()); } return true; @@ -100,7 +111,8 @@ /** * @see java.util.Collection#clear() */ - public void clear() { + public void clear() + { innerCollection.clear(); } @@ -108,77 +120,88 @@ /** * @see java.util.Collection#contains(java.lang.Object) */ - public boolean contains(Object o) { + public boolean contains(Object o) + { return innerCollection.contains(o); } /** * @see java.util.Collection#containsAll(java.util.Collection) */ - public boolean containsAll(Collection c) { + public boolean containsAll(Collection c) + { return innerCollection.containsAll(c); } /** * @see java.util.Collection#isEmpty() */ - public boolean isEmpty() { + public boolean isEmpty() + { return innerCollection.isEmpty(); } /** * @see java.util.Collection#iterator() */ - public Iterator iterator() { + public Iterator iterator() + { return innerCollection.iterator(); } /** * @see java.util.Collection#removeAll(java.util.Collection) */ - public boolean removeAll(Collection c) { + public boolean removeAll(Collection c) + { return innerCollection.removeAll(c); } /** * @see java.util.Collection#retainAll(java.util.Collection) */ - public boolean retainAll(Collection c) { + public boolean retainAll(Collection c) + { return innerCollection.retainAll(c); } /** * @see java.util.Collection#size() */ - public int size() { + public int size() + { return innerCollection.size(); } /** * @see java.util.Collection#toArray() */ - public Object[] toArray() { + public Object[] toArray() + { return innerCollection.toArray(); } /** * @see java.util.Collection#toArray(java.lang.Object[]) */ - public Object[] toArray(Object[] a) { + public Object[] toArray(Object[] a) + { return innerCollection.toArray(a); } /** * @return collection */ - public Collection getInnerCollection() { + public Collection getInnerCollection() + { return innerCollection; } /** * @param collection */ - public void setInnerCollection(Collection collection) { + public void setInnerCollection(Collection collection) + { innerCollection = collection; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/servlet/impl/WebApplicationDefinitionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/servlet/impl/WebApplicationDefinitionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/servlet/impl/WebApplicationDefinitionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -41,41 +41,53 @@ import org.apache.pluto.om.common.DisplayNameSet; import org.apache.pluto.om.common.ObjectID; import org.apache.pluto.om.common.ParameterSet; -import org.apache.pluto.om.servlet.ServletDefinitionList; import org.apache.pluto.om.common.SecurityRole; import org.apache.pluto.om.common.SecurityRoleSet; +import org.apache.pluto.om.servlet.ServletDefinitionList; /** * * WebApplicationDefinitionImpl * * @author Scott T. Weaver - * @version $Id: WebApplicationDefinitionImpl.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: WebApplicationDefinitionImpl.java 516448 2007-03-09 16:25:47Z + * ate $ + * */ -public class WebApplicationDefinitionImpl implements MutableWebApplication, Serializable +public class WebApplicationDefinitionImpl implements MutableWebApplication, + Serializable { + private Long id; + private JetspeedLongObjectID oid; + private Collection displayNames = new ArrayList(); + private DisplayNameSetImpl DNCollWrapper = new DisplayNameSetImpl(); private Collection descriptions = new ArrayList(); - private DescriptionSetImpl descCollWrapper = new DescriptionSetImpl(DescriptionImpl.TYPE_WEB_APP); + + private DescriptionSetImpl descCollWrapper = new DescriptionSetImpl( + DescriptionImpl.TYPE_WEB_APP); + private Collection securityRoles = new ArrayList(); + private SecurityRoleSetImpl secRolesListWrapper = new SecurityRoleSetImpl(); private String contextRoot; + private ParameterSet initParameters; - private static final Log log = LogFactory.getLog(WebApplicationDefinitionImpl.class); + private static final Log log = LogFactory + .getLog(WebApplicationDefinitionImpl.class); /** * @see org.apache.pluto.om.servlet.WebApplicationDefinition#getId() */ public ObjectID getId() { - if ( oid == null && id != null ) + if (oid == null && id != null) { oid = new JetspeedLongObjectID(id); } @@ -150,7 +162,8 @@ */ public void setDisplayNameSet(DisplayNameSet displayNames) { - this.displayNames = ((DisplayNameSetImpl) displayNames).getInnerCollection(); + this.displayNames = ((DisplayNameSetImpl) displayNames) + .getInnerCollection(); } /** @@ -162,7 +175,8 @@ } /** - * @see org.apache.jetspeed.om.common.servlet.MutableWebApplication#addDescription(java.util.Locale, java.lang.String) + * @see org.apache.jetspeed.om.common.servlet.MutableWebApplication#addDescription(java.util.Locale, + * java.lang.String) */ public void addDescription(Locale locale, String description) { @@ -174,21 +188,23 @@ try { MutableDescription descObj = new WebAppDescriptionImpl(); - + descObj.setLocale(locale); descObj.setDescription(description); descCollWrapper.addDescription(descObj); } catch (Exception e) { - String msg = "Unable to instantiate Description implementor, " + e.toString(); + String msg = "Unable to instantiate Description implementor, " + + e.toString(); log.error(msg, e); throw new IllegalStateException(msg); } } /** - * @see org.apache.jetspeed.om.common.servlet.MutableWebApplication#addDisplayName(java.util.Locale, java.lang.String) + * @see org.apache.jetspeed.om.common.servlet.MutableWebApplication#addDisplayName(java.util.Locale, + * java.lang.String) */ public void addDisplayName(Locale locale, String name) { @@ -200,14 +216,15 @@ try { MutableDisplayName dn = new WebAppDisplayNameImpl(); - + dn.setLocale(locale); dn.setDisplayName(name); DNCollWrapper.addDisplayName(dn); } catch (Exception e) { - String msg = "Unable to instantiate DisplayName implementor, " + e.toString(); + String msg = "Unable to instantiate DisplayName implementor, " + + e.toString(); log.error(msg, e); throw new IllegalStateException(msg); } @@ -219,26 +236,26 @@ */ public void setDescriptionSet(DescriptionSet descriptions) { - this.descriptions = ((DescriptionSetImpl) descriptions).getInnerCollection(); + this.descriptions = ((DescriptionSetImpl) descriptions) + .getInnerCollection(); } /** - * Remove when Castor is mapped correctly + * Remove when Castor is mapped correctly + * * @deprecated * @return */ public String getDescription() { Description desc = getDescription(JetspeedLocale.getDefaultLocale()); - if (desc != null) - { - return desc.getDescription(); - } + if (desc != null) { return desc.getDescription(); } return null; } /** - * Remove when Castor is mapped correctly + * Remove when Castor is mapped correctly + * * @deprecated * @param desc */ @@ -255,13 +272,13 @@ secRolesListWrapper.setInnerCollection(securityRoles); return secRolesListWrapper; } - + /** * @see org.apache.jetspeed.om.common.servlet.MutableWebApplication#addSecurityRole(org.apache.pluto.om.common.SecurityRole) */ - public void addSecurityRole(SecurityRole securityRole) + public void addSecurityRole(SecurityRole securityRole) { secRolesListWrapper.setInnerCollection(securityRoles); secRolesListWrapper.add(securityRole); - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/window/impl/PortletWindowImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/window/impl/PortletWindowImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/window/impl/PortletWindowImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,27 +18,31 @@ import java.io.Serializable; +import org.apache.jetspeed.util.JetspeedObjectID; +import org.apache.pluto.om.common.ObjectID; +import org.apache.pluto.om.entity.PortletEntity; import org.apache.pluto.om.window.PortletWindow; import org.apache.pluto.om.window.PortletWindowCtrl; import org.apache.pluto.om.window.PortletWindowListCtrl; -import org.apache.pluto.om.entity.PortletEntity; -import org.apache.pluto.om.common.ObjectID; -import org.apache.jetspeed.util.JetspeedObjectID; /** *

      - * The PortletWindow implementation represents a single window - * of an portlet instance as it can be shown only once on a single page. - * Adding the same portlet e.g. twice on a page results in two different windows. + * The PortletWindow implementation represents a single window of + * an portlet instance as it can be shown only once on a single page. Adding the + * same portlet e.g. twice on a page results in two different windows. *

      - * + * * @author David Sean Taylor * @version $Id: PortletWindowImpl.java 589933 2007-10-30 01:51:50Z woonsan $ - **/ -public class PortletWindowImpl implements PortletWindow, PortletWindowCtrl, Serializable + */ +public class PortletWindowImpl implements PortletWindow, PortletWindowCtrl, + Serializable { + private ObjectID objectId = null; + private transient PortletEntity portletEntity = null; + private boolean instantlyRendered; public PortletWindowImpl(String id) @@ -57,19 +61,20 @@ } /** - * Returns the identifier of this portlet instance window as object id - * - * @return the object identifier - **/ + * Returns the identifier of this portlet instance window as object id + * + * @return the object identifier + */ public ObjectID getId() { return objectId; } + /** * Returns the portlet entity - * + * * @return the portlet entity - **/ + */ public PortletEntity getPortletEntity() { return portletEntity; @@ -78,8 +83,9 @@ // controller impl /** * binds an identifier to this portlet window - * - * @param id the new identifier + * + * @param id + * the new identifier */ public void setId(String id) { @@ -89,14 +95,16 @@ /** * binds a portlet instance to this portlet window * - * @param portletEntity a portlet entity object - **/ + * @param portletEntity + * a portlet entity object + */ public void setPortletEntity(PortletEntity portletEntity) { this.portletEntity = portletEntity; - ((PortletWindowListCtrl)portletEntity.getPortletWindowList()).add(this); + ((PortletWindowListCtrl) portletEntity.getPortletWindowList()) + .add(this); } - + /** * Sets flag that the content is instantly rendered from JPT. */ @@ -104,7 +112,7 @@ { this.instantlyRendered = instantlyRendered; } - + /** * Checks if the content is instantly rendered from JPT. */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/window/impl/PortletWindowListImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/window/impl/PortletWindowListImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/om/window/impl/PortletWindowListImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,18 +18,20 @@ import java.io.Serializable; import java.util.HashMap; + +import org.apache.pluto.om.common.ObjectID; import org.apache.pluto.om.window.PortletWindow; import org.apache.pluto.om.window.PortletWindowList; import org.apache.pluto.om.window.PortletWindowListCtrl; -import org.apache.pluto.om.common.ObjectID; /** - * Portlet Window List implementation - * + * Portlet Window List implementation + * * @author David Sean Taylor * @version $Id: PortletWindowListImpl.java 516448 2007-03-09 16:25:47Z ate $ */ -public class PortletWindowListImpl implements PortletWindowList, PortletWindowListCtrl, Serializable +public class PortletWindowListImpl implements PortletWindowList, + PortletWindowListCtrl, Serializable { HashMap windows = null; @@ -51,12 +53,12 @@ /** * Returns the portlet window object of the given id - * + * * @param - * - * @return the portlet window object or null if the list does not - * contain a portlet window with the given id - **/ + * + * @return the portlet window object or null if the list does not contain a + * portlet window with the given id + */ public PortletWindow get(ObjectID id) { return (PortletWindow) windows.get(id.toString()); @@ -65,8 +67,9 @@ /** * Add a portlet window to the list * - * @param window the porlet window to add - **/ + * @param window + * the porlet window to add + */ public void add(PortletWindow window) { if (window != null) @@ -78,8 +81,9 @@ /** * Remove the portlet window with the given Id from the list * - * @param id the Id of the portlet window which should be removed - **/ + * @param id + * the Id of the portlet window which should be removed + */ public void remove(ObjectID id) { if (id != null) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/CSVtoCollectionFieldConversion.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/CSVtoCollectionFieldConversion.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/CSVtoCollectionFieldConversion.java 2008-05-16 01:54:54 UTC (rev 940) @@ -38,11 +38,14 @@ */ public class CSVtoCollectionFieldConversion implements FieldConversion { + private static final String DELIM = ","; + private static final String QUOTE = "\""; - - private static final Log log = LogFactory.getLog(CSVtoCollectionFieldConversion.class); - + + private static final Log log = LogFactory + .getLog(CSVtoCollectionFieldConversion.class); + /** * @see org.apache.ojb.broker.accesslayer.conversions.FieldConversion#javaToSql(java.lang.Object) * @task Fix JDK 1.3 complient problem described in the FIXME @@ -52,10 +55,7 @@ if (arg0 instanceof Collection) { Collection col = ((Collection) arg0); - if (col.size() == 0) - { - return ""; - } + if (col.size() == 0) { return ""; } Iterator itr = col.iterator(); // Estimate that the average word is going to be 5 characters long @@ -65,22 +65,28 @@ buffer.append(QUOTE); String value = getNext(itr); - // FIXME: The following is not JDK1.3 complient. So I implement a warning - // message as a workaround until this field conversion is no longer - // need and delete, or the code is made JDK 1.3 complient. (Paul Spencer) + // FIXME: The following is not JDK1.3 complient. So I implement + // a warning + // message as a workaround until this field conversion is no + // longer + // need and delete, or the code is made JDK 1.3 complient. (Paul + // Spencer) // buffer.append(value.replaceAll("\"","\\\\\"")); - if(value != null && value.toString().indexOf("\"") >= 0) + if (value != null && value.toString().indexOf("\"") >= 0) { - // FieldConversionLog.LOG.error("The string '" + value + - // "' contains embeded '\"'. It will not be converted to a CSV correctly."); - log.warn("In CSVtoCollectionFieldConversion() - The string '" + value + - "' contains embeded '\"'. It will not be converted to a CSV correctly."); + // FieldConversionLog.LOG.error("The string '" + value + + // "' contains embeded '\"'. It will not be converted to a + // CSV correctly."); + log + .warn("In CSVtoCollectionFieldConversion() - The string '" + + value + + "' contains embeded '\"'. It will not be converted to a CSV correctly."); } buffer.append(value); // End of FIXME: buffer.append(QUOTE); - + if (itr.hasNext()) { buffer.append(DELIM); @@ -107,7 +113,6 @@ st.quoteChar('"'); st.eolIsSignificant(false); - ArrayList list = new ArrayList(); try { @@ -120,8 +125,9 @@ { String message = "CSV parsing failed during field conversion."; log.error(message, e); - throw new ConversionException("CSV parsing failed during field conversion.", e); - } + throw new ConversionException( + "CSV parsing failed during field conversion.", e); + } return list; } @@ -130,10 +136,11 @@ } /** - * Makes creation of objects created via csv fields extensible - * By default simply return the string value. + * Makes creation of objects created via csv fields extensible By default + * simply return the string value. * - * @param name The string value + * @param name + * The string value * @return The string value */ protected Object createObject(String name) @@ -142,10 +149,11 @@ } /** - * Makes getting objects via csv fields extensible - * By default simply return the string value. + * Makes getting objects via csv fields extensible By default simply return + * the string value. * - * @param name The string value + * @param name + * The string value * @return The string value */ protected String getNext(Iterator iterator) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/CSVtoPortletModeFieldConversion.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/CSVtoPortletModeFieldConversion.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/CSVtoPortletModeFieldConversion.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,28 +24,34 @@ /** * CSVtoPortletModeFieldConversion - * + * * @author David Sean Taylor - * @version $Id: CSVtoPortletModeFieldConversion.java 185962 2004-03-08 01:03:33Z jford $ + * @version $Id: CSVtoPortletModeFieldConversion.java 185962 2004-03-08 + * 01:03:33Z jford $ */ -public class CSVtoPortletModeFieldConversion extends CSVtoCollectionFieldConversion implements FieldConversion +public class CSVtoPortletModeFieldConversion extends + CSVtoCollectionFieldConversion implements FieldConversion { - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.util.ojb.CSVtoCollectionFieldConversion#getNext(java.util.Iterator) */ protected String getNext(Iterator iterator) { - PortletMode mode = (PortletMode)iterator.next(); + PortletMode mode = (PortletMode) iterator.next(); return mode.toString(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.util.ojb.CSVtoCollectionFieldConversion#createObject(java.lang.String) */ protected Object createObject(String name) { return new PortletMode(name); } - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/CollectionDebugger.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/CollectionDebugger.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/CollectionDebugger.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * Created on Jan 22, 2004 * @@ -22,15 +22,12 @@ */ package org.apache.jetspeed.util.ojb; - import org.apache.ojb.broker.PersistenceBroker; import org.apache.ojb.broker.accesslayer.QueryCustomizer; import org.apache.ojb.broker.metadata.CollectionDescriptor; - import org.apache.ojb.broker.query.Query; import org.apache.ojb.broker.query.QueryByCriteria; - /** *

      * CollectionDebugger @@ -38,21 +35,26 @@ * * @author Scott T. Weaver * @version $Id: CollectionDebugger.java 185773 2004-02-24 00:31:46Z weaver $ - * + * */ public class CollectionDebugger implements QueryCustomizer { /** - * @see org.apache.ojb.broker.accesslayer.QueryCustomizer#customizeQuery(java.lang.Object, org.apache.ojb.broker.PersistenceBroker, org.apache.ojb.broker.metadata.CollectionDescriptor, org.apache.ojb.broker.query.QueryByCriteria) + * @see org.apache.ojb.broker.accesslayer.QueryCustomizer#customizeQuery(java.lang.Object, + * org.apache.ojb.broker.PersistenceBroker, + * org.apache.ojb.broker.metadata.CollectionDescriptor, + * org.apache.ojb.broker.query.QueryByCriteria) */ - public Query customizeQuery(Object arg0, PersistenceBroker pb, CollectionDescriptor arg2, QueryByCriteria arg3) - { + public Query customizeQuery(Object arg0, PersistenceBroker pb, + CollectionDescriptor arg2, QueryByCriteria arg3) + { return arg3; } /** - * @see org.apache.ojb.broker.metadata.AttributeContainer#addAttribute(java.lang.String, java.lang.String) + * @see org.apache.ojb.broker.metadata.AttributeContainer#addAttribute(java.lang.String, + * java.lang.String) */ public void addAttribute(String arg0, String arg1) { @@ -61,7 +63,8 @@ } /** - * @see org.apache.ojb.broker.metadata.AttributeContainer#getAttribute(java.lang.String, java.lang.String) + * @see org.apache.ojb.broker.metadata.AttributeContainer#getAttribute(java.lang.String, + * java.lang.String) */ public String getAttribute(String arg0, String arg1) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/FieldConversionLog.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/FieldConversionLog.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/FieldConversionLog.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,18 +20,18 @@ import org.apache.commons.logging.LogFactory; /** - * Utility class that allows convenient access to commons=logging for OJB - * FiledConversions without having to define a - * org.apache.commons.logging.Log in each of conversion - * class. - * - *@author Scott T. Weaver + * Utility class that allows convenient access to commons=logging for OJB + * FiledConversions without having to define a + * org.apache.commons.logging.Log in each of conversion class. + * + * @author Scott T. Weaver */ public abstract class FieldConversionLog { + /** - * There is only default ("package") access to this Log only as - * all OJB FieldConversions should be located here. + * There is only default ("package") access to this Log only as all OJB + * FieldConversions should be located here. */ static final Log LOG = LogFactory.getLog("org.apache.jetspeed.util.ojb"); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/LocaleFieldConversion.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/LocaleFieldConversion.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/LocaleFieldConversion.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,13 +27,14 @@ *

      * ObjectRelationalBridge field conversion. *

      - * Helps transparently map Locale objects into a database table - * that contains country, langauge and variant field and vice versa. + * Helps transparently map Locale objects into a database table that contains + * country, langauge and variant field and vice versa. * * field should be tokenized with commas */ public class LocaleFieldConversion implements FieldConversion { + private static final String DELIM = ","; /** @@ -83,24 +84,22 @@ { String localeString = (String) arg0; StringTokenizer tokenizer = new StringTokenizer(localeString, DELIM); - if(tokenizer.hasMoreTokens() == false) - { - return JetspeedLocale.getDefaultLocale(); - } + if (tokenizer.hasMoreTokens() == false) { return JetspeedLocale + .getDefaultLocale(); } String language = tokenizer.nextToken().trim(); String country = null; String variant = null; - if(tokenizer.hasMoreTokens()) + if (tokenizer.hasMoreTokens()) { country = tokenizer.nextToken().trim(); - } - if(tokenizer.hasMoreTokens()) + } + if (tokenizer.hasMoreTokens()) { variant = tokenizer.nextToken().trim(); } if (country != null && language != null && variant != null) { - return new Locale (language, country, variant); + return new Locale(language, country, variant); } else if (country != null && language != null) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/ObjectIDtoLongFieldConversion.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/ObjectIDtoLongFieldConversion.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/ObjectIDtoLongFieldConversion.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,7 +21,7 @@ import org.apache.ojb.broker.accesslayer.conversions.FieldConversion; /** - *

      + *

      * ObjectRelationalBridge field conversion. *

      * @@ -37,10 +37,8 @@ */ public Object javaToSql(Object arg0) throws ConversionException { - if (arg0 instanceof JetspeedLongObjectID) - { - return ((JetspeedLongObjectID)arg0).getLong(); - } + if (arg0 instanceof JetspeedLongObjectID) { return ((JetspeedLongObjectID) arg0) + .getLong(); } return arg0; } @@ -49,10 +47,8 @@ */ public Object sqlToJava(Object arg0) throws ConversionException { - if (arg0 instanceof Number) - { - return new JetspeedLongObjectID(((Number)arg0).longValue()); - } + if (arg0 instanceof Number) { return new JetspeedLongObjectID( + ((Number) arg0).longValue()); } return arg0; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/ObjectIDtoStringFieldConversion.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/ObjectIDtoStringFieldConversion.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/java/org/apache/jetspeed/util/ojb/ObjectIDtoStringFieldConversion.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,7 +21,7 @@ import org.apache.ojb.broker.accesslayer.conversions.FieldConversion; /** - *

      + *

      * ObjectRelationalBridge field conversion. *

      * @@ -56,8 +56,8 @@ public Object sqlToJava(Object arg0) throws ConversionException { if (arg0 instanceof String) - { - return JetspeedObjectID.createFromString((String)arg0); + { + return JetspeedObjectID.createFromString((String) arg0); } else { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletentity/ContentFragmentTestImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletentity/ContentFragmentTestImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletentity/ContentFragmentTestImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,16 +32,20 @@ * ContentFramgentTestImpl *

      * - * Dummy ContentFragment wrapper around Fragment as using the real ContentFragmentImpl would introduce a circular - * dependency between the registry and page-manager components. Probably should be replaced by a Mock but I don't - * know how to setup that quickly and the whole ContentFragment construction is bound to be replaced soon anyway... - * + * Dummy ContentFragment wrapper around Fragment as using the real + * ContentFragmentImpl would introduce a circular dependency between the + * registry and page-manager components. Probably should be replaced by a Mock + * but I don't know how to setup that quickly and the whole ContentFragment + * construction is bound to be replaced soon anyway... + * * @author Randy Watler * @version $Id$ */ class ContentFragmentTestImpl implements Fragment, ContentFragment { + private Fragment f; + private boolean instantlyRendered; /** @@ -52,8 +56,9 @@ { this(f, list, false); } - - public ContentFragmentTestImpl(Fragment f, HashMap list, boolean instantlyRendered) + + public ContentFragmentTestImpl(Fragment f, HashMap list, + boolean instantlyRendered) { this.f = f; this.instantlyRendered = instantlyRendered; @@ -61,9 +66,9 @@ public PortletContent getPortletContent() { - return null; + return null; } - + /** * @param actions * @throws SecurityException @@ -90,7 +95,7 @@ { f.checkPermissions(mask); } - + public SecurityConstraint newSecurityConstraint() { return f.newSecurityConstraint(); @@ -101,7 +106,7 @@ return f.newSecurityConstraints(); } - /** + /** * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) @@ -157,7 +162,6 @@ return f.getPermissionsEnabled(); } - /** * @return security constraints */ @@ -167,7 +171,7 @@ } /** - * @return short title + * @return short title */ public String getShortTitle() { @@ -214,7 +218,7 @@ return f.getType(); } - /** + /** * @see java.lang.Object#hashCode() */ public int hashCode() @@ -302,7 +306,7 @@ f.setType(type); } - /** + /** * @see java.lang.Object#toString() */ public String toString() @@ -310,7 +314,7 @@ return f.toString(); } - /** + /** * @see org.apache.jetspeed.om.page.ContentFragment#getContentFragments() */ public List getContentFragments() @@ -318,7 +322,7 @@ return null; } - /** + /** * @see org.apache.jetspeed.om.page.ContentFragment#getRenderedContent() */ public String getRenderedContent() throws IllegalStateException @@ -326,14 +330,16 @@ return null; } - /** + /** * @see org.apache.jetspeed.om.page.ContentFragment#overrideRenderedContent(java.lang.String) */ public void overrideRenderedContent(String contnent) { } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentFragment#getOverriddenContent() */ public String getOverriddenContent() @@ -341,7 +347,7 @@ return null; } - /** + /** * @see org.apache.jetspeed.om.page.ContentFragment#setPortletContent(org.apache.jetspeed.aggregator.PortletContent) */ public void setPortletContent(PortletContent portletContent) @@ -416,56 +422,56 @@ * @see org.apache.jetspeed.om.page.Fragment#setLayoutRow(int) */ public void setLayoutRow(int row) - { + { } /** * @see org.apache.jetspeed.om.page.Fragment#setLayoutColumn(int) */ public void setLayoutColumn(int column) - { + { } /** * @see org.apache.jetspeed.om.page.Fragment#setLayoutSizes(java.lang.String) */ public void setLayoutSizes(String sizes) - { + { } /** * @see org.apache.jetspeed.om.page.Fragment#setLayoutX(float) */ public void setLayoutX(float x) - { + { } /** * @see org.apache.jetspeed.om.page.Fragment#setLayoutY(float) */ public void setLayoutY(float y) - { + { } /** * @see org.apache.jetspeed.om.page.Fragment#setLayoutZ(float) */ public void setLayoutZ(float z) - { + { } /** * @see org.apache.jetspeed.om.page.Fragment#setLayoutWidth(float) */ public void setLayoutWidth(float width) - { + { } /** * @see org.apache.jetspeed.om.page.Fragment#setLayoutHeight(float) */ public void setLayoutHeight(float height) - { + { } /** @@ -524,10 +530,12 @@ public void setDecoration(Decoration decoration) { // TODO Auto-generated method stub - - } - /* (non-Javadoc) + } + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.om.page.ContentFragment#isInstantlyRendered() */ public boolean isInstantlyRendered() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletentity/TestPortletEntityDAO.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletentity/TestPortletEntityDAO.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletentity/TestPortletEntityDAO.java 2008-05-16 01:54:54 UTC (rev 940) @@ -51,6 +51,7 @@ */ public class TestPortletEntityDAO extends DatasourceEnabledSpringTestCase { + private static final String TEST_APP = "EntityTestApp"; private static final String TEST_PORTLET = "EntityTestPortlet"; @@ -65,7 +66,8 @@ { super.setUp(); this.registry = (PortletRegistry) ctx.getBean("portletRegistry"); - this.entityAccess = (PersistenceBrokerPortletEntityAccess) ctx.getBean("portletEntityAccessImpl"); + this.entityAccess = (PersistenceBrokerPortletEntityAccess) ctx + .getBean("portletEntityAccessImpl"); teardownTestData(); setupTestData(); @@ -84,7 +86,8 @@ public void testEntities() throws Exception { - PortletApplicationDefinition pa = registry.getPortletApplication(TEST_APP); + PortletApplicationDefinition pa = registry + .getPortletApplication(TEST_APP); assertNotNull("Portlet Application", pa); System.out.println("pa = " + pa.getId()); PortletDefinitionList portlets = pa.getPortletDefinitionList(); // .get(JetspeedObjectID.createFromString(TEST_PORTLET)); @@ -93,25 +96,31 @@ while (pi.hasNext()) { pd = (PortletDefinitionComposite) pi.next(); - assertTrue("Portlet Def not found", pd.getName().equals("EntityTestPortlet")); + assertTrue("Portlet Def not found", pd.getName().equals( + "EntityTestPortlet")); } assertNotNull("Portlet Def is null", pd); Mock mockf1 = new Mock(Fragment.class); - mockf1.expects(new InvokeAtLeastOnceMatcher()).method("getName").will(new ReturnStub(pd.getUniqueName())); - mockf1.expects(new InvokeAtLeastOnceMatcher()).method("getId").will(new ReturnStub(TEST_ENTITY)); - ContentFragment f1 = new ContentFragmentTestImpl((Fragment) mockf1.proxy(), new HashMap()); + mockf1.expects(new InvokeAtLeastOnceMatcher()).method("getName").will( + new ReturnStub(pd.getUniqueName())); + mockf1.expects(new InvokeAtLeastOnceMatcher()).method("getId").will( + new ReturnStub(TEST_ENTITY)); + ContentFragment f1 = new ContentFragmentTestImpl((Fragment) mockf1 + .proxy(), new HashMap()); MutablePortletEntity entity = entityAccess - .generateEntityFromFragment(new ContentFragmentTestImpl(f1, new HashMap())); - PreferenceSetComposite prefs = (PreferenceSetComposite) entity.getPreferenceSet(); + .generateEntityFromFragment(new ContentFragmentTestImpl(f1, + new HashMap())); + PreferenceSetComposite prefs = (PreferenceSetComposite) entity + .getPreferenceSet(); prefs.remove("pref1"); assertNotNull(prefs); assertNull(prefs.get("pref1")); // test adding a pref prefs.add("pref1", Arrays.asList(new String[] - { "1" })); + {"1"})); assertNotNull(prefs.get("pref1")); // Remove should return the deleted pref @@ -122,7 +131,7 @@ // Add it back so we can test tole back prefs.add("pref1", Arrays.asList(new String[] - { "1" })); + {"1"})); entityAccess.storePortletEntity(entity); @@ -153,7 +162,7 @@ assertNotNull(prefs.get("pref1")); prefs.add("pref2", Arrays.asList(new String[] - { "2", "3" })); + {"2", "3"})); entity.store(); @@ -193,13 +202,14 @@ assertEquals(2, count); // testing preferences null values assignments fix, issue JS2-607 - pref2.setValueAt(0, null); - assertNull("pref2.value[0] should be null", pref2.getValueAt(0)); + pref2.setValueAt(0, null); + assertNull("pref2.value[0] should be null", pref2.getValueAt(0)); String[] values = pref2.getValueArray(); assertEquals(2, values.length); assertNull("pref2.value[0] should be null", values[0]); assertEquals("3", values[1]); - pref2.setValues(new String[]{"2",null,"3"}); + pref2.setValues(new String[] + {"2", null, "3"}); assertNull("pref2.value[1] should be null", pref2.getValueAt(1)); values = pref2.getValueArray(); assertEquals(3, values.length); @@ -207,35 +217,42 @@ assertNull("pref2.value[1] should be null", values[1]); assertEquals("3", values[2]); assertTrue(pref2.isValueSet()); - pref2.setValues((String[])null); + pref2.setValues((String[]) null); assertFalse(pref2.isValueSet()); assertTrue(pref2.getValueArray().length == 0); entity.reset(); assertTrue(pref2.getValueArray().length == 2); - pref2.setValues(new String[]{}); + pref2.setValues(new String[] + {}); assertFalse(pref2.isValueSet()); assertTrue(pref2.getValueArray().length == 0); entity.reset(); assertTrue(pref2.getValueArray().length == 2); - MutablePortletEntity entity2 = entityAccess.getPortletEntityForFragment(f1); + MutablePortletEntity entity2 = entityAccess + .getPortletEntityForFragment(f1); assertTrue("entity id ", entity2.getId().toString().equals(TEST_ENTITY)); assertNotNull("entity's portlet ", entity2.getPortletDefinition()); mockf1.verify(); Mock mockf2 = new Mock(Fragment.class); - mockf2.expects(new InvokeAtLeastOnceMatcher()).method("getName").will(new ReturnStub(pd.getUniqueName())); - ContentFragment f2 = new ContentFragmentTestImpl((Fragment) mockf2.proxy(), new HashMap()); + mockf2.expects(new InvokeAtLeastOnceMatcher()).method("getName").will( + new ReturnStub(pd.getUniqueName())); + ContentFragment f2 = new ContentFragmentTestImpl((Fragment) mockf2 + .proxy(), new HashMap()); - MutablePortletEntity entity5 = entityAccess.newPortletEntityInstance(pd); + MutablePortletEntity entity5 = entityAccess + .newPortletEntityInstance(pd); System.out.println("before storing entity: " + entity5.getId()); entityAccess.storePortletEntity(entity5); System.out.println("store done: " + entity5.getId()); - mockf2.expects(new InvokeAtLeastOnceMatcher()).method("getId").will(new ReturnStub(entity5.getId().toString())); + mockf2.expects(new InvokeAtLeastOnceMatcher()).method("getId").will( + new ReturnStub(entity5.getId().toString())); - MutablePortletEntity entity6 = entityAccess.getPortletEntityForFragment(f2); + MutablePortletEntity entity6 = entityAccess + .getPortletEntityForFragment(f2); assertNotNull(entity6); System.out.println("reget : " + entity6.getId()); @@ -255,26 +272,34 @@ entityAccess.removePortletEntity(entity); } - PortletApplicationDefinition pa = registry.getPortletApplication(TEST_APP); + PortletApplicationDefinition pa = registry + .getPortletApplication(TEST_APP); System.out.println("pa == " + pa); if (pa != null) { registry.removeApplication(pa); } - if (Preferences.systemRoot().nodeExists(MutablePortletApplication.PREFS_ROOT)) + if (Preferences.systemRoot().nodeExists( + MutablePortletApplication.PREFS_ROOT)) { - Preferences.systemRoot().node(MutablePortletApplication.PREFS_ROOT).removeNode(); + Preferences.systemRoot().node(MutablePortletApplication.PREFS_ROOT) + .removeNode(); } - if (Preferences.userRoot().nodeExists(PortletDefinitionComposite.PORTLETS_PREFS_ROOT)) + if (Preferences.userRoot().nodeExists( + PortletDefinitionComposite.PORTLETS_PREFS_ROOT)) { - Preferences.userRoot().node(PortletDefinitionComposite.PORTLETS_PREFS_ROOT).removeNode(); + Preferences.userRoot().node( + PortletDefinitionComposite.PORTLETS_PREFS_ROOT) + .removeNode(); } - if (Preferences.userRoot().nodeExists(MutablePortletEntity.PORTLET_ENTITY_ROOT)) + if (Preferences.userRoot().nodeExists( + MutablePortletEntity.PORTLET_ENTITY_ROOT)) { - Preferences.userRoot().node(MutablePortletEntity.PORTLET_ENTITY_ROOT).removeNode(); + Preferences.userRoot().node( + MutablePortletEntity.PORTLET_ENTITY_ROOT).removeNode(); } } @@ -288,8 +313,10 @@ WebApplicationDefinitionImpl webApp = new WebApplicationDefinitionImpl(); webApp.setContextRoot("/app1"); - webApp.addDescription(Locale.FRENCH, "Description: Le fromage est dans mon pantalon!"); - webApp.addDisplayName(Locale.FRENCH, "Display Name: Le fromage est dans mon pantalon!"); + webApp.addDescription(Locale.FRENCH, + "Description: Le fromage est dans mon pantalon!"); + webApp.addDisplayName(Locale.FRENCH, + "Display Name: Le fromage est dans mon pantalon!"); PortletDefinitionComposite portlet = new PortletDefinitionImpl(); portlet.setClassName("org.apache.Portlet"); @@ -297,15 +324,17 @@ portlet.addDescription(Locale.getDefault(), "Portlet description."); portlet.addDisplayName(Locale.getDefault(), "Portlet display Name."); - portlet.addInitParameter("testparam", "test value", "This is a test portlet parameter", Locale.getDefault()); + portlet.addInitParameter("testparam", "test value", + "This is a test portlet parameter", Locale.getDefault()); app.addPortletDefinition(portlet); app.setWebApplicationDefinition(webApp); - PreferenceSetComposite prefSet = (PreferenceSetComposite) portlet.getPreferenceSet(); + PreferenceSetComposite prefSet = (PreferenceSetComposite) portlet + .getPreferenceSet(); prefSet.add("pref1", Arrays.asList(new String[] - { "1" })); + {"1"})); registry.registerPortletApplication(app); } @@ -313,6 +342,6 @@ protected String[] getConfigurations() { return new String[] - { "transaction.xml", "registry-test.xml", "prefs.xml", "cache.xml" }; + {"transaction.xml", "registry-test.xml", "prefs.xml", "cache.xml"}; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/AbstractRegistryTest.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/AbstractRegistryTest.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/AbstractRegistryTest.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,7 +32,8 @@ /** * @author scott */ -public abstract class AbstractRegistryTest extends DatasourceEnabledSpringTestCase +public abstract class AbstractRegistryTest extends + DatasourceEnabledSpringTestCase { protected static final String PORTLET_0_CLASS = "com.portlet.MyClass0"; @@ -85,7 +86,7 @@ */ protected void tearDown() throws Exception { - //super.tearDown(); + // super.tearDown(); } protected void validateDublinCore(GenericMetadata metadata) @@ -127,8 +128,10 @@ app = registry.getPortletApplication("App_1"); - webApp = (WebApplicationDefinitionImpl) app.getWebApplicationDefinition(); - portlet = (PortletDefinitionImpl) app.getPortletDefinitionByName("Portlet 1"); + webApp = (WebApplicationDefinitionImpl) app + .getWebApplicationDefinition(); + portlet = (PortletDefinitionImpl) app + .getPortletDefinitionByName("Portlet 1"); assertNotNull("Failed to reteive portlet application", app); @@ -138,17 +141,22 @@ assertNotNull("jetspeed services is null", services); System.out.println("services is " + services); - assertNotNull("Failed to reteive portlet application via registry", registry.getPortletApplication("App_1")); - assertNotNull("Web app was not saved along with the portlet app.", webApp); - assertNotNull("Portlet was not saved along with the portlet app.", app.getPortletDefinitionByName("Portlet 1")); + assertNotNull("Failed to reteive portlet application via registry", + registry.getPortletApplication("App_1")); + assertNotNull("Web app was not saved along with the portlet app.", + webApp); + assertNotNull("Portlet was not saved along with the portlet app.", app + .getPortletDefinitionByName("Portlet 1")); if (!afterUpdates) { - assertTrue("\"user.name.family\" user attribute was not found.", app.getUserAttributes().size() == 1); + assertTrue("\"user.name.family\" user attribute was not found.", + app.getUserAttributes().size() == 1); } else { - assertTrue("\"user.name.family\" and user.pets user attributes were not found.", app.getUserAttributes() - .size() == 2); + assertTrue( + "\"user.name.family\" and user.pets user attributes were not found.", + app.getUserAttributes().size() == 2); } @@ -158,18 +166,31 @@ validateDublinCore(portlet.getMetadata()); - assertNotNull("Portlet Application was not set in the portlet defintion.", portlet - .getPortletApplicationDefinition()); - assertNotNull("French description was not materialized for the web app.", webApp.getDescription(Locale.FRENCH)); - assertNotNull("French display name was not materialized for the web app.", webApp.getDisplayName(Locale.FRENCH)); - assertNotNull("description was not materialized for the portlet.", portlet.getDescription(Locale.getDefault())); - assertNotNull("display name was not materialized for the portlet.", portlet.getDisplayName(Locale.getDefault())); - assertNotNull("\"testparam\" portlet parameter was not saved", portlet.getInitParameterSet().get("testparam")); - assertNotNull("\"preference 1\" was not found.", portlet.getPreferenceSet().get("preference 1")); - assertNotNull("Language information not found for Portlet 1", portlet.getLanguageSet().get(Locale.getDefault())); - assertNotNull("Content Type html not found.", portlet.getContentTypeSet().get("html/text")); - assertNotNull("Content Type wml not found.", portlet.getContentTypeSet().get("wml")); - Iterator itr = portlet.getPreferenceSet().get("preference 1").getValues(); + assertNotNull( + "Portlet Application was not set in the portlet defintion.", + portlet.getPortletApplicationDefinition()); + assertNotNull( + "French description was not materialized for the web app.", + webApp.getDescription(Locale.FRENCH)); + assertNotNull( + "French display name was not materialized for the web app.", + webApp.getDisplayName(Locale.FRENCH)); + assertNotNull("description was not materialized for the portlet.", + portlet.getDescription(Locale.getDefault())); + assertNotNull("display name was not materialized for the portlet.", + portlet.getDisplayName(Locale.getDefault())); + assertNotNull("\"testparam\" portlet parameter was not saved", portlet + .getInitParameterSet().get("testparam")); + assertNotNull("\"preference 1\" was not found.", portlet + .getPreferenceSet().get("preference 1")); + assertNotNull("Language information not found for Portlet 1", portlet + .getLanguageSet().get(Locale.getDefault())); + assertNotNull("Content Type html not found.", portlet + .getContentTypeSet().get("html/text")); + assertNotNull("Content Type wml not found.", portlet + .getContentTypeSet().get("wml")); + Iterator itr = portlet.getPreferenceSet().get("preference 1") + .getValues(); int valueCount = 0; while (itr.hasNext()) @@ -185,24 +206,27 @@ app = registry.getPortletApplication("App_1"); - webApp = (WebApplicationDefinitionImpl) app.getWebApplicationDefinition(); + webApp = (WebApplicationDefinitionImpl) app + .getWebApplicationDefinition(); assertNotNull("Web app was not located by query.", webApp); webApp.addDescription(Locale.getDefault(), "Web app description"); webApp = null; app = registry.getPortletApplication("App_1"); - webApp = (WebApplicationDefinitionImpl) app.getWebApplicationDefinition(); + webApp = (WebApplicationDefinitionImpl) app + .getWebApplicationDefinition(); assertNotNull("Web app was not located by query.", webApp); - assertNotNull("Web app did NOT persist its description", webApp.getDescription(Locale.FRENCH)); + assertNotNull("Web app did NOT persist its description", webApp + .getDescription(Locale.FRENCH)); } protected String[] getConfigurations() { return new String[] - { "transaction.xml", "prefs.xml", "registry-test.xml", "cache.xml" }; + {"transaction.xml", "prefs.xml", "registry-test.xml", "cache.xml"}; } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/TestPortletRegistryDAO.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/TestPortletRegistryDAO.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/TestPortletRegistryDAO.java 2008-05-16 01:54:54 UTC (rev 940) @@ -56,6 +56,7 @@ */ public class TestPortletRegistryDAO extends DatasourceEnabledSpringTestCase { + public static final String APP_1_NAME = "RegistryTestPortlet"; protected static final String MODE_EDIT = "EDIT"; @@ -98,7 +99,9 @@ Iterator itr = portletRegistry.getPortletApplications().iterator(); while (itr.hasNext()) { - portletRegistry.removeApplication((PortletApplicationDefinition) itr.next()); + portletRegistry + .removeApplication((PortletApplicationDefinition) itr + .next()); } } @@ -148,7 +151,9 @@ Iterator itr = portletRegistry.getPortletApplications().iterator(); while (itr.hasNext()) { - portletRegistry.removeApplication((PortletApplicationDefinition) itr.next()); + portletRegistry + .removeApplication((PortletApplicationDefinition) itr + .next()); } // Create an Application and a Web app @@ -157,23 +162,29 @@ app.setName("App_1"); app.setApplicationIdentifier("App_1"); - UserAttributeRef uaRef = new UserAttributeRefImpl("user-name-family", "user.name.family"); + UserAttributeRef uaRef = new UserAttributeRefImpl("user-name-family", + "user.name.family"); app.addUserAttributeRef(uaRef); - UserAttribute ua = new UserAttributeImpl("user.name.family", "User Last Name"); + UserAttribute ua = new UserAttributeImpl("user.name.family", + "User Last Name"); app.addUserAttribute(ua); - JetspeedServiceReference service1 = new JetspeedServiceReferenceImpl("PortletEntityAccessComponent"); + JetspeedServiceReference service1 = new JetspeedServiceReferenceImpl( + "PortletEntityAccessComponent"); app.addJetspeedService(service1); - JetspeedServiceReference service2 = new JetspeedServiceReferenceImpl("PortletRegistryComponent"); + JetspeedServiceReference service2 = new JetspeedServiceReferenceImpl( + "PortletRegistryComponent"); app.addJetspeedService(service2); addDublinCore(app.getMetadata()); WebApplicationDefinitionImpl webApp = new WebApplicationDefinitionImpl(); webApp.setContextRoot("/app1"); - webApp.addDescription(Locale.FRENCH, "Description: Le fromage est dans mon pantalon!"); - webApp.addDisplayName(Locale.FRENCH, "Display Name: Le fromage est dans mon pantalon!"); + webApp.addDescription(Locale.FRENCH, + "Description: Le fromage est dans mon pantalon!"); + webApp.addDisplayName(Locale.FRENCH, + "Display Name: Le fromage est dans mon pantalon!"); PortletDefinitionComposite portlet = new PortletDefinitionImpl(); portlet.setClassName("org.apache.Portlet"); @@ -181,21 +192,25 @@ portlet.addDescription(Locale.getDefault(), "POrtlet description."); portlet.addDisplayName(Locale.getDefault(), "Portlet display Name."); - portlet.addInitParameter("testparam", "test value", "This is a test portlet parameter", Locale.getDefault()); + portlet.addInitParameter("testparam", "test value", + "This is a test portlet parameter", Locale.getDefault()); addDublinCore(portlet.getMetadata()); // PreferenceComposite pc = new PrefsPreference(); app.addPortletDefinition(portlet); - PreferenceSetCtrl prefSetCtrl = (PreferenceSetCtrl) portlet.getPreferenceSet(); - PreferenceComposite pc = (PreferenceComposite) prefSetCtrl.add("preference 1", Arrays.asList(new String[] - { "value 1", "value 2" })); - pc.addDescription(JetspeedLocale.getDefaultLocale(), "Preference Description"); + PreferenceSetCtrl prefSetCtrl = (PreferenceSetCtrl) portlet + .getPreferenceSet(); + PreferenceComposite pc = (PreferenceComposite) prefSetCtrl.add( + "preference 1", Arrays.asList(new String[] + {"value 1", "value 2"})); + pc.addDescription(JetspeedLocale.getDefaultLocale(), + "Preference Description"); assertNotNull(pc.getValueAt(0)); - portlet.addLanguage(portletRegistry.createLanguage(Locale.getDefault(), "Portlet 1", "Portlet 1", - "This is Portlet 1", null)); + portlet.addLanguage(portletRegistry.createLanguage(Locale.getDefault(), + "Portlet 1", "Portlet 1", "This is Portlet 1", null)); ContentTypeComposite html = new ContentTypeImpl(); html.setContentType("html/text"); @@ -227,8 +242,10 @@ assertNotNull(app); - webApp = (WebApplicationDefinitionImpl) app.getWebApplicationDefinition(); - portlet = (PortletDefinitionImpl) app.getPortletDefinitionByName("Portlet 1"); + webApp = (WebApplicationDefinitionImpl) app + .getWebApplicationDefinition(); + portlet = (PortletDefinitionImpl) app + .getPortletDefinitionByName("Portlet 1"); assertNotNull("Failed to reteive portlet application", app); @@ -238,39 +255,57 @@ assertNotNull("jetspeed services is null", services); System.out.println("services is " + services); - assertNotNull("Failed to reteive portlet application via registry", portletRegistry - .getPortletApplication("App_1")); - assertNotNull("Web app was not saved along with the portlet app.", webApp); - assertNotNull("Portlet was not saved along with the portlet app.", app.getPortletDefinitionByName("Portlet 1")); + assertNotNull("Failed to reteive portlet application via registry", + portletRegistry.getPortletApplication("App_1")); + assertNotNull("Web app was not saved along with the portlet app.", + webApp); + assertNotNull("Portlet was not saved along with the portlet app.", app + .getPortletDefinitionByName("Portlet 1")); if (!afterUpdates) { - assertTrue("\"user.name.family\" user attribute was not found.", app.getUserAttributes().size() == 1); + assertTrue("\"user.name.family\" user attribute was not found.", + app.getUserAttributes().size() == 1); } else { - assertTrue("\"user.name.family\" and user.pets user attributes were not found.", app.getUserAttributes() - .size() == 2); + assertTrue( + "\"user.name.family\" and user.pets user attributes were not found.", + app.getUserAttributes().size() == 2); } - portlet = portletRegistry.getPortletDefinitionByUniqueName("App_1::Portlet 1"); + portlet = portletRegistry + .getPortletDefinitionByUniqueName("App_1::Portlet 1"); assertNotNull("Portlet could not be retreived by unique name.", portlet); validateDublinCore(portlet.getMetadata()); - assertNotNull("Portlet Application was not set in the portlet defintion.", portlet - .getPortletApplicationDefinition()); - assertNotNull("French description was not materialized for the web app.", webApp.getDescription(Locale.FRENCH)); - assertNotNull("French display name was not materialized for the web app.", webApp.getDisplayName(Locale.FRENCH)); - assertNotNull("description was not materialized for the portlet.", portlet.getDescription(Locale.getDefault())); - assertNotNull("display name was not materialized for the portlet.", portlet.getDisplayName(Locale.getDefault())); - assertNotNull("\"testparam\" portlet parameter was not saved", portlet.getInitParameterSet().get("testparam")); - assertNotNull("\"preference 1\" was not found.", portlet.getPreferenceSet().get("preference 1")); - assertNotNull("Language information not found for Portlet 1", portlet.getLanguageSet().get(Locale.getDefault())); - assertNotNull("Content Type html not found.", portlet.getContentTypeSet().get("html/text")); - assertNotNull("Content Type wml not found.", portlet.getContentTypeSet().get("wml")); - Iterator itr = portlet.getPreferenceSet().get("preference 1").getValues(); + assertNotNull( + "Portlet Application was not set in the portlet defintion.", + portlet.getPortletApplicationDefinition()); + assertNotNull( + "French description was not materialized for the web app.", + webApp.getDescription(Locale.FRENCH)); + assertNotNull( + "French display name was not materialized for the web app.", + webApp.getDisplayName(Locale.FRENCH)); + assertNotNull("description was not materialized for the portlet.", + portlet.getDescription(Locale.getDefault())); + assertNotNull("display name was not materialized for the portlet.", + portlet.getDisplayName(Locale.getDefault())); + assertNotNull("\"testparam\" portlet parameter was not saved", portlet + .getInitParameterSet().get("testparam")); + assertNotNull("\"preference 1\" was not found.", portlet + .getPreferenceSet().get("preference 1")); + assertNotNull("Language information not found for Portlet 1", portlet + .getLanguageSet().get(Locale.getDefault())); + assertNotNull("Content Type html not found.", portlet + .getContentTypeSet().get("html/text")); + assertNotNull("Content Type wml not found.", portlet + .getContentTypeSet().get("wml")); + Iterator itr = portlet.getPreferenceSet().get("preference 1") + .getValues(); int valueCount = 0; while (itr.hasNext()) @@ -285,17 +320,20 @@ app = portletRegistry.getPortletApplication("App_1"); - webApp = (WebApplicationDefinitionImpl) app.getWebApplicationDefinition(); + webApp = (WebApplicationDefinitionImpl) app + .getWebApplicationDefinition(); assertNotNull("Web app was not located by query.", webApp); webApp.addDescription(Locale.getDefault(), "Web app description"); webApp = null; app = portletRegistry.getPortletApplication("App_1"); - webApp = (WebApplicationDefinitionImpl) app.getWebApplicationDefinition(); + webApp = (WebApplicationDefinitionImpl) app + .getWebApplicationDefinition(); assertNotNull("Web app was not located by query.", webApp); - assertNotNull("Web app did NOT persist its description", webApp.getDescription(Locale.FRENCH)); + assertNotNull("Web app did NOT persist its description", webApp + .getDescription(Locale.FRENCH)); } @@ -321,6 +359,6 @@ protected String[] getConfigurations() { return new String[] - { "transaction.xml", "registry-test.xml", "prefs.xml", "cache.xml" }; + {"transaction.xml", "registry-test.xml", "prefs.xml", "cache.xml"}; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/TestRegistryCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/TestRegistryCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/TestRegistryCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -52,6 +52,7 @@ */ public class TestRegistryCache extends DatasourceEnabledSpringTestCase { + protected PortletRegistry portletRegistry; /* @@ -69,62 +70,77 @@ // impl not complete public void xtestProxy() throws Exception { - MutablePortletApplication app = portletRegistry.getPortletApplication("PA-001"); - MutablePortletApplication cached = MutablePortletApplicationProxy.createProxy(app); + MutablePortletApplication app = portletRegistry + .getPortletApplication("PA-001"); + MutablePortletApplication cached = MutablePortletApplicationProxy + .createProxy(app); if (cached instanceof MutablePortletApplication) System.out.println("ISA Mutable"); if (cached instanceof PortletApplicationProxy) System.out.println("ISA Mutable Proxy"); - PortletApplicationProxy proxy = (PortletApplicationProxy)cached; + PortletApplicationProxy proxy = (PortletApplicationProxy) cached; MutablePortletApplication two = proxy.getRealApplication(); proxy.setRealApplication(two); System.out.println("Two is " + two); assertEquals(app, two); } - + public void testCache() throws Exception { assertNotNull(portletRegistry); - MutablePortletApplication one = portletRegistry.getPortletApplication("PA-001"); - MutablePortletApplication two = portletRegistry.getPortletApplication("PA-001"); + MutablePortletApplication one = portletRegistry + .getPortletApplication("PA-001"); + MutablePortletApplication two = portletRegistry + .getPortletApplication("PA-001"); assertEquals(one, two); - PortletDefinitionComposite def = portletRegistry.getPortletDefinitionByUniqueName("PA-001::Portlet-1"); + PortletDefinitionComposite def = portletRegistry + .getPortletDefinitionByUniqueName("PA-001::Portlet-1"); assertNotNull(def); assertEquals(def.getPortletApplicationDefinition(), one); assertEquals(def, two.getPortletDefinitions().iterator().next()); - MutablePortletApplication o = (MutablePortletApplication)portletRegistry.getPortletApplications().iterator().next(); + MutablePortletApplication o = (MutablePortletApplication) portletRegistry + .getPortletApplications().iterator().next(); assertEquals(one, o); - assertEquals(portletRegistry.getAllPortletDefinitions().iterator().next(), def); + assertEquals(portletRegistry.getAllPortletDefinitions().iterator() + .next(), def); } - + private void buildTestData() throws RegistryException, LockFailedException { // start clean Iterator itr = portletRegistry.getPortletApplications().iterator(); while (itr.hasNext()) { - portletRegistry.removeApplication((PortletApplicationDefinition) itr.next()); + portletRegistry + .removeApplication((PortletApplicationDefinition) itr + .next()); } // Create an Application and a Web app PortletApplicationDefinitionImpl app = new PortletApplicationDefinitionImpl(); app.setName("PA-001"); - UserAttributeRef uaRef = new UserAttributeRefImpl("user-name-family", "user.name.family"); + UserAttributeRef uaRef = new UserAttributeRefImpl("user-name-family", + "user.name.family"); app.addUserAttributeRef(uaRef); - UserAttribute ua = new UserAttributeImpl("user.name.family", "User Last Name"); + UserAttribute ua = new UserAttributeImpl("user.name.family", + "User Last Name"); app.addUserAttribute(ua); - JetspeedServiceReference service1 = new JetspeedServiceReferenceImpl("PortletEntityAccessComponent"); + JetspeedServiceReference service1 = new JetspeedServiceReferenceImpl( + "PortletEntityAccessComponent"); app.addJetspeedService(service1); - JetspeedServiceReference service2 = new JetspeedServiceReferenceImpl("PortletRegistryComponent"); + JetspeedServiceReference service2 = new JetspeedServiceReferenceImpl( + "PortletRegistryComponent"); app.addJetspeedService(service2); WebApplicationDefinitionImpl webApp = new WebApplicationDefinitionImpl(); webApp.setContextRoot("/pa-001"); - webApp.addDescription(Locale.FRENCH, "Description: Le fromage est dans mon pantalon!"); - webApp.addDisplayName(Locale.FRENCH, "Display Name: Le fromage est dans mon pantalon!"); + webApp.addDescription(Locale.FRENCH, + "Description: Le fromage est dans mon pantalon!"); + webApp.addDisplayName(Locale.FRENCH, + "Display Name: Le fromage est dans mon pantalon!"); PortletDefinitionComposite portlet = new PortletDefinitionImpl(); portlet.setClassName("org.apache.Portlet"); @@ -132,20 +148,24 @@ portlet.addDescription(Locale.getDefault(), "POrtlet description."); portlet.addDisplayName(Locale.getDefault(), "Portlet display Name."); - portlet.addInitParameter("testparam", "test value", "This is a test portlet parameter", Locale.getDefault()); + portlet.addInitParameter("testparam", "test value", + "This is a test portlet parameter", Locale.getDefault()); // PreferenceComposite pc = new PrefsPreference(); app.addPortletDefinition(portlet); - PreferenceSetCtrl prefSetCtrl = (PreferenceSetCtrl) portlet.getPreferenceSet(); - PreferenceComposite pc = (PreferenceComposite) prefSetCtrl.add("preference 1", Arrays.asList(new String[] - { "value 1", "value 2" })); - pc.addDescription(JetspeedLocale.getDefaultLocale(), "Preference Description"); + PreferenceSetCtrl prefSetCtrl = (PreferenceSetCtrl) portlet + .getPreferenceSet(); + PreferenceComposite pc = (PreferenceComposite) prefSetCtrl.add( + "preference 1", Arrays.asList(new String[] + {"value 1", "value 2"})); + pc.addDescription(JetspeedLocale.getDefaultLocale(), + "Preference Description"); assertNotNull(pc.getValueAt(0)); - portlet.addLanguage(portletRegistry.createLanguage(Locale.getDefault(), "Portlet 1", "Portlet 1", - "This is Portlet 1", null)); + portlet.addLanguage(portletRegistry.createLanguage(Locale.getDefault(), + "Portlet 1", "Portlet 1", "This is Portlet 1", null)); ContentTypeComposite html = new ContentTypeImpl(); html.setContentType("html/text"); @@ -161,7 +181,8 @@ app.setWebApplicationDefinition(webApp); portletRegistry.updatePortletApplication(app); - } + } + /* * @see TestCase#tearDown() */ @@ -170,14 +191,16 @@ Iterator itr = portletRegistry.getPortletApplications().iterator(); while (itr.hasNext()) { - portletRegistry.removeApplication((PortletApplicationDefinition) itr.next()); + portletRegistry + .removeApplication((PortletApplicationDefinition) itr + .next()); } } - + protected String[] getConfigurations() { return new String[] - { "transaction.xml", "registry-test.xml", "prefs.xml", "cache.xml" }; + {"transaction.xml", "registry-test.xml", "prefs.xml", "cache.xml"}; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectAll.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectAll.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectAll.java 2008-05-16 01:54:54 UTC (rev 940) @@ -47,13 +47,13 @@ * * TestRegistry runs a suite tests creating, updating, retreiving and deleting * portlet information from the registry. - * - * Aggregation of Part1a, Part1b, and Part2a tests that do not - * get executed in a predictable order by maven/junit. * + * Aggregation of Part1a, Part1b, and Part2a tests that do not get executed in a + * predictable order by maven/junit. + * * @author Randy Watler * @version $Id$ - * + * */ public class TestRegistryDirectAll extends AbstractRegistryTest { @@ -77,11 +77,9 @@ */ protected void tearDown() throws Exception { - // super.tearDown(); + // super.tearDown(); } - - /** *

      * buildTestData @@ -92,28 +90,34 @@ */ private void buildTestData() throws RegistryException, LockFailedException { - // Create an Application and a Web app + // Create an Application and a Web app PortletApplicationDefinitionImpl app = new PortletApplicationDefinitionImpl(); app.setName("App_1"); app.setApplicationIdentifier("App_1"); - UserAttributeRef uaRef = new UserAttributeRefImpl("user-name-family", "user.name.family"); + UserAttributeRef uaRef = new UserAttributeRefImpl("user-name-family", + "user.name.family"); app.addUserAttributeRef(uaRef); - UserAttribute ua = new UserAttributeImpl("user.name.family", "User Last Name"); + UserAttribute ua = new UserAttributeImpl("user.name.family", + "User Last Name"); app.addUserAttribute(ua); - JetspeedServiceReference service1 = new JetspeedServiceReferenceImpl("PortletEntityAccessComponent"); + JetspeedServiceReference service1 = new JetspeedServiceReferenceImpl( + "PortletEntityAccessComponent"); app.addJetspeedService(service1); - JetspeedServiceReference service2 = new JetspeedServiceReferenceImpl("PortletRegistryComponent"); + JetspeedServiceReference service2 = new JetspeedServiceReferenceImpl( + "PortletRegistryComponent"); app.addJetspeedService(service2); addDublinCore(app.getMetadata()); WebApplicationDefinitionImpl webApp = new WebApplicationDefinitionImpl(); webApp.setContextRoot("/app1"); - webApp.addDescription(Locale.FRENCH, "Description: Le fromage est dans mon pantalon!"); - webApp.addDisplayName(Locale.FRENCH, "Display Name: Le fromage est dans mon pantalon!"); + webApp.addDescription(Locale.FRENCH, + "Description: Le fromage est dans mon pantalon!"); + webApp.addDisplayName(Locale.FRENCH, + "Display Name: Le fromage est dans mon pantalon!"); PortletDefinitionComposite portlet = new PortletDefinitionImpl(); portlet.setClassName("org.apache.Portlet"); @@ -121,21 +125,25 @@ portlet.addDescription(Locale.getDefault(), "Portlet description."); portlet.addDisplayName(Locale.getDefault(), "Portlet display Name."); - portlet.addInitParameter("testparam", "test value", "This is a test portlet parameter", Locale.getDefault()); + portlet.addInitParameter("testparam", "test value", + "This is a test portlet parameter", Locale.getDefault()); addDublinCore(portlet.getMetadata()); // PreferenceComposite pc = new PrefsPreference(); app.addPortletDefinition(portlet); - PreferenceSetCtrl prefSetCtrl = (PreferenceSetCtrl) portlet.getPreferenceSet(); - PreferenceComposite pc = (PreferenceComposite) prefSetCtrl.add("preference 1", Arrays.asList(new String[]{ - "value 1", "value 2"})); - pc.addDescription(JetspeedLocale.getDefaultLocale(), "Preference Description"); + PreferenceSetCtrl prefSetCtrl = (PreferenceSetCtrl) portlet + .getPreferenceSet(); + PreferenceComposite pc = (PreferenceComposite) prefSetCtrl.add( + "preference 1", Arrays.asList(new String[] + {"value 1", "value 2"})); + pc.addDescription(JetspeedLocale.getDefaultLocale(), + "Preference Description"); assertNotNull(pc.getValueAt(0)); - portlet.addLanguage(registry.createLanguage(Locale.getDefault(), "Portlet 1", "Portlet 1", "This is Portlet 1", - null)); + portlet.addLanguage(registry.createLanguage(Locale.getDefault(), + "Portlet 1", "Portlet 1", "This is Portlet 1", null)); ContentTypeComposite html = new ContentTypeImpl(); html.setContentType("html/text"); @@ -153,7 +161,7 @@ registry.registerPortletApplication(app); } - private void addDublinCore( GenericMetadata metadata ) + private void addDublinCore(GenericMetadata metadata) { DublinCore dc = new DublinCoreImpl(metadata); dc.addTitle(JetspeedLocale.getDefaultLocale(), "Test title 1"); @@ -181,13 +189,14 @@ verifyData(false); // Part1b: updates - PortletApplicationDefinitionImpl app = (PortletApplicationDefinitionImpl) registry.getPortletApplication("App_1"); + PortletApplicationDefinitionImpl app = (PortletApplicationDefinitionImpl) registry + .getPortletApplication("App_1"); assertNotNull("PA App_1 is NULL", app); app.addUserAttribute("user.pets.doggie", "Busby"); - - registry.updatePortletApplication(app); - + + registry.updatePortletApplication(app); + System.out.println("PA update test complete"); // Part2a: data Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectPart1a.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectPart1a.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectPart1a.java 2008-05-16 01:54:54 UTC (rev 940) @@ -50,7 +50,7 @@ * * @author Scott T. Weaver * @version $Id: TestRegistryDirectPart1a.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class TestRegistryDirectPart1a extends AbstractRegistryTest { @@ -74,11 +74,9 @@ */ protected void tearDown() throws Exception { - // super.tearDown(); + // super.tearDown(); } - - /** *

      * buildTestData @@ -89,28 +87,34 @@ */ private void buildTestData() throws RegistryException, LockFailedException { - // Create an Application and a Web app + // Create an Application and a Web app PortletApplicationDefinitionImpl app = new PortletApplicationDefinitionImpl(); app.setName("App_1"); app.setApplicationIdentifier("App_1"); - UserAttributeRef uaRef = new UserAttributeRefImpl("user-name-family", "user.name.family"); + UserAttributeRef uaRef = new UserAttributeRefImpl("user-name-family", + "user.name.family"); app.addUserAttributeRef(uaRef); - UserAttribute ua = new UserAttributeImpl("user.name.family", "User Last Name"); + UserAttribute ua = new UserAttributeImpl("user.name.family", + "User Last Name"); app.addUserAttribute(ua); - JetspeedServiceReference service1 = new JetspeedServiceReferenceImpl("PortletEntityAccessComponent"); + JetspeedServiceReference service1 = new JetspeedServiceReferenceImpl( + "PortletEntityAccessComponent"); app.addJetspeedService(service1); - JetspeedServiceReference service2 = new JetspeedServiceReferenceImpl("PortletRegistryComponent"); + JetspeedServiceReference service2 = new JetspeedServiceReferenceImpl( + "PortletRegistryComponent"); app.addJetspeedService(service2); addDublinCore(app.getMetadata()); WebApplicationDefinitionImpl webApp = new WebApplicationDefinitionImpl(); webApp.setContextRoot("/app1"); - webApp.addDescription(Locale.FRENCH, "Description: Le fromage est dans mon pantalon!"); - webApp.addDisplayName(Locale.FRENCH, "Display Name: Le fromage est dans mon pantalon!"); + webApp.addDescription(Locale.FRENCH, + "Description: Le fromage est dans mon pantalon!"); + webApp.addDisplayName(Locale.FRENCH, + "Display Name: Le fromage est dans mon pantalon!"); PortletDefinitionComposite portlet = new PortletDefinitionImpl(); portlet.setClassName("org.apache.Portlet"); @@ -118,21 +122,25 @@ portlet.addDescription(Locale.getDefault(), "Portlet description."); portlet.addDisplayName(Locale.getDefault(), "Portlet display Name."); - portlet.addInitParameter("testparam", "test value", "This is a test portlet parameter", Locale.getDefault()); + portlet.addInitParameter("testparam", "test value", + "This is a test portlet parameter", Locale.getDefault()); addDublinCore(portlet.getMetadata()); // PreferenceComposite pc = new PrefsPreference(); app.addPortletDefinition(portlet); - PreferenceSetCtrl prefSetCtrl = (PreferenceSetCtrl) portlet.getPreferenceSet(); - PreferenceComposite pc = (PreferenceComposite) prefSetCtrl.add("preference 1", Arrays.asList(new String[]{ - "value 1", "value 2"})); - pc.addDescription(JetspeedLocale.getDefaultLocale(), "Preference Description"); + PreferenceSetCtrl prefSetCtrl = (PreferenceSetCtrl) portlet + .getPreferenceSet(); + PreferenceComposite pc = (PreferenceComposite) prefSetCtrl.add( + "preference 1", Arrays.asList(new String[] + {"value 1", "value 2"})); + pc.addDescription(JetspeedLocale.getDefaultLocale(), + "Preference Description"); assertNotNull(pc.getValueAt(0)); - portlet.addLanguage(registry.createLanguage(Locale.getDefault(), "Portlet 1", "Portlet 1", "This is Portlet 1", - null)); + portlet.addLanguage(registry.createLanguage(Locale.getDefault(), + "Portlet 1", "Portlet 1", "This is Portlet 1", null)); ContentTypeComposite html = new ContentTypeImpl(); html.setContentType("html/text"); @@ -150,7 +158,7 @@ registry.registerPortletApplication(app); } - private void addDublinCore( GenericMetadata metadata ) + private void addDublinCore(GenericMetadata metadata) { DublinCore dc = new DublinCoreImpl(metadata); dc.addTitle(JetspeedLocale.getDefaultLocale(), "Test title 1"); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectPart1b.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectPart1b.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectPart1b.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,10 +28,11 @@ * * @author David Sean Taylor * @version $Id: TestRegistryDirectPart1b.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class TestRegistryDirectPart1b extends AbstractRegistryTest { + /* * (non-Javadoc) * @@ -39,7 +40,7 @@ */ protected void setUp() throws Exception { - super.setUp(); + super.setUp(); } /* @@ -49,7 +50,7 @@ */ protected void tearDown() throws Exception { - // super.tearDown(); + // super.tearDown(); } public static Test suite() @@ -57,18 +58,19 @@ // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestRegistryDirectPart1b.class); } - + public void testUpdates() throws Exception { - - PortletApplicationDefinitionImpl app = (PortletApplicationDefinitionImpl) registry.getPortletApplication("App_1"); + + PortletApplicationDefinitionImpl app = (PortletApplicationDefinitionImpl) registry + .getPortletApplication("App_1"); assertNotNull("PA App_1 is NULL", app); app.addUserAttribute("user.pets.doggie", "Busby"); - - registry.updatePortletApplication(app); - + + registry.updatePortletApplication(app); + System.out.println("PA update test complete"); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectPart2a.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectPart2a.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/components/portletregistry/direct/TestRegistryDirectPart2a.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,7 +31,7 @@ * * @author Scott T. Weaver * @version $Id: TestRegistryDirectPart2a.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class TestRegistryDirectPart2a extends AbstractRegistryTest { @@ -54,13 +54,12 @@ protected void tearDown() throws Exception { Iterator itr = registry.getPortletApplications().iterator(); - while(itr.hasNext()) - { - registry.removeApplication((PortletApplicationDefinition)itr.next()); + while (itr.hasNext()) + { + registry.removeApplication((PortletApplicationDefinition) itr + .next()); } - - - + super.tearDown(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/request/MockRequestContextComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/request/MockRequestContextComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/registry/src/test/org/apache/jetspeed/request/MockRequestContextComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,13 +21,15 @@ import javax.servlet.http.HttpServletResponse; /** - * @version $Id: MockRequestContextComponent.java 648040 2008-04-14 22:42:03Z ate $ - * + * @version $Id: MockRequestContextComponent.java 648040 2008-04-14 22:42:03Z + * ate $ + * */ public class MockRequestContextComponent implements RequestContextComponent { - public RequestContext create(HttpServletRequest req, HttpServletResponse resp, ServletConfig config) + public RequestContext create(HttpServletRequest req, + HttpServletResponse resp, ServletConfig config) { return null; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/AbstractRewriter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/AbstractRewriter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/AbstractRewriter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,57 +22,76 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + /** * AbstractRewriter - * + * * @author David Sean Taylor * @version $Id: AbstractRewriter.java 516448 2007-03-09 16:25:47Z ate $ */ public abstract class AbstractRewriter implements Rewriter { + protected final static Log log = LogFactory.getLog(AbstractRewriter.class); - + private String baseUrl = null; - private boolean useProxy = false; - - /* (non-Javadoc) - * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#rewrite(ParserAdaptor, java.io.Reader) + + private boolean useProxy = false; + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#rewrite(ParserAdaptor, + * java.io.Reader) */ - public void parse(ParserAdaptor adaptor, Reader reader) throws RewriterException + public void parse(ParserAdaptor adaptor, Reader reader) + throws RewriterException { - adaptor.parse(this, reader); + adaptor.parse(this, reader); } - - /* (non-Javadoc) - * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#rewrite(ParserAdaptor, java.io.Reader, java.io.Writer) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#rewrite(ParserAdaptor, + * java.io.Reader, java.io.Writer) */ - public void rewrite(ParserAdaptor adaptor, Reader reader, Writer writer) throws RewriterException + public void rewrite(ParserAdaptor adaptor, Reader reader, Writer writer) + throws RewriterException { - adaptor.rewrite(this, reader, writer); + adaptor.rewrite(this, reader, writer); } - - /* (non-Javadoc) - * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#rewriteUrl(java.lang.String, java.lang.String, java.lang.String) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#rewriteUrl(java.lang.String, + * java.lang.String, java.lang.String) */ public abstract String rewriteUrl(String url, String tag, String attribute); - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#setBaseUrl(java.lang.String) */ public void setBaseUrl(String base) { this.baseUrl = base; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#getBaseUrl() */ public String getBaseUrl() { return baseUrl; } + public String getBaseRelativeUrl(String relativeUrl) - { + { try { String baseUrl = getBaseUrl(); @@ -88,80 +107,107 @@ } return relativeUrl; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#getUseProxy() */ public boolean getUseProxy() { return useProxy; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#setUseProxy(boolean) */ public void setUseProxy(boolean useProxy) { - this.useProxy = useProxy; + this.useProxy = useProxy; } - - /* (non-Javadoc) - * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#enterSimpleTagEvent(java.lang.String, MutableAttributes) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#enterSimpleTagEvent(java.lang.String, + * MutableAttributes) */ public boolean enterSimpleTagEvent(String tag, MutableAttributes attrs) { return true; } - - /* (non-Javadoc) - * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#exitSimpleTagEvent(java.lang.String, MutableAttributes) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#exitSimpleTagEvent(java.lang.String, + * MutableAttributes) */ public String exitSimpleTagEvent(String tag, MutableAttributes attrs) { return null; } - - /* (non-Javadoc) - * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#enterStartTagEvent(java.lang.String, MutableAttributes) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#enterStartTagEvent(java.lang.String, + * MutableAttributes) */ public boolean enterStartTagEvent(String tag, MutableAttributes attrs) { return true; } - - /* (non-Javadoc) - * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#exitStartTagEvent(java.lang.String, MutableAttributes) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#exitStartTagEvent(java.lang.String, + * MutableAttributes) */ public String exitStartTagEvent(String tag, MutableAttributes attrs) { return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#enterEndTagEvent(java.lang.String) */ public boolean enterEndTagEvent(String tag) { return true; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#exitEndTagEvent(java.lang.String) */ public String exitEndTagEvent(String tag) { return null; } - - /* (non-Javadoc) - * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#enterText(char[], int) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#enterText(char[], + * int) */ public boolean enterText(char[] values, int param) { return true; } - /* (non-Javadoc) - * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#convertTagEvent(java.lang.String, MutableAttributes) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#convertTagEvent(java.lang.String, + * MutableAttributes) */ public void enterConvertTagEvent(String tag, MutableAttributes attrs) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/BasicRewriter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/BasicRewriter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/BasicRewriter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,60 +19,60 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - /** * BasicRewriter - * + * * @author David Sean Taylor * @version $Id: BasicRewriter.java 516448 2007-03-09 16:25:47Z ate $ */ public class BasicRewriter extends AbstractRewriter implements Rewriter { + protected final static Log log = LogFactory.getLog(BasicRewriter.class); - /* - * This callback is called by the ParserAdaptor implementation to write - * back all rewritten URLs to point to the proxy server. - * Given the targetURL, rewrites the link as a link back to the proxy server. - * + /* + * This callback is called by the ParserAdaptor implementation to write back + * all rewritten URLs to point to the proxy server. Given the targetURL, + * rewrites the link as a link back to the proxy server. + * * @return the rewritten URL to the proxy server. - * + * */ public String rewriteUrl(String url, String tag, String attribute) { return getBaseRelativeUrl(url); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.Rewriter#shouldRemoveTag(java.lang.String) */ public boolean shouldRemoveTag(String tag) { - if (tag.equalsIgnoreCase("html")) - { - return true; - } + if (tag.equalsIgnoreCase("html")) { return true; } return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.Rewriter#shouldStripTag(java.lang.String) */ public boolean shouldStripTag(String tag) { - if (tag.equalsIgnoreCase("head")) - { - return true; - } + if (tag.equalsIgnoreCase("head")) { return true; } return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.Rewriter#shouldRemoveComments() */ public boolean shouldRemoveComments() { return true; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/JetspeedClasspathRewriterController.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/JetspeedClasspathRewriterController.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/JetspeedClasspathRewriterController.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,7 +16,6 @@ */ package org.apache.jetspeed.rewriter; - import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; @@ -32,39 +31,42 @@ * @version $Id: JetspeedRewriterController.java,v 1.2 2004/03/08 00:44:40 jford * Exp $ */ -public class JetspeedClasspathRewriterController - extends JetspeedRewriterController - implements RewriterController +public class JetspeedClasspathRewriterController extends + JetspeedRewriterController implements RewriterController { - protected final static Log log = LogFactory.getLog(JetspeedClasspathRewriterController.class); - public JetspeedClasspathRewriterController( String mappingFile ) throws RewriterException + protected final static Log log = LogFactory + .getLog(JetspeedClasspathRewriterController.class); + + public JetspeedClasspathRewriterController(String mappingFile) + throws RewriterException { super(mappingFile); } - public JetspeedClasspathRewriterController( String mappingFile, List rewriterClasses, List adaptorClasses ) - throws RewriterException + public JetspeedClasspathRewriterController(String mappingFile, + List rewriterClasses, List adaptorClasses) throws RewriterException { super(mappingFile, rewriterClasses, adaptorClasses); } - - public JetspeedClasspathRewriterController( String mappingFile, - String basicRewriterClassName, String rulesetRewriterClassName, - String adaptorHtmlClassName, String adaptorXmlClassName ) - throws RewriterException + + public JetspeedClasspathRewriterController(String mappingFile, + String basicRewriterClassName, String rulesetRewriterClassName, + String adaptorHtmlClassName, String adaptorXmlClassName) + throws RewriterException { - super(mappingFile, toClassList(basicRewriterClassName,rulesetRewriterClassName), - toClassList(adaptorHtmlClassName,adaptorXmlClassName)); + super(mappingFile, toClassList(basicRewriterClassName, + rulesetRewriterClassName), toClassList(adaptorHtmlClassName, + adaptorXmlClassName)); } - - protected Reader getReader(String resource) - throws RewriterException + + protected Reader getReader(String resource) throws RewriterException { - InputStream stream = this.getClass().getClassLoader().getResourceAsStream(resource); - if (stream != null) - return new InputStreamReader(stream); + InputStream stream = this.getClass().getClassLoader() + .getResourceAsStream(resource); + if (stream != null) return new InputStreamReader(stream); - throw new RewriterException("could not access rewriter classpath resource " + resource); + throw new RewriterException( + "could not access rewriter classpath resource " + resource); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/JetspeedRewriterController.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/JetspeedRewriterController.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/JetspeedRewriterController.java 2008-05-16 01:54:54 UTC (rev 940) @@ -47,11 +47,18 @@ */ public class JetspeedRewriterController implements RewriterController { - protected final static Log log = LogFactory.getLog(JetspeedRewriterController.class); + + protected final static Log log = LogFactory + .getLog(JetspeedRewriterController.class); + final static String CONFIG_MAPPING_FILE = "mapping"; + final static String CONFIG_BASIC_REWRITER = "basic.class"; + final static String CONFIG_RULESET_REWRITER = "ruleset.class"; + final static String CONFIG_ADAPTOR_HTML = "adaptor.html"; + final static String CONFIG_ADAPTOR_XML = "adaptor.xml"; // configuration parameters @@ -71,16 +78,18 @@ /** Adaptors */ protected Class adaptorHtmlClass = SwingParserAdaptor.class; + protected Class adaptorXmlClass = SaxParserAdaptor.class; - public JetspeedRewriterController( String mappingFile ) throws RewriterException + public JetspeedRewriterController(String mappingFile) + throws RewriterException { this.mappingFile = mappingFile; loadMapping(); } - public JetspeedRewriterController( String mappingFile, List rewriterClasses, List adaptorClasses ) - throws RewriterException + public JetspeedRewriterController(String mappingFile, List rewriterClasses, + List adaptorClasses) throws RewriterException { this.mappingFile = mappingFile; if (rewriterClasses.size() > 0) @@ -102,12 +111,15 @@ loadMapping(); } - - public JetspeedRewriterController( String mappingFile, String basicRewriterClassName, String rulesetRewriterClassName, - String adaptorHtmlClassName, String adaptorXmlClassName ) - throws RewriterException + + public JetspeedRewriterController(String mappingFile, + String basicRewriterClassName, String rulesetRewriterClassName, + String adaptorHtmlClassName, String adaptorXmlClassName) + throws RewriterException { - this(mappingFile, toClassList(basicRewriterClassName,rulesetRewriterClassName), toClassList(adaptorHtmlClassName,adaptorXmlClassName)); + this(mappingFile, toClassList(basicRewriterClassName, + rulesetRewriterClassName), toClassList(adaptorHtmlClassName, + adaptorXmlClassName)); } protected static List toClassList(String classNameA, String classNameB) @@ -115,28 +127,29 @@ try { List list = new ArrayList(2); - if ( classNameA != null ) + if (classNameA != null) { list.add(Class.forName(classNameA)); } - if ( classNameB != null ) + if (classNameB != null) { list.add(Class.forName(classNameB)); } return list; - } + } catch (ClassNotFoundException e) { throw new RuntimeException(e); } - } + } /* * (non-Javadoc) * * @see org.apache.jetspeed.rewriter.RewriterService#createRewriter() */ - public Rewriter createRewriter() throws InstantiationException, IllegalAccessException + public Rewriter createRewriter() throws InstantiationException, + IllegalAccessException { return (Rewriter) basicRewriterClass.newInstance(); } @@ -146,11 +159,13 @@ * * @see org.apache.jetspeed.rewriter.RewriterService#createRewriter(org.apache.jetspeed.rewriter.rules.Ruleset) */ - public RulesetRewriter createRewriter( Ruleset ruleset ) throws RewriterException + public RulesetRewriter createRewriter(Ruleset ruleset) + throws RewriterException { try { - RulesetRewriter rewriter = (RulesetRewriter) rulesetRewriterClass.newInstance(); + RulesetRewriter rewriter = (RulesetRewriter) rulesetRewriterClass + .newInstance(); rewriter.setRuleset(ruleset); return rewriter; } @@ -166,7 +181,8 @@ * * @see org.apache.jetspeed.rewriter.RewriterService#createParserAdaptor(java.lang.String) */ - public ParserAdaptor createParserAdaptor( String mimeType ) throws RewriterException + public ParserAdaptor createParserAdaptor(String mimeType) + throws RewriterException { try { @@ -191,14 +207,14 @@ /** * Load the mapping file for ruleset configuration - * + * */ protected void loadMapping() throws RewriterException { try { Reader reader = getReader(this.mappingFile); - + this.mapper = new Mapping(); InputSource is = new InputSource(reader); is.setSystemId(this.mappingFile); @@ -213,8 +229,7 @@ } } - protected Reader getReader(String resource) - throws RewriterException + protected Reader getReader(String resource) throws RewriterException { File file = new File(resource); if (file.exists() && file.isFile() && file.canRead()) @@ -225,18 +240,20 @@ } catch (Exception e) { - throw new RewriterException("could not open rewriter file " + resource, e); + throw new RewriterException("could not open rewriter file " + + resource, e); } } - throw new RewriterException("could not access rewriter file " + resource); + throw new RewriterException("could not access rewriter file " + + resource); } - + /* * (non-Javadoc) * * @see org.apache.jetspeed.rewriter.RewriterService#lookupRuleset(java.lang.String) */ - public Ruleset lookupRuleset( String id ) + public Ruleset lookupRuleset(String id) { return (Ruleset) rulesets.get(id); } @@ -246,12 +263,13 @@ * * @see org.apache.jetspeed.rewriter.RewriterService#loadRuleset(java.io.Reader) */ - public Ruleset loadRuleset( Reader reader ) + public Ruleset loadRuleset(Reader reader) { Ruleset ruleset = null; try { - DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); + DocumentBuilderFactory dbfactory = DocumentBuilderFactory + .newInstance(); DocumentBuilder builder = dbfactory.newDocumentBuilder(); InputSource source = new InputSource(reader); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/MutableAttributes.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/MutableAttributes.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/MutableAttributes.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,20 +20,23 @@ /** * MutableAttributes - * + * * @author David Sean Taylor * @version $Id: MutableAttributes.java 516448 2007-03-09 16:25:47Z ate $ */ public interface MutableAttributes extends Attributes { + /** * Creates a new attribute set similar to this one except that it contains - * an attribute with the given name and value. The object must be - * immutable, or not mutated by any client. - * - * @param name the name - * @param value the value + * an attribute with the given name and value. The object must be immutable, + * or not mutated by any client. + * + * @param name + * the name + * @param value + * the value */ public void addAttribute(String name, Object value); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/ParserAdaptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/ParserAdaptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/ParserAdaptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,33 +20,42 @@ import java.io.Writer; /** - * Interface for HTML Parser Adaptors. - * Adaptors normalize the interface over HTML and XML adaptor implementations. + * Interface for HTML Parser Adaptors. Adaptors normalize the interface over + * HTML and XML adaptor implementations. * * @author David Sean Taylor * @version $Id: ParserAdaptor.java 516448 2007-03-09 16:25:47Z ate $ */ public interface ParserAdaptor { + /** * Parses a document from the reader, without actually rewriting URLs. - * During parsing the events are called back on the given rewriter to handle the normalized events. - * - * @param reader the input stream over the content to be parsed. - * @exception RewriteException when a parsing error occurs or unexpected content is found. - */ - void parse(Rewriter rewriter, Reader reader) - throws RewriterException; + * During parsing the events are called back on the given rewriter to handle + * the normalized events. + * + * @param reader + * the input stream over the content to be parsed. + * @exception RewriteException + * when a parsing error occurs or unexpected content is + * found. + */ + void parse(Rewriter rewriter, Reader reader) throws RewriterException; /** - * Parses and rewrites a document from the reader, rewriting URLs via the rewriter's events to the writer. - * During parsing the rewriter events are called on the given rewriter to handle the rewriting. - * - * @param reader the input stream over the content to be parsed. - * @param writer the output stream where content is rewritten to. - * @exception RewriteException when a parsing error occurs or unexpected content is found. - */ + * Parses and rewrites a document from the reader, rewriting URLs via the + * rewriter's events to the writer. During parsing the rewriter events are + * called on the given rewriter to handle the rewriting. + * + * @param reader + * the input stream over the content to be parsed. + * @param writer + * the output stream where content is rewritten to. + * @exception RewriteException + * when a parsing error occurs or unexpected content is + * found. + */ void rewrite(Rewriter rewriter, Reader reader, Writer writer) - throws RewriterException; - + throws RewriterException; + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/Rewriter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/Rewriter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/Rewriter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,64 +21,78 @@ /** * Rewriter - * + * * @author David Sean Taylor * @version $Id: Rewriter.java 516448 2007-03-09 16:25:47Z ate $ */ public interface Rewriter { + /** * Parses the reader of content receiving call backs for rewriter events. - * This method does not rewrite, but only parses. Useful for readonly operations. - * The configured parser can parse over different stream formats returning a - * normalized (org.sax.xml) attribute and element based events. - * - * @param adaptor the parser adaptor which handles generating SAX-like events called back on this object. - * @param reader the input stream over the content to be parsed. - * @exception RewriteException when a parsing error occurs or unexpected content is found. + * This method does not rewrite, but only parses. Useful for readonly + * operations. The configured parser can parse over different stream formats + * returning a normalized (org.sax.xml) attribute and element based events. + * + * @param adaptor + * the parser adaptor which handles generating SAX-like events + * called back on this object. + * @param reader + * the input stream over the content to be parsed. + * @exception RewriteException + * when a parsing error occurs or unexpected content is + * found. */ - void parse(ParserAdaptor adaptor, Reader reader) - throws RewriterException; + void parse(ParserAdaptor adaptor, Reader reader) throws RewriterException; /** * Parses the reader of content receiving call backs for rewriter events. - * The content is rewritten to the output stream. - * The configured parser can parse over different stream formats returning a - * normalized (org.sax.xml) attribute and element based events. - * - * @param adaptor the parser adaptor which handles generating SAX-like events called back on this object. - * @param reader the input stream over the content to be parsed. - * @param writer the output stream where content is rewritten to. - * @exception RewriteException when a parsing error occurs or unexpected content is found. - */ + * The content is rewritten to the output stream. The configured parser can + * parse over different stream formats returning a normalized (org.sax.xml) + * attribute and element based events. + * + * @param adaptor + * the parser adaptor which handles generating SAX-like events + * called back on this object. + * @param reader + * the input stream over the content to be parsed. + * @param writer + * the output stream where content is rewritten to. + * @exception RewriteException + * when a parsing error occurs or unexpected content is + * found. + */ void rewrite(ParserAdaptor adaptor, Reader reader, Writer writer) - throws RewriterException; - + throws RewriterException; - /** - * This event is the inteface between the Rewriter and ParserAdaptor for rewriting URLs. - * The ParserAdaptor calls back the Rewriter when it finds a URL that is a candidate to be - * rewritten. The Rewriter rewrites the URL and returns it as the result of this function. + /** + * This event is the inteface between the Rewriter and ParserAdaptor for + * rewriting URLs. The ParserAdaptor calls back the Rewriter when it finds a + * URL that is a candidate to be rewritten. The Rewriter rewrites the URL + * and returns it as the result of this function. * - * @param url the URL to be rewritten - * @param tag The tag being processed - * @param attribute The current attribute being processsed + * @param url + * the URL to be rewritten + * @param tag + * The tag being processed + * @param attribute + * The current attribute being processsed */ String rewriteUrl(String url, String tag, String attribute); /** - * Returns true if the tag should be removed, otherwise false. - * Removing a tag only removes the tag but not the contents in - * between the start and end tag. + * Returns true if the tag should be removed, otherwise false. Removing a + * tag only removes the tag but not the contents in between the start and + * end tag. * * @return true if the tag should be removed. */ boolean shouldRemoveTag(String tag); /** - * Returns true if the tag should be stripped, otherwise false. - * Stripping tags removes the start and end tag, plus all tags - * and content in between the start and end tag. + * Returns true if the tag should be stripped, otherwise false. Stripping + * tags removes the start and end tag, plus all tags and content in between + * the start and end tag. * * @return true if the tag should be stripped. */ @@ -88,123 +102,155 @@ * Returns true if all comments should be removed. * * @return true If all comments should be removed. - */ + */ boolean shouldRemoveComments(); - + /** - * Sets the base URL for rewriting. This URL is the base - * from which other URLs are generated. + * Sets the base URL for rewriting. This URL is the base from which other + * URLs are generated. * - * @param base The base URL for this rewriter + * @param base + * The base URL for this rewriter */ void setBaseUrl(String base); - + /** - * Gets the base URL for rewriting. This URL is the base - * from which other URLs are generated. + * Gets the base URL for rewriting. This URL is the base from which other + * URLs are generated. * * @return The base URL for this rewriter */ String getBaseUrl(); - + /** - * Gets a new URL relative to Base according to the site / and URL - * rewriting rules of java.net.URL + * Gets a new URL relative to Base according to the site / and URL rewriting + * rules of java.net.URL * - * @return The new URL from path, relative to the base URL (or path, if path is absolute) + * @return The new URL from path, relative to the base URL (or path, if path + * is absolute) */ String getBaseRelativeUrl(String path); - + /** * Gets whether this rewriter require a proxy server. * * @return true if it requires a proxy */ boolean getUseProxy(); - + /** * Set whether this rewriter require a proxy server. * - * @param useProxy true if it requires a proxy - */ + * @param useProxy + * true if it requires a proxy + */ void setUseProxy(boolean useProxy); - + /** - * Rewriter event called back on the leading edge of processing a simple tag by the ParserAdaptor. - * Returns false to indicate to the ParserAdaptor to short-circuit processing on this tag. + * Rewriter event called back on the leading edge of processing a simple tag + * by the ParserAdaptor. Returns false to indicate to the ParserAdaptor to + * short-circuit processing on this tag. * - * @param tag The name of the tag being processed. - * @param attrs The attribute list for the tag. - * @return Should return true to continue processing the tag in the ParserAdaptor, false to indicate that processing is completed. + * @param tag + * The name of the tag being processed. + * @param attrs + * The attribute list for the tag. + * @return Should return true to continue processing the tag in the + * ParserAdaptor, false to indicate that processing is completed. */ boolean enterSimpleTagEvent(String tag, MutableAttributes attrs); - + /** - * Rewriter event called back on the trailing edge of a simple tag by the ParserAdaptor. - * Returns a String that can be appended to the rewritten output for the given tag, or null to indicate no content available. - * - * @param tag The name of the tag being processed. - * @param attrs The attribute list for the tag. - * @return Returns a String that can be appended to the rewritten output for the given tag, or null to indicate no content available. - */ + * Rewriter event called back on the trailing edge of a simple tag by the + * ParserAdaptor. Returns a String that can be appended to the rewritten + * output for the given tag, or null to indicate no content available. + * + * @param tag + * The name of the tag being processed. + * @param attrs + * The attribute list for the tag. + * @return Returns a String that can be appended to the rewritten output for + * the given tag, or null to indicate no content available. + */ String exitSimpleTagEvent(String tag, MutableAttributes attrs); /** - * Rewriter event called back on the leading edge of processing a start tag by the ParserAdaptor. - * Returns false to indicate to the ParserAdaptor to short-circuit processing on this tag. + * Rewriter event called back on the leading edge of processing a start tag + * by the ParserAdaptor. Returns false to indicate to the ParserAdaptor to + * short-circuit processing on this tag. * - * @param tag The name of the tag being processed. - * @param attrs The attribute list for the tag. - * @return Should return true to continue processing the tag in the ParserAdaptor, false to indicate that processing is completed. + * @param tag + * The name of the tag being processed. + * @param attrs + * The attribute list for the tag. + * @return Should return true to continue processing the tag in the + * ParserAdaptor, false to indicate that processing is completed. */ boolean enterStartTagEvent(String tag, MutableAttributes attrs); - + /** - * Rewriter event called back on the trailing edge of a start tag by the ParserAdaptor. - * Returns a String that can be appended to the rewritten output for the given tag, or null to indicate no content available. - * - * @param tag The name of the tag being processed. - * @param attrs The attribute list for the tag. - * @return Returns a String that can be appended to the rewritten output for the given tag, or null to indicate no content available. - */ + * Rewriter event called back on the trailing edge of a start tag by the + * ParserAdaptor. Returns a String that can be appended to the rewritten + * output for the given tag, or null to indicate no content available. + * + * @param tag + * The name of the tag being processed. + * @param attrs + * The attribute list for the tag. + * @return Returns a String that can be appended to the rewritten output for + * the given tag, or null to indicate no content available. + */ String exitStartTagEvent(String tag, MutableAttributes attrs); /** - * Rewriter event called back on the leading edge of processing an end tag by the ParserAdaptor. - * Returns false to indicate to the ParserAdaptor to short-circuit processing on this tag. + * Rewriter event called back on the leading edge of processing an end tag + * by the ParserAdaptor. Returns false to indicate to the ParserAdaptor to + * short-circuit processing on this tag. * - * @param tag The name of the tag being processed. - * @param attrs The attribute list for the tag. - * @return Should return true to continue processing the tag in the ParserAdaptor, false to indicate that processing is completed. + * @param tag + * The name of the tag being processed. + * @param attrs + * The attribute list for the tag. + * @return Should return true to continue processing the tag in the + * ParserAdaptor, false to indicate that processing is completed. */ boolean enterEndTagEvent(String tag); /** - * Rewriter event called back on the trailing edge of a end tag by the ParserAdaptor. - * Returns a String that can be appended to the rewritten output for the given tag, or null to indicate no content available. - * - * @param tag The name of the tag being processed. - * @param attrs The attribute list for the tag. - * @return Returns a String that can be appended to the rewritten output for the given tag, or null to indicate no content available. - */ + * Rewriter event called back on the trailing edge of a end tag by the + * ParserAdaptor. Returns a String that can be appended to the rewritten + * output for the given tag, or null to indicate no content available. + * + * @param tag + * The name of the tag being processed. + * @param attrs + * The attribute list for the tag. + * @return Returns a String that can be appended to the rewritten output for + * the given tag, or null to indicate no content available. + */ String exitEndTagEvent(String tag); /** - * Rewriter event called back when text is found for - * Returns false to indicate to the ParserAdaptor to short-circuit processing on this tag. + * Rewriter event called back when text is found for Returns false to + * indicate to the ParserAdaptor to short-circuit processing on this tag. * - * @param values an array of characters containing the text. - * @param param - * @return Should return true to continue processing the tag in the ParserAdaptor, false to indicate that processing is completed. + * @param values + * an array of characters containing the text. + * @param param + * @return Should return true to continue processing the tag in the + * ParserAdaptor, false to indicate that processing is completed. */ boolean enterText(char[] values, int param); /** - * Rewriter event called back just before tag conversion (rewriter callbacks) begins by the ParserAdaptor. + * Rewriter event called back just before tag conversion (rewriter + * callbacks) begins by the ParserAdaptor. * - * @param tag The name of the tag being processed. - * @param attrs The attribute list for the tag. + * @param tag + * The name of the tag being processed. + * @param attrs + * The attribute list for the tag. */ void enterConvertTagEvent(String tag, MutableAttributes attrs); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RewriterController.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RewriterController.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RewriterController.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,63 +22,66 @@ /** * RewriterService - * + * * @author David Sean Taylor * @version $Id: RewriterController.java 516448 2007-03-09 16:25:47Z ate $ */ -public interface RewriterController +public interface RewriterController { + public String SERVICE_NAME = "rewriter"; /** * Creates a basic rewriter that does not support rulesets configurations. * The Rewriter implementation is configured in the service configuration. - * + * * @return A new rewriter that does not support rulesets. * @throws InstantiationException - * @throws + * @throws * @throws IllegalAccessException */ - Rewriter createRewriter() - throws IllegalAccessException, InstantiationException; + Rewriter createRewriter() throws IllegalAccessException, + InstantiationException; /** - * Creates a rewriter that supports rulesets configurations. - * The rewriter uses the rulesets configuration to control rewriting. - * The Rewriter implementation is configured in the service configuration. + * Creates a rewriter that supports rulesets configurations. The rewriter + * uses the rulesets configuration to control rewriting. The Rewriter + * implementation is configured in the service configuration. * - * @param ruleset The ruleset configuration to control the rewriter. + * @param ruleset + * The ruleset configuration to control the rewriter. * @return A new rewriter that supports rulesets. */ - RulesetRewriter createRewriter(Ruleset ruleset) - throws RewriterException; - + RulesetRewriter createRewriter(Ruleset ruleset) throws RewriterException; /** - * Creates a Parser Adaptor for the given mime type - * The Parser Adaptor implementation is configured in the service configuration. - * Only MimeTypes of "text/html" and "text/xml" are currently supported. + * Creates a Parser Adaptor for the given mime type The Parser Adaptor + * implementation is configured in the service configuration. Only MimeTypes + * of "text/html" and "text/xml" are currently supported. * - * @param mimeType The mimetype to create a parser adaptor for. + * @param mimeType + * The mimetype to create a parser adaptor for. * @return A new parser adaptor */ - ParserAdaptor createParserAdaptor(String mimeType) - throws RewriterException; - + ParserAdaptor createParserAdaptor(String mimeType) throws RewriterException; + /** - * Loads a XML-based Rewriter Ruleset given a stream to the XML configuration. + * Loads a XML-based Rewriter Ruleset given a stream to the XML + * configuration. * - * @param reader The stream to the XML configuration. + * @param reader + * The stream to the XML configuration. * @return A Ruleset configuration tree. */ Ruleset loadRuleset(Reader reader); - + /** * Lookup a Ruleset given a ruleset identifier. * - * @param id The identifier for the Ruleset. + * @param id + * The identifier for the Ruleset. * @return A Ruleset configuration tree. */ Ruleset lookupRuleset(String id); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RewriterException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RewriterException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RewriterException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,15 +18,16 @@ /** * RewriterException - * + * * @author David Sean Taylor * @version $Id: RewriterException.java 516448 2007-03-09 16:25:47Z ate $ */ public class RewriterException extends Exception { + /** - * Constructs a new RewriterException without specified detail - * message. + * Constructs a new RewriterException without specified + * detail message. */ public RewriterException() { @@ -35,8 +36,9 @@ /** * Constructs a new RewriterException with specified detail * message. - * - * @param msg the error message. + * + * @param msg + * the error message. */ public RewriterException(String msg) { @@ -46,9 +48,10 @@ /** * Constructs a new RewriterException with specified nested * Throwable. - * - * @param nested the exception or error that caused this exception - * to be thrown. + * + * @param nested + * the exception or error that caused this exception to be + * thrown. */ public RewriterException(Throwable nested) { @@ -58,14 +61,16 @@ /** * Constructs a new RewriterException with specified detail * message and nested Throwable. - * - * @param msg the error message. - * @param nested the exception or error that caused this exception - * to be thrown. + * + * @param msg + * the error message. + * @param nested + * the exception or error that caused this exception to be + * thrown. */ public RewriterException(String msg, Throwable nested) { super(msg, nested); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RulesetRewriter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RulesetRewriter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RulesetRewriter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,16 +20,18 @@ /** * RulesetRewriter - * + * * @author David Sean Taylor * @version $Id: RulesetRewriter.java 516448 2007-03-09 16:25:47Z ate $ */ public interface RulesetRewriter extends Rewriter { + /** * Set the Ruleset configuration for this rewriter. * - * @param ruleset The Ruleset configuration. + * @param ruleset + * The Ruleset configuration. */ void setRuleset(Ruleset ruleset); @@ -37,6 +39,6 @@ * Get the Ruleset configuration for this rewriter. * * @return The Ruleset configuration. - */ + */ Ruleset getRuleset(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RulesetRewriterImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RulesetRewriterImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/RulesetRewriterImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,68 +20,64 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.apache.jetspeed.rewriter.rules.Attribute; import org.apache.jetspeed.rewriter.rules.Rule; import org.apache.jetspeed.rewriter.rules.Ruleset; import org.apache.jetspeed.rewriter.rules.Tag; - /** * RuleBasedRewriter - * + * * @author David Sean Taylor * @version $Id: RulesetRewriterImpl.java 517121 2007-03-12 07:45:49Z ate $ */ -public class RulesetRewriterImpl extends BasicRewriter implements RulesetRewriter +public class RulesetRewriterImpl extends BasicRewriter implements + RulesetRewriter { - protected final static Log log = LogFactory.getLog(RulesetRewriterImpl.class); - + + protected final static Log log = LogFactory + .getLog(RulesetRewriterImpl.class); + private Ruleset ruleset = null; + private boolean removeComments = false; public boolean shouldStripTag(String tagid) - { - if (null == ruleset) - { - return false; - } - + { + if (null == ruleset) { return false; } + Tag tag = ruleset.getTag(tagid.toUpperCase()); - if (null == tag) - { - return false; - } - return tag.getStrip(); + if (null == tag) { return false; } + return tag.getStrip(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.Rewriter#shouldRemoveTag(java.lang.String) */ public boolean shouldRemoveTag(String tagid) - { - if (null == ruleset) - { - return false; - } - + { + if (null == ruleset) { return false; } + Tag tag = ruleset.getTag(tagid.toUpperCase()); - if (null == tag) - { - return false; - } + if (null == tag) { return false; } return tag.getRemove(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.RulesetRewriter#setRuleset(org.apache.jetspeed.cps.rewriter.rules.Ruleset) */ public void setRuleset(Ruleset ruleset) { this.ruleset = ruleset; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.RulesetRewriter#getRuleset() */ public Ruleset getRuleset() @@ -89,42 +85,38 @@ return this.ruleset; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.Rewriter#shouldRemoveComments() */ public boolean shouldRemoveComments() { - if (null == ruleset) - { - return false; - } - - return ruleset.getRemoveComments(); + if (null == ruleset) { return false; } + + return ruleset.getRemoveComments(); } - /* (non-Javadoc) - * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#convertTagEvent(java.lang.String, org.xml.sax.Attributes) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#convertTagEvent(java.lang.String, + * org.xml.sax.Attributes) */ public void enterConvertTagEvent(String tagid, MutableAttributes attributes) { - if (null == ruleset) - { - return; - } - - Tag tag = ruleset.getTag(tagid.toUpperCase()); - if (null == tag) - { - return; - } + if (null == ruleset) { return; } + Tag tag = ruleset.getTag(tagid.toUpperCase()); + if (null == tag) { return; } + Iterator attribRules = tag.getAttributes().iterator(); while (attribRules.hasNext()) { - Attribute attribute = (Attribute)attribRules.next(); + Attribute attribute = (Attribute) attribRules.next(); String name = attribute.getId(); String value = attributes.getValue(name); - + if (value != null) // && name.equalsIgnoreCase(attribute.getId())) { Rule rule = attribute.getRule(); @@ -132,31 +124,32 @@ { continue; } - + if (!rule.shouldRewrite(value)) { continue; - } - - String rewritten = rewriteUrl(value, tag.getId(), name, attributes); - if (null != rewritten) // return null indicates "don't rewrite" + } + + String rewritten = rewriteUrl(value, tag.getId(), name, + attributes); + if (null != rewritten) // return null indicates "don't rewrite" { if (rule.getSuffix() != null) { rewritten = rewritten.concat(rule.getSuffix()); } - + attributes.addAttribute(name, rewritten); - + if (rule.getPopup()) { - attributes.addAttribute("TARGET", "_BLANK"); + attributes.addAttribute("TARGET", "_BLANK"); } } - } + } } } - + /** * rewriteURL * @@ -168,7 +161,8 @@ * * Rewrites all urls HREFS with a portlet action */ - public String rewriteUrl(String url, String tag, String attribute, MutableAttributes otherAttributes) + public String rewriteUrl(String url, String tag, String attribute, + MutableAttributes otherAttributes) { return getBaseRelativeUrl(url); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/TicketParamRewriter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/TicketParamRewriter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/TicketParamRewriter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,39 +16,41 @@ */ package org.apache.jetspeed.rewriter; - /** - * Parses looking for a Ticket Param, used in SSO portlets where ticket processing is required - * Often tickets are added as form parameters and checked on the authentication for better security - * + * Parses looking for a Ticket Param, used in SSO portlets where ticket + * processing is required Often tickets are added as form parameters and checked + * on the authentication for better security + * * @author David Sean Taylor * @version $Id$ */ public class TicketParamRewriter extends BasicRewriter -{ +{ + private String ticket; + private String ticketName; - public String getTicketName() + public String getTicketName() { return ticketName; } - public void setTicketName(String ticketName) + public void setTicketName(String ticketName) { this.ticketName = ticketName; } - - public String getTicket() + + public String getTicket() { - return ticket; - } + return ticket; + } - public void setTicket(String ticket) + public void setTicket(String ticket) { - this.ticket = ticket; - } - + this.ticket = ticket; + } + public boolean enterSimpleTagEvent(String tag, MutableAttributes attrs) { if (tag.equalsIgnoreCase("input")) @@ -57,11 +59,12 @@ String value = attrs.getValue("value"); if (name.equals(this.ticketName)) { - - //System.out.println("*** TICKET attr=" + name + " val = " + value); - setTicket(value); + + // System.out.println("*** TICKET attr=" + name + " val = " + + // value); + setTicket(value); } - } + } return true; - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/WebContentRewriter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/WebContentRewriter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/WebContentRewriter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,15 +28,24 @@ */ public class WebContentRewriter extends RulesetRewriterImpl implements Rewriter { - /* (non-Javadoc) - * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#convertTagEvent(java.lang.String, org.xml.sax.Attributes) - */ - public void enterConvertTagEvent(String tagid, MutableAttributes attributes) { + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter#convertTagEvent(java.lang.String, + * org.xml.sax.Attributes) + */ + public void enterConvertTagEvent(String tagid, MutableAttributes attributes) + { super.enterConvertTagEvent(tagid, attributes); } - /** parameters that need to be propagated in the action URL (since HTTP request parameters will not be available) */ - public static final String ACTION_PARAMETER_URL = "_AP_URL"; + /** + * parameters that need to be propagated in the action URL (since HTTP + * request parameters will not be available) + */ + public static final String ACTION_PARAMETER_URL = "_AP_URL"; + public static final String ACTION_PARAMETER_METHOD = "_AP_METHOD"; /* @@ -68,49 +77,57 @@ * * Rewrites all urls HREFS with a portlet action */ - public String rewriteUrl(String url, String tag, String attribute, MutableAttributes otherAttributes) + public String rewriteUrl(String url, String tag, String attribute, + MutableAttributes otherAttributes) { - String modifiedURL = url; + String modifiedURL = url; modifiedURL = getModifiedURL(url); // translate "submit" URL's as actions - // - //

      - if (( tag.equalsIgnoreCase("A") && attribute.equalsIgnoreCase("href")) || - ( tag.equalsIgnoreCase("FORM") && attribute.equalsIgnoreCase("action"))) - + // + // + if ((tag.equalsIgnoreCase("A") && attribute.equalsIgnoreCase("href")) + || (tag.equalsIgnoreCase("FORM") && attribute + .equalsIgnoreCase("action"))) + { - // Regular URL just add a portlet action - if (this.actionURL != null) + // Regular URL just add a portlet action + if (this.actionURL != null) + { + // create Action URL + actionURL.setParameter(ACTION_PARAMETER_URL, modifiedURL); + if (tag.equalsIgnoreCase("FORM")) { - // create Action URL - actionURL.setParameter(ACTION_PARAMETER_URL, modifiedURL); - if (tag.equalsIgnoreCase("FORM")) - { - String httpMethod = otherAttributes.getValue("method"); - if (httpMethod != null) - actionURL.setParameter(ACTION_PARAMETER_METHOD, httpMethod); - } - modifiedURL = actionURL.toString(); + String httpMethod = otherAttributes.getValue("method"); + if (httpMethod != null) + actionURL.setParameter(ACTION_PARAMETER_METHOD, + httpMethod); } + modifiedURL = actionURL.toString(); + } } // Deal with links in an "onclick". if (attribute.equalsIgnoreCase("onclick")) { // Check for onclick with location change - for (int i=0; i < otherAttributes.getLength(); i++) { + for (int i = 0; i < otherAttributes.getLength(); i++) + { String name = otherAttributes.getQName(i); - if (name.equalsIgnoreCase("onclick")) { + if (name.equalsIgnoreCase("onclick")) + { String value = otherAttributes.getValue(i); int index = value.indexOf(".location="); - if (index >= 0) { - String oldLocation = value.substring(index + ".location=".length()); - StringTokenizer tokenizer = new StringTokenizer(oldLocation, "\'\""); + if (index >= 0) + { + String oldLocation = value.substring(index + + ".location=".length()); + StringTokenizer tokenizer = new StringTokenizer( + oldLocation, "\'\""); oldLocation = tokenizer.nextToken(); modifiedURL = oldLocation; @@ -121,39 +138,45 @@ if (this.actionURL != null) { // create Action URL - actionURL.setParameter(ACTION_PARAMETER_URL, modifiedURL); + actionURL.setParameter(ACTION_PARAMETER_URL, + modifiedURL); modifiedURL = actionURL.toString(); } - - modifiedURL = value.replaceAll(oldLocation, modifiedURL); + modifiedURL = value + .replaceAll(oldLocation, modifiedURL); } } } + } - } - // if ( !url.equalsIgnoreCase( modifiedURL )) - // System.out.println("WebContentRewriter.rewriteUrl() - In tag: "+tag+", for attribute: "+attribute+", converted url: "+url+", to: "+modifiedURL+", base URL was: "+getBaseUrl()); + // System.out.println("WebContentRewriter.rewriteUrl() - In tag: + // "+tag+", for attribute: "+attribute+", converted url: "+url+", to: + // "+modifiedURL+", base URL was: "+getBaseUrl()); return modifiedURL; } - private String getModifiedURL(String url) { + private String getModifiedURL(String url) + { String modifiedURL = url; // Any relative URL needs to be converted to a full URL - if (url.startsWith("/") || (!url.startsWith("http:") && !url.startsWith("https:"))) + if (url.startsWith("/") + || (!url.startsWith("http:") && !url.startsWith("https:"))) { if (this.getBaseUrl() != null) { - modifiedURL = getBaseRelativeUrl(url) ; - // System.out.println("WebContentRewriter.rewriteUrl() - translated URL relative to base URL - result is: "+modifiedURL); - } + modifiedURL = getBaseRelativeUrl(url); + // System.out.println("WebContentRewriter.rewriteUrl() - + // translated URL relative to base URL - result is: + // "+modifiedURL); + } else { modifiedURL = url; // leave as is - } + } } return modifiedURL; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/SwingAttributes.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/SwingAttributes.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/SwingAttributes.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,39 +24,45 @@ import org.apache.jetspeed.rewriter.MutableAttributes; - /** * SwingAttributes - * + * * @author David Sean Taylor * @version $Id: SwingAttributes.java 516448 2007-03-09 16:25:47Z ate $ */ public class SwingAttributes implements MutableAttributes { + MutableAttributeSet swingset; - + public SwingAttributes(MutableAttributeSet swingset) { this.swingset = swingset; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.xml.sax.Attributes#getLength() */ public int getLength() { return swingset.getAttributeCount(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.xml.sax.Attributes#getURI(int) */ public String getURI(int index) { return ""; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.xml.sax.Attributes#getLocalName(int) */ public String getLocalName(int index) @@ -66,31 +72,34 @@ while (e.hasMoreElements()) { Object object = e.nextElement(); - if (ix == index) - { - return object.toString(); - } + if (ix == index) { return object.toString(); } } return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.xml.sax.Attributes#getQName(int) */ public String getQName(int index) { return getLocalName(index); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.xml.sax.Attributes#getType(int) */ public String getType(int index) { return "CDATA"; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.xml.sax.Attributes#getValue(int) */ public String getValue(int index) @@ -100,23 +109,24 @@ while (e.hasMoreElements()) { Object object = e.nextElement(); - if (ix == index) - { - return (String)swingset.getAttribute(object); - } + if (ix == index) { return (String) swingset.getAttribute(object); } } return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.xml.sax.Attributes#getIndex(java.lang.String, java.lang.String) */ public int getIndex(String uri, String localPart) { return getIndex(localPart); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.xml.sax.Attributes#getIndex(java.lang.String) */ public int getIndex(String qName) @@ -125,50 +135,58 @@ int ix = 0; while (e.hasMoreElements()) { - String name = (String)e.nextElement(); - if (name.equalsIgnoreCase(qName)) - { - return ix; - } + String name = (String) e.nextElement(); + if (name.equalsIgnoreCase(qName)) { return ix; } } return -1; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.xml.sax.Attributes#getType(java.lang.String, java.lang.String) */ public String getType(String uri, String localName) { return "CDATA"; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.xml.sax.Attributes#getType(java.lang.String) */ public String getType(String qName) { return "CDATA"; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.xml.sax.Attributes#getValue(java.lang.String, java.lang.String) */ public String getValue(String uri, String localName) { return getValue(localName); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.xml.sax.Attributes#getValue(java.lang.String) */ public String getValue(String qName) { - Attribute att = HTML.getAttributeKey(qName.toLowerCase()); - return (String)swingset.getAttribute(att); + Attribute att = HTML.getAttributeKey(qName.toLowerCase()); + return (String) swingset.getAttribute(att); } - /* (non-Javadoc) - * @see org.apache.jetspeed.cps.rewriter.MutableAttributes#addAttribute(java.lang.String, java.lang.Object) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.cps.rewriter.MutableAttributes#addAttribute(java.lang.String, + * java.lang.Object) */ public void addAttribute(String name, Object value) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/SwingParserAdaptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/SwingParserAdaptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/SwingParserAdaptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,51 +33,59 @@ /** * HTML Parser Adaptor for the Swing 'HotJava' parser. - * + * * @author David Sean Taylor * @version $Id: SwingParserAdaptor.java 516448 2007-03-09 16:25:47Z ate $ */ public class SwingParserAdaptor implements ParserAdaptor { - protected final static Log log = LogFactory.getLog(SwingParserAdaptor.class); + protected final static Log log = LogFactory + .getLog(SwingParserAdaptor.class); + private SwingParserAdaptor.Callback callback = null; + private String lineSeparator; + private boolean skippingImplied = false; + private Rewriter rewriter; - + /* - * Construct a swing (hot java) parser adaptor - * Receives a Rewriter parameter, which is used as a callback when rewriting URLs. - * The rewriter object executes the implementation specific URL rewriting. - * - * @param rewriter The rewriter object that is called back during URL rewriting + * Construct a swing (hot java) parser adaptor Receives a Rewriter + * parameter, which is used as a callback when rewriting URLs. The rewriter + * object executes the implementation specific URL rewriting. + * + * @param rewriter The rewriter object that is called back during URL + * rewriting */ public SwingParserAdaptor() { - lineSeparator = System.getProperty("line.separator", "\r\n"); + lineSeparator = System.getProperty("line.separator", "\r\n"); } /* - * Parses and an HTML document, rewriting all URLs as determined by the Rewriter callback - * - * - * @param reader The input stream reader - * - * @throws MalformedURLException - * + * Parses and an HTML document, rewriting all URLs as determined by the + * Rewriter callback + * + * + * @param reader The input stream reader + * + * @throws MalformedURLException + * * @return An HTML-String with rewritten URLs. - */ + */ public void rewrite(Rewriter rewriter, Reader reader, Writer writer) - throws RewriterException + throws RewriterException { try { - this.rewriter = rewriter; - HTMLEditorKit.Parser parser = new SwingParserAdaptor.ParserGetter().getParser(); + this.rewriter = rewriter; + HTMLEditorKit.Parser parser = new SwingParserAdaptor.ParserGetter() + .getParser(); callback = new SwingParserAdaptor.Callback(writer); parser.parse(reader, callback, true); - } + } catch (Exception e) { e.printStackTrace(); @@ -86,25 +94,26 @@ } public void parse(Rewriter rewriter, Reader reader) - throws RewriterException + throws RewriterException { try { - this.rewriter = rewriter; - HTMLEditorKit.Parser parser = new SwingParserAdaptor.ParserGetter().getParser(); + this.rewriter = rewriter; + HTMLEditorKit.Parser parser = new SwingParserAdaptor.ParserGetter() + .getParser(); callback = new SwingParserAdaptor.Callback(null); parser.parse(reader, callback, true); - } + } catch (Exception e) { e.printStackTrace(); throw new RewriterException(e); } } - + /* - * This Class is needed, because getParser is protected and therefore - * only accessibly by a subclass + * This Class is needed, because getParser is protected and therefore only + * accessibly by a subclass */ class ParserGetter extends HTMLEditorKit { @@ -113,25 +122,31 @@ { return super.getParser(); } - } - + } + /* - * Swing Parser Callback from the HTMLEditorKit. - * This class handles all SAX-like events during parsing. - * + * Swing Parser Callback from the HTMLEditorKit. This class handles all + * SAX-like events during parsing. + * */ class Callback extends HTMLEditorKit.ParserCallback { - // either handling of is buggy, or I made some weird mistake ... + + // either handling of is buggy, or I made some weird mistake ... // ... JDK 1.3 sends double "
      "-tags on closing
      - private boolean inForm = false; - private boolean inScript = false; + private boolean inForm = false; + + private boolean inScript = false; + private boolean strip = false; + private boolean simpleTag = false; + private String stripTag = null; + private Writer writer = null; - private Callback (Writer writer) + private Callback(Writer writer) { this.writer = writer; } @@ -141,84 +156,63 @@ // /* - * Hot Java event callback for text (all data in between tags) + * Hot Java event callback for text (all data in between tags) * * @param values The array of characters containing the text. */ - public void handleText(char[] values,int param) + public void handleText(char[] values, int param) { - if (strip) - { - return; - } - if (values[0] == '>') - { - return; - } - if (false == rewriter.enterText(values, param)) - { - return; - } + if (strip) { return; } + if (values[0] == '>') { return; } + if (false == rewriter.enterText(values, param)) { return; } addToResult(values); } - private void write(String text) - throws IOException + private void write(String text) throws IOException { if (writer != null) { writer.write(text); } } - + /* * Hot Java event callback for handling a simple tag (without begin/end) - * - * @param tag The HTML tag being handled. - * @param attrs The mutable HTML attribute set for the current HTML element. - * @param position the position of the tag. - * + * + * @param tag The HTML tag being handled. @param attrs The mutable HTML + * attribute set for the current HTML element. @param position the + * position of the tag. + * */ - public void handleSimpleTag(HTML.Tag htmlTag, MutableAttributeSet attrs, int param) + public void handleSimpleTag(HTML.Tag htmlTag, + MutableAttributeSet attrs, int param) { String tag = htmlTag.toString(); - - if (false == rewriter.enterSimpleTagEvent(tag, new SwingAttributes(attrs))) - { - return; - } - if (strip) - { - return; - } - - if (rewriter.shouldStripTag(tag)) - { - return; - } - - if (rewriter.shouldRemoveTag(tag)) - { - return; - } - + if (false == rewriter.enterSimpleTagEvent(tag, new SwingAttributes( + attrs))) { return; } + + if (strip) { return; } + + if (rewriter.shouldStripTag(tag)) { return; } + + if (rewriter.shouldRemoveTag(tag)) { return; } + try { - simpleTag = true; + simpleTag = true; appendTagToResult(htmlTag, attrs); write(lineSeparator); -/* - if (tag.toString().equalsIgnoreCase("param") || - tag.toString().equalsIgnoreCase("object") || - tag.toString().equalsIgnoreCase("embed")) - { - write(lineSeparator); - } -*/ + /* + * if (tag.toString().equalsIgnoreCase("param") || + * tag.toString().equalsIgnoreCase("object") || + * tag.toString().equalsIgnoreCase("embed")) { + * write(lineSeparator); } + */ simpleTag = false; - String appended = rewriter.exitSimpleTagEvent(tag, new SwingAttributes(attrs)); + String appended = rewriter.exitSimpleTagEvent(tag, + new SwingAttributes(attrs)); if (null != appended) { write(appended); @@ -226,78 +220,67 @@ } catch (Exception e) { - log.error("Simple tag parsing error", e); + log.error("Simple tag parsing error", e); } } /* * Hot Java event callback for handling a start tag. - * - * @param tag The HTML tag being handled. - * @param attrs The mutable HTML attribute set for the current HTML element. - * @param position the position of the tag. - * + * + * @param tag The HTML tag being handled. @param attrs The mutable HTML + * attribute set for the current HTML element. @param position the + * position of the tag. + * */ - public void handleStartTag(HTML.Tag htmlTag, MutableAttributeSet attrs, int position) + public void handleStartTag(HTML.Tag htmlTag, MutableAttributeSet attrs, + int position) { String tag = htmlTag.toString(); - - if (false == rewriter.enterStartTagEvent(tag, new SwingAttributes(attrs))) - { - return; - } - - if (strip) - { - return; - } - + + if (false == rewriter.enterStartTagEvent(tag, new SwingAttributes( + attrs))) { return; } + + if (strip) { return; } + if (rewriter.shouldStripTag(tag)) { stripTag = tag; strip = true; - return; - } - - if (rewriter.shouldRemoveTag(tag)) - { return; } - + + if (rewriter.shouldRemoveTag(tag)) { return; } + try { appendTagToResult(htmlTag, attrs); formatLine(htmlTag); - String appended = rewriter.exitStartTagEvent(tag, new SwingAttributes(attrs)); + String appended = rewriter.exitStartTagEvent(tag, + new SwingAttributes(attrs)); if (null != appended) { write(appended); } - } + } catch (Exception e) { - log.error("Start tag parsing error", e); + log.error("Start tag parsing error", e); } - + } - - /* * Hot Java event callback for handling an end tag. - * - * @param tag The HTML tag being handled. - * @param position the position of the tag. - * + * + * @param tag The HTML tag being handled. @param position the position + * of the tag. + * */ - public void handleEndTag(HTML.Tag htmlTag, int position) + public void handleEndTag(HTML.Tag htmlTag, int position) { String tag = htmlTag.toString(); - if (false == rewriter.enterEndTagEvent(tag.toString())) - { - return; - } - + if (false == rewriter.enterEndTagEvent(tag.toString())) { return; } + if (strip) { if (tag.equalsIgnoreCase(stripTag)) @@ -307,125 +290,112 @@ } return; } - - if (rewriter.shouldRemoveTag(tag)) - { - return; - } - + + if (rewriter.shouldRemoveTag(tag)) { return; } + try - { + { addToResult(""); - + // formatLine(htmlTag); write(lineSeparator); - + String appended = rewriter.exitEndTagEvent(tag); if (null != appended) { write(appended); } - } + } catch (Exception e) { - log.error("End tag parsing error", e); - } + log.error("End tag parsing error", e); + } } - /* * Hot Java event callback for handling errors. - * - * @param str The error message from Swing. - * @param param A parameter passed to handler. - * + * + * @param str The error message from Swing. @param param A parameter + * passed to handler. + * */ - public void handleError(java.lang.String str,int param) + public void handleError(java.lang.String str, int param) { // System.out.println("Handling error: " + str); } /* * Hot Java event callback for HTML comments. - * - * @param values The character array of text comments. - * @param param A parameter passed to handler. - * + * + * @param values The character array of text comments. @param param A + * parameter passed to handler. + * */ - public void handleComment(char[] values,int param) + public void handleComment(char[] values, int param) { - if (strip || rewriter.shouldRemoveComments()) - { - return; - } - addToResult("").addToResult(lineSeparator); + if (strip || rewriter.shouldRemoveComments()) { return; } + addToResult("") + .addToResult(lineSeparator); } /* * Hot Java event callback for end of line strings. - * + * * @param str The end-of-line string. - * + * */ - public void handleEndOfLineString(java.lang.String str) + public void handleEndOfLineString(java.lang.String str) { - if (strip) - { - return; - } - + if (strip) { return; } + addToResult(lineSeparator); addToResult(str); } - /* - * Prints new lines to make the output a little easier to read when debugging. - * - * @param tag The HTML tag being handled. - * + * Prints new lines to make the output a little easier to read when + * debugging. + * + * @param tag The HTML tag being handled. + * */ private void formatLine(HTML.Tag tag) { try { - if (tag.isBlock() || - tag.breaksFlow() || - tag == HTML.Tag.FRAME || - tag == HTML.Tag.FRAMESET || - tag == HTML.Tag.SCRIPT) + if (tag.isBlock() || tag.breaksFlow() || tag == HTML.Tag.FRAME + || tag == HTML.Tag.FRAMESET || tag == HTML.Tag.SCRIPT) { write(lineSeparator); } - - } + + } catch (Exception e) { - log.error("Format Line tag parsing error", e); + log.error("Format Line tag parsing error", e); } - + } - /* - * Used to write tag and attribute objects to the output stream. - * Returns a reference to itself so that these calls can be chained. - * + * Used to write tag and attribute objects to the output stream. Returns + * a reference to itself so that these calls can be chained. + * * @param txt Any text to be written out to stream with toString method. - * The object being written should implement its toString method. + * The object being written should implement its toString method. * @return A handle to the this, the callback, for chaining results. - * + * */ private Callback addToResult(Object txt) { // to allow for implementation using Stringbuffer or StringWriter // I don't know yet, which one is better in this case - //if (ignoreLevel > 0 ) return this; + // if (ignoreLevel > 0 ) return this; try { write(txt.toString()); - } + } catch (Exception e) { System.err.println("Error parsing:" + e); @@ -433,18 +403,17 @@ return this; } - /* - * Used to write all character content to the output stream. - * Returns a reference to itself so that these calls can be chained. - * + * Used to write all character content to the output stream. Returns a + * reference to itself so that these calls can be chained. + * * @param txt Any character text to be written out directly to stream. * @return A handle to the this, the callback, for chaining results. - * + * */ private Callback addToResult(char[] txt) { - //if (ignoreLevel > 0) return this; + // if (ignoreLevel > 0) return this; try { @@ -453,19 +422,19 @@ writer.write(txt); } - } + } catch (Exception e) { /* ignore */ } return this; } - /* + /* * Accessor to the Callback's content-String - * + * * @return Cleaned and rewritten HTML-Content - */ - public void getResult() + */ + public void getResult() { try { @@ -473,34 +442,34 @@ { writer.flush(); } - } + } catch (Exception e) { /* ignore */ } // WARNING: doesn't work, if you remove " " + ... but don't know why - //String res = " " + result.toString(); + // String res = " " + result.toString(); // return res; } /* * Flushes the output stream. NOT IMPLEMENTED - * + * */ - public void flush() throws javax.swing.text.BadLocationException + public void flush() throws javax.swing.text.BadLocationException { // nothing to do here ... } /* * Writes output to the final stream for all attributes of a given tag. - * - * @param tag The HTML tag being output. - * @param attrs The mutable HTML attribute set for the current HTML tag. - * + * + * @param tag The HTML tag being output. @param attrs The mutable HTML + * attribute set for the current HTML tag. + * */ - private void appendTagToResult(HTML.Tag tag, MutableAttributeSet attrs) + private void appendTagToResult(HTML.Tag tag, MutableAttributeSet attrs) { convertURLS(tag, attrs); Enumeration e = attrs.getAttributeNames(); @@ -509,36 +478,34 @@ { Object attr = e.nextElement(); String value = attrs.getAttribute(attr).toString(); - addToResult(" ").addToResult(attr).addToResult("=\""). - addToResult(value).addToResult("\""); - } + addToResult(" ").addToResult(attr).addToResult("=\"") + .addToResult(value).addToResult("\""); + } if (simpleTag) addToResult("/>"); - else + else addToResult(">"); } - /* - * Determines which HTML Tag/Element is being inspected, and calls the - * appropriate converter for that context. This method contains all the - * logic for determining how tags are rewritten. - * - * @param tag TAG from the Callback-Interface. - * @param attrs The mutable HTML attribute set for the current HTML element. + * Determines which HTML Tag/Element is being inspected, and calls the + * appropriate converter for that context. This method contains all the + * logic for determining how tags are rewritten. + * + * @param tag TAG from the Callback-Interface. @param attrs The mutable + * HTML attribute set for the current HTML element. */ - private void convertURLS( HTML.Tag tag, MutableAttributeSet attrs ) + private void convertURLS(HTML.Tag tag, MutableAttributeSet attrs) { - rewriter.enterConvertTagEvent(tag.toString(), new SwingAttributes(attrs)); + rewriter.enterConvertTagEvent(tag.toString(), new SwingAttributes( + attrs)); /* - if ( removeScript && (tag == HTML.Tag.SCRIPT)) { - ignoreLevel ++; - */ + * if ( removeScript && (tag == HTML.Tag.SCRIPT)) { ignoreLevel ++; + */ } - } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/CallbackElementRemover.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/CallbackElementRemover.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/CallbackElementRemover.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,13 +29,13 @@ * CallbackElementRemover *

      *

      - * Extended version of the NekoHTML ElementRemover which provides - * tag stripping/removal based on Rewriter settings. + * Extended version of the NekoHTML ElementRemover which provides tag + * stripping/removal based on Rewriter settings. *

      * * @author Scott T. Weaver * @version $Id: CallbackElementRemover.java 517719 2007-03-13 15:05:48Z ate $ - * + * */ public class CallbackElementRemover extends ElementRemover { @@ -43,33 +43,33 @@ private Rewriter rewriter; /** - * Construct with reference to the rewriter context to consult for rewriting advice + * Construct with reference to the rewriter context to consult for rewriting + * advice */ - public CallbackElementRemover( Rewriter rewriter ) + public CallbackElementRemover(Rewriter rewriter) { super(); - + this.rewriter = rewriter; } - - + // Base Class Protocol - + /** *

      * comment *

      * - * @see org.apache.xerces.xni.XMLDocumentHandler#comment(org.apache.xerces.xni.XMLString text, org.apache.xerces.xni.Augmentations augs) + * @see org.apache.xerces.xni.XMLDocumentHandler#comment(org.apache.xerces.xni.XMLString + * text, org.apache.xerces.xni.Augmentations augs) * @param text * @param augs * @throws org.apache.xerces.xni.XNIException */ - public void comment(XMLString text,Augmentations augs) throws XNIException + public void comment(XMLString text, Augmentations augs) throws XNIException { - if (rewriter.shouldRemoveComments()) - return; - super.comment(text,augs); + if (rewriter.shouldRemoveComments()) return; + super.comment(text, augs); } /** @@ -85,9 +85,10 @@ * @param arg2 * @throws org.apache.xerces.xni.XNIException */ - public void emptyElement( QName element, XMLAttributes attrs, Augmentations arg2 ) throws XNIException + public void emptyElement(QName element, XMLAttributes attrs, + Augmentations arg2) throws XNIException { - processTag(element,attrs) ; + processTag(element, attrs); super.emptyElement(element, attrs, arg2); } @@ -104,13 +105,13 @@ * @param arg2 * @throws org.apache.xerces.xni.XNIException */ - public void startElement( QName element, XMLAttributes attrs, Augmentations arg2 ) throws XNIException + public void startElement(QName element, XMLAttributes attrs, + Augmentations arg2) throws XNIException { - processTag(element,attrs); + processTag(element, attrs); super.startElement(element, attrs, arg2); } - - + // Support Methods /** @@ -126,38 +127,42 @@ if (fRemovedElements.contains(tag)) { // alread removed - return ; + return; } else if (rewriter.shouldStripTag(tag)) { // first time for this tag... // strip - remove tag and any text associated with it removeElement(tag); - return ; + return; } else if (rewriter.shouldRemoveTag(tag)) { // BOZO - block intentially left EMPTY - + // first time for this tag... - // remove - no directive necessary, the default behavior of ElementRemover is to drop tags that it does not know about (but the assocated text will remain) - return ; + // remove - no directive necessary, the default behavior of + // ElementRemover is to drop tags that it does not know about (but + // the assocated text will remain) + return; } // OTHERWISE - explicitly accept (keep tag and associated text) - // NOTE: even if fAcceptedElements contains the tag already, we need to reset the attribute names for this invocation context - rewriter.enterConvertTagEvent(tag,new XMLAttributesWrapper(attrs)); - acceptElement(tag,getAttributeNames(attrs)); + // NOTE: even if fAcceptedElements contains the tag already, we need to + // reset the attribute names for this invocation context + rewriter.enterConvertTagEvent(tag, new XMLAttributesWrapper(attrs)); + acceptElement(tag, getAttributeNames(attrs)); } + protected String[] getAttributeNames(XMLAttributes attrs) { - int length = attrs != null ? attrs.getLength() : 0 ; - String[] names = length > 0 ? new String[ length ] : null ; - - for( int i = 0, limit = length;i 0 ? new String[length] : null; + + for (int i = 0, limit = length; i < limit; i++) { - names[i] = attrs.getQName(i) ; + names[i] = attrs.getQName(i); } - return names ; + return names; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/NeckoHTMLParserAdapter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/NeckoHTMLParserAdapter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/NeckoHTMLParserAdapter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,27 +28,29 @@ * NeckoHTMLParserAdapter *

      *

      - * + * *

      + * * @author Scott T. Weaver * @version $Id: NeckoHTMLParserAdapter.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class NeckoHTMLParserAdapter implements ParserAdaptor { - /** *

      * parse *

      - * - * @see org.apache.jetspeed.rewriter.ParserAdaptor#parse(org.apache.jetspeed.rewriter.Rewriter, java.io.Reader) + * + * @see org.apache.jetspeed.rewriter.ParserAdaptor#parse(org.apache.jetspeed.rewriter.Rewriter, + * java.io.Reader) * @param rewriter * @param reader * @throws RewriterException */ - public void parse( Rewriter rewriter, Reader reader ) throws RewriterException + public void parse(Rewriter rewriter, Reader reader) + throws RewriterException { // TODO Auto-generated method stub @@ -58,14 +60,16 @@ *

      * rewrite *

      - * - * @see org.apache.jetspeed.rewriter.ParserAdaptor#rewrite(org.apache.jetspeed.rewriter.Rewriter, java.io.Reader, java.io.Writer) + * + * @see org.apache.jetspeed.rewriter.ParserAdaptor#rewrite(org.apache.jetspeed.rewriter.Rewriter, + * java.io.Reader, java.io.Writer) * @param rewriter * @param reader * @param writer * @throws RewriterException */ - public void rewrite( Rewriter rewriter, Reader reader, Writer writer ) throws RewriterException + public void rewrite(Rewriter rewriter, Reader reader, Writer writer) + throws RewriterException { // TODO Auto-generated method stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/NekoParserAdaptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/NekoParserAdaptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/NekoParserAdaptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,40 +16,38 @@ */ package org.apache.jetspeed.rewriter.html.neko; +import java.io.IOException; import java.io.Reader; -import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.xerces.xni.parser.XMLDocumentFilter; -import org.apache.xerces.xni.parser.XMLInputSource; - import org.apache.jetspeed.rewriter.ParserAdaptor; import org.apache.jetspeed.rewriter.Rewriter; import org.apache.jetspeed.rewriter.RewriterException; - -import org.xml.sax.SAXException ; - -import org.cyberneko.html.parsers.SAXParser; +import org.apache.xerces.xni.parser.XMLDocumentFilter; +import org.apache.xerces.xni.parser.XMLInputSource; import org.cyberneko.html.filters.DefaultFilter; import org.cyberneko.html.filters.Purifier; +import org.cyberneko.html.parsers.SAXParser; +import org.xml.sax.SAXException; - /** *

      * NekoParserAdapter *

      *

      - * + * *

      + * * @author David L Young * @version $Id: $ - * + * */ public class NekoParserAdaptor implements ParserAdaptor { + protected final static Log log = LogFactory.getLog(NekoParserAdaptor.class); - + /* * Construct a cyberneko HTML parser adaptor */ @@ -57,13 +55,14 @@ { super(); } - + /** *

      * parse *

      - * - * @see org.apache.jetspeed.rewriter.ParserAdaptor#parse(org.apache.jetspeed.rewriter.Rewriter, java.io.Reader) + * + * @see org.apache.jetspeed.rewriter.ParserAdaptor#parse(org.apache.jetspeed.rewriter.Rewriter, + * java.io.Reader) * @param rewriter * @param reader * @throws RewriterException @@ -72,56 +71,70 @@ throws RewriterException { // not sure what this means to parse without rewriting - rewrite(rewriter,reader,null); + rewrite(rewriter, reader, null); } /** *

      * rewrite *

      - * - * @see org.apache.jetspeed.rewriter.ParserAdaptor#rewrite(org.apache.jetspeed.rewriter.Rewriter, java.io.Reader, java.io.Writer) + * + * @see org.apache.jetspeed.rewriter.ParserAdaptor#rewrite(org.apache.jetspeed.rewriter.Rewriter, + * java.io.Reader, java.io.Writer) * @param rewriter * @param reader * @param writer * @throws RewriterException */ - public void rewrite(Rewriter rewriter, java.io.Reader reader, java.io.Writer writer) - throws RewriterException + public void rewrite(Rewriter rewriter, java.io.Reader reader, + java.io.Writer writer) throws RewriterException { // use a cyberneko SAXParser - SAXParser parser = new SAXParser() ; + SAXParser parser = new SAXParser(); // setup filter chain - XMLDocumentFilter[] filters = { - new Purifier(), // [1] standard neko purifications (tag balancing, etc) - new CallbackElementRemover( rewriter ), // [2] accept / reject tags based on advice from rewriter - writer != null ? new org.cyberneko.html.filters.Writer( writer, null ) : new DefaultFilter() // [3] propagate results to specified writer (or do nothing -- Default -- when writer is null) + XMLDocumentFilter[] filters = + {new Purifier(), // [1] standard neko purifications (tag + // balancing, etc) + new CallbackElementRemover(rewriter), // [2] accept / reject + // tags based on advice + // from rewriter + writer != null ? new org.cyberneko.html.filters.Writer(writer, + null) : new DefaultFilter() // [3] propagate results to + // specified writer (or do + // nothing -- Default -- + // when writer is null) }; - + String filtersPropName = "http://cyberneko.org/html/properties/filters"; - + try { parser.setProperty(filtersPropName, filters); } catch (SAXException e) { - // either no longer supported (SAXNotSupportedException), or no logner recognized (SAXNotRecognizedException) - log.error(filtersPropName + " is, unexpectedly, no longer defined for the cyberneko HTML parser",e); - throw new RewriterException("cyberneko parser version not supported",e); + // either no longer supported (SAXNotSupportedException), or no + // logner recognized (SAXNotRecognizedException) + log + .error( + filtersPropName + + " is, unexpectedly, no longer defined for the cyberneko HTML parser", + e); + throw new RewriterException( + "cyberneko parser version not supported", e); } try { // parse from reader - parser.parse(new XMLInputSource( null, null, null, reader, null )) ; + parser.parse(new XMLInputSource(null, null, null, reader, null)); } catch (IOException e) { String msg = "cyberneko HTML parsing failure"; - log.error(msg,e); - throw new RewriterException(msg,e); + log.error(msg, e); + throw new RewriterException(msg, e); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/URLRewriterFilter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/URLRewriterFilter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/URLRewriterFilter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,23 +34,21 @@ * * @author Scott T. Weaver * @version $Id: URLRewriterFilter.java 517121 2007-03-12 07:45:49Z ate $ - * + * */ public class URLRewriterFilter extends DefaultFilter { - - private Rewriter rewriter; - - + + private Rewriter rewriter; + /** - * + * */ - public URLRewriterFilter(Rewriter rewriter ) + public URLRewriterFilter(Rewriter rewriter) { super(); this.rewriter = rewriter; } - /** *

      @@ -65,18 +63,21 @@ * @param augs * @throws org.apache.xerces.xni.XNIException */ - public void startElement( QName element, XMLAttributes attrs, Augmentations augs ) throws XNIException + public void startElement(QName element, XMLAttributes attrs, + Augmentations augs) throws XNIException { - if (false == rewriter.enterSimpleTagEvent(element.rawname, new XMLAttributesWrapper(attrs))) + if (false == rewriter.enterSimpleTagEvent(element.rawname, + new XMLAttributesWrapper(attrs))) { doRewrite(element, attrs); - String appended = rewriter.exitSimpleTagEvent(element.rawname, new XMLAttributesWrapper(attrs)); + String appended = rewriter.exitSimpleTagEvent(element.rawname, + new XMLAttributesWrapper(attrs)); if (null != appended) { - //TODO: implement this! + // TODO: implement this! } } - + super.startElement(element, attrs, augs); } @@ -84,98 +85,111 @@ *

      * doRewrite *

      - * + * * @param element * @param attrs */ - protected void doRewrite( QName element, XMLAttributes attrs ) + protected void doRewrite(QName element, XMLAttributes attrs) { if (element.rawname.equals("A")) - { + { rewriteAttribute("href", attrs); } else if (element.rawname.equals("FORM")) - { + { rewriteAttribute("action", attrs); } } - protected void rewriteAttribute( String attrName, XMLAttributes attributes ) + protected void rewriteAttribute(String attrName, XMLAttributes attributes) { String uri = attributes.getValue(attrName); - - + if (uri != null) { - // attributes.setValue(attributes.getIndex(attrName), urlGenerator.createUrl(uri)); - + // attributes.setValue(attributes.getIndex(attrName), + // urlGenerator.createUrl(uri)); + } } + /** *

      * emptyElement *

      - * - * @see org.apache.xerces.xni.XMLDocumentHandler#emptyElement(org.apache.xerces.xni.QName, org.apache.xerces.xni.XMLAttributes, org.apache.xerces.xni.Augmentations) + * + * @see org.apache.xerces.xni.XMLDocumentHandler#emptyElement(org.apache.xerces.xni.QName, + * org.apache.xerces.xni.XMLAttributes, + * org.apache.xerces.xni.Augmentations) * @param arg0 * @param arg1 * @param arg2 * @throws org.apache.xerces.xni.XNIException */ - public void emptyElement( QName element, XMLAttributes attrs, Augmentations arg2 ) throws XNIException + public void emptyElement(QName element, XMLAttributes attrs, + Augmentations arg2) throws XNIException { doRewrite(element, attrs); super.emptyElement(element, attrs, arg2); } + /** *

      * comment *

      - * - * @see org.apache.xerces.xni.XMLDocumentHandler#comment(org.apache.xerces.xni.XMLString, org.apache.xerces.xni.Augmentations) + * + * @see org.apache.xerces.xni.XMLDocumentHandler#comment(org.apache.xerces.xni.XMLString, + * org.apache.xerces.xni.Augmentations) * @param comment * @param augs * @throws org.apache.xerces.xni.XNIException */ - public void comment( XMLString comment, Augmentations augs ) throws XNIException + public void comment(XMLString comment, Augmentations augs) + throws XNIException { if (!rewriter.shouldRemoveComments()) { - super.comment(comment, augs); + super.comment(comment, augs); } - + } + /** *

      * endElement *

      - * - * @see org.apache.xerces.xni.XMLDocumentHandler#endElement(org.apache.xerces.xni.QName, org.apache.xerces.xni.Augmentations) + * + * @see org.apache.xerces.xni.XMLDocumentHandler#endElement(org.apache.xerces.xni.QName, + * org.apache.xerces.xni.Augmentations) * @param arg0 * @param arg1 * @throws org.apache.xerces.xni.XNIException */ - public void endElement( QName element, Augmentations augs ) throws XNIException + public void endElement(QName element, Augmentations augs) + throws XNIException { super.endElement(element, augs); } + /** *

      * characters *

      - * - * @see org.apache.xerces.xni.XMLDocumentHandler#characters(org.apache.xerces.xni.XMLString, org.apache.xerces.xni.Augmentations) + * + * @see org.apache.xerces.xni.XMLDocumentHandler#characters(org.apache.xerces.xni.XMLString, + * org.apache.xerces.xni.Augmentations) * @param arg0 * @param arg1 * @throws org.apache.xerces.xni.XNIException */ - public void characters( XMLString text, Augmentations arg1 ) throws XNIException - { - if (!(text.ch[0] == '>') && ! rewriter.enterText(text.ch, text.offset)) - { + public void characters(XMLString text, Augmentations arg1) + throws XNIException + { + if (!(text.ch[0] == '>') && !rewriter.enterText(text.ch, text.offset)) + { super.characters(text, arg1); - } + } } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/XMLAttributesWrapper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/XMLAttributesWrapper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/html/neko/XMLAttributesWrapper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,16 +26,18 @@ * XMLAttributesWrapper *

      *

      - * + * *

      + * * @author Scott T. Weaver * @version $Id: XMLAttributesWrapper.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class XMLAttributesWrapper implements MutableAttributes { + protected XMLAttributes attrs; - + /** * */ @@ -49,257 +51,276 @@ *

      * addAttribute *

      - * + * * @param arg0 * @param arg1 * @param arg2 * @return */ - public int addAttribute( QName arg0, String arg1, String arg2 ) + public int addAttribute(QName arg0, String arg1, String arg2) { - int i = getIndex( arg0.rawname ); - if ( i >= 0 ) - attrs.removeAttributeAt( i ); - - return attrs.addAttribute( arg0, arg1, arg2 ); + int i = getIndex(arg0.rawname); + if (i >= 0) attrs.removeAttributeAt(i); + + return attrs.addAttribute(arg0, arg1, arg2); } + /** *

      * equals *

      - * + * * @see java.lang.Object#equals(java.lang.Object) * @param obj * @return */ - public boolean equals( Object obj ) + public boolean equals(Object obj) { return attrs.equals(obj); } + /** *

      * getAugmentations *

      - * + * * @param arg0 * @return */ - public Augmentations getAugmentations( int arg0 ) + public Augmentations getAugmentations(int arg0) { return attrs.getAugmentations(arg0); } + /** *

      * getAugmentations *

      - * + * * @param arg0 * @return */ - public Augmentations getAugmentations( String qName ) + public Augmentations getAugmentations(String qName) { - return attrs.getAugmentations(asNekoAttributeName(qName)) ; + return attrs.getAugmentations(asNekoAttributeName(qName)); } + /** *

      * getAugmentations *

      - * + * * @param arg0 * @param arg1 * @return */ - public Augmentations getAugmentations( String uri, String localPart ) + public Augmentations getAugmentations(String uri, String localPart) { - return attrs.getAugmentations(uri,asNekoAttributeName(localPart)); + return attrs.getAugmentations(uri, asNekoAttributeName(localPart)); } + /** *

      * getIndex *

      - * + * * @param arg0 * @return */ - public int getIndex( String qName ) + public int getIndex(String qName) { return attrs.getIndex(asNekoAttributeName(qName)); } + /** *

      * getIndex *

      - * + * * @param arg0 * @param arg1 * @return */ - public int getIndex( String uri, String localName ) + public int getIndex(String uri, String localName) { - return attrs.getIndex(uri,asNekoAttributeName(localName)); + return attrs.getIndex(uri, asNekoAttributeName(localName)); } + /** *

      * getLength *

      - * + * * @return */ public int getLength() { return attrs.getLength(); } + /** *

      * getLocalName *

      - * + * * @param arg0 * @return */ - public String getLocalName( int arg0 ) + public String getLocalName(int arg0) { return attrs.getLocalName(arg0); } + /** *

      * getName *

      - * + * * @param arg0 * @param arg1 */ - public void getName( int arg0, QName arg1 ) + public void getName(int arg0, QName arg1) { attrs.getName(arg0, arg1); } + /** *

      * getNonNormalizedValue *

      - * + * * @param arg0 * @return */ - public String getNonNormalizedValue( int arg0 ) + public String getNonNormalizedValue(int arg0) { return attrs.getNonNormalizedValue(arg0); } + /** *

      * getPrefix *

      - * + * * @param arg0 * @return */ - public String getPrefix( int arg0 ) + public String getPrefix(int arg0) { return attrs.getPrefix(arg0); } + /** *

      * getQName *

      - * + * * @param arg0 * @return */ - public String getQName( int arg0 ) + public String getQName(int arg0) { return attrs.getQName(arg0); } + /** *

      * getType *

      - * + * * @param arg0 * @return */ - public String getType( int arg0 ) + public String getType(int arg0) { return attrs.getType(arg0); } + /** *

      * getType *

      - * + * * @param arg0 * @return */ - public String getType( String qName ) + public String getType(String qName) { return attrs.getType(asNekoAttributeName(qName)); } + /** *

      * getType *

      - * + * * @param arg0 * @param arg1 * @return */ - public String getType( String uri, String localName ) + public String getType(String uri, String localName) { return attrs.getType(uri, asNekoAttributeName(localName)); } + /** *

      * getURI *

      - * + * * @param arg0 * @return */ - public String getURI( int arg0 ) + public String getURI(int arg0) { return attrs.getURI(arg0); } + /** *

      * getValue *

      - * + * * @param arg0 * @return */ - public String getValue( int arg0 ) + public String getValue(int arg0) { return attrs.getValue(arg0); } + /** *

      * getValue *

      - * + * * @param arg0 * @return */ - public String getValue( String qName ) + public String getValue(String qName) { return attrs.getValue(asNekoAttributeName(qName)); } + /** *

      * getValue *

      - * + * * @param arg0 * @param arg1 * @return */ - public String getValue( String uri, String localName ) + public String getValue(String uri, String localName) { return attrs.getValue(uri, asNekoAttributeName(localName)); } + /** *

      * hashCode *

      - * + * * @see java.lang.Object#hashCode() * @return */ @@ -307,117 +328,127 @@ { return attrs.hashCode(); } + /** *

      * isSpecified *

      - * + * * @param arg0 * @return */ - public boolean isSpecified( int arg0 ) + public boolean isSpecified(int arg0) { return attrs.isSpecified(arg0); } + /** *

      * removeAllAttributes *

      - * * + * */ public void removeAllAttributes() { attrs.removeAllAttributes(); } + /** *

      * removeAttributeAt *

      - * + * * @param arg0 */ - public void removeAttributeAt( int arg0 ) + public void removeAttributeAt(int arg0) { attrs.removeAttributeAt(arg0); } + /** *

      * setAugmentations *

      - * + * * @param arg0 * @param arg1 */ - public void setAugmentations( int arg0, Augmentations arg1 ) + public void setAugmentations(int arg0, Augmentations arg1) { attrs.setAugmentations(arg0, arg1); } + /** *

      * setName *

      - * + * * @param arg0 * @param arg1 */ - public void setName( int arg0, QName arg1 ) + public void setName(int arg0, QName arg1) { attrs.setName(arg0, arg1); } + /** *

      * setNonNormalizedValue *

      - * + * * @param arg0 * @param arg1 */ - public void setNonNormalizedValue( int arg0, String arg1 ) + public void setNonNormalizedValue(int arg0, String arg1) { attrs.setNonNormalizedValue(arg0, arg1); } + /** *

      * setSpecified *

      - * + * * @param arg0 * @param arg1 */ - public void setSpecified( int arg0, boolean arg1 ) + public void setSpecified(int arg0, boolean arg1) { attrs.setSpecified(arg0, arg1); } + /** *

      * setType *

      - * + * * @param arg0 * @param arg1 */ - public void setType( int arg0, String arg1 ) + public void setType(int arg0, String arg1) { attrs.setType(arg0, arg1); } + /** *

      * setValue *

      - * + * * @param arg0 * @param arg1 */ - public void setValue( int arg0, String arg1 ) + public void setValue(int arg0, String arg1) { attrs.setValue(arg0, arg1); } + /** *

      * toString *

      - * + * * @see java.lang.Object#toString() * @return */ @@ -425,40 +456,41 @@ { return attrs.toString(); } + /** *

      * addAttribute *

      - * - * @see org.apache.jetspeed.rewriter.MutableAttributes#addAttribute(java.lang.String, java.lang.Object) + * + * @see org.apache.jetspeed.rewriter.MutableAttributes#addAttribute(java.lang.String, + * java.lang.Object) * @param name * @param value */ - public void addAttribute( String name, Object value ) + public void addAttribute(String name, Object value) { - QName qName = null ; + QName qName = null; int i = name.indexOf(':'); if (i < 0) { name = name.toLowerCase(); - qName = new QName(null,name,name,null); + qName = new QName(null, name, name, null); } else { - String prefix = name.substring(0,i); - String localPart = name.substring(i+1).toLowerCase(); + String prefix = name.substring(0, i); + String localPart = name.substring(i + 1).toLowerCase(); name = name.toLowerCase(); - qName = new QName(prefix,localPart,name,null); + qName = new QName(prefix, localPart, name, null); } - addAttribute(qName,"CDATA",value.toString()); + addAttribute(qName, "CDATA", value.toString()); } - - + // Support Methods - + protected String asNekoAttributeName(String n) { // neko, by default, converts attribute names to lower case - return n != null ? n.toLowerCase() : null ; + return n != null ? n.toLowerCase() : null; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Attribute.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Attribute.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Attribute.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,23 +18,25 @@ /** * Attribute - * + * * @author David Sean Taylor * @version $Id: Attribute.java 516448 2007-03-09 16:25:47Z ate $ */ public interface Attribute extends Identified { + /** * Get the rewriter rule associated with this attribute. * * @return The rewriter rule. */ Rule getRule(); - + /** * Set the rewriter rule associated with this attribute. * - * @param rule The rewriter rule. - */ + * @param rule + * The rewriter rule. + */ void setRule(Rule rule); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Identified.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Identified.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Identified.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,24 +18,26 @@ /** * Identified - * + * * @author David Sean Taylor * @version $Id: Identified.java 516448 2007-03-09 16:25:47Z ate $ */ public interface Identified { + /** * Get the unique identification string for this rule. * - * @return the unique identifier of the rule + * @return the unique identifier of the rule */ String getId(); - + /** * Set the unique identification string for this rule. * - * @param id the unique identifier of the rule + * @param id + * the unique identifier of the rule */ void setId(String id); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Rule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Rule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Rule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,65 +18,67 @@ /** * Rule - * + * * @author David Sean Taylor * @version $Id: Rule.java 516448 2007-03-09 16:25:47Z ate $ */ public interface Rule extends Identified { + /** - * Flag indicating whether to use the Base URL for this rewriter. - * The default setting is true, use the rewriter's Base URL. + * Flag indicating whether to use the Base URL for this rewriter. The + * default setting is true, use the rewriter's Base URL. * * @return true if this rule uses the Base URL */ boolean getUseBase(); - + /** - * Flag indicating whether to use the Base URL for this rewriter. - * The default setting is true, use the rewriter's Base URL. + * Flag indicating whether to use the Base URL for this rewriter. The + * default setting is true, use the rewriter's Base URL. * - * @param true if this rule uses the Base URL - */ + * @param true + * if this rule uses the Base URL + */ void setUseBase(boolean flag); - + /** * Suffix string to append to the rewritten URL. * * @return the value of the suffix string. */ String getSuffix(); - + /** * Suffix string to append to the rewritten URL. * - * @param the value of the suffix string. - */ + * @param the + * value of the suffix string. + */ void setSuffix(String suffix); - + /** - * Flag indicating whether to rewrite links as popups. - * The default setting is false, do not rewrite as a popup. + * Flag indicating whether to rewrite links as popups. The default setting + * is false, do not rewrite as a popup. * * @return true if this rule rewrites links as popups */ boolean getPopup(); /** - * Flag indicating whether to rewrite links as popups. - * The default setting is false, do not rewrite as a popup. + * Flag indicating whether to rewrite links as popups. The default setting + * is false, do not rewrite as a popup. * - * @param true if this rule rewrites links as popups - */ + * @param true + * if this rule rewrites links as popups + */ void setPopup(boolean flag); - + /** * Checks to see if a URL should be rewritten or not. * * @param url - */ + */ boolean shouldRewrite(String url); - - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Ruleset.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Ruleset.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Ruleset.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,49 +20,54 @@ /** * Ruleset - * + * * @author David Sean Taylor * @version $Id: Ruleset.java 516448 2007-03-09 16:25:47Z ate $ */ public interface Ruleset extends Identified -{ +{ + /** - * Get the remove comments flag for removing comments from the markup source. + * Get the remove comments flag for removing comments from the markup + * source. * * @return true True if comments should be removed. */ public boolean getRemoveComments(); /** - * Set the remove comments flag for removing comments from the markup source. + * Set the remove comments flag for removing comments from the markup + * source. * - * @param flag True if comments should be removed. - */ + * @param flag + * True if comments should be removed. + */ public void setRemoveComments(boolean flag); /** * Given a tag identifier, lookup and return a tag object. * - * @param tagId the unique tag identifier + * @param tagId + * the unique tag identifier * @return the tag object for the given identifier */ Tag getTag(String tagId); - + /** * Given a rule identifier, lookup and return a rule object. * - * @param ruleId the unique rule identifier + * @param ruleId + * the unique rule identifier * @return the rule object for the given identifier - */ - Rule getRule(String ruleId); + */ + Rule getRule(String ruleId); - /** * Get a collection of rules for this rule set. * * @return A collection of rules. */ - Collection getRules(); + Collection getRules(); /** * Get a collection of markup tags for this rule set. @@ -76,5 +81,5 @@ * */ void sync(); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Tag.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Tag.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/Tag.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,24 +20,24 @@ /** * Tag - * + * * @author David Sean Taylor * @version $Id: Tag.java 516448 2007-03-09 16:25:47Z ate $ */ public interface Tag extends Identified { + /** * Get a collection of attributes for the given Tag. * * @return A collection of attributes. */ Collection getAttributes(); - - + /** * Represents whether this tag is to be removed during rewrite phase. - * Removing a tag only removes the tag but not the contents in - * between the start and end tag. + * Removing a tag only removes the tag but not the contents in between the + * start and end tag. * * @return true if this tag should be removed */ @@ -45,17 +45,18 @@ /** * Represents whether this tag is to be removed during rewrite phase. - * Removing a tag only removes the tag but not the contents in - * between the start and end tag. + * Removing a tag only removes the tag but not the contents in between the + * start and end tag. * - * @param flag true if this tag should be removed - */ + * @param flag + * true if this tag should be removed + */ public void setRemove(boolean flag); /** * Represents whether this tag is to be removed during rewrite phase. - * Stripping tags removes the start and end tag, plus all tags - * and content in between the start and end tag. + * Stripping tags removes the start and end tag, plus all tags and content + * in between the start and end tag. * * @return true if this tag should be stripped. */ @@ -63,11 +64,12 @@ /** * Represents whether this tag is to be removed during rewrite phase. - * Stripping tags removes the start and end tag, plus all tags - * and content in between the start and end tag. + * Stripping tags removes the start and end tag, plus all tags and content + * in between the start and end tag. * - * @param flag true if this tag should be stripped. - */ + * @param flag + * true if this tag should be stripped. + */ public void setStrip(boolean flag); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/AttributeImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/AttributeImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/AttributeImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,16 +21,20 @@ /** * Attribute - * + * * @author David Sean Taylor * @version $Id: AttributeImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class AttributeImpl extends IdentifiedImpl implements Attribute { + private Rule rule; + private String ruleId; - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Ruleset#setId(java.lang.String) */ public void setId(String id) @@ -40,33 +44,38 @@ this.id = id.toUpperCase(); } } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Attribute#getRule() */ public Rule getRule() { return this.rule; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Attribute#setRule(org.apache.jetspeed.cps.rewriter.rules.Rule) */ public void setRule(Rule rule) - { + { this.rule = rule; } - + /** * Castor setter to set the rule id. * - * @param ruleId The rule identifier. + * @param ruleId + * The rule identifier. */ public void setRuleId(String ruleId) { this.ruleId = ruleId; } - + /** * Castor accessor to get the rule id. * @@ -76,5 +85,5 @@ { return this.ruleId; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/IdentifiedImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/IdentifiedImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/IdentifiedImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,15 +18,18 @@ /** * IdentifiedImpl - * + * * @author David Sean Taylor * @version $Id: IdentifiedImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class IdentifiedImpl { + protected String id; - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Ruleset#getId() */ public String getId() @@ -34,15 +37,17 @@ return id; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Ruleset#setId(java.lang.String) */ public void setId(String id) { if (id != null) { - this.id = id; + this.id = id; } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/RuleImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/RuleImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/RuleImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,33 +16,40 @@ */ package org.apache.jetspeed.rewriter.rules.impl; +import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import java.util.ArrayList; import java.util.StringTokenizer; import org.apache.jetspeed.rewriter.rules.Rule; /** * Rule - * + * * @author David Sean Taylor * @version $Id: RuleImpl.java 517121 2007-03-12 07:45:49Z ate $ */ public class RuleImpl extends IdentifiedImpl implements Rule { + private boolean useBase = true; + private boolean popup = false; + private String suffix = null; + private String prefixes = null; - private List ignorePrefixes = null; - + + private List ignorePrefixes = null; + public String toString() { return id; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Rule#getPopup() */ public boolean getPopup() @@ -50,7 +57,9 @@ return popup; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Rule#getSuffix() */ public String getSuffix() @@ -58,7 +67,9 @@ return suffix; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Rule#getUseBase() */ public boolean getUseBase() @@ -66,7 +77,9 @@ return useBase; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Rule#setPopup(boolean) */ public void setPopup(boolean b) @@ -74,7 +87,9 @@ popup = b; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Rule#setSuffix(java.lang.String) */ public void setSuffix(String string) @@ -82,30 +97,29 @@ suffix = string; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Rule#setUseBase(boolean) */ public void setUseBase(boolean b) { useBase = b; } - + public void setIgnorePrefixes(String prefixes) - { - this.prefixes = prefixes; + { + this.prefixes = prefixes; } public String getIgnorePrefixes() { - return this.prefixes; + return this.prefixes; } - + public boolean shouldRewrite(String url) { - if (prefixes == null) - { - return true; - } + if (prefixes == null) { return true; } if (ignorePrefixes == null) { ignorePrefixes = new ArrayList(); @@ -114,21 +128,17 @@ { String token = tokenizer.nextToken(); ignorePrefixes.add(token); - } - + } + } - + Iterator list = ignorePrefixes.iterator(); while (list.hasNext()) { - String prefix = (String)list.next(); - if (url.startsWith(prefix)) - { - return false; - } + String prefix = (String) list.next(); + if (url.startsWith(prefix)) { return false; } } - return true; + return true; } - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/RulesetImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/RulesetImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/RulesetImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,40 +29,49 @@ /** * RulesetImpl - * + * * @author David Sean Taylor * @version $Id: RulesetImpl.java 516448 2007-03-09 16:25:47Z ate $ */ /** * Ruleset - * + * * @author David Sean Taylor * @version $Id: RulesetImpl.java 516448 2007-03-09 16:25:47Z ate $ */ -public class RulesetImpl extends IdentifiedImpl implements Ruleset +public class RulesetImpl extends IdentifiedImpl implements Ruleset { + private Collection rules = new ArrayList(); + private Collection tags = new ArrayList(); + private Map ruleMap = new HashMap(); - private Map tagMap = new HashMap(); + + private Map tagMap = new HashMap(); + private boolean removeComments = false; - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Ruleset#getTag(java.lang.String) */ public Tag getTag(String tagId) { - return (Tag)tagMap.get(tagId); + return (Tag) tagMap.get(tagId); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Ruleset#getRule(java.lang.String) */ public Rule getRule(String ruleId) { - return (Rule)ruleMap.get(ruleId); + return (Rule) ruleMap.get(ruleId); } - + public String toString() { StringBuffer buffer = new StringBuffer("Ruleset:" + id); @@ -74,12 +83,12 @@ { buffer.append(", rules: "); Iterator it = rules.iterator(); - while (it.hasNext()) + while (it.hasNext()) { - RuleImpl rule = (RuleImpl)it.next(); + RuleImpl rule = (RuleImpl) it.next(); buffer.append(rule.toString()); buffer.append(", "); - } + } } if (tags.size() == 0) { @@ -89,52 +98,54 @@ { buffer.append("tags: "); Iterator it = tags.iterator(); - while (it.hasNext()) + while (it.hasNext()) { - TagImpl tag = (TagImpl)it.next(); + TagImpl tag = (TagImpl) it.next(); buffer.append(tag.toString()); buffer.append(", "); - } + } } - return buffer.toString(); + return buffer.toString(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Ruleset#sync() */ public void sync() { ruleMap.clear(); Iterator it = rules.iterator(); - while (it.hasNext()) + while (it.hasNext()) { - Rule rule = (Rule)it.next(); - ruleMap.put(rule.getId(), rule); - } - - tagMap.clear(); + Rule rule = (Rule) it.next(); + ruleMap.put(rule.getId(), rule); + } + + tagMap.clear(); it = tags.iterator(); - while (it.hasNext()) + while (it.hasNext()) { - Tag tag = (Tag)it.next(); + Tag tag = (Tag) it.next(); tagMap.put(tag.getId(), tag); Iterator attributes = tag.getAttributes().iterator(); while (attributes.hasNext()) - { - Attribute attribute = (Attribute)attributes.next(); + { + Attribute attribute = (Attribute) attributes.next(); if (attribute instanceof AttributeImpl) { - String ruleId = ((AttributeImpl)attribute).getRuleId(); - Rule rule = (Rule)ruleMap.get(ruleId); + String ruleId = ((AttributeImpl) attribute).getRuleId(); + Rule rule = (Rule) ruleMap.get(ruleId); if (rule != null) { attribute.setRule(rule); } - } + } } - } + } } - + /** * Castor setter * @@ -145,7 +156,9 @@ this.rules = rules; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Ruleset#getRules() */ public Collection getRules() @@ -163,15 +176,19 @@ this.tags = tags; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Ruleset#getTags() */ public Collection getTags() { return this.tags; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Ruleset#getRemoveComments() */ public boolean getRemoveComments() @@ -179,7 +196,9 @@ return removeComments; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Ruleset#setRemoveComments(boolean) */ public void setRemoveComments(boolean b) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/TagImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/TagImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/rules/impl/TagImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,28 +23,35 @@ /** * Tag - * + * * @author David Sean Taylor * @version $Id: TagImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class TagImpl extends IdentifiedImpl implements Tag { + private boolean remove = false; + private boolean strip = false; - private Collection attributes = new ArrayList(); - /* (non-Javadoc) + private Collection attributes = new ArrayList(); + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Ruleset#setId(java.lang.String) */ public void setId(String id) { if (id != null) { - this.id = id.toUpperCase(); + this.id = id.toUpperCase(); } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Tag#getRemove() */ public boolean getRemove() @@ -52,7 +59,9 @@ return remove; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.cps.rewriter.rules.Tag#setRemove(boolean) */ public void setRemove(boolean b) @@ -85,7 +94,6 @@ return this.attributes; } - /** * @return */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/xml/SaxParserAdaptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/xml/SaxParserAdaptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/rewriter/xml/SaxParserAdaptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,10 +31,10 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.jetspeed.rewriter.MutableAttributes; import org.apache.jetspeed.rewriter.ParserAdaptor; import org.apache.jetspeed.rewriter.Rewriter; import org.apache.jetspeed.rewriter.RewriterException; -import org.apache.jetspeed.rewriter.MutableAttributes; import org.apache.jetspeed.util.Streams; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -42,75 +42,83 @@ /** * SaxParserAdaptor - * + * * @author David Sean Taylor * @version $Id: SaxParserAdaptor.java 516448 2007-03-09 16:25:47Z ate $ */ public class SaxParserAdaptor implements ParserAdaptor { + protected final static Log log = LogFactory.getLog(SaxParserAdaptor.class); + private String lineSeparator; private Rewriter rewriter; - - - public SaxParserAdaptor() { lineSeparator = System.getProperty("line.separator", "\r\n"); } - - /* (non-Javadoc) - * @see org.apache.jetspeed.syndication.services.crawler.rewriter.ParserAdaptor#parse(org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter, java.io.Reader) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.syndication.services.crawler.rewriter.ParserAdaptor#parse(org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter, + * java.io.Reader) */ public void parse(Rewriter rewriter, Reader reader) - throws RewriterException + throws RewriterException { try { - this.rewriter = rewriter; - SAXParser sp = getParser(); - sp.parse(new InputSource(reader), new SaxFormatHandler(null)); - } + this.rewriter = rewriter; + SAXParser sp = getParser(); + sp.parse(new InputSource(reader), new SaxFormatHandler(null)); + } catch (Exception e) { e.printStackTrace(); throw new RewriterException(e); } - + } - - /* (non-Javadoc) - * @see org.apache.jetspeed.syndication.services.crawler.rewriter.ParserAdaptor#rewrite(org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter, java.io.Reader, java.io.Writer) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.syndication.services.crawler.rewriter.ParserAdaptor#rewrite(org.apache.jetspeed.syndication.services.crawler.rewriter.Rewriter, + * java.io.Reader, java.io.Writer) */ public void rewrite(Rewriter rewriter, Reader reader, Writer writer) - throws RewriterException + throws RewriterException { // TODO Auto-generated method stub } - + /** * Get a Parser from the SAX Parser factory - * + * * @return A SAXParser */ - protected SAXParser getParser() - throws ParserConfigurationException, SAXException + protected SAXParser getParser() throws ParserConfigurationException, + SAXException { - SAXParserFactory spf = SAXParserFactory.newInstance (); + SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setValidating(false); - return spf.newSAXParser (); + return spf.newSAXParser(); } /** * Inner class to handle SAX parsing of XML files */ public class SaxFormatHandler extends DefaultHandler - { + { + private int elementCount = 0; + private boolean emit = true; + private Writer writer = null; public SaxFormatHandler(Writer writer) @@ -118,9 +126,8 @@ super(); this.writer = writer; } - - private void write(String text) - throws IOException + + private void write(String text) throws IOException { if (writer != null) { @@ -130,11 +137,9 @@ public void characters(char[] values, int start, int length) { - if (false == emit) - return; + if (false == emit) return; - if (false == rewriter.enterText(values, start)) - return; + if (false == rewriter.enterText(values, start)) return; if (writer != null) { @@ -142,92 +147,92 @@ { writer.write(values); } - catch(IOException e) - { + catch (IOException e) + { } - } + } } - - public void startElement(String uri, String localName, String qName, MutableAttributes attributes) - throws SAXException + + public void startElement(String uri, String localName, String qName, + MutableAttributes attributes) throws SAXException { -// System.out.println("qName = " + qName); -// System.out.println("localName = " + localName); -// System.out.println("uri = " + uri); + // System.out.println("qName = " + qName); + // System.out.println("localName = " + localName); + // System.out.println("uri = " + uri); String tag = qName; - - if (false == rewriter.enterStartTagEvent(tag.toString(), attributes)) - return; + if (false == rewriter + .enterStartTagEvent(tag.toString(), attributes)) return; + try { appendTagToResult(tag, attributes); - write(lineSeparator); - String appended = rewriter.exitStartTagEvent(tag.toString(), attributes); + write(lineSeparator); + String appended = rewriter.exitStartTagEvent(tag.toString(), + attributes); if (null != appended) { write(appended); } - } + } catch (Exception e) { - log.error("Start tag parsing error", e); + log.error("Start tag parsing error", e); } } - - public void endElement(String uri, String localName, String qName) - throws SAXException + + public void endElement(String uri, String localName, String qName) + throws SAXException { String tag = qName; elementCount++; - if (false == rewriter.enterEndTagEvent(tag.toString())) - return; - + if (false == rewriter.enterEndTagEvent(tag.toString())) return; + try - { + { addToResult(""); - - write(lineSeparator); + + write(lineSeparator); String appended = rewriter.exitEndTagEvent(tag.toString()); if (null != appended) { write(appended); } - } + } catch (Exception e) { - log.error("End tag parsing error", e); - } - + log.error("End tag parsing error", e); + } + } /* * Writes output to the final stream for all attributes of a given tag. - * - * @param tag The HTML tag being output. - * @param attrs The mutable HTML attribute set for the current HTML tag. + * + * @param tag The HTML tag being output. @param attrs The mutable HTML + * attribute set for the current HTML tag. */ - private void appendTagToResult(String tag, MutableAttributes attrs) + private void appendTagToResult(String tag, MutableAttributes attrs) { convertURLS(tag, attrs); addToResult("<").addToResult(tag); for (int ix = 0; ix < attrs.getLength(); ix++) { String value = attrs.getValue(ix); - addToResult(" ").addToResult(value).addToResult("=\""). - addToResult(value).addToResult("\""); - } + addToResult(" ").addToResult(value).addToResult("=\"") + .addToResult(value).addToResult("\""); + } addToResult(">"); } - + /* - * Used to write tag and attribute objects to the output stream. - * Returns a reference to itself so that these calls can be chained. - * + * Used to write tag and attribute objects to the output stream. Returns + * a reference to itself so that these calls can be chained. + * * @param txt Any text to be written out to stream with toString method. - * The object being written should implement its toString method. + * The object being written should implement its toString method. * @return A handle to the this, the callback, for chaining results. - * + * */ private SaxFormatHandler addToResult(Object txt) { @@ -238,7 +243,7 @@ try { write(txt.toString()); - } + } catch (Exception e) { System.err.println("Error parsing:" + e); @@ -247,63 +252,63 @@ } /* - * Determines which HTML Tag/Element is being inspected, and calls the - * appropriate converter for that context. This method contains all the - * logic for determining how tags are rewritten. - * - * TODO: it would be better to drive this logic off a state table that is not - * tied to the Hot Java parser. - * - * @param tag TAG from the Callback-Interface. - * @param attrs The mutable HTML attribute set for the current HTML element. + * Determines which HTML Tag/Element is being inspected, and calls the + * appropriate converter for that context. This method contains all the + * logic for determining how tags are rewritten. + * + * TODO: it would be better to drive this logic off a state table that + * is not tied to the Hot Java parser. + * + * @param tag TAG from the Callback-Interface. @param attrs The mutable + * HTML attribute set for the current HTML element. */ - private void convertURLS(String tag, MutableAttributes attrs) + private void convertURLS(String tag, MutableAttributes attrs) { rewriter.enterConvertTagEvent(tag.toString(), attrs); } - - public InputSource resolveEntity (String publicId, String systemId) + + public InputSource resolveEntity(String publicId, String systemId) { - - try + + try { - Map dtds = getDtds(); - byte[] dtd = (byte[])dtds.get(systemId); + Map dtds = getDtds(); + byte[] dtd = (byte[]) dtds.get(systemId); if (dtd == null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); URL url = new URL(systemId); Streams.drain(url.openStream(), baos); dtd = baos.toByteArray(); - dtds.put(systemId, dtd); + dtds.put(systemId, dtd); } - + if (dtd != null) { ByteArrayInputStream bais = new ByteArrayInputStream(dtd); InputSource is = new InputSource(bais); - is.setPublicId( publicId ); - is.setSystemId( systemId ); - + is.setPublicId(publicId); + is.setSystemId(systemId); + return is; } - } - catch(Throwable t ) // java.io.IOException x + } + catch (Throwable t) // java.io.IOException x { t.printStackTrace(); log.error("failed to get URL input source", t); } - + // forces to get dtd over internet return null; } - + } - // DTD Map + // DTD Map static private Map dtds = new HashMap(); - + public static Map getDtds() { return dtds; @@ -313,5 +318,5 @@ { dtds.clear(); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/util/Streams.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/util/Streams.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/java/org/apache/jetspeed/util/Streams.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,127 +17,124 @@ package org.apache.jetspeed.util; import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; -import java.io.InputStreamReader; /** * Utility functions related to Streams. - * + * * @author David Sean Taylor * @version $Id: Streams.java 516448 2007-03-09 16:25:47Z ate $ */ public class Streams { - static final int BLOCK_SIZE=4096; - public static void drain(InputStream r,OutputStream w) throws IOException - { - byte[] bytes=new byte[BLOCK_SIZE]; - try - { - int length=r.read(bytes); - while(length!=-1) + static final int BLOCK_SIZE = 4096; + + public static void drain(InputStream r, OutputStream w) throws IOException + { + byte[] bytes = new byte[BLOCK_SIZE]; + try { - if(length!=0) + int length = r.read(bytes); + while (length != -1) + { + if (length != 0) { - w.write(bytes,0,length); + w.write(bytes, 0, length); } - length=r.read(bytes); + length = r.read(bytes); + } } + finally + { + bytes = null; + } + } - finally - { - bytes=null; - } - } - - public static void drain(Reader r,Writer w) throws IOException - { - char[] bytes=new char[BLOCK_SIZE]; - try + public static void drain(Reader r, Writer w) throws IOException { - int length=r.read(bytes); - while(length!=-1) + char[] bytes = new char[BLOCK_SIZE]; + try { - if(length!=0) + int length = r.read(bytes); + while (length != -1) { - w.write(bytes,0,length); + if (length != 0) + { + w.write(bytes, 0, length); + } + length = r.read(bytes); } - length=r.read(bytes); } + finally + { + bytes = null; + } + } - finally + + public static void drain(Reader r, OutputStream os) throws IOException { - bytes=null; + Writer w = new OutputStreamWriter(os); + drain(r, w); + w.flush(); } - } - - public static void drain(Reader r,OutputStream os) throws IOException - { - Writer w=new OutputStreamWriter(os); - drain(r,w); + public static void drain(InputStream is, Writer w) throws IOException + { + Reader r = new InputStreamReader(is); + drain(r, w); w.flush(); - } + } - public static void drain(InputStream is, Writer w) throws IOException - { - Reader r = new InputStreamReader(is); - drain(r,w); - w.flush(); - } - - public static byte[] drain(InputStream r) throws IOException - { - ByteArrayOutputStream bytes=new ByteArrayOutputStream(); - drain(r,bytes); + public static byte[] drain(InputStream r) throws IOException + { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + drain(r, bytes); return bytes.toByteArray(); - } + } - public static String getAsString(InputStream is) - { - int c=0; - char lineBuffer[]=new char[128], buf[]=lineBuffer; - int room= buf.length, offset=0; - try - { - loop: while (true) - { - // read chars into a buffer which grows as needed - switch (c = is.read() ) + public static String getAsString(InputStream is) + { + int c = 0; + char lineBuffer[] = new char[128], buf[] = lineBuffer; + int room = buf.length, offset = 0; + try + { + loop: while (true) + { + // read chars into a buffer which grows as needed + switch (c = is.read()) { - case -1: break loop; + case -1: + break loop; - default: if (--room < 0) - { - buf = new char[offset + 128]; - room = buf.length - offset - 1; - System.arraycopy(lineBuffer, 0, - buf, 0, offset); - lineBuffer = buf; - } - buf[offset++] = (char) c; - break; + default: + if (--room < 0) + { + buf = new char[offset + 128]; + room = buf.length - offset - 1; + System.arraycopy(lineBuffer, 0, buf, 0, offset); + lineBuffer = buf; + } + buf[offset++] = (char) c; + break; } - } - } - catch(IOException ioe) - { - ioe.printStackTrace(); - } - if ((c == -1) && (offset == 0)) - { - return null; - } - return String.copyValueOf(buf, 0, offset); - } + } + } + catch (IOException ioe) + { + ioe.printStackTrace(); + } + if ((c == -1) && (offset == 0)) { return null; } + return String.copyValueOf(buf, 0, offset); + } - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/test/org/apache/jetspeed/rewriter/TestNekoRewriter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/test/org/apache/jetspeed/rewriter/TestNekoRewriter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/test/org/apache/jetspeed/rewriter/TestNekoRewriter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,14 +22,13 @@ import java.io.IOException; import java.util.Arrays; -import org.apache.jetspeed.rewriter.html.neko.NekoParserAdaptor; -import org.apache.jetspeed.rewriter.rules.Ruleset; -import org.apache.jetspeed.rewriter.xml.SaxParserAdaptor; - import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; +import org.apache.jetspeed.rewriter.html.neko.NekoParserAdaptor; +import org.apache.jetspeed.rewriter.rules.Ruleset; +import org.apache.jetspeed.rewriter.xml.SaxParserAdaptor; /** * TestNekoRewriter @@ -65,7 +64,7 @@ public static void main(String args[]) { junit.awtui.TestRunner.main(new String[] - { TestNekoRewriter.class.getName()}); + {TestNekoRewriter.class.getName()}); } public static Test suite() @@ -73,74 +72,45 @@ // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestNekoRewriter.class); } - - + // DOMParser example - - /* BOZO - public void testDOM() throws Exception - { - System.out.println( "testing...DOM" ) ; + /* + * BOZO + * + * public void testDOM() throws Exception { System.out.println( + * "testing...DOM" ) ; // parse something and echo the DOM tree String + * target = "http://www.google.com" ; System.out.println( "Parsing: " + + * target ) ; + * + * DOMParser parser = new DOMParser() ; parser.parse( target ) ; + * System.out.println( "parse() result..." ) ; print( parser.getDocument(), "" ) ; } + * + * void print( Node node, String indent ) { + * System.out.println(indent+node.getClass().getName()); Node child = + * node.getFirstChild(); while (child != null) { print(child, indent+" "); + * child = child.getNextSibling(); } } + */ - // parse something and echo the DOM tree - String target = "http://www.google.com" ; - System.out.println( "Parsing: " + target ) ; - - DOMParser parser = new DOMParser() ; - parser.parse( target ) ; - System.out.println( "parse() result..." ) ; - print( parser.getDocument(), "" ) ; - } - - void print( Node node, String indent ) - { - System.out.println(indent+node.getClass().getName()); - Node child = node.getFirstChild(); - while (child != null) { - print(child, indent+" "); - child = child.getNextSibling(); - } - } - */ - - // SAXParser example - - /* BOZO + /* + * BOZO + * + * public void testSAX() throws Exception { System.out.println( + * "testing...SAX" ) ; // parse something to stdout String target = + * "http://www.google.com" ; System.out.println( "Parsing: " + target ) ; + * + * SAXParser parser = new SAXParser() ; // create pipeline filters + * org.cyberneko.html.filters.Writer writer = new + * org.cyberneko.html.filters.Writer(); Purifier purifier = new Purifier() ; // + * setup filter chain XMLDocumentFilter[] filters = { purifier, writer, }; + * + * parser.setProperty("http://cyberneko.org/html/properties/filters", + * filters); // parse documents XMLInputSource source = new + * XMLInputSource(null, target, null); parser.parse(source); } + */ - public void testSAX() throws Exception - { - System.out.println( "testing...SAX" ) ; - - // parse something to stdout - String target = "http://www.google.com" ; - System.out.println( "Parsing: " + target ) ; - - SAXParser parser = new SAXParser() ; - - // create pipeline filters - org.cyberneko.html.filters.Writer writer = new org.cyberneko.html.filters.Writer(); - Purifier purifier = new Purifier() ; - - // setup filter chain - XMLDocumentFilter[] filters = { - purifier, - writer, - }; - - parser.setProperty("http://cyberneko.org/html/properties/filters", filters); - - // parse documents - XMLInputSource source = new XMLInputSource(null, target, null); - parser.parse(source); - } - */ - - - // NekoParserAdapter test - public void testNekoParserAdaptor() throws Exception { RewriterController controller = getController(); @@ -150,7 +120,7 @@ assertNotNull("ruleset is null", ruleset); RulesetRewriter rewriter = controller.createRewriter(ruleset); assertNotNull("ruleset rewriter is null", rewriter); - + FileReader htmlReader = getTestReader("test-001.html"); FileWriter htmlWriter = getTestWriter("test-002-output.html"); @@ -159,27 +129,27 @@ rewriter.rewrite(adaptor, htmlReader, htmlWriter); htmlReader.close(); } - + private RewriterController getController() throws Exception { - Class[] rewriterClasses = new Class[]{ RulesetRewriterImpl.class, RulesetRewriterImpl.class}; - - Class[] adaptorClasses = new Class[]{ NekoParserAdaptor.class, SaxParserAdaptor.class}; - return new JetspeedRewriterController("test/WEB-INF/conf/rewriter-rules-mapping.xml", Arrays.asList(rewriterClasses), Arrays.asList(adaptorClasses)); + Class[] rewriterClasses = new Class[] + {RulesetRewriterImpl.class, RulesetRewriterImpl.class}; + + Class[] adaptorClasses = new Class[] + {NekoParserAdaptor.class, SaxParserAdaptor.class}; + return new JetspeedRewriterController( + "test/WEB-INF/conf/rewriter-rules-mapping.xml", Arrays + .asList(rewriterClasses), Arrays.asList(adaptorClasses)); } /* - private Reader getRemoteReader(String uri) throws IOException - { - HttpClient client = new HttpClient(); - GetMethod get = new GetMethod(uri); - client.executeMethod(get); - BufferedInputStream bis = new BufferedInputStream(get.getResponseBodyAsStream()); - String encoding = get.getResponseCharSet(); - return new InputStreamReader(bis, encoding); - } - */ - + * private Reader getRemoteReader(String uri) throws IOException { + * HttpClient client = new HttpClient(); GetMethod get = new GetMethod(uri); + * client.executeMethod(get); BufferedInputStream bis = new + * BufferedInputStream(get.getResponseBodyAsStream()); String encoding = + * get.getResponseCharSet(); return new InputStreamReader(bis, encoding); } + */ + /** * Gets a reader for a given filename in the test directory. * @@ -202,29 +172,24 @@ new File("target/test/rewriter").mkdirs(); return new FileWriter("target/test/rewriter/" + filename); } - - - /* BOZO - public void testNekoWebTarget() throws Exception - { - // parse something with the NekoParserAdaptor - String target = "http://www.google.com"; - - RewriterController controller = getController(); - FileReader rulesReader = getTestReader("test-remove-rules.xml"); - Ruleset ruleset = controller.loadRuleset(rulesReader); - rulesReader.close(); - assertNotNull("ruleset is null", ruleset); - RulesetRewriter rewriter = controller.createRewriter(ruleset); - assertNotNull("ruleset rewriter is null", rewriter); - java.io.Reader htmlReader = getRemoteReader(target); - java.io.Writer htmlWriter = new OutputStreamWriter(System.out); - - ParserAdaptor adaptor = controller.createParserAdaptor("text/html"); - rewriter.setBaseUrl("http://www.rewriter.com"); - rewriter.rewrite(adaptor, htmlReader, htmlWriter); - htmlReader.close(); - } - */ + /* + * BOZO public void testNekoWebTarget() throws Exception { // parse + * something with the NekoParserAdaptor String target = + * "http://www.google.com"; + * + * RewriterController controller = getController(); FileReader rulesReader = + * getTestReader("test-remove-rules.xml"); Ruleset ruleset = + * controller.loadRuleset(rulesReader); rulesReader.close(); + * assertNotNull("ruleset is null", ruleset); RulesetRewriter rewriter = + * controller.createRewriter(ruleset); assertNotNull("ruleset rewriter is + * null", rewriter); + * + * java.io.Reader htmlReader = getRemoteReader(target); java.io.Writer + * htmlWriter = new OutputStreamWriter(System.out); + * + * ParserAdaptor adaptor = controller.createParserAdaptor("text/html"); + * rewriter.setBaseUrl("http://www.rewriter.com"); rewriter.rewrite(adaptor, + * htmlReader, htmlWriter); htmlReader.close(); } + */ } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/test/org/apache/jetspeed/rewriter/TestRewriterController.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/test/org/apache/jetspeed/rewriter/TestRewriterController.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/test/org/apache/jetspeed/rewriter/TestRewriterController.java 2008-05-16 01:54:54 UTC (rev 940) @@ -75,7 +75,7 @@ public static void main(String args[]) { junit.awtui.TestRunner.main(new String[] - { TestRewriterController.class.getName()}); + {TestRewriterController.class.getName()}); } public static Test suite() @@ -91,7 +91,8 @@ Rewriter basic = component.createRewriter(); assertNotNull("basic rewriter is null", basic); - FileReader reader = new FileReader("test/rewriter/test-rewriter-rules.xml"); + FileReader reader = new FileReader( + "test/rewriter/test-rewriter-rules.xml"); Ruleset ruleset = component.loadRuleset(reader); assertNotNull("ruleset is null", ruleset); RulesetRewriter rewriter = component.createRewriter(ruleset); @@ -105,7 +106,8 @@ assertNotNull("template component is null", component); assertNotNull("rewriter component is null", component); - FileReader reader = new FileReader("test/rewriter/test-rewriter-rules.xml"); + FileReader reader = new FileReader( + "test/rewriter/test-rewriter-rules.xml"); Ruleset ruleset = component.loadRuleset(reader); assertNotNull("ruleset is null", ruleset); assertEquals("ruleset id", "test-set-101", ruleset.getId()); @@ -126,8 +128,10 @@ while (attributes.hasNext()) { Attribute attribute = (Attribute) attributes.next(); - assertTrue("attribute is not ACTION", attribute.getId().equals("ACTION")); - assertEquals("attribute rule not equal", attribute.getRule().getId(), "merge"); + assertTrue("attribute is not ACTION", attribute.getId() + .equals("ACTION")); + assertEquals("attribute rule not equal", attribute + .getRule().getId(), "merge"); } } else if (tag.getId().equalsIgnoreCase("INPUT")) @@ -137,8 +141,10 @@ while (attributes.hasNext()) { Attribute attribute = (Attribute) attributes.next(); - assertTrue("attribute is not SOURCE", attribute.getId().equals("SOURCE")); - assertEquals("attribute rule not equal", attribute.getRule().getId(), "test"); + assertTrue("attribute is not SOURCE", attribute.getId() + .equals("SOURCE")); + assertEquals("attribute rule not equal", attribute + .getRule().getId(), "test"); } } @@ -149,8 +155,10 @@ while (attributes.hasNext()) { Attribute attribute = (Attribute) attributes.next(); - assertTrue("attribute is not HREF", attribute.getId().equals("HREF")); - assertEquals("attribute rule not equal", attribute.getRule().getId(), "merge"); + assertTrue("attribute is not HREF", attribute.getId() + .equals("HREF")); + assertEquals("attribute rule not equal", attribute + .getRule().getId(), "merge"); } } else if (tag.getId().equalsIgnoreCase("HEAD")) @@ -201,7 +209,8 @@ assertNotNull("rewriter component is null", component); - FileReader reader = new FileReader("test/rewriter/test-remove-rules.xml"); + FileReader reader = new FileReader( + "test/rewriter/test-remove-rules.xml"); Ruleset ruleset = component.loadRuleset(reader); reader.close(); @@ -220,24 +229,37 @@ htmlReader.close(); // validate result - FileReader testReader = new FileReader("target/test/rewriter/test-001-output.html"); + FileReader testReader = new FileReader( + "target/test/rewriter/test-001-output.html"); UnitTestRewriter testRewriter = new UnitTestRewriter(); - testRewriter.parse(component.createParserAdaptor("text/html"), testReader); - assertTrue("1st rewritten anchor: " + testRewriter.getAnchorValue("1"), testRewriter.getAnchorValue("1") - .equals("http://www.bluesunrise.com/suffix")); - assertTrue("2nd rewritten anchor: " + testRewriter.getAnchorValue("2"), testRewriter.getAnchorValue("2") - .equals("http://www.rewriter.com/stuff/junk/stuffedjunk.html/suffix")); - assertTrue("3rd rewritten anchor: " + testRewriter.getAnchorValue("3"), testRewriter.getAnchorValue("3") - .equals("http://www.rewriter.com/stuff/junk/stuffedjunk.html/suffix")); - assertTrue("4th rewritten anchor: " + testRewriter.getAnchorValue("4"), testRewriter.getAnchorValue("4") - .equals("javascript:whatever()")); - assertTrue("5th rewritten anchor: " + testRewriter.getAnchorValue("5"), testRewriter.getAnchorValue("5") - .equals("mailto:david ¡÷ bluesunrise.com")); - assertTrue("6th rewritten anchor: " + testRewriter.getAnchorValue("6"), testRewriter.getAnchorValue("6") - .equals("#INTERNAL")); + testRewriter.parse(component.createParserAdaptor("text/html"), + testReader); + assertTrue("1st rewritten anchor: " + testRewriter.getAnchorValue("1"), + testRewriter.getAnchorValue("1").equals( + "http://www.bluesunrise.com/suffix")); + assertTrue( + "2nd rewritten anchor: " + testRewriter.getAnchorValue("2"), + testRewriter + .getAnchorValue("2") + .equals( + "http://www.rewriter.com/stuff/junk/stuffedjunk.html/suffix")); + assertTrue( + "3rd rewritten anchor: " + testRewriter.getAnchorValue("3"), + testRewriter + .getAnchorValue("3") + .equals( + "http://www.rewriter.com/stuff/junk/stuffedjunk.html/suffix")); + assertTrue("4th rewritten anchor: " + testRewriter.getAnchorValue("4"), + testRewriter.getAnchorValue("4") + .equals("javascript:whatever()")); + assertTrue("5th rewritten anchor: " + testRewriter.getAnchorValue("5"), + testRewriter.getAnchorValue("5").equals( + "mailto:david ¡÷ bluesunrise.com")); + assertTrue("6th rewritten anchor: " + testRewriter.getAnchorValue("6"), + testRewriter.getAnchorValue("6").equals("#INTERNAL")); - assertTrue("Paragraph text: " + testRewriter.getParagraph(), testRewriter.getParagraph().equals( - "This is a test")); + assertTrue("Paragraph text: " + testRewriter.getParagraph(), + testRewriter.getParagraph().equals("This is a test")); } /** @@ -252,21 +274,21 @@ return new FileWriter("target/test/rewriter/" + filename); } - private RewriterController getController() throws Exception { Class[] rewriterClasses = new Class[] - { RulesetRewriterImpl.class, RulesetRewriterImpl.class}; - - //Class[] rewriterClasses = new Class[] - // { WebContentRewriter.class, WebContentRewriter.class}; - + {RulesetRewriterImpl.class, RulesetRewriterImpl.class}; + + // Class[] rewriterClasses = new Class[] + // { WebContentRewriter.class, WebContentRewriter.class}; + Class[] adaptorClasses = new Class[] - { SwingParserAdaptor.class, SaxParserAdaptor.class}; - return new JetspeedRewriterController("test/WEB-INF/conf/rewriter-rules-mapping.xml", Arrays - .asList(rewriterClasses), Arrays.asList(adaptorClasses)); + {SwingParserAdaptor.class, SaxParserAdaptor.class}; + return new JetspeedRewriterController( + "test/WEB-INF/conf/rewriter-rules-mapping.xml", Arrays + .asList(rewriterClasses), Arrays.asList(adaptorClasses)); } - + public void XXXtestExternalRewriting() throws Exception { RewriterController component = getController(); @@ -274,7 +296,8 @@ assertNotNull("rewriter component is null", component); - Reader reader = new FileReader("test/rewriter/default-rewriter-rules.xml"); + Reader reader = new FileReader( + "test/rewriter/default-rewriter-rules.xml"); Ruleset ruleset = component.loadRuleset(reader); reader.close(); @@ -288,10 +311,10 @@ FileWriter htmlWriter = getTestWriter("test-002-output.html"); ParserAdaptor adaptor = component.createParserAdaptor("text/html"); - + URL baseURL = new URL(source); - String baseurl = baseURL.getProtocol() + "://" + baseURL.getHost(); - + String baseurl = baseURL.getProtocol() + "://" + baseURL.getHost(); + rewriter.setBaseUrl(baseurl); rewriter.rewrite(adaptor, htmlReader, htmlWriter); htmlWriter.close(); @@ -306,5 +329,5 @@ InputStream is = get.getResponseBodyAsStream(); return new InputStreamReader(is); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/test/org/apache/jetspeed/rewriter/UnitTestRewriter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/test/org/apache/jetspeed/rewriter/UnitTestRewriter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/rewriter/src/test/org/apache/jetspeed/rewriter/UnitTestRewriter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,26 +21,29 @@ /** * TestRewriter - * + * * @author David Sean Taylor * @version $Id: UnitTestRewriter.java 516448 2007-03-09 16:25:47Z ate $ */ public class UnitTestRewriter extends BasicRewriter -{ +{ + private Map anchors = new HashMap(); + private String paragraph = null; + private boolean inParagraph = false; - + public String getAnchorValue(String name) { - return (String)anchors.get(name); + return (String) anchors.get(name); } - + public String getParagraph() { return paragraph; } - + public boolean enterStartTagEvent(String tag, MutableAttributes attrs) { if (tag.equalsIgnoreCase("a")) @@ -53,7 +56,7 @@ } return true; } - + public boolean enterText(char[] values, int param) { if (inParagraph) @@ -62,12 +65,11 @@ } return true; } - + public String exitEndTagEvent(String tag) { inParagraph = false; return ""; } - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/AbstractObjectHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/AbstractObjectHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/AbstractObjectHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + package org.apache.jetspeed.search; import java.util.HashSet; @@ -28,18 +28,19 @@ */ public abstract class AbstractObjectHandler implements ObjectHandler { + protected final HashSet fields = new HashSet(); + protected final HashSet keywords = new HashSet(); - - /** + /** * @see org.apache.jetspeed.services.search.ObjectHandler#getFields() */ public Set getFields() { - return fields; + return fields; } - + /** * @see org.apache.jetspeed.services.search.ObjectHandler#getKeywords() */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/BaseParsedObject.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/BaseParsedObject.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/BaseParsedObject.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,12 +16,12 @@ */ package org.apache.jetspeed.search; +import java.net.URL; import java.util.Map; -import java.net.URL; /** * Base parsed object. - * + * * @author Mark Orciuch * @version $Id: BaseParsedObject.java 516448 2007-03-09 16:25:47Z ate $ */ @@ -29,22 +29,33 @@ { private String key; + private String type; + private String title; + private String description; + private String content; + private String language; + private URL url; + private String[] keywords; + private Map keywordsMap; + private Map fields; + private float score; + private String className; /** * Returns parsed object key * - * @return + * @return */ public String getKey() { @@ -64,7 +75,7 @@ /** * Returns parsed object type * - * @return + * @return */ public String getType() { @@ -84,7 +95,7 @@ /** * Returns parsed object content * - * @return + * @return */ public String getContent() { @@ -104,7 +115,7 @@ /** * Returns parsed object description * - * @return + * @return */ public String getDescription() { @@ -124,7 +135,7 @@ /** * Returns parsed object keywords * - * @return + * @return */ public String[] getKeywords() { @@ -144,9 +155,9 @@ /** * Returns parsed object title * - * @return + * @return */ - public String getTitle() + public String getTitle() { return this.title; } @@ -164,7 +175,7 @@ /** * Returns parsed object language * - * @return + * @return */ public String getLanguage() { @@ -184,7 +195,7 @@ /** * Returns parsed object searchable fields * - * @return + * @return */ public Map getFields() { @@ -204,7 +215,7 @@ /** * Returns parsed object URL * - * @return + * @return */ public URL getURL() { @@ -230,11 +241,12 @@ { return this.score; } - + /** * Setter for property score. * - * @param score New value of property score. + * @param score + * New value of property score. */ public void setScore(float score) { @@ -254,14 +266,17 @@ /** * Setter for property className. * - * @param score New value of property className. + * @param score + * New value of property className. */ public void setClassName(String className) { - this.className = className; + this.className = className; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.ParsedObject#getKeywordsMap() */ public Map getKeywordsMap() @@ -269,13 +284,14 @@ return keywordsMap; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.ParsedObject#setKeywordsMap(java.util.Map) */ public void setKeywordsMap(Map keywordsMap) { - this.keywordsMap = keywordsMap; + this.keywordsMap = keywordsMap; } } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/HandlerFactoryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/HandlerFactoryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/HandlerFactoryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,7 +25,7 @@ /** * Search object handler factory - * + * * @author Mark Orciuch * @author Jeremy Ford * @@ -33,61 +33,64 @@ */ public class HandlerFactoryImpl implements HandlerFactory { + private final Map handlerCache = new HashMap(); + private Map classNameMapping = new HashMap(); - + public HandlerFactoryImpl(Map classNameMapping) { this.classNameMapping = classNameMapping; } - + public void addClassNameMapping(String className, String handlerClassName) { classNameMapping.put(className, handlerClassName); } - + /** * Returns parsed object handler for specific object * * @param obj - * @return + * @return */ public ObjectHandler getHandler(Object obj) throws Exception { return getHandler(obj.getClass().getName()); } - + /** - * Returns parsed object handler for specific object - * - * @param obj - * @return - */ + * Returns parsed object handler for specific object + * + * @param obj + * @return + */ public ObjectHandler getHandler(String className) throws Exception { ObjectHandler handler = null; - - if(handlerCache.containsKey(className)) + + if (handlerCache.containsKey(className)) { - handler = (ObjectHandler)handlerCache.get(className); + handler = (ObjectHandler) handlerCache.get(className); } else { String handlerClass = (String) classNameMapping.get(className); - - if (handlerClass == null) - { - throw new Exception("No handler was found for document type: " + className); - } - - //ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - - //handler = (ObjectHandler) classLoader.loadClass(handlerClass).newInstance(); - handler = (ObjectHandler)Class.forName(handlerClass).newInstance(); + + if (handlerClass == null) { throw new Exception( + "No handler was found for document type: " + className); } + + // ClassLoader classLoader = + // Thread.currentThread().getContextClassLoader(); + + // handler = (ObjectHandler) + // classLoader.loadClass(handlerClass).newInstance(); + handler = (ObjectHandler) Class.forName(handlerClass).newInstance(); handlerCache.put(className, handler); } - //System.out.println("HandlerFactory: returning handler " + handler + " for " + obj); + // System.out.println("HandlerFactory: returning handler " + handler + " + // for " + obj); return handler; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/URLToDocHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/URLToDocHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/URLToDocHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,16 +34,17 @@ */ public class URLToDocHandler extends AbstractObjectHandler { + /** * Static initialization of the logger for this class - */ - //private static final JetspeedLogger logger = JetspeedLogFactoryService.getLogger(URLToDocHandler.class.getName()); - + */ + // private static final JetspeedLogger logger = + // JetspeedLogFactoryService.getLogger(URLToDocHandler.class.getName()); /** * Parses a specific object into a document suitable for index placement * * @param o - * @return + * @return */ public org.apache.jetspeed.search.ParsedObject parseObject(Object o) { @@ -51,7 +52,7 @@ if ((o instanceof URL) == false) { - //logger.error("URLToDocHandler: invalid object type: " + o); + // logger.error("URLToDocHandler: invalid object type: " + o); return null; } @@ -73,9 +74,10 @@ // execute the method. client.executeMethod(method); statusCode = method.getStatusCode(); - //if (logger.isDebugEnabled()) + // if (logger.isDebugEnabled()) { - //logger.debug("URL = " + pageToAdd.toString() + "Status code = " + statusCode); + // logger.debug("URL = " + pageToAdd.toString() + + // "Status code = " + statusCode); } } catch (HttpException e) @@ -98,15 +100,18 @@ } catch (Exception ioe) { - //logger.error("Getting content for " + pageToAdd.toString(), ioe); + // logger.error("Getting content for " + + // pageToAdd.toString(), ioe); } if (content != null) { try { - result.setKey(java.net.URLEncoder.encode(pageToAdd.toString(),"UTF-8")); - result.setType(org.apache.jetspeed.search.ParsedObject.OBJECT_TYPE_URL); + result.setKey(java.net.URLEncoder.encode(pageToAdd + .toString(), "UTF-8")); + result + .setType(org.apache.jetspeed.search.ParsedObject.OBJECT_TYPE_URL); // TODO: We should extract the tag here. result.setTitle(pageToAdd.toString()); result.setContent(content); @@ -114,12 +119,12 @@ result.setLanguage(""); result.setURL(pageToAdd); result.setClassName(o.getClass().getName()); - //logger.info("Parsed '" + pageToAdd.toString() + "'"); + // logger.info("Parsed '" + pageToAdd.toString() + "'"); } catch (Exception e) { e.printStackTrace(); - //logger.error("Adding document to index", e); + // logger.error("Adding document to index", e); } } } @@ -133,4 +138,3 @@ } } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/pam/PortletApplicationHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/pam/PortletApplicationHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/pam/PortletApplicationHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,50 +27,52 @@ import org.apache.jetspeed.search.ParsedObject; /** - * + * * @author <a href="mailto: jford ¡÷ apache.org">Jeremy Ford</a> */ public class PortletApplicationHandler extends AbstractObjectHandler { + private static final String KEY_PREFIX = "PortletApplication::"; + private static final String ID = "ID"; - + { - fields.add(ID); + fields.add(ID); } - /** + /** * @see org.apache.jetspeed.search.ObjectHandler#parseObject(java.lang.Object) */ public ParsedObject parseObject(Object o) { BaseParsedObject result = null; - - if(o instanceof MutablePortletApplication) + + if (o instanceof MutablePortletApplication) { result = new BaseParsedObject(); - MutablePortletApplication pa = (MutablePortletApplication) o; - - result.setDescription(pa.getDescription()); - result.setTitle(pa.getName()); - result.setKey(KEY_PREFIX + pa.getName()); - result.setType(ParsedObject.OBJECT_TYPE_PORTLET_APPLICATION); - result.setClassName(pa.getClass().getName()); - - MultiHashMap fieldMap = new MultiHashMap(); - fieldMap.put(ID, pa.getName()); - - Collection fields = pa.getMetadata().getFields(); - for (Iterator fieldIter = fields.iterator(); fieldIter.hasNext();) + MutablePortletApplication pa = (MutablePortletApplication) o; + + result.setDescription(pa.getDescription()); + result.setTitle(pa.getName()); + result.setKey(KEY_PREFIX + pa.getName()); + result.setType(ParsedObject.OBJECT_TYPE_PORTLET_APPLICATION); + result.setClassName(pa.getClass().getName()); + + MultiHashMap fieldMap = new MultiHashMap(); + fieldMap.put(ID, pa.getName()); + + Collection fields = pa.getMetadata().getFields(); + for (Iterator fieldIter = fields.iterator(); fieldIter.hasNext();) { LocalizedField field = (LocalizedField) fieldIter.next(); fieldMap.put(field.getName(), field.getValue()); - //this.fields.add(field.getName()); + // this.fields.add(field.getName()); } - - result.setFields(fieldMap); + + result.setFields(fieldMap); } - + return result; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/pam/PortletDefinitionHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/pam/PortletDefinitionHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/handlers/pam/PortletDefinitionHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,76 +37,87 @@ */ public class PortletDefinitionHandler extends AbstractObjectHandler { + private static final String KEY_PREFIX = "PortletDefinition::"; + private static final String ID = "ID"; + private static final String PORTLET_APPLICATION = "portlet_application"; - + { fields.add(ID); fields.add(PORTLET_APPLICATION); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.ObjectHandler#parseObject(java.lang.Object) */ public ParsedObject parseObject(Object o) { BaseParsedObject result = null; - if(o instanceof PortletDefinitionComposite) + if (o instanceof PortletDefinitionComposite) { result = new BaseParsedObject(); - PortletDefinitionComposite pd = (PortletDefinitionComposite)o; - - //need to get Locale here - String displayNameText = pd.getDisplayNameText(JetspeedLocale.getDefaultLocale()); + PortletDefinitionComposite pd = (PortletDefinitionComposite) o; + + // need to get Locale here + String displayNameText = pd.getDisplayNameText(JetspeedLocale + .getDefaultLocale()); result.setTitle(displayNameText); - - String description = pd.getDescriptionText(JetspeedLocale.getDefaultLocale()); + + String description = pd.getDescriptionText(JetspeedLocale + .getDefaultLocale()); result.setDescription(description); - + result.setClassName(pd.getClass().getName()); result.setKey(KEY_PREFIX + pd.getUniqueName()); result.setType(ParsedObject.OBJECT_TYPE_PORTLET); - - //TODO: this is common to PAs as well, possible refactor + + // TODO: this is common to PAs as well, possible refactor MultiHashMap fieldMap = new MultiHashMap(); fieldMap.put(ID, pd.getName()); - - PortletApplication pa = (PortletApplication)pd.getPortletApplicationDefinition(); - fieldMap.put(PORTLET_APPLICATION, pa.getName()); - + + PortletApplication pa = (PortletApplication) pd + .getPortletApplicationDefinition(); + fieldMap.put(PORTLET_APPLICATION, pa.getName()); + Collection mdFields = pd.getMetadata().getFields(); for (Iterator fieldIter = mdFields.iterator(); fieldIter.hasNext();) { - LocalizedField field = (LocalizedField) fieldIter.next(); + LocalizedField field = (LocalizedField) fieldIter.next(); fieldMap.put(field.getName(), field.getValue()); } - - //Handle descriptions + + // Handle descriptions Iterator descIter = pd.getDescriptionSet().iterator(); while (descIter.hasNext()) { Description desc = (Description) descIter.next(); - fieldMap.put(ParsedObject.FIELDNAME_DESCRIPTION, desc.getDescription()); + fieldMap.put(ParsedObject.FIELDNAME_DESCRIPTION, desc + .getDescription()); } - - //Handle keywords and titles + + // Handle keywords and titles Iterator displayNameIter = pd.getDisplayNameSet().iterator(); while (displayNameIter.hasNext()) { DisplayName displayName = (DisplayName) displayNameIter.next(); - fieldMap.put(ParsedObject.FIELDNAME_TITLE, displayName.getDisplayName()); + fieldMap.put(ParsedObject.FIELDNAME_TITLE, displayName + .getDisplayName()); } - + HashSet keywordSet = new HashSet(); - + Iterator langIter = pd.getLanguageSet().iterator(); while (langIter.hasNext()) { Language lang = (Language) langIter.next(); fieldMap.put(ParsedObject.FIELDNAME_TITLE, lang.getTitle()); - fieldMap.put(ParsedObject.FIELDNAME_TITLE, lang.getShortTitle()); - + fieldMap + .put(ParsedObject.FIELDNAME_TITLE, lang.getShortTitle()); + Iterator keywordIter = lang.getKeywords(); if (keywordIter != null) { @@ -117,9 +128,9 @@ } } } - + String[] temp = new String[keywordSet.size()]; - result.setKeywords((String[])keywordSet.toArray(temp)); + result.setKeywords((String[]) keywordSet.toArray(temp)); result.setFields(fieldMap); } return result; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/lucene/SearchEngineImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/lucene/SearchEngineImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/lucene/SearchEngineImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -52,28 +52,35 @@ /** * @author <a href="mailto: jford ¡÷ apache.org">Jeremy Ford</a> - * + * */ public class SearchEngineImpl implements SearchEngine { + protected final static Log log = LogFactory.getLog(SearchEngineImpl.class); + private File rootIndexDir = null; + private String analyzerClassName = null; + private boolean optimizeAfterUpdate = true; + private HandlerFactory handlerFactory; - + private static final int KEYWORD = 0; + private static final int TEXT = 1; - - public SearchEngineImpl(String indexRoot, String analyzerClassName, boolean optimzeAfterUpdate, HandlerFactory handlerFactory) - throws Exception + + public SearchEngineImpl(String indexRoot, String analyzerClassName, + boolean optimzeAfterUpdate, HandlerFactory handlerFactory) + throws Exception { - //assume it's full path for now + // assume it's full path for now rootIndexDir = new File(indexRoot); this.analyzerClassName = analyzerClassName; this.optimizeAfterUpdate = optimzeAfterUpdate; this.handlerFactory = handlerFactory; - + try { Searcher searcher = null; @@ -84,28 +91,35 @@ { if (rootIndexDir.exists()) { - log.error("Failed to open Portal Registry indexes in " + rootIndexDir.getPath(), e); + log.error("Failed to open Portal Registry indexes in " + + rootIndexDir.getPath(), e); } try { rootIndexDir.delete(); rootIndexDir.mkdirs(); - - IndexWriter indexWriter = new IndexWriter(rootIndexDir, newAnalyzer(), true); + + IndexWriter indexWriter = new IndexWriter(rootIndexDir, + newAnalyzer(), true); indexWriter.close(); indexWriter = null; - log.warn("Re-created Lucene Index in " + rootIndexDir.getPath()); + log + .warn("Re-created Lucene Index in " + + rootIndexDir.getPath()); } catch (Exception e1) { - String message = "Cannot RECREATE Portlet Registry indexes in " + rootIndexDir.getPath(); + String message = "Cannot RECREATE Portlet Registry indexes in " + + rootIndexDir.getPath(); log.error(message, e1); throw new Exception(message); } } } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.SearchEnging#add(java.lang.Object) */ public boolean add(Object o) @@ -116,13 +130,15 @@ return add(c); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.SearchEnging#add(java.util.Collection) */ public synchronized boolean add(Collection objects) { boolean result = false; - + IndexWriter indexWriter; try { @@ -130,12 +146,13 @@ } catch (IOException e) { - //logger.error("Error while creating index writer. Skipping add...", e); + // logger.error("Error while creating index writer. Skipping + // add...", e); return result; } Iterator it = objects.iterator(); - while (it.hasNext()) + while (it.hasNext()) { Object o = it.next(); // Look up appropriate handler @@ -146,7 +163,8 @@ } catch (Exception e) { - //logger.error("Failed to create hanlder for object " + o.getClass().getName()); + // logger.error("Failed to create hanlder for object " + + // o.getClass().getName()); continue; } @@ -158,54 +176,68 @@ // Populate document from the parsed object if (parsedObject.getKey() != null) - { - doc.add(new Field(ParsedObject.FIELDNAME_KEY, parsedObject.getKey(), Field.Store.YES, Field.Index.UN_TOKENIZED)); + { + doc.add(new Field(ParsedObject.FIELDNAME_KEY, parsedObject + .getKey(), Field.Store.YES, Field.Index.UN_TOKENIZED)); } if (parsedObject.getType() != null) { - doc.add(new Field(ParsedObject.FIELDNAME_TYPE, parsedObject.getType(), Field.Store.YES, Field.Index.TOKENIZED)); + doc.add(new Field(ParsedObject.FIELDNAME_TYPE, parsedObject + .getType(), Field.Store.YES, Field.Index.TOKENIZED)); } if (parsedObject.getTitle() != null) { - doc.add(new Field(ParsedObject.FIELDNAME_TITLE, parsedObject.getTitle(), Field.Store.YES, Field.Index.TOKENIZED)); + doc.add(new Field(ParsedObject.FIELDNAME_TITLE, parsedObject + .getTitle(), Field.Store.YES, Field.Index.TOKENIZED)); } if (parsedObject.getDescription() != null) { - doc.add(new Field(ParsedObject.FIELDNAME_DESCRIPTION, parsedObject.getDescription(), Field.Store.YES, Field.Index.TOKENIZED)); + doc.add(new Field(ParsedObject.FIELDNAME_DESCRIPTION, + parsedObject.getDescription(), Field.Store.YES, + Field.Index.TOKENIZED)); } if (parsedObject.getContent() != null) { - doc.add(new Field(ParsedObject.FIELDNAME_CONTENT, parsedObject.getContent(), Field.Store.YES, Field.Index.TOKENIZED)); + doc.add(new Field(ParsedObject.FIELDNAME_CONTENT, parsedObject + .getContent(), Field.Store.YES, Field.Index.TOKENIZED)); } if (parsedObject.getLanguage() != null) { - doc.add(new Field(ParsedObject.FIELDNAME_LANGUAGE, parsedObject.getLanguage(), Field.Store.YES, Field.Index.TOKENIZED)); + doc + .add(new Field(ParsedObject.FIELDNAME_LANGUAGE, + parsedObject.getLanguage(), Field.Store.YES, + Field.Index.TOKENIZED)); } if (parsedObject.getURL() != null) { - doc.add(new Field(ParsedObject.FIELDNAME_URL, parsedObject.getURL().toString(), Field.Store.YES, Field.Index.TOKENIZED)); + doc.add(new Field(ParsedObject.FIELDNAME_URL, parsedObject + .getURL().toString(), Field.Store.YES, + Field.Index.TOKENIZED)); } - if(parsedObject.getClassName() != null) + if (parsedObject.getClassName() != null) { - doc.add(new Field(ParsedObject.FIELDNAME_CLASSNAME, parsedObject.getClassName(), Field.Store.YES, Field.Index.TOKENIZED)); + doc.add(new Field(ParsedObject.FIELDNAME_CLASSNAME, + parsedObject.getClassName(), Field.Store.YES, + Field.Index.TOKENIZED)); } - + String[] keywordArray = parsedObject.getKeywords(); - if(keywordArray != null) + if (keywordArray != null) { - for(int i=0; i<keywordArray.length; ++i) - { - String keyword = keywordArray[i]; - doc.add(new Field(ParsedObject.FIELDNAME_KEYWORDS, keyword, Field.Store.YES, Field.Index.UN_TOKENIZED)); - } + for (int i = 0; i < keywordArray.length; ++i) + { + String keyword = keywordArray[i]; + doc.add(new Field(ParsedObject.FIELDNAME_KEYWORDS, keyword, + Field.Store.YES, Field.Index.UN_TOKENIZED)); + } } Map keywords = parsedObject.getKeywordsMap(); addFieldsToDocument(doc, keywords, KEYWORD); - + Map fields = parsedObject.getFields(); addFieldsToDocument(doc, fields, TEXT); - + // Add the document to search index try { @@ -213,23 +245,23 @@ } catch (IOException e) { - //logger.error("Error adding document to index.", e); + // logger.error("Error adding document to index.", e); } - //logger.debug("Index Document Count = " + indexWriter.docCount()); - //logger.info("Added '" + parsedObject.getTitle() + "' to index"); + // logger.debug("Index Document Count = " + indexWriter.docCount()); + // logger.info("Added '" + parsedObject.getTitle() + "' to index"); result = true; } try { - if(optimizeAfterUpdate) + if (optimizeAfterUpdate) { indexWriter.optimize(); } } catch (IOException e) { - //logger.error("Error while trying to optimize index."); + // logger.error("Error while trying to optimize index."); } finally { @@ -239,14 +271,16 @@ } catch (IOException e) { - //logger.error("Error while closing index writer.", e); + // logger.error("Error while closing index writer.", e); } } - + return result; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.SearchEnging#remove(java.lang.Object) */ public boolean remove(Object o) @@ -257,19 +291,21 @@ return remove(c); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.SearchEnging#remove(java.util.Collection) */ public synchronized boolean remove(Collection objects) { boolean result = false; - - try + + try { IndexReader indexReader = IndexReader.open(this.rootIndexDir); Iterator it = objects.iterator(); - while (it.hasNext()) + while (it.hasNext()) { Object o = it.next(); // Look up appropriate handler @@ -283,18 +319,22 @@ if (parsedObject.getKey() != null) { - term = new Term(ParsedObject.FIELDNAME_KEY, parsedObject.getKey()); + term = new Term(ParsedObject.FIELDNAME_KEY, parsedObject + .getKey()); // Remove the document from search index int rc = indexReader.deleteDocuments(term); - //logger.info("Attempted to delete '" + term.toString() + "' from index, documents deleted = " + rc); - //System.out.println("Attempted to delete '" + term.toString() + "' from index, documents deleted = " + rc); + // logger.info("Attempted to delete '" + term.toString() + + // "' from index, documents deleted = " + rc); + // System.out.println("Attempted to delete '" + + // term.toString() + "' from index, documents deleted = " + + // rc); result = rc > 0; } } indexReader.close(); - if(optimizeAfterUpdate) + if (optimizeAfterUpdate) { optimize(); } @@ -302,31 +342,35 @@ } catch (Exception e) { - //logger.error("Exception", e); + // logger.error("Exception", e); result = false; } return result; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.SearchEnging#update(java.lang.Object) */ public boolean update(Object o) { Collection c = new ArrayList(1); c.add(o); - + return update(c); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.SearchEnging#update(java.util.Collection) */ public synchronized boolean update(Collection objects) { boolean result = false; - + try { // Delete entries from index @@ -335,176 +379,189 @@ } catch (Throwable e) { - //logger.error("Exception", e); + // logger.error("Exception", e); } try { // Add entries to index - if(result) - { - add(objects); - result = true; - } + if (result) + { + add(objects); + result = true; + } } catch (Throwable e) { - //logger.error("Exception", e); + // logger.error("Exception", e); } - + return result; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.SearchEnging#optimize() */ public synchronized boolean optimize() { boolean result = false; - try - { - IndexWriter indexWriter = new IndexWriter(rootIndexDir, newAnalyzer(), false); + try + { + IndexWriter indexWriter = new IndexWriter(rootIndexDir, + newAnalyzer(), false); indexWriter.optimize(); indexWriter.close(); result = true; } catch (IOException e) { - //logger.error("Error while trying to optimize index."); + // logger.error("Error while trying to optimize index."); } return result; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.SearchEngine#search(java.lang.String) */ public SearchResults search(String queryString) - { + { Searcher searcher = null; Hits hits = null; - + try { searcher = new IndexSearcher(rootIndexDir.getPath()); } catch (IOException e) { - //logger.error("Failed to create index search using path " + rootDir.getPath()); + // logger.error("Failed to create index search using path " + + // rootDir.getPath()); return null; } - + Analyzer analyzer = newAnalyzer(); - - String[] searchFields = {ParsedObject.FIELDNAME_CONTENT, ParsedObject.FIELDNAME_DESCRIPTION, ParsedObject.FIELDNAME_FIELDS, - ParsedObject.FIELDNAME_KEY, ParsedObject.FIELDNAME_KEYWORDS, ParsedObject.FIELDNAME_LANGUAGE, - ParsedObject.FIELDNAME_SCORE, ParsedObject.FIELDNAME_TITLE, ParsedObject.FIELDNAME_TYPE, - ParsedObject.FIELDNAME_URL, ParsedObject.FIELDNAME_CLASSNAME}; - - Query query= null; + + String[] searchFields = + {ParsedObject.FIELDNAME_CONTENT, ParsedObject.FIELDNAME_DESCRIPTION, + ParsedObject.FIELDNAME_FIELDS, ParsedObject.FIELDNAME_KEY, + ParsedObject.FIELDNAME_KEYWORDS, + ParsedObject.FIELDNAME_LANGUAGE, ParsedObject.FIELDNAME_SCORE, + ParsedObject.FIELDNAME_TITLE, ParsedObject.FIELDNAME_TYPE, + ParsedObject.FIELDNAME_URL, ParsedObject.FIELDNAME_CLASSNAME}; + + Query query = null; try { - String s[] = new String[searchFields.length]; - for(int i=0;i<s.length;i++) - s[i] = queryString; + String s[] = new String[searchFields.length]; + for (int i = 0; i < s.length; i++) + s[i] = queryString; query = MultiFieldQueryParser.parse(s, searchFields, analyzer); -// Query query = QueryParser.parse(searchString, ParsedObject.FIELDNAME_CONTENT, analyzer); + // Query query = QueryParser.parse(searchString, + // ParsedObject.FIELDNAME_CONTENT, analyzer); } catch (ParseException e) { - //logger.info("Failed to parse query " + query); + // logger.info("Failed to parse query " + query); return null; } - + try { hits = searcher.search(query); } catch (IOException e) { - //logger.error("Error while peforming search.", e); - return null; + // logger.error("Error while peforming search.", e); + return null; } int hitNum = hits.length(); ArrayList resultList = new ArrayList(hitNum); - for(int i=0; i<hitNum; i++) + for (int i = 0; i < hitNum; i++) { ParsedObject result = new BaseParsedObject(); try { - Document doc = hits.doc(i); - - addFieldsToParsedObject(doc, result); - - result.setScore(hits.score(i)); - Field type = doc.getField(ParsedObject.FIELDNAME_TYPE); - if(type != null) - { - result.setType(type.stringValue()); - } - - Field key = doc.getField(ParsedObject.FIELDNAME_KEY); - if(key != null) - { - result.setKey(key.stringValue()); - } - - Field description = doc.getField(ParsedObject.FIELDNAME_DESCRIPTION); - if(description != null) - { - result.setDescription(description.stringValue()); - } - - Field title = doc.getField(ParsedObject.FIELDNAME_TITLE); - if(title != null) - { - result.setTitle(title.stringValue()); - } - - Field content = doc.getField(ParsedObject.FIELDNAME_CONTENT); - if(content != null) - { - result.setContent(content.stringValue()); - } - - Field language = doc.getField(ParsedObject.FIELDNAME_LANGUAGE); - if (language != null) - { - result.setLanguage(language.stringValue()); - } - - Field classname = doc.getField(ParsedObject.FIELDNAME_CLASSNAME); - if (classname != null) - { - result.setClassName(classname.stringValue()); - } - - Field url = doc.getField(ParsedObject.FIELDNAME_URL); - if (url != null) - { - result.setURL(new URL(url.stringValue())); - } - - Field[] keywords = doc.getFields(ParsedObject.FIELDNAME_KEYWORDS); - if(keywords != null) - { - String[] keywordArray = new String[keywords.length]; - - for(int j=0; j<keywords.length; j++) - { - Field keyword = keywords[j]; - keywordArray[j] = keyword.stringValue(); - } - - result.setKeywords(keywordArray); - } - - resultList.add(i, result); + Document doc = hits.doc(i); + + addFieldsToParsedObject(doc, result); + + result.setScore(hits.score(i)); + Field type = doc.getField(ParsedObject.FIELDNAME_TYPE); + if (type != null) + { + result.setType(type.stringValue()); + } + + Field key = doc.getField(ParsedObject.FIELDNAME_KEY); + if (key != null) + { + result.setKey(key.stringValue()); + } + + Field description = doc + .getField(ParsedObject.FIELDNAME_DESCRIPTION); + if (description != null) + { + result.setDescription(description.stringValue()); + } + + Field title = doc.getField(ParsedObject.FIELDNAME_TITLE); + if (title != null) + { + result.setTitle(title.stringValue()); + } + + Field content = doc.getField(ParsedObject.FIELDNAME_CONTENT); + if (content != null) + { + result.setContent(content.stringValue()); + } + + Field language = doc.getField(ParsedObject.FIELDNAME_LANGUAGE); + if (language != null) + { + result.setLanguage(language.stringValue()); + } + + Field classname = doc + .getField(ParsedObject.FIELDNAME_CLASSNAME); + if (classname != null) + { + result.setClassName(classname.stringValue()); + } + + Field url = doc.getField(ParsedObject.FIELDNAME_URL); + if (url != null) + { + result.setURL(new URL(url.stringValue())); + } + + Field[] keywords = doc + .getFields(ParsedObject.FIELDNAME_KEYWORDS); + if (keywords != null) + { + String[] keywordArray = new String[keywords.length]; + + for (int j = 0; j < keywords.length; j++) + { + Field keyword = keywords[j]; + keywordArray[j] = keyword.stringValue(); + } + + result.setKeywords(keywordArray); + } + + resultList.add(i, result); } - catch(IOException e) + catch (IOException e) { - //logger + // logger } } @@ -516,32 +573,41 @@ } catch (IOException ioe) { - //logger.error("Closing Searcher", ioe); + // logger.error("Closing Searcher", ioe); } } - + SearchResults results = new SearchResultsImpl(resultList); return results; } - - private Analyzer newAnalyzer() { + + private Analyzer newAnalyzer() + { Analyzer rval = null; - if(analyzerClassName != null) + if (analyzerClassName != null) { - try { - Class analyzerClass = Class.forName(analyzerClassName); - rval = (Analyzer) analyzerClass.newInstance(); - } catch(InstantiationException e) { - //logger.error("InstantiationException", e); - } catch(ClassNotFoundException e) { - //logger.error("ClassNotFoundException", e); - } catch(IllegalAccessException e) { - //logger.error("IllegalAccessException", e); - } + try + { + Class analyzerClass = Class.forName(analyzerClassName); + rval = (Analyzer) analyzerClass.newInstance(); + } + catch (InstantiationException e) + { + // logger.error("InstantiationException", e); + } + catch (ClassNotFoundException e) + { + // logger.error("ClassNotFoundException", e); + } + catch (IllegalAccessException e) + { + // logger.error("IllegalAccessException", e); + } } - if(rval == null) { + if (rval == null) + { rval = new StandardAnalyzer(); } @@ -550,53 +616,62 @@ private void addFieldsToDocument(Document doc, Map fields, int type) { - if(fields != null) + if (fields != null) { Iterator keyIter = fields.keySet().iterator(); - while(keyIter.hasNext()) + while (keyIter.hasNext()) { Object key = keyIter.next(); - if(key != null) + if (key != null) { Object values = fields.get(key); - if(values != null) + if (values != null) { - if(values instanceof Collection) + if (values instanceof Collection) { - Iterator valueIter = ((Collection)values).iterator(); - while(valueIter.hasNext()) + Iterator valueIter = ((Collection) values) + .iterator(); + while (valueIter.hasNext()) { Object value = valueIter.next(); - if(value != null) + if (value != null) { - if(type == TEXT) + if (type == TEXT) { - doc.add(new Field(key.toString(), value.toString(), Field.Store.YES, Field.Index.UN_TOKENIZED)); + doc.add(new Field(key.toString(), value + .toString(), Field.Store.YES, + Field.Index.UN_TOKENIZED)); } else { - doc.add(new Field(key.toString(), value.toString(), Field.Store.YES, Field.Index.UN_TOKENIZED)); + doc.add(new Field(key.toString(), value + .toString(), Field.Store.YES, + Field.Index.UN_TOKENIZED)); } } } } else { - if(type == TEXT) + if (type == TEXT) { - doc.add(new Field(key.toString(), values.toString(), Field.Store.YES, Field.Index.UN_TOKENIZED)); + doc.add(new Field(key.toString(), values + .toString(), Field.Store.YES, + Field.Index.UN_TOKENIZED)); } else { - doc.add(new Field(key.toString(), values.toString(), Field.Store.YES, Field.Index.UN_TOKENIZED)); + doc.add(new Field(key.toString(), values + .toString(), Field.Store.YES, + Field.Index.UN_TOKENIZED)); } } } } - } + } } } - + private void addFieldsToParsedObject(Document doc, ParsedObject o) { try @@ -604,45 +679,46 @@ MultiMap multiKeywords = new MultiHashMap(); MultiMap multiFields = new MultiHashMap(); HashMap fieldMap = new HashMap(); - - Field classNameField = doc.getField(ParsedObject.FIELDNAME_CLASSNAME); - if(classNameField != null) + + Field classNameField = doc + .getField(ParsedObject.FIELDNAME_CLASSNAME); + if (classNameField != null) { String className = classNameField.stringValue(); o.setClassName(className); ObjectHandler handler = handlerFactory.getHandler(className); - + Set fields = handler.getFields(); addFieldsToMap(doc, fields, multiFields); addFieldsToMap(doc, fields, fieldMap); - + Set keywords = handler.getKeywords(); addFieldsToMap(doc, keywords, multiKeywords); } - + o.setKeywordsMap(multiKeywords); o.setFields(multiFields); o.setFields(fieldMap); } - catch(Exception e) + catch (Exception e) { - //logger.error("Error trying to add fields to parsed object.", e); + // logger.error("Error trying to add fields to parsed object.", e); } } - + private void addFieldsToMap(Document doc, Set fieldNames, Map fields) { Iterator fieldIter = fieldNames.iterator(); - while(fieldIter.hasNext()) + while (fieldIter.hasNext()) { - String fieldName = (String)fieldIter.next(); + String fieldName = (String) fieldIter.next(); Field[] docFields = doc.getFields(fieldName); - if(docFields != null) + if (docFields != null) { - for(int i=0; i<docFields.length; i++) + for (int i = 0; i < docFields.length; i++) { Field field = docFields[i]; - if(field != null) + if (field != null) { String value = field.stringValue(); fields.put(fieldName, value); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/lucene/SearchResultsImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/lucene/SearchResultsImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/java/org/apache/jetspeed/search/lucene/SearchResultsImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,18 +24,21 @@ /** * @author <a href="mailto: jford ¡÷ apache.org">Jeremy Ford</a> - * + * */ public class SearchResultsImpl implements SearchResults { + List results = null; - + public SearchResultsImpl(List results) { this.results = results; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.SearchResults#size() */ public int size() @@ -43,7 +46,9 @@ return results.size(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.SearchResults#iterator() */ public Iterator iterator() @@ -51,15 +56,19 @@ return results.iterator(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.SearchResults#get(int) */ public ParsedObject get(int index) { - return (ParsedObject)results.get(index); + return (ParsedObject) results.get(index); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.SearchResults#getResults() */ public List getResults() @@ -67,7 +76,9 @@ return results; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.search.SearchResults#getResults(int, int) */ public List getResults(int fromIndex, int toIndex) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/test/org/apache/jetspeed/search/TestSearch.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/test/org/apache/jetspeed/search/TestSearch.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/search/src/test/org/apache/jetspeed/search/TestSearch.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,143 +22,154 @@ import java.util.HashMap; import java.util.Iterator; -import org.apache.jetspeed.search.ParsedObject; -import org.apache.jetspeed.search.SearchEngine; -import org.apache.jetspeed.search.SearchResults; -import org.apache.jetspeed.search.handlers.HandlerFactoryImpl; -import org.apache.jetspeed.search.lucene.SearchEngineImpl; - import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; +import org.apache.jetspeed.search.handlers.HandlerFactoryImpl; +import org.apache.jetspeed.search.lucene.SearchEngineImpl; + /** * @author jford - * + * */ public class TestSearch extends TestCase { - + private final static String INDEX_DIRECTORY = "./target/search_index"; private File indexRoot; + SearchEngine searchEngine; - + private URL jetspeedHomePage = null; - + public TestSearch(String name) { super(name); - - try { + + try + { jetspeedHomePage = new URL("http://portals.apache.org/jetspeed-1/"); - } catch (MalformedURLException e) { + } + catch (MalformedURLException e) + { e.printStackTrace(); } - + indexRoot = new File(INDEX_DIRECTORY); } - + /** * Start the tests. - * - * @param args the arguments. Not used + * + * @param args + * the arguments. Not used */ - public static void main(String args[]) + public static void main(String args[]) { - junit.awtui.TestRunner.main( new String[] { TestSearch.class.getName() } ); + junit.awtui.TestRunner.main(new String[] + {TestSearch.class.getName()}); } - + /** * Creates the test suite. - * - * @return a test suite (<code>TestSuite</code>) that includes all methods - * starting with "test" + * + * @return a test suite (<code>TestSuite</code>) that includes all + * methods starting with "test" */ - public static Test suite() + public static Test suite() { // All methods starting with "test" will be executed in the test suite. - return new TestSuite( TestSearch.class ); + return new TestSuite(TestSearch.class); } - + protected void setUp() throws Exception { super.setUp(); HashMap mapping = new HashMap(); - mapping.put("java.net.URL", "org.apache.jetspeed.search.handlers.URLToDocHandler"); - + mapping.put("java.net.URL", + "org.apache.jetspeed.search.handlers.URLToDocHandler"); + HandlerFactoryImpl hfi = new HandlerFactoryImpl(mapping); - - searchEngine = new SearchEngineImpl(indexRoot.getPath(), null, true, hfi); + + searchEngine = new SearchEngineImpl(indexRoot.getPath(), null, true, + hfi); } - + protected void tearDown() throws Exception { File[] indexFiles = indexRoot.listFiles(); - if(indexFiles != null) + if (indexFiles != null) { - for(int i=0; i<indexFiles.length; i++) - { - File file = indexFiles[i]; - file.delete(); - } + for (int i = 0; i < indexFiles.length; i++) + { + File file = indexFiles[i]; + file.delete(); + } } - + indexRoot.delete(); } - + public void testRemoveWebPage() throws Exception { - //System.out.println("search home = " + JetspeedResources.getString("services.SearchService.directory")); - - assertNotNull("Created URL to Jetspeed Home Page", jetspeedHomePage); - assertTrue("Removing non-existent index entry", searchEngine.remove(jetspeedHomePage) == false); + // System.out.println("search home = " + + // JetspeedResources.getString("services.SearchService.directory")); + + assertNotNull("Created URL to Jetspeed Home Page", jetspeedHomePage); + assertTrue("Removing non-existent index entry", searchEngine + .remove(jetspeedHomePage) == false); assertTrue("Adding to index", searchEngine.add(jetspeedHomePage)); assertTrue("Removing from index", searchEngine.remove(jetspeedHomePage)); } - + public void testPutWebPage() throws Exception { - //System.out.println("search home = " + JetspeedResources.getString("services.SearchService.directory")); - - assertNotNull("Created URL to Jetspeed Home Page", jetspeedHomePage); + // System.out.println("search home = " + + // JetspeedResources.getString("services.SearchService.directory")); + + assertNotNull("Created URL to Jetspeed Home Page", jetspeedHomePage); assertTrue("Adding to index", searchEngine.add(jetspeedHomePage)); - assertTrue("Adding to index", searchEngine.add(new URL("http://www.java.net"))); - assertTrue("Adding to index", searchEngine.add(new URL("http://portals.apache.org"))); + assertTrue("Adding to index", searchEngine.add(new URL( + "http://www.java.net"))); + assertTrue("Adding to index", searchEngine.add(new URL( + "http://portals.apache.org"))); } - + /** - * + * * @throws Exception */ public void testVerifyJetspeedSearch() throws Exception { - //because tear down deletes files, need to do add again + // because tear down deletes files, need to do add again testPutWebPage(); - - SearchResults results = searchEngine.search("YourResultsBelongToUs"); - //System.out.println("Query 'YourResultsBelongToUs' hits = " + results.size()); + + SearchResults results = searchEngine.search("YourResultsBelongToUs"); + // System.out.println("Query 'YourResultsBelongToUs' hits = " + + // results.size()); assertTrue(" Hit count == 0", results.size() == 0); Iterator resultIter = results.iterator(); while (resultIter.hasNext()) { ParsedObject result = (ParsedObject) resultIter.next(); - + System.out.println("Score = " + result.getScore()); System.out.println("title = " + result.getTitle()); System.out.println("summary = " + result.getDescription()); System.out.println("url = " + result.getURL()); } } - + public void testVerifyJetspeedSearch1() throws Exception { -// because tear down deletes files, need to do add again + // because tear down deletes files, need to do add again testPutWebPage(); - - SearchResults results = searchEngine.search("Jetspeed"); + + SearchResults results = searchEngine.search("Jetspeed"); assertTrue(" Hit count == 0", results.size() > 0); - + Iterator resultIter = results.iterator(); while (resultIter.hasNext()) { @@ -169,15 +180,15 @@ System.out.println("url = " + result.getURL()); } } - + public void testVerifyJetspeedSearch2() throws Exception { -// because tear down deletes files, need to do add again + // because tear down deletes files, need to do add again testPutWebPage(); - - SearchResults results = searchEngine.search("community"); + + SearchResults results = searchEngine.search("community"); assertTrue(" Hit count == 0", results.size() > 0); - + Iterator resultIter = results.iterator(); while (resultIter.hasNext()) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/PolicyWrapper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/PolicyWrapper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/PolicyWrapper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security; import java.io.Serializable; @@ -21,15 +21,16 @@ /** * <p> - * Simple wrapper for security policy providing the ability to add attribute on Policy and how they - * should be used by the application. + * Simple wrapper for security policy providing the ability to add attribute on + * Policy and how they should be used by the application. * </p> * * @author <a href="mailto:LeStrat_David ¡÷ emc.com">David Le Strat</a> */ public class PolicyWrapper implements Serializable { - /** The serial version uid. */ + + /** The serial version uid. */ private static final long serialVersionUID = 3386468724328997598L; /** The policy. */ @@ -46,7 +47,8 @@ * @param useAsPolicy * @param defaultPolicy */ - public PolicyWrapper(Policy policy, boolean useAsPolicy, boolean defaultPolicy) + public PolicyWrapper(Policy policy, boolean useAsPolicy, + boolean defaultPolicy) { this.policy = policy; this.useAsPolicy = useAsPolicy; @@ -62,7 +64,8 @@ } /** - * @param policy The policy to set. + * @param policy + * The policy to set. */ public void setPolicy(Policy policy) { @@ -78,7 +81,8 @@ } /** - * @param defaultPolicy The defaultPolicy to set. + * @param defaultPolicy + * The defaultPolicy to set. */ public void setDefaultPolicy(boolean defaultPolicy) { @@ -94,7 +98,8 @@ } /** - * @param useAsPolicy The useAsPolicy to set. + * @param useAsPolicy + * The useAsPolicy to set. */ public void setUseAsPolicy(boolean useAsPolicy) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/SecurityHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/SecurityHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/SecurityHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,8 +30,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.jetspeed.security.impl.GroupPrincipalImpl; import org.apache.jetspeed.security.impl.PrincipalsSet; -import org.apache.jetspeed.security.impl.GroupPrincipalImpl; import org.apache.jetspeed.security.impl.RolePrincipalImpl; import org.apache.jetspeed.security.impl.UserPrincipalImpl; @@ -45,16 +45,21 @@ */ public class SecurityHelper { + private static final Log log = LogFactory.getLog(SecurityHelper.class); /** * <p> - * Given a subject, finds the first principal of the given classe for that subject. If a - * principal of the given classe is not found, null is returned. + * Given a subject, finds the first principal of the given classe for that + * subject. If a principal of the given classe is not found, null is + * returned. * </p> * - * @param subject The subject supplying the principals. - * @param classe A class or interface derived from java.security.InternalPrincipal. + * @param subject + * The subject supplying the principals. + * @param classe + * A class or interface derived from + * java.security.InternalPrincipal. * @return The first principal matching a principal classe parameter. */ public static Principal getPrincipal(Subject subject, Class classe) @@ -62,30 +67,33 @@ Principal principal = null; Set principalList = subject.getPrincipals(); if (principalList != null) - { - Iterator principals = subject.getPrincipals().iterator(); - while (principals.hasNext()) - { - Principal p = (Principal) principals.next(); - if (classe.isInstance(p)) - { - principal = p; - break; - } - } + { + Iterator principals = subject.getPrincipals().iterator(); + while (principals.hasNext()) + { + Principal p = (Principal) principals.next(); + if (classe.isInstance(p)) + { + principal = p; + break; + } + } } return principal; } /** * <p> - * Given a subject, finds the first principal of the given classe for that subject. If a - * principal of the given classe is not found, then the first other principal is returned. If - * the list is empty, null is returned. + * Given a subject, finds the first principal of the given classe for that + * subject. If a principal of the given classe is not found, then the first + * other principal is returned. If the list is empty, null is returned. * </p> * - * @param subject The subject supplying the principals. - * @param classe A class or interface derived from java.security.InternalPrincipal. + * @param subject + * The subject supplying the principals. + * @param classe + * A class or interface derived from + * java.security.InternalPrincipal. * @return The first principal matching a principal classe parameter. */ public static Principal getBestPrincipal(Subject subject, Class classe) @@ -111,17 +119,20 @@ } return principal; } - + /** * <p> * Returns the first matching principal of a given type. * </p> * - * @param principals The array of pricinpals - * @param classe The class of Principal + * @param principals + * The array of pricinpals + * @param classe + * The class of Principal * @return The principal. */ - public static Principal getBestPrincipal(Principal[] principals, Class classe) + public static Principal getBestPrincipal(Principal[] principals, + Class classe) { Principal principal = null; @@ -146,11 +157,12 @@ /** * <p> - * Utility method used to retrieve the Preferences API absolute/full path from a given - * principal. + * Utility method used to retrieve the Preferences API absolute/full path + * from a given principal. * </p> * - * @param principal The principal. + * @param principal + * The principal. * @return The Preferences absolute/full path. */ public static String getPreferencesFullPath(Principal principal) @@ -158,15 +170,18 @@ if ((UserPrincipal.class).isInstance(principal)) { - return UserPrincipalImpl.getFullPathFromPrincipalName(principal.getName()); + return UserPrincipalImpl.getFullPathFromPrincipalName(principal + .getName()); } else if ((RolePrincipal.class).isInstance(principal)) { - return RolePrincipalImpl.getFullPathFromPrincipalName(principal.getName()); + return RolePrincipalImpl.getFullPathFromPrincipalName(principal + .getName()); } else if ((GroupPrincipal.class).isInstance(principal)) { - return GroupPrincipalImpl.getFullPathFromPrincipalName(principal.getName()); + return GroupPrincipalImpl.getFullPathFromPrincipalName(principal + .getName()); } else { @@ -179,7 +194,8 @@ * Utility method to create a subject. * </p> * - * @param principalName The user principal name. + * @param principalName + * The user principal name. * @return The subject. */ public static Subject createSubject(String principalName) @@ -192,13 +208,18 @@ /** * <p> - * Given a subject, finds all principals of the given classe for that subject. If no principals - * of the given class is not found, null is returned. + * Given a subject, finds all principals of the given classe for that + * subject. If no principals of the given class is not found, null is + * returned. * </p> * - * @param subject The subject supplying the principals. - * @param classe A class or interface derived from java.security.InternalPrincipal. - * @return A List of all principals of type Principal matching a principal classe parameter. + * @param subject + * The subject supplying the principals. + * @param classe + * A class or interface derived from + * java.security.InternalPrincipal. + * @return A List of all principals of type Principal matching a principal + * classe parameter. */ public static List getPrincipals(Subject subject, Class classe) { @@ -217,10 +238,12 @@ /** * <p> - * Given a subject, find the (first) PasswordCredential from the private credentials + * Given a subject, find the (first) PasswordCredential from the private + * credentials * </p> * - * @param subject The subject + * @param subject + * The subject * @return the PasswordCredential or null if not found. */ public static PasswordCredential getPasswordCredential(Subject subject) @@ -229,10 +252,7 @@ while (iter.hasNext()) { Object o = iter.next(); - if (o instanceof PasswordCredential) - { - return (PasswordCredential) o; - } + if (o instanceof PasswordCredential) { return (PasswordCredential) o; } } return null; } @@ -242,10 +262,13 @@ * Adds a collection of permsToAdd to a collection of existing permissions. * </p> * - * @param perms The existing permissions. - * @param permsToAdd The permissions to add. + * @param perms + * The existing permissions. + * @param permsToAdd + * The permissions to add. */ - public static void addPermissions(PermissionCollection perms, PermissionCollection permsToAdd) + public static void addPermissions(PermissionCollection perms, + PermissionCollection permsToAdd) { int permsAdded = 0; if (null != permsToAdd) @@ -258,8 +281,10 @@ perms.add(currPerm); if (log.isDebugEnabled()) { - log.debug("Adding the permission: [class, " + currPerm.getClass().getName() + "], " + "[name, " - + currPerm.getName() + "], " + "[actions, " + currPerm.getActions() + "]"); + log.debug("Adding the permission: [class, " + + currPerm.getClass().getName() + "], " + "[name, " + + currPerm.getName() + "], " + "[actions, " + + currPerm.getActions() + "]"); } } } @@ -268,25 +293,28 @@ log.debug("No permissions to add..."); } } - + public static Principal createPrincipalFromFullPath(String fullPath) { Principal principal = null; if (fullPath.startsWith(BasePrincipal.PREFS_ROLE_ROOT)) { - String name = RolePrincipalImpl.getPrincipalNameFromFullPath(fullPath); + String name = RolePrincipalImpl + .getPrincipalNameFromFullPath(fullPath); principal = new RolePrincipalImpl(name); } else if (fullPath.startsWith(BasePrincipal.PREFS_USER_ROOT)) { - String name = UserPrincipalImpl.getPrincipalNameFromFullPath(fullPath); + String name = UserPrincipalImpl + .getPrincipalNameFromFullPath(fullPath); principal = new UserPrincipalImpl(name); } else if (fullPath.startsWith(BasePrincipal.PREFS_GROUP_ROOT)) { - String name = GroupPrincipalImpl.getPrincipalNameFromFullPath(fullPath); + String name = GroupPrincipalImpl + .getPrincipalNameFromFullPath(fullPath); principal = new GroupPrincipalImpl(name); - + } return principal; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/SecurityPolicies.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/SecurityPolicies.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/SecurityPolicies.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security; import java.security.Policy; @@ -22,14 +22,16 @@ /** * <p> - * This class is used to hold the security that will be used when applying security policies. It - * uses a singleton pattern to maintain state of the policies configured in the consuming engine. + * This class is used to hold the security that will be used when applying + * security policies. It uses a singleton pattern to maintain state of the + * policies configured in the consuming engine. * </p> * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public class SecurityPolicies { + /** The singleton instance. */ private static SecurityPolicies instance = null; @@ -70,7 +72,8 @@ * Adds a policy to the list of policies to enforces. * </p> * - * @param wrappedPolicy The {@link PolicyWrapper} to add. + * @param wrappedPolicy + * The {@link PolicyWrapper} to add. */ public void addPolicy(PolicyWrapper wrappedPolicy) { @@ -127,7 +130,8 @@ * Removes a policy from the list of policies to enforces. * </p> * - * @param policy The {@link Policy} to add. + * @param policy + * The {@link Policy} to add. */ public void removePolicy(PolicyWrapper policy) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/activeauthentication/ActiveAuthenticationIdentityProviderImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/activeauthentication/ActiveAuthenticationIdentityProviderImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/activeauthentication/ActiveAuthenticationIdentityProviderImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.activeauthentication; import java.util.List; @@ -26,29 +26,36 @@ * AuthenticationCacheBeanImpl * </p> * <p> - * Short-lived cache implementation to bridge deficiencies in Java Login Modules and general Active Authentication patterns - * based on Java login modules. Caches Authentication information across redirects, requests, and threads. The life-time - * of this cached authentication information is meant to be very short lived. + * Short-lived cache implementation to bridge deficiencies in Java Login Modules + * and general Active Authentication patterns based on Java login modules. + * Caches Authentication information across redirects, requests, and threads. + * The life-time of this cached authentication information is meant to be very + * short lived. * </p> + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ - * + * */ -public class ActiveAuthenticationIdentityProviderImpl implements ActiveAuthenticationIdentityProvider +public class ActiveAuthenticationIdentityProviderImpl implements + ActiveAuthenticationIdentityProvider { + JetspeedCache cache; + List sessionAttributes; - - public ActiveAuthenticationIdentityProviderImpl(JetspeedCache cache, List sessionAttributes) + + public ActiveAuthenticationIdentityProviderImpl(JetspeedCache cache, + List sessionAttributes) { this.cache = cache; this.sessionAttributes = sessionAttributes; } - + public IdentityToken createIdentityToken(String seed) { String token = seed + "-" + String.valueOf(System.currentTimeMillis()); - return createToken(token); + return createToken(token); } public IdentityToken createIdentityToken() @@ -60,19 +67,19 @@ private IdentityToken createToken(String token) { IdentityToken identityToken = new IdentityTokenImpl(token); - CacheElement element = cache.createElement(token, identityToken); + CacheElement element = cache.createElement(token, identityToken); cache.put(element); - return identityToken; + return identityToken; } - + public void completeAuthenticationEvent(String token) { cache.remove(token); } - + public List getSessionAttributeNames() { return this.sessionAttributes; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/activeauthentication/IdentityTokenImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/activeauthentication/IdentityTokenImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/activeauthentication/IdentityTokenImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.activeauthentication; import java.io.Serializable; @@ -25,21 +25,23 @@ * <p> * IdentityTokenImpl * </p> - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ - * + * */ public class IdentityTokenImpl implements IdentityToken, Serializable { + private Map attributes = new HashMap(); + private String token; - + public IdentityTokenImpl(String uniqueToken) { - this.token = uniqueToken; + this.token = uniqueToken; } - + public Object getAttribute(String name) { return attributes.get(name); @@ -57,7 +59,6 @@ public void setAttribute(String name, Object value) { - if (value instanceof Serializable) - attributes.put(name, value); + if (value instanceof Serializable) attributes.put(name, value); } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AggregationHierarchyResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AggregationHierarchyResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AggregationHierarchyResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -43,14 +43,18 @@ * @version $Id: AggregationHierarchyResolver.java,v 1.2 2004/09/18 19:33:58 * dlestrat Exp $ */ -public class AggregationHierarchyResolver extends BaseHierarchyResolver implements HierarchyResolver +public class AggregationHierarchyResolver extends BaseHierarchyResolver + implements HierarchyResolver { + /** * @see org.apache.jetspeed.security.HierarchyResolver#resolve(Preferences) */ public String[] resolve(Preferences prefs) { - ArgUtil.notNull(new Object[] { prefs }, new String[] { "preferences" }, "resolve(java.util.prefs.Preferences)"); + ArgUtil.notNull(new Object[] + {prefs}, new String[] + {"preferences"}, "resolve(java.util.prefs.Preferences)"); return resolveChildren(prefs); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AuthenticationProviderImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AuthenticationProviderImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AuthenticationProviderImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,9 +20,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - +import org.apache.jetspeed.components.util.system.ClassLoaderSystemResourceUtilImpl; import org.apache.jetspeed.components.util.system.SystemResourceUtil; -import org.apache.jetspeed.components.util.system.ClassLoaderSystemResourceUtilImpl; import org.apache.jetspeed.security.AuthenticationProvider; import org.apache.jetspeed.security.spi.CredentialHandler; import org.apache.jetspeed.security.spi.UserSecurityHandler; @@ -35,7 +34,8 @@ { /** The logger. */ - private static final Log log = LogFactory.getLog(AuthenticationProviderImpl.class); + private static final Log log = LogFactory + .getLog(AuthenticationProviderImpl.class); /** The provider name. */ private String providerName; @@ -55,44 +55,58 @@ * handlers. * </p> * - * @param providerName The provider name. - * @param providerDescription The provider description. - * @param credHandler The credential handler. - * @param userSecurityHandler The user security handler. + * @param providerName + * The provider name. + * @param providerDescription + * The provider description. + * @param credHandler + * The credential handler. + * @param userSecurityHandler + * The user security handler. */ - public AuthenticationProviderImpl(String providerName, String providerDescription, CredentialHandler credHandler, + public AuthenticationProviderImpl(String providerName, + String providerDescription, CredentialHandler credHandler, UserSecurityHandler userSecurityHandler) { // The provider name. this.providerName = providerName; // The provider description. this.providerDescription = providerDescription; - + // The credential handler. this.credHandler = credHandler; // The user security handler. this.userSecurityHandler = userSecurityHandler; } - + /** * <p> * Constructor configuring the security service with the correct * <code>java.security.auth.login.config</code>. * </p> * - * @param providerName The provider name. - * @param providerDescription The provider description. - * @param loginConfig The login module config. - * @param credHandler The credential handler. - * @param userSecurityHandler The user security handler. + * @param providerName + * The provider name. + * @param providerDescription + * The provider description. + * @param loginConfig + * The login module config. + * @param credHandler + * The credential handler. + * @param userSecurityHandler + * The user security handler. */ - public AuthenticationProviderImpl(String providerName, String providerDescription, String loginConfig, - CredentialHandler credHandler, UserSecurityHandler userSecurityHandler) + public AuthenticationProviderImpl(String providerName, + String providerDescription, String loginConfig, + CredentialHandler credHandler, + UserSecurityHandler userSecurityHandler) { - this(providerName, providerDescription, credHandler, userSecurityHandler); - + this(providerName, providerDescription, credHandler, + userSecurityHandler); + ClassLoader cl = Thread.currentThread().getContextClassLoader(); - SystemResourceUtil resourceUtil = new ClassLoaderSystemResourceUtilImpl(cl); + SystemResourceUtil resourceUtil = new ClassLoaderSystemResourceUtilImpl( + cl); URL loginConfigUrl = null; // The login module config. try @@ -101,13 +115,17 @@ } catch (Exception e) { - throw new IllegalStateException("Could not locate the login config. Bad URL. " + e.toString()); + throw new IllegalStateException( + "Could not locate the login config. Bad URL. " + + e.toString()); } if (null != loginConfigUrl) { if (log.isDebugEnabled()) - log.debug("java.security.auth.login.config = " + loginConfigUrl.toString()); - System.setProperty("java.security.auth.login.config", loginConfigUrl.toString()); + log.debug("java.security.auth.login.config = " + + loginConfigUrl.toString()); + System.setProperty("java.security.auth.login.config", + loginConfigUrl.toString()); } } @@ -120,7 +138,8 @@ } /** - * @param providerDescription The providerDescription to set. + * @param providerDescription + * The providerDescription to set. */ public void setProviderDescription(String providerDescription) { @@ -136,7 +155,8 @@ } /** - * @param providerName The providerName to set. + * @param providerName + * The providerName to set. */ public void setProviderName(String providerName) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AuthenticationProviderProxyImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AuthenticationProviderProxyImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AuthenticationProviderProxyImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,7 +34,8 @@ * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat </a> */ -public class AuthenticationProviderProxyImpl implements AuthenticationProviderProxy +public class AuthenticationProviderProxyImpl implements + AuthenticationProviderProxy { /** The list of {@link AuthenticationProvider}. */ @@ -43,25 +44,28 @@ /** The default authentication provider name. */ private String defaultAuthenticationProvider = null; - /** * <p> * Constructor given a list of {@link AuthenticationProvider}. * </p> * - * @param authenticationProviders The list of {@link AuthenticationProvider}. - * @param defaultAuthenticationProvider The default authentication provider name. + * @param authenticationProviders + * The list of {@link AuthenticationProvider}. + * @param defaultAuthenticationProvider + * The default authentication provider name. */ - public AuthenticationProviderProxyImpl(List authenticationProviders, String defaultAuthenticationProvider) + public AuthenticationProviderProxyImpl(List authenticationProviders, + String defaultAuthenticationProvider) { this.authenticationProviders = authenticationProviders; this.defaultAuthenticationProvider = defaultAuthenticationProvider; } - - protected AuthenticationProvider getAuthenticationProviderByName(String providerName) + + protected AuthenticationProvider getAuthenticationProviderByName( + String providerName) { AuthenticationProvider provider = null; - + for (int i = 0; i < authenticationProviders.size(); i++) { provider = (AuthenticationProvider) authenticationProviders.get(i); @@ -76,7 +80,7 @@ } return provider; } - + /** * @see org.apache.jetspeed.security.AuthenticationProviderProxy#getDefaultAuthenticationProvider() */ @@ -84,8 +88,7 @@ { return this.defaultAuthenticationProvider; } - - + /** * @see org.apache.jetspeed.security.AuthenticationProviderProxy#getAuthenticationProvider(java.lang.String) */ @@ -93,29 +96,32 @@ { AuthenticationProvider authenticationProvider; String providerName = null; - + for (int i = 0; i < authenticationProviders.size(); i++) { - authenticationProvider = (AuthenticationProvider)authenticationProviders.get(i); - if (authenticationProvider.getUserSecurityHandler().isUserPrincipal(userName)) + authenticationProvider = (AuthenticationProvider) authenticationProviders + .get(i); + if (authenticationProvider.getUserSecurityHandler() + .isUserPrincipal(userName)) { providerName = authenticationProvider.getProviderName(); break; } } return providerName; - } - + } + /** * @see org.apache.jetspeed.security.spi.UserSecurityHandler#isUserPrincipal(java.lang.String) */ public boolean isUserPrincipal(String userName) { boolean exists = false; - + for (int i = 0; i < authenticationProviders.size(); i++) { - exists = ((AuthenticationProvider)authenticationProviders.get(i)).getUserSecurityHandler().isUserPrincipal(userName); + exists = ((AuthenticationProvider) authenticationProviders.get(i)) + .getUserSecurityHandler().isUserPrincipal(userName); if (exists) { break; @@ -123,9 +129,7 @@ } return exists; } - - - + /** * @see org.apache.jetspeed.security.spi.UserSecurityHandler#getUserPrincipal(java.lang.String) */ @@ -134,7 +138,9 @@ Principal userPrincipal = null; for (int i = 0; i < authenticationProviders.size(); i++) { - userPrincipal = ((AuthenticationProvider)authenticationProviders.get(i)).getUserSecurityHandler().getUserPrincipal(username); + userPrincipal = ((AuthenticationProvider) authenticationProviders + .get(i)).getUserSecurityHandler() + .getUserPrincipal(username); if (null != userPrincipal) { break; @@ -151,26 +157,34 @@ List userPrincipals = new LinkedList(); for (int i = 0; i < authenticationProviders.size(); i++) { - userPrincipals.addAll(((AuthenticationProvider)authenticationProviders.get(i)).getUserSecurityHandler().getUserPrincipals(filter)); + userPrincipals + .addAll(((AuthenticationProvider) authenticationProviders + .get(i)).getUserSecurityHandler() + .getUserPrincipals(filter)); } return userPrincipals; } /** - * @see org.apache.jetspeed.security.spi.UserSecurityHandler#getUserPrincipals(java.lang.String, java.lang.String) + * @see org.apache.jetspeed.security.spi.UserSecurityHandler#getUserPrincipals(java.lang.String, + * java.lang.String) */ - public List getUserPrincipals(String filter, String authenticationProvider) throws SecurityException + public List getUserPrincipals(String filter, String authenticationProvider) + throws SecurityException { AuthenticationProvider provider = getAuthenticationProviderByName(authenticationProvider); - if ( provider != null ) + if (provider != null) { List userPrincipals = new LinkedList(); - userPrincipals.addAll(provider.getUserSecurityHandler().getUserPrincipals(filter)); + userPrincipals.addAll(provider.getUserSecurityHandler() + .getUserPrincipals(filter)); return userPrincipals; } else { - throw new SecurityException(SecurityException.INVALID_AUTHENTICATION_PROVIDER.create(authenticationProvider)); + throw new SecurityException( + SecurityException.INVALID_AUTHENTICATION_PROVIDER + .create(authenticationProvider)); } } @@ -182,24 +196,29 @@ int count = 0; for (int i = 0; i < authenticationProviders.size(); i++) { - count += ((AuthenticationProvider)authenticationProviders.get(i)).getUserSecurityHandler().getUserCount(filter); + count += ((AuthenticationProvider) authenticationProviders.get(i)) + .getUserSecurityHandler().getUserCount(filter); } return count; } /** - * @see org.apache.jetspeed.security.spi.UserSecurityHandler#getUserCount(java.lang.String, java.lang.String) + * @see org.apache.jetspeed.security.spi.UserSecurityHandler#getUserCount(java.lang.String, + * java.lang.String) */ - public int getUserCount(String filter, String authenticationProvider) throws SecurityException + public int getUserCount(String filter, String authenticationProvider) + throws SecurityException { AuthenticationProvider provider = getAuthenticationProviderByName(authenticationProvider); - if ( provider != null ) + if (provider != null) { return provider.getUserSecurityHandler().getUserCount(filter); } else { - throw new SecurityException(SecurityException.INVALID_AUTHENTICATION_PROVIDER.create(authenticationProvider)); + throw new SecurityException( + SecurityException.INVALID_AUTHENTICATION_PROVIDER + .create(authenticationProvider)); } } @@ -207,26 +226,30 @@ * @see org.apache.jetspeed.security.AuthenticationProviderProxy#addUserPrincipal(org.apache.jetspeed.security.UserPrincipal, * java.lang.String) */ - public void addUserPrincipal(UserPrincipal userPrincipal, String authenticationProvider) throws SecurityException + public void addUserPrincipal(UserPrincipal userPrincipal, + String authenticationProvider) throws SecurityException { AuthenticationProvider provider = getAuthenticationProviderByName(authenticationProvider); - if ( provider != null ) + if (provider != null) { provider.getUserSecurityHandler().addUserPrincipal(userPrincipal); } else { - throw new SecurityException(SecurityException.INVALID_AUTHENTICATION_PROVIDER.create(authenticationProvider)); + throw new SecurityException( + SecurityException.INVALID_AUTHENTICATION_PROVIDER + .create(authenticationProvider)); } } /** * @see org.apache.jetspeed.security.spi.UserSecurityHandler#addUserPrincipal(org.apache.jetspeed.security.UserPrincipal) */ - public void addUserPrincipal(UserPrincipal userPrincipal) throws SecurityException + public void addUserPrincipal(UserPrincipal userPrincipal) + throws SecurityException { String providerName = getAuthenticationProvider(userPrincipal.getName()); - if ( providerName == null ) + if (providerName == null) { addUserPrincipal(userPrincipal, defaultAuthenticationProvider); } @@ -240,32 +263,38 @@ * @see org.apache.jetspeed.security.AuthenticationProviderProxy#updateUserPrincipal(org.apache.jetspeed.security.UserPrincipal, * java.lang.String) */ - public void updateUserPrincipal(UserPrincipal userPrincipal, String authenticationProvider) throws SecurityException + public void updateUserPrincipal(UserPrincipal userPrincipal, + String authenticationProvider) throws SecurityException { AuthenticationProvider provider = getAuthenticationProviderByName(authenticationProvider); - if ( provider != null ) + if (provider != null) { - provider.getUserSecurityHandler().updateUserPrincipal(userPrincipal); + provider.getUserSecurityHandler() + .updateUserPrincipal(userPrincipal); } else { - throw new SecurityException(SecurityException.INVALID_AUTHENTICATION_PROVIDER.create(authenticationProvider)); + throw new SecurityException( + SecurityException.INVALID_AUTHENTICATION_PROVIDER + .create(authenticationProvider)); } } /** * @see org.apache.jetspeed.security.spi.UserSecurityHandler#updateUserPrincipal(org.apache.jetspeed.security.UserPrincipal) */ - public void updateUserPrincipal(UserPrincipal userPrincipal) throws SecurityException + public void updateUserPrincipal(UserPrincipal userPrincipal) + throws SecurityException { String providerName = getAuthenticationProvider(userPrincipal.getName()); - if ( providerName != null ) + if (providerName != null) { updateUserPrincipal(userPrincipal, providerName); } else { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(userPrincipal.getName())); + throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST + .create(userPrincipal.getName())); } } @@ -273,26 +302,31 @@ * @see org.apache.jetspeed.security.AuthenticationProviderProxy#removeUserPrincipal(org.apache.jetspeed.security.UserPrincipal, * java.lang.String) */ - public void removeUserPrincipal(UserPrincipal userPrincipal, String authenticationProvider) throws SecurityException + public void removeUserPrincipal(UserPrincipal userPrincipal, + String authenticationProvider) throws SecurityException { AuthenticationProvider provider = getAuthenticationProviderByName(authenticationProvider); - if ( provider != null ) + if (provider != null) { - provider.getUserSecurityHandler().removeUserPrincipal(userPrincipal); + provider.getUserSecurityHandler() + .removeUserPrincipal(userPrincipal); } else { - throw new SecurityException(SecurityException.INVALID_AUTHENTICATION_PROVIDER.create(authenticationProvider)); + throw new SecurityException( + SecurityException.INVALID_AUTHENTICATION_PROVIDER + .create(authenticationProvider)); } } /** * @see org.apache.jetspeed.security.spi.UserSecurityHandler#removeUserPrincipal(org.apache.jetspeed.security.UserPrincipal) */ - public void removeUserPrincipal(UserPrincipal userPrincipal) throws SecurityException + public void removeUserPrincipal(UserPrincipal userPrincipal) + throws SecurityException { String providerName = getAuthenticationProvider(userPrincipal.getName()); - if ( providerName != null ) + if (providerName != null) { removeUserPrincipal(userPrincipal, providerName); } @@ -305,80 +339,94 @@ { Set publicCredentials = new HashSet(); String providerName = getAuthenticationProvider(username); - if ( providerName != null ) + if (providerName != null) { AuthenticationProvider provider = getAuthenticationProviderByName(providerName); - publicCredentials.addAll(provider.getCredentialHandler().getPublicCredentials(username)); + publicCredentials.addAll(provider.getCredentialHandler() + .getPublicCredentials(username)); } return publicCredentials; } /** - * @see org.apache.jetspeed.security.AuthenticationProviderProxy#setPassword(String, String, String, String) + * @see org.apache.jetspeed.security.AuthenticationProviderProxy#setPassword(String, + * String, String, String) */ - public void setPassword(String userName, String oldPassword, String newPassword, String authenticationProvider) throws SecurityException + public void setPassword(String userName, String oldPassword, + String newPassword, String authenticationProvider) + throws SecurityException { AuthenticationProvider provider = getAuthenticationProviderByName(authenticationProvider); - if ( provider != null ) + if (provider != null) { - provider.getCredentialHandler().setPassword(userName,oldPassword,newPassword); + provider.getCredentialHandler().setPassword(userName, oldPassword, + newPassword); } else { - throw new SecurityException(SecurityException.INVALID_AUTHENTICATION_PROVIDER.create(authenticationProvider)); + throw new SecurityException( + SecurityException.INVALID_AUTHENTICATION_PROVIDER + .create(authenticationProvider)); } } /** * @see org.apache.jetspeed.security.spi.CredentialHandler#setPassword(java.lang.String,java.lang.String,java.lang.String) */ - public void setPassword(String userName, String oldPassword, String newPassword) throws SecurityException + public void setPassword(String userName, String oldPassword, + String newPassword) throws SecurityException { String providerName = getAuthenticationProvider(userName); - if ( providerName != null ) + if (providerName != null) { setPassword(userName, oldPassword, newPassword, providerName); } else { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(userName)); + throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST + .create(userName)); } } - /** - * @see org.apache.jetspeed.security.AuthenticationProviderProxy#importPassword(String, String, String, String) + * @see org.apache.jetspeed.security.AuthenticationProviderProxy#importPassword(String, + * String, String, String) */ - public void importPassword(String userName, String newPassword, String authenticationProvider) throws SecurityException + public void importPassword(String userName, String newPassword, + String authenticationProvider) throws SecurityException { AuthenticationProvider provider = getAuthenticationProviderByName(authenticationProvider); - if ( provider != null ) + if (provider != null) { - provider.getCredentialHandler().importPassword(userName,newPassword); + provider.getCredentialHandler().importPassword(userName, + newPassword); } else { - throw new SecurityException(SecurityException.INVALID_AUTHENTICATION_PROVIDER.create(authenticationProvider)); + throw new SecurityException( + SecurityException.INVALID_AUTHENTICATION_PROVIDER + .create(authenticationProvider)); } } /** * @see org.apache.jetspeed.security.spi.CredentialHandler#importPassword(java.lang.String,java.lang.String,java.lang.String) */ - public void importPassword(String userName, String newPassword) throws SecurityException + public void importPassword(String userName, String newPassword) + throws SecurityException { String providerName = getAuthenticationProvider(userName); - if ( providerName != null ) + if (providerName != null) { importPassword(userName, newPassword, providerName); } else { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(userName)); + throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST + .create(userName)); } } - - + /** * @see org.apache.jetspeed.security.spi.CredentialHandler#getPrivateCredentials(java.lang.String) */ @@ -386,141 +434,173 @@ { Set privateCredentials = new HashSet(); String providerName = getAuthenticationProvider(username); - if ( providerName != null ) + if (providerName != null) { AuthenticationProvider provider = getAuthenticationProviderByName(providerName); - privateCredentials.addAll(provider.getCredentialHandler().getPrivateCredentials(username)); + privateCredentials.addAll(provider.getCredentialHandler() + .getPrivateCredentials(username)); } return privateCredentials; - } - + } + /** - * @see org.apache.jetspeed.security.AuthenticationProviderProxy#setPasswordEnabled(java.lang.String, boolean, java.lang.String) + * @see org.apache.jetspeed.security.AuthenticationProviderProxy#setPasswordEnabled(java.lang.String, + * boolean, java.lang.String) */ - public void setPasswordEnabled(String userName, boolean enabled, String authenticationProvider) - throws SecurityException + public void setPasswordEnabled(String userName, boolean enabled, + String authenticationProvider) throws SecurityException { AuthenticationProvider provider = getAuthenticationProviderByName(authenticationProvider); - if ( provider != null ) + if (provider != null) { - provider.getCredentialHandler().setPasswordEnabled(userName,enabled); + provider.getCredentialHandler().setPasswordEnabled(userName, + enabled); } else { - throw new SecurityException(SecurityException.INVALID_AUTHENTICATION_PROVIDER.create(authenticationProvider)); + throw new SecurityException( + SecurityException.INVALID_AUTHENTICATION_PROVIDER + .create(authenticationProvider)); } } /** - * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordEnabled(java.lang.String, boolean) + * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordEnabled(java.lang.String, + * boolean) */ - public void setPasswordEnabled(String userName, boolean enabled) throws SecurityException + public void setPasswordEnabled(String userName, boolean enabled) + throws SecurityException { String providerName = getAuthenticationProvider(userName); - if ( providerName != null ) + if (providerName != null) { setPasswordEnabled(userName, enabled, providerName); } else { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(userName)); + throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST + .create(userName)); } } /** - * @see org.apache.jetspeed.security.AuthenticationProviderProxy#setPasswordUpdateRequired(java.lang.String, boolean, java.lang.String) + * @see org.apache.jetspeed.security.AuthenticationProviderProxy#setPasswordUpdateRequired(java.lang.String, + * boolean, java.lang.String) */ - public void setPasswordUpdateRequired(String userName, boolean updateRequired, String authenticationProvider) + public void setPasswordUpdateRequired(String userName, + boolean updateRequired, String authenticationProvider) throws SecurityException { AuthenticationProvider provider = getAuthenticationProviderByName(authenticationProvider); - if ( provider != null ) + if (provider != null) { - provider.getCredentialHandler().setPasswordUpdateRequired(userName,updateRequired); + provider.getCredentialHandler().setPasswordUpdateRequired(userName, + updateRequired); } else { - throw new SecurityException(SecurityException.INVALID_AUTHENTICATION_PROVIDER.create(authenticationProvider)); + throw new SecurityException( + SecurityException.INVALID_AUTHENTICATION_PROVIDER + .create(authenticationProvider)); } } /** - * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordUpdateRequired(java.lang.String, boolean) + * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordUpdateRequired(java.lang.String, + * boolean) */ - public void setPasswordUpdateRequired(String userName, boolean updateRequired) throws SecurityException + public void setPasswordUpdateRequired(String userName, + boolean updateRequired) throws SecurityException { String providerName = getAuthenticationProvider(userName); - if ( providerName != null ) + if (providerName != null) { setPasswordUpdateRequired(userName, updateRequired, providerName); } else { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(userName)); + throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST + .create(userName)); } } /** - * @see org.apache.jetspeed.security.AuthenticationProviderProxy#setPasswordExpiration(java.lang.String, java.sql.Date, java.lang.String) + * @see org.apache.jetspeed.security.AuthenticationProviderProxy#setPasswordExpiration(java.lang.String, + * java.sql.Date, java.lang.String) */ - public void setPasswordExpiration(String userName, Date expirationDate, String authenticationProvider) throws SecurityException + public void setPasswordExpiration(String userName, Date expirationDate, + String authenticationProvider) throws SecurityException { AuthenticationProvider provider = getAuthenticationProviderByName(authenticationProvider); - if ( provider != null ) + if (provider != null) { - provider.getCredentialHandler().setPasswordExpiration(userName,expirationDate); + provider.getCredentialHandler().setPasswordExpiration(userName, + expirationDate); } else { - throw new SecurityException(SecurityException.INVALID_AUTHENTICATION_PROVIDER.create(authenticationProvider)); + throw new SecurityException( + SecurityException.INVALID_AUTHENTICATION_PROVIDER + .create(authenticationProvider)); } } /** - * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordExpiration(java.lang.String, java.sql.Date) + * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordExpiration(java.lang.String, + * java.sql.Date) */ - public void setPasswordExpiration(String userName, Date expirationDate) throws SecurityException + public void setPasswordExpiration(String userName, Date expirationDate) + throws SecurityException { String providerName = getAuthenticationProvider(userName); - if ( providerName != null ) + if (providerName != null) { setPasswordExpiration(userName, expirationDate, providerName); } else { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(userName)); + throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST + .create(userName)); } } /** - * @see org.apache.jetspeed.security.AuthenticationProviderProxy#authenticate(String, String, String) + * @see org.apache.jetspeed.security.AuthenticationProviderProxy#authenticate(String, + * String, String) */ - public boolean authenticate(String userName, String password, String authenticationProvider) throws SecurityException + public boolean authenticate(String userName, String password, + String authenticationProvider) throws SecurityException { AuthenticationProvider provider = getAuthenticationProviderByName(authenticationProvider); - if ( provider != null ) + if (provider != null) { - return provider.getCredentialHandler().authenticate(userName, password); + return provider.getCredentialHandler().authenticate(userName, + password); } else { - throw new SecurityException(SecurityException.INVALID_AUTHENTICATION_PROVIDER.create(authenticationProvider)); + throw new SecurityException( + SecurityException.INVALID_AUTHENTICATION_PROVIDER + .create(authenticationProvider)); } } /** - * @see org.apache.jetspeed.security.spi.CredentialHandler#authenticate(java.lang.String, java.lang.String) + * @see org.apache.jetspeed.security.spi.CredentialHandler#authenticate(java.lang.String, + * java.lang.String) */ - public boolean authenticate(String userName, String password) throws SecurityException + public boolean authenticate(String userName, String password) + throws SecurityException { String providerName = getAuthenticationProvider(userName); - if ( providerName != null ) + if (providerName != null) { return authenticate(userName, password, providerName); } else { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(userName)); + throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST + .create(userName)); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AuthorizationProviderImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AuthorizationProviderImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/AuthorizationProviderImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,12 +31,15 @@ /** * <p> - * Constructor for adding another policy to be enforced. This constructor makes the assumption - * that the input policy should be used as the primary policy. + * Constructor for adding another policy to be enforced. This constructor + * makes the assumption that the input policy should be used as the primary + * policy. * </p> * - * @param policy The policy to configure. - * @param useDefaultPolicy Whether to also use the default policy. + * @param policy + * The policy to configure. + * @param useDefaultPolicy + * Whether to also use the default policy. */ public AuthorizationProviderImpl(Policy policy, boolean useDefaultPolicy) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/BaseHierarchyResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/BaseHierarchyResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/BaseHierarchyResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.impl; import java.util.ArrayList; @@ -34,28 +34,34 @@ */ public class BaseHierarchyResolver { + /** The logger. */ - private static final Log log = LogFactory.getLog(BaseHierarchyResolver.class); - + private static final Log log = LogFactory + .getLog(BaseHierarchyResolver.class); + /** * @see org.apache.jetspeed.security.HierarchyResolver#resolveChildren(java.util.prefs.Preferences) */ public String[] resolveChildren(Preferences prefs) { - ArgUtil.notNull(new Object[] { prefs }, new String[] { "preferences" }, "resolveChildren(java.util.prefs.Preferences)"); + ArgUtil.notNull(new Object[] + {prefs}, new String[] + {"preferences"}, "resolveChildren(java.util.prefs.Preferences)"); List children = new ArrayList(); processPreferences(prefs, children); return (String[]) children.toArray(new String[0]); } - + /** * <p> * Recursively processes the preferences. * </p> * - * @param prefs The preferences. - * @param list The list to add the preferences to. + * @param prefs + * The preferences. + * @param list + * The list to add the preferences to. */ protected void processPreferences(Preferences prefs, List list) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/BasePrincipalImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/BasePrincipalImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/BasePrincipalImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,7 +27,7 @@ */ public abstract class BasePrincipalImpl implements BasePrincipal { - + /** The version uid. */ private static final long serialVersionUID = 5687385387290144541L; @@ -37,29 +37,34 @@ /** The full path. */ private final String fullPath; - /** is this principal enabled **/ + /** is this principal enabled * */ private boolean enabled = true; - - /** is this principal a mapping **/ + + /** is this principal a mapping * */ private boolean isMapping = false; - + /** * <p> * Principal constructor given a name and preferences root. * </p> * - * @param name The principal name. - * @param prefsRoot The preferences root node. + * @param name + * The principal name. + * @param prefsRoot + * The preferences root node. */ - public BasePrincipalImpl(String name, String prefsRoot, boolean hiearchicalNames) + public BasePrincipalImpl(String name, String prefsRoot, + boolean hiearchicalNames) { this(name, prefsRoot, hiearchicalNames, true, false); } - - public BasePrincipalImpl(String name, String prefsRoot, boolean hiearchicalNames, boolean isEnabled, boolean isMapping) + + public BasePrincipalImpl(String name, String prefsRoot, + boolean hiearchicalNames, boolean isEnabled, boolean isMapping) { this.name = name; - this.fullPath = getFullPathFromPrincipalName(name, prefsRoot, hiearchicalNames); + this.fullPath = getFullPathFromPrincipalName(name, prefsRoot, + hiearchicalNames); this.enabled = isEnabled; this.isMapping = isMapping; } @@ -105,24 +110,31 @@ * Gets the principal implementation full path from the principal name. * </p> * <p> - * Hierarchical principal names should follow: {principal}.{subprincipal}. "." is used as the - * separator for hierarchical elements. + * Hierarchical principal names should follow: {principal}.{subprincipal}. + * "." is used as the separator for hierarchical elements. * </p> * <p> - * The implementation path follow /PREFS_{PRINCIPAL}_ROOT/{principal}/{subprincipal}. + * The implementation path follow + * /PREFS_{PRINCIPAL}_ROOT/{principal}/{subprincipal}. * </p> * - * @param name The principal name. - * @param prefsRoot The preferences root node. - * @param hiearchicalNames indicator if hierarchy encoding (replacing '.' with '/') should be done + * @param name + * The principal name. + * @param prefsRoot + * The preferences root node. + * @param hiearchicalNames + * indicator if hierarchy encoding (replacing '.' with '/') + * should be done * @return The preferences full path / principal name. */ - public static String getFullPathFromPrincipalName(String name, String prefsRoot, boolean hiearchicalNames) + public static String getFullPathFromPrincipalName(String name, + String prefsRoot, boolean hiearchicalNames) { String fullPath = name; - if (null != name ) + if (null != name) { - fullPath = prefsRoot + (hiearchicalNames ? name.replace('.','/') : name ); + fullPath = prefsRoot + + (hiearchicalNames ? name.replace('.', '/') : name); } return fullPath; } @@ -132,42 +144,51 @@ * Gets the principal implementation full path from the principal name. * </p> * <p> - * Hierarchical principal names should follow: {principal}.{subprincipal}. "." is used as the - * separator for hierarchical elements. + * Hierarchical principal names should follow: {principal}.{subprincipal}. + * "." is used as the separator for hierarchical elements. * </p> * <p> - * The implementation path follow /PREFS_{PRINCIPAL}_ROOT/{principal}/{subprincipal}. + * The implementation path follow + * /PREFS_{PRINCIPAL}_ROOT/{principal}/{subprincipal}. * </p> * - * @param name The principal name. - * @param prefsRoot The preferences root node. + * @param name + * The principal name. + * @param prefsRoot + * The preferences root node. * @return The preferences full path / principal name. - */ + */ /** * <p> * Gets the principal name from the principal implementation full path. * </p> * <p> - * Hierarchical principal names should follow: {principal}.{subprincipal}. "." is used as the - * separator for hierarchical elements. + * Hierarchical principal names should follow: {principal}.{subprincipal}. + * "." is used as the separator for hierarchical elements. * </p> * <p> - * The implementation path follow /PREFS_{PRINCIPAL}_ROOT/{principal}/{subprincipal}. + * The implementation path follow + * /PREFS_{PRINCIPAL}_ROOT/{principal}/{subprincipal}. * </p> * - * @param fullPath The principal full path. - * @param prefsRoot The preferences root node. - * @param hiearchicalNames indicator if hierarchical decoding (replacing '/' with '.') should be done + * @param fullPath + * The principal full path. + * @param prefsRoot + * The preferences root node. + * @param hiearchicalNames + * indicator if hierarchical decoding (replacing '/' with '.') + * should be done * @return The principal name. */ - public static String getPrincipalNameFromFullPath(String fullPath, String prefsRoot, boolean hiearchicalNames) + public static String getPrincipalNameFromFullPath(String fullPath, + String prefsRoot, boolean hiearchicalNames) { String name = fullPath; if (null != name) { name = name.substring(prefsRoot.length(), name.length()); - if ( hiearchicalNames ) + if (hiearchicalNames) { name = name.replace('/', '.'); } @@ -180,23 +201,26 @@ * Gets the principal name from the principal implementation full path. * </p> * <p> - * Hierarchical principal names should follow: {principal}.{subprincipal}. "." is used as the - * separator for hierarchical elements. + * Hierarchical principal names should follow: {principal}.{subprincipal}. + * "." is used as the separator for hierarchical elements. * </p> * <p> - * The implementation path follow /PREFS_{PRINCIPAL}_ROOT/{principal}/{subprincipal}. + * The implementation path follow + * /PREFS_{PRINCIPAL}_ROOT/{principal}/{subprincipal}. * </p> * - * @param fullPath The principal full path. - * @param prefsRoot The preferences root node. + * @param fullPath + * The principal full path. + * @param prefsRoot + * The preferences root node. * @return The principal name. */ -// MOVED TO DERVICED CLASSES -// public static String getPrincipalNameFromFullPath(String fullPath, String prefsRoot) -// { -// return getPrincipalNameFromFullPath(fullPath, prefsRoot, true); -// } - + // MOVED TO DERVICED CLASSES + // public static String getPrincipalNameFromFullPath(String fullPath, String + // prefsRoot) + // { + // return getPrincipalNameFromFullPath(fullPath, prefsRoot, true); + // } /** * @see org.apache.jetspeed.security.BasePrincipal#isEnabled() */ @@ -212,10 +236,10 @@ { this.enabled = enabled; } - + public boolean isMapping() { return isMapping; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/DefaultLoginModule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/DefaultLoginModule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/DefaultLoginModule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,55 +37,104 @@ import org.apache.jetspeed.security.UserPrincipal; /** - * <p>LoginModule implementation that authenticates a user - * against a relational database. OJB based implementation.</p> - * <p>When a user is successfully authenticated, the user principal - * are added to the current subject.</p> - * <p>The LoginModule also recognizes the debug option.</p> - * <p>Configuration files should provide:</p> + * <p> + * LoginModule implementation that authenticates a user against a relational + * database. OJB based implementation. + * </p> + * <p> + * When a user is successfully authenticated, the user principal are added to + * the current subject. + * </p> + * <p> + * The LoginModule also recognizes the debug option. + * </p> + * <p> + * Configuration files should provide: + * </p> + * * <pre><code> * Jetspeed { * org.apache.jetspeed.security.impl.DefaultLoginModule required debug=true; * }; * </code></pre> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public class DefaultLoginModule implements LoginModule { - /** <p>LoginModule debug mode is turned off by default.</p> */ + /** + * <p> + * LoginModule debug mode is turned off by default. + * </p> + */ protected boolean debug; - /** <p>The authentication status.</p> */ + /** + * <p> + * The authentication status. + * </p> + */ protected boolean success; - /** <p>The commit status.</p> */ + /** + * <p> + * The commit status. + * </p> + */ protected boolean commitSuccess; - /** <p>The Subject to be authenticated.</p> */ + /** + * <p> + * The Subject to be authenticated. + * </p> + */ protected Subject subject; - /** <p>A CallbackHandler for communicating with the end user (prompting for usernames and passwords, for example).</p> */ + /** + * <p> + * A CallbackHandler for communicating with the end user (prompting for + * usernames and passwords, for example). + * </p> + */ protected CallbackHandler callbackHandler; - /** <p>State shared with other configured LoginModules.</p> */ + /** + * <p> + * State shared with other configured LoginModules. + * </p> + */ protected Map sharedState; - /** <p>Options specified in the login Configuration for this particular LoginModule.</p> */ + /** + * <p> + * Options specified in the login Configuration for this particular + * LoginModule. + * </p> + */ protected Map options; - /** <p>InternalUserPrincipal manager service.</p> */ + /** + * <p> + * InternalUserPrincipal manager service. + * </p> + */ protected UserManager ums; /** The portal user role. */ protected String portalUserRole; - /** <p>The user name.</p> */ + /** + * <p> + * The user name. + * </p> + */ protected String username; - /** - * <p>The default login module constructor.</p> + * <p> + * The default login module constructor. + * </p> */ public DefaultLoginModule() { @@ -101,13 +150,15 @@ username = null; } - /** * Create a new login module that uses the given user manager. - * @param userManager the user manager to use - * @param portalUserRole the portal user role to use + * + * @param userManager + * the user manager to use + * @param portalUserRole + * the portal user role to use */ - protected DefaultLoginModule (UserManager userManager, String portalUserRole) + protected DefaultLoginModule(UserManager userManager, String portalUserRole) { this.ums = userManager; this.portalUserRole = portalUserRole; @@ -116,11 +167,12 @@ commitSuccess = false; username = null; } - protected DefaultLoginModule (UserManager userManager) + + protected DefaultLoginModule(UserManager userManager) { this(userManager, LoginModuleProxy.DEFAULT_PORTAL_USER_ROLE_NAME); } - + /** * @see javax.security.auth.spi.LoginModule#abort() */ @@ -147,9 +199,9 @@ { this.ums = loginModuleProxy.getUserManager(); } - } + } } - + /** * @see javax.security.auth.spi.LoginModule#commit() */ @@ -157,14 +209,14 @@ { if (success) { - if (subject.isReadOnly()) - { - throw new LoginException("Subject is Readonly"); - } + if (subject.isReadOnly()) { throw new LoginException( + "Subject is Readonly"); } try { - // TODO We should get the user profile here and had it in cache so that we do not have to retrieve it again. - // TODO Ideally the User should be available from the session. Need discussion around this. + // TODO We should get the user profile here and had it in cache + // so that we do not have to retrieve it again. + // TODO Ideally the User should be available from the session. + // Need discussion around this. refreshProxy(); commitPrincipals(subject, ums.getUser(username)); @@ -192,31 +244,31 @@ */ public boolean login() throws LoginException { - if (callbackHandler == null) - { - throw new LoginException("Error: no CallbackHandler available " + "to garner authentication information from the user"); - } + if (callbackHandler == null) { throw new LoginException( + "Error: no CallbackHandler available " + + "to garner authentication information from the user"); } try { // Setup default callback handlers. - Callback[] callbacks = new Callback[] { new NameCallback("Username: "), new PasswordCallback("Password: ", false)}; + Callback[] callbacks = new Callback[] + {new NameCallback("Username: "), + new PasswordCallback("Password: ", false)}; callbackHandler.handle(callbacks); username = ((NameCallback) callbacks[0]).getName(); - String password = new String(((PasswordCallback) callbacks[1]).getPassword()); + String password = new String(((PasswordCallback) callbacks[1]) + .getPassword()); ((PasswordCallback) callbacks[1]).clearPassword(); - refreshProxy(); + refreshProxy(); success = ums.authenticate(this.username, password); callbacks[0] = null; callbacks[1] = null; - if (!success) - { - throw new FailedLoginException("Authentication failed: Password does not match"); - } + if (!success) { throw new FailedLoginException( + "Authentication failed: Password does not match"); } return (true); } @@ -247,9 +299,12 @@ } /** - * @see javax.security.auth.spi.LoginModule#initialize(javax.security.auth.Subject, javax.security.auth.callback.CallbackHandler, java.util.Map, java.util.Map) + * @see javax.security.auth.spi.LoginModule#initialize(javax.security.auth.Subject, + * javax.security.auth.callback.CallbackHandler, java.util.Map, + * java.util.Map) */ - public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) + public void initialize(Subject subject, CallbackHandler callbackHandler, + Map sharedState, Map options) { this.subject = subject; this.callbackHandler = callbackHandler; @@ -263,19 +318,21 @@ } } - protected Principal getUserPrincipal(User user) { - return SecurityHelper.getPrincipal(user.getSubject(),UserPrincipal.class); + return SecurityHelper.getPrincipal(user.getSubject(), + UserPrincipal.class); } - + protected List getUserRoles(User user) { - return SecurityHelper.getPrincipals(user.getSubject(),RolePrincipal.class); + return SecurityHelper.getPrincipals(user.getSubject(), + RolePrincipal.class); } - + /** * Default setup of the logged on Subject Principals for Tomcat + * * @param subject * @param user */ @@ -287,6 +344,6 @@ // add portal user role: used in web.xml authorization to // detect authenticated portal users - subject.getPrincipals().add(new RolePrincipalImpl(portalUserRole)); + subject.getPrincipals().add(new RolePrincipalImpl(portalUserRole)); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GeneralizationHierarchyResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GeneralizationHierarchyResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GeneralizationHierarchyResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -40,7 +40,8 @@ * @version $Id: GeneralizationHierarchyResolver.java,v 1.2 2004/09/18 19:33:58 * dlestrat Exp $ */ -public class GeneralizationHierarchyResolver extends BaseHierarchyResolver implements HierarchyResolver +public class GeneralizationHierarchyResolver extends BaseHierarchyResolver + implements HierarchyResolver { /** @@ -48,11 +49,14 @@ */ public String[] resolve(Preferences prefs) { - ArgUtil.notNull(new Object[] { prefs }, new String[] { "preferences" }, "resolve(java.util.prefs.Preferences)"); + ArgUtil.notNull(new Object[] + {prefs}, new String[] + {"preferences"}, "resolve(java.util.prefs.Preferences)"); List list = new ArrayList(); Preferences preferences = prefs; - while ((preferences.parent() != null) && (preferences.parent().parent() != null)) + while ((preferences.parent() != null) + && (preferences.parent().parent() != null)) { list.add(preferences.absolutePath()); preferences = preferences.parent(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GroupImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GroupImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GroupImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,22 +22,34 @@ import org.apache.jetspeed.security.Group; /** - * <p>A group made of a {@link org.apache.jetspeed.security.GroupPrincipal} and the user {@link Preferences}.</p> + * <p> + * A group made of a {@link org.apache.jetspeed.security.GroupPrincipal} and the + * user {@link Preferences}. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public class GroupImpl implements Group { + /** - * <p>Default constructor.</p> + * <p> + * Default constructor. + * </p> */ public GroupImpl() { } /** - * <p>{@link Group} constructor given a group principal and preferences.</p> - * @param groupPrincipal The group principal. - * @param preferences The preferences. + * <p> + * {@link Group} constructor given a group principal and preferences. + * </p> + * + * @param groupPrincipal + * The group principal. + * @param preferences + * The preferences. */ public GroupImpl(Principal groupPrincipal, Preferences preferences) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GroupManagerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GroupManagerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GroupManagerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -91,13 +91,13 @@ public void addGroup(String groupFullPathName) throws SecurityException { ArgUtil.notNull(new Object[] - { groupFullPathName}, new String[] - { "groupFullPathName"}, "addGroup(java.lang.String)"); + {groupFullPathName}, new String[] + {"groupFullPathName"}, "addGroup(java.lang.String)"); // Check if group already exists. - if (groupExists(groupFullPathName)) { - throw new SecurityException(SecurityException.GROUP_ALREADY_EXISTS.create(groupFullPathName)); - } + if (groupExists(groupFullPathName)) { throw new SecurityException( + SecurityException.GROUP_ALREADY_EXISTS + .create(groupFullPathName)); } GroupPrincipal groupPrincipal = new GroupPrincipalImpl( groupFullPathName); @@ -120,7 +120,8 @@ log.debug("Added group: " + fullPath); } } - } catch (SecurityException se) + } + catch (SecurityException se) { String msg = "Unable to create the role."; log.error(msg, se); @@ -129,7 +130,8 @@ try { preferences.removeNode(); - } catch (BackingStoreException bse) + } + catch (BackingStoreException bse) { bse.printStackTrace(); } @@ -143,8 +145,8 @@ public void removeGroup(String groupFullPathName) throws SecurityException { ArgUtil.notNull(new Object[] - { groupFullPathName}, new String[] - { "groupFullPathName"}, "removeGroup(java.lang.String)"); + {groupFullPathName}, new String[] + {"groupFullPathName"}, "removeGroup(java.lang.String)"); // Resolve the group hierarchy. Preferences prefs = Preferences.userRoot().node( @@ -160,30 +162,34 @@ .removeGroupPrincipal(new GroupPrincipalImpl( GroupPrincipalImpl .getPrincipalNameFromFullPath(groups[i]))); - } catch (SecurityException se) + } + catch (SecurityException se) { throw se; - } catch (Exception e) + } + catch (Exception e) { - KeyedMessage msg = - SecurityException.UNEXPECTED.create("GroupManager.removeGroup", - "GroupSecurityHandler.removeGroupPrincipal("+ - GroupPrincipalImpl.getPrincipalNameFromFullPath(groups[i])+")", - e.getMessage()); + KeyedMessage msg = SecurityException.UNEXPECTED + .create( + "GroupManager.removeGroup", + "GroupSecurityHandler.removeGroupPrincipal(" + + GroupPrincipalImpl + .getPrincipalNameFromFullPath(groups[i]) + + ")", e.getMessage()); log.error(msg, e); throw new SecurityException(msg, e); } // Remove preferences - Preferences groupPref = Preferences.userRoot().node( - groups[i]); + Preferences groupPref = Preferences.userRoot().node(groups[i]); try { groupPref.removeNode(); - } catch (BackingStoreException bse) + } + catch (BackingStoreException bse) { - KeyedMessage msg = - SecurityException.UNEXPECTED.create("Preferences.removeNode("+groups[i]+")", - bse.getMessage()); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "Preferences.removeNode(" + groups[i] + ")", bse + .getMessage()); log.error(msg, bse); throw new SecurityException(msg, bse); } @@ -196,8 +202,8 @@ public boolean groupExists(String groupFullPathName) { ArgUtil.notNull(new Object[] - { groupFullPathName}, new String[] - { "groupFullPathName"}, "groupExists(java.lang.String)"); + {groupFullPathName}, new String[] + {"groupFullPathName"}, "groupExists(java.lang.String)"); Principal principal = groupSecurityHandler .getGroupPrincipal(groupFullPathName); @@ -216,18 +222,17 @@ public Group getGroup(String groupFullPathName) throws SecurityException { ArgUtil.notNull(new Object[] - { groupFullPathName}, new String[] - { "groupFullPathName"}, "getGroup(java.lang.String)"); + {groupFullPathName}, new String[] + {"groupFullPathName"}, "getGroup(java.lang.String)"); String fullPath = GroupPrincipalImpl .getFullPathFromPrincipalName(groupFullPathName); Principal groupPrincipal = groupSecurityHandler .getGroupPrincipal(groupFullPathName); - if (null == groupPrincipal) { - throw new SecurityException( - SecurityException.GROUP_DOES_NOT_EXIST.create(groupFullPathName)); - } + if (null == groupPrincipal) { throw new SecurityException( + SecurityException.GROUP_DOES_NOT_EXIST + .create(groupFullPathName)); } Preferences preferences = Preferences.userRoot().node(fullPath); Group group = new GroupImpl(groupPrincipal, preferences); return group; @@ -240,8 +245,8 @@ throws SecurityException { ArgUtil.notNull(new Object[] - { username}, new String[] - { "username"}, "getGroupsForUser(java.lang.String)"); + {username}, new String[] + {"username"}, "getGroupsForUser(java.lang.String)"); Collection groups = new ArrayList(); @@ -267,8 +272,8 @@ throws SecurityException { ArgUtil.notNull(new Object[] - { roleFullPathName}, new String[] - { "roleFullPathName"}, "getGroupsInRole(java.lang.String)"); + {roleFullPathName}, new String[] + {"roleFullPathName"}, "getGroupsInRole(java.lang.String)"); Collection groups = new ArrayList(); @@ -295,26 +300,28 @@ throws SecurityException { ArgUtil.notNull(new Object[] - { username, groupFullPathName}, new String[] - { "username", "groupFullPathName"}, + {username, groupFullPathName}, new String[] + {"username", "groupFullPathName"}, "addUserToGroup(java.lang.String, java.lang.String)"); // Get the group principal to add to user. - GroupPrincipal groupPrincipal = groupSecurityHandler.getGroupPrincipal(groupFullPathName); - if (null == groupPrincipal) { - throw new SecurityException(SecurityException.GROUP_DOES_NOT_EXIST.create(groupFullPathName)); - } + GroupPrincipal groupPrincipal = groupSecurityHandler + .getGroupPrincipal(groupFullPathName); + if (null == groupPrincipal) { throw new SecurityException( + SecurityException.GROUP_DOES_NOT_EXIST + .create(groupFullPathName)); } // Check that user exists. Principal userPrincipal = atnProviderProxy.getUserPrincipal(username); - if (null == userPrincipal) { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(username)); - } + if (null == userPrincipal) { throw new SecurityException( + SecurityException.USER_DOES_NOT_EXIST.create(username)); } // Get the user groups. - Set groupPrincipals = securityMappingHandler.getGroupPrincipals(username); + Set groupPrincipals = securityMappingHandler + .getGroupPrincipals(username); // Add group to user. if (!groupPrincipals.contains(groupPrincipal)) { - securityMappingHandler.setUserPrincipalInGroup(username,groupFullPathName); + securityMappingHandler.setUserPrincipalInGroup(username, + groupFullPathName); } } @@ -326,15 +333,14 @@ throws SecurityException { ArgUtil.notNull(new Object[] - { username, groupFullPathName}, new String[] - { "username", "groupFullPathName"}, + {username, groupFullPathName}, new String[] + {"username", "groupFullPathName"}, "removeUserFromGroup(java.lang.String, java.lang.String)"); // Check that user exists. Principal userPrincipal = atnProviderProxy.getUserPrincipal(username); - if (null == userPrincipal) { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(username)); - } + if (null == userPrincipal) { throw new SecurityException( + SecurityException.USER_DOES_NOT_EXIST.create(username)); } // Get the group principal to remove. Principal groupPrincipal = groupSecurityHandler .getGroupPrincipal(groupFullPathName); @@ -353,8 +359,8 @@ throws SecurityException { ArgUtil.notNull(new Object[] - { username, groupFullPathName}, new String[] - { "username", "groupFullPathName"}, + {username, groupFullPathName}, new String[] + {"username", "groupFullPathName"}, "isUserInGroup(java.lang.String, java.lang.String)"); boolean isUserInGroup = false; @@ -375,7 +381,8 @@ public Iterator getGroups(String filter) throws SecurityException { List groups = new LinkedList(); - Iterator groupPrincipals = groupSecurityHandler.getGroupPrincipals(filter).iterator(); + Iterator groupPrincipals = groupSecurityHandler.getGroupPrincipals( + filter).iterator(); while (groupPrincipals.hasNext()) { String groupName = ((Principal) groupPrincipals.next()).getName(); @@ -384,22 +391,25 @@ } return groups.iterator(); } - + /** - * @see org.apache.jetspeed.security.GroupManager#setGroupEnabled(java.lang.String, boolean) + * @see org.apache.jetspeed.security.GroupManager#setGroupEnabled(java.lang.String, + * boolean) */ - public void setGroupEnabled(String groupFullPathName, boolean enabled) throws SecurityException + public void setGroupEnabled(String groupFullPathName, boolean enabled) + throws SecurityException { - ArgUtil.notNull(new Object[] { groupFullPathName }, new String[] { "groupFullPathName" }, - "setGroupEnabled(java.lang.String,boolean)"); + ArgUtil.notNull(new Object[] + {groupFullPathName}, new String[] + {"groupFullPathName"}, "setGroupEnabled(java.lang.String,boolean)"); - GroupPrincipalImpl groupPrincipal = (GroupPrincipalImpl)groupSecurityHandler.getGroupPrincipal(groupFullPathName); - if (null == groupPrincipal) + GroupPrincipalImpl groupPrincipal = (GroupPrincipalImpl) groupSecurityHandler + .getGroupPrincipal(groupFullPathName); + if (null == groupPrincipal) { throw new SecurityException( + SecurityException.GROUP_DOES_NOT_EXIST + .create(groupFullPathName)); } + if (enabled != groupPrincipal.isEnabled()) { - throw new SecurityException(SecurityException.GROUP_DOES_NOT_EXIST.create(groupFullPathName)); - } - if ( enabled != groupPrincipal.isEnabled() ) - { groupPrincipal.setEnabled(enabled); groupSecurityHandler.setGroupPrincipal(groupPrincipal); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GroupPrincipalImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GroupPrincipalImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/GroupPrincipalImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,11 +19,15 @@ import org.apache.jetspeed.security.GroupPrincipal; /** - * <p>{@link GroupPrincipal} interface implementation.</p> + * <p> + * {@link GroupPrincipal} interface implementation. + * </p> + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: GroupPrincipalImpl.java 592149 2007-11-05 21:05:25Z taylor $ */ -public class GroupPrincipalImpl extends BasePrincipalImpl implements GroupPrincipal +public class GroupPrincipalImpl extends BasePrincipalImpl implements + GroupPrincipal { /** The serial version uid. */ @@ -36,63 +40,88 @@ GroupPrincipalImpl.hiearchicalNames = hierarchicalNames; return null; } - + /** - * <p>The group principal constructor.</p> - * @param groupName The group principal name. + * <p> + * The group principal constructor. + * </p> + * + * @param groupName + * The group principal name. */ public GroupPrincipalImpl(String groupName) { super(groupName, PREFS_GROUP_ROOT, hiearchicalNames); } - public GroupPrincipalImpl(String groupName, boolean isEnabled, boolean isMapping) + public GroupPrincipalImpl(String groupName, boolean isEnabled, + boolean isMapping) { - super(groupName, PREFS_GROUP_ROOT, hiearchicalNames, isEnabled, isMapping); + super(groupName, PREFS_GROUP_ROOT, hiearchicalNames, isEnabled, + isMapping); } - + /** - * <p>Compares this principal to the specified object. Returns true - * if the object passed in matches the principal represented by - * the implementation of this interface.</p> - * @param another Principal to compare with. - * @return True if the principal passed in is the same as that - * encapsulated by this principal, and false otherwise. - + * <p> + * Compares this principal to the specified object. Returns true if the + * object passed in matches the principal represented by the implementation + * of this interface. + * </p> + * + * @param another + * Principal to compare with. + * @return True if the principal passed in is the same as that encapsulated + * by this principal, and false otherwise. + * */ public boolean equals(Object another) { - if (!(another instanceof GroupPrincipalImpl)) - return false; - GroupPrincipalImpl principal = (GroupPrincipalImpl)another; + if (!(another instanceof GroupPrincipalImpl)) return false; + GroupPrincipalImpl principal = (GroupPrincipalImpl) another; return this.getName().equals(principal.getName()); } /** - * <p>Gets the principal implementation full path from the principal name.</p> - * <p>Prepends PREFS_GROUP_ROOT if not prepended.</p> - * @param name The principal name. + * <p> + * Gets the principal implementation full path from the principal name. + * </p> + * <p> + * Prepends PREFS_GROUP_ROOT if not prepended. + * </p> + * + * @param name + * The principal name. * @return The preferences full path / principal name. */ public static String getFullPathFromPrincipalName(String name) { - return BasePrincipalImpl.getFullPathFromPrincipalName(name, PREFS_GROUP_ROOT, hiearchicalNames); + return BasePrincipalImpl.getFullPathFromPrincipalName(name, + PREFS_GROUP_ROOT, hiearchicalNames); } /** - * <p>Gets the principal name from the principal implementation full path.</p> - * <p>Remove prepended PREFS_GROUP_ROOT if present.</p> - * @param fullPath The principal full path. + * <p> + * Gets the principal name from the principal implementation full path. + * </p> + * <p> + * Remove prepended PREFS_GROUP_ROOT if present. + * </p> + * + * @param fullPath + * The principal full path. * @return The principal name. */ public static String getPrincipalNameFromFullPath(String fullPath) { - return BasePrincipalImpl.getPrincipalNameFromFullPath(fullPath, PREFS_GROUP_ROOT, hiearchicalNames); + return BasePrincipalImpl.getPrincipalNameFromFullPath(fullPath, + PREFS_GROUP_ROOT, hiearchicalNames); } - public static String getFullPathFromPrincipalName(String name, String prefsRoot) + public static String getFullPathFromPrincipalName(String name, + String prefsRoot) { - return BasePrincipalImpl.getFullPathFromPrincipalName(name, prefsRoot, hiearchicalNames); + return BasePrincipalImpl.getFullPathFromPrincipalName(name, prefsRoot, + hiearchicalNames); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/JaasPolicyCoordinator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/JaasPolicyCoordinator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/JaasPolicyCoordinator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,6 +30,7 @@ */ public class JaasPolicyCoordinator extends Policy { + private final Policy defaultPolicy; private final Policy j2Policy; @@ -39,8 +40,10 @@ * Constructor for coordinating the policies. * </p> * - * @param defaultPolicy The default policy. - * @param j2Policy Jetspeed policy. + * @param defaultPolicy + * The default policy. + * @param j2Policy + * Jetspeed policy. */ public JaasPolicyCoordinator(Policy defaultPolicy, Policy j2Policy) { @@ -66,7 +69,8 @@ } /** - * @see java.security.Policy#implies(java.security.ProtectionDomain, java.security.Permission) + * @see java.security.Policy#implies(java.security.ProtectionDomain, + * java.security.Permission) */ public boolean implies(ProtectionDomain domain, Permission permission) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/LoginModuleProxyImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/LoginModuleProxyImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/LoginModuleProxyImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,6 +25,7 @@ */ public class LoginModuleProxyImpl implements LoginModuleProxy { + /** The {@link LoginModuleProxy}instance. */ static LoginModuleProxy loginModuleProxy; @@ -40,11 +41,12 @@ * manager. * </p> * - * @param userMgr The user manager. - * @param portalUserRole The portal user role shared by all portal users: used - * in web.xml authorization to detect authenticated portal - * users. - * + * @param userMgr + * The user manager. + * @param portalUserRole + * The portal user role shared by all portal users: used in + * web.xml authorization to detect authenticated portal users. + * */ public LoginModuleProxyImpl(UserManager userMgr, String portalUserRole) { @@ -52,12 +54,14 @@ this.userMgr = userMgr; // The portal user role - this.portalUserRole = (portalUserRole != null ? portalUserRole : DEFAULT_PORTAL_USER_ROLE_NAME); + this.portalUserRole = (portalUserRole != null ? portalUserRole + : DEFAULT_PORTAL_USER_ROLE_NAME); // Hack providing access to the UserManager in the LoginModule. // TODO Can we fix this? LoginModuleProxyImpl.loginModuleProxy = this; } + public LoginModuleProxyImpl(UserManager userMgr) { this(userMgr, DEFAULT_PORTAL_USER_ROLE_NAME); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/PassiveCallbackHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/PassiveCallbackHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/PassiveCallbackHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,19 +16,32 @@ */ package org.apache.jetspeed.security.impl; -import javax.security.auth.callback.*; +import java.io.IOException; +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; + /** - * <p>PassiveCallbackHandler has constructor that takes - * a username and password so its handle() method does - * not have to prompt the user for input.</p> - * <p>Useful for server-side applications.</p> + * <p> + * PassiveCallbackHandler has constructor that takes a username and password so + * its handle() method does not have to prompt the user for input. + * </p> + * <p> + * Useful for server-side applications. + * </p> * - * <p>This code was inspired from an article from:<p> + * <p> + * This code was inspired from an article from: + * <p> * <ul> - * <li><a href="http://www.javaworld.com/javaworld/jw-09-2002/jw-0913-jaas.html"> - * All that JAAS</a></li> + * <li><a + * href="http://www.javaworld.com/javaworld/jw-09-2002/jw-0913-jaas.html"> All + * that JAAS</a></li> * </ul> * + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ @@ -36,13 +49,18 @@ { private String username; + char[] password; /** - * <p>Creates a callback handler with the give username - * and password.</p> - * @param username The username. - * @param password The password. + * <p> + * Creates a callback handler with the give username and password. + * </p> + * + * @param username + * The username. + * @param password + * The password. */ public PassiveCallbackHandler(String username, String password) { @@ -51,17 +69,24 @@ } /** - * <p>Handles the specified set of Callbacks. Uses the - * username and password that were supplied to our - * constructor to popluate the Callbacks.</p> - * <p>This class supports NameCallback and PasswordCallback.</p> - * - * @param callbacks the callbacks to handle - * @throws IOException if an input or output error occurs. - * @throws UnsupportedCallbackException if the callback is not an - * instance of NameCallback or PasswordCallback + * <p> + * Handles the specified set of Callbacks. Uses the username and password + * that were supplied to our constructor to popluate the Callbacks. + * </p> + * <p> + * This class supports NameCallback and PasswordCallback. + * </p> + * + * @param callbacks + * the callbacks to handle + * @throws IOException + * if an input or output error occurs. + * @throws UnsupportedCallbackException + * if the callback is not an instance of NameCallback or + * PasswordCallback */ - public void handle(Callback[] callbacks) throws java.io.IOException, UnsupportedCallbackException + public void handle(Callback[] callbacks) throws java.io.IOException, + UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { @@ -75,13 +100,16 @@ } else { - throw new UnsupportedCallbackException(callbacks[i], "Callback class not supported"); + throw new UnsupportedCallbackException(callbacks[i], + "Callback class not supported"); } } } /** - * <p>Clears out password state.</p> + * <p> + * Clears out password state. + * </p> */ public void clearPassword() { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/PermissionManagerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/PermissionManagerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/PermissionManagerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -74,52 +74,58 @@ * </code> * * <pre> - * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> + * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> * * */ -public class PermissionManagerImpl extends PersistenceBrokerDaoSupport implements PermissionManager +public class PermissionManagerImpl extends PersistenceBrokerDaoSupport + implements PermissionManager { - private static final Log log = LogFactory.getLog(PermissionManagerImpl.class); + + private static final Log log = LogFactory + .getLog(PermissionManagerImpl.class); + private static ThreadLocal permissionsCache = new ThreadLocal(); - + /** * @see org.apache.jetspeed.security.PermissionManager#getPermissions(java.security.Principal) */ public Permissions getPermissions(Principal principal) - { + { String fullPath = SecurityHelper.getPreferencesFullPath(principal); - ArgUtil.notNull(new Object[] { fullPath }, new String[] { "fullPath" }, - "removePermission(java.security.Principal)"); + ArgUtil.notNull(new Object[] + {fullPath}, new String[] + {"fullPath"}, "removePermission(java.security.Principal)"); - HashMap permissionsMap = (HashMap)permissionsCache.get(); - if ( permissionsMap == null ) + HashMap permissionsMap = (HashMap) permissionsCache.get(); + if (permissionsMap == null) { permissionsMap = new HashMap(); permissionsCache.set(permissionsMap); } - HashSet principalPermissions = (HashSet)permissionsMap.get(fullPath); - if ( principalPermissions == null ) + HashSet principalPermissions = (HashSet) permissionsMap.get(fullPath); + if (principalPermissions == null) { InternalPrincipal internalPrincipal = getInternalPrincipal(fullPath); if (null != internalPrincipal) { - principalPermissions = getSecurityPermissions(internalPrincipal.getPermissions()); + principalPermissions = getSecurityPermissions(internalPrincipal + .getPermissions()); } - if ( principalPermissions == null) + if (principalPermissions == null) { principalPermissions = new HashSet(); } permissionsMap.put(fullPath, principalPermissions); } - + Permissions permissions = new Permissions(); - Iterator iter =principalPermissions.iterator(); + Iterator iter = principalPermissions.iterator(); while (iter.hasNext()) { - permissions.add((Permission)iter.next()); + permissions.add((Permission) iter.next()); } - + return permissions; } @@ -128,43 +134,49 @@ */ public Permissions getPermissions(Collection principals) { - ArgUtil.notNull(new Object[] { principals }, new String[] { "principals" }, - "getPermissions(java.util.Collection)"); + ArgUtil.notNull(new Object[] + {principals}, new String[] + {"principals"}, "getPermissions(java.util.Collection)"); Permissions permissions = new Permissions(); Collection principalsFullPath = getPrincipalsFullPath(principals); if ((null != principalsFullPath) && principalsFullPath.size() > 0) { HashSet permissionsSet = new HashSet(); - HashMap permissionsMap = (HashMap)permissionsCache.get(); + HashMap permissionsMap = (HashMap) permissionsCache.get(); if (permissionsMap == null) { permissionsMap = new HashMap(); permissionsCache.set(permissionsMap); } - + Iterator iter = principalsFullPath.iterator(); HashSet principalPermissions; - while ( iter.hasNext()) + while (iter.hasNext()) { - principalPermissions = (HashSet)permissionsMap.get(iter.next()); - if ( principalPermissions != null ) + principalPermissions = (HashSet) permissionsMap + .get(iter.next()); + if (principalPermissions != null) { iter.remove(); permissionsSet.addAll(principalPermissions); } } - if ( principalsFullPath.size() > 0) + if (principalsFullPath.size() > 0) { Criteria filter = new Criteria(); filter.addIn("fullPath", principalsFullPath); - Query query = QueryFactory.newQuery(InternalPrincipalImpl.class, filter); - Collection internalPrincipals = getPersistenceBrokerTemplate().getCollectionByQuery(query); + Query query = QueryFactory.newQuery( + InternalPrincipalImpl.class, filter); + Collection internalPrincipals = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); Iterator internalPrincipalsIter = internalPrincipals.iterator(); while (internalPrincipalsIter.hasNext()) { - InternalPrincipal internalPrincipal = (InternalPrincipal) internalPrincipalsIter.next(); - Collection internalPermissions = internalPrincipal.getPermissions(); + InternalPrincipal internalPrincipal = (InternalPrincipal) internalPrincipalsIter + .next(); + Collection internalPermissions = internalPrincipal + .getPermissions(); if (null != internalPermissions) { principalPermissions = getSecurityPermissions(internalPermissions); @@ -174,13 +186,14 @@ { principalPermissions = new HashSet(); } - permissionsMap.put(internalPrincipal.getFullPath(),principalPermissions); + permissionsMap.put(internalPrincipal.getFullPath(), + principalPermissions); } } iter = permissionsSet.iterator(); while (iter.hasNext()) { - permissions.add((Permission)iter.next()); + permissions.add((Permission) iter.next()); } } return permissions; @@ -191,7 +204,8 @@ * Get the full path for the {@link Principal}in the collection. * </p> * - * @param principals The collection of principals. + * @param principals + * The collection of principals. * @return The collection of principals names. */ private Collection getPrincipalsFullPath(Collection principals) @@ -216,30 +230,39 @@ * unique collection of {@link java.security.Permission}. * </p> * - * @param omPermissions The collection of {@link InternalPermission}. + * @param omPermissions + * The collection of {@link InternalPermission}. */ private HashSet getSecurityPermissions(Collection omPermissions) - { + { HashSet permissions = new HashSet(); Iterator internalPermissionsIter = omPermissions.iterator(); while (internalPermissionsIter.hasNext()) { - InternalPermission internalPermission = (InternalPermission) internalPermissionsIter.next(); + InternalPermission internalPermission = (InternalPermission) internalPermissionsIter + .next(); Permission permission = null; try { - Class permissionClass = Class.forName(internalPermission.getClassname()); - Class[] parameterTypes = { String.class, String.class }; - Constructor permissionConstructor = permissionClass.getConstructor(parameterTypes); - Object[] initArgs = { internalPermission.getName(), internalPermission.getActions() }; - permission = (Permission) permissionConstructor.newInstance(initArgs); - if(permissions.add(permission)) + Class permissionClass = Class.forName(internalPermission + .getClassname()); + Class[] parameterTypes = + {String.class, String.class}; + Constructor permissionConstructor = permissionClass + .getConstructor(parameterTypes); + Object[] initArgs = + {internalPermission.getName(), internalPermission.getActions()}; + permission = (Permission) permissionConstructor + .newInstance(initArgs); + if (permissions.add(permission)) { if (log.isDebugEnabled()) { - log.debug("Added permimssion: [class, " + permission.getClass().getName() + "], " + "[name, " - + permission.getName() + "], " + "[actions, " + permission.getActions() + "]"); - } + log.debug("Added permimssion: [class, " + + permission.getClass().getName() + "], " + + "[name, " + permission.getName() + "], " + + "[actions, " + permission.getActions() + "]"); + } } } catch (Exception e) @@ -255,20 +278,22 @@ */ public void addPermission(Permission permission) throws SecurityException { - ArgUtil.notNull(new Object[] { permission }, new String[] { "permission" }, - "addPermission(java.security.Permission)"); + ArgUtil.notNull(new Object[] + {permission}, new String[] + {"permission"}, "addPermission(java.security.Permission)"); - InternalPermission internalPermission = new InternalPermissionImpl(permission.getClass().getName(), permission - .getName(), permission.getActions()); + InternalPermission internalPermission = new InternalPermissionImpl( + permission.getClass().getName(), permission.getName(), + permission.getActions()); try - { - getPersistenceBrokerTemplate().store(internalPermission); + { + getPersistenceBrokerTemplate().store(internalPermission); } catch (Exception e) { - KeyedMessage msg = SecurityException.UNEXPECTED.create("PermissionManager.addPermission", - "store", e.getMessage()); - logger.error(msg, e); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "PermissionManager.addPermission", "store", e.getMessage()); + logger.error(msg, e); throw new SecurityException(msg, e); } } @@ -276,10 +301,12 @@ /** * @see org.apache.jetspeed.security.PermissionManager#removePermission(java.security.Permission) */ - public void removePermission(Permission permission) throws SecurityException + public void removePermission(Permission permission) + throws SecurityException { - ArgUtil.notNull(new Object[] { permission }, new String[] { "permission" }, - "removePermission(java.security.Permission)"); + ArgUtil.notNull(new Object[] + {permission}, new String[] + {"permission"}, "removePermission(java.security.Permission)"); InternalPermission internalPermission = getInternalPermission(permission); if (null != internalPermission) @@ -293,9 +320,10 @@ } catch (Exception e) { - KeyedMessage msg = SecurityException.UNEXPECTED.create("PermissionManager.removePermission", - "delete", e.getMessage()); - logger.error(msg, e); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "PermissionManager.removePermission", "delete", e + .getMessage()); + logger.error(msg, e); throw new SecurityException(msg, e); } } @@ -307,8 +335,9 @@ public void removePermissions(Principal principal) throws SecurityException { String fullPath = SecurityHelper.getPreferencesFullPath(principal); - ArgUtil.notNull(new Object[] { fullPath }, new String[] { "fullPath" }, - "removePermission(java.security.Principal)"); + ArgUtil.notNull(new Object[] + {fullPath}, new String[] + {"fullPath"}, "removePermission(java.security.Principal)"); // Remove permissions on principal. InternalPrincipal internalPrincipal = getInternalPrincipal(fullPath); @@ -323,16 +352,18 @@ permissionsCache.set(null); try { - internalPrincipal.setModifiedDate(new Timestamp(System.currentTimeMillis())); + internalPrincipal.setModifiedDate(new Timestamp(System + .currentTimeMillis())); internalPrincipal.setPermissions(internalPermissions); - + getPersistenceBrokerTemplate().store(internalPrincipal); } catch (Exception e) { - KeyedMessage msg = SecurityException.UNEXPECTED.create("PermissionManager.removePermissions", - "store", e.getMessage()); - logger.error(msg, e); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "PermissionManager.removePermissions", "store", e + .getMessage()); + logger.error(msg, e); throw new SecurityException(msg, e); } } @@ -342,33 +373,38 @@ * @see org.apache.jetspeed.security.PermissionManager#grantPermission(java.security.Principal, * java.security.Permission) */ - public void grantPermission(Principal principal, Permission permission) throws SecurityException + public void grantPermission(Principal principal, Permission permission) + throws SecurityException { String fullPath = SecurityHelper.getPreferencesFullPath(principal); - ArgUtil.notNull(new Object[] { fullPath, permission }, new String[] { "fullPath", "permission" }, - "grantPermission(java.security.Principal, java.security.Permission)"); + ArgUtil + .notNull(new Object[] + {fullPath, permission}, new String[] + {"fullPath", "permission"}, + "grantPermission(java.security.Principal, java.security.Permission)"); Collection internalPermissions = new ArrayList(); InternalPrincipal internalPrincipal = getInternalPrincipal(fullPath); if (null == internalPrincipal) { - if ( principal instanceof UserPrincipal ) + if (principal instanceof UserPrincipal) { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(principal.getName())); + throw new SecurityException( + SecurityException.USER_DOES_NOT_EXIST.create(principal + .getName())); } - else if ( principal instanceof RolePrincipal ) - { - throw new SecurityException(SecurityException.ROLE_DOES_NOT_EXIST.create(principal.getName())); - } + else if (principal instanceof RolePrincipal) { throw new SecurityException( + SecurityException.ROLE_DOES_NOT_EXIST.create(principal + .getName())); } // must/should be GroupPrincipal - throw new SecurityException(SecurityException.GROUP_DOES_NOT_EXIST.create(principal.getName())); + throw new SecurityException(SecurityException.GROUP_DOES_NOT_EXIST + .create(principal.getName())); } InternalPermission internalPermission = getInternalPermission(permission); - if (null == internalPermission) - { - throw new SecurityException(SecurityException.PERMISSION_DOES_NOT_EXIST.create(permission.getName())); - } + if (null == internalPermission) { throw new SecurityException( + SecurityException.PERMISSION_DOES_NOT_EXIST.create(permission + .getName())); } if (null != internalPrincipal.getPermissions()) { @@ -382,16 +418,18 @@ permissionsCache.set(null); try { - internalPrincipal.setModifiedDate(new Timestamp(System.currentTimeMillis())); + internalPrincipal.setModifiedDate(new Timestamp(System + .currentTimeMillis())); internalPrincipal.setPermissions(internalPermissions); - + getPersistenceBrokerTemplate().store(internalPrincipal); } catch (Exception e) { - KeyedMessage msg = SecurityException.UNEXPECTED.create("PermissionManager.grantPermission", - "store", e.getMessage()); - logger.error(msg, e); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "PermissionManager.grantPermission", "store", e + .getMessage()); + logger.error(msg, e); throw new SecurityException(msg, e); } } @@ -414,11 +452,15 @@ * @see org.apache.jetspeed.security.PermissionManager#revokePermission(java.security.Principal, * java.security.Permission) */ - public void revokePermission(Principal principal, Permission permission) throws SecurityException + public void revokePermission(Principal principal, Permission permission) + throws SecurityException { String fullPath = SecurityHelper.getPreferencesFullPath(principal); - ArgUtil.notNull(new Object[] { fullPath, permission }, new String[] { "fullPath", "permission" }, - "revokePermission(java.security.Principal, java.security.Permission)"); + ArgUtil + .notNull(new Object[] + {fullPath, permission}, new String[] + {"fullPath", "permission"}, + "revokePermission(java.security.Principal, java.security.Permission)"); // Remove permissions on principal. InternalPrincipal internalPrincipal = getInternalPrincipal(fullPath); @@ -429,13 +471,17 @@ { boolean revokePermission = false; ArrayList newInternalPermissions = new ArrayList(); - Iterator internalPermissionsIter = internalPermissions.iterator(); + Iterator internalPermissionsIter = internalPermissions + .iterator(); while (internalPermissionsIter.hasNext()) { - InternalPermission internalPermission = (InternalPermission) internalPermissionsIter.next(); - if (!((internalPermission.getClassname().equals(permission.getClass().getName())) - && (internalPermission.getName().equals(permission.getName())) && (internalPermission.getActions() - .equals(permission.getActions())))) + InternalPermission internalPermission = (InternalPermission) internalPermissionsIter + .next(); + if (!((internalPermission.getClassname().equals(permission + .getClass().getName())) + && (internalPermission.getName().equals(permission + .getName())) && (internalPermission + .getActions().equals(permission.getActions())))) { newInternalPermissions.add(internalPermission); } @@ -450,16 +496,19 @@ permissionsCache.set(null); try { - internalPrincipal.setModifiedDate(new Timestamp(System.currentTimeMillis())); - internalPrincipal.setPermissions(newInternalPermissions); + internalPrincipal.setModifiedDate(new Timestamp(System + .currentTimeMillis())); + internalPrincipal + .setPermissions(newInternalPermissions); getPersistenceBrokerTemplate().store(internalPrincipal); } catch (Exception e) { - KeyedMessage msg = SecurityException.UNEXPECTED.create("PermissionManager.revokePermission", - "store", e.getMessage()); - logger.error(msg, e); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "PermissionManager.revokePermission", "store", + e.getMessage()); + logger.error(msg, e); throw new SecurityException(msg, e); } } @@ -472,15 +521,18 @@ * Returns the {@link InternalPrincipal}from the full path. * </p> * - * @param fullPath The full path. + * @param fullPath + * The full path. * @return The {@link InternalPrincipal}. */ InternalPrincipal getInternalPrincipal(String fullPath) { Criteria filter = new Criteria(); filter.addEqualTo("fullPath", fullPath); - Query query = QueryFactory.newQuery(InternalPrincipalImpl.class, filter); - InternalPrincipal internalPrincipal = (InternalPrincipal) getPersistenceBrokerTemplate().getObjectByQuery(query); + Query query = QueryFactory + .newQuery(InternalPrincipalImpl.class, filter); + InternalPrincipal internalPrincipal = (InternalPrincipal) getPersistenceBrokerTemplate() + .getObjectByQuery(query); return internalPrincipal; } @@ -489,7 +541,8 @@ * Returns the {@link InternalPermission} from a Permission. * </p> * - * @param permission The permission. + * @param permission + * The permission. * @return The {@link InternalPermission}. */ InternalPermission getInternalPermission(Permission permission) @@ -498,18 +551,21 @@ filter.addEqualTo("classname", permission.getClass().getName()); filter.addEqualTo("name", permission.getName()); filter.addEqualTo("actions", permission.getActions()); - Query query = QueryFactory.newQuery(InternalPermissionImpl.class, filter); - InternalPermission internalPermission = (InternalPermission) getPersistenceBrokerTemplate().getObjectByQuery(query); + Query query = QueryFactory.newQuery(InternalPermissionImpl.class, + filter); + InternalPermission internalPermission = (InternalPermission) getPersistenceBrokerTemplate() + .getObjectByQuery(query); return internalPermission; } - - public boolean checkPermission(Subject subject, final Permission permission) + + public boolean checkPermission(Subject subject, final Permission permission) { try { - //JSSubject.doAs(subject, new PrivilegedAction() - JSSubject.doAsPrivileged(subject, new PrivilegedAction() + // JSSubject.doAs(subject, new PrivilegedAction() + JSSubject.doAsPrivileged(subject, new PrivilegedAction() { + public Object run() { AccessController.checkPermission(permission); @@ -521,49 +577,59 @@ { return false; } - return true; + return true; } - + public Collection getPermissions() { - QueryByCriteria query = QueryFactory.newQuery(InternalPermissionImpl.class, new Criteria()); + QueryByCriteria query = QueryFactory.newQuery( + InternalPermissionImpl.class, new Criteria()); query.addOrderByAscending("classname"); query.addOrderByAscending("name"); - Collection internalPermissions = getPersistenceBrokerTemplate().getCollectionByQuery(query); + Collection internalPermissions = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); return internalPermissions; } - + public Permissions getPermissions(String classname, String resource) { Criteria filter = new Criteria(); filter.addEqualTo("classname", classname); filter.addEqualTo("name", resource); - Query query = QueryFactory.newQuery(InternalPermissionImpl.class, filter); - Collection internalPermissions = getPersistenceBrokerTemplate().getCollectionByQuery(query); + Query query = QueryFactory.newQuery(InternalPermissionImpl.class, + filter); + Collection internalPermissions = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); Permissions permissions = new Permissions(); Iterator iter = internalPermissions.iterator(); try { while (iter.hasNext()) { - InternalPermission internalPermission = (InternalPermission)iter.next(); - Class permissionClass = Class.forName(internalPermission.getClassname()); - Class[] parameterTypes = { String.class, String.class }; - Constructor permissionConstructor = permissionClass.getConstructor(parameterTypes); - Object[] initArgs = { internalPermission.getName(), internalPermission.getActions() }; - Permission permission = (Permission) permissionConstructor.newInstance(initArgs); + InternalPermission internalPermission = (InternalPermission) iter + .next(); + Class permissionClass = Class.forName(internalPermission + .getClassname()); + Class[] parameterTypes = + {String.class, String.class}; + Constructor permissionConstructor = permissionClass + .getConstructor(parameterTypes); + Object[] initArgs = + {internalPermission.getName(), internalPermission.getActions()}; + Permission permission = (Permission) permissionConstructor + .newInstance(initArgs); permissions.add(permission); } } catch (Exception e) { - logger.error("Failed to retrieve permissions", e); + logger.error("Failed to retrieve permissions", e); } - return permissions; - } - + return permissions; + } + public int updatePermission(Permission permission, Collection principals) - throws SecurityException + throws SecurityException { int count = 0; InternalPermission internal = getInternalPermission(permission); @@ -571,46 +637,46 @@ Collection newPrincipals = new LinkedList(); while (iter.hasNext()) { - Principal principal = (Principal)iter.next(); + Principal principal = (Principal) iter.next(); String fullPath = SecurityHelper.getPreferencesFullPath(principal); InternalPrincipal internalPrincipal = getInternalPrincipal(fullPath); - newPrincipals.add(internalPrincipal); + newPrincipals.add(internalPrincipal); } internal.setPrincipals(newPrincipals); internal.setModifiedDate(new Timestamp(System.currentTimeMillis())); try - { - getPersistenceBrokerTemplate().store(internal); + { + getPersistenceBrokerTemplate().store(internal); } catch (Exception e) { - KeyedMessage msg = SecurityException.UNEXPECTED.create("PermissionManager.updatePermission", - "store", e.getMessage()); - logger.error(msg, e); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "PermissionManager.updatePermission", "store", e + .getMessage()); + logger.error(msg, e); throw new SecurityException(msg, e); } return count; } - + public Collection getPrincipals(Permission permission) { - Collection result = new LinkedList(); - InternalPermission internalPermission = this.getInternalPermission(permission); - if (internalPermission == null) - { - return result; - } + Collection result = new LinkedList(); + InternalPermission internalPermission = this + .getInternalPermission(permission); + if (internalPermission == null) { return result; } Iterator principals = internalPermission.getPrincipals().iterator(); while (principals.hasNext()) { - InternalPrincipal internalPrincipal = (InternalPrincipal)principals.next(); - Principal principal = - SecurityHelper.createPrincipalFromFullPath(internalPrincipal.getFullPath()); + InternalPrincipal internalPrincipal = (InternalPrincipal) principals + .next(); + Principal principal = SecurityHelper + .createPrincipalFromFullPath(internalPrincipal + .getFullPath()); result.add(principal); } - return result; + return result; } - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/PrincipalsSet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/PrincipalsSet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/PrincipalsSet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.impl; import java.util.Collection; @@ -23,10 +23,9 @@ import java.util.List; import java.util.Set; - /** - * PrincipalsSet - provides an ordered 'set' of principals required - * for some profiling rules that are dependent on order of insert. + * PrincipalsSet - provides an ordered 'set' of principals required for some + * profiling rules that are dependent on order of insert. * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ @@ -34,13 +33,18 @@ public class PrincipalsSet implements Set { + List principals = new LinkedList(); + Set set = new HashSet(); public PrincipalsSet() - {} - - /* (non-Javadoc) + { + } + + /* + * (non-Javadoc) + * * @see java.util.Collection#size() */ public int size() @@ -48,7 +52,9 @@ return principals.size(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Collection#clear() */ public void clear() @@ -57,7 +63,9 @@ principals.clear(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Collection#isEmpty() */ public boolean isEmpty() @@ -65,7 +73,9 @@ return principals.isEmpty(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Collection#toArray() */ public Object[] toArray() @@ -73,7 +83,9 @@ return principals.toArray(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Collection#add(java.lang.Object) */ public boolean add(Object o) @@ -86,7 +98,9 @@ return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Collection#contains(java.lang.Object) */ public boolean contains(Object o) @@ -94,7 +108,9 @@ return set.contains(o); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Collection#remove(java.lang.Object) */ public boolean remove(Object o) @@ -103,7 +119,9 @@ return principals.remove(o); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Collection#addAll(java.util.Collection) */ public boolean addAll(Collection c) @@ -112,7 +130,9 @@ return principals.addAll(c); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Collection#containsAll(java.util.Collection) */ public boolean containsAll(Collection c) @@ -120,7 +140,9 @@ return set.containsAll(c); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Collection#removeAll(java.util.Collection) */ public boolean removeAll(Collection c) @@ -129,7 +151,9 @@ return principals.removeAll(c); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Collection#retainAll(java.util.Collection) */ public boolean retainAll(Collection c) @@ -138,7 +162,9 @@ return principals.retainAll(c); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Collection#iterator() */ public Iterator iterator() @@ -146,7 +172,9 @@ return principals.iterator(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see java.util.Collection#toArray(java.lang.Object[]) */ public Object[] toArray(Object[] a) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RdbmsPolicy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RdbmsPolicy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RdbmsPolicy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -40,10 +40,10 @@ * <p> * This code was partially inspired from articles from:<br> * <ul> - * <li><a href="http://www.ibm.com/developerworks/library/j-jaas/"> Extend JAAS for class - * instance-level authorization.</a></li> - * <li><a href="http://www.javageeks.com/Papers/JavaPolicy/index.html"> When "java.policy" Just - * Isn't Good Enough.</li> + * <li><a href="http://www.ibm.com/developerworks/library/j-jaas/"> Extend JAAS + * for class instance-level authorization.</a></li> + * <li><a href="http://www.javageeks.com/Papers/JavaPolicy/index.html"> When + * "java.policy" Just Isn't Good Enough.</li> * </ul> * </p> * @@ -51,6 +51,7 @@ */ public class RdbmsPolicy extends Policy { + private static final Log log = LogFactory.getLog(RdbmsPolicy.class); /** @@ -79,26 +80,28 @@ */ public void refresh() { -// if (log.isDebugEnabled()) -// { -// log.debug("RdbmsPolicy refresh called."); -// } + // if (log.isDebugEnabled()) + // { + // log.debug("RdbmsPolicy refresh called."); + // } } /** * <p> - * Check that the permission is implied for the protection domain. This will check for - * permissions against the configured RDBMS and all {@link SecurityPolicies} configured through - * the AuthorizationProvider. + * Check that the permission is implied for the protection domain. This will + * check for permissions against the configured RDBMS and all + * {@link SecurityPolicies} configured through the AuthorizationProvider. * </p> * <p> - * The default policy is by default part of the {@link SecurityPolicies} and will only if - * configured through assembly. + * The default policy is by default part of the {@link SecurityPolicies} and + * will only if configured through assembly. * </p> * - * @see java.security.Policy#implies(java.security.ProtectionDomain, java.security.Permission) + * @see java.security.Policy#implies(java.security.ProtectionDomain, + * java.security.Permission) */ - public boolean implies(ProtectionDomain protectionDomain, Permission permission) + public boolean implies(ProtectionDomain protectionDomain, + Permission permission) { Principal[] principals = protectionDomain.getPrincipals(); PermissionCollection perms = new Permissions(); @@ -113,24 +116,29 @@ } else { -// if (log.isDebugEnabled()) -// { -// log.debug("Implying permission [class, " + permission.getClass().getName() + "], " + "[name, " -// + permission.getName() + "], " + "[actions, " + permission.getActions() + "] for: "); -// log.debug("\tCodeSource:" + protectionDomain.getCodeSource().getLocation().getPath()); -// for (int i = 0; i < principals.length; i++) -// { -// log.debug("\tPrincipal[" + i + "]: [name, " + principals[i].getName() + "], [class, " -// + principals[i].getClass() + "]"); -// } -// } + // if (log.isDebugEnabled()) + // { + // log.debug("Implying permission [class, " + + // permission.getClass().getName() + "], " + "[name, " + // + permission.getName() + "], " + "[actions, " + + // permission.getActions() + "] for: "); + // log.debug("\tCodeSource:" + + // protectionDomain.getCodeSource().getLocation().getPath()); + // for (int i = 0; i < principals.length; i++) + // { + // log.debug("\tPrincipal[" + i + "]: [name, " + + // principals[i].getName() + "], [class, " + // + principals[i].getClass() + "]"); + // } + // } perms = pms.getPermissions(Arrays.asList(principals)); } } else { // No principal is returned from the subject. - // For security check, be sure to use doAsPrivileged(theSubject, anAction, null)... + // For security check, be sure to use doAsPrivileged(theSubject, + // anAction, null)... // We grant access when no principal is associated to the subject. perms.add(new AllPermission()); } @@ -156,18 +164,18 @@ /** * <p> - * The RdbmsPolicy does not protect code source per say, but will return the protected code - * source from the other configured policies. + * The RdbmsPolicy does not protect code source per say, but will return the + * protected code source from the other configured policies. * </p> * * @see java.security.Policy#getPermissions(java.security.CodeSource) */ public PermissionCollection getPermissions(CodeSource codeSource) { -// if (log.isDebugEnabled()) -// { -// log.debug("getPermissions called for '" + codeSource + "'."); -// } + // if (log.isDebugEnabled()) + // { + // log.debug("getPermissions called for '" + codeSource + "'."); + // } PermissionCollection otherPerms = getOtherPoliciesPermissions(codeSource); return otherPerms; @@ -175,21 +183,25 @@ /** * <p> - * Gets all the permissions that should be enforced through the other policies configured. + * Gets all the permissions that should be enforced through the other + * policies configured. * </p> * - * @param codeSource The CodeSource. + * @param codeSource + * The CodeSource. * @return A collection of permissions as a {@link PermissionCollection} */ - private PermissionCollection getOtherPoliciesPermissions(CodeSource codeSource) + private PermissionCollection getOtherPoliciesPermissions( + CodeSource codeSource) { -// if (log.isDebugEnabled()) -// { -// log.debug("Checking other policies permissions."); -// } + // if (log.isDebugEnabled()) + // { + // log.debug("Checking other policies permissions."); + // } log.debug("CodeSource: " + codeSource.getLocation().getPath()); - List securityPolicies = SecurityPolicies.getInstance().getUsedPolicies(); + List securityPolicies = SecurityPolicies.getInstance() + .getUsedPolicies(); PermissionCollection otherPerms = new Permissions(); for (int i = 0; i < securityPolicies.size(); i++) { @@ -198,9 +210,11 @@ { if (log.isDebugEnabled()) { - log.debug("Checking policy: " + currPolicy.getClass().getName()); + log.debug("Checking policy: " + + currPolicy.getClass().getName()); } - PermissionCollection currPerms = currPolicy.getPermissions(codeSource); + PermissionCollection currPerms = currPolicy + .getPermissions(codeSource); SecurityHelper.addPermissions(otherPerms, currPerms); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RoleImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RoleImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RoleImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,23 +22,33 @@ import org.apache.jetspeed.security.Role; /** - * <p>A role made of a {@link Principal} and the user {@link Preferences}.</p> + * <p> + * A role made of a {@link Principal} and the user {@link Preferences}. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public class RoleImpl implements Role { /** - * <p>Default constructor.</p> + * <p> + * Default constructor. + * </p> */ public RoleImpl() { } /** - * <p>{@link Role} constructor given a role principal and preferences.</p> - * @param rolePrincipal The role principal. - * @param preferences The preferences. + * <p> + * {@link Role} constructor given a role principal and preferences. + * </p> + * + * @param rolePrincipal + * The role principal. + * @param preferences + * The preferences. */ public RoleImpl(Principal rolePrincipal, Preferences preferences) { @@ -47,7 +57,7 @@ } private Principal rolePrincipal; - + /** * @see org.apache.jetspeed.security.Role#getPrincipal() */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RoleManagerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RoleManagerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RoleManagerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -59,12 +59,13 @@ */ public class RoleManagerImpl implements RoleManager { + /** The logger. */ private static final Log log = LogFactory.getLog(RoleManagerImpl.class); /** The authentication provider proxy. */ private AuthenticationProviderProxy atnProviderProxy = null; - + /** The role security handler. */ private RoleSecurityHandler roleSecurityHandler = null; @@ -72,13 +73,16 @@ private SecurityMappingHandler securityMappingHandler = null; /** - * @param securityProvider The security provider. + * @param securityProvider + * The security provider. */ public RoleManagerImpl(SecurityProvider securityProvider) { - this.atnProviderProxy = securityProvider.getAuthenticationProviderProxy(); + this.atnProviderProxy = securityProvider + .getAuthenticationProviderProxy(); this.roleSecurityHandler = securityProvider.getRoleSecurityHandler(); - this.securityMappingHandler = securityProvider.getSecurityMappingHandler(); + this.securityMappingHandler = securityProvider + .getSecurityMappingHandler(); } /** @@ -86,14 +90,13 @@ */ public void addRole(String roleFullPathName) throws SecurityException { - ArgUtil.notNull(new Object[] { roleFullPathName }, new String[] { "roleFullPathName" }, - "addRole(java.lang.String)"); + ArgUtil.notNull(new Object[] + {roleFullPathName}, new String[] + {"roleFullPathName"}, "addRole(java.lang.String)"); // Check if role already exists. - if (roleExists(roleFullPathName)) - { - throw new SecurityException(SecurityException.ROLE_ALREADY_EXISTS.create(roleFullPathName)); - } + if (roleExists(roleFullPathName)) { throw new SecurityException( + SecurityException.ROLE_ALREADY_EXISTS.create(roleFullPathName)); } RolePrincipal rolePrincipal = new RolePrincipalImpl(roleFullPathName); String fullPath = rolePrincipal.getFullPath(); @@ -105,7 +108,8 @@ } try { - if ((null != preferences) && preferences.absolutePath().equals(fullPath)) + if ((null != preferences) + && preferences.absolutePath().equals(fullPath)) { // Add role principal. roleSecurityHandler.setRolePrincipal(rolePrincipal); @@ -117,10 +121,10 @@ } catch (SecurityException se) { - KeyedMessage msg = - SecurityException.UNEXPECTED.create("RoleManager.addRole", - "RoleSecurityHandler.setRolePrincipal("+rolePrincipal.getName()+")", - se.getMessage()); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "RoleManager.addRole", + "RoleSecurityHandler.setRolePrincipal(" + + rolePrincipal.getName() + ")", se.getMessage()); log.error(msg, se); // Remove the preferences node. @@ -141,26 +145,32 @@ */ public void removeRole(String roleFullPathName) throws SecurityException { - ArgUtil.notNull(new Object[] { roleFullPathName }, new String[] { "roleFullPathName" }, - "removeRole(java.lang.String)"); + ArgUtil.notNull(new Object[] + {roleFullPathName}, new String[] + {"roleFullPathName"}, "removeRole(java.lang.String)"); // Resolve the role hierarchy. Preferences prefs = Preferences.userRoot().node( - RolePrincipalImpl.getFullPathFromPrincipalName(roleFullPathName)); - String[] roles = securityMappingHandler.getRoleHierarchyResolver().resolveChildren(prefs); + RolePrincipalImpl + .getFullPathFromPrincipalName(roleFullPathName)); + String[] roles = securityMappingHandler.getRoleHierarchyResolver() + .resolveChildren(prefs); for (int i = 0; i < roles.length; i++) { try { - roleSecurityHandler.removeRolePrincipal(new RolePrincipalImpl(RolePrincipalImpl - .getPrincipalNameFromFullPath(roles[i]))); + roleSecurityHandler.removeRolePrincipal(new RolePrincipalImpl( + RolePrincipalImpl + .getPrincipalNameFromFullPath(roles[i]))); } catch (Exception e) { - KeyedMessage msg = - SecurityException.UNEXPECTED.create("RoleManager.removeRole", - "RoleSecurityHandler.removeRolePrincipal("+RolePrincipalImpl.getPrincipalNameFromFullPath(roles[i])+")", - e.getMessage()); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "RoleManager.removeRole", + "RoleSecurityHandler.removeRolePrincipal(" + + RolePrincipalImpl + .getPrincipalNameFromFullPath(roles[i]) + + ")", e.getMessage()); log.error(msg, e); throw new SecurityException(msg, e); } @@ -172,10 +182,9 @@ } catch (BackingStoreException bse) { - KeyedMessage msg = - SecurityException.UNEXPECTED.create("RoleManager.removeRole", - "Preferences.removeNode("+roles[i]+")", - bse.getMessage()); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "RoleManager.removeRole", "Preferences.removeNode(" + + roles[i] + ")", bse.getMessage()); log.error(msg, bse); throw new SecurityException(msg, bse); } @@ -187,10 +196,12 @@ */ public boolean roleExists(String roleFullPathName) { - ArgUtil.notNull(new Object[] { roleFullPathName }, new String[] { "roleFullPathName" }, - "roleExists(java.lang.String)"); + ArgUtil.notNull(new Object[] + {roleFullPathName}, new String[] + {"roleFullPathName"}, "roleExists(java.lang.String)"); - Principal principal = roleSecurityHandler.getRolePrincipal(roleFullPathName); + Principal principal = roleSecurityHandler + .getRolePrincipal(roleFullPathName); boolean roleExists = (null != principal); if (log.isDebugEnabled()) { @@ -205,16 +216,17 @@ */ public Role getRole(String roleFullPathName) throws SecurityException { - ArgUtil.notNull(new Object[] { roleFullPathName }, new String[] { "roleFullPathName" }, - "getRole(java.lang.String)"); + ArgUtil.notNull(new Object[] + {roleFullPathName}, new String[] + {"roleFullPathName"}, "getRole(java.lang.String)"); - String fullPath = RolePrincipalImpl.getFullPathFromPrincipalName(roleFullPathName); + String fullPath = RolePrincipalImpl + .getFullPathFromPrincipalName(roleFullPathName); - Principal rolePrincipal = roleSecurityHandler.getRolePrincipal(roleFullPathName); - if (null == rolePrincipal) - { - throw new SecurityException(SecurityException.ROLE_DOES_NOT_EXIST.create(roleFullPathName)); - } + Principal rolePrincipal = roleSecurityHandler + .getRolePrincipal(roleFullPathName); + if (null == rolePrincipal) { throw new SecurityException( + SecurityException.ROLE_DOES_NOT_EXIST.create(roleFullPathName)); } Preferences preferences = Preferences.userRoot().node(fullPath); Role role = new RoleImpl(rolePrincipal, preferences); return role; @@ -225,7 +237,9 @@ */ public Collection getRolesForUser(String username) throws SecurityException { - ArgUtil.notNull(new Object[] { username }, new String[] { "username" }, "getRolesForUser(java.lang.String)"); + ArgUtil.notNull(new Object[] + {username}, new String[] + {"username"}, "getRolesForUser(java.lang.String)"); Collection roles = new ArrayList(); @@ -235,7 +249,9 @@ { Principal rolePrincipal = (Principal) rolePrincipalsIter.next(); Preferences preferences = Preferences.userRoot().node( - RolePrincipalImpl.getFullPathFromPrincipalName(rolePrincipal.getName())); + RolePrincipalImpl + .getFullPathFromPrincipalName(rolePrincipal + .getName())); roles.add(new RoleImpl(rolePrincipal, preferences)); } return roles; @@ -244,20 +260,25 @@ /** * @see org.apache.jetspeed.security.RoleManager#getRolesInGroup(java.lang.String) */ - public Collection getRolesInGroup(String groupFullPathName) throws SecurityException + public Collection getRolesInGroup(String groupFullPathName) + throws SecurityException { - ArgUtil.notNull(new Object[] { groupFullPathName }, new String[] { "groupFullPathName" }, - "getRolesInGroup(java.lang.String)"); + ArgUtil.notNull(new Object[] + {groupFullPathName}, new String[] + {"groupFullPathName"}, "getRolesInGroup(java.lang.String)"); Collection roles = new ArrayList(); - Set rolePrincipals = securityMappingHandler.getRolePrincipalsInGroup(groupFullPathName); + Set rolePrincipals = securityMappingHandler + .getRolePrincipalsInGroup(groupFullPathName); Iterator rolePrincipalsIter = rolePrincipals.iterator(); while (rolePrincipalsIter.hasNext()) { Principal rolePrincipal = (Principal) rolePrincipalsIter.next(); Preferences preferences = Preferences.userRoot().node( - RolePrincipalImpl.getFullPathFromPrincipalName(rolePrincipal.getName())); + RolePrincipalImpl + .getFullPathFromPrincipalName(rolePrincipal + .getName())); roles.add(new RoleImpl(rolePrincipal, preferences)); } return roles; @@ -267,29 +288,30 @@ * @see org.apache.jetspeed.security.RoleManager#addRoleToUser(java.lang.String, * java.lang.String) */ - public void addRoleToUser(String username, String roleFullPathName) throws SecurityException + public void addRoleToUser(String username, String roleFullPathName) + throws SecurityException { - ArgUtil.notNull(new Object[] { username, roleFullPathName }, new String[] { "username", "roleFullPathName" }, + ArgUtil.notNull(new Object[] + {username, roleFullPathName}, new String[] + {"username", "roleFullPathName"}, "addUserToRole(java.lang.String, java.lang.String)"); // Get the role principal to add to user. - Principal rolePrincipal = roleSecurityHandler.getRolePrincipal(roleFullPathName); - if (null == rolePrincipal) - { - throw new SecurityException(SecurityException.ROLE_DOES_NOT_EXIST.create(roleFullPathName)); - } + Principal rolePrincipal = roleSecurityHandler + .getRolePrincipal(roleFullPathName); + if (null == rolePrincipal) { throw new SecurityException( + SecurityException.ROLE_DOES_NOT_EXIST.create(roleFullPathName)); } // Check that user exists. Principal userPrincipal = atnProviderProxy.getUserPrincipal(username); - if (null == userPrincipal) - { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(username)); - } + if (null == userPrincipal) { throw new SecurityException( + SecurityException.USER_DOES_NOT_EXIST.create(username)); } // Get the user roles. Set rolePrincipals = securityMappingHandler.getRolePrincipals(username); // Add role to user. if (!rolePrincipals.contains(rolePrincipal)) { - securityMappingHandler.setUserPrincipalInRole(username, roleFullPathName); + securityMappingHandler.setUserPrincipalInRole(username, + roleFullPathName); } } @@ -297,22 +319,25 @@ * @see org.apache.jetspeed.security.RoleManager#removeRoleFromUser(java.lang.String, * java.lang.String) */ - public void removeRoleFromUser(String username, String roleFullPathName) throws SecurityException + public void removeRoleFromUser(String username, String roleFullPathName) + throws SecurityException { - ArgUtil.notNull(new Object[] { username, roleFullPathName }, new String[] { "username", "roleFullPathName" }, + ArgUtil.notNull(new Object[] + {username, roleFullPathName}, new String[] + {"username", "roleFullPathName"}, "removeRoleFromUser(java.lang.String, java.lang.String)"); // Check that user exists. Principal userPrincipal = atnProviderProxy.getUserPrincipal(username); - if (null == userPrincipal) - { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(username)); - } + if (null == userPrincipal) { throw new SecurityException( + SecurityException.USER_DOES_NOT_EXIST.create(username)); } // Get the role principal to remove. - Principal rolePrincipal = roleSecurityHandler.getRolePrincipal(roleFullPathName); + Principal rolePrincipal = roleSecurityHandler + .getRolePrincipal(roleFullPathName); if (null != rolePrincipal) { - securityMappingHandler.removeUserPrincipalInRole(username, roleFullPathName); + securityMappingHandler.removeUserPrincipalInRole(username, + roleFullPathName); } } @@ -320,9 +345,12 @@ * @see org.apache.jetspeed.security.RoleManager#isUserInRole(java.lang.String, * java.lang.String) */ - public boolean isUserInRole(String username, String roleFullPathName) throws SecurityException + public boolean isUserInRole(String username, String roleFullPathName) + throws SecurityException { - ArgUtil.notNull(new Object[] { username, roleFullPathName }, new String[] { "username", "roleFullPathName" }, + ArgUtil.notNull(new Object[] + {username, roleFullPathName}, new String[] + {"username", "roleFullPathName"}, "isUserInRole(java.lang.String, java.lang.String)"); boolean isUserInRole = false; @@ -340,34 +368,42 @@ * @see org.apache.jetspeed.security.RoleManager#addRoleToGroup(java.lang.String, * java.lang.String) */ - public void addRoleToGroup(String roleFullPathName, String groupFullPathName) throws SecurityException + public void addRoleToGroup(String roleFullPathName, String groupFullPathName) + throws SecurityException { - ArgUtil.notNull(new Object[] { roleFullPathName, groupFullPathName }, new String[] { "roleFullPathName", - "groupFullPathName" }, "addRoleToGroup(java.lang.String, java.lang.String)"); + ArgUtil.notNull(new Object[] + {roleFullPathName, groupFullPathName}, new String[] + {"roleFullPathName", "groupFullPathName"}, + "addRoleToGroup(java.lang.String, java.lang.String)"); // Get the role principal to add to group. - Principal rolePrincipal = roleSecurityHandler.getRolePrincipal(roleFullPathName); - if (null == rolePrincipal) - { - throw new SecurityException(SecurityException.ROLE_DOES_NOT_EXIST.create(roleFullPathName)); - } - securityMappingHandler.setRolePrincipalInGroup(groupFullPathName, roleFullPathName); + Principal rolePrincipal = roleSecurityHandler + .getRolePrincipal(roleFullPathName); + if (null == rolePrincipal) { throw new SecurityException( + SecurityException.ROLE_DOES_NOT_EXIST.create(roleFullPathName)); } + securityMappingHandler.setRolePrincipalInGroup(groupFullPathName, + roleFullPathName); } /** * @see org.apache.jetspeed.security.RoleManager#removeRoleFromGroup(java.lang.String, * java.lang.String) */ - public void removeRoleFromGroup(String roleFullPathName, String groupFullPathName) throws SecurityException + public void removeRoleFromGroup(String roleFullPathName, + String groupFullPathName) throws SecurityException { - ArgUtil.notNull(new Object[] { roleFullPathName, groupFullPathName }, new String[] { "roleFullPathName", - "groupFullPathName" }, "removeRoleFromGroup(java.lang.String, java.lang.String)"); - + ArgUtil.notNull(new Object[] + {roleFullPathName, groupFullPathName}, new String[] + {"roleFullPathName", "groupFullPathName"}, + "removeRoleFromGroup(java.lang.String, java.lang.String)"); + // Get the role principal to remove. - Principal rolePrincipal = roleSecurityHandler.getRolePrincipal(roleFullPathName); + Principal rolePrincipal = roleSecurityHandler + .getRolePrincipal(roleFullPathName); if (null != rolePrincipal) { - securityMappingHandler.removeRolePrincipalInGroup(groupFullPathName, roleFullPathName); + securityMappingHandler.removeRolePrincipalInGroup( + groupFullPathName, roleFullPathName); } } @@ -375,14 +411,18 @@ * @see org.apache.jetspeed.security.RoleManager#isGroupInRole(java.lang.String, * java.lang.String) */ - public boolean isGroupInRole(String groupFullPathName, String roleFullPathName) throws SecurityException + public boolean isGroupInRole(String groupFullPathName, + String roleFullPathName) throws SecurityException { - ArgUtil.notNull(new Object[] { roleFullPathName, groupFullPathName }, new String[] { "roleFullPathName", - "groupFullPathName" }, "isGroupInRole(java.lang.String, java.lang.String)"); + ArgUtil.notNull(new Object[] + {roleFullPathName, groupFullPathName}, new String[] + {"roleFullPathName", "groupFullPathName"}, + "isGroupInRole(java.lang.String, java.lang.String)"); boolean isGroupInRole = false; - Set rolePrincipals = securityMappingHandler.getRolePrincipalsInGroup(groupFullPathName); + Set rolePrincipals = securityMappingHandler + .getRolePrincipalsInGroup(groupFullPathName); Principal rolePrincipal = new RolePrincipalImpl(roleFullPathName); if (rolePrincipals.contains(rolePrincipal)) { @@ -398,7 +438,8 @@ public Iterator getRoles(String filter) throws SecurityException { List roles = new LinkedList(); - Iterator rolePrincipals = roleSecurityHandler.getRolePrincipals(filter).iterator(); + Iterator rolePrincipals = roleSecurityHandler.getRolePrincipals(filter) + .iterator(); while (rolePrincipals.hasNext()) { String roleName = ((Principal) rolePrincipals.next()).getName(); @@ -408,21 +449,23 @@ return roles.iterator(); } - /** - * @see org.apache.jetspeed.security.RoleManager#setRoleEnabled(java.lang.String, boolean) + /** + * @see org.apache.jetspeed.security.RoleManager#setRoleEnabled(java.lang.String, + * boolean) */ - public void setRoleEnabled(String roleFullPathName, boolean enabled) throws SecurityException + public void setRoleEnabled(String roleFullPathName, boolean enabled) + throws SecurityException { - ArgUtil.notNull(new Object[] { roleFullPathName }, new String[] { "roleFullPathName" }, - "setRoleEnabled(java.lang.String,boolean)"); + ArgUtil.notNull(new Object[] + {roleFullPathName}, new String[] + {"roleFullPathName"}, "setRoleEnabled(java.lang.String,boolean)"); - RolePrincipalImpl rolePrincipal = (RolePrincipalImpl)roleSecurityHandler.getRolePrincipal(roleFullPathName); - if (null == rolePrincipal) + RolePrincipalImpl rolePrincipal = (RolePrincipalImpl) roleSecurityHandler + .getRolePrincipal(roleFullPathName); + if (null == rolePrincipal) { throw new SecurityException( + SecurityException.ROLE_DOES_NOT_EXIST.create(roleFullPathName)); } + if (enabled != rolePrincipal.isEnabled()) { - throw new SecurityException(SecurityException.ROLE_DOES_NOT_EXIST.create(roleFullPathName)); - } - if ( enabled != rolePrincipal.isEnabled() ) - { rolePrincipal.setEnabled(enabled); roleSecurityHandler.setRolePrincipal(rolePrincipal); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RolePrincipalImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RolePrincipalImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/RolePrincipalImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,11 +19,15 @@ import org.apache.jetspeed.security.RolePrincipal; /** - * <p>{@link RolePrincipal} interface implementation.</p> + * <p> + * {@link RolePrincipal} interface implementation. + * </p> + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: RolePrincipalImpl.java 592149 2007-11-05 21:05:25Z taylor $ */ -public class RolePrincipalImpl extends BasePrincipalImpl implements RolePrincipal +public class RolePrincipalImpl extends BasePrincipalImpl implements + RolePrincipal { /** The serial version uid. */ @@ -36,65 +40,86 @@ RolePrincipalImpl.hiearchicalNames = hierarchicalNames; return null; } - + /** - * <p>The role principal constructor.</p> - * @param roleName The role principal name. + * <p> + * The role principal constructor. + * </p> + * + * @param roleName + * The role principal name. */ public RolePrincipalImpl(String roleName) { this(roleName, true, false); } - - public RolePrincipalImpl(String roleName, boolean isEnabled, boolean isMapping) + + public RolePrincipalImpl(String roleName, boolean isEnabled, + boolean isMapping) { super(roleName, PREFS_ROLE_ROOT, hiearchicalNames, isEnabled, isMapping); } - /** - * <p>Compares this principal to the specified object. Returns true - * if the object passed in matches the principal represented by - * the implementation of this interface.</p> - * @param another Principal to compare with. - * @return True if the principal passed in is the same as that - * encapsulated by this principal, and false otherwise. + * <p> + * Compares this principal to the specified object. Returns true if the + * object passed in matches the principal represented by the implementation + * of this interface. + * </p> + * + * @param another + * Principal to compare with. + * @return True if the principal passed in is the same as that encapsulated + * by this principal, and false otherwise. */ public boolean equals(Object another) { - if (!(another instanceof RolePrincipalImpl)) - { - return false; - } + if (!(another instanceof RolePrincipalImpl)) { return false; } RolePrincipalImpl principal = (RolePrincipalImpl) another; return this.getName().equals(principal.getName()); } /** - * <p>Gets the principal implementation full path from the principal name.</p> - * <p>Prepends PREFS_ROLE_ROOT if not prepended.</p> - * @param name The principal name. + * <p> + * Gets the principal implementation full path from the principal name. + * </p> + * <p> + * Prepends PREFS_ROLE_ROOT if not prepended. + * </p> + * + * @param name + * The principal name. * @return The preferences full path / principal name. */ public static String getFullPathFromPrincipalName(String name) { - return BasePrincipalImpl.getFullPathFromPrincipalName(name, PREFS_ROLE_ROOT, hiearchicalNames); + return BasePrincipalImpl.getFullPathFromPrincipalName(name, + PREFS_ROLE_ROOT, hiearchicalNames); } /** - * <p>Gets the principal name from the principal implementation full path.</p> - * <p>Remove prepended PREFS_ROLE_ROOT if present.</p> - * @param fullPath The principal full path. + * <p> + * Gets the principal name from the principal implementation full path. + * </p> + * <p> + * Remove prepended PREFS_ROLE_ROOT if present. + * </p> + * + * @param fullPath + * The principal full path. * @return The principal name. */ public static String getPrincipalNameFromFullPath(String fullPath) { - return BasePrincipalImpl.getPrincipalNameFromFullPath(fullPath, PREFS_ROLE_ROOT, hiearchicalNames); + return BasePrincipalImpl.getPrincipalNameFromFullPath(fullPath, + PREFS_ROLE_ROOT, hiearchicalNames); } - - public static String getFullPathFromPrincipalName(String name, String prefsRoot) + + public static String getFullPathFromPrincipalName(String name, + String prefsRoot) { - return BasePrincipalImpl.getFullPathFromPrincipalName(name, prefsRoot, hiearchicalNames); + return BasePrincipalImpl.getFullPathFromPrincipalName(name, prefsRoot, + hiearchicalNames); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/SecurityProviderImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/SecurityProviderImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/SecurityProviderImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,7 +24,7 @@ /** * @author <a href="">David Le Strat </a> - * + * */ public class SecurityProviderImpl implements SecurityProvider { @@ -47,13 +47,18 @@ * handlers. * </p> * - * @param atnProviderProxy The authentication provider. - * @param roleSecurityHandler The role security handler. - * @param groupSecurityHandler The group security handler. - * @param securityMappingHandler The security mapping handler. + * @param atnProviderProxy + * The authentication provider. + * @param roleSecurityHandler + * The role security handler. + * @param groupSecurityHandler + * The group security handler. + * @param securityMappingHandler + * The security mapping handler. */ public SecurityProviderImpl(AuthenticationProviderProxy atnProviderProxy, - RoleSecurityHandler roleSecurityHandler, GroupSecurityHandler groupSecurityHandler, + RoleSecurityHandler roleSecurityHandler, + GroupSecurityHandler groupSecurityHandler, SecurityMappingHandler securityMappingHandler) { // The authentication provider proxy. Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,25 +23,37 @@ import org.apache.jetspeed.security.User; /** - * <p>A user made of a {@link Subject} and the user {@link Preferences}.</p> + * <p> + * A user made of a {@link Subject} and the user {@link Preferences}. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public class UserImpl implements User { + private Subject subject; + private Preferences preferences; /** - * <p>Default constructor.</p> + * <p> + * Default constructor. + * </p> */ public UserImpl() { } - + /** - * <p>{@link User} constructor given a subject and preferences.</p> - * @param subject The subject. - * @param preferences The preferences. + * <p> + * {@link User} constructor given a subject and preferences. + * </p> + * + * @param subject + * The subject. + * @param preferences + * The preferences. */ public UserImpl(Subject subject, Preferences preferences) { @@ -83,10 +95,8 @@ public Preferences getUserAttributes() { - if (preferences != null) - { - return preferences.node(USER_INFO_PROPERTY_SET); - } + if (preferences != null) { return preferences + .node(USER_INFO_PROPERTY_SET); } return null; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserManagerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserManagerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserManagerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -62,14 +62,16 @@ private SecurityMappingHandler securityMappingHandler = null; private String anonymousUser = "guest"; + private User guest = null; - - /** - * Flag whether the principals's user group matches the user group to which the role has been mapped. (See SRV.12.4) - * If this flag is set to true, roles can be inherited to users via groups. + + /** + * Flag whether the principals's user group matches the user group to which + * the role has been mapped. (See SRV.12.4) If this flag is set to true, + * roles can be inherited to users via groups. */ private boolean rolesInheritableViaGroups = true; - + /** * @param securityProvider * The security provider. @@ -160,12 +162,12 @@ { return this.anonymousUser; } - + public void setRolesInheritableViaGroups(boolean rolesInheritableViaGroups) { this.rolesInheritableViaGroups = rolesInheritableViaGroups; } - + /** * @see org.apache.jetspeed.security.UserManager#authenticate(java.lang.String, * java.lang.String) @@ -173,8 +175,8 @@ public boolean authenticate(String username, String password) { ArgUtil.notNull(new Object[] - { username, password}, new String[] - { "username", "password"}, + {username, password}, new String[] + {"username", "password"}, "authenticate(java.lang.String, java.lang.String)"); boolean authenticated = false; @@ -189,7 +191,8 @@ log.debug("Authenticated user: " + username); } } - } catch (SecurityException e) + } + catch (SecurityException e) { // ignore: not authenticated } @@ -204,15 +207,13 @@ throws SecurityException { ArgUtil.notNull(new Object[] - { username}, new String[] - { "username"}, "addUser(java.lang.String, java.lang.String)"); + {username}, new String[] + {"username"}, "addUser(java.lang.String, java.lang.String)"); createUser(username, password, atnProviderProxy - .getDefaultAuthenticationProvider(),false); + .getDefaultAuthenticationProvider(), false); } - - /** * @see org.apache.jetspeed.security.UserManager#addUser(java.lang.String, * java.lang.String, java.lang.String) @@ -221,8 +222,8 @@ throws SecurityException { ArgUtil.notNull(new Object[] - { username}, new String[] - { "username"}, "addUser(java.lang.String, java.lang.String)"); + {username}, new String[] + {"username"}, "addUser(java.lang.String, java.lang.String)"); createUser(username, password, atnProviderName, false); } @@ -235,46 +236,48 @@ throws SecurityException { ArgUtil.notNull(new Object[] - { username}, new String[] - { "username"}, "addUser(java.lang.String, java.lang.String)"); + {username}, new String[] + {"username"}, "addUser(java.lang.String, java.lang.String)"); createUser(username, password, atnProviderProxy - .getDefaultAuthenticationProvider(),passThrough); + .getDefaultAuthenticationProvider(), passThrough); } /** * @see org.apache.jetspeed.security.UserManager#importUser(java.lang.String, * java.lang.String, java.lang.String, boolean) */ - public void importUser(String username, String password, String atnProviderName, boolean passThrough) + public void importUser(String username, String password, + String atnProviderName, boolean passThrough) throws SecurityException { ArgUtil.notNull(new Object[] - { username}, new String[] - { "username"}, "addUser(java.lang.String, java.lang.String)"); + {username}, new String[] + {"username"}, "addUser(java.lang.String, java.lang.String)"); - createUser(username, password, atnProviderName,passThrough); + createUser(username, password, atnProviderName, passThrough); } + /** * @see org.apache.jetspeed.security.UserManager#addUser(java.lang.String, * java.lang.String, java.lang.String) */ - protected void createUser(String username, String password, String atnProviderName, boolean raw) - throws SecurityException + protected void createUser(String username, String password, + String atnProviderName, boolean raw) throws SecurityException { ArgUtil .notNull(new Object[] - { username, atnProviderName}, new String[] - { "username", "atnProviderName"}, + {username, atnProviderName}, new String[] + {"username", "atnProviderName"}, "addUser(java.lang.String, java.lang.String, java.lang.String)"); -// if (getAnonymousUser().equals(username)) { throw new SecurityException( -// SecurityException.ANONYMOUS_USER_PROTECTED.create(username)); } + // if (getAnonymousUser().equals(username)) { throw new + // SecurityException( + // SecurityException.ANONYMOUS_USER_PROTECTED.create(username)); } // Check if user already exists. - if (userExists(username)) { - throw new SecurityException(SecurityException.USER_ALREADY_EXISTS.create(username)); - } + if (userExists(username)) { throw new SecurityException( + SecurityException.USER_ALREADY_EXISTS.create(username)); } UserPrincipal userPrincipal = new UserPrincipalImpl(username); String fullPath = userPrincipal.getFullPath(); @@ -296,10 +299,12 @@ try { // Set private password credential - if (raw) - atnProviderProxy.importPassword(username, password,atnProviderName); - else - atnProviderProxy.setPassword(username, null, password,atnProviderName); + if (raw) + atnProviderProxy.importPassword(username, password, + atnProviderName); + else + atnProviderProxy.setPassword(username, null, + password, atnProviderName); } catch (SecurityException se1) { @@ -310,7 +315,10 @@ } catch (SecurityException se2) { - log.error("Failed to rollback created user after its password turned out to be invalid", se2); + log + .error( + "Failed to rollback created user after its password turned out to be invalid", + se2); } throw se1; } @@ -320,7 +328,8 @@ log.debug("Added user: " + fullPath); } } - } catch (SecurityException se) + } + catch (SecurityException se) { log.error(se.getMessage(), se); @@ -328,7 +337,8 @@ try { preferences.removeNode(); - } catch (BackingStoreException bse) + } + catch (BackingStoreException bse) { bse.printStackTrace(); } @@ -336,8 +346,6 @@ } } - - /** * @see org.apache.jetspeed.security.UserManager#removeUser(java.lang.String) * @@ -346,8 +354,8 @@ public void removeUser(String username) throws SecurityException { ArgUtil.notNull(new Object[] - { username}, new String[] - { "username"}, "removeUser(java.lang.String)"); + {username}, new String[] + {"username"}, "removeUser(java.lang.String)"); if (getAnonymousUser().equals(username)) { throw new SecurityException( SecurityException.ANONYMOUS_USER_PROTECTED.create(username)); } @@ -359,7 +367,8 @@ try { preferences.removeNode(); - } catch (BackingStoreException bse) + } + catch (BackingStoreException bse) { bse.printStackTrace(); } @@ -371,8 +380,8 @@ public boolean userExists(String username) { ArgUtil.notNull(new Object[] - { username}, new String[] - { "username"}, "userExists(java.lang.String)"); + {username}, new String[] + {"username"}, "userExists(java.lang.String)"); return atnProviderProxy.getUserPrincipal(username) != null; } @@ -383,35 +392,36 @@ public User getUser(String username) throws SecurityException { ArgUtil.notNull(new Object[] - { username}, new String[] - { "username"}, "getUser(java.lang.String)"); + {username}, new String[] + {"username"}, "getUser(java.lang.String)"); // optimize guest lookups as they can be excessive if (guest != null && getAnonymousUser().equals(username)) { - // TODO: need to handle caching issues + // TODO: need to handle caching issues return guest; } - + Set principals = new PrincipalsSet(); String fullPath = (new UserPrincipalImpl(username)).getFullPath(); Principal userPrincipal = atnProviderProxy.getUserPrincipal(username); - if (null == userPrincipal) { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(username)); - } + if (null == userPrincipal) { throw new SecurityException( + SecurityException.USER_DOES_NOT_EXIST.create(username)); } principals.add(userPrincipal); principals.addAll(securityMappingHandler.getRolePrincipals(username)); - Set groupPrincipals = securityMappingHandler.getGroupPrincipals(username); + Set groupPrincipals = securityMappingHandler + .getGroupPrincipals(username); principals.addAll(groupPrincipals); - + if (this.rolesInheritableViaGroups) { - for (Iterator it = groupPrincipals.iterator(); it.hasNext(); ) + for (Iterator it = groupPrincipals.iterator(); it.hasNext();) { Principal groupPrincipal = (Principal) it.next(); - Set rolePrincipalsInGroup = securityMappingHandler.getRolePrincipalsInGroup(groupPrincipal.getName()); + Set rolePrincipalsInGroup = securityMappingHandler + .getRolePrincipalsInGroup(groupPrincipal.getName()); principals.addAll(rolePrincipalsInGroup); } } @@ -421,7 +431,8 @@ { subject = new Subject(true, principals, new HashSet(), new HashSet()); - } else + } + else { subject = new Subject(true, principals, atnProviderProxy .getPublicCredentials(username), atnProviderProxy @@ -459,7 +470,8 @@ public Iterator getUserNames(String filter) throws SecurityException { List usernames = new LinkedList(); - Iterator userPrincipals = atnProviderProxy.getUserPrincipals(filter).iterator(); + Iterator userPrincipals = atnProviderProxy.getUserPrincipals(filter) + .iterator(); while (userPrincipals.hasNext()) { usernames.add(((Principal) userPrincipals.next()).getName()); @@ -474,8 +486,8 @@ throws SecurityException { ArgUtil.notNull(new Object[] - { roleFullPathName}, new String[] - { "roleFullPathName"}, "getUsersInRole(java.lang.String)"); + {roleFullPathName}, new String[] + {"roleFullPathName"}, "getUsersInRole(java.lang.String)"); Collection users = new ArrayList(); @@ -497,8 +509,8 @@ throws SecurityException { ArgUtil.notNull(new Object[] - { groupFullPathName}, new String[] - { "groupFullPathName"}, "getUsersInGroup(java.lang.String)"); + {groupFullPathName}, new String[] + {"groupFullPathName"}, "getUsersInGroup(java.lang.String)"); Collection users = new ArrayList(); @@ -524,8 +536,8 @@ { ArgUtil .notNull(new Object[] - { username, newPassword}, new String[] - { "username", "newPassword"}, + {username, newPassword}, new String[] + {"username", "newPassword"}, "setPassword(java.lang.String, java.lang.String, java.lang.String)"); if (getAnonymousUser().equals(username)) { throw new SecurityException( @@ -541,8 +553,8 @@ throws SecurityException { ArgUtil.notNull(new Object[] - { userName,}, new String[] - { "userName"}, "setPasswordEnabled(java.lang.String, boolean)"); + {userName,}, new String[] + {"userName"}, "setPasswordEnabled(java.lang.String, boolean)"); if (getAnonymousUser().equals(userName)) { throw new SecurityException( SecurityException.ANONYMOUS_USER_PROTECTED.create(userName)); } @@ -557,34 +569,33 @@ boolean updateRequired) throws SecurityException { ArgUtil.notNull(new Object[] - { userName,}, new String[] - { "userName"}, "setPasswordUpdateRequired(java.lang.String, boolean)"); + {userName,}, new String[] + {"userName"}, "setPasswordUpdateRequired(java.lang.String, boolean)"); if (getAnonymousUser().equals(userName)) { throw new SecurityException( SecurityException.ANONYMOUS_USER_PROTECTED.create(userName)); } atnProviderProxy.setPasswordUpdateRequired(userName, updateRequired); } - - + /** - * @see org.apache.jetspeed.security.UserManager#setUserEnabled(java.lang.String, boolean) + * @see org.apache.jetspeed.security.UserManager#setUserEnabled(java.lang.String, + * boolean) */ - public void setUserEnabled(String userName, boolean enabled) throws SecurityException + public void setUserEnabled(String userName, boolean enabled) + throws SecurityException { - ArgUtil.notNull(new Object[] { userName, }, new String[] { "userName" }, - "setUserEnabled(java.lang.String, boolean)"); + ArgUtil.notNull(new Object[] + {userName,}, new String[] + {"userName"}, "setUserEnabled(java.lang.String, boolean)"); - if (getAnonymousUser().equals(userName)) - { - throw new SecurityException(SecurityException.ANONYMOUS_USER_PROTECTED.create(userName)); - } + if (getAnonymousUser().equals(userName)) { throw new SecurityException( + SecurityException.ANONYMOUS_USER_PROTECTED.create(userName)); } - UserPrincipalImpl userPrincipal = (UserPrincipalImpl)atnProviderProxy.getUserPrincipal(userName); - if (null == userPrincipal) - { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(userName)); - } - if ( enabled != userPrincipal.isEnabled() ) + UserPrincipalImpl userPrincipal = (UserPrincipalImpl) atnProviderProxy + .getUserPrincipal(userName); + if (null == userPrincipal) { throw new SecurityException( + SecurityException.USER_DOES_NOT_EXIST.create(userName)); } + if (enabled != userPrincipal.isEnabled()) { userPrincipal.setEnabled(enabled); atnProviderProxy.updateUserPrincipal(userPrincipal); @@ -592,18 +603,18 @@ } /** - * @see org.apache.jetspeed.security.UserManager#setPasswordExpiration(java.lang.String, java.sql.Date) + * @see org.apache.jetspeed.security.UserManager#setPasswordExpiration(java.lang.String, + * java.sql.Date) */ - public void setPasswordExpiration(String userName, Date expirationDate) throws SecurityException + public void setPasswordExpiration(String userName, Date expirationDate) + throws SecurityException { ArgUtil.notNull(new Object[] - { userName,}, new String[] - { "userName"}, "setPasswordExpiration(java.lang.String, java.sql.Date)"); + {userName,}, new String[] + {"userName"}, "setPasswordExpiration(java.lang.String, java.sql.Date)"); - if (getAnonymousUser().equals(userName)) - { - throw new SecurityException(SecurityException.ANONYMOUS_USER_PROTECTED.create(userName)); - } + if (getAnonymousUser().equals(userName)) { throw new SecurityException( + SecurityException.ANONYMOUS_USER_PROTECTED.create(userName)); } atnProviderProxy.setPasswordExpiration(userName, expirationDate); } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserPrincipalImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserPrincipalImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserPrincipalImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,86 +19,113 @@ import org.apache.jetspeed.security.UserPrincipal; /** - * <p>{@link UserPrincipal} interface implementation.</p> + * <p> + * {@link UserPrincipal} interface implementation. + * </p> + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: UserPrincipalImpl.java 592149 2007-11-05 21:05:25Z taylor $ */ -public class UserPrincipalImpl extends BasePrincipalImpl implements UserPrincipal +public class UserPrincipalImpl extends BasePrincipalImpl implements + UserPrincipal { /** The serial version uid. */ private static final long serialVersionUID = 4134905654850335230L; - + private static boolean hiearchicalNames = true; - public static final Object useHierarchicalNames(boolean hierarchicalNames) { UserPrincipalImpl.hiearchicalNames = hierarchicalNames; return null; } - + /** - * <p>The user principal constructor.</p> - * @param userName The user principal name. + * <p> + * The user principal constructor. + * </p> + * + * @param userName + * The user principal name. */ public UserPrincipalImpl(String userName) { - this(userName, true, false); + this(userName, true, false); } public UserPrincipalImpl(String userName, boolean isMapping) { - this(userName, true, isMapping); + this(userName, true, isMapping); } - - public UserPrincipalImpl(String userName, boolean isEnabled, boolean isMapping) + + public UserPrincipalImpl(String userName, boolean isEnabled, + boolean isMapping) { super(userName, PREFS_USER_ROOT, hiearchicalNames, isEnabled, isMapping); } - + /** - * <p>Compares this principal to the specified object. Returns true - * if the object passed in matches the principal represented by - * the implementation of this interface.</p> - * @param another Principal to compare with. - * @return True if the principal passed in is the same as that - * encapsulated by this principal, and false otherwise. - + * <p> + * Compares this principal to the specified object. Returns true if the + * object passed in matches the principal represented by the implementation + * of this interface. + * </p> + * + * @param another + * Principal to compare with. + * @return True if the principal passed in is the same as that encapsulated + * by this principal, and false otherwise. + * */ public boolean equals(Object another) { - if (!(another instanceof UserPrincipalImpl)) - return false; + if (!(another instanceof UserPrincipalImpl)) return false; UserPrincipalImpl principal = (UserPrincipalImpl) another; return this.getName().equals(principal.getName()); } /** - * <p>Gets the principal implementation full path from the principal name.</p> - * <p>Prepends PREFS_USER_ROOT if not prepended.</p> - * @param name The principal name. + * <p> + * Gets the principal implementation full path from the principal name. + * </p> + * <p> + * Prepends PREFS_USER_ROOT if not prepended. + * </p> + * + * @param name + * The principal name. * @return The preferences full path / principal name. */ public static String getFullPathFromPrincipalName(String name) { - return BasePrincipalImpl.getFullPathFromPrincipalName(name, PREFS_USER_ROOT, hiearchicalNames); + return BasePrincipalImpl.getFullPathFromPrincipalName(name, + PREFS_USER_ROOT, hiearchicalNames); } /** - * <p>Gets the principal name from the principal implementation full path.</p> - * <p>Remove prepended PREFS_GROUP_ROOT if present.</p> - * @param fullPath The principal full path. + * <p> + * Gets the principal name from the principal implementation full path. + * </p> + * <p> + * Remove prepended PREFS_GROUP_ROOT if present. + * </p> + * + * @param fullPath + * The principal full path. * @return The principal name. */ public static String getPrincipalNameFromFullPath(String fullPath) { - return BasePrincipalImpl.getPrincipalNameFromFullPath(fullPath, PREFS_USER_ROOT, hiearchicalNames); + return BasePrincipalImpl.getPrincipalNameFromFullPath(fullPath, + PREFS_USER_ROOT, hiearchicalNames); } - public static String getFullPathFromPrincipalName(String name, String prefsRoot) + public static String getFullPathFromPrincipalName(String name, + String prefsRoot) { - return BasePrincipalImpl.getFullPathFromPrincipalName(name, prefsRoot, hiearchicalNames); + return BasePrincipalImpl.getFullPathFromPrincipalName(name, prefsRoot, + hiearchicalNames); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserSubjectPrincipalImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserSubjectPrincipalImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/UserSubjectPrincipalImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,31 +22,40 @@ import org.apache.jetspeed.security.UserSubjectPrincipal; /** - * <p>{@link UserPrincipal} interface implementation.</p> + * <p> + * {@link UserPrincipal} interface implementation. + * </p> + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: UserPrincipalImpl.java 331065 2005-11-06 03:40:32Z dlestrat $ */ -public class UserSubjectPrincipalImpl extends UserPrincipalImpl implements UserSubjectPrincipal +public class UserSubjectPrincipalImpl extends UserPrincipalImpl implements + UserSubjectPrincipal { /** The serial version uid. */ private static final long serialVersionUID = 4134905654850335230L; + protected Subject subject; /** - * <p>The user principal constructor.</p> - * @param userName The user principal name. + * <p> + * The user principal constructor. + * </p> + * + * @param userName + * The user principal name. */ public UserSubjectPrincipalImpl(String userName) { - super(userName); + super(userName); } public void setSubject(Subject subject) { this.subject = subject; } - + public Subject getSubject() { return subject; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/ext/JBossLoginModule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/ext/JBossLoginModule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/impl/ext/JBossLoginModule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.impl.ext; import java.security.Principal; @@ -31,16 +31,21 @@ import org.apache.jetspeed.security.impl.RolePrincipalImpl; /** - * <p>Configures Subject principals for JBoss JAAS implementation + * <p> + * Configures Subject principals for JBoss JAAS implementation + * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> */ public class JBossLoginModule extends DefaultLoginModule { + private static class JBossGroup implements Group { + private String name; + private ArrayList members = new ArrayList(); - + public JBossGroup(String name, List members) { this.name = name; @@ -49,7 +54,7 @@ public boolean addMember(Principal user) { - if ( !isMember(user) ) + if (!isMember(user)) { members.add(user); return true; @@ -75,31 +80,34 @@ public String getName() { return name; - } + } } - + /** * Create a new JBoss login module */ - public JBossLoginModule () { - super (); + public JBossLoginModule() + { + super(); } /** * Create a new JBoss login module that uses the given user manager. + * * @param userManager * @see DefaultLoginModule#DefaultLoginModule(UserManager) */ - protected JBossLoginModule (UserManager userManager) { - super (userManager); + protected JBossLoginModule(UserManager userManager) + { + super(userManager); } - + protected void commitPrincipals(Subject subject, User user) { // add UserPrincipal to subject subject.getPrincipals().add(getUserPrincipal(user)); JBossGroup roles = new JBossGroup("Roles", getUserRoles(user)); roles.addMember(new RolePrincipalImpl(portalUserRole)); - subject.getPrincipals().add(roles); + subject.getPrincipals().add(roles); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalCredentialImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalCredentialImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalCredentialImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,31 +22,44 @@ import org.apache.jetspeed.security.om.InternalCredential; /** - * <p>{@link InternalCredential} interface implementation.</p> + * <p> + * {@link InternalCredential} interface implementation. + * </p> * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> * @version $Id: InternalCredentialImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class InternalCredentialImpl implements InternalCredential { + /** The serial version uid. */ private static final long serialVersionUID = -8064404995292602590L; /** - * <p>InternalCredential implementation default constructor.</p> + * <p> + * InternalCredential implementation default constructor. + * </p> */ public InternalCredentialImpl() { } /** - * <p>InternalCredentialImpl constructor given a value, type and classname.</p> - * @param principalId The principal id. - * @param value The value. - * @param type The type. - * @param classname The classname. + * <p> + * InternalCredentialImpl constructor given a value, type and classname. + * </p> + * + * @param principalId + * The principal id. + * @param value + * The value. + * @param type + * The type. + * @param classname + * The classname. */ - public InternalCredentialImpl(long principalId, String value, int type, String classname) + public InternalCredentialImpl(long principalId, String value, int type, + String classname) { this.principalId = principalId; this.value = value; @@ -55,13 +68,20 @@ this.creationDate = new Timestamp(new java.util.Date().getTime()); this.modifiedDate = this.creationDate; } - + /** - * <p>InternalCredentialImpl copy constructor given another InternalCredential and overriding classname</p> - * @param credential The credential to copy from - * @param classname The classname for the new credential + * <p> + * InternalCredentialImpl copy constructor given another InternalCredential + * and overriding classname + * </p> + * + * @param credential + * The credential to copy from + * @param classname + * The classname for the new credential */ - public InternalCredentialImpl(InternalCredential credential, String classname) + public InternalCredentialImpl(InternalCredential credential, + String classname) { this.authenticationFailures = credential.getAuthenticationFailures(); this.classname = classname; @@ -70,7 +90,8 @@ this.encoded = credential.isEncoded(); this.expirationDate = credential.getExpirationDate(); this.expired = credential.isExpired(); - this.previousAuthenticationDate = credential.getPreviousAuthenticationDate(); + this.previousAuthenticationDate = credential + .getPreviousAuthenticationDate(); this.lastAuthenticationDate = credential.getLastAuthenticationDate(); this.modifiedDate = credential.getModifiedDate(); this.principalId = credential.getPrincipalId(); @@ -132,9 +153,9 @@ { this.value = value; } - + private boolean updateRequired; - + /** * @see org.apache.jetspeed.security.om.InternalCredential#isUpdateRequired() */ @@ -142,7 +163,7 @@ { return updateRequired; } - + /* * @see org.apache.jetspeed.security.om.InternalCredential#setUpdateRequired(boolean) */ @@ -150,46 +171,46 @@ { this.updateRequired = updateRequired; } - + private boolean encoded; - - /** + + /** * @see org.apache.jetspeed.security.om.InternalCredential#isEncoded() */ public boolean isEncoded() { return encoded; } - - /** + + /** * @see org.apache.jetspeed.security.om.InternalCredential#setEncoded(boolean) */ public void setEncoded(boolean encoded) { this.encoded = encoded; } - + private boolean enabled = true; - - /** + + /** * @see org.apache.jetspeed.security.om.InternalCredential#isEnabled() */ public boolean isEnabled() { return enabled; } - - /** + + /** * @see org.apache.jetspeed.security.om.InternalCredential#setEnabled(boolean) */ public void setEnabled(boolean enabled) { this.enabled = enabled; } - + private int authenticationFailures; - - /** + + /** * @see org.apache.jetspeed.security.om.InternalCredential#getAuthenticationFailures() */ public int getAuthenticationFailures() @@ -206,7 +227,7 @@ } private boolean expired; - + /** * @see org.apache.jetspeed.security.om.InternalCredential#isExpired() */ @@ -222,9 +243,9 @@ { this.expired = expired; } - + private Date expirationDate; - + /** * @see org.apache.jetspeed.security.om.InternalCredential#getExpirationDate() */ @@ -240,7 +261,7 @@ { this.expirationDate = expirationDate; } - + private int type; /** @@ -322,17 +343,18 @@ { return previousAuthenticationDate; } - + /** * @see org.apache.jetspeed.security.om.InternalCredential#setPreviousAuthenticationDate(java.sql.Timestamp) */ - public void setPreviousAuthenticationDate(Timestamp previousAuthenticationDate) + public void setPreviousAuthenticationDate( + Timestamp previousAuthenticationDate) { this.previousAuthenticationDate = previousAuthenticationDate; } private Timestamp lastAuthenticationDate; - + /** * @see org.apache.jetspeed.security.om.InternalCredential#getLastAuthenticationDate() */ @@ -340,7 +362,7 @@ { return lastAuthenticationDate; } - + /** * @see org.apache.jetspeed.security.om.InternalCredential#setLastAuthenticationDate(java.sql.Timestamp) */ @@ -348,44 +370,76 @@ { this.lastAuthenticationDate = lastAuthenticationDate; } - + /** - * <p>Compares this {@link InternalCredential} to the provided credential - * and check if they are equal.</p> + * <p> + * Compares this {@link InternalCredential} to the provided credential and + * check if they are equal. + * </p> * return Whether the {@link InternalCredential} are equal. */ public boolean equals(Object object) - { - if (!(object instanceof InternalCredential)) - return false; + { + if (!(object instanceof InternalCredential)) return false; InternalCredential c = (InternalCredential) object; - boolean isEqual = (((null == c.getClassname()) || (c.getClassname().equals(this.getClassname()))) && - (c.getValue().equals(this.getValue())) && - (c.getType() == this.getType())); + boolean isEqual = (((null == c.getClassname()) || (c.getClassname() + .equals(this.getClassname()))) + && (c.getValue().equals(this.getValue())) && (c.getType() == this + .getType())); return isEqual; } /** - * <p>Convert <code>Node</code> to string.</p> + * <p> + * Convert <code>Node</code> to string. + * </p> + * * @return The Node string value. */ public String toString() { - String toStringCredential = "[[principalId, " + this.principalId + "], " - + "[value, " + this.value + "], " - + "[updateRequired, " + this.updateRequired + "], " - + "[encoded, " + this.encoded + "], " - + "[enabled, " + this.enabled + "], " - + "[authenticationFailures, "+ this.authenticationFailures + "], " - + "[expired, "+ this.expired + "], " - + "[type, " + this.type + "], " - + "[classname, " + this.classname + "], " - + "[creationDate, " + this.creationDate + "], " - + "[modifiedDate, " + this.modifiedDate + "], " - + "[previousAuthenticationDate, " + this.previousAuthenticationDate + "]" - + "[lastAuthenticationDate, " + this.lastAuthenticationDate + "]" - + (expirationDate != null ? (", [expirationDate, "+ this.expirationDate + "]]") : "]"); + String toStringCredential = "[[principalId, " + + this.principalId + + "], " + + "[value, " + + this.value + + "], " + + "[updateRequired, " + + this.updateRequired + + "], " + + "[encoded, " + + this.encoded + + "], " + + "[enabled, " + + this.enabled + + "], " + + "[authenticationFailures, " + + this.authenticationFailures + + "], " + + "[expired, " + + this.expired + + "], " + + "[type, " + + this.type + + "], " + + "[classname, " + + this.classname + + "], " + + "[creationDate, " + + this.creationDate + + "], " + + "[modifiedDate, " + + this.modifiedDate + + "], " + + "[previousAuthenticationDate, " + + this.previousAuthenticationDate + + "]" + + "[lastAuthenticationDate, " + + this.lastAuthenticationDate + + "]" + + (expirationDate != null ? (", [expirationDate, " + + this.expirationDate + "]]") : "]"); return toStringCredential; - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalGroupPrincipalImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalGroupPrincipalImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalGroupPrincipalImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,20 +22,30 @@ import org.apache.jetspeed.security.om.InternalGroupPrincipal; /** - * <p>{@link InternalGroupPrincipal} interface implementation.</p> + * <p> + * {@link InternalGroupPrincipal} interface implementation. + * </p> * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ -public class InternalGroupPrincipalImpl extends InternalPrincipalImpl implements InternalGroupPrincipal +public class InternalGroupPrincipalImpl extends InternalPrincipalImpl implements + InternalGroupPrincipal { + /** The serial version uid. */ private static final long serialVersionUID = -8236429453373927824L; - - /** <p>Group principal security class.</p> */ + + /** + * <p> + * Group principal security class. + * </p> + */ static String GROUP_PRINCIPAL_CLASSNAME = "org.apache.jetspeed.security.InternalGroupPrincipalImpl"; /** - * <p>Group principal implementation default constructor.</p> + * <p> + * Group principal implementation default constructor. + * </p> */ public InternalGroupPrincipalImpl() { @@ -43,13 +53,17 @@ } /** - * <p>Constructor to create a new group principal.</p> - * @param fullPath The group full path. + * <p> + * Constructor to create a new group principal. + * </p> + * + * @param fullPath + * The group full path. */ public InternalGroupPrincipalImpl(String fullPath) { - super(GROUP_PRINCIPAL_CLASSNAME, fullPath); - this.rolePrincipals = new ArrayList(); + super(GROUP_PRINCIPAL_CLASSNAME, fullPath); + this.rolePrincipals = new ArrayList(); } private Collection userPrincipals; @@ -89,14 +103,15 @@ } /** - * <p>Compares this {@link InternalGroupPrincipal} to the provided group principal - * and check if they are equal.</p> + * <p> + * Compares this {@link InternalGroupPrincipal} to the provided group + * principal and check if they are equal. + * </p> * return Whether the {@link InternalGroupPrincipal} are equal. */ public boolean equals(Object object) - { - if (!(object instanceof InternalGroupPrincipal)) - return false; + { + if (!(object instanceof InternalGroupPrincipal)) return false; InternalGroupPrincipal r = (InternalGroupPrincipal) object; boolean isEqual = (r.getFullPath().equals(this.getFullPath())); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalPermissionImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalPermissionImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalPermissionImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,8 +22,10 @@ import org.apache.jetspeed.security.om.InternalPermission; /** - * <p>{@link InternalPermission} interface implementation.</p> - * + * <p> + * {@link InternalPermission} interface implementation. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public class InternalPermissionImpl implements InternalPermission @@ -33,17 +35,25 @@ private static final long serialVersionUID = 251708679848856538L; /** - * <p>InternalPermission implementation default constructor.</p> + * <p> + * InternalPermission implementation default constructor. + * </p> */ public InternalPermissionImpl() { } /** - * <p>InternalPermission constructor.</p> - * @param classname The classname. - * @param name The name. - * @param actions The actions. + * <p> + * InternalPermission constructor. + * </p> + * + * @param classname + * The classname. + * @param name + * The name. + * @param actions + * The actions. */ public InternalPermissionImpl(String classname, String name, String actions) { @@ -184,13 +194,13 @@ * @see org.apache.jetspeed.security.om.InternalPermission#equals(java.lang.Object) */ public boolean equals(Object object) - { - if (!(object instanceof InternalPermission)) - return false; + { + if (!(object instanceof InternalPermission)) return false; InternalPermission p = (InternalPermission) object; - boolean isEqual = - ((p.getClassname().equals(this.getClassname())) && (p.getName().equals(this.getName())) && (p.getActions().equals(this.getActions()))); + boolean isEqual = ((p.getClassname().equals(this.getClassname())) + && (p.getName().equals(this.getName())) && (p.getActions() + .equals(this.getActions()))); return isEqual; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalPrincipalImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalPrincipalImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalPrincipalImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,6 +31,7 @@ */ public class InternalPrincipalImpl implements InternalPrincipal { + /** The serial version uid. */ private static final long serialVersionUID = 3615655651128923549L; @@ -54,7 +55,7 @@ /** The modified date. */ private Timestamp modifiedDate; - + /** The enabled state. */ private boolean enabled = true; @@ -82,8 +83,10 @@ * InternalPrincipal constructor given a classname and name. * </p> * - * @param classname The classname. - * @param fullPath The full path. + * @param classname + * The classname. + * @param fullPath + * The full path. */ public InternalPrincipalImpl(String classname, String fullPath) { @@ -137,7 +140,8 @@ } /** - * @param isMappingOnly The isMappingOnly to set. + * @param isMappingOnly + * The isMappingOnly to set. */ public void setMappingOnly(boolean isMappingOnly) { @@ -208,19 +212,19 @@ this.modifiedDate = modifiedDate; } - /** + /** * @see org.apache.jetspeed.security.om.InternalPrincipal#isEnabled() */ public boolean isEnabled() { return enabled; } - - /** + + /** * @see org.apache.jetspeed.security.om.InternalPrincipal#setEnabled(boolean) */ public void setEnabled(boolean enabled) { this.enabled = enabled; - } + } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalRolePrincipalImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalRolePrincipalImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalRolePrincipalImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,20 +21,30 @@ import org.apache.jetspeed.security.om.InternalRolePrincipal; /** - * <p>{@link InternalRolePrincipal} interface implementation.</p> + * <p> + * {@link InternalRolePrincipal} interface implementation. + * </p> * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ -public class InternalRolePrincipalImpl extends InternalPrincipalImpl implements InternalRolePrincipal +public class InternalRolePrincipalImpl extends InternalPrincipalImpl implements + InternalRolePrincipal { + /** The serial version uid. */ private static final long serialVersionUID = 4422827842052325846L; - - /** <p>Role principal security class.</p> */ + + /** + * <p> + * Role principal security class. + * </p> + */ static String ROLE_PRINCIPAL_CLASSNAME = "org.apache.jetspeed.security.InternalRolePrincipalImpl"; /** - * <p>Role principal implementation default constructor.</p> + * <p> + * Role principal implementation default constructor. + * </p> */ public InternalRolePrincipalImpl() { @@ -42,8 +52,12 @@ } /** - * <p>Constructor to create a new role principal.</p> - * @param fullPath The role full path. + * <p> + * Constructor to create a new role principal. + * </p> + * + * @param fullPath + * The role full path. */ public InternalRolePrincipalImpl(String fullPath) { @@ -87,14 +101,15 @@ } /** - * <p>Compares this {@link InternalRolePrincipal} to the provided role principal - * and check if they are equal.</p> + * <p> + * Compares this {@link InternalRolePrincipal} to the provided role + * principal and check if they are equal. + * </p> * return Whether the {@link InternalRolePrincipal} are equal. */ public boolean equals(Object object) - { - if (!(object instanceof InternalRolePrincipal)) - return false; + { + if (!(object instanceof InternalRolePrincipal)) return false; InternalRolePrincipal r = (InternalRolePrincipal) object; boolean isEqual = (r.getFullPath().equals(this.getFullPath())); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalUserPrincipalImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalUserPrincipalImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/om/impl/InternalUserPrincipalImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,39 +22,53 @@ import org.apache.jetspeed.security.om.InternalUserPrincipal; /** - * <p>{@link InternalUserPrincipal} interface implementation.</p> + * <p> + * {@link InternalUserPrincipal} interface implementation. + * </p> * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ -public class InternalUserPrincipalImpl extends InternalPrincipalImpl implements InternalUserPrincipal +public class InternalUserPrincipalImpl extends InternalPrincipalImpl implements + InternalUserPrincipal { + /** The serial version uid. */ private static final long serialVersionUID = 6713096308414915156L; - /** <p>User principal security class.</p> */ + /** + * <p> + * User principal security class. + * </p> + */ static String USER_PRINCIPAL_CLASSNAME = "org.apache.jetspeed.security.InternalUserPrincipalImpl"; - + /** The credentials. */ private Collection credentials; - + /** The role principals. */ private Collection rolePrincipals; - + /** The group principals. */ private Collection groupPrincipals; /** - * <p>InternalUserPrincipal implementation default constructor.</p> + * <p> + * InternalUserPrincipal implementation default constructor. + * </p> */ public InternalUserPrincipalImpl() { super(); } - + /** - * <p>Constructor to create a new user principal and its credential given - * a username and password.</p> - * @param username The username. + * <p> + * Constructor to create a new user principal and its credential given a + * username and password. + * </p> + * + * @param username + * The username. */ public InternalUserPrincipalImpl(String username) { @@ -112,14 +126,15 @@ } /** - * <p>Compares this {@link InternalUserPrincipal} to the provided user principal - * and check if they are equal.</p> + * <p> + * Compares this {@link InternalUserPrincipal} to the provided user + * principal and check if they are equal. + * </p> * return Whether the {@link InternalUserPrincipal} are equal. */ public boolean equals(Object object) - { - if (!(object instanceof InternalUserPrincipal)) - return false; + { + if (!(object instanceof InternalUserPrincipal)) return false; InternalUserPrincipal r = (InternalUserPrincipal) object; boolean isEqual = (r.getFullPath().equals(this.getFullPath())); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/AbstractInternalPasswordCredentialInterceptorImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/AbstractInternalPasswordCredentialInterceptorImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/AbstractInternalPasswordCredentialInterceptorImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi.impl; import java.util.Collection; @@ -26,20 +26,25 @@ /** * <p> - * Base class providing default empty behavior for a {@link InternalPasswordCredentialInterceptor} - * implementation. + * Base class providing default empty behavior for a + * {@link InternalPasswordCredentialInterceptor} implementation. * </p> * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id$ */ -public abstract class AbstractInternalPasswordCredentialInterceptorImpl implements InternalPasswordCredentialInterceptor +public abstract class AbstractInternalPasswordCredentialInterceptorImpl + implements InternalPasswordCredentialInterceptor { + /** * @return false - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterLoad(org.apache.jetspeed.security.spi.PasswordCredentialProvider, java.lang.String, org.apache.jetspeed.security.om.InternalCredential) + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterLoad(org.apache.jetspeed.security.spi.PasswordCredentialProvider, + * java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential) */ - public boolean afterLoad(PasswordCredentialProvider pcProvider, String userName, InternalCredential credential) + public boolean afterLoad(PasswordCredentialProvider pcProvider, + String userName, InternalCredential credential) throws SecurityException { return false; @@ -47,27 +52,39 @@ /** * @return false - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterAuthenticated(org.apache.jetspeed.security.om.InternalUserPrincipal, java.lang.String, org.apache.jetspeed.security.om.InternalCredential, boolean) + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterAuthenticated(org.apache.jetspeed.security.om.InternalUserPrincipal, + * java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential, boolean) */ - public boolean afterAuthenticated(InternalUserPrincipal internalUser, String userName, - InternalCredential credential, boolean authenticated) throws SecurityException + public boolean afterAuthenticated(InternalUserPrincipal internalUser, + String userName, InternalCredential credential, + boolean authenticated) throws SecurityException { return false; } /** - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeCreate(org.apache.jetspeed.security.om.InternalUserPrincipal, java.util.Collection, java.lang.String, InternalCredential, java.lang.String) + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeCreate(org.apache.jetspeed.security.om.InternalUserPrincipal, + * java.util.Collection, java.lang.String, InternalCredential, + * java.lang.String) */ - public void beforeCreate(InternalUserPrincipal internalUser, Collection credentials, String userName, - InternalCredential credential, String password) throws SecurityException + public void beforeCreate(InternalUserPrincipal internalUser, + Collection credentials, String userName, + InternalCredential credential, String password) + throws SecurityException { } /** - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeSetPassword(org.apache.jetspeed.security.om.InternalUserPrincipal, java.util.Collection, java.lang.String, org.apache.jetspeed.security.om.InternalCredential, java.lang.String, boolean) + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeSetPassword(org.apache.jetspeed.security.om.InternalUserPrincipal, + * java.util.Collection, java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential, + * java.lang.String, boolean) */ - public void beforeSetPassword(InternalUserPrincipal internalUser, Collection credentials, String userName, - InternalCredential credential, String password, boolean authenticated) throws SecurityException + public void beforeSetPassword(InternalUserPrincipal internalUser, + Collection credentials, String userName, + InternalCredential credential, String password, + boolean authenticated) throws SecurityException { } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/AlgorithmUpgradePBEPasswordService.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/AlgorithmUpgradePBEPasswordService.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/AlgorithmUpgradePBEPasswordService.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,6 +21,7 @@ import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; + import org.apache.jetspeed.security.AlgorithmUpgradePasswordEncodingService; import org.apache.jetspeed.security.PasswordCredential; import org.apache.jetspeed.security.SecurityException; @@ -30,41 +31,59 @@ /** * <p> - * MessageDigestToPBEPasswordUpgradeService allows for migrating from a MessageDigestCredentialPasswordEncoder - * to the PBEPasswordService + * MessageDigestToPBEPasswordUpgradeService allows for migrating from a + * MessageDigestCredentialPasswordEncoder to the PBEPasswordService * </p> * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id:$ */ -public class AlgorithmUpgradePBEPasswordService extends PBEPasswordService implements AlgorithmUpgradeCredentialPasswordEncoder, AlgorithmUpgradePasswordEncodingService +public class AlgorithmUpgradePBEPasswordService extends PBEPasswordService + implements AlgorithmUpgradeCredentialPasswordEncoder, + AlgorithmUpgradePasswordEncodingService { + private CredentialPasswordEncoder oldEncoder; + private Timestamp startPBEPasswordEncoding; - - public AlgorithmUpgradePBEPasswordService(String pbePassword, CredentialPasswordEncoder oldEncoder, String startPBEPasswordEncoding) throws InvalidKeySpecException, + + public AlgorithmUpgradePBEPasswordService(String pbePassword, + CredentialPasswordEncoder oldEncoder, + String startPBEPasswordEncoding) throws InvalidKeySpecException, NoSuchAlgorithmException, ParseException { super(pbePassword); this.oldEncoder = oldEncoder; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - this.startPBEPasswordEncoding = new Timestamp(df.parse(startPBEPasswordEncoding).getTime()); + this.startPBEPasswordEncoding = new Timestamp(df.parse( + startPBEPasswordEncoding).getTime()); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.security.AlgorithmUpgradePasswordEncodingService#usesOldEncodingAlgorithm(org.apache.jetspeed.security.PasswordCredential) */ public boolean usesOldEncodingAlgorithm(PasswordCredential credential) { - return usesOldEncodingAlgorithm(credential.isEnabled(), credential.getLastAuthenticationDate(), credential.getPreviousAuthenticationDate()); + return usesOldEncodingAlgorithm(credential.isEnabled(), credential + .getLastAuthenticationDate(), credential + .getPreviousAuthenticationDate()); } - /* (non-Javadoc) - * @see org.apache.jetspeed.security.spi.AlgorithmUpgradeCredentialPasswordEncoder#encode(java.lang.String, java.lang.String, org.apache.jetspeed.security.om.InternalCredential) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.security.spi.AlgorithmUpgradeCredentialPasswordEncoder#encode(java.lang.String, + * java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential) */ - public String encode(String userName, String clearTextPassword, InternalCredential credential) throws SecurityException + public String encode(String userName, String clearTextPassword, + InternalCredential credential) throws SecurityException { - if ( usesOldEncodingAlgorithm(credential.isEnabled(), credential.getLastAuthenticationDate(), credential.getPreviousAuthenticationDate())) + if (usesOldEncodingAlgorithm(credential.isEnabled(), credential + .getLastAuthenticationDate(), credential + .getPreviousAuthenticationDate())) { return oldEncoder.encode(userName, clearTextPassword); } @@ -74,26 +93,34 @@ } } - /* (non-Javadoc) - * @see org.apache.jetspeed.security.spi.AlgorithmUpgradeCredentialPasswordEncoder#recodeIfNeeded(java.lang.String, java.lang.String, org.apache.jetspeed.security.om.InternalCredential) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.security.spi.AlgorithmUpgradeCredentialPasswordEncoder#recodeIfNeeded(java.lang.String, + * java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential) */ - public void recodeIfNeeded(String userName, String clearTextPassword, InternalCredential credential) throws SecurityException + public void recodeIfNeeded(String userName, String clearTextPassword, + InternalCredential credential) throws SecurityException { - if ( usesOldEncodingAlgorithm(credential.isEnabled(), credential.getLastAuthenticationDate(), credential.getPreviousAuthenticationDate())) + if (usesOldEncodingAlgorithm(credential.isEnabled(), credential + .getLastAuthenticationDate(), credential + .getPreviousAuthenticationDate())) { credential.setValue(encode(userName, clearTextPassword)); } } - - private boolean usesOldEncodingAlgorithm(boolean encoded, Timestamp lastAuthDate, Timestamp prevAuthDate ) + + private boolean usesOldEncodingAlgorithm(boolean encoded, + Timestamp lastAuthDate, Timestamp prevAuthDate) { - if ( encoded ) + if (encoded) { - if ( lastAuthDate != null ) + if (lastAuthDate != null) { return lastAuthDate.before(startPBEPasswordEncoding); } - else if ( prevAuthDate != null ) + else if (prevAuthDate != null) { // password was created, but the user is not authenticated yet return prevAuthDate.before(startPBEPasswordEncoding); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/CredentialPasswordValidatorsProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/CredentialPasswordValidatorsProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/CredentialPasswordValidatorsProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,8 +5,10 @@ import org.apache.jetspeed.security.SecurityException; import org.apache.jetspeed.security.spi.CredentialPasswordValidator; -public class CredentialPasswordValidatorsProxy implements CredentialPasswordValidator +public class CredentialPasswordValidatorsProxy implements + CredentialPasswordValidator { + private CredentialPasswordValidator[] credentialPasswordValidators; public CredentialPasswordValidatorsProxy(List validators) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultCredentialHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultCredentialHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultCredentialHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,8 +34,8 @@ import org.apache.jetspeed.security.om.InternalCredential; import org.apache.jetspeed.security.om.InternalUserPrincipal; import org.apache.jetspeed.security.om.impl.InternalCredentialImpl; +import org.apache.jetspeed.security.spi.AlgorithmUpgradeCredentialPasswordEncoder; import org.apache.jetspeed.security.spi.CredentialHandler; -import org.apache.jetspeed.security.spi.AlgorithmUpgradeCredentialPasswordEncoder; import org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor; import org.apache.jetspeed.security.spi.PasswordCredentialProvider; import org.apache.jetspeed.security.spi.SecurityAccess; @@ -46,42 +46,49 @@ */ public class DefaultCredentialHandler implements CredentialHandler { - private static final Log log = LogFactory.getLog(DefaultCredentialHandler.class); + private static final Log log = LogFactory + .getLog(DefaultCredentialHandler.class); + private SecurityAccess securityAccess; private PasswordCredentialProvider pcProvider; - + private InternalPasswordCredentialInterceptor ipcInterceptor; - - public DefaultCredentialHandler(SecurityAccess securityAccess, PasswordCredentialProvider pcProvider, + + public DefaultCredentialHandler(SecurityAccess securityAccess, + PasswordCredentialProvider pcProvider, InternalPasswordCredentialInterceptor ipcInterceptor) { this.securityAccess = securityAccess; this.pcProvider = pcProvider; this.ipcInterceptor = ipcInterceptor; } - + /** * @see org.apache.jetspeed.security.spi.CredentialHandler#getPrivateCredentials(java.lang.String) */ public Set getPrivateCredentials(String username) { Set credentials = new HashSet(); - InternalUserPrincipal internalUser = securityAccess.getInternalUserPrincipal(username, false); + InternalUserPrincipal internalUser = securityAccess + .getInternalUserPrincipal(username, false); if (null != internalUser) { - InternalCredential credential = getPasswordCredential(internalUser, username ); - if ( credential != null ) + InternalCredential credential = getPasswordCredential(internalUser, + username); + if (credential != null) { try { - credentials.add(pcProvider.create(username,credential)); + credentials.add(pcProvider.create(username, credential)); } catch (SecurityException e) { - if ( log.isErrorEnabled() ) - log.error("Failure creating a PasswordCredential for InternalCredential "+credential, e); + if (log.isErrorEnabled()) + log.error( + "Failure creating a PasswordCredential for InternalCredential " + + credential, e); } } } @@ -95,37 +102,45 @@ { return new HashSet(); } - - private InternalCredential getPasswordCredential(InternalUserPrincipal internalUser, String username) + + private InternalCredential getPasswordCredential( + InternalUserPrincipal internalUser, String username) { InternalCredential credential = null; - + Collection internalCredentials = internalUser.getCredentials(); - if ( internalCredentials != null ) + if (internalCredentials != null) { Iterator iter = internalCredentials.iterator(); - + while (iter.hasNext()) { credential = (InternalCredential) iter.next(); - if (credential.getType() == InternalCredential.PRIVATE ) + if (credential.getType() == InternalCredential.PRIVATE) { if ((null != credential.getClassname()) - && (credential.getClassname().equals(pcProvider.getPasswordCredentialClass().getName()))) + && (credential.getClassname().equals(pcProvider + .getPasswordCredentialClass().getName()))) { try { - if ( ipcInterceptor != null && ipcInterceptor.afterLoad(pcProvider, username, credential) ) + if (ipcInterceptor != null + && ipcInterceptor.afterLoad(pcProvider, + username, credential)) { - // update InternalUserPrincipal to save post processed data - securityAccess.setInternalUserPrincipal(internalUser,internalUser.isMappingOnly()); + // update InternalUserPrincipal to save post + // processed data + securityAccess.setInternalUserPrincipal( + internalUser, internalUser + .isMappingOnly()); } break; } catch (SecurityException e) { - if ( log.isErrorEnabled() ) - log.error("Failure loading InternalCredential "+credential, e); + if (log.isErrorEnabled()) + log.error("Failure loading InternalCredential " + + credential, e); } } } @@ -138,164 +153,183 @@ /** * @see org.apache.jetspeed.security.spi.CredentialHandler#setPassword(java.lang.String,java.lang.String,java.lang.String) */ - public void setPassword(String userName, String oldPassword, String newPassword) throws SecurityException + public void setPassword(String userName, String oldPassword, + String newPassword) throws SecurityException { - setPassword (userName, oldPassword, newPassword, false); + setPassword(userName, oldPassword, newPassword, false); } - + /** * @see org.apache.jetspeed.security.spi.CredentialHandler#importPassword(java.lang.String,java.lang.String) */ - public void importPassword(String userName, String newPassword) throws SecurityException + public void importPassword(String userName, String newPassword) + throws SecurityException { - setPassword (userName, null, newPassword, true); + setPassword(userName, null, newPassword, true); } - + /** - * @see org.apache.jetspeed.security.spi.CredentialHandler#setPassword(java.lang.String,java.lang.String,java.lang.String, boolean) + * @see org.apache.jetspeed.security.spi.CredentialHandler#setPassword(java.lang.String,java.lang.String,java.lang.String, + * boolean) */ - protected void setPassword(String userName, String oldPassword, String newPassword, boolean raw) throws SecurityException + protected void setPassword(String userName, String oldPassword, + String newPassword, boolean raw) throws SecurityException { - InternalUserPrincipal internalUser = securityAccess.getInternalUserPrincipal(userName, false); - if (null == internalUser) - { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(userName)); - } - + InternalUserPrincipal internalUser = securityAccess + .getInternalUserPrincipal(userName, false); + if (null == internalUser) { throw new SecurityException( + SecurityException.USER_DOES_NOT_EXIST.create(userName)); } + Collection credentials = internalUser.getCredentials(); if (null == credentials) { credentials = new ArrayList(); } - InternalCredential credential = getPasswordCredential(internalUser, userName ); - + InternalCredential credential = getPasswordCredential(internalUser, + userName); + if (null != oldPassword) { - if ( credential != null && - credential.getValue() != null && - credential.isEncoded() && - pcProvider.getEncoder() != null ) + if (credential != null && credential.getValue() != null + && credential.isEncoded() + && pcProvider.getEncoder() != null) { - if ( pcProvider.getEncoder() instanceof AlgorithmUpgradeCredentialPasswordEncoder ) + if (pcProvider.getEncoder() instanceof AlgorithmUpgradeCredentialPasswordEncoder) { - oldPassword = ((AlgorithmUpgradeCredentialPasswordEncoder)pcProvider.getEncoder()).encode(userName,oldPassword, credential); + oldPassword = ((AlgorithmUpgradeCredentialPasswordEncoder) pcProvider + .getEncoder()).encode(userName, oldPassword, + credential); } else { - oldPassword = pcProvider.getEncoder().encode(userName,oldPassword); + oldPassword = pcProvider.getEncoder().encode(userName, + oldPassword); } } } - - if (oldPassword != null && (credential == null || credential.getValue() == null || !credential.getValue().equals(oldPassword))) + + if (oldPassword != null + && (credential == null || credential.getValue() == null || !credential + .getValue().equals(oldPassword))) { // supplied PasswordCredential not defined for this user throw new InvalidPasswordException(); } - if (!raw) // bypass validation if raw + if (!raw) // bypass validation if raw { - if ( pcProvider.getValidator() != null ) - { - try - { - pcProvider.getValidator().validate(newPassword); - } - catch (InvalidPasswordException ipe) - { - throw new InvalidNewPasswordException(); - } - } + if (pcProvider.getValidator() != null) + { + try + { + pcProvider.getValidator().validate(newPassword); + } + catch (InvalidPasswordException ipe) + { + throw new InvalidNewPasswordException(); + } + } } boolean encoded = false; - if ( pcProvider.getEncoder() != null ) + if (pcProvider.getEncoder() != null) { - if (!(raw)) // if raw just bypass encoding - newPassword = pcProvider.getEncoder().encode(userName, newPassword); + if (!(raw)) // if raw just bypass encoding + newPassword = pcProvider.getEncoder().encode(userName, + newPassword); encoded = true; } boolean create = credential == null; - if ( create ) + if (create) { - credential = new InternalCredentialImpl(internalUser.getPrincipalId(), newPassword, InternalCredential.PRIVATE, - pcProvider.getPasswordCredentialClass().getName()); + credential = new InternalCredentialImpl(internalUser + .getPrincipalId(), newPassword, InternalCredential.PRIVATE, + pcProvider.getPasswordCredentialClass().getName()); credential.setEncoded(encoded); credentials.add(credential); } - else if ( oldPassword == null ) + else if (oldPassword == null) { -/* TODO: should only be allowed for admin - // User *has* an PasswordCredential: setting a new Credential without supplying - // its current one is not allowed - throw new SecurityException(SecurityException.PASSWORD_REQUIRED); -*/ + /* + * TODO: should only be allowed for admin // User *has* an + * PasswordCredential: setting a new Credential without supplying // + * its current one is not allowed throw new + * SecurityException(SecurityException.PASSWORD_REQUIRED); + */ } - else if ( oldPassword.equals(newPassword) ) - { - throw new PasswordAlreadyUsedException(); - } + else if (oldPassword.equals(newPassword)) { throw new PasswordAlreadyUsedException(); } - if ( ipcInterceptor != null ) + if (ipcInterceptor != null) { - if ( create ) + if (create) { - ipcInterceptor.beforeCreate(internalUser, credentials, userName, credential, newPassword ); + ipcInterceptor.beforeCreate(internalUser, credentials, + userName, credential, newPassword); } else { - ipcInterceptor.beforeSetPassword(internalUser, credentials, userName, credential, newPassword, oldPassword != null ); + ipcInterceptor.beforeSetPassword(internalUser, credentials, + userName, credential, newPassword, oldPassword != null); } } - + if (!create) { credential.setValue(newPassword); credential.setEncoded(encoded); credential.setUpdateRequired(false); } - + long time = new Date().getTime(); - - if ( oldPassword == null ) + + if (oldPassword == null) { // non-user (admin) modified the password - - if ( encoded && pcProvider.getEncoder() instanceof AlgorithmUpgradePasswordEncodingService ) + + if (encoded + && pcProvider.getEncoder() instanceof AlgorithmUpgradePasswordEncodingService) { - // set current time in previous auth date, and clear last authentication date - // !!! While this might be a bit strange logic, it is *required* for the AlgorithmUpgradePBEPasswordEncodingService + // set current time in previous auth date, and clear last + // authentication date + // !!! While this might be a bit strange logic, it is *required* + // for the AlgorithmUpgradePBEPasswordEncodingService // to be able to distinguise password changes from other changes - credential.setPreviousAuthenticationDate(new Timestamp(new Date().getTime())); + credential.setPreviousAuthenticationDate(new Timestamp( + new Date().getTime())); credential.setLastAuthenticationDate(null); } } else { // authenticated password change (by user itself) - credential.setPreviousAuthenticationDate(credential.getLastAuthenticationDate()); + credential.setPreviousAuthenticationDate(credential + .getLastAuthenticationDate()); credential.setLastAuthenticationDate(new Timestamp(time)); } - + credential.setModifiedDate(new Timestamp(time)); internalUser.setModifiedDate(new Timestamp(time)); internalUser.setCredentials(credentials); // Set the user with the new credentials. securityAccess.setInternalUserPrincipal(internalUser, false); } - - + /** - * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordEnabled(java.lang.String, boolean) + * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordEnabled(java.lang.String, + * boolean) */ - public void setPasswordEnabled(String userName, boolean enabled) throws SecurityException + public void setPasswordEnabled(String userName, boolean enabled) + throws SecurityException { - InternalUserPrincipal internalUser = securityAccess.getInternalUserPrincipal(userName, false); + InternalUserPrincipal internalUser = securityAccess + .getInternalUserPrincipal(userName, false); if (null != internalUser) { - InternalCredential credential = getPasswordCredential(internalUser, userName ); - if ( credential != null && !credential.isExpired() && credential.isEnabled() != enabled ) + InternalCredential credential = getPasswordCredential(internalUser, + userName); + if (credential != null && !credential.isExpired() + && credential.isEnabled() != enabled) { long time = new Date().getTime(); credential.setEnabled(enabled); @@ -307,33 +341,44 @@ } else { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(userName)); + throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST + .create(userName)); } } - + /** - * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordUpdateRequired(java.lang.String, boolean) + * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordUpdateRequired(java.lang.String, + * boolean) */ - public void setPasswordUpdateRequired(String userName, boolean updateRequired) throws SecurityException + public void setPasswordUpdateRequired(String userName, + boolean updateRequired) throws SecurityException { - InternalUserPrincipal internalUser = securityAccess.getInternalUserPrincipal(userName, false); + InternalUserPrincipal internalUser = securityAccess + .getInternalUserPrincipal(userName, false); if (null != internalUser) { - InternalCredential credential = getPasswordCredential(internalUser, userName ); - if ( credential != null && !credential.isExpired() && credential.isUpdateRequired() != updateRequired ) + InternalCredential credential = getPasswordCredential(internalUser, + userName); + if (credential != null && !credential.isExpired() + && credential.isUpdateRequired() != updateRequired) { - // only allow setting updateRequired off if (non-Encoded) password is valid - if ( !updateRequired && !credential.isEncoded() && pcProvider.getValidator() != null ) + // only allow setting updateRequired off if (non-Encoded) + // password is valid + if (!updateRequired && !credential.isEncoded() + && pcProvider.getValidator() != null) { pcProvider.getValidator().validate(credential.getValue()); } credential.setUpdateRequired(updateRequired); long time = new Date().getTime(); credential.setModifiedDate(new Timestamp(time)); - // temporary hack for now to support setting passwordUpdateRequired = false + // temporary hack for now to support setting + // passwordUpdateRequired = false // for users never authenticated yet. - // The current InternalPasswordCredentialStateHandlingInterceptor.afterLoad() - // logic will only set it (back) to true if both prev and last auth. date is null + // The current + // InternalPasswordCredentialStateHandlingInterceptor.afterLoad() + // logic will only set it (back) to true if both prev and last + // auth. date is null credential.setPreviousAuthenticationDate(new Timestamp(time)); credential.setModifiedDate(new Timestamp(time)); internalUser.setModifiedDate(new Timestamp(time)); @@ -342,23 +387,29 @@ } else { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(userName)); + throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST + .create(userName)); } } - + /** - * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordExpiration(java.lang.String, java.sql.Date) + * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordExpiration(java.lang.String, + * java.sql.Date) */ - public void setPasswordExpiration(String userName, java.sql.Date expirationDate) throws SecurityException + public void setPasswordExpiration(String userName, + java.sql.Date expirationDate) throws SecurityException { - InternalUserPrincipal internalUser = securityAccess.getInternalUserPrincipal(userName, false); + InternalUserPrincipal internalUser = securityAccess + .getInternalUserPrincipal(userName, false); if (null != internalUser) { - InternalCredential credential = getPasswordCredential(internalUser, userName ); - if ( credential != null ) + InternalCredential credential = getPasswordCredential(internalUser, + userName); + if (credential != null) { long time = new Date().getTime(); - if ( expirationDate != null && new java.sql.Date(time).after(expirationDate)) + if (expirationDate != null + && new java.sql.Date(time).after(expirationDate)) { credential.setExpired(true); } @@ -367,7 +418,7 @@ credential.setExpired(false); } credential.setExpirationDate(expirationDate); - + credential.setModifiedDate(new Timestamp(time)); internalUser.setModifiedDate(new Timestamp(time)); securityAccess.setInternalUserPrincipal(internalUser, false); @@ -375,73 +426,91 @@ } else { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(userName)); + throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST + .create(userName)); } } /** - * @see org.apache.jetspeed.security.spi.CredentialHandler#authenticate(java.lang.String, java.lang.String) + * @see org.apache.jetspeed.security.spi.CredentialHandler#authenticate(java.lang.String, + * java.lang.String) */ - public boolean authenticate(String userName, String password) throws SecurityException + public boolean authenticate(String userName, String password) + throws SecurityException { boolean authenticated = false; - InternalUserPrincipal internalUser = securityAccess.getInternalUserPrincipal(userName, false); + InternalUserPrincipal internalUser = securityAccess + .getInternalUserPrincipal(userName, false); if (null != internalUser) { - InternalCredential credential = getPasswordCredential(internalUser, userName ); - if ( credential != null && credential.isEnabled() && !credential.isExpired()) + InternalCredential credential = getPasswordCredential(internalUser, + userName); + if (credential != null && credential.isEnabled() + && !credential.isExpired()) { String encodedPassword = password; - if ( pcProvider.getEncoder() != null && credential.isEncoded()) + if (pcProvider.getEncoder() != null && credential.isEncoded()) { - if ( pcProvider.getEncoder() instanceof AlgorithmUpgradeCredentialPasswordEncoder ) + if (pcProvider.getEncoder() instanceof AlgorithmUpgradeCredentialPasswordEncoder) { - encodedPassword = ((AlgorithmUpgradeCredentialPasswordEncoder)pcProvider.getEncoder()).encode(userName,password, credential); + encodedPassword = ((AlgorithmUpgradeCredentialPasswordEncoder) pcProvider + .getEncoder()).encode(userName, password, + credential); } else { - encodedPassword = pcProvider.getEncoder().encode(userName,password); + encodedPassword = pcProvider.getEncoder().encode( + userName, password); } } authenticated = credential.getValue().equals(encodedPassword); boolean update = false; - if ( ipcInterceptor != null ) + if (ipcInterceptor != null) { - update = ipcInterceptor.afterAuthenticated(internalUser, userName, credential, authenticated); - if ( update && (!credential.isEnabled() || credential.isExpired())) + update = ipcInterceptor.afterAuthenticated(internalUser, + userName, credential, authenticated); + if (update + && (!credential.isEnabled() || credential + .isExpired())) { authenticated = false; } } long time = new Date().getTime(); - - if ( authenticated ) + + if (authenticated) { credential.setAuthenticationFailures(0); - if ( pcProvider.getEncoder() != null && pcProvider.getEncoder() instanceof AlgorithmUpgradeCredentialPasswordEncoder) + if (pcProvider.getEncoder() != null + && pcProvider.getEncoder() instanceof AlgorithmUpgradeCredentialPasswordEncoder) { - ((AlgorithmUpgradeCredentialPasswordEncoder)pcProvider.getEncoder()).recodeIfNeeded(userName,password,credential); + ((AlgorithmUpgradeCredentialPasswordEncoder) pcProvider + .getEncoder()).recodeIfNeeded(userName, + password, credential); } - - credential.setPreviousAuthenticationDate(credential.getLastAuthenticationDate()); + + credential.setPreviousAuthenticationDate(credential + .getLastAuthenticationDate()); credential.setLastAuthenticationDate(new Timestamp(time)); update = true; } - - if ( update ) + + if (update) { credential.setModifiedDate(new Timestamp(time)); internalUser.setModifiedDate(new Timestamp(time)); - securityAccess.setInternalUserPrincipal(internalUser, false); + securityAccess + .setInternalUserPrincipal(internalUser, false); } } } else { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(userName)); + throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST + .create(userName)); } return authenticated; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultCredentialPasswordValidator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultCredentialPasswordValidator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultCredentialPasswordValidator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi.impl; import java.util.regex.Matcher; @@ -29,47 +29,52 @@ * </p> * * @author <a href="mailto:ate ¡÷ apache.org">Ate Douma</a> - * @version $Id: DefaultCredentialPasswordValidator.java 601032 2007-12-04 18:45:55Z taylor $ + * @version $Id: DefaultCredentialPasswordValidator.java 601032 2007-12-04 + * 18:45:55Z taylor $ */ -public class DefaultCredentialPasswordValidator implements CredentialPasswordValidator +public class DefaultCredentialPasswordValidator implements + CredentialPasswordValidator { + private String passwordPattern; + private boolean strictPassword = false; - /* Example: - * Must be at least 6 characters - * Must contain at least one one lower case letter, one upper case letter, one digit and one special character - * Valid special characters are @#$%^&+= - */ + + /* + * Example: Must be at least 6 characters Must contain at least one one + * lower case letter, one upper case letter, one digit and one special + * character Valid special characters are @#$%^&+= + */ private final static String defaultPasswordPattern = "[^.*(?=.{6,})(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$]"; - + public DefaultCredentialPasswordValidator(String passwordPattern) { - this.passwordPattern = passwordPattern; + this.passwordPattern = passwordPattern; this.strictPassword = true; } + public DefaultCredentialPasswordValidator() { strictPassword = false; } - + /** * @see org.apache.jetspeed.security.spi.CredentialPasswordValidator#validate(java.lang.String) */ public void validate(String clearTextPassword) throws SecurityException { - if (strictPassword) - { - Pattern p = Pattern.compile(passwordPattern); - //Match the given string with the pattern - Matcher m = p.matcher(clearTextPassword); - if(!m.matches()) - throw new InvalidPasswordException(); - } - else - { - if ( clearTextPassword == null || clearTextPassword.length() == 0) - throw new InvalidPasswordException(); - } - + if (strictPassword) + { + Pattern p = Pattern.compile(passwordPattern); + // Match the given string with the pattern + Matcher m = p.matcher(clearTextPassword); + if (!m.matches()) throw new InvalidPasswordException(); + } + else + { + if (clearTextPassword == null || clearTextPassword.length() == 0) + throw new InvalidPasswordException(); + } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultGroupSecurityHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultGroupSecurityHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultGroupSecurityHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -61,7 +61,8 @@ if (null != internalGroup) { groupPrincipal = new GroupPrincipalImpl(GroupPrincipalImpl - .getPrincipalNameFromFullPath(internalGroup.getFullPath()), internalGroup.isEnabled(), internalGroup.isMappingOnly()); + .getPrincipalNameFromFullPath(internalGroup.getFullPath()), + internalGroup.isEnabled(), internalGroup.isMappingOnly()); } return groupPrincipal; } @@ -73,16 +74,17 @@ throws SecurityException { String fullPath = groupPrincipal.getFullPath(); - InternalGroupPrincipal internalGroup = commonQueries.getInternalGroupPrincipal(fullPath); - if ( null == internalGroup ) + InternalGroupPrincipal internalGroup = commonQueries + .getInternalGroupPrincipal(fullPath); + if (null == internalGroup) { internalGroup = new InternalGroupPrincipalImpl(fullPath); internalGroup.setEnabled(groupPrincipal.isEnabled()); commonQueries.setInternalGroupPrincipal(internalGroup, false); } - else if ( !internalGroup.isMappingOnly() ) + else if (!internalGroup.isMappingOnly()) { - if ( internalGroup.isEnabled() != groupPrincipal.isEnabled() ) + if (internalGroup.isEnabled() != groupPrincipal.isEnabled()) { internalGroup.setEnabled(groupPrincipal.isEnabled()); commonQueries.setInternalGroupPrincipal(internalGroup, false); @@ -124,10 +126,9 @@ { continue; } - groupPrincipals - .add(new GroupPrincipalImpl(GroupPrincipalImpl.getPrincipalNameFromFullPath(internalGroup.getFullPath()), - internalGroup.isEnabled(), internalGroup.isMappingOnly()) - ); + groupPrincipals.add(new GroupPrincipalImpl(GroupPrincipalImpl + .getPrincipalNameFromFullPath(internalGroup.getFullPath()), + internalGroup.isEnabled(), internalGroup.isMappingOnly())); } return groupPrincipals; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultPasswordCredentialImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultPasswordCredentialImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultPasswordCredentialImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,8 +26,8 @@ /** * <p> - * Default Password credential implementation. Provides the same mechanism as J2EE - * <code>javax.resource.spi.security.PasswordCredential</code>. + * Default Password credential implementation. Provides the same mechanism as + * J2EE <code>javax.resource.spi.security.PasswordCredential</code>. * </p> * * <p> @@ -36,7 +36,8 @@ * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat </a> */ -public class DefaultPasswordCredentialImpl implements PasswordCredential, Serializable +public class DefaultPasswordCredentialImpl implements PasswordCredential, + Serializable { /** The default uid. */ @@ -50,22 +51,22 @@ /** The update required state */ private boolean updateRequired; - + /** The enabled state. */ private boolean enabled = true; - + /** The expired state. */ private boolean expired; - + /** The expiration date. */ private Date expirationDate; - + /** The previous authentication in date */ private Timestamp previousAuthenticationDate; - + /** The last authentication in date */ private Timestamp lastAuthenticationDate; - + /** The number of authentication failures */ private int authenticationFailures; @@ -78,19 +79,21 @@ this.userName = userName; this.password = (char[]) password.clone(); } - - public DefaultPasswordCredentialImpl(String userName, InternalCredential credential) + + public DefaultPasswordCredentialImpl(String userName, + InternalCredential credential) { this(userName, credential.getValue().toCharArray()); this.updateRequired = credential.isUpdateRequired(); this.enabled = credential.isEnabled(); this.expired = credential.isExpired(); this.expirationDate = credential.getExpirationDate(); - this.previousAuthenticationDate = credential.getPreviousAuthenticationDate(); + this.previousAuthenticationDate = credential + .getPreviousAuthenticationDate(); this.lastAuthenticationDate = credential.getLastAuthenticationDate(); this.authenticationFailures = credential.getAuthenticationFailures(); } - + /** * @return The username. */ @@ -106,8 +109,7 @@ { return (char[]) password.clone(); } - - + /** * @see org.apache.jetspeed.security.PasswordCredential#isUpdateRequired() */ @@ -139,7 +141,7 @@ { return expirationDate; } - + /** * @see org.apache.jetspeed.security.PasswordCredential#getPreviousAuthenticationDate() */ @@ -156,7 +158,7 @@ return lastAuthenticationDate; } - /** + /** * @see org.apache.jetspeed.security.PasswordCredential#getAuthenticationFailures() */ public int getAuthenticationFailures() @@ -169,17 +171,13 @@ */ public boolean equals(Object o) { - if (this == o) - return true; - if (!(o instanceof DefaultPasswordCredentialImpl)) - return false; + if (this == o) return true; + if (!(o instanceof DefaultPasswordCredentialImpl)) return false; final DefaultPasswordCredentialImpl credential = (DefaultPasswordCredentialImpl) o; - if (!Arrays.equals(password, credential.password)) - return false; - if (!userName.equals(credential.userName)) - return false; + if (!Arrays.equals(password, credential.password)) return false; + if (!userName.equals(credential.userName)) return false; return true; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultPasswordCredentialProvider.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultPasswordCredentialProvider.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultPasswordCredentialProvider.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi.impl; import org.apache.jetspeed.security.PasswordCredential; @@ -29,19 +29,25 @@ * </p> * * @author <a href="mailto:ate ¡÷ apache.org">Ate Douma</a> - * @version $Id: DefaultPasswordCredentialProvider.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: DefaultPasswordCredentialProvider.java 516448 2007-03-09 + * 16:25:47Z ate $ */ -public class DefaultPasswordCredentialProvider implements PasswordCredentialProvider +public class DefaultPasswordCredentialProvider implements + PasswordCredentialProvider { + private CredentialPasswordValidator validator; - private CredentialPasswordEncoder encoder; - + + private CredentialPasswordEncoder encoder; + public DefaultPasswordCredentialProvider() { - this(new DefaultCredentialPasswordValidator(),null); + this(new DefaultCredentialPasswordValidator(), null); } - - public DefaultPasswordCredentialProvider(CredentialPasswordValidator validator, CredentialPasswordEncoder encoder) + + public DefaultPasswordCredentialProvider( + CredentialPasswordValidator validator, + CredentialPasswordEncoder encoder) { this.validator = validator; this.encoder = encoder; @@ -72,27 +78,33 @@ } /** - * @see org.apache.jetspeed.security.spi.PasswordCredentialProvider#create(java.lang.String, java.lang.String) + * @see org.apache.jetspeed.security.spi.PasswordCredentialProvider#create(java.lang.String, + * java.lang.String) */ - public PasswordCredential create(String userName, String password) throws SecurityException + public PasswordCredential create(String userName, String password) + throws SecurityException { validator.validate(password); PasswordCredential pc; - if ( encoder != null ) + if (encoder != null) { - pc = new DefaultPasswordCredentialImpl(userName, encoder.encode(userName, password).toCharArray()); + pc = new DefaultPasswordCredentialImpl(userName, encoder.encode( + userName, password).toCharArray()); } else { - pc = new DefaultPasswordCredentialImpl(userName, password.toCharArray()); + pc = new DefaultPasswordCredentialImpl(userName, password + .toCharArray()); } return pc; } /** - * @see org.apache.jetspeed.security.spi.PasswordCredentialProvider#create(java.lang.String, org.apache.jetspeed.security.om.InternalCredential) + * @see org.apache.jetspeed.security.spi.PasswordCredentialProvider#create(java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential) */ - public PasswordCredential create(String userName, InternalCredential credential) throws SecurityException + public PasswordCredential create(String userName, + InternalCredential credential) throws SecurityException { return new DefaultPasswordCredentialImpl(userName, credential); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultRoleSecurityHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultRoleSecurityHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultRoleSecurityHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -61,7 +61,7 @@ if (null != internalRole) { rolePrincipal = new RolePrincipalImpl(RolePrincipalImpl - .getPrincipalNameFromFullPath(internalRole.getFullPath()), + .getPrincipalNameFromFullPath(internalRole.getFullPath()), internalRole.isEnabled(), internalRole.isMappingOnly()); } return rolePrincipal; @@ -74,16 +74,17 @@ throws SecurityException { String fullPath = rolePrincipal.getFullPath(); - InternalRolePrincipal internalRole = commonQueries.getInternalRolePrincipal(fullPath); - if ( null == internalRole ) + InternalRolePrincipal internalRole = commonQueries + .getInternalRolePrincipal(fullPath); + if (null == internalRole) { internalRole = new InternalRolePrincipalImpl(fullPath); internalRole.setEnabled(rolePrincipal.isEnabled()); commonQueries.setInternalRolePrincipal(internalRole, false); } - else if ( !internalRole.isMappingOnly() ) + else if (!internalRole.isMappingOnly()) { - if ( internalRole.isEnabled() != rolePrincipal.isEnabled() ) + if (internalRole.isEnabled() != rolePrincipal.isEnabled()) { internalRole.setEnabled(rolePrincipal.isEnabled()); commonQueries.setInternalRolePrincipal(internalRole, false); @@ -130,5 +131,5 @@ } return rolePrincipals; } - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultSecurityMappingHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultSecurityMappingHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultSecurityMappingHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -69,7 +69,8 @@ * resolvers. * </p> */ - public DefaultSecurityMappingHandler(SecurityAccess commonQueries, HierarchyResolver roleHierarchyResolver, + public DefaultSecurityMappingHandler(SecurityAccess commonQueries, + HierarchyResolver roleHierarchyResolver, HierarchyResolver groupHierarchyResolver) { this.commonQueries = commonQueries; @@ -110,7 +111,8 @@ /** * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#setGroupHierarchyResolver(org.apache.jetspeed.security.HierarchyResolver) */ - public void setGroupHierarchyResolver(HierarchyResolver groupHierarchyResolver) + public void setGroupHierarchyResolver( + HierarchyResolver groupHierarchyResolver) { this.groupHierarchyResolver = groupHierarchyResolver; } @@ -121,7 +123,8 @@ public Set getRolePrincipals(String username) { Set rolePrincipals = new HashSet(); - InternalUserPrincipal internalUser = commonQueries.getInternalUserPrincipal(username); + InternalUserPrincipal internalUser = commonQueries + .getInternalUserPrincipal(username); if (null != internalUser) { Collection internalRoles = internalUser.getRolePrincipals(); @@ -130,13 +133,17 @@ Iterator internalRolesIter = internalRoles.iterator(); while (internalRolesIter.hasNext()) { - InternalRolePrincipal internalRole = (InternalRolePrincipal) internalRolesIter.next(); - Preferences preferences = Preferences.userRoot().node(internalRole.getFullPath()); - String[] fullPaths = roleHierarchyResolver.resolve(preferences); + InternalRolePrincipal internalRole = (InternalRolePrincipal) internalRolesIter + .next(); + Preferences preferences = Preferences.userRoot().node( + internalRole.getFullPath()); + String[] fullPaths = roleHierarchyResolver + .resolve(preferences); for (int i = 0; i < fullPaths.length; i++) { - Principal rolePrincipal = new RolePrincipalImpl(RolePrincipalImpl - .getPrincipalNameFromFullPath(fullPaths[i])); + Principal rolePrincipal = new RolePrincipalImpl( + RolePrincipalImpl + .getPrincipalNameFromFullPath(fullPaths[i])); if (!rolePrincipals.contains(rolePrincipal)) { rolePrincipals.add(rolePrincipal); @@ -152,25 +159,27 @@ * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#setUserPrincipalInRole(java.lang.String, * java.lang.String) */ - public void setUserPrincipalInRole(String username, String roleFullPathName) throws SecurityException + public void setUserPrincipalInRole(String username, String roleFullPathName) + throws SecurityException { - InternalUserPrincipal internalUser = commonQueries.getInternalUserPrincipal(username); + InternalUserPrincipal internalUser = commonQueries + .getInternalUserPrincipal(username); boolean isMappingOnly = false; if (null == internalUser) { // This is a record for mapping only. isMappingOnly = true; - internalUser = new InternalUserPrincipalImpl(UserPrincipalImpl.getFullPathFromPrincipalName(username)); + internalUser = new InternalUserPrincipalImpl(UserPrincipalImpl + .getFullPathFromPrincipalName(username)); } Collection internalRoles = internalUser.getRolePrincipals(); // This should not be null. Check for null should be made by the caller. - InternalRolePrincipal internalRole = commonQueries.getInternalRolePrincipal(RolePrincipalImpl - .getFullPathFromPrincipalName(roleFullPathName)); + InternalRolePrincipal internalRole = commonQueries + .getInternalRolePrincipal(RolePrincipalImpl + .getFullPathFromPrincipalName(roleFullPathName)); // Check anyway. - if (null == internalRole) - { - throw new SecurityException(SecurityException.ROLE_DOES_NOT_EXIST.create(roleFullPathName)); - } + if (null == internalRole) { throw new SecurityException( + SecurityException.ROLE_DOES_NOT_EXIST.create(roleFullPathName)); } internalRoles.add(internalRole); internalUser.setRolePrincipals(internalRoles); commonQueries.setInternalUserPrincipal(internalUser, isMappingOnly); @@ -180,30 +189,36 @@ * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#removeUserPrincipalInRole(java.lang.String, * java.lang.String) */ - public void removeUserPrincipalInRole(String username, String roleFullPathName) throws SecurityException + public void removeUserPrincipalInRole(String username, + String roleFullPathName) throws SecurityException { boolean isMappingOnly = false; // Check is the record is used for mapping only. - InternalUserPrincipal internalUser = commonQueries.getInternalUserPrincipal(username, false); + InternalUserPrincipal internalUser = commonQueries + .getInternalUserPrincipal(username, false); if (null == internalUser) { - internalUser = commonQueries.getInternalUserPrincipal(username, true); + internalUser = commonQueries.getInternalUserPrincipal(username, + true); isMappingOnly = true; } if (null != internalUser) { Collection internalRoles = internalUser.getRolePrincipals(); - // This should not be null. Check for null should be made by the caller. - InternalRolePrincipal internalRole = commonQueries.getInternalRolePrincipal(RolePrincipalImpl - .getFullPathFromPrincipalName(roleFullPathName)); + // This should not be null. Check for null should be made by the + // caller. + InternalRolePrincipal internalRole = commonQueries + .getInternalRolePrincipal(RolePrincipalImpl + .getFullPathFromPrincipalName(roleFullPathName)); // Check anyway. - if (null == internalRole) - { - throw new SecurityException(SecurityException.ROLE_DOES_NOT_EXIST.create(roleFullPathName)); - } + if (null == internalRole) { throw new SecurityException( + SecurityException.ROLE_DOES_NOT_EXIST + .create(roleFullPathName)); } internalRoles.remove(internalRole); - // Remove dead mapping records. I.e. No mapping is associated with the specific record. - if (isMappingOnly && internalRoles.isEmpty() && internalUser.getGroupPrincipals().isEmpty() + // Remove dead mapping records. I.e. No mapping is associated with + // the specific record. + if (isMappingOnly && internalRoles.isEmpty() + && internalUser.getGroupPrincipals().isEmpty() && internalUser.getPermissions().isEmpty()) { commonQueries.removeInternalUserPrincipal(internalUser); @@ -211,12 +226,14 @@ else { internalUser.setRolePrincipals(internalRoles); - commonQueries.setInternalUserPrincipal(internalUser, isMappingOnly); + commonQueries.setInternalUserPrincipal(internalUser, + isMappingOnly); } } else { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(username)); + throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST + .create(username)); } } @@ -228,11 +245,13 @@ Set rolePrincipals = new HashSet(); Preferences preferences = Preferences.userRoot().node( - GroupPrincipalImpl.getFullPathFromPrincipalName(groupFullPathName)); + GroupPrincipalImpl + .getFullPathFromPrincipalName(groupFullPathName)); String[] fullPaths = groupHierarchyResolver.resolve(preferences); for (int i = 0; i < fullPaths.length; i++) { - InternalGroupPrincipal internalGroup = commonQueries.getInternalGroupPrincipal(fullPaths[i]); + InternalGroupPrincipal internalGroup = commonQueries + .getInternalGroupPrincipal(fullPaths[i]); if (null != internalGroup) { Collection internalRoles = internalGroup.getRolePrincipals(); @@ -241,9 +260,12 @@ Iterator internalRolesIter = internalRoles.iterator(); while (internalRolesIter.hasNext()) { - InternalRolePrincipal internalRole = (InternalRolePrincipal) internalRolesIter.next(); - Principal rolePrincipal = new RolePrincipalImpl(UserPrincipalImpl - .getPrincipalNameFromFullPath(internalRole.getFullPath())); + InternalRolePrincipal internalRole = (InternalRolePrincipal) internalRolesIter + .next(); + Principal rolePrincipal = new RolePrincipalImpl( + UserPrincipalImpl + .getPrincipalNameFromFullPath(internalRole + .getFullPath())); if (!rolePrincipals.contains(rolePrincipal)) { rolePrincipals.add(rolePrincipal); @@ -259,20 +281,23 @@ * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#setRolePrincipalInGroup(java.lang.String, * java.lang.String) */ - public void setRolePrincipalInGroup(String groupFullPathName, String roleFullPathName) throws SecurityException + public void setRolePrincipalInGroup(String groupFullPathName, + String roleFullPathName) throws SecurityException { - InternalGroupPrincipal internalGroup = commonQueries.getInternalGroupPrincipal(GroupPrincipalImpl - .getFullPathFromPrincipalName(groupFullPathName)); + InternalGroupPrincipal internalGroup = commonQueries + .getInternalGroupPrincipal(GroupPrincipalImpl + .getFullPathFromPrincipalName(groupFullPathName)); boolean isMappingOnly = false; if (null == internalGroup) { // This is a record for mapping only. isMappingOnly = true; internalGroup = new InternalGroupPrincipalImpl(groupFullPathName); - } + } Collection internalRoles = internalGroup.getRolePrincipals(); - InternalRolePrincipal internalRole = commonQueries.getInternalRolePrincipal(RolePrincipalImpl - .getFullPathFromPrincipalName(roleFullPathName)); + InternalRolePrincipal internalRole = commonQueries + .getInternalRolePrincipal(RolePrincipalImpl + .getFullPathFromPrincipalName(roleFullPathName)); internalRoles.add(internalRole); internalGroup.setRolePrincipals(internalRoles); commonQueries.setInternalGroupPrincipal(internalGroup, isMappingOnly); @@ -282,24 +307,25 @@ * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#removeRolePrincipalInGroup(java.lang.String, * java.lang.String) */ - public void removeRolePrincipalInGroup(String groupFullPathName, String roleFullPathName) throws SecurityException + public void removeRolePrincipalInGroup(String groupFullPathName, + String roleFullPathName) throws SecurityException { - InternalGroupPrincipal internalGroup = commonQueries.getInternalGroupPrincipal(GroupPrincipalImpl - .getFullPathFromPrincipalName(groupFullPathName)); + InternalGroupPrincipal internalGroup = commonQueries + .getInternalGroupPrincipal(GroupPrincipalImpl + .getFullPathFromPrincipalName(groupFullPathName)); boolean isMappingOnly = false; if (null == internalGroup) { // This is a record for mapping only. isMappingOnly = true; internalGroup = new InternalGroupPrincipalImpl(groupFullPathName); - } - if (null == internalGroup) - { - throw new SecurityException(SecurityException.GROUP_DOES_NOT_EXIST.create(internalGroup)); } + if (null == internalGroup) { throw new SecurityException( + SecurityException.GROUP_DOES_NOT_EXIST.create(internalGroup)); } Collection internalRoles = internalGroup.getRolePrincipals(); - InternalRolePrincipal internalRole = commonQueries.getInternalRolePrincipal(RolePrincipalImpl - .getFullPathFromPrincipalName(roleFullPathName)); + InternalRolePrincipal internalRole = commonQueries + .getInternalRolePrincipal(RolePrincipalImpl + .getFullPathFromPrincipalName(roleFullPathName)); internalRoles.remove(internalRole); internalGroup.setRolePrincipals(internalRoles); commonQueries.setInternalGroupPrincipal(internalGroup, isMappingOnly); @@ -311,7 +337,8 @@ public Set getGroupPrincipals(String username) { Set groupPrincipals = new HashSet(); - InternalUserPrincipal internalUser = commonQueries.getInternalUserPrincipal(username); + InternalUserPrincipal internalUser = commonQueries + .getInternalUserPrincipal(username); if (null != internalUser) { Collection internalGroups = internalUser.getGroupPrincipals(); @@ -320,13 +347,18 @@ Iterator internalGroupsIter = internalGroups.iterator(); while (internalGroupsIter.hasNext()) { - InternalGroupPrincipal internalGroup = (InternalGroupPrincipal) internalGroupsIter.next(); - Preferences preferences = Preferences.userRoot().node(internalGroup.getFullPath()); - String[] fullPaths = groupHierarchyResolver.resolve(preferences); + InternalGroupPrincipal internalGroup = (InternalGroupPrincipal) internalGroupsIter + .next(); + Preferences preferences = Preferences.userRoot().node( + internalGroup.getFullPath()); + String[] fullPaths = groupHierarchyResolver + .resolve(preferences); for (int i = 0; i < fullPaths.length; i++) { - groupPrincipals.add(new GroupPrincipalImpl(GroupPrincipalImpl - .getPrincipalNameFromFullPath(fullPaths[i]))); + groupPrincipals + .add(new GroupPrincipalImpl( + GroupPrincipalImpl + .getPrincipalNameFromFullPath(fullPaths[i]))); } } } @@ -342,11 +374,13 @@ Set groupPrincipals = new HashSet(); Preferences preferences = Preferences.userRoot().node( - RolePrincipalImpl.getFullPathFromPrincipalName(roleFullPathName)); + RolePrincipalImpl + .getFullPathFromPrincipalName(roleFullPathName)); String[] fullPaths = roleHierarchyResolver.resolve(preferences); for (int i = 0; i < fullPaths.length; i++) { - InternalRolePrincipal internalRole = commonQueries.getInternalRolePrincipal(fullPaths[i]); + InternalRolePrincipal internalRole = commonQueries + .getInternalRolePrincipal(fullPaths[i]); if (null != internalRole) { Collection internalGroups = internalRole.getGroupPrincipals(); @@ -355,9 +389,12 @@ Iterator internalGroupsIter = internalGroups.iterator(); while (internalGroupsIter.hasNext()) { - InternalGroupPrincipal internalGroup = (InternalGroupPrincipal) internalGroupsIter.next(); - Principal groupPrincipal = new GroupPrincipalImpl(GroupPrincipalImpl - .getPrincipalNameFromFullPath(internalGroup.getFullPath())); + InternalGroupPrincipal internalGroup = (InternalGroupPrincipal) internalGroupsIter + .next(); + Principal groupPrincipal = new GroupPrincipalImpl( + GroupPrincipalImpl + .getPrincipalNameFromFullPath(internalGroup + .getFullPath())); if (!groupPrincipals.contains(groupPrincipal)) { groupPrincipals.add(groupPrincipal); @@ -377,11 +414,13 @@ Set userPrincipals = new HashSet(); Preferences preferences = Preferences.userRoot().node( - RolePrincipalImpl.getFullPathFromPrincipalName(roleFullPathName)); + RolePrincipalImpl + .getFullPathFromPrincipalName(roleFullPathName)); String[] fullPaths = roleHierarchyResolver.resolve(preferences); for (int i = 0; i < fullPaths.length; i++) { - InternalRolePrincipal internalRole = commonQueries.getInternalRolePrincipal(fullPaths[i]); + InternalRolePrincipal internalRole = commonQueries + .getInternalRolePrincipal(fullPaths[i]); if (null != internalRole) { Collection internalUsers = internalRole.getUserPrincipals(); @@ -390,9 +429,12 @@ Iterator internalUsersIter = internalUsers.iterator(); while (internalUsersIter.hasNext()) { - InternalUserPrincipal internalUser = (InternalUserPrincipal) internalUsersIter.next(); - Principal userPrincipal = new UserPrincipalImpl(UserPrincipalImpl - .getPrincipalNameFromFullPath(internalUser.getFullPath())); + InternalUserPrincipal internalUser = (InternalUserPrincipal) internalUsersIter + .next(); + Principal userPrincipal = new UserPrincipalImpl( + UserPrincipalImpl + .getPrincipalNameFromFullPath(internalUser + .getFullPath())); if (!userPrincipals.contains(userPrincipal)) { userPrincipals.add(userPrincipal); @@ -412,11 +454,13 @@ Set userPrincipals = new HashSet(); Preferences preferences = Preferences.userRoot().node( - GroupPrincipalImpl.getFullPathFromPrincipalName(groupFullPathName)); + GroupPrincipalImpl + .getFullPathFromPrincipalName(groupFullPathName)); String[] fullPaths = groupHierarchyResolver.resolve(preferences); for (int i = 0; i < fullPaths.length; i++) { - InternalGroupPrincipal internalGroup = commonQueries.getInternalGroupPrincipal(fullPaths[i]); + InternalGroupPrincipal internalGroup = commonQueries + .getInternalGroupPrincipal(fullPaths[i]); if (null != internalGroup) { Collection internalUsers = internalGroup.getUserPrincipals(); @@ -425,9 +469,12 @@ Iterator internalUsersIter = internalUsers.iterator(); while (internalUsersIter.hasNext()) { - InternalUserPrincipal internalUser = (InternalUserPrincipal) internalUsersIter.next(); - Principal userPrincipal = new UserPrincipalImpl(UserPrincipalImpl - .getPrincipalNameFromFullPath(internalUser.getFullPath())); + InternalUserPrincipal internalUser = (InternalUserPrincipal) internalUsersIter + .next(); + Principal userPrincipal = new UserPrincipalImpl( + UserPrincipalImpl + .getPrincipalNameFromFullPath(internalUser + .getFullPath())); if (!userPrincipals.contains(userPrincipal)) { userPrincipals.add(userPrincipal); @@ -443,25 +490,28 @@ * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#setUserPrincipalInGroup(java.lang.String, * java.lang.String) */ - public void setUserPrincipalInGroup(String username, String groupFullPathName) throws SecurityException + public void setUserPrincipalInGroup(String username, + String groupFullPathName) throws SecurityException { - InternalUserPrincipal internalUser = commonQueries.getInternalUserPrincipal(username); + InternalUserPrincipal internalUser = commonQueries + .getInternalUserPrincipal(username); boolean isMappingOnly = false; if (null == internalUser) { // This is a record for mapping only. isMappingOnly = true; - internalUser = new InternalUserPrincipalImpl(UserPrincipalImpl.getFullPathFromPrincipalName(username)); + internalUser = new InternalUserPrincipalImpl(UserPrincipalImpl + .getFullPathFromPrincipalName(username)); } Collection internalGroups = internalUser.getGroupPrincipals(); // This should not be null. Check for null should be made by the caller. - InternalGroupPrincipal internalGroup = commonQueries.getInternalGroupPrincipal(GroupPrincipalImpl - .getFullPathFromPrincipalName(groupFullPathName)); + InternalGroupPrincipal internalGroup = commonQueries + .getInternalGroupPrincipal(GroupPrincipalImpl + .getFullPathFromPrincipalName(groupFullPathName)); // Check anyway. - if (null == internalGroup) - { - throw new SecurityException(SecurityException.GROUP_DOES_NOT_EXIST.create(groupFullPathName)); - } + if (null == internalGroup) { throw new SecurityException( + SecurityException.GROUP_DOES_NOT_EXIST + .create(groupFullPathName)); } internalGroups.add(internalGroup); internalUser.setGroupPrincipals(internalGroups); commonQueries.setInternalUserPrincipal(internalUser, isMappingOnly); @@ -471,44 +521,52 @@ * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#removeUserPrincipalInGroup(java.lang.String, * java.lang.String) */ - public void removeUserPrincipalInGroup(String username, String groupFullPathName) throws SecurityException + public void removeUserPrincipalInGroup(String username, + String groupFullPathName) throws SecurityException { boolean isMappingOnly = false; // Check is the record is used for mapping only. - InternalUserPrincipal internalUser = commonQueries.getInternalUserPrincipal(username, false); + InternalUserPrincipal internalUser = commonQueries + .getInternalUserPrincipal(username, false); if (null == internalUser) { - internalUser = commonQueries.getInternalUserPrincipal(username, true); + internalUser = commonQueries.getInternalUserPrincipal(username, + true); isMappingOnly = true; } if (null != internalUser) { Collection internalGroups = internalUser.getGroupPrincipals(); - // This should not be null. Check for null should be made by the caller. - InternalGroupPrincipal internalGroup = commonQueries.getInternalGroupPrincipal(GroupPrincipalImpl - .getFullPathFromPrincipalName(groupFullPathName)); + // This should not be null. Check for null should be made by the + // caller. + InternalGroupPrincipal internalGroup = commonQueries + .getInternalGroupPrincipal(GroupPrincipalImpl + .getFullPathFromPrincipalName(groupFullPathName)); // Check anyway. - if (null == internalGroup) - { - throw new SecurityException(SecurityException.GROUP_DOES_NOT_EXIST.create(groupFullPathName)); - } + if (null == internalGroup) { throw new SecurityException( + SecurityException.GROUP_DOES_NOT_EXIST + .create(groupFullPathName)); } internalGroups.remove(internalGroup); - // Remove dead mapping records. I.e. No mapping is associated with the specific record. - if (isMappingOnly && internalGroups.isEmpty() && internalUser.getRolePrincipals().isEmpty() + // Remove dead mapping records. I.e. No mapping is associated with + // the specific record. + if (isMappingOnly && internalGroups.isEmpty() + && internalUser.getRolePrincipals().isEmpty() && internalUser.getPermissions().isEmpty()) { commonQueries.removeInternalUserPrincipal(internalUser); } else { - internalUser.setGroupPrincipals(internalGroups); - commonQueries.setInternalUserPrincipal(internalUser, isMappingOnly); + internalUser.setGroupPrincipals(internalGroups); + commonQueries.setInternalUserPrincipal(internalUser, + isMappingOnly); } } else { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(username)); + throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST + .create(username)); } } - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultUserSecurityHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultUserSecurityHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/DefaultUserSecurityHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -35,17 +35,20 @@ */ public class DefaultUserSecurityHandler implements UserSecurityHandler { + /** SecurityAccess. */ private SecurityAccess securityAccess = null; - + /** - * <p>Constructor providing access to the SecurityAccess implementation.</p> + * <p> + * Constructor providing access to the SecurityAccess implementation. + * </p> */ public DefaultUserSecurityHandler(SecurityAccess securityAccess) { this.securityAccess = securityAccess; } - + /** * @see org.apache.jetspeed.security.spi.UserSecurityHandler#isUserPrincipal(java.lang.String) */ @@ -53,22 +56,25 @@ { return securityAccess.isKnownUser(userName); } - + /** * @see org.apache.jetspeed.security.spi.UserSecurityHandler#getUserPrincipal(java.lang.String) */ public Principal getUserPrincipal(String username) { UserPrincipal userPrincipal = null; - InternalUserPrincipal internalUser = securityAccess.getInternalUserPrincipal(username, false); + InternalUserPrincipal internalUser = securityAccess + .getInternalUserPrincipal(username, false); if (null != internalUser) { - userPrincipal = new UserPrincipalImpl(UserPrincipalImpl.getPrincipalNameFromFullPath(internalUser.getFullPath()), true, internalUser.isMappingOnly()); + userPrincipal = new UserPrincipalImpl(UserPrincipalImpl + .getPrincipalNameFromFullPath(internalUser.getFullPath()), + true, internalUser.isMappingOnly()); userPrincipal.setEnabled(internalUser.isEnabled()); } return userPrincipal; } - + /** * @see org.apache.jetspeed.security.spi.UserSecurityHandler#getUserPrincipals(java.lang.String) */ @@ -78,13 +84,16 @@ Iterator result = securityAccess.getInternalUserPrincipals(filter); while (result.hasNext()) { - InternalUserPrincipal internalUser = (InternalUserPrincipal) result.next(); + InternalUserPrincipal internalUser = (InternalUserPrincipal) result + .next(); String path = internalUser.getFullPath(); if (path == null) { continue; } - UserPrincipal userPrincipal = new UserPrincipalImpl(UserPrincipalImpl.getPrincipalNameFromFullPath(internalUser.getFullPath())); + UserPrincipal userPrincipal = new UserPrincipalImpl( + UserPrincipalImpl.getPrincipalNameFromFullPath(internalUser + .getFullPath())); userPrincipal.setEnabled(internalUser.isEnabled()); userPrincipals.add(userPrincipal); } @@ -102,51 +111,62 @@ /** * @see org.apache.jetspeed.security.spi.UserSecurityHandler#addUserPrincipal(org.apache.jetspeed.security.UserPrincipal) */ - public void addUserPrincipal(UserPrincipal userPrincipal) throws SecurityException + public void addUserPrincipal(UserPrincipal userPrincipal) + throws SecurityException { - if ( null == securityAccess.getInternalUserPrincipal(userPrincipal.getName(), false) ) + if (null == securityAccess.getInternalUserPrincipal(userPrincipal + .getName(), false)) { - securityAccess.setInternalUserPrincipal(new InternalUserPrincipalImpl(userPrincipal.getFullPath()), false); + securityAccess.setInternalUserPrincipal( + new InternalUserPrincipalImpl(userPrincipal.getFullPath()), + false); } else { - throw new SecurityException(SecurityException.USER_ALREADY_EXISTS.create(userPrincipal.getName())); + throw new SecurityException(SecurityException.USER_ALREADY_EXISTS + .create(userPrincipal.getName())); } } - + /** * @see org.apache.jetspeed.security.spi.UserSecurityHandler#updateUserPrincipal(org.apache.jetspeed.security.UserPrincipal) */ - public void updateUserPrincipal(UserPrincipal userPrincipal) throws SecurityException + public void updateUserPrincipal(UserPrincipal userPrincipal) + throws SecurityException { - InternalUserPrincipal internalUser = securityAccess.getInternalUserPrincipal(userPrincipal.getName(), false); - if ( null != internalUser ) + InternalUserPrincipal internalUser = securityAccess + .getInternalUserPrincipal(userPrincipal.getName(), false); + if (null != internalUser) { - if ( internalUser.isEnabled() != userPrincipal.isEnabled()) + if (internalUser.isEnabled() != userPrincipal.isEnabled()) { internalUser.setEnabled(userPrincipal.isEnabled()); - securityAccess.setInternalUserPrincipal(internalUser, false); + securityAccess.setInternalUserPrincipal(internalUser, false); } } else { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(userPrincipal.getName())); + throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST + .create(userPrincipal.getName())); } } - + /** * @see org.apache.jetspeed.security.spi.UserSecurityHandler#removeUserPrincipal(org.apache.jetspeed.security.UserPrincipal) */ - public void removeUserPrincipal(UserPrincipal userPrincipal) throws SecurityException + public void removeUserPrincipal(UserPrincipal userPrincipal) + throws SecurityException { - InternalUserPrincipal internalUser = securityAccess.getInternalUserPrincipal(userPrincipal.getName(), false); + InternalUserPrincipal internalUser = securityAccess + .getInternalUserPrincipal(userPrincipal.getName(), false); if (null != internalUser) { securityAccess.removeInternalUserPrincipal(internalUser); } else { - internalUser = securityAccess.getInternalUserPrincipal(userPrincipal.getName(), true); + internalUser = securityAccess.getInternalUserPrincipal( + userPrincipal.getName(), true); if (null != internalUser) { securityAccess.removeInternalUserPrincipal(internalUser); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/EncodePasswordOnFirstLoadInterceptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/EncodePasswordOnFirstLoadInterceptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/EncodePasswordOnFirstLoadInterceptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi.impl; import java.sql.Timestamp; @@ -26,38 +26,54 @@ /** * <p> - * Encodes (encrypts) an {@link InternalCredential} password using the configured {@link PasswordCredentialProvider#getEncoder() encoder} - * if it is loaded unencoded from the persistent store.</p> + * Encodes (encrypts) an {@link InternalCredential} password using the + * configured {@link PasswordCredentialProvider#getEncoder() encoder} if it is + * loaded unencoded from the persistent store. + * </p> * <p> - * This interceptor is useful when credentials need to be preset in the persistent store (like through scripts) or - * migrated unencoded from a different storage.</p> + * This interceptor is useful when credentials need to be preset in the + * persistent store (like through scripts) or migrated unencoded from a + * different storage. + * </p> * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id$ */ -public class EncodePasswordOnFirstLoadInterceptor extends AbstractInternalPasswordCredentialInterceptorImpl +public class EncodePasswordOnFirstLoadInterceptor extends + AbstractInternalPasswordCredentialInterceptorImpl { + /** * @return true if now encoded - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterLoad(org.apache.jetspeed.security.spi.PasswordCredentialProvider, java.lang.String, org.apache.jetspeed.security.om.InternalCredential) + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterLoad(org.apache.jetspeed.security.spi.PasswordCredentialProvider, + * java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential) */ - public boolean afterLoad(PasswordCredentialProvider pcProvider, String userName, InternalCredential credential) + public boolean afterLoad(PasswordCredentialProvider pcProvider, + String userName, InternalCredential credential) throws SecurityException { boolean updated = false; - if (!credential.isEncoded() && pcProvider.getEncoder() != null ) + if (!credential.isEncoded() && pcProvider.getEncoder() != null) { - credential.setValue(pcProvider.getEncoder().encode(userName,credential.getValue())); + credential.setValue(pcProvider.getEncoder().encode(userName, + credential.getValue())); credential.setEncoded(true); - - if ( pcProvider.getEncoder() instanceof AlgorithmUpgradePasswordEncodingService) + + if (pcProvider.getEncoder() instanceof AlgorithmUpgradePasswordEncodingService) { - // For the AlgorithmUpgradePBEPasswordService to be able to distinguise between - // old and new encoded passwords, it evaluates the last and previous authentication timestamps. - // With an automatic encoding (using the new encoding schema) the last authentication must be - // set to null (as the user hasn't been authenticated yet again, which leaves the previous - // authentication timestamp for indicating when the (new) encoding took place. - credential.setPreviousAuthenticationDate(new Timestamp(new Date().getTime())); + // For the AlgorithmUpgradePBEPasswordService to be able to + // distinguise between + // old and new encoded passwords, it evaluates the last and + // previous authentication timestamps. + // With an automatic encoding (using the new encoding schema) + // the last authentication must be + // set to null (as the user hasn't been authenticated yet again, + // which leaves the previous + // authentication timestamp for indicating when the (new) + // encoding took place. + credential.setPreviousAuthenticationDate(new Timestamp( + new Date().getTime())); credential.setLastAuthenticationDate(null); } updated = true; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/InternalPasswordCredentialInterceptorsProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/InternalPasswordCredentialInterceptorsProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/InternalPasswordCredentialInterceptorsProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi.impl; import java.util.Collection; @@ -28,33 +28,41 @@ /** * <p> * Provides a wrapper around a list of interceptors so multiple interceptors can - * be used with the {@link DefaultCredentialHandler}. - * Each interceptor will be invoked sequentially. + * be used with the {@link DefaultCredentialHandler}. Each interceptor will be + * invoked sequentially. * </p> * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id$ */ -public class InternalPasswordCredentialInterceptorsProxy implements InternalPasswordCredentialInterceptor +public class InternalPasswordCredentialInterceptorsProxy implements + InternalPasswordCredentialInterceptor { + private InternalPasswordCredentialInterceptor[] interceptors; public InternalPasswordCredentialInterceptorsProxy(List interceptors) { this.interceptors = (InternalPasswordCredentialInterceptor[]) interceptors - .toArray(new InternalPasswordCredentialInterceptor[interceptors.size()]); + .toArray(new InternalPasswordCredentialInterceptor[interceptors + .size()]); } /** - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterLoad(org.apache.jetspeed.security.spi.PasswordCredentialProvider, java.lang.String, org.apache.jetspeed.security.om.InternalCredential) + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterLoad(org.apache.jetspeed.security.spi.PasswordCredentialProvider, + * java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential) */ - public boolean afterLoad(PasswordCredentialProvider pcProvider, String userName, InternalCredential credential) + public boolean afterLoad(PasswordCredentialProvider pcProvider, + String userName, InternalCredential credential) throws SecurityException { boolean updated = false; for (int i = 0; i < interceptors.length; i++) { - if (interceptors[i] != null && interceptors[i].afterLoad(pcProvider, userName, credential)) + if (interceptors[i] != null + && interceptors[i].afterLoad(pcProvider, userName, + credential)) { updated = true; } @@ -63,16 +71,20 @@ } /** - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterAuthenticated(org.apache.jetspeed.security.om.InternalUserPrincipal, java.lang.String, org.apache.jetspeed.security.om.InternalCredential, boolean) + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterAuthenticated(org.apache.jetspeed.security.om.InternalUserPrincipal, + * java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential, boolean) */ - public boolean afterAuthenticated(InternalUserPrincipal internalUser, String userName, - InternalCredential credential, boolean authenticated) throws SecurityException + public boolean afterAuthenticated(InternalUserPrincipal internalUser, + String userName, InternalCredential credential, + boolean authenticated) throws SecurityException { boolean updated = false; for (int i = 0; i < interceptors.length; i++) { if (interceptors[i] != null - && interceptors[i].afterAuthenticated(internalUser, userName, credential, authenticated)) + && interceptors[i].afterAuthenticated(internalUser, + userName, credential, authenticated)) { updated = true; } @@ -81,32 +93,42 @@ } /** - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeCreate(org.apache.jetspeed.security.om.InternalUserPrincipal, java.util.Collection, java.lang.String, InternalCredential, java.lang.String) + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeCreate(org.apache.jetspeed.security.om.InternalUserPrincipal, + * java.util.Collection, java.lang.String, InternalCredential, + * java.lang.String) */ - public void beforeCreate(InternalUserPrincipal internalUser, Collection credentials, String userName, - InternalCredential credential, String password) throws SecurityException + public void beforeCreate(InternalUserPrincipal internalUser, + Collection credentials, String userName, + InternalCredential credential, String password) + throws SecurityException { for (int i = 0; i < interceptors.length; i++) { if (interceptors[i] != null) { - interceptors[i].beforeCreate(internalUser, credentials, userName, credential, password); + interceptors[i].beforeCreate(internalUser, credentials, + userName, credential, password); } } } /** - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeSetPassword(org.apache.jetspeed.security.om.InternalUserPrincipal, java.util.Collection, java.lang.String, org.apache.jetspeed.security.om.InternalCredential, java.lang.String, boolean) + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeSetPassword(org.apache.jetspeed.security.om.InternalUserPrincipal, + * java.util.Collection, java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential, + * java.lang.String, boolean) */ - public void beforeSetPassword(InternalUserPrincipal internalUser, Collection credentials, String userName, - InternalCredential credential, String password, boolean authenticated) throws SecurityException + public void beforeSetPassword(InternalUserPrincipal internalUser, + Collection credentials, String userName, + InternalCredential credential, String password, + boolean authenticated) throws SecurityException { for (int i = 0; i < interceptors.length; i++) { if (interceptors[i] != null) { - interceptors[i].beforeSetPassword(internalUser, credentials, userName, credential, password, - authenticated); + interceptors[i].beforeSetPassword(internalUser, credentials, + userName, credential, password, authenticated); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapCredentialHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapCredentialHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapCredentialHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,13 +33,15 @@ /** * @see org.apache.jetspeed.security.spi.CredentialHandler - * + * * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long</a> */ public class LdapCredentialHandler implements CredentialHandler { + /** The logger. */ - private static final Log LOG = LogFactory.getLog(LdapCredentialHandler.class); + private static final Log LOG = LogFactory + .getLog(LdapCredentialHandler.class); /** The {@link LdapUserCredentialDao}. */ private LdapUserCredentialDao ldap; @@ -59,11 +61,15 @@ * Constructor given a {@link LdapUserCredentialDao}. * </p> * - * @param ldap The {@link LdapUserCredentialDao}. - * @throws NamingException A {@link NamingException}. - * @throws SecurityException A {@link SecurityException}. + * @param ldap + * The {@link LdapUserCredentialDao}. + * @throws NamingException + * A {@link NamingException}. + * @throws SecurityException + * A {@link SecurityException}. */ - public LdapCredentialHandler(LdapUserCredentialDao ldap) throws NamingException, SecurityException + public LdapCredentialHandler(LdapUserCredentialDao ldap) + throws NamingException, SecurityException { this.ldap = ldap; } @@ -85,7 +91,8 @@ try { - privateCredentials.add(new DefaultPasswordCredentialImpl(uid, ldap.getPassword(uid))); + privateCredentials.add(new DefaultPasswordCredentialImpl(uid, ldap + .getPassword(uid))); } catch (SecurityException e) { @@ -99,19 +106,21 @@ { if (LOG.isErrorEnabled()) { - LOG.error("Failure creating a PasswordCredential for InternalCredential uid:" + uid, e); + LOG.error( + "Failure creating a PasswordCredential for InternalCredential uid:" + + uid, e); } } - /** * @see org.apache.jetspeed.security.spi.CredentialHandler#importPassword(java.lang.String,java.lang.String) */ - public void importPassword(String uid, String newPassword) throws SecurityException + public void importPassword(String uid, String newPassword) + throws SecurityException { ldap.changePassword(uid, newPassword); - } - + } + /** * <p> * Adds or updates a private password credential. <br> @@ -119,14 +128,19 @@ * checked (authenticated). <br> * </p> * - * @param uid The LDAP uid attribute. - * @param oldPassword The old {@link PasswordCredential}. - * @param newPassword The new {@link PasswordCredential}. - * @throws SecurityException when the lookup fails because the user does not - * exist or the non-null password is not correct. Throws a + * @param uid + * The LDAP uid attribute. + * @param oldPassword + * The old {@link PasswordCredential}. + * @param newPassword + * The new {@link PasswordCredential}. + * @throws SecurityException + * when the lookup fails because the user does not exist or the + * non-null password is not correct. Throws a * {@link SecurityException}. */ - public void setPassword(String uid, String oldPassword, String newPassword) throws SecurityException + public void setPassword(String uid, String oldPassword, String newPassword) + throws SecurityException { validate(uid, newPassword); @@ -142,7 +156,8 @@ * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordEnabled(java.lang.String, * boolean) */ - public void setPasswordEnabled(String userName, boolean enabled) throws SecurityException + public void setPasswordEnabled(String userName, boolean enabled) + throws SecurityException { // TODO Implement this. } @@ -151,24 +166,29 @@ * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordUpdateRequired(java.lang.String, * boolean) */ - public void setPasswordUpdateRequired(String userName, boolean updateRequired) throws SecurityException + public void setPasswordUpdateRequired(String userName, + boolean updateRequired) throws SecurityException { // TODO Implement this. - } + } /** - * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordExpiration(java.lang.String, java.sql.Date) + * @see org.apache.jetspeed.security.spi.CredentialHandler#setPasswordExpiration(java.lang.String, + * java.sql.Date) */ - public void setPasswordExpiration(String userName, Date expirationDate) throws SecurityException + public void setPasswordExpiration(String userName, Date expirationDate) + throws SecurityException { // TODO Implement this - + } /** - * @see org.apache.jetspeed.security.spi.CredentialHandler#authenticate(java.lang.String, java.lang.String) + * @see org.apache.jetspeed.security.spi.CredentialHandler#authenticate(java.lang.String, + * java.lang.String) */ - public boolean authenticate(String uid, String password) throws SecurityException + public boolean authenticate(String uid, String password) + throws SecurityException { validate(uid, password); @@ -180,20 +200,19 @@ * Validates the uid. * </p> * - * @param uid The uid. - * @param password The password. - * @throws SecurityException Throws a {@link SecurityException}. + * @param uid + * The uid. + * @param password + * The password. + * @throws SecurityException + * Throws a {@link SecurityException}. */ private void validate(String uid, String password) throws SecurityException { - if (StringUtils.isEmpty(password)) - { - throw new SecurityException(SecurityException.EMPTY_PARAMETER.create("password")); - } + if (StringUtils.isEmpty(password)) { throw new SecurityException( + SecurityException.EMPTY_PARAMETER.create("password")); } - if (StringUtils.isEmpty(uid)) - { - throw new SecurityException(SecurityException.EMPTY_PARAMETER.create("uid")); - } + if (StringUtils.isEmpty(uid)) { throw new SecurityException( + SecurityException.EMPTY_PARAMETER.create("uid")); } } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapGroupSecurityHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapGroupSecurityHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapGroupSecurityHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,8 +29,8 @@ import org.apache.jetspeed.security.SecurityException; import org.apache.jetspeed.security.impl.GroupPrincipalImpl; import org.apache.jetspeed.security.spi.GroupSecurityHandler; +import org.apache.jetspeed.security.spi.impl.ldap.LdapGroupDaoImpl; import org.apache.jetspeed.security.spi.impl.ldap.LdapPrincipalDao; -import org.apache.jetspeed.security.spi.impl.ldap.LdapGroupDaoImpl; /** * @see org.apache.jetspeed.security.spi.GroupSecurityHandler @@ -39,14 +39,17 @@ */ public class LdapGroupSecurityHandler implements GroupSecurityHandler { + /** The logger. */ - private static final Log logger = LogFactory.getLog(LdapGroupSecurityHandler.class); + private static final Log logger = LogFactory + .getLog(LdapGroupSecurityHandler.class); /** The {@link LdapPrincipalDao}. */ private LdapPrincipalDao ldap; /** - * @param ldap The {@link LdapPrincipalDao}. + * @param ldap + * The {@link LdapPrincipalDao}. */ public LdapGroupSecurityHandler(LdapPrincipalDao ldap) { @@ -58,8 +61,10 @@ * Default constructor. * </p> * - * @throws NamingException A {@link NamingException}. - * @throws SecurityException A {@link SecurityException}. + * @throws NamingException + * A {@link NamingException}. + * @throws SecurityException + * A {@link SecurityException}. */ public LdapGroupSecurityHandler() throws NamingException, SecurityException { @@ -71,16 +76,15 @@ */ public GroupPrincipal getGroupPrincipal(String groupPrincipalUid) { - String groupUidWithoutSlashes = ldap.convertUidToLdapAcceptableName(groupPrincipalUid); + String groupUidWithoutSlashes = ldap + .convertUidToLdapAcceptableName(groupPrincipalUid); verifyGroupId(groupUidWithoutSlashes); try { String dn = ldap.lookupByUid(groupUidWithoutSlashes); - if (!StringUtils.isEmpty(dn)) - { - return new GroupPrincipalImpl(groupPrincipalUid); - } + if (!StringUtils.isEmpty(dn)) { return new GroupPrincipalImpl( + groupPrincipalUid); } } catch (SecurityException e) { @@ -94,14 +98,13 @@ * Verify that the group uid is valid. * </p> * - * @param groupPrincipalUid The group uid. + * @param groupPrincipalUid + * The group uid. */ private void verifyGroupId(String groupPrincipalUid) { - if (StringUtils.isEmpty(groupPrincipalUid)) - { - throw new IllegalArgumentException("The groupId cannot be null or empty."); - } + if (StringUtils.isEmpty(groupPrincipalUid)) { throw new IllegalArgumentException( + "The groupId cannot be null or empty."); } } /** @@ -109,26 +112,32 @@ * Log the security exception. * </p> * - * @param e The {@link SecurityException}. - * @param groupPrincipalUid The group principal uid. + * @param e + * The {@link SecurityException}. + * @param groupPrincipalUid + * The group principal uid. */ - private void logSecurityException(SecurityException e, String groupPrincipalUid) + private void logSecurityException(SecurityException e, + String groupPrincipalUid) { if (logger.isErrorEnabled()) { - logger.error("An LDAP error has occurred for groupId:" + groupPrincipalUid, e); + logger.error("An LDAP error has occurred for groupId:" + + groupPrincipalUid, e); } } /** * @see org.apache.jetspeed.security.spi.GroupSecurityHandler#setGroupPrincipal(org.apache.jetspeed.security.GroupPrincipal) */ - public void setGroupPrincipal(GroupPrincipal groupPrincipal) throws SecurityException + public void setGroupPrincipal(GroupPrincipal groupPrincipal) + throws SecurityException { verifyGroupPrincipal(groupPrincipal); String fullPath = groupPrincipal.getFullPath(); - String groupUidWithoutSlashes = ldap.convertUidToLdapAcceptableName(fullPath); + String groupUidWithoutSlashes = ldap + .convertUidToLdapAcceptableName(fullPath); if (getGroupPrincipal(groupUidWithoutSlashes) == null) { ldap.create(groupUidWithoutSlashes); @@ -141,25 +150,26 @@ * Verify that the group principal is valid. * </p> * - * @param groupPrincipal The group principal. + * @param groupPrincipal + * The group principal. */ private void verifyGroupPrincipal(GroupPrincipal groupPrincipal) { - if (groupPrincipal == null) - { - throw new IllegalArgumentException("The GroupPrincipal cannot be null or empty."); - } + if (groupPrincipal == null) { throw new IllegalArgumentException( + "The GroupPrincipal cannot be null or empty."); } } /** * @see org.apache.jetspeed.security.spi.GroupSecurityHandler#removeGroupPrincipal(org.apache.jetspeed.security.GroupPrincipal) */ - public void removeGroupPrincipal(GroupPrincipal groupPrincipal) throws SecurityException + public void removeGroupPrincipal(GroupPrincipal groupPrincipal) + throws SecurityException { verifyGroupPrincipal(groupPrincipal); String fullPath = groupPrincipal.getFullPath(); - String groupUidWithoutSlashes = ldap.convertUidToLdapAcceptableName(fullPath); + String groupUidWithoutSlashes = ldap + .convertUidToLdapAcceptableName(fullPath); ldap.delete(groupUidWithoutSlashes); } @@ -171,7 +181,8 @@ { try { - return Arrays.asList(ldap.find(filter, GroupPrincipal.PREFS_GROUP_ROOT)); + return Arrays.asList(ldap.find(filter, + GroupPrincipal.PREFS_GROUP_ROOT)); } catch (SecurityException e) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapRoleSecurityHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapRoleSecurityHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapRoleSecurityHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,19 +29,22 @@ import org.apache.jetspeed.security.SecurityException; import org.apache.jetspeed.security.impl.RolePrincipalImpl; import org.apache.jetspeed.security.spi.RoleSecurityHandler; +import org.apache.jetspeed.security.spi.impl.ldap.LdapPrincipalDao; import org.apache.jetspeed.security.spi.impl.ldap.LdapRoleDaoImpl; -import org.apache.jetspeed.security.spi.impl.ldap.LdapPrincipalDao; -public class LdapRoleSecurityHandler implements RoleSecurityHandler { +public class LdapRoleSecurityHandler implements RoleSecurityHandler +{ - /** The logger. */ - private static final Log logger = LogFactory.getLog(LdapRoleSecurityHandler.class); + /** The logger. */ + private static final Log logger = LogFactory + .getLog(LdapRoleSecurityHandler.class); /** The {@link LdapPrincipalDao}. */ private LdapPrincipalDao ldap; /** - * @param ldap The {@link LdapPrincipalDao}. + * @param ldap + * The {@link LdapPrincipalDao}. */ public LdapRoleSecurityHandler(LdapPrincipalDao ldap) { @@ -53,78 +56,87 @@ * Default constructor. * </p> * - * @throws NamingException A {@link NamingException}. - * @throws SecurityException A {@link SecurityException}. + * @throws NamingException + * A {@link NamingException}. + * @throws SecurityException + * A {@link SecurityException}. */ public LdapRoleSecurityHandler() throws NamingException, SecurityException { this(new LdapRoleDaoImpl()); } - - public RolePrincipal getRolePrincipal(String roleFullPathName) { - String roleUidWithoutSlashes = ldap.convertUidToLdapAcceptableName(roleFullPathName); + + public RolePrincipal getRolePrincipal(String roleFullPathName) + { + String roleUidWithoutSlashes = ldap + .convertUidToLdapAcceptableName(roleFullPathName); verifyRoleId(roleUidWithoutSlashes); try { String dn = ldap.lookupByUid(roleUidWithoutSlashes); - if (!StringUtils.isEmpty(dn)) - { - return new RolePrincipalImpl(roleFullPathName); - } + if (!StringUtils.isEmpty(dn)) { return new RolePrincipalImpl( + roleFullPathName); } } catch (SecurityException e) { logSecurityException(e, roleFullPathName); } return null; - } + } - public void setRolePrincipal(RolePrincipal rolePrincipal) throws SecurityException { + public void setRolePrincipal(RolePrincipal rolePrincipal) + throws SecurityException + { verifyRolePrincipal(rolePrincipal); String fullPath = rolePrincipal.getFullPath(); - String groupUidWithoutSlashes = ldap.convertUidToLdapAcceptableName(fullPath); + String groupUidWithoutSlashes = ldap + .convertUidToLdapAcceptableName(fullPath); if (getRolePrincipal(groupUidWithoutSlashes) == null) { ldap.create(groupUidWithoutSlashes); } - } + } - public void removeRolePrincipal(RolePrincipal rolePrincipal) throws SecurityException { + public void removeRolePrincipal(RolePrincipal rolePrincipal) + throws SecurityException + { verifyRolePrincipal(rolePrincipal); String fullPath = rolePrincipal.getFullPath(); - String roleUidWithoutSlashes = ldap.convertUidToLdapAcceptableName(fullPath); + String roleUidWithoutSlashes = ldap + .convertUidToLdapAcceptableName(fullPath); ldap.delete(roleUidWithoutSlashes); - } + } - public List getRolePrincipals(String filter) { + public List getRolePrincipals(String filter) + { try { - return Arrays.asList(ldap.find(filter, RolePrincipal.PREFS_ROLE_ROOT)); + return Arrays.asList(ldap.find(filter, + RolePrincipal.PREFS_ROLE_ROOT)); } catch (SecurityException e) { logSecurityException(e, filter); } return new ArrayList(); - } - + } + /** * <p> * Verify that the group uid is valid. * </p> * - * @param groupPrincipalUid The group uid. + * @param groupPrincipalUid + * The group uid. */ private void verifyRoleId(String rolePrincipalUid) { - if (StringUtils.isEmpty(rolePrincipalUid)) - { - throw new IllegalArgumentException("The roleId cannot be null or empty."); - } + if (StringUtils.isEmpty(rolePrincipalUid)) { throw new IllegalArgumentException( + "The roleId cannot be null or empty."); } } /** @@ -132,29 +144,32 @@ * Log the security exception. * </p> * - * @param e The {@link SecurityException}. - * @param groupPrincipalUid The group principal uid. + * @param e + * The {@link SecurityException}. + * @param groupPrincipalUid + * The group principal uid. */ - private void logSecurityException(SecurityException e, String groupPrincipalUid) + private void logSecurityException(SecurityException e, + String groupPrincipalUid) { if (logger.isErrorEnabled()) { - logger.error("An LDAP error has occurred for groupId:" + groupPrincipalUid, e); + logger.error("An LDAP error has occurred for groupId:" + + groupPrincipalUid, e); } } - + /** * <p> * Verify that the group principal is valid. * </p> * - * @param groupPrincipal The group principal. + * @param groupPrincipal + * The group principal. */ private void verifyRolePrincipal(RolePrincipal rolePrincipal) { - if (rolePrincipal == null) - { - throw new IllegalArgumentException("The RolePrincipal cannot be null or empty."); - } - } + if (rolePrincipal == null) { throw new IllegalArgumentException( + "The RolePrincipal cannot be null or empty."); } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapSecurityMappingHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapSecurityMappingHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapSecurityMappingHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -43,8 +43,8 @@ /** * @see org.apache.jetspeed.security.spi.SecurityMappingHandler - * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long </a><br/> - * <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat </a> + * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long </a><br/> <a + * href="mailto:dlestrat ¡÷ apache.org">David Le Strat </a> */ public class LdapSecurityMappingHandler implements SecurityMappingHandler { @@ -52,11 +52,12 @@ private LdapUserPrincipalDao userDao; private LdapPrincipalDao groupDao; - + private LdapPrincipalDao roleDao; /** The logger. */ - private static final Log LOG = LogFactory.getLog(LdapSecurityMappingHandler.class); + private static final Log LOG = LogFactory + .getLog(LdapSecurityMappingHandler.class); /** The role hierarchy resolver. */ private HierarchyResolver roleHierarchyResolver = new GeneralizationHierarchyResolver(); @@ -68,7 +69,8 @@ * @param userDao * @param groupDao */ - public LdapSecurityMappingHandler(LdapUserPrincipalDao userDao, LdapPrincipalDao groupDao,LdapPrincipalDao roleDao) + public LdapSecurityMappingHandler(LdapUserPrincipalDao userDao, + LdapPrincipalDao groupDao, LdapPrincipalDao roleDao) { this.userDao = userDao; this.groupDao = groupDao; @@ -76,17 +78,20 @@ } /** - * @throws NamingException A {@link NamingException}. - * @throws SecurityException A {@link SecurityException}. + * @throws NamingException + * A {@link NamingException}. + * @throws SecurityException + * A {@link SecurityException}. */ - public LdapSecurityMappingHandler() throws SecurityException, NamingException + public LdapSecurityMappingHandler() throws SecurityException, + NamingException { this.userDao = new LdapUserPrincipalDaoImpl(); this.groupDao = new LdapGroupDaoImpl(); this.roleDao = new LdapRoleDaoImpl(); } - /** + /** * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#getRoleHierarchyResolver() */ public HierarchyResolver getRoleHierarchyResolver() @@ -113,7 +118,8 @@ /** * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#setGroupHierarchyResolver(org.apache.jetspeed.security.HierarchyResolver) */ - public void setGroupHierarchyResolver(HierarchyResolver groupHierarchyResolver) + public void setGroupHierarchyResolver( + HierarchyResolver groupHierarchyResolver) { this.groupHierarchyResolver = groupHierarchyResolver; } @@ -130,7 +136,8 @@ roles = userDao.getRoleUidsForUser(username); for (int i = 0; i < roles.length; i++) { - createResolvedRolePrincipalSet(username, rolePrincipals, roles, i); + createResolvedRolePrincipalSet(username, rolePrincipals, roles, + i); } } catch (SecurityException e) @@ -138,14 +145,15 @@ LOG.error(e); } return rolePrincipals; - + } /** * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#setUserPrincipalInRole(java.lang.String, * java.lang.String) */ - public void setUserPrincipalInRole(String username, String roleFullPathName) throws SecurityException + public void setUserPrincipalInRole(String username, String roleFullPathName) + throws SecurityException { verifyUserAndRoleExist(username, roleFullPathName); addRoleToUser(username, roleFullPathName); @@ -155,7 +163,8 @@ * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#removeUserPrincipalInRole(java.lang.String, * java.lang.String) */ - public void removeUserPrincipalInRole(String username, String roleFullPathName) throws SecurityException + public void removeUserPrincipalInRole(String username, + String roleFullPathName) throws SecurityException { verifyUserAndRoleExist(username, roleFullPathName); removeUserFromRole(username, roleFullPathName); @@ -170,49 +179,51 @@ String[] roles; try { - //TODO: see if we can't use the groupDao here + // TODO: see if we can't use the groupDao here roles = userDao.getRolesForGroup(groupFullPathName); for (int i = 0; i < roles.length; i++) { - createResolvedRolePrincipalSet(groupFullPathName, rolePrincipalsInGroup, roles, i); + createResolvedRolePrincipalSet(groupFullPathName, + rolePrincipalsInGroup, roles, i); } } catch (SecurityException e) { LOG.error(e); } - return rolePrincipalsInGroup; + return rolePrincipalsInGroup; } /** * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#setRolePrincipalInGroup(java.lang.String, * java.lang.String) */ - public void setRolePrincipalInGroup(String groupFullPathName, String roleFullPathName) throws SecurityException + public void setRolePrincipalInGroup(String groupFullPathName, + String roleFullPathName) throws SecurityException { verifyGroupAndRoleExist(groupFullPathName, roleFullPathName); - addRoleToGroup(groupFullPathName, roleFullPathName); + addRoleToGroup(groupFullPathName, roleFullPathName); } /** * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#removeRolePrincipalInGroup(java.lang.String, * java.lang.String) */ - public void removeRolePrincipalInGroup(String groupFullPathName, String roleFullPathName) throws SecurityException + public void removeRolePrincipalInGroup(String groupFullPathName, + String roleFullPathName) throws SecurityException { verifyGroupAndRoleExist(groupFullPathName, roleFullPathName); - removeRoleFromGroup(groupFullPathName, roleFullPathName); + removeRoleFromGroup(groupFullPathName, roleFullPathName); } - - /** + /** * This method returns the set of group principals associated with a user. * * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#getGroupPrincipals(java.lang.String) */ public Set getGroupPrincipals(String userPrincipalUid) { - Set groupPrincipals = new HashSet(); + Set groupPrincipals = new HashSet(); String[] groups; try @@ -220,7 +231,8 @@ groups = userDao.getGroupUidsForUser(userPrincipalUid); for (int i = 0; i < groups.length; i++) { - createResolvedGroupPrincipalSet(userPrincipalUid, groupPrincipals, groups, i); + createResolvedGroupPrincipalSet(userPrincipalUid, + groupPrincipals, groups, i); } } catch (SecurityException e) @@ -244,9 +256,10 @@ */ public Set getUserPrincipalsInRole(String roleFullPathName) { - //TODO: Check that this is correct - Set userPrincipals = new HashSet(); - String[] fullPaths = {roleFullPathName}; + // TODO: Check that this is correct + Set userPrincipals = new HashSet(); + String[] fullPaths = + {roleFullPathName}; try { getUserPrincipalsInRole(userPrincipals, fullPaths); @@ -268,14 +281,15 @@ */ public Set getUserPrincipalsInGroup(String groupFullPathName) { - Set userPrincipals = new HashSet(); + Set userPrincipals = new HashSet(); - //TODO: Check that this is correct - String[] fullPaths = {groupFullPathName}; + // TODO: Check that this is correct + String[] fullPaths = + {groupFullPathName}; try { - getUserPrincipalsInGroup(userPrincipals, fullPaths); + getUserPrincipalsInGroup(userPrincipals, fullPaths); } catch (SecurityException e) { @@ -291,9 +305,11 @@ * * @param userPrincipals * @param fullPaths - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ - private void getUserPrincipalsInGroup(Set userPrincipals, String[] fullPaths) throws SecurityException + private void getUserPrincipalsInGroup(Set userPrincipals, String[] fullPaths) + throws SecurityException { for (int i = 0; i < fullPaths.length; i++) { @@ -305,7 +321,7 @@ } } } - + /** * <p> * Gets the user principals in groups. @@ -313,9 +329,11 @@ * * @param userPrincipals * @param fullPaths - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ - private void getUserPrincipalsInRole(Set userPrincipals, String[] fullPaths) throws SecurityException + private void getUserPrincipalsInRole(Set userPrincipals, String[] fullPaths) + throws SecurityException { for (int i = 0; i < fullPaths.length; i++) { @@ -326,13 +344,14 @@ userPrincipals.add(userPrincipal); } } - } + } /** * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#setUserPrincipalInGroup(java.lang.String, * java.lang.String) */ - public void setUserPrincipalInGroup(String username, String groupFullPathName) throws SecurityException + public void setUserPrincipalInGroup(String username, + String groupFullPathName) throws SecurityException { verifyUserAndGroupExist(username, groupFullPathName); addGroupToUser(username, groupFullPathName); @@ -342,54 +361,53 @@ * @see org.apache.jetspeed.security.spi.SecurityMappingHandler#removeUserPrincipalInGroup(java.lang.String, * java.lang.String) */ - public void removeUserPrincipalInGroup(String username, String groupFullPathName) throws SecurityException + public void removeUserPrincipalInGroup(String username, + String groupFullPathName) throws SecurityException { verifyUserAndGroupExist(username, groupFullPathName); removeUserFromGroup(username, groupFullPathName); } + /** * @param username * @param groupFullPathName * @throws SecurityException */ - private void verifyGroupAndRoleExist(String groupFullPathName, String roleFullPathName) throws SecurityException + private void verifyGroupAndRoleExist(String groupFullPathName, + String roleFullPathName) throws SecurityException { GroupPrincipal group = getGroup(groupFullPathName); RolePrincipal role = getRole(roleFullPathName); - if ((null == group) && (null == role)) - { - throw new SecurityException(SecurityException.ROLE_DOES_NOT_EXIST); - } + if ((null == group) && (null == role)) { throw new SecurityException( + SecurityException.ROLE_DOES_NOT_EXIST); } } - + /** * @param username * @param groupFullPathName * @throws SecurityException */ - private void verifyUserAndGroupExist(String username, String groupFullPathName) throws SecurityException + private void verifyUserAndGroupExist(String username, + String groupFullPathName) throws SecurityException { UserPrincipal user = getUser(username); GroupPrincipal group = getGroup(groupFullPathName); - if ((null == user) && (null == group)) - { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST); - } - } + if ((null == user) && (null == group)) { throw new SecurityException( + SecurityException.USER_DOES_NOT_EXIST); } + } /** * @param username * @param groupFullPathName * @throws SecurityException */ - private void verifyUserAndRoleExist(String username, String roleFullPathName) throws SecurityException + private void verifyUserAndRoleExist(String username, String roleFullPathName) + throws SecurityException { UserPrincipal user = getUser(username); RolePrincipal role = getRole(roleFullPathName); - if ((null == user) && (null == role)) - { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST); - } + if ((null == user) && (null == role)) { throw new SecurityException( + SecurityException.USER_DOES_NOT_EXIST); } } /** @@ -398,19 +416,28 @@ * @param groups * @param i */ - private void createResolvedGroupPrincipalSet(String username, Set groupPrincipals, String[] groups, int i) + private void createResolvedGroupPrincipalSet(String username, + Set groupPrincipals, String[] groups, int i) { - LOG.debug("Group [" + i + "] for user[" + username + "] is [" + groups[i] + "]"); + LOG.debug("Group [" + i + "] for user[" + username + "] is [" + + groups[i] + "]"); GroupPrincipal group = new GroupPrincipalImpl(groups[i]); - Preferences preferences = Preferences.userRoot().node(group.getFullPath()); + Preferences preferences = Preferences.userRoot().node( + group.getFullPath()); LOG.debug("Group name:" + group.getName()); String[] fullPaths = groupHierarchyResolver.resolve(preferences); for (int n = 0; n < fullPaths.length; n++) { - LOG.debug("Group [" + i + "] for user[" + username + "] is [" - + GroupPrincipalImpl.getPrincipalNameFromFullPath(fullPaths[n]) + "]"); - groupPrincipals.add(new GroupPrincipalImpl(GroupPrincipalImpl.getPrincipalNameFromFullPath(fullPaths[n]))); + LOG.debug("Group [" + + i + + "] for user[" + + username + + "] is [" + + GroupPrincipalImpl + .getPrincipalNameFromFullPath(fullPaths[n]) + "]"); + groupPrincipals.add(new GroupPrincipalImpl(GroupPrincipalImpl + .getPrincipalNameFromFullPath(fullPaths[n]))); } } @@ -420,53 +447,64 @@ * @param groups * @param i */ - private void createResolvedRolePrincipalSet(String username, Set rolePrincipals, String[] roles, int i) + private void createResolvedRolePrincipalSet(String username, + Set rolePrincipals, String[] roles, int i) { - LOG.debug("Group [" + i + "] for user[" + username + "] is [" + roles[i] + "]"); + LOG.debug("Group [" + i + "] for user[" + username + "] is [" + + roles[i] + "]"); RolePrincipal role = new RolePrincipalImpl(roles[i]); - Preferences preferences = Preferences.userRoot().node(role.getFullPath()); + Preferences preferences = Preferences.userRoot().node( + role.getFullPath()); LOG.debug("Group name:" + role.getName()); String[] fullPaths = roleHierarchyResolver.resolve(preferences); for (int n = 0; n < fullPaths.length; n++) { - LOG.debug("Group [" + i + "] for user[" + username + "] is [" - + RolePrincipalImpl.getPrincipalNameFromFullPath(fullPaths[n]) + "]"); - rolePrincipals.add(new RolePrincipalImpl(RolePrincipalImpl.getPrincipalNameFromFullPath(fullPaths[n]))); + LOG.debug("Group [" + + i + + "] for user[" + + username + + "] is [" + + RolePrincipalImpl + .getPrincipalNameFromFullPath(fullPaths[n]) + "]"); + rolePrincipals.add(new RolePrincipalImpl(RolePrincipalImpl + .getPrincipalNameFromFullPath(fullPaths[n]))); } } - /** * @param username * @param groupFullPathName * @throws SecurityException */ - private void removeUserFromGroup(String username, String groupFullPathName) throws SecurityException + private void removeUserFromGroup(String username, String groupFullPathName) + throws SecurityException { userDao.removeGroup(username, groupFullPathName); } - + /** * @param username * @param groupFullPathName * @throws SecurityException */ - private void removeUserFromRole(String username, String roleFullPathName) throws SecurityException + private void removeUserFromRole(String username, String roleFullPathName) + throws SecurityException { userDao.removeRole(username, roleFullPathName); - } - - private void removeRoleFromGroup(String groupFullPathName, String roleFullPathName)throws SecurityException + } + + private void removeRoleFromGroup(String groupFullPathName, + String roleFullPathName) throws SecurityException { - userDao.removeRoleFromGroup(groupFullPathName,roleFullPathName); - } - + userDao.removeRoleFromGroup(groupFullPathName, roleFullPathName); + } /** * @param uid * @return - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ private UserPrincipal getUser(String uid) throws SecurityException { @@ -477,14 +515,16 @@ } else { - throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST.create(uid)); + throw new SecurityException(SecurityException.USER_DOES_NOT_EXIST + .create(uid)); } } /** * @param uid * @return - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ private GroupPrincipal getGroup(String uid) throws SecurityException { @@ -495,36 +535,41 @@ } else { - throw new SecurityException(SecurityException.GROUP_DOES_NOT_EXIST.create(uid)); + throw new SecurityException(SecurityException.GROUP_DOES_NOT_EXIST + .create(uid)); } } /** * @param uid * @return - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ private RolePrincipal getRole(String uid) throws SecurityException { Principal[] role = roleDao.find(uid, RolePrincipal.PREFS_ROLE_ROOT); - + if (role.length == 1) - + { return (RolePrincipal) role[0]; } else { - throw new SecurityException(SecurityException.ROLE_DOES_NOT_EXIST.create(uid)); + throw new SecurityException(SecurityException.ROLE_DOES_NOT_EXIST + .create(uid)); } } /** * @param username * @param groupFullPathName - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ - private void addGroupToUser(String username, String groupFullPathName) throws SecurityException + private void addGroupToUser(String username, String groupFullPathName) + throws SecurityException { userDao.addGroup(username, groupFullPathName); } @@ -532,22 +577,25 @@ /** * @param username * @param groupFullPathName - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ - private void addRoleToUser(String username, String roleFullPathName) throws SecurityException + private void addRoleToUser(String username, String roleFullPathName) + throws SecurityException { userDao.addRole(username, roleFullPathName); } - + /** * @param username * @param groupFullPathName - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ - private void addRoleToGroup(String groupFullPathName, String roleFullPathName) throws SecurityException + private void addRoleToGroup(String groupFullPathName, + String roleFullPathName) throws SecurityException { userDao.addRoleToGroup(groupFullPathName, roleFullPathName); - } + } - } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapUserSecurityHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapUserSecurityHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LdapUserSecurityHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -39,14 +39,17 @@ */ public class LdapUserSecurityHandler implements UserSecurityHandler { + /** The logger. */ - private static final Log logger = LogFactory.getLog(LdapUserSecurityHandler.class); + private static final Log logger = LogFactory + .getLog(LdapUserSecurityHandler.class); /** The {@link LdapPrincipalDao}. */ private LdapPrincipalDao ldap; /** - * @param ldap The LdapPrincipalDao. + * @param ldap + * The LdapPrincipalDao. */ public LdapUserSecurityHandler(LdapPrincipalDao ldap) { @@ -88,10 +91,7 @@ { String dn = ldap.lookupByUid(uid); - if (!StringUtils.isEmpty(dn)) - { - return new UserPrincipalImpl(uid); - } + if (!StringUtils.isEmpty(dn)) { return new UserPrincipalImpl(uid); } } catch (SecurityException e) { @@ -106,19 +106,20 @@ * Verify the uid. * </p> * - * @param uid The uid. + * @param uid + * The uid. */ private void verifyUid(String uid) { - if (StringUtils.isEmpty(uid)) - { - throw new IllegalArgumentException("The uid cannot be null or empty."); - } + if (StringUtils.isEmpty(uid)) { throw new IllegalArgumentException( + "The uid cannot be null or empty."); } } /** - * @param se SecurityException Throws a {@link SecurityException}. - * @param uid The uid. + * @param se + * SecurityException Throws a {@link SecurityException}. + * @param uid + * The uid. */ private void logSecurityException(SecurityException se, String uid) { @@ -135,7 +136,8 @@ { try { - return Arrays.asList(ldap.find(filter, UserPrincipal.PREFS_USER_ROOT)); + return Arrays.asList(ldap.find(filter, + UserPrincipal.PREFS_USER_ROOT)); } catch (SecurityException e) { @@ -165,22 +167,22 @@ /** * @see org.apache.jetspeed.security.spi.UserSecurityHandler#addUserPrincipal(org.apache.jetspeed.security.UserPrincipal) */ - public void addUserPrincipal(UserPrincipal userPrincipal) throws SecurityException + public void addUserPrincipal(UserPrincipal userPrincipal) + throws SecurityException { verifyUserPrincipal(userPrincipal); String uid = userPrincipal.getName(); - if (isUserPrincipal(uid)) - { - throw new SecurityException(SecurityException.USER_ALREADY_EXISTS.create(uid)); - } + if (isUserPrincipal(uid)) { throw new SecurityException( + SecurityException.USER_ALREADY_EXISTS.create(uid)); } ldap.create(uid); } /** * @see org.apache.jetspeed.security.spi.UserSecurityHandler#updateUserPrincipal(org.apache.jetspeed.security.UserPrincipal) */ - public void updateUserPrincipal(UserPrincipal userPrincipal) throws SecurityException + public void updateUserPrincipal(UserPrincipal userPrincipal) + throws SecurityException { verifyUserPrincipal(userPrincipal); String uid = userPrincipal.getName(); @@ -195,16 +197,15 @@ */ private void verifyUserPrincipal(UserPrincipal userPrincipal) { - if (userPrincipal == null) - { - throw new IllegalArgumentException("The UserPrincipal cannot be null or empty."); - } + if (userPrincipal == null) { throw new IllegalArgumentException( + "The UserPrincipal cannot be null or empty."); } } /** * @see org.apache.jetspeed.security.spi.UserSecurityHandler#removeUserPrincipal(org.apache.jetspeed.security.UserPrincipal) */ - public void removeUserPrincipal(UserPrincipal userPrincipal) throws SecurityException + public void removeUserPrincipal(UserPrincipal userPrincipal) + throws SecurityException { verifyUserPrincipal(userPrincipal); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LengthCredentialPasswordValidator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LengthCredentialPasswordValidator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/LengthCredentialPasswordValidator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -4,8 +4,10 @@ import org.apache.jetspeed.security.SecurityException; import org.apache.jetspeed.security.spi.CredentialPasswordValidator; -public class LengthCredentialPasswordValidator implements CredentialPasswordValidator +public class LengthCredentialPasswordValidator implements + CredentialPasswordValidator { + private int minPasswordLength; private int maxPasswordLength; @@ -14,12 +16,14 @@ private int minDigitLength; - public LengthCredentialPasswordValidator(int minPasswordLength, int maxPasswordLength) + public LengthCredentialPasswordValidator(int minPasswordLength, + int maxPasswordLength) { this(minPasswordLength, maxPasswordLength, 0, 0); } - public LengthCredentialPasswordValidator(int minPasswordLength, int maxPasswordLength, int minLetterLength, int minDigitLength) + public LengthCredentialPasswordValidator(int minPasswordLength, + int maxPasswordLength, int minLetterLength, int minDigitLength) { this.minPasswordLength = minPasswordLength; this.maxPasswordLength = maxPasswordLength; @@ -36,15 +40,9 @@ char[] pwd = clearTextPassword.toCharArray(); - if (minPasswordLength > 0 && pwd.length < minPasswordLength) - { - throw new InvalidPasswordException(); - } + if (minPasswordLength > 0 && pwd.length < minPasswordLength) { throw new InvalidPasswordException(); } - if (maxPasswordLength > 0 && maxPasswordLength < pwd.length) - { - throw new InvalidPasswordException(); - } + if (maxPasswordLength > 0 && maxPasswordLength < pwd.length) { throw new InvalidPasswordException(); } if (minLetterLength > 0) { @@ -56,10 +54,7 @@ count++; } } - if (count < minLetterLength) - { - throw new InvalidPasswordException(); - } + if (count < minLetterLength) { throw new InvalidPasswordException(); } } if (minDigitLength > 0) @@ -72,10 +67,7 @@ count++; } } - if (count < minDigitLength) - { - throw new InvalidPasswordException(); - } + if (count < minDigitLength) { throw new InvalidPasswordException(); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/MaxPasswordAuthenticationFailuresInterceptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/MaxPasswordAuthenticationFailuresInterceptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/MaxPasswordAuthenticationFailuresInterceptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi.impl; import java.util.Collection; @@ -24,47 +24,66 @@ /** * <p> - * Enforces a {@link #MaxPasswordAuthenticationFailuresInterceptor(int) maximum number of times} a user may provide an invalid password. - * Once the maximum number of invalid authentications is reached, the credential is disabled.</p> + * Enforces a + * {@link #MaxPasswordAuthenticationFailuresInterceptor(int) maximum number of times} + * a user may provide an invalid password. Once the maximum number of invalid + * authentications is reached, the credential is disabled. + * </p> * <p> - * Note: the current count is <em>not</em> reset on valid authentication by this interceptor. - * This is done by the {@link DefaultCredentialHandler} which invokes the interceptor(s) after authentication - * and no interceptor {@link #afterAuthenticated(InternalUserPrincipal, String, InternalCredential, boolean) afterAuthenicated} - * method returns true.</p> + * Note: the current count is <em>not</em> reset on valid authentication by + * this interceptor. This is done by the {@link DefaultCredentialHandler} which + * invokes the interceptor(s) after authentication and no interceptor + * {@link #afterAuthenticated(InternalUserPrincipal, String, InternalCredential, boolean) afterAuthenicated} + * method returns true. + * </p> * <p> - * But, this interceptor <em>does</em> (re)sets the count on creation and on change of the password.</p> + * But, this interceptor <em>does</em> (re)sets the count on creation and on + * change of the password. + * </p> * <p> * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id$ */ -public class MaxPasswordAuthenticationFailuresInterceptor extends AbstractInternalPasswordCredentialInterceptorImpl +public class MaxPasswordAuthenticationFailuresInterceptor extends + AbstractInternalPasswordCredentialInterceptorImpl { + private int maxNumberOfAuthenticationFailures; - + /** * <p> - * Configure the maximum number of invalid authentications allowed in a row.</p> + * Configure the maximum number of invalid authentications allowed in a row. + * </p> * <p> - * A value of zero (0) disables the check</p> + * A value of zero (0) disables the check + * </p> */ - public MaxPasswordAuthenticationFailuresInterceptor(int maxNumberOfAuthenticationFailures) + public MaxPasswordAuthenticationFailuresInterceptor( + int maxNumberOfAuthenticationFailures) { this.maxNumberOfAuthenticationFailures = maxNumberOfAuthenticationFailures; } - + /** - * Checks the current count of authentication failures when the credential is not expired and authentication failed. - * @return true if the maximum number of invalid authentications is reached and the credential is disabled. - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterAuthenticated(org.apache.jetspeed.security.om.InternalUserPrincipal, java.lang.String, org.apache.jetspeed.security.om.InternalCredential, boolean) + * Checks the current count of authentication failures when the credential + * is not expired and authentication failed. + * + * @return true if the maximum number of invalid authentications is reached + * and the credential is disabled. + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterAuthenticated(org.apache.jetspeed.security.om.InternalUserPrincipal, + * java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential, boolean) */ - public boolean afterAuthenticated(InternalUserPrincipal internalUser, String userName, - InternalCredential credential, boolean authenticated) throws SecurityException + public boolean afterAuthenticated(InternalUserPrincipal internalUser, + String userName, InternalCredential credential, + boolean authenticated) throws SecurityException { boolean update = false; - if ( !credential.isExpired() && !authenticated && maxNumberOfAuthenticationFailures > 0 ) + if (!credential.isExpired() && !authenticated + && maxNumberOfAuthenticationFailures > 0) { - int authenticationFailures = credential.getAuthenticationFailures()+1; + int authenticationFailures = credential.getAuthenticationFailures() + 1; credential.setAuthenticationFailures(authenticationFailures); if (authenticationFailures >= maxNumberOfAuthenticationFailures) { @@ -74,23 +93,34 @@ } return update; } - + /** * Sets the count of invalid authentications to zero (0). - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeCreate(org.apache.jetspeed.security.om.InternalUserPrincipal, java.util.Collection, java.lang.String, InternalCredential, java.lang.String) + * + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeCreate(org.apache.jetspeed.security.om.InternalUserPrincipal, + * java.util.Collection, java.lang.String, InternalCredential, + * java.lang.String) */ - public void beforeCreate(InternalUserPrincipal internalUser, Collection credentials, String userName, - InternalCredential credential, String password) throws SecurityException + public void beforeCreate(InternalUserPrincipal internalUser, + Collection credentials, String userName, + InternalCredential credential, String password) + throws SecurityException { credential.setAuthenticationFailures(0); } - + /** * Resets the count of invalid authentications to zero (0). - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeSetPassword(org.apache.jetspeed.security.om.InternalUserPrincipal, java.util.Collection, java.lang.String, org.apache.jetspeed.security.om.InternalCredential, java.lang.String, boolean) + * + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeSetPassword(org.apache.jetspeed.security.om.InternalUserPrincipal, + * java.util.Collection, java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential, + * java.lang.String, boolean) */ - public void beforeSetPassword(InternalUserPrincipal internalUser, Collection credentials, String userName, - InternalCredential credential, String password, boolean authenticated) throws SecurityException + public void beforeSetPassword(InternalUserPrincipal internalUser, + Collection credentials, String userName, + InternalCredential credential, String password, + boolean authenticated) throws SecurityException { credential.setAuthenticationFailures(0); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/MessageDigestCredentialPasswordEncoder.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/MessageDigestCredentialPasswordEncoder.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/MessageDigestCredentialPasswordEncoder.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi.impl; import java.security.MessageDigest; @@ -29,48 +29,58 @@ * </p> * * @author <a href="mailto:ate ¡÷ apache.org">Ate Douma</a> - * @version $Id: MessageDigestCredentialPasswordEncoder.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: MessageDigestCredentialPasswordEncoder.java 516448 2007-03-09 + * 16:25:47Z ate $ */ -public class MessageDigestCredentialPasswordEncoder implements CredentialPasswordEncoder +public class MessageDigestCredentialPasswordEncoder implements + CredentialPasswordEncoder { - // Allow copying of encoded passwords or salt the digest with the userName preventing that + + // Allow copying of encoded passwords or salt the digest with the userName + // preventing that boolean simpleEncryption = false; + MessageDigest digester; - - public MessageDigestCredentialPasswordEncoder() throws NoSuchAlgorithmException + + public MessageDigestCredentialPasswordEncoder() + throws NoSuchAlgorithmException { this("SHA-1", false); } - - public MessageDigestCredentialPasswordEncoder(boolean simpleEncryption) throws NoSuchAlgorithmException + + public MessageDigestCredentialPasswordEncoder(boolean simpleEncryption) + throws NoSuchAlgorithmException { this("SHA-1", simpleEncryption); } - - public MessageDigestCredentialPasswordEncoder(String algorithm) throws NoSuchAlgorithmException + + public MessageDigestCredentialPasswordEncoder(String algorithm) + throws NoSuchAlgorithmException { this(algorithm, false); } - - public MessageDigestCredentialPasswordEncoder(String algorithm, boolean simpleEncryption) throws NoSuchAlgorithmException + + public MessageDigestCredentialPasswordEncoder(String algorithm, + boolean simpleEncryption) throws NoSuchAlgorithmException { this.digester = MessageDigest.getInstance(algorithm); this.simpleEncryption = simpleEncryption; } - + public String getAlgorithm() { return digester.getAlgorithm(); } /** - * @see org.apache.jetspeed.security.spi.CredentialPasswordEncoder#encode(java.lang.String, java.lang.String) + * @see org.apache.jetspeed.security.spi.CredentialPasswordEncoder#encode(java.lang.String, + * java.lang.String) */ public String encode(String userName, String clearTextPassword) throws SecurityException { byte[] value; - synchronized(digester) + synchronized (digester) { digester.reset(); value = digester.digest(clearTextPassword.getBytes()); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/PBEPasswordService.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/PBEPasswordService.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/PBEPasswordService.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,13 +25,15 @@ /** * <p> - * PBEPasswordService provides an PBE based PasswordEncodingService, allowing decoding of user passwords + * PBEPasswordService provides an PBE based PasswordEncodingService, allowing + * decoding of user passwords * </p> * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id$ */ -public class PBEPasswordService extends PBEPasswordTool implements PasswordEncodingService, CredentialPasswordEncoder +public class PBEPasswordService extends PBEPasswordTool implements + PasswordEncodingService, CredentialPasswordEncoder { /** @@ -39,7 +41,8 @@ * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException */ - public PBEPasswordService(String pbePassword) throws InvalidKeySpecException, NoSuchAlgorithmException + public PBEPasswordService(String pbePassword) + throws InvalidKeySpecException, NoSuchAlgorithmException { super(pbePassword); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/PasswordExpirationInterceptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/PasswordExpirationInterceptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/PasswordExpirationInterceptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi.impl; import java.sql.Date; @@ -26,51 +26,67 @@ /** * <p> - * Enforces a maximum lifespan for a password credential.</p> - * When {@link #afterAuthenticated(InternalUserPrincipal, String, InternalCredential, boolean) on authentication} - * a password its expiration date is reached, its expired flag is set. - * The {@link DefaultCredentialHandler} then will fail the authentication and subsequent authentications - * will fail immediately.</p> + * Enforces a maximum lifespan for a password credential. + * </p> + * When + * {@link #afterAuthenticated(InternalUserPrincipal, String, InternalCredential, boolean) on authentication} + * a password its expiration date is reached, its expired flag is set. The + * {@link DefaultCredentialHandler} then will fail the authentication and + * subsequent authentications will fail immediately. + * </p> * <p> - * To ensure proper expiration handling, an empty (null) expiration date will be automatically - * filled in when the credential is loaded from the persistent store using the {@link #PasswordExpirationInterceptor(int) configured} - * max lifespan in days.</p> + * To ensure proper expiration handling, an empty (null) expiration date will be + * automatically filled in when the credential is loaded from the persistent + * store using the {@link #PasswordExpirationInterceptor(int) configured} max + * lifespan in days. + * </p> * <p> - * When a password credential is {@link #beforeCreate(InternalUserPrincipal, Collection, String, InternalCredential, String) created} - * or a password is {@link #beforeSetPassword(InternalUserPrincipal, Collection, String, InternalCredential, String, boolean) updated} - * a new future expiration date is calculated.</p> + * When a password credential is + * {@link #beforeCreate(InternalUserPrincipal, Collection, String, InternalCredential, String) created} + * or a password is + * {@link #beforeSetPassword(InternalUserPrincipal, Collection, String, InternalCredential, String, boolean) updated} + * a new future expiration date is calculated. + * </p> * <p> - * An existing or already provided higher expiration date will be preserved though. - * This allows to (pre)set a (very) high expiration date, like with {@link InternalCredential#MAX_DATE}, - * for credentials which shouldn't expire.</p> + * An existing or already provided higher expiration date will be preserved + * though. This allows to (pre)set a (very) high expiration date, like with + * {@link InternalCredential#MAX_DATE}, for credentials which shouldn't expire. + * </p> * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id$ */ -public class PasswordExpirationInterceptor extends AbstractInternalPasswordCredentialInterceptorImpl +public class PasswordExpirationInterceptor extends + AbstractInternalPasswordCredentialInterceptorImpl { + private long maxLifeSpanInMillis; - + /** - * @param maxLifeSpanInDays default lifespan of password credentials in days + * @param maxLifeSpanInDays + * default lifespan of password credentials in days */ public PasswordExpirationInterceptor(int maxLifeSpanInDays) { - this.maxLifeSpanInMillis = (long)(maxLifeSpanInDays) * 1000*60*60*24; + this.maxLifeSpanInMillis = (long) (maxLifeSpanInDays) * 1000 * 60 * 60 + * 24; } - + /** * @return true when the password credential is now expired - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterAuthenticated(org.apache.jetspeed.security.om.InternalUserPrincipal, java.lang.String, org.apache.jetspeed.security.om.InternalCredential, boolean) + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterAuthenticated(org.apache.jetspeed.security.om.InternalUserPrincipal, + * java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential, boolean) */ - public boolean afterAuthenticated(InternalUserPrincipal internalUser, String userName, - InternalCredential credential, boolean authenticated) throws SecurityException + public boolean afterAuthenticated(InternalUserPrincipal internalUser, + String userName, InternalCredential credential, + boolean authenticated) throws SecurityException { boolean update = false; - if ( !credential.isExpired() ) + if (!credential.isExpired()) { long expirationTime = credential.getExpirationDate().getTime(); - long currentTime = new java.util.Date().getTime(); + long currentTime = new java.util.Date().getTime(); if (expirationTime <= currentTime) { credential.setExpired(true); @@ -79,47 +95,67 @@ } return update; } - + /** * @return true when a new default expiration date is set - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterLoad(org.apache.jetspeed.security.spi.PasswordCredentialProvider, java.lang.String, org.apache.jetspeed.security.om.InternalCredential) + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterLoad(org.apache.jetspeed.security.spi.PasswordCredentialProvider, + * java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential) */ - public boolean afterLoad(PasswordCredentialProvider pcProvider, String userName, InternalCredential credential) + public boolean afterLoad(PasswordCredentialProvider pcProvider, + String userName, InternalCredential credential) throws SecurityException { boolean update = false; - if ( credential.getExpirationDate() == null ) + if (credential.getExpirationDate() == null) { - credential.setExpirationDate(new Date(new java.util.Date().getTime()+maxLifeSpanInMillis)); + credential.setExpirationDate(new Date(new java.util.Date() + .getTime() + + maxLifeSpanInMillis)); update = true; } return update; } - + /** - * Calculates and sets the default expiration date and the expired flag to false - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeCreate(org.apache.jetspeed.security.om.InternalUserPrincipal, java.util.Collection, java.lang.String, InternalCredential, java.lang.String) + * Calculates and sets the default expiration date and the expired flag to + * false + * + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeCreate(org.apache.jetspeed.security.om.InternalUserPrincipal, + * java.util.Collection, java.lang.String, InternalCredential, + * java.lang.String) */ - public void beforeCreate(InternalUserPrincipal internalUser, Collection credentials, String userName, - InternalCredential credential, String password) throws SecurityException + public void beforeCreate(InternalUserPrincipal internalUser, + Collection credentials, String userName, + InternalCredential credential, String password) + throws SecurityException { setExpiration(credential); } - + /** - * Sets a new expiration date if a higher expiration date isn't set already and resets the expired flag - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeSetPassword(org.apache.jetspeed.security.om.InternalUserPrincipal, java.util.Collection, java.lang.String, org.apache.jetspeed.security.om.InternalCredential, java.lang.String, boolean) + * Sets a new expiration date if a higher expiration date isn't set already + * and resets the expired flag + * + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeSetPassword(org.apache.jetspeed.security.om.InternalUserPrincipal, + * java.util.Collection, java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential, + * java.lang.String, boolean) */ - public void beforeSetPassword(InternalUserPrincipal internalUser, Collection credentials, String userName, - InternalCredential credential, String password, boolean authenticated) throws SecurityException + public void beforeSetPassword(InternalUserPrincipal internalUser, + Collection credentials, String userName, + InternalCredential credential, String password, + boolean authenticated) throws SecurityException { setExpiration(credential); } - + protected void setExpiration(InternalCredential credential) { - Date nextExpirationDate = new Date(new java.util.Date().getTime()+maxLifeSpanInMillis); - if ( credential.getExpirationDate() == null || credential.getExpirationDate().before(nextExpirationDate)) + Date nextExpirationDate = new Date(new java.util.Date().getTime() + + maxLifeSpanInMillis); + if (credential.getExpirationDate() == null + || credential.getExpirationDate().before(nextExpirationDate)) { credential.setExpirationDate(nextExpirationDate); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/PasswordHistoryInterceptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/PasswordHistoryInterceptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/PasswordHistoryInterceptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi.impl; import java.sql.Timestamp; @@ -32,68 +32,86 @@ /** * <p> - * Maintains a configurable FIFO stack of used password credentials for a principal. - * It also requires a unique password (with regards to the values currently in the stack) when - * a password is changed directly by the user itself.</p> + * Maintains a configurable FIFO stack of used password credentials for a + * principal. It also requires a unique password (with regards to the values + * currently in the stack) when a password is changed directly by the user + * itself. + * </p> * <p> - * The historical passwords are maintained as {@link InternalCredential} instances with as {@link InternalCredential#getClassname() classname} - * value {@link #HISTORICAL_PASSWORD_CREDENTIAL} to distinguish them from the current password credential.</p> + * The historical passwords are maintained as {@link InternalCredential} + * instances with as {@link InternalCredential#getClassname() classname} value + * {@link #HISTORICAL_PASSWORD_CREDENTIAL} to distinguish them from the current + * password credential. + * </p> * <p> * <em>Implementation Note:</em><br> - * When a new password is about to be saved, a new <em>copy</em> of the current credential is saved as - * a historic password credential. This means that the current password credential <em>instance</em>, - * and thus also its {@link InternalCredential#getCredentialId() key}, remains the same.</p> + * When a new password is about to be saved, a new <em>copy</em> of the + * current credential is saved as a historic password credential. This means + * that the current password credential <em>instance</em>, and thus also its + * {@link InternalCredential#getCredentialId() key}, remains the same. + * </p> * <p> * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id$ */ -public class PasswordHistoryInterceptor extends AbstractInternalPasswordCredentialInterceptorImpl +public class PasswordHistoryInterceptor extends + AbstractInternalPasswordCredentialInterceptorImpl { + private int historySize; - + /** - * Value used for {@link InternalCredential#getClassname()} to distinguish from current password credentials + * Value used for {@link InternalCredential#getClassname()} to distinguish + * from current password credentials */ public static final String HISTORICAL_PASSWORD_CREDENTIAL = "org.apache.jetspeed.security.spi.impl.HistoricalPasswordCredentialImpl"; - - private static final Comparator internalCredentialCreationDateComparator = - new Comparator() + + private static final Comparator internalCredentialCreationDateComparator = new Comparator() + { + + public int compare(Object obj1, Object obj2) { - public int compare(Object obj1, Object obj2) - { - return ((InternalCredential)obj2).getCreationDate().compareTo(((InternalCredential)obj1).getCreationDate()); - } - }; - + return ((InternalCredential) obj2).getCreationDate().compareTo( + ((InternalCredential) obj1).getCreationDate()); + } + }; + /** - * @param historySize stack size maintained for historical passwords + * @param historySize + * stack size maintained for historical passwords */ public PasswordHistoryInterceptor(int historySize) { this.historySize = historySize; } - + /** - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeSetPassword(org.apache.jetspeed.security.om.InternalUserPrincipal, java.util.Collection, java.lang.String, org.apache.jetspeed.security.om.InternalCredential, java.lang.String, boolean) + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#beforeSetPassword(org.apache.jetspeed.security.om.InternalUserPrincipal, + * java.util.Collection, java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential, + * java.lang.String, boolean) */ - public void beforeSetPassword(InternalUserPrincipal internalUser, Collection credentials, String userName, - InternalCredential credential, String password, boolean authenticated) throws SecurityException + public void beforeSetPassword(InternalUserPrincipal internalUser, + Collection credentials, String userName, + InternalCredential credential, String password, + boolean authenticated) throws SecurityException { Collection internalCredentials = internalUser.getCredentials(); ArrayList historicalPasswordCredentials = new ArrayList(); - if ( internalCredentials != null ) + if (internalCredentials != null) { InternalCredential currCredential; Iterator iter = internalCredentials.iterator(); - + while (iter.hasNext()) { currCredential = (InternalCredential) iter.next(); - if (currCredential.getType() == InternalCredential.PRIVATE ) + if (currCredential.getType() == InternalCredential.PRIVATE) { if ((null != currCredential.getClassname()) - && (currCredential.getClassname().equals(HISTORICAL_PASSWORD_CREDENTIAL))) + && (currCredential.getClassname() + .equals(HISTORICAL_PASSWORD_CREDENTIAL))) { historicalPasswordCredentials.add(currCredential); } @@ -102,33 +120,35 @@ } if (historicalPasswordCredentials.size() > 1) { - Collections.sort(historicalPasswordCredentials,internalCredentialCreationDateComparator); + Collections.sort(historicalPasswordCredentials, + internalCredentialCreationDateComparator); } - + int historyCount = historicalPasswordCredentials.size(); InternalCredential historicalPasswordCredential; - if ( authenticated ) + if (authenticated) { // check password already used - for ( int i = 0; i < historyCount && i < historySize; i++ ) + for (int i = 0; i < historyCount && i < historySize; i++) { - historicalPasswordCredential = (InternalCredential)historicalPasswordCredentials.get(i); - if ( historicalPasswordCredential.getValue() != null && - historicalPasswordCredential.getValue().equals(password) ) - { - throw new PasswordAlreadyUsedException(); - } + historicalPasswordCredential = (InternalCredential) historicalPasswordCredentials + .get(i); + if (historicalPasswordCredential.getValue() != null + && historicalPasswordCredential.getValue().equals( + password)) { throw new PasswordAlreadyUsedException(); } } } - for ( int i = historySize-1; i < historyCount; i++ ) + for (int i = historySize - 1; i < historyCount; i++) { credentials.remove(historicalPasswordCredentials.get(i)); } - historicalPasswordCredential = new InternalCredentialImpl(credential,HISTORICAL_PASSWORD_CREDENTIAL); + historicalPasswordCredential = new InternalCredentialImpl(credential, + HISTORICAL_PASSWORD_CREDENTIAL); credentials.add(historicalPasswordCredential); - - // fake update to current InternalCredential as being an insert of a new one + + // fake update to current InternalCredential as being an insert of a new + // one credential.setCreationDate(new Timestamp(new Date().getTime())); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/RegexCredentialPasswordValidator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/RegexCredentialPasswordValidator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/RegexCredentialPasswordValidator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -4,8 +4,10 @@ import org.apache.jetspeed.security.SecurityException; import org.apache.jetspeed.security.spi.CredentialPasswordValidator; -public class RegexCredentialPasswordValidator implements CredentialPasswordValidator +public class RegexCredentialPasswordValidator implements + CredentialPasswordValidator { + private String regex; public RegexCredentialPasswordValidator(String regex) @@ -20,10 +22,7 @@ clearTextPassword = ""; } - if (!clearTextPassword.matches(regex)) - { - throw new InvalidPasswordException(); - } + if (!clearTextPassword.matches(regex)) { throw new InvalidPasswordException(); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ReservedWordsCredentialPasswordValidator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ReservedWordsCredentialPasswordValidator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ReservedWordsCredentialPasswordValidator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -6,8 +6,10 @@ import org.apache.jetspeed.security.SecurityException; import org.apache.jetspeed.security.spi.CredentialPasswordValidator; -public class ReservedWordsCredentialPasswordValidator implements CredentialPasswordValidator +public class ReservedWordsCredentialPasswordValidator implements + CredentialPasswordValidator { + private String[] reservedWords; private boolean ignoreCase; @@ -17,7 +19,8 @@ this(words, false); } - public ReservedWordsCredentialPasswordValidator(List words, boolean ignoreCase) + public ReservedWordsCredentialPasswordValidator(List words, + boolean ignoreCase) { this.reservedWords = (String[]) words.toArray(new String[words.size()]); this.ignoreCase = ignoreCase; @@ -34,20 +37,14 @@ { for (int i = 0; i < reservedWords.length; i++) { - if (clearTextPassword.equalsIgnoreCase(reservedWords[i])) - { - throw new InvalidPasswordException(); - } + if (clearTextPassword.equalsIgnoreCase(reservedWords[i])) { throw new InvalidPasswordException(); } } } else { for (int i = 0; i < reservedWords.length; i++) { - if (clearTextPassword.equals(reservedWords[i])) - { - throw new InvalidPasswordException(); - } + if (clearTextPassword.equals(reservedWords[i])) { throw new InvalidPasswordException(); } } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/SecurityAccessImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/SecurityAccessImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/SecurityAccessImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -45,9 +45,9 @@ * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat </a> * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor </a> */ -public class SecurityAccessImpl extends InitablePersistenceBrokerDaoSupport implements SecurityAccess +public class SecurityAccessImpl extends InitablePersistenceBrokerDaoSupport + implements SecurityAccess { - /** * @@ -55,15 +55,16 @@ */ public SecurityAccessImpl(String repositoryPath) { - super(repositoryPath); + super(repositoryPath); } - + /** * <p> * Returns if a Internal UserPrincipal is defined for the user name. * </p> * - * @param username The user name. + * @param username + * The user name. * @return true if the user is known */ public boolean isKnownUser(String username) @@ -74,10 +75,12 @@ Criteria filter = new Criteria(); filter.addEqualTo("fullPath", fullPath); // The isMappingOnly must not be true. - // We don't need the mapping only user, mapping user can't be authenticated with this provider. + // We don't need the mapping only user, mapping user can't be + // authenticated with this provider. // we just need the true user. filter.addEqualTo("isMappingOnly", Boolean.FALSE); - Query query = QueryFactory.newQuery(InternalUserPrincipalImpl.class, filter); + Query query = QueryFactory.newQuery(InternalUserPrincipalImpl.class, + filter); return getPersistenceBrokerTemplate().getCount(query) == 1; } @@ -86,7 +89,8 @@ * Returns the {@link InternalUserPrincipal} from the user name. * </p> * - * @param username The user name. + * @param username + * The user name. * @return The {@link InternalUserPrincipal}. */ public InternalUserPrincipal getInternalUserPrincipal(String username) @@ -96,21 +100,26 @@ // Get user. Criteria filter = new Criteria(); filter.addEqualTo("fullPath", fullPath); - Query query = QueryFactory.newQuery(InternalUserPrincipalImpl.class, filter); - InternalUserPrincipal internalUser = (InternalUserPrincipal) getPersistenceBrokerTemplate().getObjectByQuery(query); + Query query = QueryFactory.newQuery(InternalUserPrincipalImpl.class, + filter); + InternalUserPrincipal internalUser = (InternalUserPrincipal) getPersistenceBrokerTemplate() + .getObjectByQuery(query); return internalUser; } - + /** * <p> * Returns the {@link InternalUserPrincipal} from the user name. * </p> * - * @param username The user name. - * @param isMappingOnly Whether a principal's purpose is for security mappping only. + * @param username + * The user name. + * @param isMappingOnly + * Whether a principal's purpose is for security mappping only. * @return The {@link InternalUserPrincipal}. */ - public InternalUserPrincipal getInternalUserPrincipal(String username, boolean isMappingOnly) + public InternalUserPrincipal getInternalUserPrincipal(String username, + boolean isMappingOnly) { UserPrincipal userPrincipal = new UserPrincipalImpl(username); String fullPath = userPrincipal.getFullPath(); @@ -118,8 +127,10 @@ Criteria filter = new Criteria(); filter.addEqualTo("fullPath", fullPath); filter.addEqualTo("isMappingOnly", new Boolean(isMappingOnly)); - Query query = QueryFactory.newQuery(InternalUserPrincipalImpl.class, filter); - InternalUserPrincipal internalUser = (InternalUserPrincipal) getPersistenceBrokerTemplate().getObjectByQuery(query); + Query query = QueryFactory.newQuery(InternalUserPrincipalImpl.class, + filter); + InternalUserPrincipal internalUser = (InternalUserPrincipal) getPersistenceBrokerTemplate() + .getObjectByQuery(query); return internalUser; } @@ -128,7 +139,8 @@ * Returns a collection of {@link Principal}given the filter. * </p> * - * @param filter The filter. + * @param filter + * The filter. * @return Collection of {@link InternalUserPrincipal}. */ public Iterator getInternalUserPrincipals(String filter) @@ -155,8 +167,10 @@ { queryCriteria.addLike("fullPath", UserPrincipal.PREFS_USER_ROOT + filter + "%"); - Query query = QueryFactory.newQuery(InternalUserPrincipalImpl.class, queryCriteria); - Iterator result = getPersistenceBrokerTemplate().getIteratorByQuery(query); + Query query = QueryFactory.newQuery( + InternalUserPrincipalImpl.class, queryCriteria); + Iterator result = getPersistenceBrokerTemplate() + .getIteratorByQuery(query); return result; } } @@ -166,7 +180,8 @@ * Returns the number of {@link Principal} given the filter. * </p> * - * @param filter The filter. + * @param filter + * The filter. * @return The number of {@link InternalUserPrincipal}. */ public int getInternalUserCount(String filter) @@ -192,36 +207,40 @@ { queryCriteria.addLike("fullPath", UserPrincipal.PREFS_USER_ROOT + filter + "%"); - Query query = QueryFactory.newQuery(InternalUserPrincipalImpl.class, queryCriteria); + Query query = QueryFactory.newQuery( + InternalUserPrincipalImpl.class, queryCriteria); int count = getPersistenceBrokerTemplate().getCount(query); return count; } } - private String getFilterParameter(String filter, String key,String defaultValue) + private String getFilterParameter(String filter, String key, + String defaultValue) { StringTokenizer st = new StringTokenizer(filter, ", "); while (st.hasMoreTokens()) { String pair = st.nextToken(); - if (pair.startsWith(key + "=")) - { - return pair.substring(key.length() + 1); - } + if (pair.startsWith(key + "=")) { return pair.substring(key + .length() + 1); } } return defaultValue; } - + /** * <p> * Sets the given {@link InternalUserPrincipal}. * </p> * - * @param internalUser The {@link InternalUserPrincipal}. - * @param isMappingOnly Whether a principal's purpose is for security mappping only. - * @throws SecurityException Throws a {@link SecurityException}. + * @param internalUser + * The {@link InternalUserPrincipal}. + * @param isMappingOnly + * Whether a principal's purpose is for security mappping only. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - public void setInternalUserPrincipal(InternalUserPrincipal internalUser, boolean isMappingOnly) throws SecurityException + public void setInternalUserPrincipal(InternalUserPrincipal internalUser, + boolean isMappingOnly) throws SecurityException { try { @@ -233,9 +252,9 @@ } catch (Exception e) { - KeyedMessage msg = SecurityException.UNEXPECTED.create("SecurityAccess.setInternalUserPrincipal", - "store", - e.getMessage()); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "SecurityAccess.setInternalUserPrincipal", "store", e + .getMessage()); logger.error(msg, e); throw new SecurityException(msg, e); } @@ -246,10 +265,13 @@ * Remove the given {@link InternalUserPrincipal}. * </p> * - * @param internalUser The {@link InternalUserPrincipal}. - * @throws SecurityException Throws a {@link SecurityException}. + * @param internalUser + * The {@link InternalUserPrincipal}. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - public void removeInternalUserPrincipal(InternalUserPrincipal internalUser) throws SecurityException + public void removeInternalUserPrincipal(InternalUserPrincipal internalUser) + throws SecurityException { try { @@ -263,9 +285,9 @@ } catch (Exception e) { - KeyedMessage msg = SecurityException.UNEXPECTED.create("SecurityAccess.removeInternalUserPrincipal", - "store", - e.getMessage()); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "SecurityAccess.removeInternalUserPrincipal", "store", e + .getMessage()); logger.error(msg, e); throw new SecurityException(msg, e); } @@ -276,28 +298,36 @@ * Returns the {@link InternalRolePrincipal}from the role full path name. * </p> * - * @param roleFullPathName The role full path name. + * @param roleFullPathName + * The role full path name. * @return The {@link InternalRolePrincipal}. */ - public InternalRolePrincipal getInternalRolePrincipal(String roleFullPathName) + public InternalRolePrincipal getInternalRolePrincipal( + String roleFullPathName) { Criteria filter = new Criteria(); filter.addEqualTo("fullPath", roleFullPathName); - Query query = QueryFactory.newQuery(InternalRolePrincipalImpl.class, filter); - InternalRolePrincipal internalRole = (InternalRolePrincipal) getPersistenceBrokerTemplate().getObjectByQuery(query); + Query query = QueryFactory.newQuery(InternalRolePrincipalImpl.class, + filter); + InternalRolePrincipal internalRole = (InternalRolePrincipal) getPersistenceBrokerTemplate() + .getObjectByQuery(query); return internalRole; } - + /** * <p> * Sets the given {@link InternalRolePrincipal}. * </p> * - * @param internalRole The {@link InternalRolePrincipal}. - * @param isMappingOnly Whether a principal's purpose is for security mappping only. - * @throws SecurityException Throws a {@link SecurityException}. + * @param internalRole + * The {@link InternalRolePrincipal}. + * @param isMappingOnly + * Whether a principal's purpose is for security mappping only. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - public void setInternalRolePrincipal(InternalRolePrincipal internalRole, boolean isMappingOnly) throws SecurityException + public void setInternalRolePrincipal(InternalRolePrincipal internalRole, + boolean isMappingOnly) throws SecurityException { try { @@ -309,23 +339,26 @@ } catch (Exception e) { - KeyedMessage msg = SecurityException.UNEXPECTED.create("SecurityAccess.setInternalRolePrincipal", - "store", - e.getMessage()); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "SecurityAccess.setInternalRolePrincipal", "store", e + .getMessage()); logger.error(msg, e); throw new SecurityException(msg, e); } } - + /** * <p> * Remove the given {@link InternalRolePrincipal}. * </p> * - * @param internalRole The {@link InternalRolePrincipal}. - * @throws SecurityException Throws a {@link SecurityException}. + * @param internalRole + * The {@link InternalRolePrincipal}. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - public void removeInternalRolePrincipal(InternalRolePrincipal internalRole) throws SecurityException + public void removeInternalRolePrincipal(InternalRolePrincipal internalRole) + throws SecurityException { try { @@ -340,13 +373,13 @@ } catch (Exception e) { - KeyedMessage msg = SecurityException.UNEXPECTED.create("SecurityAccess.removeInternalRolePrincipal", - "store", - e.getMessage()); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "SecurityAccess.removeInternalRolePrincipal", "store", e + .getMessage()); logger.error(msg, e); throw new SecurityException(msg, e); } - + } /** @@ -354,32 +387,40 @@ * Returns the {@link InternalGroupPrincipal}from the group full path name. * </p> * - * @param groupFullPathName The group full path name. + * @param groupFullPathName + * The group full path name. * @return The {@link InternalGroupPrincipal}. */ - public InternalGroupPrincipal getInternalGroupPrincipal(String groupFullPathName) + public InternalGroupPrincipal getInternalGroupPrincipal( + String groupFullPathName) { Criteria filter = new Criteria(); filter.addEqualTo("fullPath", groupFullPathName); - Query query = QueryFactory.newQuery(InternalGroupPrincipalImpl.class, filter); - InternalGroupPrincipal internalGroup = (InternalGroupPrincipal) getPersistenceBrokerTemplate().getObjectByQuery(query); + Query query = QueryFactory.newQuery(InternalGroupPrincipalImpl.class, + filter); + InternalGroupPrincipal internalGroup = (InternalGroupPrincipal) getPersistenceBrokerTemplate() + .getObjectByQuery(query); return internalGroup; } - + /** * <p> * Sets the given {@link InternalGroupPrincipal}. * </p> * - * @param internalGroup The {@link InternalGroupPrincipal}. - * @param isMappingOnly Whether a principal's purpose is for security mappping only. - * @throws SecurityException Throws a {@link SecurityException}. + * @param internalGroup + * The {@link InternalGroupPrincipal}. + * @param isMappingOnly + * Whether a principal's purpose is for security mappping only. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - public void setInternalGroupPrincipal(InternalGroupPrincipal internalGroup, boolean isMappingOnly) throws SecurityException + public void setInternalGroupPrincipal(InternalGroupPrincipal internalGroup, + boolean isMappingOnly) throws SecurityException { try { - + if (isMappingOnly) { internalGroup.setMappingOnly(isMappingOnly); @@ -388,29 +429,32 @@ } catch (Exception e) { - KeyedMessage msg = SecurityException.UNEXPECTED.create("SecurityAccess.setInternalGroupPrincipal", - "store", - e.getMessage()); - logger.error(msg, e); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "SecurityAccess.setInternalGroupPrincipal", "store", e + .getMessage()); + logger.error(msg, e); throw new SecurityException(msg, e); } } - + /** * <p> * Remove the given {@link InternalGroupPrincipal}. * </p> * - * @param internalGroup The {@link InternalGroupPrincipal}. - * @throws SecurityException Throws a {@link SecurityException}. + * @param internalGroup + * The {@link InternalGroupPrincipal}. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - public void removeInternalGroupPrincipal(InternalGroupPrincipal internalGroup) throws SecurityException + public void removeInternalGroupPrincipal( + InternalGroupPrincipal internalGroup) throws SecurityException { try { - // Remove role. + // Remove role. getPersistenceBrokerTemplate().delete(internalGroup); - + if (logger.isDebugEnabled()) { logger.debug("Deleted group: " + internalGroup.getFullPath()); @@ -419,34 +463,40 @@ } catch (Exception e) { - KeyedMessage msg = SecurityException.UNEXPECTED.create("SecurityAccess.removeInternalGroupPrincipal", - "store", - e.getMessage()); + KeyedMessage msg = SecurityException.UNEXPECTED.create( + "SecurityAccess.removeInternalGroupPrincipal", "store", e + .getMessage()); logger.error(msg, e); throw new SecurityException(msg, e); } - + } public Iterator getInternalRolePrincipals(String filter) { Criteria queryCriteria = new Criteria(); queryCriteria.addEqualTo("isMappingOnly", new Boolean(false)); - queryCriteria.addLike("fullPath", UserPrincipal.PREFS_ROLE_ROOT + filter + "%"); - Query query = QueryFactory.newQuery(InternalRolePrincipalImpl.class, queryCriteria); - Collection c = getPersistenceBrokerTemplate().getCollectionByQuery(query); + queryCriteria.addLike("fullPath", UserPrincipal.PREFS_ROLE_ROOT + + filter + "%"); + Query query = QueryFactory.newQuery(InternalRolePrincipalImpl.class, + queryCriteria); + Collection c = getPersistenceBrokerTemplate().getCollectionByQuery( + query); return c.iterator(); } public Iterator getInternalGroupPrincipals(String filter) { - + Criteria queryCriteria = new Criteria(); queryCriteria.addEqualTo("isMappingOnly", new Boolean(false)); - queryCriteria.addLike("fullPath", UserPrincipal.PREFS_GROUP_ROOT + filter + "%"); - Query query = QueryFactory.newQuery(InternalGroupPrincipalImpl.class, queryCriteria); - Collection c = getPersistenceBrokerTemplate().getCollectionByQuery(query); + queryCriteria.addLike("fullPath", UserPrincipal.PREFS_GROUP_ROOT + + filter + "%"); + Query query = QueryFactory.newQuery(InternalGroupPrincipalImpl.class, + queryCriteria); + Collection c = getPersistenceBrokerTemplate().getCollectionByQuery( + query); return c.iterator(); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/SimpleCredentialPasswordValidator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/SimpleCredentialPasswordValidator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/SimpleCredentialPasswordValidator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi.impl; import org.apache.jetspeed.security.InvalidPasswordException; @@ -26,18 +26,23 @@ * </p> * * @author <a href="mailto:ate ¡÷ apache.org">Ate Douma</a> - * @version $Id: SimpleCredentialPasswordValidator.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: SimpleCredentialPasswordValidator.java 516448 2007-03-09 + * 16:25:47Z ate $ */ -public class SimpleCredentialPasswordValidator implements CredentialPasswordValidator +public class SimpleCredentialPasswordValidator implements + CredentialPasswordValidator { + private int minPasswordLength; + private int minNumberOfDigits; - + /** * @param minPasswordLength * @param minNumberOfDigits */ - public SimpleCredentialPasswordValidator(int minPasswordLength, int minNumberOfDigits) + public SimpleCredentialPasswordValidator(int minPasswordLength, + int minNumberOfDigits) { this.minPasswordLength = minPasswordLength; this.minNumberOfDigits = minNumberOfDigits; @@ -49,30 +54,24 @@ public void validate(String clearTextPassword) throws SecurityException { int digits = 0; - if ( clearTextPassword == null ) + if (clearTextPassword == null) { clearTextPassword = ""; } char[] pwd = clearTextPassword.toCharArray(); - if ( minPasswordLength > 0 && pwd.length < minPasswordLength ) - { - throw new InvalidPasswordException(); - } + if (minPasswordLength > 0 && pwd.length < minPasswordLength) { throw new InvalidPasswordException(); } - if ( minNumberOfDigits > 0) + if (minNumberOfDigits > 0) { - for ( int i = 0; i < pwd.length; i++ ) + for (int i = 0; i < pwd.length; i++) { if (Character.isDigit(pwd[i])) { digits++; } } - if (digits < minNumberOfDigits) - { - throw new InvalidPasswordException(); - } + if (digits < minNumberOfDigits) { throw new InvalidPasswordException(); } } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ValidatePasswordOnLoadInterceptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ValidatePasswordOnLoadInterceptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ValidatePasswordOnLoadInterceptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi.impl; import org.apache.commons.logging.Log; @@ -25,28 +25,38 @@ /** * <p> - * Checks if a (pre)set password in the persitent store is valid according to the configured - * {@link PasswordCredentialProvider#getValidator() validator} when loaded from the persistent store.</p> + * Checks if a (pre)set password in the persitent store is valid according to + * the configured {@link PasswordCredentialProvider#getValidator() validator} + * when loaded from the persistent store. + * </p> * <p> - * If the password checks out to be invalid, an error is logged and the credential is flagged to be - * {@link InternalCredential#isUpdateRequired() updateRequired}.</p> + * If the password checks out to be invalid, an error is logged and the + * credential is flagged to be + * {@link InternalCredential#isUpdateRequired() updateRequired}. + * </p> * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id$ */ -public class ValidatePasswordOnLoadInterceptor extends AbstractInternalPasswordCredentialInterceptorImpl +public class ValidatePasswordOnLoadInterceptor extends + AbstractInternalPasswordCredentialInterceptorImpl { - private static final Log log = LogFactory.getLog(InternalPasswordCredentialInterceptor.class); - + + private static final Log log = LogFactory + .getLog(InternalPasswordCredentialInterceptor.class); + /** * @return true is the password was invalid and update is required - * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterLoad(org.apache.jetspeed.security.spi.PasswordCredentialProvider, java.lang.String, org.apache.jetspeed.security.om.InternalCredential) + * @see org.apache.jetspeed.security.spi.InternalPasswordCredentialInterceptor#afterLoad(org.apache.jetspeed.security.spi.PasswordCredentialProvider, + * java.lang.String, + * org.apache.jetspeed.security.om.InternalCredential) */ - public boolean afterLoad(PasswordCredentialProvider pcProvider, String userName, InternalCredential credential) + public boolean afterLoad(PasswordCredentialProvider pcProvider, + String userName, InternalCredential credential) throws SecurityException { boolean updated = false; - if (!credential.isEncoded() && pcProvider.getValidator() != null ) + if (!credential.isEncoded() && pcProvider.getValidator() != null) { try { @@ -54,9 +64,13 @@ } catch (SecurityException e) { - log.error("Loaded password for user "+userName+" is invalid. The user will be required to change it."); + log + .error("Loaded password for user " + + userName + + " is invalid. The user will be required to change it."); // persitent store contains an invalid password - // allow login (assuming the user knows the invalid value) but enforce an update + // allow login (assuming the user knows the invalid value) but + // enforce an update credential.setUpdateRequired(true); updated = true; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/AbstractLdapDao.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/AbstractLdapDao.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/AbstractLdapDao.java 2008-05-16 01:54:54 UTC (rev 940) @@ -43,9 +43,9 @@ */ public abstract class AbstractLdapDao { - - private static final Log logger = LogFactory.getLog(AbstractLdapDao.class); - + + private static final Log logger = LogFactory.getLog(AbstractLdapDao.class); + /** The ldap binding configuration. */ private LdapBindingConfig ldapBindingConfig = null; @@ -59,7 +59,8 @@ */ public AbstractLdapDao() { - throw new UnsupportedOperationException("Must be instantiated with LDAP binding configuration."); + throw new UnsupportedOperationException( + "Must be instantiated with LDAP binding configuration."); } /** @@ -67,10 +68,12 @@ * Initializes the dao. * </p> * - * @param ldapConfig Holds the ldap configuration. + * @param ldapConfig + * Holds the ldap configuration. * @throws SecurityException */ - public AbstractLdapDao(LdapBindingConfig ldapConfig) throws SecurityException + public AbstractLdapDao(LdapBindingConfig ldapConfig) + throws SecurityException { this.ldapBindingConfig = ldapConfig; bindToServer(ldapConfig.getRootDn(), ldapConfig.getRootPassword()); @@ -85,9 +88,10 @@ * @param rootPassword * @throws SecurityException */ - protected void bindToServer(String rootDn, String rootPassword) throws SecurityException + protected void bindToServer(String rootDn, String rootPassword) + throws SecurityException { - if ( ctx == null ) + if (ctx == null) { validateDn(rootDn); validatePassword(rootPassword); @@ -101,7 +105,8 @@ * Gets the sub context name. * </p> * - * @param dn The domain name. + * @param dn + * The domain name. * @return The sub context name. * @throws NamingException */ @@ -127,14 +132,12 @@ * Validate the domain name. * </p> * - * @param dn The domain name. + * @param dn + * The domain name. */ protected void validateDn(final String dn) throws SecurityException { - if (StringUtils.isEmpty(dn)) - { - throw new InvalidDnException(); - } + if (StringUtils.isEmpty(dn)) { throw new InvalidDnException(); } } /** @@ -142,19 +145,18 @@ * Valiate the users password. * </p> * - * @param password The user. + * @param password + * The user. */ - protected void validatePassword(final String password) throws SecurityException + protected void validatePassword(final String password) + throws SecurityException { - if (StringUtils.isEmpty(password)) - { - throw new InvalidPasswordException(); - } + if (StringUtils.isEmpty(password)) { throw new InvalidPasswordException(); } } /** - * @return The factors that determine the scope of the search and what gets returned as a result - * of the search. + * @return The factors that determine the scope of the search and what gets + * returned as a result of the search. */ protected SearchControls setSearchControls() { @@ -168,7 +170,8 @@ /** * <p> - * Searches the LDAP server for the user with the specified userid (uid attribute). + * Searches the LDAP server for the user with the specified userid (uid + * attribute). * </p> * * @return the user's DN @@ -189,18 +192,21 @@ throw new SecurityException(e); } } - /** * <p> * Gets the first matching user for the given uid. * </p> * - * @param searchResults The {@link NamingEnumeration}. - * @return the user's DN of the first use in the list. Null if no users were found. - * @throws NamingException Throws a {@link NamingException}. + * @param searchResults + * The {@link NamingEnumeration}. + * @return the user's DN of the first use in the list. Null if no users were + * found. + * @throws NamingException + * Throws a {@link NamingException}. */ - private String getFirstDnForUid(NamingEnumeration searchResults) throws NamingException + private String getFirstDnForUid(NamingEnumeration searchResults) + throws NamingException { String userDn = null; while ((null != searchResults) && searchResults.hasMore()) @@ -210,7 +216,9 @@ String searchDomain = getSearchDomain(); if (searchDomain.length() > 0) { - userDn += "," + StringUtils.replace(searchDomain, "," + getRootContext(), ""); + userDn += "," + + StringUtils.replace(searchDomain, "," + + getRootContext(), ""); } } return userDn; @@ -221,15 +229,13 @@ * Validate the uid. * </p> * - * @param uid The uid. + * @param uid + * The uid. */ protected void validateUid(String uid) throws SecurityException { String pattern = ".*\\(.*|.*\\[.*|.*\\{.*|.*\\\\.*|.*\\^.*|.*\\$.*|.*\\|.*|.*\\).*|.*\\?.*|.*\\*.*|.*\\+.*|.*\\..*"; - if (StringUtils.isEmpty(uid) || uid.matches(pattern)) - { - throw new InvalidUidException(); - } + if (StringUtils.isEmpty(uid) || uid.matches(pattern)) { throw new InvalidUidException(); } } /** @@ -237,86 +243,121 @@ * Search uid by wild card. * </p> * - * @param filter The filter. - * @param cons The {@link SearchControls} + * @param filter + * The filter. + * @param cons + * The {@link SearchControls} * @return The {@link NamingEnumeration} - * @throws NamingException Throws a {@link NamingEnumeration}. + * @throws NamingException + * Throws a {@link NamingEnumeration}. */ - protected NamingEnumeration searchByWildcardedUid(final String filter, SearchControls cons) throws NamingException + protected NamingEnumeration searchByWildcardedUid(final String filter, + SearchControls cons) throws NamingException { - // usa a template method to use users/groups/roles - String query = ""; - if (StringUtils.isEmpty(getSearchSuffix())) { - query = "(" + getEntryPrefix() + "=" + (StringUtils.isEmpty(filter) ? "*" : filter) + ")"; - } else { - query = "(&(" + getEntryPrefix() + "=" + (StringUtils.isEmpty(filter) ? "*" : filter) + ")" + getSearchSuffix() + ")"; + // usa a template method to use users/groups/roles + String query = ""; + if (StringUtils.isEmpty(getSearchSuffix())) + { + query = "(" + getEntryPrefix() + "=" + + (StringUtils.isEmpty(filter) ? "*" : filter) + ")"; } - logger.debug("searchByWildCardedUid = " + query); + else + { + query = "(&(" + getEntryPrefix() + "=" + + (StringUtils.isEmpty(filter) ? "*" : filter) + ")" + + getSearchSuffix() + ")"; + } + logger.debug("searchByWildCardedUid = " + query); - cons.setSearchScope(getSearchScope()); - //TODO: added this here for OpenLDAP (when users are stored in ou=People,o=evenSeas) - String searchBase = StringUtils.replace(getSearchDomain(), "," + getRootContext(), ""); - NamingEnumeration results = ((DirContext) ctx).search(searchBase,query , cons); + cons.setSearchScope(getSearchScope()); + // TODO: added this here for OpenLDAP (when users are stored in + // ou=People,o=evenSeas) + String searchBase = StringUtils.replace(getSearchDomain(), "," + + getRootContext(), ""); + NamingEnumeration results = ((DirContext) ctx).search(searchBase, + query, cons); return results; } - + /** * <p> * Search uid by wild card. * </p> * - * @param filter The filter. - * @param cons The {@link SearchControls} + * @param filter + * The filter. + * @param cons + * The {@link SearchControls} * @return The {@link NamingEnumeration} - * @throws NamingException Throws a {@link NamingEnumeration}. + * @throws NamingException + * Throws a {@link NamingEnumeration}. */ - protected NamingEnumeration searchGroupByWildcardedUid(final String filter, SearchControls cons) throws NamingException + protected NamingEnumeration searchGroupByWildcardedUid(final String filter, + SearchControls cons) throws NamingException { - // usa a template method to use users/groups/roles + // usa a template method to use users/groups/roles String query = ""; - if (StringUtils.isEmpty(getGroupFilter())) { - query = "(" + getGroupIdAttribute() + "=" + (StringUtils.isEmpty(filter) ? "*" : filter) + ")"; - } else { - query = "(&(" + getGroupIdAttribute() + "=" + (StringUtils.isEmpty(filter) ? "*" : filter) + ")" + getGroupFilter() + ")"; - } - - String searchBase = ""; - if (!StringUtils.isEmpty(getGroupFilterBase())) - searchBase+=getGroupFilterBase(); - cons.setSearchScope(getSearchScope()); - NamingEnumeration results = ((DirContext) ctx).search(searchBase,query , cons); + if (StringUtils.isEmpty(getGroupFilter())) + { + query = "(" + getGroupIdAttribute() + "=" + + (StringUtils.isEmpty(filter) ? "*" : filter) + ")"; + } + else + { + query = "(&(" + getGroupIdAttribute() + "=" + + (StringUtils.isEmpty(filter) ? "*" : filter) + ")" + + getGroupFilter() + ")"; + } + String searchBase = ""; + if (!StringUtils.isEmpty(getGroupFilterBase())) + searchBase += getGroupFilterBase(); + cons.setSearchScope(getSearchScope()); + NamingEnumeration results = ((DirContext) ctx).search(searchBase, + query, cons); + return results; - } - + } + /** * <p> * Search uid by wild card. * </p> * - * @param filter The filter. - * @param cons The {@link SearchControls} + * @param filter + * The filter. + * @param cons + * The {@link SearchControls} * @return The {@link NamingEnumeration} - * @throws NamingException Throws a {@link NamingEnumeration}. + * @throws NamingException + * Throws a {@link NamingEnumeration}. */ - protected NamingEnumeration searchRoleByWildcardedUid(final String filter, SearchControls cons) throws NamingException + protected NamingEnumeration searchRoleByWildcardedUid(final String filter, + SearchControls cons) throws NamingException { String query = ""; - if (StringUtils.isEmpty(getRoleFilter())) { - query = "(" + getRoleIdAttribute() + "=" + (StringUtils.isEmpty(filter) ? "*" : filter) + ")"; - } else { - query = "(&(" + getRoleIdAttribute() + "=" + (StringUtils.isEmpty(filter) ? "*" : filter) + ")" + getRoleFilter() + ")"; - } - - String searchBase = ""; - if (!StringUtils.isEmpty(getRoleFilterBase())) - searchBase+=getRoleFilterBase(); - cons.setSearchScope(getSearchScope()); - NamingEnumeration results = ((DirContext) ctx).search(searchBase,query , cons); + if (StringUtils.isEmpty(getRoleFilter())) + { + query = "(" + getRoleIdAttribute() + "=" + + (StringUtils.isEmpty(filter) ? "*" : filter) + ")"; + } + else + { + query = "(&(" + getRoleIdAttribute() + "=" + + (StringUtils.isEmpty(filter) ? "*" : filter) + ")" + + getRoleFilter() + ")"; + } + String searchBase = ""; + if (!StringUtils.isEmpty(getRoleFilterBase())) + searchBase += getRoleFilterBase(); + cons.setSearchScope(getSearchScope()); + NamingEnumeration results = ((DirContext) ctx).search(searchBase, + query, cons); + return results; - } + } /** * <p> @@ -329,7 +370,7 @@ { return this.ldapBindingConfig.getGroupFilterBase(); } - + /** * <p> * Returns the default Group suffix dn. @@ -340,8 +381,7 @@ protected String[] getGroupObjectClasses() { return this.ldapBindingConfig.getGroupObjectClasses(); - } - + } /** * <p> @@ -354,7 +394,7 @@ { return this.ldapBindingConfig.getRoleFilterBase(); } - + /** * <p> * Returns the default Group suffix dn. @@ -365,8 +405,8 @@ protected String[] getRoleObjectClasses() { return this.ldapBindingConfig.getRoleObjectClasses(); - } - + } + /** * <p> * Returns the default Group suffix dn. @@ -377,8 +417,8 @@ protected String getUserFilterBase() { return this.ldapBindingConfig.getUserFilterBase(); - } - + } + /** * <p> * Returns the default Group suffix dn. @@ -389,9 +429,8 @@ protected String getGroupFilter() { return this.ldapBindingConfig.getGroupFilter(); - } - - + } + /** * <p> * Returns the default Group suffix dn. @@ -402,9 +441,7 @@ protected String getRoleFilter() { return this.ldapBindingConfig.getRoleFilter(); - } - - + } /** * <p> @@ -417,7 +454,7 @@ { return this.ldapBindingConfig.getRootContext(); } - + /** * <p> * A template method that returns the LDAP entry prefix of the concrete DAO. @@ -426,9 +463,9 @@ * TODO : this should be in spring config * * @return a String containing the LDAP entry prefix name. - */ + */ protected abstract String getEntryPrefix(); - + /** * <p> * A template method that returns the LDAP entry prefix of the concrete DAO. @@ -437,9 +474,9 @@ * TODO : this should be in spring config * * @return a String containing the LDAP entry prefix name. - */ + */ protected abstract String getSearchSuffix(); - + /** * <p> * The domain in wich to perform a search @@ -448,10 +485,10 @@ * TODO : this should be in spring config * * @return a String containing the LDAP entry prefix name. - */ - protected abstract String getSearchDomain(); - - protected String getUserFilter() + */ + protected abstract String getSearchDomain(); + + protected String getUserFilter() { return this.ldapBindingConfig.getUserFilter(); } @@ -459,112 +496,115 @@ protected String[] getUserObjectClasses() { return this.ldapBindingConfig.getUserObjectClasses(); - } + } - protected String getGroupMembershipAttribute() + protected String getGroupMembershipAttribute() { return this.ldapBindingConfig.getGroupMembershipAttributes(); - } - - protected String getUserGroupMembershipAttribute() + } + + protected String getUserGroupMembershipAttribute() { return this.ldapBindingConfig.getUserGroupMembershipAttributes(); - } - - - protected String getGroupMembershipForRoleAttribute() + } + + protected String getGroupMembershipForRoleAttribute() { return this.ldapBindingConfig.getGroupMembershipForRoleAttributes(); - } - - protected String getRoleGroupMembershipForRoleAttribute() + } + + protected String getRoleGroupMembershipForRoleAttribute() { return this.ldapBindingConfig.getRoleGroupMembershipForRoleAttributes(); - } - - protected String getRoleMembershipAttribute() + } + + protected String getRoleMembershipAttribute() { return this.ldapBindingConfig.getRoleMembershipAttributes(); } - - protected String getUserRoleMembershipAttribute() + + protected String getUserRoleMembershipAttribute() { return this.ldapBindingConfig.getUserRoleMembershipAttributes(); } - protected String getRoleIdAttribute() + protected String getRoleIdAttribute() { return this.ldapBindingConfig.getRoleIdAttribute(); - } + } - protected String getGroupIdAttribute() + protected String getGroupIdAttribute() { return this.ldapBindingConfig.getGroupIdAttribute(); - } + } - protected String getUserIdAttribute() + protected String getUserIdAttribute() { return this.ldapBindingConfig.getUserIdAttribute(); - } + } - protected String getUidAttribute() + protected String getUidAttribute() { return this.ldapBindingConfig.getUidAttribute(); - } - - protected int getSearchScope() + } + + protected int getSearchScope() { - return Integer.parseInt(this.ldapBindingConfig.getMemberShipSearchScope()); - } - + return Integer.parseInt(this.ldapBindingConfig + .getMemberShipSearchScope()); + } + protected String getRoleUidAttribute() { return this.ldapBindingConfig.getRoleUidAttribute(); - } - + } + protected String getGroupUidAttribute() { return this.ldapBindingConfig.getGroupUidAttribute(); - } - + } + protected String getUserUidAttribute() { return this.ldapBindingConfig.getUserUidAttribute(); - } - + } + protected String getGroupObjectRequiredAttributeClasses() { return this.ldapBindingConfig.getGroupObjectRequiredAttributeClasses(); - } - + } + protected String getRoleObjectRequiredAttributeClasses() { return this.ldapBindingConfig.getRoleObjectRequiredAttributeClasses(); - } - + } + protected String[] getUserAttributes() { return this.ldapBindingConfig.getUserAttributes(); - } - + } + protected String[] getGroupAttributes() { return this.ldapBindingConfig.getGroupAttributes(); - } - + } + protected String[] getRoleAttributes() { return this.ldapBindingConfig.getRoleAttributes(); - } - - protected String getUserPasswordAttribute() { - return this.ldapBindingConfig.getUserPasswordAttribute(); } - - protected String[] getKnownAttributes() { - return this.ldapBindingConfig.getKnownAttributes(); - } + protected String getUserPasswordAttribute() + { + return this.ldapBindingConfig.getUserPasswordAttribute(); + } + + protected String[] getKnownAttributes() + { + return this.ldapBindingConfig.getKnownAttributes(); + } + protected abstract String[] getObjectClasses(); + protected abstract String[] getAttributes(); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/InitLdapSchema.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/InitLdapSchema.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/InitLdapSchema.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,7 +32,8 @@ * Default constructor. * </p> * - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ public InitLdapSchema() throws SecurityException { @@ -44,10 +45,13 @@ * Initializes the LDAP schema. * </p> * - * @param ldapConfig Holds the ldap binding configuration. - * @throws SecurityException A {@link SecurityException}. + * @param ldapConfig + * Holds the ldap binding configuration. + * @throws SecurityException + * A {@link SecurityException}. */ - public InitLdapSchema(LdapBindingConfig ldapConfig) throws SecurityException + public InitLdapSchema(LdapBindingConfig ldapConfig) + throws SecurityException { super(ldapConfig); } @@ -66,7 +70,8 @@ * Inits a given ou. * </p> * - * @param ou The org unit. + * @param ou + * The org unit. * @throws SecurityException */ public void initOu(String ou) throws NamingException @@ -78,22 +83,24 @@ ctx.createSubcontext(dn, attrs); } } - - public void initOu(String ou,String folder) throws NamingException + + public void initOu(String ou, String folder) throws NamingException { if (!StringUtils.isEmpty(ou)) { Attributes attrs = defineLdapAttributes(ou); ctx.createSubcontext("ou=" + ou + "," + folder, attrs); } - } + } /** * <p> - * A template method for defining the attributes for a particular LDAP class. + * A template method for defining the attributes for a particular LDAP + * class. * </p> * - * @param principalUid The principal uid. + * @param principalUid + * The principal uid. * @return the LDAP attributes object for the particular class. */ protected Attributes defineLdapAttributes(String ou) @@ -109,25 +116,29 @@ return attrs; } - protected String getEntryPrefix() - { - return null; - } - - protected String getSearchSuffix() { - return null; - } + protected String getEntryPrefix() + { + return null; + } - protected String getSearchDomain() { - return null; - } + protected String getSearchSuffix() + { + return null; + } - protected String[] getObjectClasses() { - return null; - } + protected String getSearchDomain() + { + return null; + } - protected String[] getAttributes() { + protected String[] getObjectClasses() + { return null; } + protected String[] getAttributes() + { + return null; + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapBindingConfig.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapBindingConfig.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapBindingConfig.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,113 +33,123 @@ */ public class LdapBindingConfig { + /** The logger. */ - private static final Log logger = LogFactory.getLog(LdapBindingConfig.class); - + private static final Log logger = LogFactory + .getLog(LdapBindingConfig.class); + private LdapContext context; private String initialContextFactory; + private String ldapSocketFactory; + private String ldapScheme = "ldap"; + private String ldapServerName; + private String ldapServerPort; + private String ldapSecurityLevel = "simple"; + private String ldapSecurityProtocol; + private String rootDn; + private String rootPassword; + private String rootContext; - + private PropertiesConfiguration props = null; - private String groupFilter; - private String userFilter; + private String groupFilter; - private String userRoleMembershipAttributes; + private String userFilter; - private String groupMembershipAttributes; - private String userGroupMembershipAttributes; + private String userRoleMembershipAttributes; - private String defaultSearchBase; + private String groupMembershipAttributes; - private String groupFilterBase; - private String userFilterBase; - - private String groupIdAttribute; - private String userIdAttribute; - - private String uidAttribute; - private String memberShipSearchScope; + private String userGroupMembershipAttributes; - private String[] groupObjectClasses; + private String defaultSearchBase; - private String[] userObjectClasses; + private String groupFilterBase; - private String groupMembershipForRoleAttributes; + private String userFilterBase; - private String groupUidAttribute; - private String userUidAttribute; - - private String[] groupAttributes; - private String[] userAttributes; - - private String groupObjectRequiredAttributeClasses; - - private String[] roleObjectClasses; - private String roleGroupMembershipForRoleAttributes; - private String[] roleAttributes; - private String roleObjectRequiredAttributeClasses; - private String roleFilter; - private String roleFilterBase; - private String roleIdAttribute; - private String roleUidAttribute; - private String roleMembershipAttributes; - - private String userPasswordAttribute; + private String groupIdAttribute; - private String[] knownAttributes; + private String userIdAttribute; + private String uidAttribute; + + private String memberShipSearchScope; + + private String[] groupObjectClasses; + + private String[] userObjectClasses; + + private String groupMembershipForRoleAttributes; + + private String groupUidAttribute; + + private String userUidAttribute; + + private String[] groupAttributes; + + private String[] userAttributes; + + private String groupObjectRequiredAttributeClasses; + + private String[] roleObjectClasses; + + private String roleGroupMembershipForRoleAttributes; + + private String[] roleAttributes; + + private String roleObjectRequiredAttributeClasses; + + private String roleFilter; + + private String roleFilterBase; + + private String roleIdAttribute; + + private String roleUidAttribute; + + private String roleMembershipAttributes; + + private String userPasswordAttribute; + + private String[] knownAttributes; + public LdapBindingConfig() { - // allow for properties setting configuration instead of through one big ugly constructor call or external properties file + // allow for properties setting configuration instead of through one big + // ugly constructor call or external properties file } - - public LdapBindingConfig(String factory, - String name, - String port, - String context, - String dn, - String password, - String roleFilter, - String groupFilter, - String userFilter, - String roleMembershipAttributes, - String userRoleMembershipAttributes, - String groupMembershipAttributes, - String userGroupMembershipAttributes, - String groupMembershipForRoleAttributes, - String roleGroupMembershipForRoleAttributes, - String defaultSearchBase, - String roleFilterBase, - String groupFilterBase, - String userFilterBase, - String roleObjectClasses, - String groupObjectClasses, - String userObjectClasses, - String roleIdAttribute, - String groupIdAttribute, - String userIdAttribute, - String uidAttribute, - String memberShipSearchScope, - String roleUidAttribute, - String groupUidAttribute, - String userUidAttribute, - String roleObjectRequiredAttributeClasses, - String groupObjectRequiredAttributeClasses, - String userAttributes, - String roleAttributes, - String groupAttributes, - String userPasswordAttribute, - String knownAttributes) + + public LdapBindingConfig(String factory, String name, String port, + String context, String dn, String password, String roleFilter, + String groupFilter, String userFilter, + String roleMembershipAttributes, + String userRoleMembershipAttributes, + String groupMembershipAttributes, + String userGroupMembershipAttributes, + String groupMembershipForRoleAttributes, + String roleGroupMembershipForRoleAttributes, + String defaultSearchBase, String roleFilterBase, + String groupFilterBase, String userFilterBase, + String roleObjectClasses, String groupObjectClasses, + String userObjectClasses, String roleIdAttribute, + String groupIdAttribute, String userIdAttribute, + String uidAttribute, String memberShipSearchScope, + String roleUidAttribute, String groupUidAttribute, + String userUidAttribute, String roleObjectRequiredAttributeClasses, + String groupObjectRequiredAttributeClasses, String userAttributes, + String roleAttributes, String groupAttributes, + String userPasswordAttribute, String knownAttributes) { initialContextFactory = factory; ldapServerName = name; @@ -148,51 +158,49 @@ rootDn = dn; rootPassword = password; - this.roleFilter=roleFilter; - this.groupFilter=groupFilter; - this.userFilter=userFilter; - - this.roleMembershipAttributes=roleMembershipAttributes; - this.userRoleMembershipAttributes=userRoleMembershipAttributes; - - this.groupMembershipAttributes=groupMembershipAttributes; - this.userGroupMembershipAttributes=userGroupMembershipAttributes; - - this.groupMembershipForRoleAttributes=groupMembershipForRoleAttributes; - this.roleGroupMembershipForRoleAttributes=roleGroupMembershipForRoleAttributes; - this.defaultSearchBase=defaultSearchBase; - - this.roleFilterBase=roleFilterBase; - this.groupFilterBase=groupFilterBase; - this.userFilterBase=userFilterBase; - - - this.roleObjectClasses=StringUtils.split(roleObjectClasses,","); - this.groupObjectClasses=StringUtils.split(groupObjectClasses,","); - this.userObjectClasses=StringUtils.split(userObjectClasses,","); - - this.roleIdAttribute=roleIdAttribute; - this.groupIdAttribute=groupIdAttribute; - this.userIdAttribute=userIdAttribute; - + this.roleFilter = roleFilter; + this.groupFilter = groupFilter; + this.userFilter = userFilter; + + this.roleMembershipAttributes = roleMembershipAttributes; + this.userRoleMembershipAttributes = userRoleMembershipAttributes; + + this.groupMembershipAttributes = groupMembershipAttributes; + this.userGroupMembershipAttributes = userGroupMembershipAttributes; + + this.groupMembershipForRoleAttributes = groupMembershipForRoleAttributes; + this.roleGroupMembershipForRoleAttributes = roleGroupMembershipForRoleAttributes; + this.defaultSearchBase = defaultSearchBase; + + this.roleFilterBase = roleFilterBase; + this.groupFilterBase = groupFilterBase; + this.userFilterBase = userFilterBase; + + this.roleObjectClasses = StringUtils.split(roleObjectClasses, ","); + this.groupObjectClasses = StringUtils.split(groupObjectClasses, ","); + this.userObjectClasses = StringUtils.split(userObjectClasses, ","); + + this.roleIdAttribute = roleIdAttribute; + this.groupIdAttribute = groupIdAttribute; + this.userIdAttribute = userIdAttribute; + this.uidAttribute = uidAttribute; - this.memberShipSearchScope=memberShipSearchScope; - + this.memberShipSearchScope = memberShipSearchScope; - this.roleUidAttribute=roleUidAttribute; - this.groupUidAttribute=groupUidAttribute; - this.userUidAttribute=userUidAttribute; - - this.roleObjectRequiredAttributeClasses=roleObjectRequiredAttributeClasses; - this.groupObjectRequiredAttributeClasses=groupObjectRequiredAttributeClasses; - - this.roleAttributes=StringUtils.split(roleAttributes,","); - this.groupAttributes = StringUtils.split(groupAttributes,","); - this.userAttributes = StringUtils.split(userAttributes,","); - + this.roleUidAttribute = roleUidAttribute; + this.groupUidAttribute = groupUidAttribute; + this.userUidAttribute = userUidAttribute; + + this.roleObjectRequiredAttributeClasses = roleObjectRequiredAttributeClasses; + this.groupObjectRequiredAttributeClasses = groupObjectRequiredAttributeClasses; + + this.roleAttributes = StringUtils.split(roleAttributes, ","); + this.groupAttributes = StringUtils.split(groupAttributes, ","); + this.userAttributes = StringUtils.split(userAttributes, ","); + this.userPasswordAttribute = userPasswordAttribute; - - this.knownAttributes = StringUtils.split(knownAttributes,","); + + this.knownAttributes = StringUtils.split(knownAttributes, ","); } /** @@ -205,70 +213,114 @@ { try { - props = new PropertiesConfiguration("JETSPEED-INF/directory/config/" + ldapType + "/ldap.properties"); - initialContextFactory = props.getString("org.apache.jetspeed.ldap.initialContextFactory"); - ldapServerName = props.getString("org.apache.jetspeed.ldap.ldapServerName"); - ldapServerPort = props.getString("org.apache.jetspeed.ldap.ldapServerPort"); - rootContext = props.getString("org.apache.jetspeed.ldap.rootContext"); + props = new PropertiesConfiguration( + "JETSPEED-INF/directory/config/" + ldapType + + "/ldap.properties"); + initialContextFactory = props + .getString("org.apache.jetspeed.ldap.initialContextFactory"); + ldapServerName = props + .getString("org.apache.jetspeed.ldap.ldapServerName"); + ldapServerPort = props + .getString("org.apache.jetspeed.ldap.ldapServerPort"); + rootContext = props + .getString("org.apache.jetspeed.ldap.rootContext"); rootDn = props.getString("org.apache.jetspeed.ldap.rootDn"); - rootPassword = props.getString("org.apache.jetspeed.ldap.rootPassword"); - - roleFilter=props.getString("org.apache.jetspeed.ldap.RoleFilter"); - groupFilter=props.getString("org.apache.jetspeed.ldap.GroupFilter"); - userFilter=props.getString("org.apache.jetspeed.ldap.UserFilter"); + rootPassword = props + .getString("org.apache.jetspeed.ldap.rootPassword"); - roleMembershipAttributes=props.getString("org.apache.jetspeed.ldap.RoleMembershipAttributes"); - userRoleMembershipAttributes=props.getString("org.apache.jetspeed.ldap.UserRoleMembershipAttributes"); + roleFilter = props.getString("org.apache.jetspeed.ldap.RoleFilter"); + groupFilter = props + .getString("org.apache.jetspeed.ldap.GroupFilter"); + userFilter = props.getString("org.apache.jetspeed.ldap.UserFilter"); - groupMembershipAttributes=props.getString("org.apache.jetspeed.ldap.GroupMembershipAttributes"); - userGroupMembershipAttributes=props.getString("org.apache.jetspeed.ldap.UserGroupMembershipAttributes"); + roleMembershipAttributes = props + .getString("org.apache.jetspeed.ldap.RoleMembershipAttributes"); + userRoleMembershipAttributes = props + .getString("org.apache.jetspeed.ldap.UserRoleMembershipAttributes"); - groupMembershipForRoleAttributes=props.getString("org.apache.jetspeed.ldap.GroupMembershipForRoleAttributes"); - roleGroupMembershipForRoleAttributes=props.getString("org.apache.jetspeed.ldap.RoleGroupMembershipForRoleAttributes"); + groupMembershipAttributes = props + .getString("org.apache.jetspeed.ldap.GroupMembershipAttributes"); + userGroupMembershipAttributes = props + .getString("org.apache.jetspeed.ldap.UserGroupMembershipAttributes"); - - defaultSearchBase=props.getString("org.apache.jetspeed.ldap.DefaultSearchBase"); - - roleFilterBase=props.getString("org.apache.jetspeed.ldap.RoleFilterBase"); - groupFilterBase=props.getString("org.apache.jetspeed.ldap.GroupFilterBase"); - userFilterBase=props.getString("org.apache.jetspeed.ldap.UserFilterBase"); - - this.roleObjectClasses=StringUtils.split(props.getString("org.apache.jetspeed.ldap.RoleObjectClasses"),","); - this.groupObjectClasses=StringUtils.split(props.getString("org.apache.jetspeed.ldap.GroupObjectClasses"),","); - this.userObjectClasses=StringUtils.split(props.getString("org.apache.jetspeed.ldap.UserObjectClasses"),","); - - roleIdAttribute=props.getString("org.apache.jetspeed.ldap.RoleIdAttribute"); - groupIdAttribute=props.getString("org.apache.jetspeed.ldap.GroupIdAttribute"); - userIdAttribute=props.getString("org.apache.jetspeed.ldap.UserIdAttribute"); + groupMembershipForRoleAttributes = props + .getString("org.apache.jetspeed.ldap.GroupMembershipForRoleAttributes"); + roleGroupMembershipForRoleAttributes = props + .getString("org.apache.jetspeed.ldap.RoleGroupMembershipForRoleAttributes"); - uidAttribute =props.getString("org.apache.jetspeed.ldap.UidAttribute"); - memberShipSearchScope = props.getString("org.apache.jetspeed.ldap.MemberShipSearchScope"); - - this.roleUidAttribute=props.getString("org.apache.jetspeed.ldap.roleUidAttribute"); - this.groupUidAttribute=props.getString("org.apache.jetspeed.ldap.groupUidAttribute"); - this.userUidAttribute=props.getString("org.apache.jetspeed.ldap.userUidAttribute"); + defaultSearchBase = props + .getString("org.apache.jetspeed.ldap.DefaultSearchBase"); - this.roleObjectRequiredAttributeClasses=props.getString("org.apache.jetspeed.ldap.roleObjectRequiredAttributeClasses"); - this.groupObjectRequiredAttributeClasses=props.getString("org.apache.jetspeed.ldap.groupObjectRequiredAttributeClasses"); + roleFilterBase = props + .getString("org.apache.jetspeed.ldap.RoleFilterBase"); + groupFilterBase = props + .getString("org.apache.jetspeed.ldap.GroupFilterBase"); + userFilterBase = props + .getString("org.apache.jetspeed.ldap.UserFilterBase"); - this.roleAttributes=StringUtils.split(props.getString("org.apache.jetspeed.ldap.roleAttributes"),","); - this.groupAttributes=StringUtils.split(props.getString("org.apache.jetspeed.ldap.groupAttributes"),","); - this.userAttributes=StringUtils.split(props.getString("org.apache.jetspeed.ldap.userAttributes"),","); - this.userPasswordAttribute=props.getString("org.apache.jetspeed.ldap.userPasswordAttribute"); - - this.knownAttributes=StringUtils.split(props.getString("org.apache.jetspeed.ldap.knownAttributes"),","); + this.roleObjectClasses = StringUtils.split(props + .getString("org.apache.jetspeed.ldap.RoleObjectClasses"), + ","); + this.groupObjectClasses = StringUtils.split(props + .getString("org.apache.jetspeed.ldap.GroupObjectClasses"), + ","); + this.userObjectClasses = StringUtils.split(props + .getString("org.apache.jetspeed.ldap.UserObjectClasses"), + ","); + + roleIdAttribute = props + .getString("org.apache.jetspeed.ldap.RoleIdAttribute"); + groupIdAttribute = props + .getString("org.apache.jetspeed.ldap.GroupIdAttribute"); + userIdAttribute = props + .getString("org.apache.jetspeed.ldap.UserIdAttribute"); + + uidAttribute = props + .getString("org.apache.jetspeed.ldap.UidAttribute"); + memberShipSearchScope = props + .getString("org.apache.jetspeed.ldap.MemberShipSearchScope"); + + this.roleUidAttribute = props + .getString("org.apache.jetspeed.ldap.roleUidAttribute"); + this.groupUidAttribute = props + .getString("org.apache.jetspeed.ldap.groupUidAttribute"); + this.userUidAttribute = props + .getString("org.apache.jetspeed.ldap.userUidAttribute"); + + this.roleObjectRequiredAttributeClasses = props + .getString("org.apache.jetspeed.ldap.roleObjectRequiredAttributeClasses"); + this.groupObjectRequiredAttributeClasses = props + .getString("org.apache.jetspeed.ldap.groupObjectRequiredAttributeClasses"); + + this.roleAttributes = StringUtils.split(props + .getString("org.apache.jetspeed.ldap.roleAttributes"), ","); + this.groupAttributes = StringUtils + .split( + props + .getString("org.apache.jetspeed.ldap.groupAttributes"), + ","); + this.userAttributes = StringUtils.split(props + .getString("org.apache.jetspeed.ldap.userAttributes"), ","); + this.userPasswordAttribute = props + .getString("org.apache.jetspeed.ldap.userPasswordAttribute"); + + this.knownAttributes = StringUtils + .split( + props + .getString("org.apache.jetspeed.ldap.knownAttributes"), + ","); } catch (ConfigurationException ce) { logger.error("Could not configure LdapBindingConfig: " + ce); } } - + LdapContext getContext() { return context; } - + void setContext(LdapContext context) { this.context = context; @@ -283,13 +335,14 @@ } /** - * @param initialContextFactory The initialContextFactory to set. + * @param initialContextFactory + * The initialContextFactory to set. */ public void setInitialContextFactory(String initialContextFactory) { this.initialContextFactory = initialContextFactory; } - + /** * @return the ldapScheme */ @@ -299,7 +352,8 @@ } /** - * @param ldapScheme the ldapScheme to set + * @param ldapScheme + * the ldapScheme to set */ public void setLdapScheme(String ldapScheme) { @@ -315,7 +369,8 @@ } /** - * @param ldapSocketFactory the ldapSocketFactory to set + * @param ldapSocketFactory + * the ldapSocketFactory to set */ public void setLdapSocketFactory(String ldapSocketFactory) { @@ -331,7 +386,8 @@ } /** - * @param ldapServerName The ldapServerName to set. + * @param ldapServerName + * The ldapServerName to set. */ public void setLdapServerName(String ldapServerName) { @@ -347,7 +403,8 @@ } /** - * @param ldapServerPort The ldapServerPort to set. + * @param ldapServerPort + * The ldapServerPort to set. */ public void setLdapServerPort(String ldapServerPort) { @@ -363,7 +420,8 @@ } /** - * @param ldapSecurityLevel the ldapSecurityLevel to set + * @param ldapSecurityLevel + * the ldapSecurityLevel to set */ public void setLdapSecurityLevel(String ldapSecurityLevel) { @@ -379,7 +437,8 @@ } /** - * @param ldapSecurityProtocol the ldapSecurityProtocol to set + * @param ldapSecurityProtocol + * the ldapSecurityProtocol to set */ public void setLdapSecurityProtocol(String ldapSecurityProtocol) { @@ -395,7 +454,8 @@ } /** - * @param rootContext The rootContext to set. + * @param rootContext + * The rootContext to set. */ public void setRootContext(String rootContext) { @@ -411,7 +471,8 @@ } /** - * @param rootDn The rootDn to set. + * @param rootDn + * The rootDn to set. */ public void setRootDn(String rootDn) { @@ -427,272 +488,328 @@ } /** - * @param rootPassword The rootPassword to set. + * @param rootPassword + * The rootPassword to set. */ public void setRootPassword(String rootPassword) { this.rootPassword = rootPassword; } - public String getUserFilter() { - return userFilter; - } + public String getUserFilter() + { + return userFilter; + } - public void setUserFilter(String userFilter) { - this.userFilter = userFilter; - } + public void setUserFilter(String userFilter) + { + this.userFilter = userFilter; + } - public String getUserFilterBase() { - return userFilterBase; - } + public String getUserFilterBase() + { + return userFilterBase; + } - public void setUserFilterBase(String userFilterBase) { - this.userFilterBase = userFilterBase; - } + public void setUserFilterBase(String userFilterBase) + { + this.userFilterBase = userFilterBase; + } - public String getUserGroupMembershipAttributes() { - return userGroupMembershipAttributes; - } + public String getUserGroupMembershipAttributes() + { + return userGroupMembershipAttributes; + } - public void setUserGroupMembershipAttributes( - String userGroupMembershipAttributes) { - this.userGroupMembershipAttributes = userGroupMembershipAttributes; - } + public void setUserGroupMembershipAttributes( + String userGroupMembershipAttributes) + { + this.userGroupMembershipAttributes = userGroupMembershipAttributes; + } - public String getUserRoleMembershipAttributes() { - return userRoleMembershipAttributes; - } + public String getUserRoleMembershipAttributes() + { + return userRoleMembershipAttributes; + } - public void setUserRoleMembershipAttributes(String userRoleMembershipAttributes) { - this.userRoleMembershipAttributes = userRoleMembershipAttributes; - } + public void setUserRoleMembershipAttributes( + String userRoleMembershipAttributes) + { + this.userRoleMembershipAttributes = userRoleMembershipAttributes; + } - public String getDefaultSearchBase() { - return defaultSearchBase; - } + public String getDefaultSearchBase() + { + return defaultSearchBase; + } - public void setDefaultSearchBase(String defaultSearchBase) { - this.defaultSearchBase = defaultSearchBase; - } + public void setDefaultSearchBase(String defaultSearchBase) + { + this.defaultSearchBase = defaultSearchBase; + } - public String getGroupFilter() { - return groupFilter; - } + public String getGroupFilter() + { + return groupFilter; + } - public void setGroupFilter(String groupFilter) { - this.groupFilter = groupFilter; - } + public void setGroupFilter(String groupFilter) + { + this.groupFilter = groupFilter; + } - public String getGroupFilterBase() { - return groupFilterBase; - } + public String getGroupFilterBase() + { + return groupFilterBase; + } - public void setGroupFilterBase(String groupFilterBase) { - this.groupFilterBase = groupFilterBase; - } + public void setGroupFilterBase(String groupFilterBase) + { + this.groupFilterBase = groupFilterBase; + } - public String getGroupMembershipAttributes() { - return groupMembershipAttributes; - } + public String getGroupMembershipAttributes() + { + return groupMembershipAttributes; + } - public void setGroupMembershipAttributes(String groupMembershipAttributes) { - this.groupMembershipAttributes = groupMembershipAttributes; - } + public void setGroupMembershipAttributes(String groupMembershipAttributes) + { + this.groupMembershipAttributes = groupMembershipAttributes; + } - public String getGroupIdAttribute() { - return groupIdAttribute; - } + public String getGroupIdAttribute() + { + return groupIdAttribute; + } - public void setGroupIdAttribute(String groupIdAttribute) { - this.groupIdAttribute = groupIdAttribute; - } + public void setGroupIdAttribute(String groupIdAttribute) + { + this.groupIdAttribute = groupIdAttribute; + } + public String getUserIdAttribute() + { + return userIdAttribute; + } - public String getUserIdAttribute() { - return userIdAttribute; - } + public void setUserIdAttribute(String userIdAttribute) + { + this.userIdAttribute = userIdAttribute; + } - public void setUserIdAttribute(String userIdAttribute) { - this.userIdAttribute = userIdAttribute; - } + public String[] getGroupObjectClasses() + { + return groupObjectClasses; + } - public String[] getGroupObjectClasses() { - return groupObjectClasses; - } + public void setGroupObjectClasses(String[] groupObjectClasses) + { + this.groupObjectClasses = groupObjectClasses; + } - public void setGroupObjectClasses(String[] groupObjectClasses) { - this.groupObjectClasses = groupObjectClasses; - } + public String[] getUserObjectClasses() + { + return userObjectClasses; + } + public void setUserObjectClasses(String[] userObjectClasses) + { + this.userObjectClasses = userObjectClasses; + } + public String getGroupMembershipForRoleAttributes() + { + return this.groupMembershipForRoleAttributes; + } - public String[] getUserObjectClasses() { - return userObjectClasses; - } + public void setGroupMembershipForRoleAttributes( + String groupMembershipForRoleAttributes) + { + this.groupMembershipForRoleAttributes = groupMembershipForRoleAttributes; + } - public void setUserObjectClasses(String[] userObjectClasses) { - this.userObjectClasses = userObjectClasses; - } + public String getUidAttribute() + { + return uidAttribute; + } + public void setUidAttribute(String uidAttribute) + { + this.uidAttribute = uidAttribute; + } - public String getGroupMembershipForRoleAttributes() { - return this.groupMembershipForRoleAttributes; - } - + public String getMemberShipSearchScope() + { + return memberShipSearchScope; + } + public void setMemberShipSearchScope(String memberShipSearchScope) + { + this.memberShipSearchScope = memberShipSearchScope; + } - public void setGroupMembershipForRoleAttributes(String groupMembershipForRoleAttributes) { - this.groupMembershipForRoleAttributes=groupMembershipForRoleAttributes; - } + public String getGroupUidAttribute() + { + return this.groupUidAttribute; + } - public String getUidAttribute() { - return uidAttribute; - } + public void setGroupUidAttribute(String groupUidAttribute) + { + this.groupUidAttribute = groupUidAttribute; + } - public void setUidAttribute(String uidAttribute) { - this.uidAttribute = uidAttribute; - } + public String getUserUidAttribute() + { + return this.userUidAttribute; + } - public String getMemberShipSearchScope() { - return memberShipSearchScope; - } + public void setUserUidAttribute(String userUidAttribute) + { + this.userUidAttribute = userUidAttribute; + } - public void setMemberShipSearchScope(String memberShipSearchScope) { - this.memberShipSearchScope = memberShipSearchScope; - } + public String getGroupObjectRequiredAttributeClasses() + { + return groupObjectRequiredAttributeClasses; + } - public String getGroupUidAttribute() { - return this.groupUidAttribute; - } + public void setGroupObjectRequiredAttributeClasses( + String groupObjectRequiredAttributeClasses) + { + this.groupObjectRequiredAttributeClasses = groupObjectRequiredAttributeClasses; + } - public void setGroupUidAttribute(String groupUidAttribute) { - this.groupUidAttribute = groupUidAttribute; - } + public String[] getGroupAttributes() + { + return groupAttributes; + } - public String getUserUidAttribute() { - return this.userUidAttribute; - } - - public void setUserUidAttribute(String userUidAttribute) { - this.userUidAttribute = userUidAttribute; - } + public void setGroupAttributes(String[] groupAttributes) + { + this.groupAttributes = groupAttributes; + } - public String getGroupObjectRequiredAttributeClasses() { - return groupObjectRequiredAttributeClasses; - } + public String[] getUserAttributes() + { + return userAttributes; + } - public void setGroupObjectRequiredAttributeClasses( - String groupObjectRequiredAttributeClasses) { - this.groupObjectRequiredAttributeClasses = groupObjectRequiredAttributeClasses; - } + public void setUserAttributes(String[] userAttributes) + { + this.userAttributes = userAttributes; + } + public String getRoleObjectRequiredAttributeClasses() + { + return roleObjectRequiredAttributeClasses; + } + public void setRoleObjectRequiredAttributeClasses( + String roleObjectRequiredAttributeClasses) + { + this.roleObjectRequiredAttributeClasses = roleObjectRequiredAttributeClasses; + } - public String[] getGroupAttributes() { - return groupAttributes; - } + public String[] getRoleAttributes() + { + return roleAttributes; + } - public void setGroupAttributes(String[] groupAttributes) { - this.groupAttributes = groupAttributes; - } + public void setRoleAttributes(String[] roleAttributes) + { + this.roleAttributes = roleAttributes; + } - public String[] getUserAttributes() { - return userAttributes; - } + public String[] getRoleObjectClasses() + { + return roleObjectClasses; + } - public void setUserAttributes(String[] userAttributes) { - this.userAttributes = userAttributes; - } - - public String getRoleObjectRequiredAttributeClasses() { - return roleObjectRequiredAttributeClasses; - } + public void setRoleObjectClasses(String[] roleObjectClasses) + { + this.roleObjectClasses = roleObjectClasses; + } - public void setRoleObjectRequiredAttributeClasses( - String roleObjectRequiredAttributeClasses) { - this.roleObjectRequiredAttributeClasses = roleObjectRequiredAttributeClasses; - } - - public String[] getRoleAttributes() { - return roleAttributes; - } + public String getRoleGroupMembershipForRoleAttributes() + { + return this.roleGroupMembershipForRoleAttributes; + } - public void setRoleAttributes(String[] roleAttributes) { - this.roleAttributes = roleAttributes; - } - - public String[] getRoleObjectClasses() { - return roleObjectClasses; - } + public void setRoleGroupMembershipForRoleAttributes( + String roleGroupMembershipForRoleAttributes) + { + this.roleGroupMembershipForRoleAttributes = roleGroupMembershipForRoleAttributes; + } - public void setRoleObjectClasses(String[] roleObjectClasses) { - this.roleObjectClasses = roleObjectClasses; - } - + public String getRoleFilter() + { + return roleFilter; + } - public String getRoleGroupMembershipForRoleAttributes() { - return this.roleGroupMembershipForRoleAttributes; - } - - public void setRoleGroupMembershipForRoleAttributes(String roleGroupMembershipForRoleAttributes) { - this.roleGroupMembershipForRoleAttributes=roleGroupMembershipForRoleAttributes; - } + public void setRoleFilter(String roleFilter) + { + this.roleFilter = roleFilter; + } - public String getRoleFilter() { - return roleFilter; - } + public String getRoleFilterBase() + { + return roleFilterBase; + } - public void setRoleFilter(String roleFilter) { - this.roleFilter = roleFilter; - } + public void setRoleFilterBase(String roleFilterBase) + { + this.roleFilterBase = roleFilterBase; + } - public String getRoleFilterBase() { - return roleFilterBase; - } + public String getRoleMembershipAttributes() + { + return roleMembershipAttributes; + } - public void setRoleFilterBase(String roleFilterBase) { - this.roleFilterBase = roleFilterBase; - } + public void setRoleMembershipAttributes(String roleMembershipAttributes) + { + this.roleMembershipAttributes = roleMembershipAttributes; + } - public String getRoleMembershipAttributes() { - return roleMembershipAttributes; - } + public String getRoleUidAttribute() + { + return this.roleUidAttribute; + } - public void setRoleMembershipAttributes(String roleMembershipAttributes) { - this.roleMembershipAttributes = roleMembershipAttributes; - } + public void setRoleUidAttribute(String roleUidAttribute) + { + this.roleUidAttribute = roleUidAttribute; + } - public String getRoleUidAttribute() { - return this.roleUidAttribute; - } + public String getRoleIdAttribute() + { + return roleIdAttribute; + } - public void setRoleUidAttribute(String roleUidAttribute) { - this.roleUidAttribute = roleUidAttribute; - } - + public void setRoleIdAttribute(String roleIdAttribute) + { + this.roleIdAttribute = roleIdAttribute; + } - public String getRoleIdAttribute() { - return roleIdAttribute; - } + public String getUserPasswordAttribute() + { + return userPasswordAttribute; + } - public void setRoleIdAttribute(String roleIdAttribute) { - this.roleIdAttribute = roleIdAttribute; - } + public void setUserPasswordAttribute(String userPasswordAttribute) + { + this.userPasswordAttribute = userPasswordAttribute; + } - public String getUserPasswordAttribute() { - return userPasswordAttribute; - } + public String[] getKnownAttributes() + { + return this.knownAttributes; + } - public void setUserPasswordAttribute(String userPasswordAttribute) { - this.userPasswordAttribute = userPasswordAttribute; - } + public void setKnownAttributes(String[] knownAttributes) + { + this.knownAttributes = knownAttributes; + } - public String[] getKnownAttributes() { - return this.knownAttributes; - } - - public void setKnownAttributes(String[] knownAttributes) { - this.knownAttributes = knownAttributes; - } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapContextProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapContextProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapContextProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -39,52 +39,64 @@ */ public class LdapContextProxy implements InvocationHandler { + private Properties env; + private LdapContext ctx; - + public static LdapContext createProxy(LdapBindingConfig config) { LdapContext proxy = config.getContext(); - - if ( proxy == null || !(Proxy.getInvocationHandler(proxy) instanceof LdapContextProxy)) + + if (proxy == null + || !(Proxy.getInvocationHandler(proxy) instanceof LdapContextProxy)) { - proxy = (LdapContext)Proxy.newProxyInstance(LdapContext.class.getClassLoader(),new Class[]{LdapContext.class}, new LdapContextProxy(config)); + proxy = (LdapContext) Proxy.newProxyInstance(LdapContext.class + .getClassLoader(), new Class[] + {LdapContext.class}, new LdapContextProxy(config)); config.setContext(proxy); } return proxy; } - + private LdapContextProxy(LdapBindingConfig ldapBindingConfig) { env = new Properties(); - env.put(Context.INITIAL_CONTEXT_FACTORY, ldapBindingConfig.getInitialContextFactory()); - env.put(Context.PROVIDER_URL, ldapBindingConfig.getLdapScheme() + "://" + ldapBindingConfig.getLdapServerName() + ":" - + ldapBindingConfig.getLdapServerPort() + "/" + ldapBindingConfig.getRootContext()); + env.put(Context.INITIAL_CONTEXT_FACTORY, ldapBindingConfig + .getInitialContextFactory()); + env.put(Context.PROVIDER_URL, ldapBindingConfig.getLdapScheme() + "://" + + ldapBindingConfig.getLdapServerName() + ":" + + ldapBindingConfig.getLdapServerPort() + "/" + + ldapBindingConfig.getRootContext()); env.put(Context.SECURITY_PRINCIPAL, ldapBindingConfig.getRootDn()); - env.put(Context.SECURITY_CREDENTIALS, ldapBindingConfig.getRootPassword()); - env.put(Context.SECURITY_AUTHENTICATION, ldapBindingConfig.getLdapSecurityLevel()); - if ( !StringUtils.isEmpty(ldapBindingConfig.getLdapSecurityProtocol()) ) + env.put(Context.SECURITY_CREDENTIALS, ldapBindingConfig + .getRootPassword()); + env.put(Context.SECURITY_AUTHENTICATION, ldapBindingConfig + .getLdapSecurityLevel()); + if (!StringUtils.isEmpty(ldapBindingConfig.getLdapSecurityProtocol())) { - env.put(Context.SECURITY_PROTOCOL, ldapBindingConfig.getLdapSecurityProtocol()); + env.put(Context.SECURITY_PROTOCOL, ldapBindingConfig + .getLdapSecurityProtocol()); } - if ( !StringUtils.isEmpty(ldapBindingConfig.getLdapSocketFactory()) ) + if (!StringUtils.isEmpty(ldapBindingConfig.getLdapSocketFactory())) { - env.put("java.naming.ldap.factory.socket", ldapBindingConfig.getLdapSocketFactory()); + env.put("java.naming.ldap.factory.socket", ldapBindingConfig + .getLdapSocketFactory()); } } - + private LdapContext getCtx() throws NamingException { - if ( ctx == null ) + if (ctx == null) { ctx = new InitialLdapContext(env, null); } return ctx; } - + private void closeCtx() { - if ( ctx != null ) + if (ctx != null) { try { @@ -96,17 +108,19 @@ ctx = null; } } + /* * (non-Javadoc) * * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, * java.lang.reflect.Method, java.lang.Object[]) */ - public synchronized Object invoke(Object proxy, Method m, Object[] args) throws Throwable + public synchronized Object invoke(Object proxy, Method m, Object[] args) + throws Throwable { Object result = null; boolean close = "close".equals(m.getName()) && args.length == 0; - if ( close && ctx == null ) + if (close && ctx == null) { // don't need to do anything ; @@ -114,11 +128,11 @@ else { LdapContext ctx = getCtx(); - + try { - result = m.invoke(ctx,args); - if ( close ) + result = m.invoke(ctx, args); + if (close) { closeCtx(); } @@ -126,26 +140,28 @@ catch (Throwable t) { closeCtx(); - - if ( t instanceof InvocationTargetException) + + if (t instanceof InvocationTargetException) { - t = ((InvocationTargetException)t).getTargetException(); + t = ((InvocationTargetException) t).getTargetException(); } - if (t instanceof ServiceUnavailableException || t instanceof CommunicationException) + if (t instanceof ServiceUnavailableException + || t instanceof CommunicationException) { try { ctx = getCtx(); - result = m.invoke(ctx,args); + result = m.invoke(ctx, args); } catch (Throwable t2) { closeCtx(); - if ( t2 instanceof InvocationTargetException) + if (t2 instanceof InvocationTargetException) { - t2 = ((InvocationTargetException)t2).getTargetException(); + t2 = ((InvocationTargetException) t2) + .getTargetException(); } - + throw t2; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapGroupDaoImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapGroupDaoImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapGroupDaoImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,12 +37,13 @@ public class LdapGroupDaoImpl extends LdapPrincipalDaoImpl { - /** + /** * <p> * Default constructor. * </p> * - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ public LdapGroupDaoImpl() throws SecurityException { @@ -54,20 +55,25 @@ * Initializes the dao. * </p> * - * @param ldapConfig Holds the ldap binding configuration. - * @throws SecurityException A {@link SecurityException}. + * @param ldapConfig + * Holds the ldap binding configuration. + * @throws SecurityException + * A {@link SecurityException}. */ - public LdapGroupDaoImpl(LdapBindingConfig ldapConfig) throws SecurityException + public LdapGroupDaoImpl(LdapBindingConfig ldapConfig) + throws SecurityException { super(ldapConfig); } /** * <p> - * A template method for defining the attributes for a particular LDAP class. + * A template method for defining the attributes for a particular LDAP + * class. * </p> * - * @param principalUid The principal uid. + * @param principalUid + * The principal uid. * @return The LDAP attributes object for the particular class. */ protected Attributes defineLdapAttributes(final String principalUid) @@ -75,19 +81,21 @@ Attributes attrs = new BasicAttributes(true); BasicAttribute classes = new BasicAttribute("objectclass"); - for (int i=0 ; i<getObjectClasses().length ; i++) - classes.add(getObjectClasses()[i]); + for (int i = 0; i < getObjectClasses().length; i++) + classes.add(getObjectClasses()[i]); attrs.put(classes); attrs.put(getEntryPrefix(), principalUid); - if(!StringUtils.isEmpty(getGroupObjectRequiredAttributeClasses())) + if (!StringUtils.isEmpty(getGroupObjectRequiredAttributeClasses())) { - String[] required = getGroupObjectRequiredAttributeClasses().split(","); - for (int i=0; i<required.length; i++) - attrs.put(required[i], ""); + String[] required = getGroupObjectRequiredAttributeClasses().split( + ","); + for (int i = 0; i < required.length; i++) + attrs.put(required[i], ""); } - for (int i=0;i<getAttributes().length;i++) - attrs.put(parseAttr(getAttributes()[i],principalUid)[0], parseAttr(getAttributes()[i],principalUid)[1]); - + for (int i = 0; i < getAttributes().length; i++) + attrs.put(parseAttr(getAttributes()[i], principalUid)[0], + parseAttr(getAttributes()[i], principalUid)[1]); + return attrs; } @@ -96,7 +104,7 @@ */ protected String getDnSuffix() { - return getGroupFilterBase(); + return getGroupFilterBase(); } /** @@ -104,7 +112,8 @@ * Creates a GroupPrincipal object. * </p> * - * @param principalUid The principal uid. + * @param principalUid + * The principal uid. * @return A group principal object. */ protected Principal makePrincipal(String principalUid) @@ -112,30 +121,34 @@ return new GroupPrincipalImpl(principalUid); } + protected String getEntryPrefix() + { + return this.getGroupIdAttribute(); + } - protected String getEntryPrefix() { - return this.getGroupIdAttribute(); - } - - protected String getSearchSuffix() { - return this.getGroupFilter(); - } + protected String getSearchSuffix() + { + return this.getGroupFilter(); + } - protected String getSearchDomain() { - return this.getGroupFilterBase(); - } + protected String getSearchDomain() + { + return this.getGroupFilterBase(); + } - protected String[] getObjectClasses() { - return this.getGroupObjectClasses(); - } + protected String[] getObjectClasses() + { + return this.getGroupObjectClasses(); + } - protected String getUidAttributeForPrincipal() { - return this.getGroupUidAttribute(); - } + protected String getUidAttributeForPrincipal() + { + return this.getGroupUidAttribute(); + } - protected String[] getAttributes() { - return this.getGroupAttributes(); - } - - + protected String[] getAttributes() + { + return this.getGroupAttributes(); + } + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapMemberShipDaoImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapMemberShipDaoImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapMemberShipDaoImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi.impl.ldap; import java.security.Principal; @@ -38,350 +38,454 @@ import org.apache.jetspeed.security.SecurityException; import org.apache.jetspeed.security.impl.UserPrincipalImpl; +public class LdapMemberShipDaoImpl extends LdapPrincipalDaoImpl implements + LdapMembershipDao +{ -public class LdapMemberShipDaoImpl extends LdapPrincipalDaoImpl implements LdapMembershipDao { + /** The logger. */ + private static final Log logger = LogFactory + .getLog(LdapMemberShipDaoImpl.class); - /** The logger. */ - private static final Log logger = LogFactory.getLog(LdapMemberShipDaoImpl.class); + public LdapMemberShipDaoImpl() throws SecurityException + { + super(); + } - public LdapMemberShipDaoImpl() throws SecurityException { - super(); - } - - public LdapMemberShipDaoImpl(LdapBindingConfig config) throws SecurityException { - super(config); - } + public LdapMemberShipDaoImpl(LdapBindingConfig config) + throws SecurityException + { + super(config); + } - /* (non-Javadoc) - * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchGroupMemberShipByGroup(java.lang.String, javax.naming.directory.SearchControls) - */ - public String[] searchGroupMemberShipByGroup(final String userPrincipalUid, SearchControls cons) throws NamingException { - - String query = "(&(" + getGroupMembershipAttribute() + "=" + getUserDN(userPrincipalUid) + ")" + getGroupFilter() + ")"; - - if (logger.isDebugEnabled()) - { - logger.debug("query[" + query + "]"); - } - - cons.setSearchScope(getSearchScope()); + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchGroupMemberShipByGroup(java.lang.String, + * javax.naming.directory.SearchControls) + */ + public String[] searchGroupMemberShipByGroup(final String userPrincipalUid, + SearchControls cons) throws NamingException + { + + String query = "(&(" + getGroupMembershipAttribute() + "=" + + getUserDN(userPrincipalUid) + ")" + getGroupFilter() + ")"; + + if (logger.isDebugEnabled()) + { + logger.debug("query[" + query + "]"); + } + + cons.setSearchScope(getSearchScope()); String groupFilterBase = getGroupFilterBase(); - NamingEnumeration searchResults = ((DirContext) ctx).search(groupFilterBase,query , cons); + NamingEnumeration searchResults = ((DirContext) ctx).search( + groupFilterBase, query, cons); - List groupPrincipalUids = new ArrayList(); - while (searchResults.hasMore()) - { - SearchResult result = (SearchResult) searchResults.next(); - Attributes answer = result.getAttributes(); - groupPrincipalUids.addAll(getAttributes(getAttribute(getGroupIdAttribute(), answer))); - } - return (String[]) groupPrincipalUids.toArray(new String[groupPrincipalUids.size()]); - - } + List groupPrincipalUids = new ArrayList(); + while (searchResults.hasMore()) + { + SearchResult result = (SearchResult) searchResults.next(); + Attributes answer = result.getAttributes(); + groupPrincipalUids.addAll(getAttributes(getAttribute( + getGroupIdAttribute(), answer))); + } + return (String[]) groupPrincipalUids + .toArray(new String[groupPrincipalUids.size()]); - /* (non-Javadoc) - * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchGroupMemberShipByUser(java.lang.String, javax.naming.directory.SearchControls) - */ - public String[] searchGroupMemberShipByUser(final String userPrincipalUid, SearchControls cons) throws NamingException { - NamingEnumeration searchResults = searchByWildcardedUid(userPrincipalUid, cons); - - if (!searchResults.hasMore()) - { - throw new NamingException("Could not find any user with uid[" + userPrincipalUid + "]"); - } - - Attributes userAttributes = getFirstUser(searchResults); - List groupUids = new ArrayList(); - Attribute attr = getAttribute(getUserGroupMembershipAttribute(), userAttributes); - List attrs = getAttributes(attr); - Iterator it = attrs.iterator(); - while(it.hasNext()) { - String cnfull = (String)it.next(); - if(cnfull.toLowerCase().indexOf(getGroupFilterBase().toLowerCase())!=-1) { - String cn = extractLdapAttr(cnfull,getRoleUidAttribute()); - if (cn != null){ - groupUids.add(cn); - } - } - } - //List uids = getAttributes(getAttribute(getUserGroupMembershipAttribute(), userAttributes),getGroupFilterBase()); - return (String[]) groupUids.toArray(new String[groupUids.size()]); - } + } - /* (non-Javadoc) - * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchRoleMemberShipByRole(java.lang.String, javax.naming.directory.SearchControls) - */ - public String[] searchRoleMemberShipByRole(final String userPrincipalUid, SearchControls cons) throws NamingException { + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchGroupMemberShipByUser(java.lang.String, + * javax.naming.directory.SearchControls) + */ + public String[] searchGroupMemberShipByUser(final String userPrincipalUid, + SearchControls cons) throws NamingException + { + NamingEnumeration searchResults = searchByWildcardedUid( + userPrincipalUid, cons); - String query = "(&(" + getRoleMembershipAttribute() + "=" + getUserDN(userPrincipalUid) + ")" + getRoleFilter() + ")"; - - if (logger.isDebugEnabled()) - { - logger.debug("query[" + query + "]"); - } + if (!searchResults.hasMore()) { throw new NamingException( + "Could not find any user with uid[" + userPrincipalUid + "]"); } - cons.setSearchScope(getSearchScope()); - NamingEnumeration searchResults = ((DirContext) ctx).search(getRoleFilterBase(),query , cons); - List rolePrincipalUids = new ArrayList(); - while (searchResults.hasMore()) - { - - SearchResult result = (SearchResult) searchResults.next(); - Attributes answer = result.getAttributes(); - rolePrincipalUids.addAll(getAttributes(getAttribute(getRoleIdAttribute(), answer))); - } - return (String[]) rolePrincipalUids.toArray(new String[rolePrincipalUids.size()]); - } + Attributes userAttributes = getFirstUser(searchResults); + List groupUids = new ArrayList(); + Attribute attr = getAttribute(getUserGroupMembershipAttribute(), + userAttributes); + List attrs = getAttributes(attr); + Iterator it = attrs.iterator(); + while (it.hasNext()) + { + String cnfull = (String) it.next(); + if (cnfull.toLowerCase() + .indexOf(getGroupFilterBase().toLowerCase()) != -1) + { + String cn = extractLdapAttr(cnfull, getRoleUidAttribute()); + if (cn != null) + { + groupUids.add(cn); + } + } + } + // List uids = + // getAttributes(getAttribute(getUserGroupMembershipAttribute(), + // userAttributes),getGroupFilterBase()); + return (String[]) groupUids.toArray(new String[groupUids.size()]); + } - /* (non-Javadoc) - * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchRoleMemberShipByUser(java.lang.String, javax.naming.directory.SearchControls) - */ - public String[] searchRoleMemberShipByUser(final String userPrincipalUid, SearchControls cons) throws NamingException { - - NamingEnumeration results = searchByWildcardedUid(userPrincipalUid, cons); - - if (!results.hasMore()) - { - throw new NamingException("Could not find any user with uid[" + userPrincipalUid + "]"); - } - - Attributes userAttributes = getFirstUser(results); - List newAttrs = new ArrayList(); - Attribute attr = getAttribute(getUserRoleMembershipAttribute(), userAttributes); - List attrs = getAttributes(attr); - Iterator it = attrs.iterator(); - while(it.hasNext()) { - String cnfull = (String)it.next(); - if(cnfull.toLowerCase().indexOf(getRoleFilterBase().toLowerCase())!=-1) { - String cn = extractLdapAttr(cnfull,getRoleUidAttribute()); - if (cn != null){ - newAttrs.add(cn); - } - }else{ - // No conversion required (I think!) - String cn = cnfull; - newAttrs.add(cn); - } - } - return (String[]) newAttrs.toArray(new String[newAttrs.size()]); - } + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchRoleMemberShipByRole(java.lang.String, + * javax.naming.directory.SearchControls) + */ + public String[] searchRoleMemberShipByRole(final String userPrincipalUid, + SearchControls cons) throws NamingException + { - /* (non-Javadoc) - * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchUsersFromGroupByGroup(java.lang.String, javax.naming.directory.SearchControls) - */ - public String[] searchUsersFromGroupByGroup(final String groupPrincipalUid, SearchControls cons) - throws NamingException - { - - String query = "(&(" + getGroupIdAttribute() + "=" + (groupPrincipalUid) + ")" + getGroupFilter() + ")"; - - if (logger.isDebugEnabled()) - { - logger.debug("query[" + query + "]"); - } - - ArrayList userPrincipalUids=new ArrayList(); - - cons.setSearchScope(getSearchScope()); - NamingEnumeration results = ((DirContext) ctx).search(getGroupFilterBase(),query , cons); - - while (results.hasMore()) - { - SearchResult result = (SearchResult) results.next(); - Attributes answer = result.getAttributes(); - - List newAttrs = new ArrayList(); - - Attribute userPrincipalUid = getAttribute(getGroupMembershipAttribute(), answer); - List attrs = getAttributes(userPrincipalUid); - Iterator it = attrs.iterator(); - while(it.hasNext()) { - String uidfull = (String)it.next(); - if (!StringUtils.isEmpty(uidfull)) { - if (uidfull.toLowerCase().indexOf(getUserFilterBase().toLowerCase())!=-1) { - String uid = extractLdapAttr(uidfull,getUserIdAttribute()); - if (uid != null){ - newAttrs.add(uid); - } - } - } - } - userPrincipalUids.addAll(newAttrs); - } - return (String[]) userPrincipalUids.toArray(new String[userPrincipalUids.size()]); - } + String query = "(&(" + getRoleMembershipAttribute() + "=" + + getUserDN(userPrincipalUid) + ")" + getRoleFilter() + ")"; - /* (non-Javadoc) - * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchUsersFromGroupByUser(java.lang.String, javax.naming.directory.SearchControls) - */ - public String[] searchUsersFromGroupByUser(final String groupPrincipalUid, SearchControls cons) - throws NamingException - { - - String query = "(&(" + getUserGroupMembershipAttribute() + "=" + getGroupDN(groupPrincipalUid) + ")" + getUserFilter() + ")"; - if (logger.isDebugEnabled()) - { - logger.debug("query[" + query + "]"); - } + if (logger.isDebugEnabled()) + { + logger.debug("query[" + query + "]"); + } - cons.setSearchScope(getSearchScope()); - NamingEnumeration results = ((DirContext) ctx).search(getUserFilterBase(),query , cons); + cons.setSearchScope(getSearchScope()); + NamingEnumeration searchResults = ((DirContext) ctx).search( + getRoleFilterBase(), query, cons); + List rolePrincipalUids = new ArrayList(); + while (searchResults.hasMore()) + { - ArrayList userPrincipalUids = new ArrayList(); - - while (results.hasMore()) - { - SearchResult result = (SearchResult) results.next(); - Attributes answer = result.getAttributes(); - userPrincipalUids.addAll(getAttributes(getAttribute(getUserIdAttribute(), answer))); - } - return (String[]) userPrincipalUids.toArray(new String[userPrincipalUids.size()]); - } - - public String[] searchRolesFromGroupByGroup(final String groupPrincipalUid, - SearchControls cons) throws NamingException { + SearchResult result = (SearchResult) searchResults.next(); + Attributes answer = result.getAttributes(); + rolePrincipalUids.addAll(getAttributes(getAttribute( + getRoleIdAttribute(), answer))); + } + return (String[]) rolePrincipalUids + .toArray(new String[rolePrincipalUids.size()]); + } - String query = "(&(" + getGroupIdAttribute() + "=" + (groupPrincipalUid) + ")" + getGroupFilter() + ")"; + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchRoleMemberShipByUser(java.lang.String, + * javax.naming.directory.SearchControls) + */ + public String[] searchRoleMemberShipByUser(final String userPrincipalUid, + SearchControls cons) throws NamingException + { - if (logger.isDebugEnabled()) { - logger.debug("query[" + query + "]"); - } + NamingEnumeration results = searchByWildcardedUid(userPrincipalUid, + cons); - ArrayList rolePrincipalUids = new ArrayList(); + if (!results.hasMore()) { throw new NamingException( + "Could not find any user with uid[" + userPrincipalUid + "]"); } - cons.setSearchScope(getSearchScope()); - NamingEnumeration groups = ((DirContext) ctx).search(getGroupFilterBase(),query , cons); + Attributes userAttributes = getFirstUser(results); + List newAttrs = new ArrayList(); + Attribute attr = getAttribute(getUserRoleMembershipAttribute(), + userAttributes); + List attrs = getAttributes(attr); + Iterator it = attrs.iterator(); + while (it.hasNext()) + { + String cnfull = (String) it.next(); + if (cnfull.toLowerCase().indexOf(getRoleFilterBase().toLowerCase()) != -1) + { + String cn = extractLdapAttr(cnfull, getRoleUidAttribute()); + if (cn != null) + { + newAttrs.add(cn); + } + } + else + { + // No conversion required (I think!) + String cn = cnfull; + newAttrs.add(cn); + } + } + return (String[]) newAttrs.toArray(new String[newAttrs.size()]); + } - while (groups.hasMore()) { - SearchResult group = (SearchResult) groups.next(); - Attributes groupAttributes = group.getAttributes(); + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchUsersFromGroupByGroup(java.lang.String, + * javax.naming.directory.SearchControls) + */ + public String[] searchUsersFromGroupByGroup(final String groupPrincipalUid, + SearchControls cons) throws NamingException + { - Attribute rolesFromGroup = getAttribute(getGroupMembershipForRoleAttribute(), groupAttributes); - List roleDNs = getAttributes(rolesFromGroup,getRoleFilterBase()); - Iterator it = roleDNs.iterator(); - while (it.hasNext()) { - String roleDN = (String) it.next(); - if (!StringUtils.isEmpty(roleDN)) { - String roleId = extractLdapAttr(roleDN,getRoleUidAttribute()); - if (roleId!=null) { - NamingEnumeration rolesResults = searchRoleByWildcardedUid(roleId, cons); - if (rolesResults.hasMore()) - if(rolesResults.nextElement()!=null) - rolePrincipalUids.add(roleId); - } - } - } - } - return (String[]) rolePrincipalUids.toArray(new String[rolePrincipalUids.size()]); - } + String query = "(&(" + getGroupIdAttribute() + "=" + + (groupPrincipalUid) + ")" + getGroupFilter() + ")"; - /* - * (non-Javadoc) - * - * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchUsersFromGroupByUser(java.lang.String, - * javax.naming.directory.SearchControls) - */ - public String[] searchRolesFromGroupByRole(final String groupPrincipalUid, - SearchControls cons) throws NamingException { + if (logger.isDebugEnabled()) + { + logger.debug("query[" + query + "]"); + } - String query = "(&(" + getRoleGroupMembershipForRoleAttribute() + "=" + getGroupDN(groupPrincipalUid) + ")" + getRoleFilter() + ")"; - - if (logger.isDebugEnabled()) { - logger.debug("query[" + query + "]"); - } - - cons.setSearchScope(getSearchScope()); - NamingEnumeration results = ((DirContext) ctx).search(getRoleFilterBase(),query , cons); + ArrayList userPrincipalUids = new ArrayList(); - ArrayList rolePrincipalUids = new ArrayList(); + cons.setSearchScope(getSearchScope()); + NamingEnumeration results = ((DirContext) ctx).search( + getGroupFilterBase(), query, cons); - while (results.hasMore()) { - SearchResult result = (SearchResult) results.next(); - Attributes answer = result.getAttributes(); - rolePrincipalUids.addAll(getAttributes(getAttribute(getRoleIdAttribute(), answer))); - } - return (String[]) rolePrincipalUids - .toArray(new String[rolePrincipalUids.size()]); - } + while (results.hasMore()) + { + SearchResult result = (SearchResult) results.next(); + Attributes answer = result.getAttributes(); + List newAttrs = new ArrayList(); - /* (non-Javadoc) - * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchUsersFromRoleByRole(java.lang.String, javax.naming.directory.SearchControls) - */ - public String[] searchUsersFromRoleByRole(final String rolePrincipalUid, SearchControls cons) - throws NamingException - { - - String query = "(&(" + getRoleIdAttribute() + "=" + (rolePrincipalUid) + ")" + getRoleFilter() + ")"; - - if (logger.isDebugEnabled()) - { - logger.debug("query[" + query + "]"); - } - - ArrayList userPrincipalUids=new ArrayList(); + Attribute userPrincipalUid = getAttribute( + getGroupMembershipAttribute(), answer); + List attrs = getAttributes(userPrincipalUid); + Iterator it = attrs.iterator(); + while (it.hasNext()) + { + String uidfull = (String) it.next(); + if (!StringUtils.isEmpty(uidfull)) + { + if (uidfull.toLowerCase().indexOf( + getUserFilterBase().toLowerCase()) != -1) + { + String uid = extractLdapAttr(uidfull, + getUserIdAttribute()); + if (uid != null) + { + newAttrs.add(uid); + } + } + } + } + userPrincipalUids.addAll(newAttrs); + } + return (String[]) userPrincipalUids + .toArray(new String[userPrincipalUids.size()]); + } - cons.setSearchScope(getSearchScope()); - NamingEnumeration results = ((DirContext) ctx).search(getRoleFilterBase(),query , cons); - - while (results.hasMore()) - { - SearchResult result = (SearchResult) results.next(); - Attributes answer = result.getAttributes(); - - Attribute userPrincipalUid = getAttribute(getRoleMembershipAttribute(), answer); - List attrs = getAttributes(userPrincipalUid); - Iterator it = attrs.iterator(); - while(it.hasNext()) { - String uidfull = (String)it.next(); - if (!StringUtils.isEmpty(uidfull)) { - String uid = extractLdapAttr(uidfull,getUserIdAttribute()); - if (uid!=null){ - userPrincipalUids.add(uid); - } - } - } - } - return (String[]) userPrincipalUids.toArray(new String[userPrincipalUids.size()]); - } + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchUsersFromGroupByUser(java.lang.String, + * javax.naming.directory.SearchControls) + */ + public String[] searchUsersFromGroupByUser(final String groupPrincipalUid, + SearchControls cons) throws NamingException + { - /* (non-Javadoc) - * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchUsersFromRoleByUser(java.lang.String, javax.naming.directory.SearchControls) - */ - public String[] searchUsersFromRoleByUser(final String rolePrincipalUid, SearchControls cons) - throws NamingException - { + String query = "(&(" + getUserGroupMembershipAttribute() + "=" + + getGroupDN(groupPrincipalUid) + ")" + getUserFilter() + ")"; + if (logger.isDebugEnabled()) + { + logger.debug("query[" + query + "]"); + } + + cons.setSearchScope(getSearchScope()); + NamingEnumeration results = ((DirContext) ctx).search( + getUserFilterBase(), query, cons); + + ArrayList userPrincipalUids = new ArrayList(); + + while (results.hasMore()) + { + SearchResult result = (SearchResult) results.next(); + Attributes answer = result.getAttributes(); + userPrincipalUids.addAll(getAttributes(getAttribute( + getUserIdAttribute(), answer))); + } + return (String[]) userPrincipalUids + .toArray(new String[userPrincipalUids.size()]); + } + + public String[] searchRolesFromGroupByGroup(final String groupPrincipalUid, + SearchControls cons) throws NamingException + { + + String query = "(&(" + getGroupIdAttribute() + "=" + + (groupPrincipalUid) + ")" + getGroupFilter() + ")"; + + if (logger.isDebugEnabled()) + { + logger.debug("query[" + query + "]"); + } + + ArrayList rolePrincipalUids = new ArrayList(); + + cons.setSearchScope(getSearchScope()); + NamingEnumeration groups = ((DirContext) ctx).search( + getGroupFilterBase(), query, cons); + + while (groups.hasMore()) + { + SearchResult group = (SearchResult) groups.next(); + Attributes groupAttributes = group.getAttributes(); + + Attribute rolesFromGroup = getAttribute( + getGroupMembershipForRoleAttribute(), groupAttributes); + List roleDNs = getAttributes(rolesFromGroup, getRoleFilterBase()); + Iterator it = roleDNs.iterator(); + while (it.hasNext()) + { + String roleDN = (String) it.next(); + if (!StringUtils.isEmpty(roleDN)) + { + String roleId = extractLdapAttr(roleDN, + getRoleUidAttribute()); + if (roleId != null) + { + NamingEnumeration rolesResults = searchRoleByWildcardedUid( + roleId, cons); + if (rolesResults.hasMore()) + if (rolesResults.nextElement() != null) + rolePrincipalUids.add(roleId); + } + } + } + } + return (String[]) rolePrincipalUids + .toArray(new String[rolePrincipalUids.size()]); + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchUsersFromGroupByUser(java.lang.String, + * javax.naming.directory.SearchControls) + */ + public String[] searchRolesFromGroupByRole(final String groupPrincipalUid, + SearchControls cons) throws NamingException + { + + String query = "(&(" + getRoleGroupMembershipForRoleAttribute() + "=" + + getGroupDN(groupPrincipalUid) + ")" + getRoleFilter() + ")"; + + if (logger.isDebugEnabled()) + { + logger.debug("query[" + query + "]"); + } + + cons.setSearchScope(getSearchScope()); + NamingEnumeration results = ((DirContext) ctx).search( + getRoleFilterBase(), query, cons); + + ArrayList rolePrincipalUids = new ArrayList(); + + while (results.hasMore()) + { + SearchResult result = (SearchResult) results.next(); + Attributes answer = result.getAttributes(); + rolePrincipalUids.addAll(getAttributes(getAttribute( + getRoleIdAttribute(), answer))); + } + return (String[]) rolePrincipalUids + .toArray(new String[rolePrincipalUids.size()]); + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchUsersFromRoleByRole(java.lang.String, + * javax.naming.directory.SearchControls) + */ + public String[] searchUsersFromRoleByRole(final String rolePrincipalUid, + SearchControls cons) throws NamingException + { + + String query = "(&(" + getRoleIdAttribute() + "=" + (rolePrincipalUid) + + ")" + getRoleFilter() + ")"; + + if (logger.isDebugEnabled()) + { + logger.debug("query[" + query + "]"); + } + + ArrayList userPrincipalUids = new ArrayList(); + + cons.setSearchScope(getSearchScope()); + NamingEnumeration results = ((DirContext) ctx).search( + getRoleFilterBase(), query, cons); + + while (results.hasMore()) + { + SearchResult result = (SearchResult) results.next(); + Attributes answer = result.getAttributes(); + + Attribute userPrincipalUid = getAttribute( + getRoleMembershipAttribute(), answer); + List attrs = getAttributes(userPrincipalUid); + Iterator it = attrs.iterator(); + while (it.hasNext()) + { + String uidfull = (String) it.next(); + if (!StringUtils.isEmpty(uidfull)) + { + String uid = extractLdapAttr(uidfull, getUserIdAttribute()); + if (uid != null) + { + userPrincipalUids.add(uid); + } + } + } + } + return (String[]) userPrincipalUids + .toArray(new String[userPrincipalUids.size()]); + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.security.spi.impl.ldap.LdapMembershipDao#searchUsersFromRoleByUser(java.lang.String, + * javax.naming.directory.SearchControls) + */ + public String[] searchUsersFromRoleByUser(final String rolePrincipalUid, + SearchControls cons) throws NamingException + { String roleMemberAttr = getUserRoleMembershipAttribute(); /* - * search for those users with a role membership attribute matching two possible values: - * - the role principal UID (e.g. 'admin') or - * - the full DN of the role (e.g. 'cn=admin,ou=Roles,o=sevenSeas') - */ - StringBuffer byRolePrincipalUidMatch = new StringBuffer("(").append(roleMemberAttr).append("=").append(rolePrincipalUid).append(")"); - StringBuffer byRoleDNMatch = new StringBuffer("(").append(roleMemberAttr).append("=").append(getRoleDN(rolePrincipalUid, true)).append(")"); - - StringBuffer completeRoleAttrMatch = new StringBuffer("(|").append(byRolePrincipalUidMatch).append(byRoleDNMatch).append(")"); - StringBuffer query= new StringBuffer("(&").append(completeRoleAttrMatch).append("(").append(getUserFilter()).append("))"); - - if (logger.isDebugEnabled()) - { - logger.debug("query[" + query + "]"); - } - - cons.setSearchScope(getSearchScope()); - NamingEnumeration results = ((DirContext) ctx).search(getUserFilterBase(),query.toString() , cons); + * search for those users with a role membership attribute matching two + * possible values: - the role principal UID (e.g. 'admin') or - the + * full DN of the role (e.g. 'cn=admin,ou=Roles,o=sevenSeas') + */ + StringBuffer byRolePrincipalUidMatch = new StringBuffer("(").append( + roleMemberAttr).append("=").append(rolePrincipalUid) + .append(")"); + StringBuffer byRoleDNMatch = new StringBuffer("(").append( + roleMemberAttr).append("=").append( + getRoleDN(rolePrincipalUid, true)).append(")"); - ArrayList userPrincipalUids = new ArrayList(); - - while (results.hasMore()) - { - SearchResult result = (SearchResult) results.next(); - Attributes answer = result.getAttributes(); - userPrincipalUids.addAll(getAttributes(getAttribute(getUserIdAttribute(), answer))); - } - return (String[]) userPrincipalUids.toArray(new String[userPrincipalUids.size()]); - } + StringBuffer completeRoleAttrMatch = new StringBuffer("(|").append( + byRolePrincipalUidMatch).append(byRoleDNMatch).append(")"); + StringBuffer query = new StringBuffer("(&").append( + completeRoleAttrMatch).append("(").append(getUserFilter()) + .append("))"); + if (logger.isDebugEnabled()) + { + logger.debug("query[" + query + "]"); + } + + cons.setSearchScope(getSearchScope()); + NamingEnumeration results = ((DirContext) ctx).search( + getUserFilterBase(), query.toString(), cons); + + ArrayList userPrincipalUids = new ArrayList(); + + while (results.hasMore()) + { + SearchResult result = (SearchResult) results.next(); + Attributes answer = result.getAttributes(); + userPrincipalUids.addAll(getAttributes(getAttribute( + getUserIdAttribute(), answer))); + } + return (String[]) userPrincipalUids + .toArray(new String[userPrincipalUids.size()]); + } + /** * @param attr * @return @@ -389,14 +493,16 @@ */ protected List getAttributes(Attribute attr) throws NamingException { - return getAttributes(attr, null); + return getAttributes(attr, null); } + /** * @param attr * @return * @throws NamingException */ - protected List getAttributes(Attribute attr,String filter) throws NamingException + protected List getAttributes(Attribute attr, String filter) + throws NamingException { List uids = new ArrayList(); if (attr != null) @@ -404,57 +510,62 @@ Enumeration groupUidEnum = attr.getAll(); while (groupUidEnum.hasMoreElements()) { - String groupDN = (String)groupUidEnum.nextElement(); - if (filter==null) { - uids.add(groupDN); - } else if (filter!=null && groupDN.toLowerCase().indexOf(filter.toLowerCase())!=-1) { - uids.add(groupDN); - } + String groupDN = (String) groupUidEnum.nextElement(); + if (filter == null) + { + uids.add(groupDN); + } + else if (filter != null + && groupDN.toLowerCase().indexOf(filter.toLowerCase()) != -1) + { + uids.add(groupDN); + } } } return uids; - } + } /** * @param results * @return * @throws NamingException */ - private Attributes getFirstUser(NamingEnumeration results) throws NamingException + private Attributes getFirstUser(NamingEnumeration results) + throws NamingException { SearchResult result = (SearchResult) results.next(); Attributes answer = result.getAttributes(); return answer; } - + /** + * <p> + * A template method for defining the attributes for a particular LDAP + * class. + * </p> + * + * @param principalUid + * The principal uid. + * @return the LDAP attributes object for the particular class. + */ + protected Attributes defineLdapAttributes(final String principalUid) + { + Attributes attrs = new BasicAttributes(true); + BasicAttribute classes = new BasicAttribute("objectclass"); - /** - * <p> - * A template method for defining the attributes for a particular LDAP class. - * </p> - * - * @param principalUid The principal uid. - * @return the LDAP attributes object for the particular class. - */ - protected Attributes defineLdapAttributes(final String principalUid) - { - Attributes attrs = new BasicAttributes(true); - BasicAttribute classes = new BasicAttribute("objectclass"); - - classes.add("top"); - classes.add("person"); - classes.add("organizationalPerson"); - classes.add("inetorgperson"); - attrs.put(classes); - attrs.put("cn", principalUid); - attrs.put("sn", principalUid); - - return attrs; - } + classes.add("top"); + classes.add("person"); + classes.add("organizationalPerson"); + classes.add("inetorgperson"); + attrs.put(classes); + attrs.put("cn", principalUid); + attrs.put("sn", principalUid); - /** + return attrs; + } + + /** * @see org.apache.jetspeed.security.spi.impl.ldap.LdapPrincipalDaoImpl#getDnSuffix() */ protected String getDnSuffix() @@ -462,50 +573,59 @@ return this.getUserFilterBase(); } - /** - * <p> - * Creates a GroupPrincipal object. - * </p> - * - * @param principalUid The principal uid. - * @return A group principal object. - */ - protected Principal makePrincipal(String principalUid) - { - return new UserPrincipalImpl(principalUid); - } - - private String extractLdapAttr(String dn,String ldapAttrName) { + /** + * <p> + * Creates a GroupPrincipal object. + * </p> + * + * @param principalUid + * The principal uid. + * @return A group principal object. + */ + protected Principal makePrincipal(String principalUid) + { + return new UserPrincipalImpl(principalUid); + } - String dnLowerCase = dn.toLowerCase(); - String ldapAttrNameLowerCase = ldapAttrName.toLowerCase(); - - if (dnLowerCase.indexOf(ldapAttrNameLowerCase + "=")==-1) - return null; - - if (dn.indexOf(",")!=-1 && dnLowerCase.indexOf(ldapAttrNameLowerCase + "=")!=-1) - return dn.substring(dnLowerCase.indexOf(ldapAttrNameLowerCase)+ldapAttrName.length()+1,dn.indexOf(",")); - return dn.substring(dnLowerCase.indexOf(ldapAttrNameLowerCase)+ldapAttrName.length()+1,dn.length()); - } + private String extractLdapAttr(String dn, String ldapAttrName) + { - protected String[] getObjectClasses() { - return this.getUserObjectClasses(); - } - - protected String getUidAttributeForPrincipal() { - return this.getUserUidAttribute(); - } + String dnLowerCase = dn.toLowerCase(); + String ldapAttrNameLowerCase = ldapAttrName.toLowerCase(); - protected String[] getAttributes() { - return getUserAttributes(); - } + if (dnLowerCase.indexOf(ldapAttrNameLowerCase + "=") == -1) + return null; - protected String getEntryPrefix() + if (dn.indexOf(",") != -1 + && dnLowerCase.indexOf(ldapAttrNameLowerCase + "=") != -1) + return dn.substring(dnLowerCase.indexOf(ldapAttrNameLowerCase) + + ldapAttrName.length() + 1, dn.indexOf(",")); + return dn.substring(dnLowerCase.indexOf(ldapAttrNameLowerCase) + + ldapAttrName.length() + 1, dn.length()); + } + + protected String[] getObjectClasses() { + return this.getUserObjectClasses(); + } + + protected String getUidAttributeForPrincipal() + { + return this.getUserUidAttribute(); + } + + protected String[] getAttributes() + { + return getUserAttributes(); + } + + protected String getEntryPrefix() + { return this.getUidAttribute(); - } + } - protected String getSearchSuffix() { - return this.getUserFilter(); - } + protected String getSearchSuffix() + { + return this.getUserFilter(); + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapMembershipDao.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapMembershipDao.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapMembershipDao.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,102 +1,109 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi.impl.ldap; import javax.naming.NamingException; import javax.naming.directory.SearchControls; -public interface LdapMembershipDao { +public interface LdapMembershipDao +{ - public abstract String[] searchGroupMemberShipByGroup( - final String userPrincipalUid, SearchControls cons) - throws NamingException; + public abstract String[] searchGroupMemberShipByGroup( + final String userPrincipalUid, SearchControls cons) + throws NamingException; - public abstract String[] searchGroupMemberShipByUser( - final String userPrincipalUid, SearchControls cons) - throws NamingException; + public abstract String[] searchGroupMemberShipByUser( + final String userPrincipalUid, SearchControls cons) + throws NamingException; - public abstract String[] searchRoleMemberShipByRole( - final String userPrincipalUid, SearchControls cons) - throws NamingException; + public abstract String[] searchRoleMemberShipByRole( + final String userPrincipalUid, SearchControls cons) + throws NamingException; - public abstract String[] searchRoleMemberShipByUser( - final String userPrincipalUid, SearchControls cons) - throws NamingException; + public abstract String[] searchRoleMemberShipByUser( + final String userPrincipalUid, SearchControls cons) + throws NamingException; - /** - * <p> - * Search user by group using the GroupMembershipAttribute. - * </p> - * - * @param groupPrincipalUid - * @param cons - * @return - * @throws NamingException A {@link NamingException}. - */ - public abstract String[] searchUsersFromGroupByGroup( - final String groupPrincipalUid, SearchControls cons) - throws NamingException; + /** + * <p> + * Search user by group using the GroupMembershipAttribute. + * </p> + * + * @param groupPrincipalUid + * @param cons + * @return + * @throws NamingException + * A {@link NamingException}. + */ + public abstract String[] searchUsersFromGroupByGroup( + final String groupPrincipalUid, SearchControls cons) + throws NamingException; - /** - * <p> - * Search user by group using the UserGroupMembershipAttribute. - * </p> - * - * @param groupPrincipalUid - * @param cons - * @return - * @throws NamingException A {@link NamingException}. - */ - public abstract String[] searchUsersFromGroupByUser( - final String groupPrincipalUid, SearchControls cons) - throws NamingException; + /** + * <p> + * Search user by group using the UserGroupMembershipAttribute. + * </p> + * + * @param groupPrincipalUid + * @param cons + * @return + * @throws NamingException + * A {@link NamingException}. + */ + public abstract String[] searchUsersFromGroupByUser( + final String groupPrincipalUid, SearchControls cons) + throws NamingException; - /** - * <p> - * Search user by role using the RoleMembershipAttribute. - * </p> - * - * @param groupPrincipalUid - * @param cons - * @return - * @throws NamingException A {@link NamingException}. - */ - public abstract String[] searchUsersFromRoleByRole( - final String rolePrincipalUid, SearchControls cons) - throws NamingException; + /** + * <p> + * Search user by role using the RoleMembershipAttribute. + * </p> + * + * @param groupPrincipalUid + * @param cons + * @return + * @throws NamingException + * A {@link NamingException}. + */ + public abstract String[] searchUsersFromRoleByRole( + final String rolePrincipalUid, SearchControls cons) + throws NamingException; - /** - * <p> - * Search user by role using the UserRoleMembershipAttribute. - * </p> - * - * @param groupPrincipalUid - * @param cons - * @return - * @throws NamingException A {@link NamingException}. - */ - public abstract String[] searchUsersFromRoleByUser( - final String groupPrincipalUid, SearchControls cons) - throws NamingException; - - public abstract String[] searchRolesFromGroupByGroup(final String groupPrincipalUid, - SearchControls cons) throws NamingException; + /** + * <p> + * Search user by role using the UserRoleMembershipAttribute. + * </p> + * + * @param groupPrincipalUid + * @param cons + * @return + * @throws NamingException + * A {@link NamingException}. + */ + public abstract String[] searchUsersFromRoleByUser( + final String groupPrincipalUid, SearchControls cons) + throws NamingException; - public abstract String[] searchRolesFromGroupByRole(final String groupPrincipalUid, - SearchControls cons) throws NamingException; + public abstract String[] searchRolesFromGroupByGroup( + final String groupPrincipalUid, SearchControls cons) + throws NamingException; + public abstract String[] searchRolesFromGroupByRole( + final String groupPrincipalUid, SearchControls cons) + throws NamingException; + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapPrincipalDao.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapPrincipalDao.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapPrincipalDao.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,13 +30,16 @@ */ public interface LdapPrincipalDao extends LdapReadOnlyPrincipalDao { + /** * <p> * Makes a new ldap entry for the specified principal. * </p> * - * @param principalUid The principal uid. - * @throws SecurityException Throws a {@link SecurityException}. + * @param principalUid + * The principal uid. + * @throws SecurityException + * Throws a {@link SecurityException}. */ abstract void create(final String principalUid) throws SecurityException; @@ -45,8 +48,10 @@ * Deletes a ldap entry for the specified principal. * </p> * - * @param principalUid The principal uid. - * @throws SecurityException Throws a {@link SecurityException}. + * @param principalUid + * The principal uid. + * @throws SecurityException + * Throws a {@link SecurityException}. */ abstract void delete(final String principalUid) throws SecurityException; @@ -55,18 +60,22 @@ * Search the ldap directory for the principal. * </p> * - * @param principalUid The uid value of the principal. - * @param principalType The type of principal. + * @param principalUid + * The uid value of the principal. + * @param principalType + * The type of principal. * @return All the objects of this LDAP class type. */ - Principal[] find(final String principalUid, String principalType) throws SecurityException; + Principal[] find(final String principalUid, String principalType) + throws SecurityException; /** * <p> * Converts the uid to an ldap acceptable name. * </p> * - * @param uid The uid. + * @param uid + * The uid. * @return The converted name. */ String convertUidToLdapAcceptableName(String uid); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapPrincipalDaoImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapPrincipalDaoImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapPrincipalDaoImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -43,18 +43,21 @@ * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long </a>, <a * href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ -public abstract class LdapPrincipalDaoImpl extends AbstractLdapDao implements LdapPrincipalDao +public abstract class LdapPrincipalDaoImpl extends AbstractLdapDao implements + LdapPrincipalDao { + /** The logger. */ - private static final Log logger = LogFactory.getLog(LdapPrincipalDaoImpl.class); + private static final Log logger = LogFactory + .getLog(LdapPrincipalDaoImpl.class); - /** * <p> * Default constructor. * </p> * - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ public LdapPrincipalDaoImpl() throws SecurityException { @@ -66,10 +69,13 @@ * Initializes the dao. * </p> * - * @param ldapConfig Holds the ldap binding configuration. - * @throws SecurityException A {@link SecurityException}. + * @param ldapConfig + * Holds the ldap binding configuration. + * @throws SecurityException + * A {@link SecurityException}. */ - public LdapPrincipalDaoImpl(LdapBindingConfig ldapConfig) throws SecurityException + public LdapPrincipalDaoImpl(LdapBindingConfig ldapConfig) + throws SecurityException { super(ldapConfig); } @@ -79,17 +85,20 @@ * A template method for creating a concrete principal object. * </p> * - * @param principalUid The principal uid. + * @param principalUid + * The principal uid. * @return A concrete principal object. */ protected abstract Principal makePrincipal(String principalUid); /** * <p> - * A template method for defining the attributes for a particular LDAP class. + * A template method for defining the attributes for a particular LDAP + * class. * </p> * - * @param principalUid The principal uid. + * @param principalUid + * The principal uid. * @return The LDAP attributes object for the particular class. */ protected abstract Attributes defineLdapAttributes(final String principalUid); @@ -103,12 +112,12 @@ logger.debug("creating principal with " + attrs); try { - String userDn = getEntryPrefix() + "=" + principalUid; - if (!StringUtils.isEmpty(getDnSuffix())) - userDn+="," + getDnSuffix(); + String userDn = getEntryPrefix() + "=" + principalUid; + if (!StringUtils.isEmpty(getDnSuffix())) + userDn += "," + getDnSuffix(); logger.debug("userDn = " + userDn); - + ctx.createSubcontext(userDn, attrs); if (logger.isDebugEnabled()) { @@ -139,7 +148,6 @@ */ protected abstract String getUidAttributeForPrincipal(); - /** * @see org.apache.jetspeed.security.spi.impl.ldap.LdapPrincipalDao#delete(java.lang.String) */ @@ -147,17 +155,14 @@ { String dn = lookupByUid(principalUid); - if (dn == null) - { - return; - } + if (dn == null) { return; } String rdn; try { rdn = getSubcontextName(dn); - //if(!StringUtils.isEmpty(getSearchDomain())) - // rdn+="," + getSearchDomain(); + // if(!StringUtils.isEmpty(getSearchDomain())) + // rdn+="," + getSearchDomain(); ctx.destroySubcontext(rdn); } catch (NamingException e) @@ -182,16 +187,19 @@ } else if (fullPath.indexOf(UserPrincipal.PREFS_USER_ROOT) >= 0) { - ldapAcceptableName = convertUidWithoutSlashes(UserPrincipalImpl.getPrincipalNameFromFullPath(fullPath)); + ldapAcceptableName = convertUidWithoutSlashes(UserPrincipalImpl + .getPrincipalNameFromFullPath(fullPath)); } else if (fullPath.indexOf(GroupPrincipal.PREFS_GROUP_ROOT) >= 0) { - ldapAcceptableName = convertUidWithoutSlashes(GroupPrincipalImpl.getPrincipalNameFromFullPath(fullPath)); + ldapAcceptableName = convertUidWithoutSlashes(GroupPrincipalImpl + .getPrincipalNameFromFullPath(fullPath)); } else if (fullPath.indexOf(GroupPrincipal.PREFS_ROLE_ROOT) >= 0) { - ldapAcceptableName = convertUidWithoutSlashes(RolePrincipalImpl.getPrincipalNameFromFullPath(fullPath)); - } + ldapAcceptableName = convertUidWithoutSlashes(RolePrincipalImpl + .getPrincipalNameFromFullPath(fullPath)); + } if (logger.isErrorEnabled()) { logger.debug("Ldap acceptable name:" + ldapAcceptableName); @@ -205,7 +213,8 @@ * Returns a well formed uid for LDAP. * </p> * - * @param uid The uid. + * @param uid + * The uid. * @return The well formed uid. */ private String convertUidWithoutSlashes(String uid) @@ -218,12 +227,14 @@ * @see org.apache.jetspeed.security.spi.impl.ldap.LdapPrincipalDao#find(java.lang.String, * java.lang.String) */ - public Principal[] find(final String principalUid, String principalType) throws SecurityException + public Principal[] find(final String principalUid, String principalType) + throws SecurityException { try { SearchControls cons = setSearchControls(); - NamingEnumeration searchResults = searchByWildcardedUid(convertUidToLdapAcceptableName(principalUid), cons); + NamingEnumeration searchResults = searchByWildcardedUid( + convertUidToLdapAcceptableName(principalUid), cons); Collection principals = new ArrayList(); enumerateOverSearchResults(searchResults, principals); @@ -241,12 +252,14 @@ * Converts a list of principals to an array of principals. * </p> * - * @param principals The list of principals. + * @param principals + * The list of principals. * @return The array of principals. */ private Principal[] convertPrincipalListToArray(Collection principals) { - return (Principal[]) principals.toArray(new Principal[principals.size()]); + return (Principal[]) principals + .toArray(new Principal[principals.size()]); } /** @@ -254,12 +267,15 @@ * Build the user principal by enumerating through the search results. * </p> * - * @param searchResults The {@link NamingEnumeration} of results. - * @param principals The collection of user principals. - * @throws NamingException Throws a {@link NamingException}. + * @param searchResults + * The {@link NamingEnumeration} of results. + * @param principals + * The collection of user principals. + * @throws NamingException + * Throws a {@link NamingException}. */ - private void enumerateOverSearchResults(NamingEnumeration searchResults, Collection principals) - throws NamingException + private void enumerateOverSearchResults(NamingEnumeration searchResults, + Collection principals) throws NamingException { while (searchResults.hasMore()) { @@ -269,101 +285,118 @@ } /** - * @param principals The collection of principals. - * @param searchResult The {@link SearchResult} - * @throws NamingException Throws a {@link NamingException}. + * @param principals + * The collection of principals. + * @param searchResult + * The {@link SearchResult} + * @throws NamingException + * Throws a {@link NamingException}. */ - private void buildPrincipal(Collection principals, SearchResult searchResult) throws NamingException + private void buildPrincipal(Collection principals, SearchResult searchResult) + throws NamingException { if (searchResult.getObject() instanceof DirContext) { Attributes atts = searchResult.getAttributes(); - String uid = (String) getAttribute(getUidAttributeForPrincipal(), atts).getAll().next(); + String uid = (String) getAttribute(getUidAttributeForPrincipal(), + atts).getAll().next(); Principal principal = makePrincipal(uid); principals.add(principal); - + } } /** - * @param attributeName The attribute name. - * @param userAttributes The user {@link Attributes}. + * @param attributeName + * The attribute name. + * @param userAttributes + * The user {@link Attributes}. * @return The {@link Attribute}. - * @throws NamingException Throws a {@link NamingException}. + * @throws NamingException + * Throws a {@link NamingException}. */ - protected Attribute getAttribute(String attributeName, Attributes userAttributes) throws NamingException + protected Attribute getAttribute(String attributeName, + Attributes userAttributes) throws NamingException { for (NamingEnumeration ae = userAttributes.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); - if (attr.getID().equalsIgnoreCase(attributeName)) - { - return attr; - } + if (attr.getID().equalsIgnoreCase(attributeName)) { return attr; } } return null; } - - protected String getSearchDomain() { - return this.getUserFilterBase(); - } - protected String[] parseAttr(String attr, String replace) { + protected String getSearchDomain() + { + return this.getUserFilterBase(); + } + + protected String[] parseAttr(String attr, String replace) + { attr = StringUtils.replace(attr, "{u}", replace); int index = attr.indexOf('='); - - if (index != -1){ - return new String[]{ - attr.substring(0,index), - index < attr.length() -1 ? attr.substring(index + 1) : null}; - } else { - return new String[]{ attr, null }; + + if (index != -1) + { + return new String[] + { + attr.substring(0, index), + index < attr.length() - 1 ? attr.substring(index + 1) + : null}; } - } + else + { + return new String[] + {attr, null}; + } + } - protected String getGroupDN(String groupPrincipalUid) { - return getGroupDN(groupPrincipalUid,true); - } + protected String getGroupDN(String groupPrincipalUid) + { + return getGroupDN(groupPrincipalUid, true); + } - protected String getGroupDN(String groupPrincipalUid, boolean includeBaseDN) { - String groupDN = getGroupIdAttribute() + "=" + groupPrincipalUid; - if (!StringUtils.isEmpty(getGroupFilterBase())) - groupDN += "," + getGroupFilterBase(); - if (includeBaseDN && !StringUtils.isEmpty(getRootContext())) - groupDN += "," + getRootContext(); - return groupDN; - } + protected String getGroupDN(String groupPrincipalUid, boolean includeBaseDN) + { + String groupDN = getGroupIdAttribute() + "=" + groupPrincipalUid; + if (!StringUtils.isEmpty(getGroupFilterBase())) + groupDN += "," + getGroupFilterBase(); + if (includeBaseDN && !StringUtils.isEmpty(getRootContext())) + groupDN += "," + getRootContext(); + return groupDN; + } - protected String getRoleDN(String rolePrincipalUid) { - return getRoleDN(rolePrincipalUid,true); - } - - protected String getRoleDN(String rolePrincipalUid, boolean includeBaseDN) { - String roleDN = getRoleIdAttribute() + "=" + rolePrincipalUid; - if (!StringUtils.isEmpty(getRoleFilterBase())) - roleDN+="," + getRoleFilterBase(); - if (includeBaseDN && !StringUtils.isEmpty(getRootContext())) - roleDN+="," + getRootContext(); - return roleDN; - } + protected String getRoleDN(String rolePrincipalUid) + { + return getRoleDN(rolePrincipalUid, true); + } - protected String getUserDN(String userPrincipalUid) { - return getUserDN(userPrincipalUid,true); - } - - protected String getUserDN(String userPrincipalUid, boolean includeBaseDN) { - String userDN = getUserIdAttribute() + "=" + userPrincipalUid; - if (!StringUtils.isEmpty(getUserFilterBase())) - userDN += "," + getUserFilterBase(); - if (includeBaseDN && !StringUtils.isEmpty(getRootContext())) - userDN += "," + getRootContext(); - return userDN; - } + protected String getRoleDN(String rolePrincipalUid, boolean includeBaseDN) + { + String roleDN = getRoleIdAttribute() + "=" + rolePrincipalUid; + if (!StringUtils.isEmpty(getRoleFilterBase())) + roleDN += "," + getRoleFilterBase(); + if (includeBaseDN && !StringUtils.isEmpty(getRootContext())) + roleDN += "," + getRootContext(); + return roleDN; + } + protected String getUserDN(String userPrincipalUid) + { + return getUserDN(userPrincipalUid, true); + } + protected String getUserDN(String userPrincipalUid, boolean includeBaseDN) + { + String userDN = getUserIdAttribute() + "=" + userPrincipalUid; + if (!StringUtils.isEmpty(getUserFilterBase())) + userDN += "," + getUserFilterBase(); + if (includeBaseDN && !StringUtils.isEmpty(getRootContext())) + userDN += "," + getRootContext(); + return userDN; + } - } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapReadOnlyPrincipalDao.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapReadOnlyPrincipalDao.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapReadOnlyPrincipalDao.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,6 +27,7 @@ */ public interface LdapReadOnlyPrincipalDao { + /** * <p> * Searches the LDAP server for the user with the specified principal id @@ -34,7 +35,8 @@ * </p> * * @return The principal's uid value - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ String lookupByUid(final String principalUid) throws SecurityException; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapRoleDaoImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapRoleDaoImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapRoleDaoImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -41,7 +41,8 @@ * Default constructor. * </p> * - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ public LdapRoleDaoImpl() throws SecurityException { @@ -53,20 +54,25 @@ * Initializes the dao. * </p> * - * @param ldapConfig Holds the ldap binding configuration. - * @throws SecurityException A {@link SecurityException}. + * @param ldapConfig + * Holds the ldap binding configuration. + * @throws SecurityException + * A {@link SecurityException}. */ - public LdapRoleDaoImpl(LdapBindingConfig ldapConfig) throws SecurityException + public LdapRoleDaoImpl(LdapBindingConfig ldapConfig) + throws SecurityException { super(ldapConfig); } /** * <p> - * A template method for defining the attributes for a particular LDAP class. + * A template method for defining the attributes for a particular LDAP + * class. * </p> * - * @param principalUid The principal uid. + * @param principalUid + * The principal uid. * @return The LDAP attributes object for the particular class. */ protected Attributes defineLdapAttributes(final String principalUid) @@ -74,26 +80,27 @@ Attributes attrs = new BasicAttributes(true); BasicAttribute classes = new BasicAttribute("objectclass"); - for (int i=0;i<getObjectClasses().length;i++) - classes.add(getObjectClasses()[i]); + for (int i = 0; i < getObjectClasses().length; i++) + classes.add(getObjectClasses()[i]); attrs.put(classes); attrs.put(getEntryPrefix(), principalUid); - if(!StringUtils.isEmpty(getRoleObjectRequiredAttributeClasses())) + if (!StringUtils.isEmpty(getRoleObjectRequiredAttributeClasses())) { - String key = getRoleObjectRequiredAttributeClasses(); - if ( key.indexOf(',') >= 0 ) - { - String[] allKeys = key.split(","); - for (int i=0; i<allKeys.length; i++) - attrs.put( allKeys[i], "" ); - } - else - { - attrs.put(getRoleObjectRequiredAttributeClasses(), ""); - } + String key = getRoleObjectRequiredAttributeClasses(); + if (key.indexOf(',') >= 0) + { + String[] allKeys = key.split(","); + for (int i = 0; i < allKeys.length; i++) + attrs.put(allKeys[i], ""); + } + else + { + attrs.put(getRoleObjectRequiredAttributeClasses(), ""); + } } - for (int i=0;i<getAttributes().length;i++) - attrs.put(parseAttr(getAttributes()[i],principalUid)[0], parseAttr(getAttributes()[i],principalUid)[1]); + for (int i = 0; i < getAttributes().length; i++) + attrs.put(parseAttr(getAttributes()[i], principalUid)[0], + parseAttr(getAttributes()[i], principalUid)[1]); return attrs; } @@ -110,7 +117,8 @@ * Creates a GroupPrincipal object. * </p> * - * @param principalUid The principal uid. + * @param principalUid + * The principal uid. * @return A group principal object. */ protected Principal makePrincipal(String principalUid) @@ -118,30 +126,34 @@ return new RolePrincipalImpl(principalUid); } - protected String getEntryPrefix() { - return this.getRoleIdAttribute(); - } - - protected String getSearchSuffix() { - return this.getRoleFilter(); - } + protected String getEntryPrefix() + { + return this.getRoleIdAttribute(); + } - protected String getSearchDomain() { - return this.getRoleFilterBase(); - } + protected String getSearchSuffix() + { + return this.getRoleFilter(); + } - protected String[] getObjectClasses() { - return this.getRoleObjectClasses(); - } + protected String getSearchDomain() + { + return this.getRoleFilterBase(); + } - protected String getUidAttributeForPrincipal() { - return this.getRoleUidAttribute(); - } + protected String[] getObjectClasses() + { + return this.getRoleObjectClasses(); + } - protected String[] getAttributes() { - return getRoleAttributes(); - } - - + protected String getUidAttributeForPrincipal() + { + return this.getRoleUidAttribute(); + } + + protected String[] getAttributes() + { + return getRoleAttributes(); + } + } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserCredentialDao.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserCredentialDao.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserCredentialDao.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,16 +27,21 @@ */ public interface LdapUserCredentialDao extends LdapReadOnlyPrincipalDao { + /** * <p> * Updates the password for the specified user. * </p> * - * @param uid The uid. - * @param password The password. - * @throws SecurityException A {@link SecurityException}. + * @param uid + * The uid. + * @param password + * The password. + * @throws SecurityException + * A {@link SecurityException}. */ - abstract void changePassword(final String uid, final String password) throws SecurityException; + abstract void changePassword(final String uid, final String password) + throws SecurityException; /** * <p> @@ -46,16 +51,22 @@ * OperationNotSupportedException if the password is empty. * </p> * - * @param uid The uid. - * @param password The password. - * @throws SecurityException A {@link SecurityException}. + * @param uid + * The uid. + * @param password + * The password. + * @throws SecurityException + * A {@link SecurityException}. */ - abstract boolean authenticate(final String uid, final String password) throws SecurityException; + abstract boolean authenticate(final String uid, final String password) + throws SecurityException; /** - * @param uid The uid. + * @param uid + * The uid. * @return The password. - *@throws SecurityException A {@link SecurityException}. ¡÷ throws SecurityException + * @throws SecurityException + * A {@link SecurityException}. ¡÷ throws SecurityException */ abstract char[] getPassword(final String uid) throws SecurityException; } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserCredentialDaoImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserCredentialDaoImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserCredentialDaoImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -38,47 +38,56 @@ /** * @see org.apache.jetspeed.security.spi.impl.ldap.LdapUserCredentialDao - * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long </a>, <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> + * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long </a>, <a + * href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ -public class LdapUserCredentialDaoImpl extends AbstractLdapDao implements LdapUserCredentialDao +public class LdapUserCredentialDaoImpl extends AbstractLdapDao implements + LdapUserCredentialDao { + /** The logger. */ - private static final Log logger = LogFactory.getLog(LdapUserCredentialDaoImpl.class); + private static final Log logger = LogFactory + .getLog(LdapUserCredentialDaoImpl.class); - /** The password attribute. */ - + /** The password attribute. */ + /** * <p> * Default constructor. * </p> - * - * @throws SecurityException A {@link SecurityException}. + * + * @throws SecurityException + * A {@link SecurityException}. */ public LdapUserCredentialDaoImpl() throws SecurityException { super(); } - + /** * <p> * Initializes the dao. * </p> * - * @param ldapConfig Holds the ldap binding configuration. + * @param ldapConfig + * Holds the ldap binding configuration. * - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ - public LdapUserCredentialDaoImpl(LdapBindingConfig ldapConfig) throws SecurityException + public LdapUserCredentialDaoImpl(LdapBindingConfig ldapConfig) + throws SecurityException { super(ldapConfig); - } - + } + /** * <p> * Updates the password for the specified user. * </p> */ - public void changePassword(final String uid, final String password) throws SecurityException + public void changePassword(final String uid, final String password) + throws SecurityException { validateUid(uid); validatePassword(password); @@ -103,46 +112,54 @@ * OperationNotSupportedException if the password is empty. * </p> * - * @param uid The uid. - * @param password The password. - * @throws SecurityException Throws a {@link SecurityException}. - */ - public boolean authenticate(final String uid, final String password) throws SecurityException + * @param uid + * The uid. + * @param password + * The password. + * @throws SecurityException + * Throws a {@link SecurityException}. + */ + public boolean authenticate(final String uid, final String password) + throws SecurityException { validateUid(uid); validatePassword(password); try { - Hashtable env = this.ctx.getEnvironment(); - //String savedPassword = String.valueOf(getPassword(uid)); - String oldCredential = (String)env.get(Context.SECURITY_CREDENTIALS); - String oldUsername = (String)env.get(Context.SECURITY_PRINCIPAL); - - String dn = lookupByUid(uid); - if ( dn == null ) - throw new SecurityException(new KeyedMessage("User " + uid + " not found")); - - // Build user dn using lookup value, just appending the user filter after the uid won't work when users + Hashtable env = this.ctx.getEnvironment(); + // String savedPassword = String.valueOf(getPassword(uid)); + String oldCredential = (String) env + .get(Context.SECURITY_CREDENTIALS); + String oldUsername = (String) env.get(Context.SECURITY_PRINCIPAL); + + String dn = lookupByUid(uid); + if (dn == null) + throw new SecurityException(new KeyedMessage("User " + uid + + " not found")); + + // Build user dn using lookup value, just appending the user filter + // after the uid won't work when users // are/can be stored in a subtree (searchScope sub-tree) - // The looked up dn though is/should always be correct, just need to append the root context. + // The looked up dn though is/should always be correct, just need to + // append the root context. if (!StringUtils.isEmpty(getRootContext())) - dn +="," + getRootContext(); - - env.put(Context.SECURITY_PRINCIPAL,dn); - env.put(Context.SECURITY_CREDENTIALS,password); - new InitialContext(env); - env.put(Context.SECURITY_PRINCIPAL,oldUsername); - env.put(Context.SECURITY_CREDENTIALS,oldCredential); - return true; - } - catch (AuthenticationException e) - { - return false; - } - catch (NamingException e) - { - throw new SecurityException(e); - } + dn += "," + getRootContext(); + + env.put(Context.SECURITY_PRINCIPAL, dn); + env.put(Context.SECURITY_CREDENTIALS, password); + new InitialContext(env); + env.put(Context.SECURITY_PRINCIPAL, oldUsername); + env.put(Context.SECURITY_CREDENTIALS, oldCredential); + return true; + } + catch (AuthenticationException e) + { + return false; + } + catch (NamingException e) + { + throw new SecurityException(e); + } } /** @@ -169,16 +186,20 @@ * Set the user's password. * </p> * - * @param userDn The user. - * @param password The password. - * @throws NamingException Throws a {@link NamingException}. + * @param userDn + * The user. + * @param password + * The password. + * @throws NamingException + * Throws a {@link NamingException}. */ - private void setPassword(final String userDn, final String password) throws NamingException + private void setPassword(final String userDn, final String password) + throws NamingException { - logger.debug("setPassword userDn = " + userDn); + logger.debug("setPassword userDn = " + userDn); String rdn = getSubcontextName(userDn); - //if (!StringUtils.isEmpty(getUserFilterBase())) - // rdn+="," + getUserFilterBase(); + // if (!StringUtils.isEmpty(getUserFilterBase())) + // rdn+="," + getUserFilterBase(); logger.debug("setPassword rdn = " + rdn); Attributes attrs = new BasicAttributes(false); @@ -191,21 +212,24 @@ * Get the password. * </p> * - * @param results The {@link NamingEnumeration}. - * @param uid The uid. + * @param results + * The {@link NamingEnumeration}. + * @param uid + * The uid. * @return The password as an array of char. - * @throws NamingException Throws a {@link NamingException}. + * @throws NamingException + * Throws a {@link NamingException}. */ - private char[] getPassword(final NamingEnumeration results, final String uid) throws NamingException + private char[] getPassword(final NamingEnumeration results, final String uid) + throws NamingException { - if (!results.hasMore()) - { - throw new NamingException("Could not find any user with uid[" + uid + "]"); - } + if (!results.hasMore()) { throw new NamingException( + "Could not find any user with uid[" + uid + "]"); } Attributes userAttributes = getFirstUser(results); - char[] rawPassword = convertRawPassword(getAttribute(getUserPasswordAttribute(), userAttributes)); + char[] rawPassword = convertRawPassword(getAttribute( + getUserPasswordAttribute(), userAttributes)); return rawPassword; } @@ -214,21 +238,22 @@ * Get the attribute. * </p> * - * @param attributeName The attribute name. - * @param userAttributes The user {@link Attributes}. + * @param attributeName + * The attribute name. + * @param userAttributes + * The user {@link Attributes}. * @return The {@link Attribute} - * @throws NamingException Throws a {@link NamingException}. + * @throws NamingException + * Throws a {@link NamingException}. */ - private Attribute getAttribute(String attributeName, Attributes userAttributes) throws NamingException + private Attribute getAttribute(String attributeName, + Attributes userAttributes) throws NamingException { for (NamingEnumeration ae = userAttributes.getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); - if (attr.getID().equalsIgnoreCase(attributeName)) - { - return attr; - } + if (attr.getID().equalsIgnoreCase(attributeName)) { return attr; } } return null; } @@ -239,13 +264,14 @@ * improved to do proper unicode conversion. * </p> * - * @param attr The {@link Attribute}. + * @param attr + * The {@link Attribute}. */ private char[] convertRawPassword(Attribute attr) throws NamingException { char[] charPass = null; - - if ( attr != null ) + + if (attr != null) { byte[] rawPass = (byte[]) attr.getAll().next(); charPass = new char[rawPass.length]; @@ -253,7 +279,7 @@ for (int i = 0; i < rawPass.length; i++) { // I know I lose the sign and this is only good for ascii text. - charPass[i] = (char) rawPass[i]; + charPass[i] = (char) rawPass[i]; } } else @@ -268,11 +294,14 @@ * Gets the first matching user. * </p> * - * @param results The results to find the user in. + * @param results + * The results to find the user in. * @return The Attributes. - * @throws NamingException Throws a {@link NamingException}. + * @throws NamingException + * Throws a {@link NamingException}. */ - private Attributes getFirstUser(NamingEnumeration results) throws NamingException + private Attributes getFirstUser(NamingEnumeration results) + throws NamingException { SearchResult result = (SearchResult) results.next(); Attributes answer = result.getAttributes(); @@ -280,24 +309,29 @@ return answer; } - protected String getEntryPrefix() { - return this.getUserIdAttribute(); - } - - protected String getSearchSuffix() { - return this.getUserFilter(); - } + protected String getEntryPrefix() + { + return this.getUserIdAttribute(); + } - protected String getSearchDomain() { - return this.getUserFilterBase(); - } - - protected String[] getObjectClasses() { - return this.getUserObjectClasses(); - } + protected String getSearchSuffix() + { + return this.getUserFilter(); + } - protected String[] getAttributes() { - return this.getUserAttributes(); - } - + protected String getSearchDomain() + { + return this.getUserFilterBase(); + } + + protected String[] getObjectClasses() + { + return this.getUserObjectClasses(); + } + + protected String[] getAttributes() + { + return this.getUserAttributes(); + } + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserPrincipalDao.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserPrincipalDao.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserPrincipalDao.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,127 +28,168 @@ */ public interface LdapUserPrincipalDao extends LdapPrincipalDao { + /** * <p> * Add a user to a group. * </p> * - * @param userPrincipalUid The user principal. - * @param groupPrincipalUid The group principal. - * @throws SecurityException A {@link SecurityException}. + * @param userPrincipalUid + * The user principal. + * @param groupPrincipalUid + * The group principal. + * @throws SecurityException + * A {@link SecurityException}. */ - void addGroup(String userPrincipalUid, String groupPrincipalUid) throws SecurityException; + void addGroup(String userPrincipalUid, String groupPrincipalUid) + throws SecurityException; /** * <p> * Remove a user from a group. * </p> * - * @param userPrincipalUid The user principal. - * @param groupPrincipalUid The group principal. - * @throws SecurityException A {@link SecurityException}. + * @param userPrincipalUid + * The user principal. + * @param groupPrincipalUid + * The group principal. + * @throws SecurityException + * A {@link SecurityException}. */ - void removeGroup(String userPrincipalUid, String groupPrincipalUid) throws SecurityException; + void removeGroup(String userPrincipalUid, String groupPrincipalUid) + throws SecurityException; /** * <p> * Add a user to a group. * </p> * - * @param userPrincipalUid The user principal. - * @param rolePrincipalUid The role principal. - * @throws SecurityException A {@link SecurityException}. + * @param userPrincipalUid + * The user principal. + * @param rolePrincipalUid + * The role principal. + * @throws SecurityException + * A {@link SecurityException}. */ - void addRole(String userPrincipalUid, String rolePrincipalUid) throws SecurityException; + void addRole(String userPrincipalUid, String rolePrincipalUid) + throws SecurityException; /** * <p> * Remove a user from a group. * </p> * - * @param userPrincipalUid The user principal. - * @param rolePrincipalUid The role principal. - * @throws SecurityException A {@link SecurityException}. + * @param userPrincipalUid + * The user principal. + * @param rolePrincipalUid + * The role principal. + * @throws SecurityException + * A {@link SecurityException}. */ - void removeRole(String userPrincipalUid, String rolePrincipalUid) throws SecurityException; - - + void removeRole(String userPrincipalUid, String rolePrincipalUid) + throws SecurityException; + /** * <p> - * Return an array of the group principal UIDS that belong to a specific user. + * Return an array of the group principal UIDS that belong to a specific + * user. * </p> * - * @param userPrincipalUid The user principal uid. + * @param userPrincipalUid + * The user principal uid. * @return The array of group uids asociated with this user - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ - String[] getGroupUidsForUser(String userPrincipalUid) throws SecurityException; - + String[] getGroupUidsForUser(String userPrincipalUid) + throws SecurityException; + /** * <p> - * Return an array of the role principal UIDS that belong to a specific user. + * Return an array of the role principal UIDS that belong to a specific + * user. * </p> * - * @param userPrincipalUid The user principal uid. + * @param userPrincipalUid + * The user principal uid. * @return The array of group uids asociated with this user - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ - String[] getRoleUidsForUser(String userPrincipalUid) throws SecurityException; + String[] getRoleUidsForUser(String userPrincipalUid) + throws SecurityException; /** * <p> * Return an array of the user principal uids that belong to a group. * </p> * - * @param groupPrincipalUid The group uid. + * @param groupPrincipalUid + * The group uid. * @return The array of user uids asociated with this group - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ - String[] getUserUidsForGroup(String groupPrincipalUid) throws SecurityException; + String[] getUserUidsForGroup(String groupPrincipalUid) + throws SecurityException; /** * <p> * Return an array of the user principal uids that belong to a role. * </p> * - * @param rolePrincipalUid The role uid. + * @param rolePrincipalUid + * The role uid. * @return The array of user uids asociated with this group - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ - String[] getUserUidsForRole(String rolePrincipalUid) throws SecurityException; + String[] getUserUidsForRole(String rolePrincipalUid) + throws SecurityException; /** * <p> - * Return an array of the role principal UIDS that belong to a specific group. + * Return an array of the role principal UIDS that belong to a specific + * group. * </p> * - * @param groupPrincipalUid The group principal uid. + * @param groupPrincipalUid + * The group principal uid. * @return The array of role uids asociated with this user - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ - String[] getRolesForGroup(String groupPrincipalUid) throws SecurityException; - + String[] getRolesForGroup(String groupPrincipalUid) + throws SecurityException; + /** * <p> * Add a role to a group. * </p> * - * @param groupPrincipalUid The group principal. - * @param rolePrincipalUid The role principal. - * @throws SecurityException A {@link SecurityException}. - */ - void addRoleToGroup(String groupPrincipalUid, String rolePrincipalUid) throws SecurityException; - + * @param groupPrincipalUid + * The group principal. + * @param rolePrincipalUid + * The role principal. + * @throws SecurityException + * A {@link SecurityException}. + */ + void addRoleToGroup(String groupPrincipalUid, String rolePrincipalUid) + throws SecurityException; + /** * <p> * Remove a role from a group. * </p> * - * @param groupPrincipalUid The group principal. - * @param rolePrincipalUid The role principal. - * @throws SecurityException A {@link SecurityException}. - */ - void removeRoleFromGroup(String groupPrincipalUid, String rolePrincipalUid) throws SecurityException; - - + * @param groupPrincipalUid + * The group principal. + * @param rolePrincipalUid + * The role principal. + * @throws SecurityException + * A {@link SecurityException}. + */ + void removeRoleFromGroup(String groupPrincipalUid, String rolePrincipalUid) + throws SecurityException; + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserPrincipalDaoImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserPrincipalDaoImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/spi/impl/ldap/LdapUserPrincipalDaoImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,8 +33,10 @@ * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long </a>, <a * href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ -public class LdapUserPrincipalDaoImpl extends LdapPrincipalDaoImpl implements LdapUserPrincipalDao +public class LdapUserPrincipalDaoImpl extends LdapPrincipalDaoImpl implements + LdapUserPrincipalDao { + private LdapMembershipDao membership; /** @@ -42,12 +44,13 @@ * Default constructor. * </p> * - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ public LdapUserPrincipalDaoImpl() throws SecurityException { - super(); - membership=new LdapMemberShipDaoImpl(); + super(); + membership = new LdapMemberShipDaoImpl(); } /** @@ -55,26 +58,32 @@ * Initializes the dao. * </p> * - * @param ldapConfig Holds the ldap binding configuration. - * @throws SecurityException A {@link SecurityException}. + * @param ldapConfig + * Holds the ldap binding configuration. + * @throws SecurityException + * A {@link SecurityException}. */ - public LdapUserPrincipalDaoImpl(LdapBindingConfig ldapConfig) throws SecurityException + public LdapUserPrincipalDaoImpl(LdapBindingConfig ldapConfig) + throws SecurityException { - super(ldapConfig); - membership=new LdapMemberShipDaoImpl(ldapConfig); + super(ldapConfig); + membership = new LdapMemberShipDaoImpl(ldapConfig); } /** * @see org.apache.jetspeed.security.spi.impl.ldap.LdapUserPrincipalDao#addGroup(java.lang.String, * java.lang.String) */ - public void addGroup(String userPrincipalUid, String groupPrincipalUid) throws SecurityException + public void addGroup(String userPrincipalUid, String groupPrincipalUid) + throws SecurityException { - if (!StringUtils.isEmpty(getUserGroupMembershipAttribute())) - modifyUserGroupByUser(userPrincipalUid, groupPrincipalUid, DirContext.ADD_ATTRIBUTE); - else - modifyUserGroupByGroup(userPrincipalUid, groupPrincipalUid, DirContext.ADD_ATTRIBUTE); - + if (!StringUtils.isEmpty(getUserGroupMembershipAttribute())) + modifyUserGroupByUser(userPrincipalUid, groupPrincipalUid, + DirContext.ADD_ATTRIBUTE); + else + modifyUserGroupByGroup(userPrincipalUid, groupPrincipalUid, + DirContext.ADD_ATTRIBUTE); + } /** @@ -84,10 +93,14 @@ * * @param userPrincipalUid * @param groupPrincipalUid - * @param operationType whether to replace or remove the specified user group from the user - * @throws SecurityException A {@link SecurityException}. + * @param operationType + * whether to replace or remove the specified user group from the + * user + * @throws SecurityException + * A {@link SecurityException}. */ - private void modifyUserGroupByGroup(String userPrincipalUid, String groupPrincipalUid, int operationType) + private void modifyUserGroupByGroup(String userPrincipalUid, + String groupPrincipalUid, int operationType) throws SecurityException { validateUid(userPrincipalUid); @@ -95,73 +108,85 @@ try { - + Attributes attrs = new BasicAttributes(false); - attrs.put(getGroupMembershipAttribute(), getUserDN(userPrincipalUid)); - - ctx.modifyAttributes(getGroupDN(groupPrincipalUid,false), operationType, attrs); + attrs.put(getGroupMembershipAttribute(), + getUserDN(userPrincipalUid)); + + ctx.modifyAttributes(getGroupDN(groupPrincipalUid, false), + operationType, attrs); } catch (NamingException e) { throw new SecurityException(e); } } - - - /** + /** * <p> * Replace or delete the user group attribute. * </p> * * @param userPrincipalUid * @param groupPrincipalUid - * @param operationType whether to replace or remove the specified user group from the user - * @throws SecurityException A {@link SecurityException}. + * @param operationType + * whether to replace or remove the specified user group from the + * user + * @throws SecurityException + * A {@link SecurityException}. */ - private void modifyUserGroupByUser(String userPrincipalUid, String groupPrincipalUid, int operationType) + private void modifyUserGroupByUser(String userPrincipalUid, + String groupPrincipalUid, int operationType) throws SecurityException { validateUid(userPrincipalUid); validateUid(groupPrincipalUid); - + try { - Attributes attrs = new BasicAttributes(false); - attrs.put(getUserGroupMembershipAttribute(), getGroupDN(groupPrincipalUid)); + Attributes attrs = new BasicAttributes(false); + attrs.put(getUserGroupMembershipAttribute(), + getGroupDN(groupPrincipalUid)); - ctx.modifyAttributes(getUserDN(userPrincipalUid,false), operationType, attrs); - + ctx.modifyAttributes(getUserDN(userPrincipalUid, false), + operationType, attrs); + } catch (NamingException e) { throw new SecurityException(e); } - } + } /** * @see org.apache.jetspeed.security.spi.impl.ldap.LdapUserPrincipalDao#removeGroup(java.lang.String, * java.lang.String) */ - public void removeGroup(String userPrincipalUid, String groupPrincipalUid) throws SecurityException + public void removeGroup(String userPrincipalUid, String groupPrincipalUid) + throws SecurityException { - if (!StringUtils.isEmpty(getUserGroupMembershipAttribute())) - modifyUserGroupByUser(userPrincipalUid, groupPrincipalUid, DirContext.REMOVE_ATTRIBUTE); - else - modifyUserGroupByGroup(userPrincipalUid, groupPrincipalUid, DirContext.REMOVE_ATTRIBUTE); - + if (!StringUtils.isEmpty(getUserGroupMembershipAttribute())) + modifyUserGroupByUser(userPrincipalUid, groupPrincipalUid, + DirContext.REMOVE_ATTRIBUTE); + else + modifyUserGroupByGroup(userPrincipalUid, groupPrincipalUid, + DirContext.REMOVE_ATTRIBUTE); + } - + /** * @see org.apache.jetspeed.security.spi.impl.ldap.LdapUserPrincipalDao#addGroup(java.lang.String, * java.lang.String) */ - public void addRole(String userPrincipalUid, String rolePrincipalUid) throws SecurityException + public void addRole(String userPrincipalUid, String rolePrincipalUid) + throws SecurityException { - if (!StringUtils.isEmpty(getUserRoleMembershipAttribute())) - modifyUserRoleByUser(userPrincipalUid, rolePrincipalUid, DirContext.ADD_ATTRIBUTE); - else - modifyUserRoleByRole(userPrincipalUid, rolePrincipalUid, DirContext.ADD_ATTRIBUTE); + if (!StringUtils.isEmpty(getUserRoleMembershipAttribute())) + modifyUserRoleByUser(userPrincipalUid, rolePrincipalUid, + DirContext.ADD_ATTRIBUTE); + else + modifyUserRoleByRole(userPrincipalUid, rolePrincipalUid, + DirContext.ADD_ATTRIBUTE); } /** @@ -172,21 +197,27 @@ * * @param userPrincipalUid * @param rolePrincipalUid - * @param operationType whether to replace or remove the specified user group from the user - * @throws SecurityException A {@link SecurityException}. + * @param operationType + * whether to replace or remove the specified user group from the + * user + * @throws SecurityException + * A {@link SecurityException}. */ - private void modifyUserRoleByUser(String userPrincipalUid, String rolePrincipalUid, int operationType) + private void modifyUserRoleByUser(String userPrincipalUid, + String rolePrincipalUid, int operationType) throws SecurityException { validateUid(userPrincipalUid); validateUid(rolePrincipalUid); - + try { - Attributes attrs = new BasicAttributes(false); - attrs.put(getUserRoleMembershipAttribute(), getRoleDN(rolePrincipalUid)); + Attributes attrs = new BasicAttributes(false); + attrs.put(getUserRoleMembershipAttribute(), + getRoleDN(rolePrincipalUid)); - ctx.modifyAttributes(getUserDN(userPrincipalUid,false), operationType, attrs); + ctx.modifyAttributes(getUserDN(userPrincipalUid, false), + operationType, attrs); } catch (NamingException e) { @@ -202,47 +233,58 @@ * * @param userPrincipalUid * @param rolePrincipalUid - * @param operationType whether to replace or remove the specified user group from the user - * @throws SecurityException A {@link SecurityException}. + * @param operationType + * whether to replace or remove the specified user group from the + * user + * @throws SecurityException + * A {@link SecurityException}. */ - private void modifyUserRoleByRole(String userPrincipalUid, String rolePrincipalUid, int operationType) + private void modifyUserRoleByRole(String userPrincipalUid, + String rolePrincipalUid, int operationType) throws SecurityException { validateUid(userPrincipalUid); validateUid(rolePrincipalUid); - + try { Attributes attrs = new BasicAttributes(false); - attrs.put(getRoleMembershipAttribute(), getUserDN(userPrincipalUid)); + attrs + .put(getRoleMembershipAttribute(), + getUserDN(userPrincipalUid)); - ctx.modifyAttributes(getRoleDN(rolePrincipalUid,false), operationType, attrs); + ctx.modifyAttributes(getRoleDN(rolePrincipalUid, false), + operationType, attrs); } catch (NamingException e) { throw new SecurityException(e); } - } + } - - /** + /** * @see org.apache.jetspeed.security.spi.impl.ldap.LdapUserPrincipalDao#removeGroup(java.lang.String, * java.lang.String) */ - public void removeRole(String userPrincipalUid, String rolePrincipalUid) throws SecurityException + public void removeRole(String userPrincipalUid, String rolePrincipalUid) + throws SecurityException { - if (!StringUtils.isEmpty(getUserRoleMembershipAttribute())) - modifyUserRoleByUser(userPrincipalUid, rolePrincipalUid, DirContext.REMOVE_ATTRIBUTE); - else - modifyUserRoleByRole(userPrincipalUid, rolePrincipalUid, DirContext.REMOVE_ATTRIBUTE); - } + if (!StringUtils.isEmpty(getUserRoleMembershipAttribute())) + modifyUserRoleByUser(userPrincipalUid, rolePrincipalUid, + DirContext.REMOVE_ATTRIBUTE); + else + modifyUserRoleByRole(userPrincipalUid, rolePrincipalUid, + DirContext.REMOVE_ATTRIBUTE); + } /** * <p> - * A template method for defining the attributes for a particular LDAP class. + * A template method for defining the attributes for a particular LDAP + * class. * </p> * - * @param principalUid The principal uid. + * @param principalUid + * The principal uid. * @return the LDAP attributes object for the particular class. */ protected Attributes defineLdapAttributes(final String principalUid) @@ -250,26 +292,26 @@ Attributes attrs = new BasicAttributes(true); BasicAttribute classes = new BasicAttribute("objectclass"); - for (int i=0;i<getObjectClasses().length;i++) - classes.add(getObjectClasses()[i]); + for (int i = 0; i < getObjectClasses().length; i++) + classes.add(getObjectClasses()[i]); attrs.put(classes); - for (int i=0;i<getAttributes().length;i++) - attrs.put(parseAttr(getAttributes()[i],principalUid)[0], parseAttr(getAttributes()[i],principalUid)[1]); - + for (int i = 0; i < getAttributes().length; i++) + attrs.put(parseAttr(getAttributes()[i], principalUid)[0], + parseAttr(getAttributes()[i], principalUid)[1]); + attrs.put(getEntryPrefix(), principalUid); - + return attrs; } - - /** * <p> * Creates a GroupPrincipal object. * </p> * - * @param principalUid The principal uid. + * @param principalUid + * The principal uid. * @return A group principal object. */ protected Principal makePrincipal(String principalUid) @@ -281,13 +323,16 @@ * @see org.apache.jetspeed.security.spi.impl.ldap.LdapUserPrincipalDao#addGroup(java.lang.String, * java.lang.String) */ - public void addRoleToGroup(String groupPrincipalUid, String rolePrincipalUid) throws SecurityException + public void addRoleToGroup(String groupPrincipalUid, String rolePrincipalUid) + throws SecurityException { - if (!StringUtils.isEmpty(getRoleGroupMembershipForRoleAttribute())) - modifyRoleGroupByRole(groupPrincipalUid, rolePrincipalUid, DirContext.ADD_ATTRIBUTE); - else - modifyRoleGroupByGroup(groupPrincipalUid, rolePrincipalUid, DirContext.ADD_ATTRIBUTE); - + if (!StringUtils.isEmpty(getRoleGroupMembershipForRoleAttribute())) + modifyRoleGroupByRole(groupPrincipalUid, rolePrincipalUid, + DirContext.ADD_ATTRIBUTE); + else + modifyRoleGroupByGroup(groupPrincipalUid, rolePrincipalUid, + DirContext.ADD_ATTRIBUTE); + } /** @@ -297,10 +342,14 @@ * * @param userPrincipalUid * @param groupPrincipalUid - * @param operationType whether to replace or remove the specified user group from the user - * @throws SecurityException A {@link SecurityException}. + * @param operationType + * whether to replace or remove the specified user group from the + * user + * @throws SecurityException + * A {@link SecurityException}. */ - private void modifyRoleGroupByRole(String groupPrincipalUid, String rolePrincipalUid, int operationType) + private void modifyRoleGroupByRole(String groupPrincipalUid, + String rolePrincipalUid, int operationType) throws SecurityException { validateUid(groupPrincipalUid); @@ -309,16 +358,18 @@ { Attributes attrs = new BasicAttributes(false); - attrs.put(getRoleGroupMembershipForRoleAttribute(), getGroupDN(groupPrincipalUid)); + attrs.put(getRoleGroupMembershipForRoleAttribute(), + getGroupDN(groupPrincipalUid)); - ctx.modifyAttributes(getRoleDN(rolePrincipalUid,false), operationType, attrs); + ctx.modifyAttributes(getRoleDN(rolePrincipalUid, false), + operationType, attrs); } catch (NamingException e) { throw new SecurityException(e); } } - + /** * <p> * Replace or delete the user group attribute. @@ -326,10 +377,14 @@ * * @param userPrincipalUid * @param groupPrincipalUid - * @param operationType whether to replace or remove the specified user group from the user - * @throws SecurityException A {@link SecurityException}. + * @param operationType + * whether to replace or remove the specified user group from the + * user + * @throws SecurityException + * A {@link SecurityException}. */ - private void modifyRoleGroupByGroup(String groupPrincipalUid, String rolePrincipalUid, int operationType) + private void modifyRoleGroupByGroup(String groupPrincipalUid, + String rolePrincipalUid, int operationType) throws SecurityException { validateUid(groupPrincipalUid); @@ -337,30 +392,35 @@ try { Attributes attrs = new BasicAttributes(false); - attrs.put(getGroupMembershipForRoleAttribute(), getRoleDN(rolePrincipalUid)); + attrs.put(getGroupMembershipForRoleAttribute(), + getRoleDN(rolePrincipalUid)); - ctx.modifyAttributes(getGroupDN(groupPrincipalUid, false), operationType, attrs); + ctx.modifyAttributes(getGroupDN(groupPrincipalUid, false), + operationType, attrs); } catch (NamingException e) { throw new SecurityException(e); } - } + } /** * @see org.apache.jetspeed.security.spi.impl.ldap.LdapUserPrincipalDao#removeGroup(java.lang.String, * java.lang.String) */ - public void removeRoleFromGroup(String groupPrincipalUid, String rolePrincipalUid) throws SecurityException + public void removeRoleFromGroup(String groupPrincipalUid, + String rolePrincipalUid) throws SecurityException { - - if (!StringUtils.isEmpty(getRoleGroupMembershipForRoleAttribute())) - modifyRoleGroupByRole(groupPrincipalUid, rolePrincipalUid, DirContext.REMOVE_ATTRIBUTE); - else - modifyRoleGroupByGroup(groupPrincipalUid, rolePrincipalUid, DirContext.REMOVE_ATTRIBUTE); - - } + if (!StringUtils.isEmpty(getRoleGroupMembershipForRoleAttribute())) + modifyRoleGroupByRole(groupPrincipalUid, rolePrincipalUid, + DirContext.REMOVE_ATTRIBUTE); + else + modifyRoleGroupByGroup(groupPrincipalUid, rolePrincipalUid, + DirContext.REMOVE_ATTRIBUTE); + + } + /** * * Return the list of group IDs for a particular user @@ -369,18 +429,18 @@ * @return the array of group uids asociated with this user * @throws SecurityException */ - public String[] getGroupUidsForUser(String userPrincipalUid) throws SecurityException + public String[] getGroupUidsForUser(String userPrincipalUid) + throws SecurityException { validateUid(userPrincipalUid); SearchControls cons = setSearchControls(); try { - if (!StringUtils.isEmpty(getUserGroupMembershipAttribute())) { - return membership.searchGroupMemberShipByUser(userPrincipalUid,cons); - } - return membership.searchGroupMemberShipByGroup(userPrincipalUid,cons); - - + if (!StringUtils.isEmpty(getUserGroupMembershipAttribute())) { return membership + .searchGroupMemberShipByUser(userPrincipalUid, cons); } + return membership.searchGroupMemberShipByGroup(userPrincipalUid, + cons); + } catch (NamingException e) { @@ -388,55 +448,60 @@ } } - /** - * <p> - * Return an array of the roles that belong to a group. - * </p> - * - * @param groupPrincipalUid The group principal uid. - * @return The array of user uids asociated with this group - * @throws SecurityException A {@link SecurityException}. - */ - public String[] getRolesForGroup(String groupPrincipalUid) throws SecurityException - { - { - validateUid(groupPrincipalUid); - SearchControls cons = setSearchControls(); - try - { - if (!StringUtils.isEmpty(getRoleGroupMembershipForRoleAttribute())) { - return membership.searchRolesFromGroupByRole(groupPrincipalUid,cons); - } - return membership.searchRolesFromGroupByGroup(groupPrincipalUid,cons); - } - catch (NamingException e) - { - throw new SecurityException(e); - } - } - } + /** + * <p> + * Return an array of the roles that belong to a group. + * </p> + * + * @param groupPrincipalUid + * The group principal uid. + * @return The array of user uids asociated with this group + * @throws SecurityException + * A {@link SecurityException}. + */ + public String[] getRolesForGroup(String groupPrincipalUid) + throws SecurityException + { + { + validateUid(groupPrincipalUid); + SearchControls cons = setSearchControls(); + try + { + if (!StringUtils + .isEmpty(getRoleGroupMembershipForRoleAttribute())) { return membership + .searchRolesFromGroupByRole(groupPrincipalUid, cons); } + return membership.searchRolesFromGroupByGroup( + groupPrincipalUid, cons); + } + catch (NamingException e) + { + throw new SecurityException(e); + } + } + } - /** * * Returns the role IDs for a particular user * - * Looks up the user, and extracts the rolemembership attr (ex : uniquemember) + * Looks up the user, and extracts the rolemembership attr (ex : + * uniquemember) * * @param userPrincipalUid * @return the array of group uids asociated with this user * @throws SecurityException */ - public String[] getRoleUidsForUser(String userPrincipalUid) throws SecurityException + public String[] getRoleUidsForUser(String userPrincipalUid) + throws SecurityException { validateUid(userPrincipalUid); SearchControls cons = setSearchControls(); try { - if (!StringUtils.isEmpty(getUserRoleMembershipAttribute())) { - return membership.searchRoleMemberShipByUser(userPrincipalUid,cons); - } - return membership.searchRoleMemberShipByRole(userPrincipalUid,cons); + if (!StringUtils.isEmpty(getUserRoleMembershipAttribute())) { return membership + .searchRoleMemberShipByUser(userPrincipalUid, cons); } + return membership + .searchRoleMemberShipByRole(userPrincipalUid, cons); } catch (NamingException e) { @@ -444,81 +509,92 @@ } } - /** - * <p> - * Return an array of the user principal UIDS that belong to a group. - * </p> - * - * @param groupPrincipalUid The group principal uid. - * @return The array of user uids asociated with this group - * @throws SecurityException A {@link SecurityException}. - */ - public String[] getUserUidsForGroup(String groupPrincipalUid) throws SecurityException - { - - validateUid(groupPrincipalUid); - SearchControls cons = setSearchControls(); - try - { - if (!StringUtils.isEmpty(getUserGroupMembershipAttribute())) { - return membership.searchUsersFromGroupByUser(groupPrincipalUid,cons); - } - return membership.searchUsersFromGroupByGroup(groupPrincipalUid,cons); - } - catch (NamingException e) - { - throw new SecurityException(e); - } - } + /** + * <p> + * Return an array of the user principal UIDS that belong to a group. + * </p> + * + * @param groupPrincipalUid + * The group principal uid. + * @return The array of user uids asociated with this group + * @throws SecurityException + * A {@link SecurityException}. + */ + public String[] getUserUidsForGroup(String groupPrincipalUid) + throws SecurityException + { - /** - * <p> - * Return an array of the user principal UIDS that belong to a group. - * </p> - * - * @param groupPrincipalUid The group principal uid. - * @return The array of user uids asociated with this group - * @throws SecurityException A {@link SecurityException}. - */ - public String[] getUserUidsForRole(String rolePrincipalUid) throws SecurityException - { - validateUid(rolePrincipalUid); - SearchControls cons = setSearchControls(); - try - { - if (!StringUtils.isEmpty(getUserRoleMembershipAttribute())) { - return membership.searchUsersFromRoleByUser(rolePrincipalUid,cons); - } - return membership.searchUsersFromRoleByRole(rolePrincipalUid,cons); - } - catch (NamingException e) - { - throw new SecurityException(e); - } - } - - protected String[] getObjectClasses() { - return this.getUserObjectClasses(); - } - - protected String[] getAttributes() { - return this.getUserAttributes(); - } - - protected String getUidAttributeForPrincipal() { - return this.getUserUidAttribute(); - } + validateUid(groupPrincipalUid); + SearchControls cons = setSearchControls(); + try + { + if (!StringUtils.isEmpty(getUserGroupMembershipAttribute())) { return membership + .searchUsersFromGroupByUser(groupPrincipalUid, cons); } + return membership.searchUsersFromGroupByGroup(groupPrincipalUid, + cons); + } + catch (NamingException e) + { + throw new SecurityException(e); + } + } - protected String getEntryPrefix() { - return this.getUserIdAttribute(); - } + /** + * <p> + * Return an array of the user principal UIDS that belong to a group. + * </p> + * + * @param groupPrincipalUid + * The group principal uid. + * @return The array of user uids asociated with this group + * @throws SecurityException + * A {@link SecurityException}. + */ + public String[] getUserUidsForRole(String rolePrincipalUid) + throws SecurityException + { + validateUid(rolePrincipalUid); + SearchControls cons = setSearchControls(); + try + { + if (!StringUtils.isEmpty(getUserRoleMembershipAttribute())) { return membership + .searchUsersFromRoleByUser(rolePrincipalUid, cons); } + return membership.searchUsersFromRoleByRole(rolePrincipalUid, cons); + } + catch (NamingException e) + { + throw new SecurityException(e); + } + } - protected String getSearchSuffix() { - return this.getUserFilter(); - } + protected String[] getObjectClasses() + { + return this.getUserObjectClasses(); + } - protected String getDnSuffix() { + protected String[] getAttributes() + { + return this.getUserAttributes(); + } + + protected String getUidAttributeForPrincipal() + { + return this.getUserUidAttribute(); + } + + protected String getEntryPrefix() + { + return this.getUserIdAttribute(); + } + + protected String getSearchSuffix() + { + return this.getUserFilter(); + } + + protected String getDnSuffix() + { return this.getUserFilterBase(); } - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/util/GullibleSSLSocketFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/util/GullibleSSLSocketFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/util/GullibleSSLSocketFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,72 +25,113 @@ import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; -import javax.net.ssl.X509TrustManager; + import javax.net.SocketFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; /** * Socket Factory for SSL connections which do not provide an authentication - * This is used to connect to servers where we are just interested in - * an encypted tunnel, and not to verify that both parties trust each other. - * + * This is used to connect to servers where we are just interested in an + * encypted tunnel, and not to verify that both parties trust each other. + * * @author <a href="mailto:b.vanhalderen ¡÷ hippo.nl">Berry van Halderen</a> * @version $Id: GullibleSSLSocketFactory.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public class GullibleSSLSocketFactory extends SSLSocketFactory { +public class GullibleSSLSocketFactory extends SSLSocketFactory +{ - class GullibleTrustManager implements X509TrustManager - { - GullibleTrustManager() { } - public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { + class GullibleTrustManager implements X509TrustManager + { + + GullibleTrustManager() + { + } + + public void checkClientTrusted(final X509Certificate[] chain, + final String authType) throws CertificateException + { + } + + public void checkServerTrusted(final X509Certificate[] chain, + final String authType) throws CertificateException + { + } + + public X509Certificate[] getAcceptedIssuers() + { + return new X509Certificate[0]; + } } - public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { + private SSLSocketFactory factory; + + protected GullibleSSLSocketFactory() + { + try + { + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, new TrustManager[] + {new GullibleTrustManager()}, new SecureRandom()); + factory = context.getSocketFactory(); + } + catch (NoSuchAlgorithmException e) + { + e.printStackTrace(); + } + catch (KeyManagementException e) + { + e.printStackTrace(); + } } - - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; + + public static SocketFactory getDefault() + { + return new GullibleSSLSocketFactory(); } - } - private SSLSocketFactory factory; - protected GullibleSSLSocketFactory() { - try { - SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, new TrustManager[] {new GullibleTrustManager()}, - new SecureRandom()); - factory = context.getSocketFactory(); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } catch (KeyManagementException e) { - e.printStackTrace(); - } - } - public static SocketFactory getDefault() { - return new GullibleSSLSocketFactory(); - } - public String[] getDefaultCipherSuites() { - return factory.getDefaultCipherSuites(); - } - public String[] getSupportedCipherSuites() { - return factory.getSupportedCipherSuites(); - } - public Socket createSocket(final Socket s, final String host, final int port, final boolean autoClose) throws IOException { - return factory.createSocket(s, host, port, autoClose); - } - public Socket createSocket(final String host, final int port) throws IOException, UnknownHostException { - return factory.createSocket(host, port); - } - public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort) throws IOException, UnknownHostException { - return factory.createSocket(host, port, localAddress, localPort); - } - public Socket createSocket(final InetAddress host, final int port) throws IOException { - return factory.createSocket(host, port); - } - public Socket createSocket(final InetAddress address, final int port, final InetAddress localAddress, final int localPort) throws IOException { - return factory.createSocket(address, port, localAddress, localPort); - } + public String[] getDefaultCipherSuites() + { + return factory.getDefaultCipherSuites(); + } + + public String[] getSupportedCipherSuites() + { + return factory.getSupportedCipherSuites(); + } + + public Socket createSocket(final Socket s, final String host, + final int port, final boolean autoClose) throws IOException + { + return factory.createSocket(s, host, port, autoClose); + } + + public Socket createSocket(final String host, final int port) + throws IOException, UnknownHostException + { + return factory.createSocket(host, port); + } + + public Socket createSocket(final String host, final int port, + final InetAddress localAddress, final int localPort) + throws IOException, UnknownHostException + { + return factory.createSocket(host, port, localAddress, localPort); + } + + public Socket createSocket(final InetAddress host, final int port) + throws IOException + { + return factory.createSocket(host, port); + } + + public Socket createSocket(final InetAddress address, final int port, + final InetAddress localAddress, final int localPort) + throws IOException + { + return factory.createSocket(address, port, localAddress, localPort); + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/util/PBEPasswordTool.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/util/PBEPasswordTool.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/util/PBEPasswordTool.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,7 +30,8 @@ /** * <p> - * PBEPasswordTool encodes and decodes user passwords using Password Based encryptionl + * PBEPasswordTool encodes and decodes user passwords using Password Based + * encryptionl * </p> * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> @@ -38,72 +39,99 @@ */ public class PBEPasswordTool { + // PKCS #5 (PBE) algoritm private static final String CIPHER_ALGORITM = "PBEwithMD5andDES"; - // PKCS #5 iteration count is advised to be at least 1000 + + // PKCS #5 iteration count is advised to be at least 1000 private static final int PKCS_5_ITERATIONCOUNT = 1111; + // pseudo random base salt which will be overlayed with userName.getBytes() - private static final byte[] PKCS_5_BASE_SALT = {(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32, (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03}; - + private static final byte[] PKCS_5_BASE_SALT = + {(byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32, (byte) 0x56, + (byte) 0x35, (byte) 0xE3, (byte) 0x03}; + // PBE cipher private SecretKey pbeKey; - - public PBEPasswordTool(String pbePassword) throws InvalidKeySpecException, NoSuchAlgorithmException + + public PBEPasswordTool(String pbePassword) throws InvalidKeySpecException, + NoSuchAlgorithmException { - pbeKey = SecretKeyFactory.getInstance(CIPHER_ALGORITM).generateSecret(new PBEKeySpec(pbePassword.toCharArray())); + pbeKey = SecretKeyFactory.getInstance(CIPHER_ALGORITM).generateSecret( + new PBEKeySpec(pbePassword.toCharArray())); } - /* (non-Javadoc) - * @see org.apache.jetspeed.security.spi.CredentialPasswordEncoder#encode(java.lang.String, java.lang.String) - * @see org.apache.jetspeed.security.PasswordEncodingService#encode(java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.security.spi.CredentialPasswordEncoder#encode(java.lang.String, + * java.lang.String) + * @see org.apache.jetspeed.security.PasswordEncodingService#encode(java.lang.String, + * java.lang.String) */ - public String encode(String userName, String clearTextPassword) throws SecurityException + public String encode(String userName, String clearTextPassword) + throws SecurityException { try { - // prevent dictionary attacks as well as copying of encoded passwords by using the userName as salt - PBEParameterSpec cipherSpec = new PBEParameterSpec(createSalt(userName.getBytes("UTF-8")), PKCS_5_ITERATIONCOUNT); - + // prevent dictionary attacks as well as copying of encoded + // passwords by using the userName as salt + PBEParameterSpec cipherSpec = new PBEParameterSpec( + createSalt(userName.getBytes("UTF-8")), + PKCS_5_ITERATIONCOUNT); + Cipher cipher = Cipher.getInstance(CIPHER_ALGORITM); - cipher.init(Cipher.ENCRYPT_MODE,pbeKey,cipherSpec); - - return new String(Base64.encodeBase64(cipher.doFinal(clearTextPassword.getBytes("UTF-8"))), "UTF-8"); + cipher.init(Cipher.ENCRYPT_MODE, pbeKey, cipherSpec); + + return new String(Base64.encodeBase64(cipher + .doFinal(clearTextPassword.getBytes("UTF-8"))), "UTF-8"); } catch (Exception e) { - throw new SecurityException(SecurityException.UNEXPECTED.create("PBEPasswordTool","encode",e.getMessage()), e); + throw new SecurityException(SecurityException.UNEXPECTED.create( + "PBEPasswordTool", "encode", e.getMessage()), e); } } - - /* (non-Javadoc) - * @see org.apache.jetspeed.security.PasswordEncodingService#decode(java.lang.String, java.lang.String) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.security.PasswordEncodingService#decode(java.lang.String, + * java.lang.String) */ - public String decode(String userName, String encodedPassword) throws SecurityException + public String decode(String userName, String encodedPassword) + throws SecurityException { try { - // prevent dictionary attacks as well as copying of encoded passwords by using the userName as salt - PBEParameterSpec cipherSpec = new PBEParameterSpec(createSalt(userName.getBytes("UTF-8")), PKCS_5_ITERATIONCOUNT); - + // prevent dictionary attacks as well as copying of encoded + // passwords by using the userName as salt + PBEParameterSpec cipherSpec = new PBEParameterSpec( + createSalt(userName.getBytes("UTF-8")), + PKCS_5_ITERATIONCOUNT); + Cipher cipher = Cipher.getInstance(CIPHER_ALGORITM); - cipher.init(Cipher.DECRYPT_MODE,pbeKey,cipherSpec); - - return new String(cipher.doFinal(Base64.decodeBase64(encodedPassword.getBytes("UTF-8"))), "UTF-8"); + cipher.init(Cipher.DECRYPT_MODE, pbeKey, cipherSpec); + + return new String(cipher.doFinal(Base64 + .decodeBase64(encodedPassword.getBytes("UTF-8"))), "UTF-8"); } catch (Exception e) { - throw new SecurityException(SecurityException.UNEXPECTED.create("PBEPasswordTool","decode",e.getMessage()), e); + throw new SecurityException(SecurityException.UNEXPECTED.create( + "PBEPasswordTool", "decode", e.getMessage()), e); } } - + /* - * Create a PCKS #5 salt using the BASE_PCKS_5_SALT overlayed with the provided secret parameter + * Create a PCKS #5 salt using the BASE_PCKS_5_SALT overlayed with the + * provided secret parameter */ private byte[] createSalt(byte[] secret) { byte[] salt = new byte[PKCS_5_BASE_SALT.length]; int i = 0; - for (;i < salt.length && i < secret.length; i++) + for (; i < salt.length && i < secret.length; i++) { salt[i] = secret[i]; } @@ -116,22 +144,31 @@ public static void main(String args[]) throws Exception { - if (args.length != 4 || (!args[0].equals("encode") && !args[0].equals("decode"))) + if (args.length != 4 + || (!args[0].equals("encode") && !args[0].equals("decode"))) { - System.err.println("Encode/Decode a user password using Password Based Encryption"); - System.err.println("Usage: PBEPasswordTool <encode|decode> <encoding-password> <username> <password>"); - System.err.println(" encode|decode : specify if to encode or decode the provided password"); - System.err.println(" encoding-password: the password to be used for encoding and decoding"); - System.err.println(" username : the name of the user to which the provided password belongs"); - System.err.println(" password : the cleartext password to encode, or the encoded password to decode\n"); + System.err + .println("Encode/Decode a user password using Password Based Encryption"); + System.err + .println("Usage: PBEPasswordTool <encode|decode> <encoding-password> <username> <password>"); + System.err + .println(" encode|decode : specify if to encode or decode the provided password"); + System.err + .println(" encoding-password: the password to be used for encoding and decoding"); + System.err + .println(" username : the name of the user to which the provided password belongs"); + System.err + .println(" password : the cleartext password to encode, or the encoded password to decode\n"); } else if (args[0].toLowerCase().equals("encode")) { - System.out.println("Encoded password: "+new PBEPasswordTool(args[1]).encode(args[2],args[3])); + System.out.println("Encoded password: " + + new PBEPasswordTool(args[1]).encode(args[2], args[3])); } else { - System.out.println("Decoded password: "+new PBEPasswordTool(args[1]).decode(args[2],args[3])); + System.out.println("Decoded password: " + + new PBEPasswordTool(args[1]).decode(args[2], args[3])); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/util/test/AbstractSecurityTestcase.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/util/test/AbstractSecurityTestcase.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/java/org/apache/jetspeed/security/util/test/AbstractSecurityTestcase.java 2008-05-16 01:54:54 UTC (rev 940) @@ -45,31 +45,32 @@ * @author <a href="mailto:sweaver ¡÷ einnovation.com">Scott T. Weaver </a> * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat </a> * @version $Id: AbstractSecurityTestcase.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class AbstractSecurityTestcase extends AbstractPrefsSupportedTestCase { + /** SPI Common Queries. */ protected SecurityAccess securityAccess; - + /** SPI Default Credential Handler. */ protected CredentialHandler ch; - + /** SPI Default User Security Handler. */ protected UserSecurityHandler ush; - + /** SPI Default Role Security Handler. */ protected RoleSecurityHandler rsh; - + /** SPI Default Group Security Handler. */ protected GroupSecurityHandler gsh; - + /** SPI Default Security Mapping Handler. */ protected SecurityMappingHandler smh; - + /** The security provider. */ protected SecurityProvider securityProvider; - + /** The user manager. */ protected UserManager ums; @@ -91,32 +92,47 @@ super.setUp(); // SPI Security handlers. - securityAccess = (SecurityAccess) ctx.getBean("org.apache.jetspeed.security.spi.SecurityAccess"); - ch = (CredentialHandler) ctx.getBean("org.apache.jetspeed.security.spi.CredentialHandler"); - ush = (UserSecurityHandler) ctx.getBean("org.apache.jetspeed.security.spi.UserSecurityHandler"); - rsh = (RoleSecurityHandler) ctx.getBean("org.apache.jetspeed.security.spi.RoleSecurityHandler"); - gsh = (GroupSecurityHandler) ctx.getBean("org.apache.jetspeed.security.spi.GroupSecurityHandler"); - smh = (SecurityMappingHandler) ctx.getBean("org.apache.jetspeed.security.spi.SecurityMappingHandler"); - - // Security Providers. - AuthenticationProvider atnProvider = (AuthenticationProvider) ctx.getBean("org.apache.jetspeed.security.AuthenticationProvider"); + securityAccess = (SecurityAccess) ctx + .getBean("org.apache.jetspeed.security.spi.SecurityAccess"); + ch = (CredentialHandler) ctx + .getBean("org.apache.jetspeed.security.spi.CredentialHandler"); + ush = (UserSecurityHandler) ctx + .getBean("org.apache.jetspeed.security.spi.UserSecurityHandler"); + rsh = (RoleSecurityHandler) ctx + .getBean("org.apache.jetspeed.security.spi.RoleSecurityHandler"); + gsh = (GroupSecurityHandler) ctx + .getBean("org.apache.jetspeed.security.spi.GroupSecurityHandler"); + smh = (SecurityMappingHandler) ctx + .getBean("org.apache.jetspeed.security.spi.SecurityMappingHandler"); + + // Security Providers. + AuthenticationProvider atnProvider = (AuthenticationProvider) ctx + .getBean("org.apache.jetspeed.security.AuthenticationProvider"); List atnProviders = new ArrayList(); atnProviders.add(atnProvider); - - - AuthenticationProviderProxy atnProviderProxy = (AuthenticationProviderProxy) ctx.getBean("org.apache.jetspeed.security.AuthenticationProviderProxy"); - securityProvider = new SecurityProviderImpl(atnProviderProxy, rsh, gsh, smh); - - securityProvider = (SecurityProvider) ctx.getBean("org.apache.jetspeed.security.SecurityProvider"); - - ums = (UserManager) ctx.getBean("org.apache.jetspeed.security.UserManager"); - gms = (GroupManager) ctx.getBean("org.apache.jetspeed.security.GroupManager"); - rms = (RoleManager) ctx.getBean("org.apache.jetspeed.security.RoleManager"); - + + AuthenticationProviderProxy atnProviderProxy = (AuthenticationProviderProxy) ctx + .getBean("org.apache.jetspeed.security.AuthenticationProviderProxy"); + securityProvider = new SecurityProviderImpl(atnProviderProxy, rsh, gsh, + smh); + + securityProvider = (SecurityProvider) ctx + .getBean("org.apache.jetspeed.security.SecurityProvider"); + + ums = (UserManager) ctx + .getBean("org.apache.jetspeed.security.UserManager"); + gms = (GroupManager) ctx + .getBean("org.apache.jetspeed.security.GroupManager"); + rms = (RoleManager) ctx + .getBean("org.apache.jetspeed.security.RoleManager"); + // Authorization. - pms = (PermissionManager) ctx.getBean("org.apache.jetspeed.security.PermissionManager"); - - new JetspeedActions(new String[] {"secure"}, new String[] {}); + pms = (PermissionManager) ctx + .getBean("org.apache.jetspeed.security.PermissionManager"); + + new JetspeedActions(new String[] + {"secure"}, new String[] + {}); } /** @@ -132,8 +148,7 @@ for (Iterator iter = subject.getPrincipals().iterator(); iter.hasNext();) { Object element = iter.next(); - if (claz.isInstance(element)) - principals.add(element); + if (claz.isInstance(element)) principals.add(element); } return principals; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestAggregationHierarchy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestAggregationHierarchy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestAggregationHierarchy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -45,7 +45,8 @@ protected void setUp() throws Exception { super.setUp(); - ums = new UserManagerImpl(securityProvider, new AggregationHierarchyResolver(), + ums = new UserManagerImpl(securityProvider, + new AggregationHierarchyResolver(), new AggregationHierarchyResolver()); } @@ -79,7 +80,8 @@ } catch (SecurityException sex) { - assertTrue("user exists. should not have thrown an exception.", false); + assertTrue("user exists. should not have thrown an exception.", + false); } assertNotNull("user is null", user); @@ -104,17 +106,19 @@ assertNotNull("subject is null", subject); Collection principals = getPrincipals(subject, RolePrincipal.class); assertEquals("should have 3 principals;", 3, principals.size()); - assertTrue("should contain rootrole", principals.contains(new RolePrincipalImpl("rootrole"))); - assertTrue("should contain rootrole.childrole1", principals.contains(new RolePrincipalImpl( - "rootrole.childrole1"))); - assertTrue("should contain rootrole.childrole2", principals.contains(new RolePrincipalImpl( - "rootrole.childrole2"))); + assertTrue("should contain rootrole", principals + .contains(new RolePrincipalImpl("rootrole"))); + assertTrue("should contain rootrole.childrole1", principals + .contains(new RolePrincipalImpl("rootrole.childrole1"))); + assertTrue("should contain rootrole.childrole2", principals + .contains(new RolePrincipalImpl("rootrole.childrole2"))); rms.removeRoleFromUser("test", "rootrole"); user = ums.getUser("test"); principals = getPrincipals(user.getSubject(), RolePrincipal.class); - assertEquals("should not have any principals;", 0, principals.size()); + assertEquals("should not have any principals;", 0, principals + .size()); } catch (SecurityException sex) @@ -132,14 +136,15 @@ Collection principals = getPrincipals(subject, RolePrincipal.class); assertEquals("shoud have 1 principal;", 1, principals.size()); - assertTrue("should contain rootrole.childrole1", principals.contains(new RolePrincipalImpl( - "rootrole.childrole1"))); + assertTrue("should contain rootrole.childrole1", principals + .contains(new RolePrincipalImpl("rootrole.childrole1"))); rms.removeRoleFromUser("test", "rootrole.childrole1"); user = ums.getUser("test"); principals = getPrincipals(user.getSubject(), RolePrincipal.class); - assertEquals("should not have any principals;", 0, principals.size()); + assertEquals("should not have any principals;", 0, principals + .size()); } catch (SecurityException sex) @@ -158,14 +163,14 @@ { try { - if (ums.userExists("test")) - ums.removeUser("test"); - if (rms.roleExists("rootrole")) - rms.removeRole("rootrole"); + if (ums.userExists("test")) ums.removeUser("test"); + if (rms.roleExists("rootrole")) rms.removeRole("rootrole"); } catch (SecurityException sex) { - System.out.println("could not remove test users. exception caught: " + sex); + System.out + .println("could not remove test users. exception caught: " + + sex); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestAuthenticationProviderProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestAuthenticationProviderProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestAuthenticationProviderProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,16 +37,18 @@ * Unit testing for {@link TestAuthenticationProviderProxy}. * </p> * - * TODO Needs an LDAP server configured for most of those tests to be valid. - * Commented until embedded ldap is supported. + * TODO Needs an LDAP server configured for most of those tests to be valid. + * Commented until embedded ldap is supported. * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat </a> */ public class TestAuthenticationProviderProxy extends AbstractSecurityTestcase { - int userCount = 0; - int usersAdded = 0; - + + int userCount = 0; + + int usersAdded = 0; + /** * @see junit.framework.TestCase#setUp() */ @@ -62,8 +64,9 @@ // CredentialHandler ldapCh = new LdapCredentialHandler(); // Security Providers. - AuthenticationProvider defaultAtnProvider = new AuthenticationProviderImpl("DefaultAuthenticator", - "The default authenticator", "login.conf", ch, ush); + AuthenticationProvider defaultAtnProvider = new AuthenticationProviderImpl( + "DefaultAuthenticator", "The default authenticator", + "login.conf", ch, ush); // AuthenticationProvider ldapAtnProvider = new // AuthenticationProviderImpl("LdapAuthenticator", "The ldap // authenticator", ldapCh, ldapUsh); @@ -71,11 +74,12 @@ List atnProviders = new ArrayList(); atnProviders.add(defaultAtnProvider); // atnProviders.add(ldapAtnProvider); - AuthenticationProviderProxy atnProviderProxy = new AuthenticationProviderProxyImpl(atnProviders, - "DefaultAuthenticator"); + AuthenticationProviderProxy atnProviderProxy = new AuthenticationProviderProxyImpl( + atnProviders, "DefaultAuthenticator"); // Need to override the AbstractSecurityTestcase behavior. - securityProvider = new SecurityProviderImpl(atnProviderProxy, rsh, gsh, smh); + securityProvider = new SecurityProviderImpl(atnProviderProxy, rsh, gsh, + smh); ums = new UserManagerImpl(securityProvider); gms = new GroupManagerImpl(securityProvider); rms = new RoleManagerImpl(securityProvider); @@ -121,7 +125,8 @@ // From RDBMS. User user = ums.getUser("anonuser1"); assertNotNull(user); - assertEquals("anonuser1", SecurityHelper.getPrincipal(user.getSubject(), UserPrincipal.class).getName()); + assertEquals("anonuser1", SecurityHelper.getPrincipal( + user.getSubject(), UserPrincipal.class).getName()); // Authenticate. // From Ldap. @@ -140,9 +145,9 @@ users.next(); count++; } - + // assertEquals(8, count); - + assertEquals(userCount + usersAdded, count); } catch (SecurityException sex) @@ -159,96 +164,56 @@ * </p> */ /* - public void testRoleManager() - { - initTestData(); + * public void testRoleManager() { initTestData(); + * + * try { // Add user to role. // Mapping only. rms.addRoleToUser("ldap1", + * "testrole1.subrole1"); // Get role mapping. Collection roles = + * rms.getRolesForUser("ldap1"); assertNotNull(roles); // Given the + * hierarchy resolution. Should contain 2 roles. assertEquals("should + * contain 2 roles", 2, roles.size()); // Is user in roles? + * assertTrue(rms.isUserInRole("ldap1", "testrole1")); + * assertTrue(rms.isUserInRole("ldap1", "testrole1.subrole1")); // Remove + * role mapping. rms.removeRoleFromUser("ldap1", "testrole1.subrole1"); // + * Get role mapping. roles = rms.getRolesForUser("ldap1"); + * assertNotNull(roles); assertEquals("should not contain any role", 0, + * roles.size()); // The mapping entry should be gone. + * assertNull(securityAccess.getInternalUserPrincipal("ldap1", true)); // Is + * user in roles? assertFalse(rms.isUserInRole("ldap1", "testrole1")); + * assertFalse(rms.isUserInRole("ldap1", "testrole1.subrole1")); } catch + * (SecurityException sex) { assertTrue("security exception caught: " + sex, + * false); } + * + * destroyTestData(); } + */ - try - { - // Add user to role. - // Mapping only. - rms.addRoleToUser("ldap1", "testrole1.subrole1"); - // Get role mapping. - Collection roles = rms.getRolesForUser("ldap1"); - assertNotNull(roles); - // Given the hierarchy resolution. Should contain 2 roles. - assertEquals("should contain 2 roles", 2, roles.size()); - - // Is user in roles? - assertTrue(rms.isUserInRole("ldap1", "testrole1")); - assertTrue(rms.isUserInRole("ldap1", "testrole1.subrole1")); - - // Remove role mapping. - rms.removeRoleFromUser("ldap1", "testrole1.subrole1"); - // Get role mapping. - roles = rms.getRolesForUser("ldap1"); - assertNotNull(roles); - assertEquals("should not contain any role", 0, roles.size()); - - // The mapping entry should be gone. - assertNull(securityAccess.getInternalUserPrincipal("ldap1", true)); - - // Is user in roles? - assertFalse(rms.isUserInRole("ldap1", "testrole1")); - assertFalse(rms.isUserInRole("ldap1", "testrole1.subrole1")); - } - catch (SecurityException sex) - { - assertTrue("security exception caught: " + sex, false); - } - - destroyTestData(); - } - */ - /** * <p> * Test group manager. * </p> */ /* - public void testGroupManager() - { - initTestData(); + * public void testGroupManager() { initTestData(); + * + * try { // Add user to group. // Mapping only. gms.addUserToGroup("ldap1", + * "testgroup1.subgroup1"); // Get group mapping. Collection groups = + * gms.getGroupsForUser("ldap1"); assertNotNull(groups); // Given the + * hierarchy resolution. Should contain 2 groups. assertEquals("should + * contain 2 groups", 2, groups.size()); // Is user in groups? + * assertTrue(gms.isUserInGroup("ldap1", "testgroup1")); + * assertTrue(gms.isUserInGroup("ldap1", "testgroup1.subgroup1")); // Remove + * group mapping. gms.removeUserFromGroup("ldap1", "testgroup1.subgroup1"); // + * Get group mapping. groups = gms.getGroupsForUser("ldap1"); + * assertNotNull(groups); assertEquals("should not contain any group", 0, + * groups.size()); // The mapping entry should be gone. + * assertNull(securityAccess.getInternalUserPrincipal("ldap1", true)); // Is + * user in groups? assertFalse(gms.isUserInGroup("ldap1", "testgroup1")); + * assertFalse(gms.isUserInGroup("ldap1", "testgroup1.subgroup1")); } catch + * (SecurityException sex) { assertTrue("security exception caught: " + sex, + * false); } + * + * destroyTestData(); } + */ - try - { - // Add user to group. - // Mapping only. - gms.addUserToGroup("ldap1", "testgroup1.subgroup1"); - // Get group mapping. - Collection groups = gms.getGroupsForUser("ldap1"); - assertNotNull(groups); - // Given the hierarchy resolution. Should contain 2 groups. - assertEquals("should contain 2 groups", 2, groups.size()); - - // Is user in groups? - assertTrue(gms.isUserInGroup("ldap1", "testgroup1")); - assertTrue(gms.isUserInGroup("ldap1", "testgroup1.subgroup1")); - - // Remove group mapping. - gms.removeUserFromGroup("ldap1", "testgroup1.subgroup1"); - // Get group mapping. - groups = gms.getGroupsForUser("ldap1"); - assertNotNull(groups); - assertEquals("should not contain any group", 0, groups.size()); - - // The mapping entry should be gone. - assertNull(securityAccess.getInternalUserPrincipal("ldap1", true)); - - // Is user in groups? - assertFalse(gms.isUserInGroup("ldap1", "testgroup1")); - assertFalse(gms.isUserInGroup("ldap1", "testgroup1.subgroup1")); - } - catch (SecurityException sex) - { - assertTrue("security exception caught: " + sex, false); - } - - destroyTestData(); - } - */ - /** * <p> * Init test data. @@ -256,29 +221,32 @@ */ private void initTestData() { - final String[] users = new String[] { "anonuser1", "anonuser2", "anonuser3", "anonuser4", "anonuser5", }; - final String[] roles = new String[] { "testrole1", "testrole1.subrole1", "testrole1.subrole1.subrole2", - "testrole2", "testrole2.subrole1" }; - final String[] groups = new String[] { "testgroup1", "testgroup1.subgroup1", "testgroup1.subgroup1.subgroup2", - "testgroup2", "testgroup2.subgroup1" }; + final String[] users = new String[] + {"anonuser1", "anonuser2", "anonuser3", "anonuser4", "anonuser5",}; + final String[] roles = new String[] + {"testrole1", "testrole1.subrole1", "testrole1.subrole1.subrole2", + "testrole2", "testrole2.subrole1"}; + final String[] groups = new String[] + {"testgroup1", "testgroup1.subgroup1", + "testgroup1.subgroup1.subgroup2", "testgroup2", + "testgroup2.subgroup1"}; - - //before we adding users make sure we know how mnay we have + // before we adding users make sure we know how mnay we have try { - Iterator it = ums.getUsers(""); - userCount = 0; - while (it.hasNext()) - { - it.next(); - userCount++; - } + Iterator it = ums.getUsers(""); + userCount = 0; + while (it.hasNext()) + { + it.next(); + userCount++; + } } catch (Exception e) { - + } - + usersAdded = 0; for (int i = 0; i < users.length; i++) { @@ -333,7 +301,8 @@ while (userIter.hasNext()) { user = (User) userIter.next(); - userName = SecurityHelper.getPrincipal(user.getSubject(), UserPrincipal.class).getName(); + userName = SecurityHelper.getPrincipal(user.getSubject(), + UserPrincipal.class).getName(); if (!userName.equals(ums.getAnonymousUser())) { ums.removeUser(userName); @@ -345,10 +314,13 @@ System.err.println(e.toString()); } - final String[] roles = new String[] { "testrole1", "testrole1.subrole1", "testrole1.subrole1.subrole2", - "testrole2", "testrole2.subrole1" }; - final String[] groups = new String[] { "testgroup1", "testgroup1.subgroup1", "testgroup1.subgroup1.subgroup2", - "testgroup2", "testgroup2.subgroup1" }; + final String[] roles = new String[] + {"testrole1", "testrole1.subrole1", "testrole1.subrole1.subrole2", + "testrole2", "testrole2.subrole1"}; + final String[] groups = new String[] + {"testgroup1", "testgroup1.subgroup1", + "testgroup1.subgroup1.subgroup2", "testgroup2", + "testgroup2.subgroup1"}; for (int i = 0; i < roles.length; i++) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestGeneralizationHierarchy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestGeneralizationHierarchy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestGeneralizationHierarchy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,10 +29,13 @@ import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; /** - * <p>Unit testing for {@link GeneralizationHierarchyResolver}.</p> - * + * <p> + * Unit testing for {@link GeneralizationHierarchyResolver}. + * </p> + * * @author <a href="mailto:Artem.Grinshtein ¡÷ t-systems.com">Artem Grinshtein</a> - * @version $Id: TestGeneralizationHierarchy.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: TestGeneralizationHierarchy.java 516448 2007-03-09 16:25:47Z + * ate $ */ public class TestGeneralizationHierarchy extends AbstractSecurityTestcase { @@ -43,32 +46,33 @@ protected void setUp() throws Exception { super.setUp(); - ums = new UserManagerImpl(securityProvider, new GeneralizationHierarchyResolver(), new GeneralizationHierarchyResolver()); + ums = new UserManagerImpl(securityProvider, + new GeneralizationHierarchyResolver(), + new GeneralizationHierarchyResolver()); } - + /** * @see junit.framework.TestCase#tearDown() */ public void tearDown() throws Exception - { + { destroyUserObject(); super.tearDown(); } - - public static Test suite() { - return new TestSuite(TestGeneralizationHierarchy.class); + return new TestSuite(TestGeneralizationHierarchy.class); } - /** - * <p>Test RoleManager.</p> + * <p> + * Test RoleManager. + * </p> */ public void testRoleManager() { - + User user = null; try { @@ -77,100 +81,97 @@ } catch (SecurityException sex) { - assertTrue("user exists. should not have thrown an exception.", false); + assertTrue("user exists. should not have thrown an exception.", + false); } assertNotNull("user is null", user); - + try { rms.addRole("rootrole"); rms.addRole("rootrole.childrole1"); rms.addRole("rootrole.childrole2"); - + } catch (SecurityException sex) { assertTrue("add roles. should not have thrown an exception.", false); } - + try { - rms.addRoleToUser("test","rootrole"); - + rms.addRoleToUser("test", "rootrole"); + user = ums.getUser("test"); Subject subject = user.getSubject(); assertNotNull("subject is null", subject); Collection principals = getPrincipals(subject, RolePrincipal.class); - assertEquals("shoud have one principal;", 1 , principals.size()); - - assertTrue( - "should contain rootrole", - principals.contains(new RolePrincipalImpl("rootrole"))); - - rms.removeRoleFromUser("test","rootrole"); - + assertEquals("shoud have one principal;", 1, principals.size()); + + assertTrue("should contain rootrole", principals + .contains(new RolePrincipalImpl("rootrole"))); + + rms.removeRoleFromUser("test", "rootrole"); + user = ums.getUser("test"); - principals= getPrincipals(user.getSubject(),RolePrincipal.class); - assertEquals("shoud not have any principals;", 0,principals.size()); - + principals = getPrincipals(user.getSubject(), RolePrincipal.class); + assertEquals("shoud not have any principals;", 0, principals.size()); + } catch (SecurityException sex) { - assertTrue("test with parent role "+sex.getMessage(), false); + assertTrue("test with parent role " + sex.getMessage(), false); } - + try { - rms.addRoleToUser("test","rootrole.childrole1"); - + rms.addRoleToUser("test", "rootrole.childrole1"); + user = ums.getUser("test"); Subject subject = user.getSubject(); assertNotNull("subject is null", subject); - Collection principals=getPrincipals(subject,RolePrincipal.class); - assertEquals("expected 2 principals;", 2,principals.size()); - - assertTrue( - "should contain rootrole", - principals.contains(new RolePrincipalImpl("rootrole"))); - - assertTrue( - "should contain rootrole", - principals.contains(new RolePrincipalImpl("rootrole.childrole1"))); - - rms.removeRoleFromUser("test","rootrole.childrole1"); - + Collection principals = getPrincipals(subject, RolePrincipal.class); + assertEquals("expected 2 principals;", 2, principals.size()); + + assertTrue("should contain rootrole", principals + .contains(new RolePrincipalImpl("rootrole"))); + + assertTrue("should contain rootrole", principals + .contains(new RolePrincipalImpl("rootrole.childrole1"))); + + rms.removeRoleFromUser("test", "rootrole.childrole1"); + user = ums.getUser("test"); - principals=getPrincipals(user.getSubject(),RolePrincipal.class); - assertEquals("shoud not have any principals;", 0,principals.size()); - + principals = getPrincipals(user.getSubject(), RolePrincipal.class); + assertEquals("shoud not have any principals;", 0, principals.size()); + } catch (SecurityException sex) { - assertTrue("test with child role "+sex.getMessage(), false); + assertTrue("test with child role " + sex.getMessage(), false); } - - + } - - - /** - * <p>Destroy user test object.</p> + * <p> + * Destroy user test object. + * </p> */ protected void destroyUserObject() { try { - + if (ums.userExists("test")) ums.removeUser("test"); if (rms.roleExists("rootrole")) rms.removeRole("rootrole"); - - + } catch (SecurityException sex) { - System.out.println("could not remove test users. exception caught: " + sex); + System.out + .println("could not remove test users. exception caught: " + + sex); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestGroupManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestGroupManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestGroupManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -75,7 +75,8 @@ } catch (SecurityException sex) { - assertTrue("group should not already exists. exception caught: " + sex, false); + assertTrue("group should not already exists. exception caught: " + + sex, false); } try { @@ -83,13 +84,15 @@ } catch (SecurityException sex) { - assertTrue("group should not already exists. exception caught: " + sex, false); + assertTrue("group should not already exists. exception caught: " + + sex, false); } // Add existing group. try { gms.addGroup("testgroup.newgroup0"); - assertTrue("group should already exists. exception not thrown.", false); + assertTrue("group should already exists. exception not thrown.", + false); } catch (SecurityException sex) { @@ -102,7 +105,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove group. exception caught: " + sex, false); + assertTrue("could not remove group. exception caught: " + sex, + false); } } @@ -129,25 +133,31 @@ try { gms.addUserToGroup("anonuser1", "testusertogroup1.group1"); - Collection principals = ums.getUser("anonuser1").getSubject().getPrincipals(); - assertTrue("anonuser1 should contain testusertogroup1.group1", principals.contains(new GroupPrincipalImpl( - "testusertogroup1.group1"))); + Collection principals = ums.getUser("anonuser1").getSubject() + .getPrincipals(); + assertTrue("anonuser1 should contain testusertogroup1.group1", + principals.contains(new GroupPrincipalImpl( + "testusertogroup1.group1"))); } catch (SecurityException sex) { - assertTrue("should add user to group. exception caught: " + sex, false); + assertTrue("should add user to group. exception caught: " + sex, + false); } // Add group with existing groups. try { gms.addUserToGroup("anonuser1", "testusertogroup1.group2"); - Collection principals = ums.getUser("anonuser1").getSubject().getPrincipals(); - assertTrue("anonuser1 should contain testusertogroup1.group2", principals.contains(new GroupPrincipalImpl( - "testusertogroup1.group2"))); + Collection principals = ums.getUser("anonuser1").getSubject() + .getPrincipals(); + assertTrue("anonuser1 should contain testusertogroup1.group2", + principals.contains(new GroupPrincipalImpl( + "testusertogroup1.group2"))); } catch (SecurityException sex) { - assertTrue("should add user to group. exception caught: " + sex, false); + assertTrue("should add user to group. exception caught: " + sex, + false); } // Add group when user does not exist. try @@ -176,7 +186,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and group. exception caught: " + sex, false); + assertTrue("could not remove user and group. exception caught: " + + sex, false); } } @@ -208,15 +219,17 @@ try { gms.removeGroup("testgroup1.group1"); - Collection principals = ums.getUser("anonuser2").getSubject().getPrincipals(); - // because of hierarchical groups with generalization strategy as default. Was 5 groups + 1 user, should now be 5 + Collection principals = ums.getUser("anonuser2").getSubject() + .getPrincipals(); + // because of hierarchical groups with generalization strategy as + // default. Was 5 groups + 1 user, should now be 5 // (4 groups + 1 user). assertEquals( - "principal size should be == 5 after removing testgroup1.group1, for principals: " + principals.toString(), - 5, - principals.size()); - assertFalse("anonuser2 should not contain testgroup1.group1", principals.contains(new GroupPrincipalImpl( - "testgroup1.group1"))); + "principal size should be == 5 after removing testgroup1.group1, for principals: " + + principals.toString(), 5, principals.size()); + assertFalse("anonuser2 should not contain testgroup1.group1", + principals.contains(new GroupPrincipalImpl( + "testgroup1.group1"))); } catch (SecurityException sex) { @@ -232,7 +245,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and group. exception caught: " + sex, false); + assertTrue("could not remove user and group. exception caught: " + + sex, false); } } @@ -247,7 +261,9 @@ try { gms.getGroup("testgroupdoesnotexist"); - assertTrue("group does not exist. should have thrown an exception.", false); + assertTrue( + "group does not exist. should have thrown an exception.", + false); } catch (SecurityException sex) { @@ -261,18 +277,21 @@ } catch (SecurityException sex) { - assertTrue("group exists. should not have thrown an exception.", false); + assertTrue("group exists. should not have thrown an exception.", + false); } assertNotNull("group is null", group); // Test the Principal. Principal groupPrincipal = group.getPrincipal(); assertNotNull("group principal is null", groupPrincipal); - assertEquals("expected group principal full path == testgetgroup", "testgetgroup", groupPrincipal.getName()); + assertEquals("expected group principal full path == testgetgroup", + "testgetgroup", groupPrincipal.getName()); // Test the Group Preferences. Preferences preferences = group.getPreferences(); - assertEquals("expected group node == /group/testgetgroup", SecurityHelper - .getPreferencesFullPath(groupPrincipal), preferences.absolutePath()); + assertEquals("expected group node == /group/testgetgroup", + SecurityHelper.getPreferencesFullPath(groupPrincipal), + preferences.absolutePath()); // Cleanup test. try @@ -281,7 +300,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove group. exception caught: " + sex, false); + assertTrue("could not remove group. exception caught: " + sex, + false); } } @@ -318,7 +338,8 @@ } catch (SecurityException sex) { - assertTrue("user exists. should not have thrown an exception: " + sex, false); + assertTrue("user exists. should not have thrown an exception: " + + sex, false); } // Cleanup test. @@ -330,7 +351,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and group. exception caught: " + sex, false); + assertTrue("could not remove user and group. exception caught: " + + sex, false); } } @@ -349,8 +371,10 @@ gms.addGroup("testrolegroupmapping.group1"); gms.addGroup("testrolegroupmapping.group2"); rms.addRoleToGroup("testuserrolemapping", "testrolegroupmapping"); - rms.addRoleToGroup("testuserrolemapping", "testrolegroupmapping.group1"); - rms.addRoleToGroup("testuserrolemapping", "testrolegroupmapping.group2"); + rms.addRoleToGroup("testuserrolemapping", + "testrolegroupmapping.group1"); + rms.addRoleToGroup("testuserrolemapping", + "testrolegroupmapping.group2"); } catch (SecurityException sex) { @@ -364,7 +388,8 @@ } catch (SecurityException sex) { - assertTrue("role exists. should not have thrown an exception: " + sex, false); + assertTrue("role exists. should not have thrown an exception: " + + sex, false); } // Cleanup test. @@ -375,7 +400,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove role and group. exception caught: " + sex, false); + assertTrue("could not remove role and group. exception caught: " + + sex, false); } } @@ -396,7 +422,8 @@ } catch (SecurityException sex) { - assertTrue("failed to init testRemoveUserFromGroup(), " + sex, false); + assertTrue("failed to init testRemoveUserFromGroup(), " + sex, + false); } try @@ -407,7 +434,8 @@ } catch (SecurityException sex) { - assertTrue("user exists. should not have thrown an exception: " + sex, false); + assertTrue("user exists. should not have thrown an exception: " + + sex, false); } // Cleanup test. @@ -418,7 +446,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and group. exception caught: " + sex, false); + assertTrue("could not remove user and group. exception caught: " + + sex, false); } } @@ -439,17 +468,22 @@ } catch (SecurityException sex) { - assertTrue("failed to init testRemoveUserFromGroup(), " + sex, false); + assertTrue("failed to init testRemoveUserFromGroup(), " + sex, + false); } try { - boolean isUserInGroup = gms.isUserInGroup("anonuser3", "testgroup1.group1"); - assertTrue("anonuser3 should be in group testgroup1.group1", isUserInGroup); + boolean isUserInGroup = gms.isUserInGroup("anonuser3", + "testgroup1.group1"); + assertTrue("anonuser3 should be in group testgroup1.group1", + isUserInGroup); } catch (SecurityException sex) { - assertTrue("user and group exist. should not have thrown an exception: " + sex, false); + assertTrue( + "user and group exist. should not have thrown an exception: " + + sex, false); } // Cleanup test. @@ -460,7 +494,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and group. exception caught: " + sex, false); + assertTrue("could not remove user and group. exception caught: " + + sex, false); } } @@ -469,12 +504,13 @@ * Test get groups. * </p> * - * @throws Exception Throws an exception. + * @throws Exception + * Throws an exception. */ public void testGetGroups() throws Exception { - int groupCount = 0; - int groupAdded = 0; + int groupCount = 0; + int groupAdded = 0; Iterator it = gms.getGroups(""); while (it.hasNext()) { @@ -483,7 +519,7 @@ groupCount++; } - ums.addUser("notme", "one-pw"); + ums.addUser("notme", "one-pw"); gms.addGroup("g1"); gms.addGroup("g2"); gms.addGroup("g3"); @@ -500,10 +536,11 @@ gms.removeGroup("g1"); gms.removeGroup("g2"); gms.removeGroup("g3"); - assertTrue("group count should be " + (groupAdded + groupCount), count == (groupAdded + groupCount)); - + assertTrue("group count should be " + (groupAdded + groupCount), + count == (groupAdded + groupCount)); + } - + /** * <p> * Destroy group test objects. Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestLoginModule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestLoginModule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestLoginModule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,7 +33,12 @@ */ public class TestLoginModule extends AbstractSecurityTestcase { - /** <p>The JAAS login context.</p> */ + + /** + * <p> + * The JAAS login context. + * </p> + */ private LoginContext loginContext = null; /** @@ -45,8 +50,10 @@ initUserObject(); // Set up login context. - try { - PassiveCallbackHandler pch = new PassiveCallbackHandler("anonlogin", "password"); + try + { + PassiveCallbackHandler pch = new PassiveCallbackHandler( + "anonlogin", "password"); loginContext = new LoginContext("Jetspeed", pch); } catch (LoginException le) @@ -63,7 +70,7 @@ { destroyUserObject(); super.tearDown(); - + } public static Test suite() @@ -75,21 +82,27 @@ public void testLogin() throws LoginException { loginContext.login(); - Principal found = SecurityHelper.getPrincipal(loginContext.getSubject(), UserPrincipal.class); + Principal found = SecurityHelper.getPrincipal( + loginContext.getSubject(), UserPrincipal.class); assertNotNull("found principal is null", found); - assertTrue("found principal should be anonlogin, " + found.getName(), found.getName().equals((new UserPrincipalImpl("anonlogin")).getName())); + assertTrue("found principal should be anonlogin, " + found.getName(), + found.getName().equals( + (new UserPrincipalImpl("anonlogin")).getName())); } - + public void testLogout() throws LoginException { loginContext.login(); loginContext.logout(); - Principal found = SecurityHelper.getBestPrincipal(loginContext.getSubject(), UserPrincipal.class); + Principal found = SecurityHelper.getBestPrincipal(loginContext + .getSubject(), UserPrincipal.class); assertNull("found principal is not null", found); } /** - * <p>Initialize user test object.</p> + * <p> + * Initialize user test object. + * </p> */ protected void initUserObject() { @@ -103,7 +116,9 @@ } /** - * <p>Destroy user test object.</p> + * <p> + * Destroy user test object. + * </p> */ protected void destroyUserObject() throws Exception { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestPermissionManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestPermissionManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestPermissionManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -42,18 +42,22 @@ import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; /** - * <p>Unit testing for {@link PermissionManager}.</p> - * + * <p> + * Unit testing for {@link PermissionManager}. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public class TestPermissionManager extends AbstractSecurityTestcase { + private static final Comparator principalComparator = new Comparator() { public int compare(Object arg0, Object arg1) { - return ((Principal)arg0).getName().compareTo(((Principal)arg1).getName()); + return ((Principal) arg0).getName().compareTo( + ((Principal) arg1).getName()); } }; @@ -64,14 +68,14 @@ { super.setUp(); } - + /** * @see junit.framework.TestCase#tearDown() */ public void tearDown() throws Exception { destroyPermissions(); - super.tearDown(); + super.tearDown(); } public static Test suite() @@ -80,72 +84,78 @@ return new TestSuite(TestPermissionManager.class); } - public void testWildcardPermissionCheck() - throws Exception + public void testWildcardPermissionCheck() throws Exception { - ////////////////////////////////////////////////////////////////////////// + // //////////////////////////////////////////////////////////////////////// // setup - //////////// + // ////////// UserPrincipal adminUser = new UserPrincipalImpl("adminTEST"); UserPrincipal userUser = new UserPrincipalImpl("userTEST"); - PortletPermission adminPerm = new PortletPermission("adminTEST::*", "view, edit"); - PortletPermission userPerm = new PortletPermission("demoTEST::*", "view, edit"); + PortletPermission adminPerm = new PortletPermission("adminTEST::*", + "view, edit"); + PortletPermission userPerm = new PortletPermission("demoTEST::*", + "view, edit"); RolePrincipal adminRole = new RolePrincipalImpl("adminTEST"); RolePrincipal userRole = new RolePrincipalImpl("userTEST"); - + try { ums.addUser(adminUser.getName(), "password"); - ums.addUser(userUser.getName(), "password"); + ums.addUser(userUser.getName(), "password"); rms.addRole(adminRole.getName()); - rms.addRole(userRole.getName()); + rms.addRole(userRole.getName()); rms.addRoleToUser(adminUser.getName(), adminRole.getName()); rms.addRoleToUser(userUser.getName(), userRole.getName()); - rms.addRoleToUser(adminUser.getName(), userRole.getName()); + rms.addRoleToUser(adminUser.getName(), userRole.getName()); pms.addPermission(adminPerm); pms.addPermission(userPerm); pms.grantPermission(adminRole, adminPerm); - pms.grantPermission(userRole, userPerm); + pms.grantPermission(userRole, userPerm); } catch (SecurityException sex) { - assertTrue("failed to init testRemovePrincipalPermissions(), " + sex, false); + assertTrue("failed to init testRemovePrincipalPermissions(), " + + sex, false); } - - ////////////////////////////////////////////////////////////////////////// + + // //////////////////////////////////////////////////////////////////////// // Run Test - //////////// + // ////////// Set adminPrincipals = new PrincipalsSet(); Set adminPublicCredentials = new HashSet(); Set adminPrivateCredentials = new HashSet(); Set userPrincipals = new PrincipalsSet(); Set userPublicCredentials = new HashSet(); Set userPrivateCredentials = new HashSet(); - + adminPrincipals.add(adminUser); adminPrincipals.add(adminRole); adminPrincipals.add(userRole); userPrincipals.add(userUser); userPrincipals.add(userRole); - + try { - Subject adminSubject = new Subject(true, adminPrincipals, adminPublicCredentials, adminPrivateCredentials); - Subject userSubject = new Subject(true, userPrincipals, userPublicCredentials, userPrivateCredentials); - + Subject adminSubject = new Subject(true, adminPrincipals, + adminPublicCredentials, adminPrivateCredentials); + Subject userSubject = new Subject(true, userPrincipals, + userPublicCredentials, userPrivateCredentials); + boolean access = pms.checkPermission(adminSubject, adminPerm); - assertTrue("access to admin Perm should be granted to Admin ", access); - + assertTrue("access to admin Perm should be granted to Admin ", + access); + access = pms.checkPermission(adminSubject, userPerm); assertTrue("access to user should NOT be granted to Admin ", access); access = pms.checkPermission(userSubject, userPerm); assertTrue("access to User Perm should be granted to User ", access); - + access = pms.checkPermission(userSubject, adminPerm); - assertFalse("access to Admin Perm should NOT be granted to User ", access); - + assertFalse("access to Admin Perm should NOT be granted to User ", + access); + } catch (AccessControlException e) { @@ -153,47 +163,49 @@ } finally { - ////////////////////////////////////////////////////////////////////////// + // //////////////////////////////////////////////////////////////////////// // cleanup - //////////// + // ////////// try { ums.removeUser(adminUser.getName()); ums.removeUser(userUser.getName()); rms.removeRole(adminRole.getName()); rms.removeRole(userRole.getName()); - + pms.removePermission(adminPerm); pms.removePermission(userPerm); } catch (SecurityException sex) { - assertTrue("could not remove user and permission. exception caught: " + sex, false); - } + assertTrue( + "could not remove user and permission. exception caught: " + + sex, false); + } } - - + } - - public void testPermissionCheck() - throws Exception + + public void testPermissionCheck() throws Exception { - ////////////////////////////////////////////////////////////////////////// + // //////////////////////////////////////////////////////////////////////// // setup - //////////// + // ////////// UserPrincipal user = new UserPrincipalImpl("test"); - PortletPermission perm1 = new PortletPermission("PortletOne", "view, edit"); + PortletPermission perm1 = new PortletPermission("PortletOne", + "view, edit"); PortletPermission perm2 = new PortletPermission("PortletTwo", "view"); PortletPermission perm3 = new PortletPermission("PortletThree", "view"); - PortletPermission perm3a = new PortletPermission("PortletThreeA", "view, edit"); + PortletPermission perm3a = new PortletPermission("PortletThreeA", + "view, edit"); RolePrincipal role1 = new RolePrincipalImpl("Role1"); RolePrincipal role2 = new RolePrincipalImpl("Role2"); - + try { ums.addUser(user.getName(), "password"); rms.addRole(role1.getName()); - rms.addRole(role2.getName()); + rms.addRole(role2.getName()); rms.addRoleToUser(user.getName(), role1.getName()); rms.addRoleToUser(user.getName(), role2.getName()); pms.addPermission(perm1); @@ -201,17 +213,18 @@ pms.addPermission(perm3); pms.addPermission(perm3a); pms.grantPermission(user, perm1); - pms.grantPermission(role1, perm2); - pms.grantPermission(role2, perm3); + pms.grantPermission(role1, perm2); + pms.grantPermission(role2, perm3); } catch (SecurityException sex) { - assertTrue("failed to init testRemovePrincipalPermissions(), " + sex, false); + assertTrue("failed to init testRemovePrincipalPermissions(), " + + sex, false); } - - ////////////////////////////////////////////////////////////////////////// + + // //////////////////////////////////////////////////////////////////////// // Run Test - //////////// + // ////////// Set principals = new PrincipalsSet(); Set publicCredentials = new HashSet(); Set privateCredentials = new HashSet(); @@ -221,7 +234,8 @@ try { - Subject subject = new Subject(true, principals, publicCredentials, privateCredentials); + Subject subject = new Subject(true, principals, publicCredentials, + privateCredentials); boolean access = pms.checkPermission(subject, perm1); assertTrue("access to perm1 should be granted ", access); access = pms.checkPermission(subject, perm2); @@ -237,36 +251,40 @@ } finally { - ////////////////////////////////////////////////////////////////////////// + // //////////////////////////////////////////////////////////////////////// // cleanup - //////////// + // ////////// try { ums.removeUser(user.getName()); rms.removeRole(role1.getName()); - rms.removeRole(role2.getName()); + rms.removeRole(role2.getName()); pms.removePermission(perm1); pms.removePermission(perm2); pms.removePermission(perm3); - pms.removePermission(perm3a); + pms.removePermission(perm3a); } catch (SecurityException sex) { - assertTrue("could not remove user and permission. exception caught: " + sex, false); - } + assertTrue( + "could not remove user and permission. exception caught: " + + sex, false); + } } - - + } - + /** - * <p>Test remove principal and associated permissions.</p> + * <p> + * Test remove principal and associated permissions. + * </p> */ public void testRemovePrincipalPermissions() { // Init test. UserPrincipal user = new UserPrincipalImpl("test"); - PortletPermission perm = new PortletPermission("anontestportlet", "view, edit"); + PortletPermission perm = new PortletPermission("anontestportlet", + "view, edit"); try { ums.addUser(user.getName(), "password"); @@ -275,20 +293,21 @@ } catch (SecurityException sex) { - assertTrue("failed to init testRemovePrincipalPermissions(), " + sex, false); + assertTrue("failed to init testRemovePrincipalPermissions(), " + + sex, false); } try { pms.removePermissions(user); Permissions permissions = pms.getPermissions(user); - assertEquals( - "permissions should be empty for user " + user.getName(), - 0, - (Collections.list(permissions.elements())).size()); + assertEquals("permissions should be empty for user " + + user.getName(), 0, (Collections.list(permissions + .elements())).size()); } catch (SecurityException sex) { - assertTrue("could not remove permission. exception caught: " + sex, false); + assertTrue("could not remove permission. exception caught: " + sex, + false); } // Cleanup test. try @@ -298,17 +317,23 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and permission. exception caught: " + sex, false); + assertTrue( + "could not remove user and permission. exception caught: " + + sex, false); } } /** - * <p>Test remove permission.</p> + * <p> + * Test remove permission. + * </p> */ public void testPermissionExists() { - PortletPermission perm1 = new PortletPermission("removepermission1", "view, edit, secure, minimized, maximized"); - PortletPermission perm2 = new PortletPermission("removepermission2", "view, edit, minimized, maximized"); + PortletPermission perm1 = new PortletPermission("removepermission1", + "view, edit, secure, minimized, maximized"); + PortletPermission perm2 = new PortletPermission("removepermission2", + "view, edit, minimized, maximized"); try { pms.addPermission(perm1); @@ -319,28 +344,33 @@ assertTrue("could not add permission, " + sex, false); } assertFalse(pms.permissionExists(perm2)); - - // Cleanup test. + + // Cleanup test. try { pms.removePermission(perm1); } catch (SecurityException sex) { - assertTrue("could not remove permission. exception caught: " + sex, false); + assertTrue("could not remove permission. exception caught: " + sex, + false); } } - + /** - * <p>Test remove permission.</p> + * <p> + * Test remove permission. + * </p> */ public void testRemovePermission() { // Init test. UserPrincipal user = new UserPrincipalImpl("removepermission"); RolePrincipal role = new RolePrincipalImpl("removepermissionrole"); - PortletPermission perm1 = new PortletPermission("removepermission1", "view, edit, secure, minimized, maximized"); - PortletPermission perm2 = new PortletPermission("removepermission2", "view, edit, minimized, maximized"); + PortletPermission perm1 = new PortletPermission("removepermission1", + "view, edit, secure, minimized, maximized"); + PortletPermission perm2 = new PortletPermission("removepermission2", + "view, edit, minimized, maximized"); try { ums.addUser(user.getName(), "password"); @@ -359,28 +389,25 @@ try { pms.removePermission(perm1); - Permissions permCol1 = pms.getPermissions(new UserPrincipalImpl("removepermission")); - assertTrue( - "should only contain permission == {name = " - + perm2.getName() - + "}, {action = " - + perm2.getActions() + Permissions permCol1 = pms.getPermissions(new UserPrincipalImpl( + "removepermission")); + assertTrue("should only contain permission == {name = " + + perm2.getName() + "}, {action = " + perm2.getActions() + "}, in collection of size == 1, actual size: " + (Collections.list(permCol1.elements())).size(), - validatePermissions(permCol1, perm2, 1)); - Permissions permCol2 = pms.getPermissions(new RolePrincipalImpl("removepermissionrole")); - assertTrue( - "should only contain permission == {name = " - + perm2.getName() - + "}, {action = " - + perm2.getActions() + validatePermissions(permCol1, perm2, 1)); + Permissions permCol2 = pms.getPermissions(new RolePrincipalImpl( + "removepermissionrole")); + assertTrue("should only contain permission == {name = " + + perm2.getName() + "}, {action = " + perm2.getActions() + "}, in collection of size == 1, actual size: " + (Collections.list(permCol2.elements())).size(), - validatePermissions(permCol2, perm2, 1)); + validatePermissions(permCol2, perm2, 1)); } catch (SecurityException sex) { - assertTrue("could not remove permission. exception caught: " + sex, false); + assertTrue("could not remove permission. exception caught: " + sex, + false); } // Cleanup test. try @@ -391,20 +418,26 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and permission. exception caught: " + sex, false); + assertTrue( + "could not remove user and permission. exception caught: " + + sex, false); } } /** - * <p>Test grant permission to principal.</p> + * <p> + * Test grant permission to principal. + * </p> */ public void testGrantPermission() { // Init test. UserPrincipal user1 = new UserPrincipalImpl("testgrantpermission1"); UserPrincipal user2 = new UserPrincipalImpl("testgrantpermission2"); - PortletPermission perm1 = new PortletPermission("testportlet", "view, minimized, secure"); - PortletPermission perm2 = new PortletPermission("testportlet", "view, minimized, maximized, secure"); + PortletPermission perm1 = new PortletPermission("testportlet", + "view, minimized, secure"); + PortletPermission perm2 = new PortletPermission("testportlet", + "view, minimized, maximized, secure"); try { ums.addUser(user2.getName(), "password"); @@ -416,11 +449,14 @@ assertTrue("failed to init testGrantPermission(), " + sex, false); } - // Test permission for new permission and new principal (does not exist). + // Test permission for new permission and new principal (does not + // exist). try { pms.grantPermission(user1, perm1); - assertTrue("principal does not exist. should have caught exception.", false); + assertTrue( + "principal does not exist. should have caught exception.", + false); } catch (SecurityException sex) { @@ -432,17 +468,15 @@ } catch (SecurityException sex) { - assertTrue("principal does not exist. caught exception, " + sex, false); + assertTrue("principal does not exist. caught exception, " + sex, + false); } Permissions permCol1 = pms.getPermissions(user2); - assertTrue( - "should contain permission == {name = " - + perm2.getName() - + "}, {action = " - + perm2.getActions() + assertTrue("should contain permission == {name = " + perm2.getName() + + "}, {action = " + perm2.getActions() + "}, in collection of size == 1, actual size: " + (Collections.list(permCol1.elements())).size(), - validatePermissions(permCol1, perm2, 1)); + validatePermissions(permCol1, perm2, 1)); // Test insert duplicate permission for same principal try { @@ -450,17 +484,15 @@ } catch (SecurityException sex) { - assertTrue("principal does not exist. caught exception, " + sex, false); + assertTrue("principal does not exist. caught exception, " + sex, + false); } Permissions permCol2 = pms.getPermissions(user2); - assertTrue( - "should contain permission == {name = " - + perm2.getName() - + "}, {action = " - + perm2.getActions() + assertTrue("should contain permission == {name = " + perm2.getName() + + "}, {action = " + perm2.getActions() + "}, in collection of size == 1, actual size: " + (Collections.list(permCol2.elements())).size(), - validatePermissions(permCol2, perm2, 1)); + validatePermissions(permCol2, perm2, 1)); // Cleanup test. try @@ -471,19 +503,25 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and permission. exception caught: " + sex, false); + assertTrue( + "could not remove user and permission. exception caught: " + + sex, false); } } /** - * <p>Test get permissions from a principal.</p> + * <p> + * Test get permissions from a principal. + * </p> */ public void testGetPrincipalPermissions() { // Init test. UserPrincipal user = new UserPrincipalImpl("anon"); - PortletPermission perm1 = new PortletPermission("anontestportlet", "view"); - PortletPermission perm2 = new PortletPermission("anontestportlet", "view, edit"); + PortletPermission perm1 = new PortletPermission("anontestportlet", + "view"); + PortletPermission perm2 = new PortletPermission("anontestportlet", + "view, edit"); try { ums.addUser(user.getName(), "password"); @@ -494,26 +532,21 @@ } catch (SecurityException sex) { - assertTrue("failed to init testGetPrincipalPermissions(), " + sex, false); + assertTrue("failed to init testGetPrincipalPermissions(), " + sex, + false); } Permissions permissions = pms.getPermissions(user); - assertTrue( - "should contain permission == {name = " - + perm1.getName() - + "}, {action = " - + perm1.getActions() + assertTrue("should contain permission == {name = " + perm1.getName() + + "}, {action = " + perm1.getActions() + "}, in collection of size == 2, actual size: " + (Collections.list(permissions.elements())).size(), - validatePermissions(permissions, perm1, 2)); - assertTrue( - "should contain permission == {name = " - + perm2.getName() - + "}, {action = " - + perm2.getActions() + validatePermissions(permissions, perm1, 2)); + assertTrue("should contain permission == {name = " + perm2.getName() + + "}, {action = " + perm2.getActions() + "}, in collection of size == 2, actual size: " + (Collections.list(permissions.elements())).size(), - validatePermissions(permissions, perm2, 2)); + validatePermissions(permissions, perm2, 2)); // Cleanup test. try @@ -524,12 +557,16 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and permission. exception caught: " + sex, false); + assertTrue( + "could not remove user and permission. exception caught: " + + sex, false); } } /** - * <p>Test get permissions from a collection of principals.</p> + * <p> + * Test get permissions from a collection of principals. + * </p> */ public void testGetPermissions() { @@ -539,10 +576,14 @@ RolePrincipal role2 = new RolePrincipalImpl("anonrole2"); GroupPrincipal group1 = new GroupPrincipalImpl("anongroup1"); GroupPrincipal group2 = new GroupPrincipalImpl("anongroup2"); - PortletPermission perm1 = new PortletPermission("anontestportlet", "view"); - PortletPermission perm2 = new PortletPermission("anontestportlet", "view, edit"); - PortletPermission perm3 = new PortletPermission("anontestportlet", "view, edit, secure"); - PortletPermission perm4 = new PortletPermission("anontestportlet", "view, edit, secure, minimized"); + PortletPermission perm1 = new PortletPermission("anontestportlet", + "view"); + PortletPermission perm2 = new PortletPermission("anontestportlet", + "view, edit"); + PortletPermission perm3 = new PortletPermission("anontestportlet", + "view, edit, secure"); + PortletPermission perm4 = new PortletPermission("anontestportlet", + "view, edit, secure, minimized"); try { ums.addUser(user.getName(), "password"); @@ -567,7 +608,8 @@ } catch (SecurityException sex) { - assertTrue("failed to init testGetPrincipalPermissions(), " + sex, false); + assertTrue("failed to init testGetPrincipalPermissions(), " + sex, + false); } ArrayList principals = new ArrayList(); @@ -577,38 +619,26 @@ principals.add(group1); principals.add(group2); Permissions permissions = pms.getPermissions(principals); - assertTrue( - "should contain permission == {name = " - + perm1.getName() - + "}, {action = " - + perm1.getActions() + assertTrue("should contain permission == {name = " + perm1.getName() + + "}, {action = " + perm1.getActions() + "}, in collection of size == 4, actual size: " + (Collections.list(permissions.elements())).size(), - validatePermissions(permissions, perm1, 4)); - assertTrue( - "should contain permission == {name = " - + perm2.getName() - + "}, {action = " - + perm2.getActions() + validatePermissions(permissions, perm1, 4)); + assertTrue("should contain permission == {name = " + perm2.getName() + + "}, {action = " + perm2.getActions() + "}, in collection of size == 4, actual size: " + (Collections.list(permissions.elements())).size(), - validatePermissions(permissions, perm2, 4)); - assertTrue( - "should contain permission == {name = " - + perm3.getName() - + "}, {action = " - + perm3.getActions() + validatePermissions(permissions, perm2, 4)); + assertTrue("should contain permission == {name = " + perm3.getName() + + "}, {action = " + perm3.getActions() + "}, in collection of size == 4, actual size: " + (Collections.list(permissions.elements())).size(), - validatePermissions(permissions, perm3, 4)); - assertTrue( - "should contain permission == {name = " - + perm4.getName() - + "}, {action = " - + perm4.getActions() + validatePermissions(permissions, perm3, 4)); + assertTrue("should contain permission == {name = " + perm4.getName() + + "}, {action = " + perm4.getActions() + "}, in collection of size == 4, actual size: " + (Collections.list(permissions.elements())).size(), - validatePermissions(permissions, perm4, 4)); + validatePermissions(permissions, perm4, 4)); // Cleanup test. try @@ -626,14 +656,18 @@ } /** - * <p>Test revoke permission.</p> + * <p> + * Test revoke permission. + * </p> */ public void testRevokePermission() { // Init test. UserPrincipal user = new UserPrincipalImpl("revokepermission"); - PortletPermission perm1 = new PortletPermission("revokepermission1", "view, edit, minimized, maximized"); - PortletPermission perm2 = new PortletPermission("revokepermission2", "view, edit, minimized, maximized"); + PortletPermission perm1 = new PortletPermission("revokepermission1", + "view, edit, minimized, maximized"); + PortletPermission perm2 = new PortletPermission("revokepermission2", + "view, edit, minimized, maximized"); try { ums.addUser(user.getName(), "password"); @@ -650,18 +684,16 @@ { pms.revokePermission(user, perm2); Permissions permCol = pms.getPermissions(user); - assertTrue( - "should only contain permission == {name = " - + perm1.getName() - + "}, {action = " - + perm1.getActions() + assertTrue("should only contain permission == {name = " + + perm1.getName() + "}, {action = " + perm1.getActions() + "}, in collection of size == 1, actual size: " + (Collections.list(permCol.elements())).size(), - validatePermissions(permCol, perm1, 1)); + validatePermissions(permCol, perm1, 1)); } catch (SecurityException sex) { - assertTrue("could not revoke permission. esception caught: " + sex, false); + assertTrue("could not revoke permission. esception caught: " + sex, + false); } // Cleanup test. try @@ -677,14 +709,21 @@ } /** - * <p>Validate whether permission belongs to permissions and whether the permissions - * size equals the size provided.</p> - * @param permissions The permissions. - * @param permission The permission to validate. - * @param size The permissions expected size. + * <p> + * Validate whether permission belongs to permissions and whether the + * permissions size equals the size provided. + * </p> + * + * @param permissions + * The permissions. + * @param permission + * The permission to validate. + * @param size + * The permissions expected size. * @return */ - private boolean validatePermissions(Permissions permissions, Permission permission, int size) + private boolean validatePermissions(Permissions permissions, + Permission permission, int size) { Enumeration permissionEnums = permissions.elements(); boolean hasPermission = false; @@ -703,7 +742,9 @@ } /** - * <p>Destroy permission test objects.</p> + * <p> + * Destroy permission test objects. + * </p> */ protected void destroyPermissions() { @@ -725,18 +766,29 @@ } catch (SecurityException sex) { - assertTrue("could not remove user, role and group. exception caught: " + sex, false); + assertTrue( + "could not remove user, role and group. exception caught: " + + sex, false); } // Remove permissions. - PortletPermission perm1 = new PortletPermission("anontestportlet", "view"); - PortletPermission perm2 = new PortletPermission("anontestportlet", "view, edit"); - PortletPermission perm3 = new PortletPermission("anontestportlet", "view, edit, secure"); - PortletPermission perm4 = new PortletPermission("anontestportlet", "view, edit, secure, minimized"); - PortletPermission perm5 = new PortletPermission("removepermission1", "view, edit, secure, minimized, maximized"); - PortletPermission perm6 = new PortletPermission("removepermission2", "view, edit, minimized, maximized"); - PortletPermission perm7 = new PortletPermission("revokepermission1", "view, edit, minimized, maximized"); - PortletPermission perm8 = new PortletPermission("revokepermission2", "view, edit, minimized, maximized"); - PortletPermission perm9 = new PortletPermission("testportlet", "view, minimized, secure"); + PortletPermission perm1 = new PortletPermission("anontestportlet", + "view"); + PortletPermission perm2 = new PortletPermission("anontestportlet", + "view, edit"); + PortletPermission perm3 = new PortletPermission("anontestportlet", + "view, edit, secure"); + PortletPermission perm4 = new PortletPermission("anontestportlet", + "view, edit, secure, minimized"); + PortletPermission perm5 = new PortletPermission("removepermission1", + "view, edit, secure, minimized, maximized"); + PortletPermission perm6 = new PortletPermission("removepermission2", + "view, edit, minimized, maximized"); + PortletPermission perm7 = new PortletPermission("revokepermission1", + "view, edit, minimized, maximized"); + PortletPermission perm8 = new PortletPermission("revokepermission2", + "view, edit, minimized, maximized"); + PortletPermission perm9 = new PortletPermission("testportlet", + "view, minimized, secure"); try { pms.removePermission(perm1); @@ -751,10 +803,12 @@ } catch (SecurityException sex) { - assertTrue("could not remove permissions. exception caught: " + sex, false); + assertTrue( + "could not remove permissions. exception caught: " + sex, + false); } } - + public void testUpdatePermission() { // Init test. @@ -768,7 +822,7 @@ rms.addRole(role1.getName()); rms.addRole(role2.getName()); rms.addRole(role3.getName()); - rms.addRole(role4.getName()); + rms.addRole(role4.getName()); pms.addPermission(perm1); } catch (SecurityException sex) @@ -776,7 +830,7 @@ assertTrue("failed to init testUpdatePermission(), " + sex, false); } - // Grant 1 and 2 + // Grant 1 and 2 try { pms.grantPermission(role1, perm1); @@ -784,18 +838,21 @@ } catch (SecurityException sex) { - assertTrue("failed to grant on testUpdatePermission. caught exception, " + sex, false); + assertTrue( + "failed to grant on testUpdatePermission. caught exception, " + + sex, false); } - Collection principals = pms.getPrincipals(perm1); - assertTrue("principal count should be 2 ", principals.size() == 2); - Object [] array = (Object[])principals.toArray(); + Collection principals = pms.getPrincipals(perm1); + assertTrue("principal count should be 2 ", principals.size() == 2); + Object[] array = (Object[]) principals.toArray(); Arrays.sort(array, principalComparator); assertTrue("element is Principal ", array[0] instanceof Principal); - assertTrue("first element not found ", ((Principal)array[0]).getName().equals("role1")); - assertTrue("second element not found ", ((Principal)array[1]).getName().equals("role2")); - - + assertTrue("first element not found ", ((Principal) array[0]).getName() + .equals("role1")); + assertTrue("second element not found ", ((Principal) array[1]) + .getName().equals("role2")); + // Try to update collection try { @@ -807,16 +864,21 @@ } catch (SecurityException sex) { - assertTrue("principal does not exist. caught exception, " + sex, false); + assertTrue("principal does not exist. caught exception, " + sex, + false); } principals = pms.getPrincipals(perm1); assertTrue("principal count should be 3 ", principals.size() == 3); - array = (Object[])principals.toArray(); + array = (Object[]) principals.toArray(); Arrays.sort(array, principalComparator); - assertTrue("first element should be [role1] but found ["+((Principal)array[0]).getName()+"]", ((Principal)array[0]).getName().equals("role1")); - assertTrue("second element not found ", ((Principal)array[1]).getName().equals("role3")); - assertTrue("third element not found ", ((Principal)array[2]).getName().equals("role4")); - + assertTrue("first element should be [role1] but found [" + + ((Principal) array[0]).getName() + "]", + ((Principal) array[0]).getName().equals("role1")); + assertTrue("second element not found ", ((Principal) array[1]) + .getName().equals("role3")); + assertTrue("third element not found ", ((Principal) array[2]).getName() + .equals("role4")); + // Cleanup test. try { @@ -828,8 +890,10 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and permission. exception caught: " + sex, false); + assertTrue( + "could not remove user and permission. exception caught: " + + sex, false); } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestRdbmsPolicy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestRdbmsPolicy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestRdbmsPolicy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -36,6 +36,7 @@ */ public class TestRdbmsPolicy extends AbstractSecurityTestcase { + /** * <p> * The JAAS login context. @@ -55,7 +56,8 @@ try { System.out.println("\t\t[TestRdbmsPolicy] Creating login context."); - PassiveCallbackHandler pch = new PassiveCallbackHandler("anon", "password"); + PassiveCallbackHandler pch = new PassiveCallbackHandler("anon", + "password"); loginContext = new LoginContext("Jetspeed", pch); loginContext.login(); } @@ -109,96 +111,92 @@ * </code></pre> * * <p> - * Such an entry would also test the Rdbms defaulting behavior if no entry is provided in the - * database for the tested Subject InternalUserPrincipal. + * Such an entry would also test the Rdbms defaulting behavior if no entry + * is provided in the database for the tested Subject InternalUserPrincipal. * </p> */ - /*public void testPermissionWithSubjectInContructor() - { - // InternalPermission should be granted. - PortletPermission perm1 = new PortletPermission("myportlet", "view", loginContext.getSubject()); - try - { - AccessController.checkPermission(perm1); - } - catch (AccessControlException ace) - { - assertTrue("did not authorize view permission on the portlet.", false); - } + /* + * public void testPermissionWithSubjectInContructor() { // + * InternalPermission should be granted. PortletPermission perm1 = new + * PortletPermission("myportlet", "view", loginContext.getSubject()); try { + * AccessController.checkPermission(perm1); } catch (AccessControlException + * ace) { assertTrue("did not authorize view permission on the portlet.", + * false); } // InternalPermission should be denied. PortletPermission perm2 = + * new PortletPermission("myportlet", "edit", loginContext.getSubject()); + * try { AccessController.checkPermission(perm2); assertTrue("did not deny + * edit permission on the portlet.", false); } catch (AccessControlException + * ace) { } // Subject is omitted. InternalPermission should be denied. + * PortletPermission perm3 = new PortletPermission("myportlet", "view"); try { + * AccessController.checkPermission(perm3); // assertTrue("did not deny + * permission with no subject passed.", false); } catch + * (AccessControlException ace) { } } + */ - // InternalPermission should be denied. - PortletPermission perm2 = new PortletPermission("myportlet", "edit", loginContext.getSubject()); - try - { - AccessController.checkPermission(perm2); - assertTrue("did not deny edit permission on the portlet.", false); - } - catch (AccessControlException ace) - { - } - - // Subject is omitted. InternalPermission should be denied. - PortletPermission perm3 = new PortletPermission("myportlet", "view"); - try - { - AccessController.checkPermission(perm3); - // assertTrue("did not deny permission with no subject passed.", false); - } - catch (AccessControlException ace) - { - } - }*/ - /** * <p> - * Test the policy with the default spring setting where the default underlying policy is not - * applied. + * Test the policy with the default spring setting where the default + * underlying policy is not applied. * </p> */ public void testPermissionWithSubjectInAccessControlContext() { - + // InternalPermission should be granted. try { - JSSubject.doAsPrivileged(loginContext.getSubject(), new PrivilegedAction() - { - public Object run() - { - PortletPermission perm1 = new PortletPermission("myportlet", "view"); - System.out.println("\t\t[TestRdbmsPolicy] Check access control for permission: [myportlet, view]"); - System.out.println("\t\t with policy: " + Policy.getPolicy().getClass().getName()); - AccessController.checkPermission(perm1); - return null; - } - }, null); + JSSubject.doAsPrivileged(loginContext.getSubject(), + new PrivilegedAction() + { + + public Object run() + { + PortletPermission perm1 = new PortletPermission( + "myportlet", "view"); + System.out + .println("\t\t[TestRdbmsPolicy] Check access control for permission: [myportlet, view]"); + System.out + .println("\t\t with policy: " + + Policy.getPolicy().getClass() + .getName()); + AccessController.checkPermission(perm1); + return null; + } + }, null); } catch (AccessControlException ace) { - assertTrue("did not authorize view permission on the portlet.", false); + assertTrue("did not authorize view permission on the portlet.", + false); } // Should be denied. try { - JSSubject.doAsPrivileged(loginContext.getSubject(), new PrivilegedAction() - { - public Object run() - { - PortletPermission perm2 = new PortletPermission("myportlet", "secure"); - System.out.println("\t\t[TestRdbmsPolicy] Check access control for permission: [myportlet, secure]"); - System.out.println("\t\t with policy: " + Policy.getPolicy().getClass().getName()); - AccessController.checkPermission(perm2); - return null; - } - }, null); + JSSubject.doAsPrivileged(loginContext.getSubject(), + new PrivilegedAction() + { + + public Object run() + { + PortletPermission perm2 = new PortletPermission( + "myportlet", "secure"); + System.out + .println("\t\t[TestRdbmsPolicy] Check access control for permission: [myportlet, secure]"); + System.out + .println("\t\t with policy: " + + Policy.getPolicy().getClass() + .getName()); + AccessController.checkPermission(perm2); + return null; + } + }, null); assertTrue("did not deny secure permission on the portlet.", false); } catch (AccessControlException ace) { } } - + /** * <p> * Test the policy with the default policy being evaluated as well. @@ -206,8 +204,10 @@ */ public void testPermissionWithSubjectInAccessControlContextAndDefaultPolicy() { - System.out.println("\n\n\t\t[TestRdbmsPolicy] Test with default Policy enabled."); - AuthorizationProvider atzProvider = (AuthorizationProvider) ctx.getBean("org.apache.jetspeed.security.AuthorizationProvider"); + System.out + .println("\n\n\t\t[TestRdbmsPolicy] Test with default Policy enabled."); + AuthorizationProvider atzProvider = (AuthorizationProvider) ctx + .getBean("org.apache.jetspeed.security.AuthorizationProvider"); atzProvider.useDefaultPolicy(true); testPermissionWithSubjectInAccessControlContext(); } @@ -228,7 +228,8 @@ } UserPrincipal user = new UserPrincipalImpl("anon"); PortletPermission perm1 = new PortletPermission("myportlet", "view"); - PortletPermission perm2 = new PortletPermission("myportlet", "view, edit"); + PortletPermission perm2 = new PortletPermission("myportlet", + "view, edit"); try { pms.addPermission(perm1); @@ -253,7 +254,8 @@ ums.removeUser("anon"); // Remove permissions. PortletPermission perm1 = new PortletPermission("myportlet", "view"); - PortletPermission perm2 = new PortletPermission("myportlet", "view, edit"); + PortletPermission perm2 = new PortletPermission("myportlet", + "view, edit"); pms.removePermission(perm1); pms.removePermission(perm2); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestRdbmsPolicyFolder.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestRdbmsPolicyFolder.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestRdbmsPolicyFolder.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,20 +26,23 @@ import junit.framework.Test; import junit.framework.TestSuite; -import org.apache.jetspeed.security.FolderPermission; -import org.apache.jetspeed.security.SecurityException; -import org.apache.jetspeed.security.UserPrincipal; import org.apache.jetspeed.security.impl.PassiveCallbackHandler; import org.apache.jetspeed.security.impl.UserPrincipalImpl; import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; /** - * @author <a href="mailto:christophe.lombart ¡÷ sword-technologies.com">Christophe Lombart</a> + * @author <a href="mailto:christophe.lombart ¡÷ sword-technologies.com">Christophe + * Lombart</a> * @version $Id: TestRdbmsPolicyFolder.java 517121 2007-03-12 07:45:49Z ate $ */ public class TestRdbmsPolicyFolder extends AbstractSecurityTestcase { - /** <p>The JAAS login context.</p> */ + + /** + * <p> + * The JAAS login context. + * </p> + */ private LoginContext loginContext = null; /** @@ -54,15 +57,18 @@ // Let's login in. try { - System.out.println("\t\t[TestRdbmsPolicy - Folder] Creating login context."); - PassiveCallbackHandler pch = new PassiveCallbackHandler("anon", "password"); + System.out + .println("\t\t[TestRdbmsPolicy - Folder] Creating login context."); + PassiveCallbackHandler pch = new PassiveCallbackHandler("anon", + "password"); loginContext = new LoginContext("jetspeed", pch); loginContext.login(); } catch (LoginException le) { le.printStackTrace(); - assertTrue("\t\t[TestRdbmsPolicy - Folder] Failed to setup test.", false); + assertTrue("\t\t[TestRdbmsPolicy - Folder] Failed to setup test.", + false); } } @@ -81,7 +87,9 @@ catch (LoginException le) { le.printStackTrace(); - assertTrue("\t\t[TestRdbmsPolicy - Folder] Failed to tear down test.", false); + assertTrue( + "\t\t[TestRdbmsPolicy - Folder] Failed to tear down test.", + false); } destroyUser(); super.tearDown(); @@ -95,7 +103,7 @@ /** * Test simple permission on one document - * + * */ public void testSimplePermission() { @@ -104,9 +112,11 @@ { JSSubject.doAs(loginContext.getSubject(), new PrivilegedAction() { + public Object run() { - FolderPermission perm1 = new FolderPermission("/files/test.xml", "edit"); + FolderPermission perm1 = new FolderPermission( + "/files/test.xml", "edit"); AccessController.checkPermission(perm1); return null; } @@ -114,7 +124,8 @@ } catch (AccessControlException ace) { - assertTrue("did not authorize view permission on the Folder.", false); + assertTrue("did not authorize view permission on the Folder.", + false); } // Should be denied. @@ -122,9 +133,11 @@ { JSSubject.doAs(loginContext.getSubject(), new PrivilegedAction() { + public Object run() { - FolderPermission perm2 = new FolderPermission("/files/test.xml", "secure"); + FolderPermission perm2 = new FolderPermission( + "/files/test.xml", "secure"); AccessController.checkPermission(perm2); return null; } @@ -137,8 +150,9 @@ } /** - * Test permissions with wild card (eg. /file/*) & with recursive setting (eg. /files/- ) - * + * Test permissions with wild card (eg. /file/*) & with recursive setting + * (eg. /files/- ) + * */ public void testAdvancedPermission() { @@ -147,9 +161,11 @@ { JSSubject.doAs(loginContext.getSubject(), new PrivilegedAction() { + public Object run() { - FolderPermission perm1 = new FolderPermission("/files/subfolder1/test.xml", "view"); + FolderPermission perm1 = new FolderPermission( + "/files/subfolder1/test.xml", "view"); AccessController.checkPermission(perm1); return null; } @@ -160,14 +176,15 @@ fail("did not authorize view permission on the Folder."); } - try { JSSubject.doAs(loginContext.getSubject(), new PrivilegedAction() { + public Object run() { - FolderPermission perm1 = new FolderPermission("/files/subfolder1/foo", "view"); + FolderPermission perm1 = new FolderPermission( + "/files/subfolder1/foo", "view"); AccessController.checkPermission(perm1); return null; } @@ -176,15 +193,17 @@ catch (AccessControlException ace) { fail("did not authorize view permission on the Folder."); - } - + } + try { JSSubject.doAs(loginContext.getSubject(), new PrivilegedAction() { + public Object run() { - FolderPermission perm1 = new FolderPermission("/files/subfolder1/foo/anotherdoc.xml", "view"); + FolderPermission perm1 = new FolderPermission( + "/files/subfolder1/foo/anotherdoc.xml", "view"); AccessController.checkPermission(perm1); return null; } @@ -194,15 +213,17 @@ catch (AccessControlException ace) { // Correct behavior - not authorise to view the document - } - + } + try { JSSubject.doAs(loginContext.getSubject(), new PrivilegedAction() { + public Object run() { - FolderPermission perm1 = new FolderPermission("/files/subfolder2/test.xml", "view"); + FolderPermission perm1 = new FolderPermission( + "/files/subfolder2/test.xml", "view"); AccessController.checkPermission(perm1); return null; } @@ -213,14 +234,15 @@ fail("did not authorize view permission on the Folder."); } - try { JSSubject.doAs(loginContext.getSubject(), new PrivilegedAction() { + public Object run() { - FolderPermission perm1 = new FolderPermission("/files/subfolder2/foo", "view"); + FolderPermission perm1 = new FolderPermission( + "/files/subfolder2/foo", "view"); AccessController.checkPermission(perm1); return null; } @@ -230,14 +252,16 @@ { fail("did not authorize view permission on the Folder."); } - + try { JSSubject.doAs(loginContext.getSubject(), new PrivilegedAction() { + public Object run() { - FolderPermission perm1 = new FolderPermission("/files/subfolder2/foo/anotherdoc.xml", "view"); + FolderPermission perm1 = new FolderPermission( + "/files/subfolder2/foo/anotherdoc.xml", "view"); AccessController.checkPermission(perm1); return null; } @@ -246,12 +270,13 @@ catch (AccessControlException ace) { fail("did not authorize view permission on the Folder."); - } + } } - /** - * <p>Initialize user test object.</p> + * <p> + * Initialize user test object. + * </p> */ protected void initUser() { @@ -262,18 +287,20 @@ catch (SecurityException sex) { } - + UserPrincipal user = new UserPrincipalImpl("anon"); FolderPermission perm1 = new FolderPermission("/files/test.xml", "edit"); - FolderPermission perm2 = new FolderPermission("/files/subfolder1/*", "view"); - FolderPermission perm3 = new FolderPermission("/files/subfolder2/-", "view"); + FolderPermission perm2 = new FolderPermission("/files/subfolder1/*", + "view"); + FolderPermission perm3 = new FolderPermission("/files/subfolder2/-", + "view"); try { pms.addPermission(perm1); pms.addPermission(perm2); pms.addPermission(perm3); - + pms.grantPermission(user, perm1); pms.grantPermission(user, perm2); pms.grantPermission(user, perm3); @@ -285,15 +312,19 @@ } /** - * <p>Destroy user test object.</p> + * <p> + * Destroy user test object. + * </p> */ protected void destroyUser() throws Exception { ums.removeUser("anon"); FolderPermission perm1 = new FolderPermission("/files/test.xml", "edit"); - FolderPermission perm2 = new FolderPermission("/files/subfolder1/*", "view"); - FolderPermission perm3 = new FolderPermission("/files/subfolder2/-", "view"); + FolderPermission perm2 = new FolderPermission("/files/subfolder1/*", + "view"); + FolderPermission perm3 = new FolderPermission("/files/subfolder2/-", + "view"); pms.removePermission(perm1); pms.removePermission(perm2); pms.removePermission(perm3); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestRoleManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestRoleManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestRoleManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,6 +37,7 @@ */ public class TestRoleManager extends AbstractSecurityTestcase { + /** * @see junit.framework.TestCase#setUp() */ @@ -74,7 +75,8 @@ } catch (SecurityException sex) { - assertTrue("role should not already exists. exception caught: " + sex, false); + assertTrue("role should not already exists. exception caught: " + + sex, false); } try { @@ -82,13 +84,15 @@ } catch (SecurityException sex) { - assertTrue("role should not already exists. exception caught: " + sex, false); + assertTrue("role should not already exists. exception caught: " + + sex, false); } // Add existing role. try { rms.addRole("testrole.newrole0"); - assertTrue("role should already exists. exception not thrown.", false); + assertTrue("role should already exists. exception not thrown.", + false); } catch (SecurityException sex) { @@ -128,25 +132,31 @@ { rms.addRoleToUser("anonuser1", "testusertorole1.role1"); - Collection principals = ums.getUser("anonuser1").getSubject().getPrincipals(); - assertTrue("anonuser1 should contain testusertorole1.role1", principals.contains(new RolePrincipalImpl( - "testusertorole1.role1"))); + Collection principals = ums.getUser("anonuser1").getSubject() + .getPrincipals(); + assertTrue("anonuser1 should contain testusertorole1.role1", + principals.contains(new RolePrincipalImpl( + "testusertorole1.role1"))); } catch (SecurityException sex) { - assertTrue("should add user to role. exception caught: " + sex, false); + assertTrue("should add user to role. exception caught: " + sex, + false); } // Add role with existing roles. try { rms.addRoleToUser("anonuser1", "testusertorole1.role2"); - Collection principals = ums.getUser("anonuser1").getSubject().getPrincipals(); - assertTrue("anonuser1 should contain testusertorole1.role2", principals.contains(new RolePrincipalImpl( - "testusertorole1.role2"))); + Collection principals = ums.getUser("anonuser1").getSubject() + .getPrincipals(); + assertTrue("anonuser1 should contain testusertorole1.role2", + principals.contains(new RolePrincipalImpl( + "testusertorole1.role2"))); } catch (SecurityException sex) { - assertTrue("should add user to role. exception caught: " + sex, false); + assertTrue("should add user to role. exception caught: " + sex, + false); } // Add role when user does not exist. try @@ -175,7 +185,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and role. exception caught: " + sex, false); + assertTrue("could not remove user and role. exception caught: " + + sex, false); } } @@ -208,12 +219,15 @@ try { rms.removeRole("testrole1.role1"); - Collection principals = ums.getUser("anonuser2").getSubject().getPrincipals(); + Collection principals = ums.getUser("anonuser2").getSubject() + .getPrincipals(); // because of hierarchical roles with generalization strategy. - assertEquals("principal size should be == 5 after removing testrole1.role1, for principals: " - + principals.toString(), 5, principals.size()); - assertFalse("anonuser2 should not contain testrole1.role1", principals.contains(new RolePrincipalImpl( - "testrole1.role1"))); + assertEquals( + "principal size should be == 5 after removing testrole1.role1, for principals: " + + principals.toString(), 5, principals.size()); + assertFalse("anonuser2 should not contain testrole1.role1", + principals + .contains(new RolePrincipalImpl("testrole1.role1"))); // Make sure that the children are removed as well. rms.removeRole("testrole2"); boolean roleExists = rms.roleExists("testrole2.role1"); @@ -234,7 +248,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and role. exception caught: " + sex, false); + assertTrue("could not remove user and role. exception caught: " + + sex, false); } } @@ -249,7 +264,8 @@ try { rms.getRole("testroledoesnotexist"); - assertTrue("role does not exist. should have thrown an exception.", false); + assertTrue("role does not exist. should have thrown an exception.", + false); } catch (SecurityException sex) { @@ -263,18 +279,21 @@ } catch (SecurityException sex) { - assertTrue("role exists. should not have thrown an exception.", false); + assertTrue("role exists. should not have thrown an exception.", + false); } assertNotNull("role is null", role); // Test the Principal. Principal rolePrincipal = role.getPrincipal(); assertNotNull("role principal is null", rolePrincipal); - assertEquals("expected role principal full path name == testgetrole", "testgetrole", rolePrincipal.getName()); + assertEquals("expected role principal full path name == testgetrole", + "testgetrole", rolePrincipal.getName()); // Test the Role Preferences. Preferences preferences = role.getPreferences(); - assertEquals("expected role node == /role/testgetrole", SecurityHelper.getPreferencesFullPath(rolePrincipal), - preferences.absolutePath()); + assertEquals("expected role node == /role/testgetrole", SecurityHelper + .getPreferencesFullPath(rolePrincipal), preferences + .absolutePath()); // Cleanup test. try @@ -317,7 +336,8 @@ } catch (SecurityException sex) { - assertTrue("user exists. should not have thrown an exception: " + sex, false); + assertTrue("user exists. should not have thrown an exception: " + + sex, false); } // Cleanup test. @@ -329,7 +349,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and role. exception caught: " + sex, false); + assertTrue("could not remove user and role. exception caught: " + + sex, false); } } @@ -348,8 +369,10 @@ rms.addRole("testuserrolemapping.role3"); gms.addGroup("testrolegroupmapping"); rms.addRoleToGroup("testuserrolemapping", "testrolegroupmapping"); - rms.addRoleToGroup("testuserrolemapping.role1", "testrolegroupmapping"); - rms.addRoleToGroup("testuserrolemapping.role3", "testrolegroupmapping"); + rms.addRoleToGroup("testuserrolemapping.role1", + "testrolegroupmapping"); + rms.addRoleToGroup("testuserrolemapping.role3", + "testrolegroupmapping"); } catch (SecurityException sex) { @@ -363,7 +386,8 @@ } catch (SecurityException sex) { - assertTrue("group exists. should not have thrown an exception: " + sex, false); + assertTrue("group exists. should not have thrown an exception: " + + sex, false); } // Cleanup test. @@ -374,7 +398,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove role and group. exception caught: " + sex, false); + assertTrue("could not remove role and group. exception caught: " + + sex, false); } } @@ -405,7 +430,8 @@ } catch (SecurityException sex) { - assertTrue("user exists. should not have thrown an exception: " + sex, false); + assertTrue("user exists. should not have thrown an exception: " + + sex, false); } // Cleanup test. @@ -416,7 +442,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and role. exception caught: " + sex, false); + assertTrue("could not remove user and role. exception caught: " + + sex, false); } } @@ -441,12 +468,16 @@ try { - boolean isUserInRole = rms.isUserInRole("anonuser4", "testuserrolemapping"); - assertTrue("anonuser4 should be in role testuserrolemapping", isUserInRole); + boolean isUserInRole = rms.isUserInRole("anonuser4", + "testuserrolemapping"); + assertTrue("anonuser4 should be in role testuserrolemapping", + isUserInRole); } catch (SecurityException sex) { - assertTrue("user and role exist. should not have thrown an exception: " + sex, false); + assertTrue( + "user and role exist. should not have thrown an exception: " + + sex, false); } // Cleanup test. @@ -457,7 +488,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and role. exception caught: " + sex, false); + assertTrue("could not remove user and role. exception caught: " + + sex, false); } } @@ -476,23 +508,28 @@ rms.addRole("testuserrolemapping.role3"); gms.addGroup("testrolegroupmapping"); rms.addRoleToGroup("testuserrolemapping", "testrolegroupmapping"); - rms.addRoleToGroup("testuserrolemapping.role1", "testrolegroupmapping"); - rms.addRoleToGroup("testuserrolemapping.role3", "testrolegroupmapping"); + rms.addRoleToGroup("testuserrolemapping.role1", + "testrolegroupmapping"); + rms.addRoleToGroup("testuserrolemapping.role3", + "testrolegroupmapping"); } catch (SecurityException sex) { - assertTrue("failed to init testRemoveRoleFromGroup(), " + sex, false); + assertTrue("failed to init testRemoveRoleFromGroup(), " + sex, + false); } try { - rms.removeRoleFromGroup("testuserrolemapping.role3", "testrolegroupmapping"); + rms.removeRoleFromGroup("testuserrolemapping.role3", + "testrolegroupmapping"); Collection roles = rms.getRolesInGroup("testrolegroupmapping"); assertEquals("roles size should be == 2", 2, roles.size()); } catch (SecurityException sex) { - assertTrue("group exists. should not have thrown an exception: " + sex, false); + assertTrue("group exists. should not have thrown an exception: " + + sex, false); } // Cleanup test. @@ -503,7 +540,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove group and role. exception caught: " + sex, false); + assertTrue("could not remove group and role. exception caught: " + + sex, false); } } @@ -527,12 +565,17 @@ } try { - boolean isGroupInRole = rms.isGroupInRole("testrolegroupmapping", "testuserrolemapping"); - assertTrue("testrolegroupmapping should be in role testuserrolemapping", isGroupInRole); + boolean isGroupInRole = rms.isGroupInRole("testrolegroupmapping", + "testuserrolemapping"); + assertTrue( + "testrolegroupmapping should be in role testuserrolemapping", + isGroupInRole); } catch (SecurityException sex) { - assertTrue("group and role exist. should not have thrown an exception: " + sex, false); + assertTrue( + "group and role exist. should not have thrown an exception: " + + sex, false); } // Cleanup test. @@ -543,7 +586,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove role and group. exception caught: " + sex, false); + assertTrue("could not remove role and group. exception caught: " + + sex, false); } } @@ -554,10 +598,15 @@ */ protected void destroyRoles() { - final String[] users = new String[] { "anonuser1", "anonuser2", "anonuser3", "anonuser4", "anonuser5", }; - final String[] roles = new String[] { "testrole", "testrole1", "testrole2", "testrole3", "testgetrole", - "testusertorole1", "testuserrolemapping.role1", "testuserrolemapping2.role2", "testuserrolemapping","testuserrolemapping2" }; - final String[] groups = new String[] { "testusertorole1" }; + final String[] users = new String[] + {"anonuser1", "anonuser2", "anonuser3", "anonuser4", "anonuser5",}; + final String[] roles = new String[] + {"testrole", "testrole1", "testrole2", "testrole3", "testgetrole", + "testusertorole1", "testuserrolemapping.role1", + "testuserrolemapping2.role2", "testuserrolemapping", + "testuserrolemapping2"}; + final String[] groups = new String[] + {"testusertorole1"}; for (int i = 0; i < users.length; i++) { @@ -601,12 +650,13 @@ * Test get roles. * </p> * - * @throws Exception Throws an exception. + * @throws Exception + * Throws an exception. */ public void testGetRoles() throws Exception { - int roleCount = 0; - int rolesAdded = 0; + int roleCount = 0; + int rolesAdded = 0; Iterator it = rms.getRoles(""); while (it.hasNext()) { @@ -621,7 +671,7 @@ rolesAdded = 3; int count = 0; - + it = rms.getRoles(""); while (it.hasNext()) { @@ -633,8 +683,9 @@ rms.removeRole("r1"); rms.removeRole("r2"); rms.removeRole("r3"); - assertTrue("role count should be " + (rolesAdded + roleCount), count == (rolesAdded + roleCount)); - + assertTrue("role count should be " + (rolesAdded + roleCount), + count == (rolesAdded + roleCount)); + } - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestSecurityHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestSecurityHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestSecurityHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,30 +31,34 @@ /** * TestSecurityHelper - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: TestSecurityHelper.java 516448 2007-03-09 16:25:47Z ate $ */ public class TestSecurityHelper extends AbstractSecurityTestcase { + public static Test suite() { // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestSecurityHelper.class); } - + public void testHelpers() throws Exception { Principal principal = new UserPrincipalImpl("anon"); Set principals = new PrincipalsSet(); principals.add(principal); - Subject subject = new Subject(true, principals, new HashSet(), new HashSet()); + Subject subject = new Subject(true, principals, new HashSet(), + new HashSet()); System.out.println("subject = " + subject); - - Principal found = SecurityHelper.getBestPrincipal(subject, UserPrincipal.class); + + Principal found = SecurityHelper.getBestPrincipal(subject, + UserPrincipal.class); assertNotNull("found principal is null", found); - assertTrue("found principal should be anon", found.getName().equals("anon")); + assertTrue("found principal should be anon", found.getName().equals( + "anon")); System.out.println("found = " + found.getName()); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestUserManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestUserManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/TestUserManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,12 +17,11 @@ package org.apache.jetspeed.security; import java.security.Principal; +import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; -import java.util.ArrayList; import java.util.prefs.Preferences; -import java.security.Principal; import javax.security.auth.Subject; import javax.security.auth.login.LoginContext; @@ -86,7 +85,8 @@ try { ums.addUser("anon", "password"); - assertTrue("user should already exists. exception not thrown.", false); + assertTrue("user should already exists. exception not thrown.", + false); } catch (SecurityException sex) { @@ -117,7 +117,8 @@ try { ums.getUser("test"); - assertTrue("user does not exist. should have thrown an exception.", false); + assertTrue("user does not exist. should have thrown an exception.", + false); } catch (SecurityException sex) { @@ -131,29 +132,36 @@ } catch (SecurityException sex) { - assertTrue("user exists. should not have thrown an exception.", false); + assertTrue("user exists. should not have thrown an exception.", + false); } assertNotNull("user is null", user); // Test the User JSSubject Subject subject = user.getSubject(); assertNotNull("subject is null", subject); // Asset user principal. - Principal userPrincipal = SecurityHelper.getPrincipal(subject, UserPrincipal.class); + Principal userPrincipal = SecurityHelper.getPrincipal(subject, + UserPrincipal.class); assertNotNull("user principal is null", userPrincipal); - assertEquals("expected user principal full path == /user/test", "/user/test", SecurityHelper - .getPreferencesFullPath(userPrincipal)); - assertEquals("expected user principal name == test", "test", userPrincipal.getName()); + assertEquals("expected user principal full path == /user/test", + "/user/test", SecurityHelper + .getPreferencesFullPath(userPrincipal)); + assertEquals("expected user principal name == test", "test", + userPrincipal.getName()); // Test the User Preferences. Preferences preferences = user.getPreferences(); - assertEquals("expected user node == /user/test", "/user/test", preferences.absolutePath()); - + assertEquals("expected user node == /user/test", "/user/test", + preferences.absolutePath()); + // Test if roles are inheritable to a user via groups try { - // If user 'inheritedUser' belongs to group 'inheritingGroup' and group 'group' has role 'assignedRole', then - // the role 'assignedRole' can be inherited to the user 'inheritedUser' via group 'inheritingGroup'. - + // If user 'inheritedUser' belongs to group 'inheritingGroup' and + // group 'group' has role 'assignedRole', then + // the role 'assignedRole' can be inherited to the user + // 'inheritedUser' via group 'inheritingGroup'. + ums.addUser("inheritedUser", "password"); gms.addGroup("inheritingGroup"); gms.addUserToGroup("inheritedUser", "inheritingGroup"); @@ -162,32 +170,47 @@ User testUser = ums.getUser("inheritedUser"); List principalNames = new ArrayList(); - for (Iterator it = testUser.getSubject().getPrincipals().iterator(); it.hasNext(); ) + for (Iterator it = testUser.getSubject().getPrincipals().iterator(); it + .hasNext();) { Principal p = (Principal) it.next(); principalNames.add(p.getName()); } - - assertTrue("user is expected to have a user principal named inheritedUser.", principalNames.contains("inheritedUser")); - assertTrue("user is expected to have a group principal named inheritingGroup.", principalNames.contains("inheritingGroup")); - assertTrue("user is expected to have a role principal named assignedRole which is inherited via the group.", principalNames.contains("assignedRole")); - - // However, roles from role manager should not contain the role 'assignedRole' - // because the role 'assignedRole' is not directly assigned to user 'inheritedUser'. - // For example, the Users Admin portlet uses RoleManager to retrieve roles directly assigned to a user. - + + assertTrue( + "user is expected to have a user principal named inheritedUser.", + principalNames.contains("inheritedUser")); + assertTrue( + "user is expected to have a group principal named inheritingGroup.", + principalNames.contains("inheritingGroup")); + assertTrue( + "user is expected to have a role principal named assignedRole which is inherited via the group.", + principalNames.contains("assignedRole")); + + // However, roles from role manager should not contain the role + // 'assignedRole' + // because the role 'assignedRole' is not directly assigned to user + // 'inheritedUser'. + // For example, the Users Admin portlet uses RoleManager to retrieve + // roles directly assigned to a user. + List userRoleNames = new ArrayList(); - for (Iterator it = rms.getRolesForUser("inheritedUser").iterator(); it.hasNext(); ) + for (Iterator it = rms.getRolesForUser("inheritedUser").iterator(); it + .hasNext();) { Role role = (Role) it.next(); userRoleNames.add(role.getPrincipal().getName()); } - - assertFalse("role 'assignedRole' is not expected to be retrieved because the role 'assignedRole' is not directly assigned to user 'inheritedUser'.", userRoleNames.contains("assignedRole")); + + assertFalse( + "role 'assignedRole' is not expected to be retrieved because the role 'assignedRole' is not directly assigned to user 'inheritedUser'.", + userRoleNames.contains("assignedRole")); } catch (SecurityException sex) { - assertTrue("failed to test 'rolesInheritableViaGroups' mode in testGetUser(), " + sex, false); + assertTrue( + "failed to test 'rolesInheritableViaGroups' mode in testGetUser(), " + + sex, false); } finally { @@ -199,7 +222,7 @@ catch (SecurityException sex) { } - + try { gms.removeGroup("inheritingGroup"); @@ -207,7 +230,7 @@ catch (SecurityException sex) { } - + try { ums.removeUser("inheritedUser"); @@ -251,7 +274,8 @@ } catch (SecurityException sex) { - assertTrue("role exists. should not have thrown an exception: " + sex, false); + assertTrue("role exists. should not have thrown an exception: " + + sex, false); } // Cleanup test. @@ -263,7 +287,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and role. exception caught: " + sex, false); + assertTrue("could not remove user and role. exception caught: " + + sex, false); } } @@ -298,7 +323,8 @@ } catch (SecurityException sex) { - assertTrue("group exists. should not have thrown an exception: " + sex, false); + assertTrue("group exists. should not have thrown an exception: " + + sex, false); } // Cleanup test. @@ -311,7 +337,8 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and group. exception caught: " + sex, false); + assertTrue("could not remove user and group. exception caught: " + + sex, false); } } @@ -331,7 +358,8 @@ // Test that the user can log in with the new password. try { - PassiveCallbackHandler pch = new PassiveCallbackHandler("anon", "newpassword"); + PassiveCallbackHandler pch = new PassiveCallbackHandler("anon", + "newpassword"); loginContext = new LoginContext("Jetspeed", pch); loginContext.login(); loginContext.logout(); @@ -352,7 +380,8 @@ * Test get users. * </p> * - * @throws Exception Throws an exception. + * @throws Exception + * Throws an exception. */ public void testGetUsers() throws Exception { @@ -398,14 +427,14 @@ { try { - if (ums.userExists("anon")) - ums.removeUser("anon"); - if (ums.userExists("test")) - ums.removeUser("test"); + if (ums.userExists("anon")) ums.removeUser("anon"); + if (ums.userExists("test")) ums.removeUser("test"); } catch (SecurityException sex) { - System.out.println("could not remove test users. exception caught: " + sex); + System.out + .println("could not remove test users. exception caught: " + + sex); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestCredentialHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestCredentialHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestCredentialHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,12 +18,13 @@ import java.util.Set; +import junit.framework.Test; +import junit.framework.TestSuite; + import org.apache.jetspeed.security.PasswordCredential; +import org.apache.jetspeed.security.UserManager; import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; -import junit.framework.Test; -import junit.framework.TestSuite; - /** * <p> * Unit testing for {@link UserManager}. @@ -39,7 +40,7 @@ */ protected void setUp() throws Exception { - super.setUp(); + super.setUp(); // cleanup for previously failed test destroyUser(); } @@ -75,12 +76,13 @@ Set privateCredentials = ch.getPrivateCredentials("testcred"); assertNotNull(privateCredentials); assertEquals(1, privateCredentials.size()); - PasswordCredential[] pwdCreds = (PasswordCredential[]) privateCredentials.toArray(new PasswordCredential[1]); + PasswordCredential[] pwdCreds = (PasswordCredential[]) privateCredentials + .toArray(new PasswordCredential[1]); assertEquals("testcred", pwdCreds[0].getUserName()); assertNotNull(new String(pwdCreds[0].getPassword())); destroyUser(); } - + /** * <p> * Test <code>getPublicCredentials</code>.. @@ -104,23 +106,24 @@ { initUser(); // Replace existing password credential. - ch.setPassword("testcred","password","newpassword"); + ch.setPassword("testcred", "password", "newpassword"); // Test that the credential was properly set. Set privateCredentials = ch.getPrivateCredentials("testcred"); assertNotNull(privateCredentials); assertEquals(1, privateCredentials.size()); - PasswordCredential[] pwdCreds = (PasswordCredential[]) privateCredentials.toArray(new PasswordCredential[0]); + PasswordCredential[] pwdCreds = (PasswordCredential[]) privateCredentials + .toArray(new PasswordCredential[0]); assertEquals("testcred", pwdCreds[0].getUserName()); assertNotNull(new String(pwdCreds[0].getPassword())); // Add password credential. - ch.setPassword("testcred","newpassword","anotherpassword"); + ch.setPassword("testcred", "newpassword", "anotherpassword"); // Test that the credential was properly set. privateCredentials = ch.getPrivateCredentials("testcred"); assertNotNull(privateCredentials); assertEquals(1, privateCredentials.size()); destroyUser(); } - + /** * <p> * Initialize user test object. Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestCredentialPasswordEncoder.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestCredentialPasswordEncoder.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestCredentialPasswordEncoder.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,28 +21,30 @@ import java.util.List; import java.util.Set; +import junit.framework.Test; +import junit.framework.TestSuite; + import org.apache.jetspeed.security.PasswordCredential; import org.apache.jetspeed.security.om.InternalUserPrincipal; import org.apache.jetspeed.security.om.impl.InternalCredentialImpl; import org.apache.jetspeed.security.spi.impl.DefaultPasswordCredentialImpl; import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; -import junit.framework.Test; -import junit.framework.TestSuite; - /** -* <p> + * <p> * TestDefaultInternalPasswordCredentialIntercepto * </p> * * @author <a href="mailto:ate ¡÷ apache.org">Ate Douma</a> - * @version $Id: TestCredentialPasswordEncoder.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: TestCredentialPasswordEncoder.java 516448 2007-03-09 16:25:47Z + * ate $ */ public class TestCredentialPasswordEncoder extends AbstractSecurityTestcase { + protected void setUp() throws Exception { - super.setUp(); + super.setUp(); // cleanup for previously failed test destroyUser(); initUser(); @@ -61,39 +63,43 @@ public void testEncodedPassword() throws Exception { - Set privateCredentials = ums.getUser("testcred").getSubject().getPrivateCredentials(); + Set privateCredentials = ums.getUser("testcred").getSubject() + .getPrivateCredentials(); assertNotNull(privateCredentials); assertEquals(1, privateCredentials.size()); - PasswordCredential[] pwdCreds = (PasswordCredential[]) privateCredentials.toArray(new PasswordCredential[0]); + PasswordCredential[] pwdCreds = (PasswordCredential[]) privateCredentials + .toArray(new PasswordCredential[0]); assertEquals("testcred", pwdCreds[0].getUserName()); - assertNotSame("Password should be not same (encoded)", "password", new String(pwdCreds[0].getPassword())); + assertNotSame("Password should be not same (encoded)", "password", + new String(pwdCreds[0].getPassword())); } protected void initUser() throws Exception { // create user without password ums.addUser("testcred", null); - // add a non-encoded password credential directly - InternalUserPrincipal internalUser = securityAccess.getInternalUserPrincipal("testcred"); + // add a non-encoded password credential directly + InternalUserPrincipal internalUser = securityAccess + .getInternalUserPrincipal("testcred"); ArrayList credentials = new ArrayList(); - InternalCredentialImpl credential = - new InternalCredentialImpl(internalUser.getPrincipalId(), - "password", 0, DefaultPasswordCredentialImpl.class.getName()); + InternalCredentialImpl credential = new InternalCredentialImpl( + internalUser.getPrincipalId(), "password", 0, + DefaultPasswordCredentialImpl.class.getName()); credentials.add(credential); internalUser.setCredentials(credentials); - securityAccess.setInternalUserPrincipal(internalUser,false); + securityAccess.setInternalUserPrincipal(internalUser, false); } protected void destroyUser() throws Exception { ums.removeUser("testcred"); } - + protected String[] getConfigurations() { String[] confs = super.getConfigurations(); List confList = new ArrayList(Arrays.asList(confs)); confList.add("JETSPEED-INF/spring/TestCredentialPasswordEncoder.xml"); - return (String[])confList.toArray(new String[1]); - } + return (String[]) confList.toArray(new String[1]); + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestGroupSecurityHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestGroupSecurityHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestGroupSecurityHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,11 +18,11 @@ import java.security.Principal; -import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; - import junit.framework.Test; import junit.framework.TestSuite; +import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; + /** * <p> * Unit testing for {@link GroupSecurityHandler}. @@ -33,8 +33,6 @@ public class TestGroupSecurityHandler extends AbstractSecurityTestcase { - - /** * @see junit.framework.TestCase#setUp() */ @@ -76,7 +74,7 @@ assertEquals("testusertogroup1", principal.getName()); destroyGroup(); } - + /** * <p> * Initialize group test object. Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestPasswordCredentialProvider.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestPasswordCredentialProvider.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestPasswordCredentialProvider.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,13 +21,13 @@ import java.util.List; import java.util.Set; +import junit.framework.Test; +import junit.framework.TestSuite; + import org.apache.jetspeed.security.PasswordCredential; +import org.apache.jetspeed.security.SecurityException; import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; -import org.apache.jetspeed.security.SecurityException; -import junit.framework.Test; -import junit.framework.TestSuite; - /** * <p> * Unit testing for {@link PasswordCredentialProvider}. @@ -37,12 +37,13 @@ */ public class TestPasswordCredentialProvider extends AbstractSecurityTestcase { + /** * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { - super.setUp(); + super.setUp(); // cleanup for previously failed test destroyUser(); } @@ -75,15 +76,17 @@ public void testGetPrivateCredentials() throws Exception { initUser(); - Set privateCredentials = ums.getUser("testcred").getSubject().getPrivateCredentials(); + Set privateCredentials = ums.getUser("testcred").getSubject() + .getPrivateCredentials(); assertNotNull(privateCredentials); assertEquals(1, privateCredentials.size()); - PasswordCredential[] pwdCreds = (PasswordCredential[]) privateCredentials.toArray(new PasswordCredential[0]); + PasswordCredential[] pwdCreds = (PasswordCredential[]) privateCredentials + .toArray(new PasswordCredential[0]); assertEquals("testcred", pwdCreds[0].getUserName()); assertNotSame("password01", new String(pwdCreds[0].getPassword())); destroyUser(); } - + /** * <p> * Test <code>setPassword</code>.. @@ -92,46 +95,54 @@ public void testSetPassword() throws Exception { initUser(); - Set privateCredentials = ums.getUser("testcred").getSubject().getPrivateCredentials(); + Set privateCredentials = ums.getUser("testcred").getSubject() + .getPrivateCredentials(); assertNotNull(privateCredentials); assertEquals(1, privateCredentials.size()); - PasswordCredential[] pwdCreds = (PasswordCredential[]) privateCredentials.toArray(new PasswordCredential[0]); + PasswordCredential[] pwdCreds = (PasswordCredential[]) privateCredentials + .toArray(new PasswordCredential[0]); assertEquals("testcred", pwdCreds[0].getUserName()); String encodedPassword = new String(pwdCreds[0].getPassword()); - assertNotSame("password01", encodedPassword ); - + assertNotSame("password01", encodedPassword); + // Try setting an invalid password: to short (min: 8) try { - ums.setPassword("testcred","password01","1234567"); + ums.setPassword("testcred", "password01", "1234567"); fail("Should not be able to set an invalid password"); } - catch (SecurityException e){} + catch (SecurityException e) + { + } // Try setting an invalid password: no digits try { - ums.setPassword("testcred","password01","newpassword"); + ums.setPassword("testcred", "password01", "newpassword"); fail("Should not be able to set an invalid password"); } - catch (SecurityException e){} + catch (SecurityException e) + { + } // Setting a valid password - ums.setPassword("testcred","password01","passwd01"); + ums.setPassword("testcred", "password01", "passwd01"); // Test that the credential was updated. - privateCredentials = ums.getUser("testcred").getSubject().getPrivateCredentials(); + privateCredentials = ums.getUser("testcred").getSubject() + .getPrivateCredentials(); assertNotNull(privateCredentials); assertEquals(1, privateCredentials.size()); - pwdCreds = (PasswordCredential[]) privateCredentials.toArray(new PasswordCredential[0]); + pwdCreds = (PasswordCredential[]) privateCredentials + .toArray(new PasswordCredential[0]); assertEquals("testcred", pwdCreds[0].getUserName()); String newEncodedPassword = new String(pwdCreds[0].getPassword()); assertNotSame(encodedPassword, newEncodedPassword); assertNotSame("passwd01", newEncodedPassword); - + // Test authentication with the new password - assertTrue(ums.authenticate("testcred","passwd01")); + assertTrue(ums.authenticate("testcred", "passwd01")); destroyUser(); } - + /** * <p> * Initialize user test object. @@ -151,12 +162,12 @@ { ums.removeUser("testcred"); } - + protected String[] getConfigurations() { String[] confs = super.getConfigurations(); List confList = new ArrayList(Arrays.asList(confs)); confList.add("JETSPEED-INF/spring/TestPasswordCredentialProvider.xml"); return (String[]) confList.toArray(new String[1]); - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestPasswordExpirationAndMaxAuthenticationFailuresInterceptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestPasswordExpirationAndMaxAuthenticationFailuresInterceptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestPasswordExpirationAndMaxAuthenticationFailuresInterceptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,21 +29,26 @@ import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; /** -* <p> + * <p> * TestInternalPasswordCredentialStateHandlingInterceptor * </p> * * @author <a href="mailto:ate ¡÷ apache.org">Ate Douma</a> - * @version $Id: TestPasswordExpirationAndMaxAuthenticationFailuresInterceptor.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: + * TestPasswordExpirationAndMaxAuthenticationFailuresInterceptor.java + * 516448 2007-03-09 16:25:47Z ate $ */ -public class TestPasswordExpirationAndMaxAuthenticationFailuresInterceptor extends AbstractSecurityTestcase +public class TestPasswordExpirationAndMaxAuthenticationFailuresInterceptor + extends AbstractSecurityTestcase { + private InternalUserPrincipal internalUser; + private InternalCredential credential; - + protected void setUp() throws Exception { - super.setUp(); + super.setUp(); // cleanup for previously failed test destroyUser(); initUser(); @@ -57,25 +62,35 @@ public static Test suite() { - return new TestSuite(TestPasswordExpirationAndMaxAuthenticationFailuresInterceptor.class); + return new TestSuite( + TestPasswordExpirationAndMaxAuthenticationFailuresInterceptor.class); } public void testExpirationAndMaxAuthenticationFailures() throws Exception { - assertTrue("should be allowed to authenticate",ums.authenticate("testcred","password")); + assertTrue("should be allowed to authenticate", ums.authenticate( + "testcred", "password")); credential.setExpirationDate(new Date(new java.util.Date().getTime())); updateCredential(); - assertFalse("should be expired",ums.authenticate("testcred","password")); - ums.setPassword("testcred","password","password2"); - assertTrue("should be allowed to authenticate",ums.authenticate("testcred","password2")); - assertFalse("should not be allowed to authenticate (wrong password1)",ums.authenticate("testcred","password")); - assertFalse("should not be allowed to authenticate (wrong password2)",ums.authenticate("testcred","password")); - assertFalse("should not be allowed to authenticate (wrong password3)",ums.authenticate("testcred","password")); - assertFalse("should not be allowed to authenticate (disabled)",ums.authenticate("testcred","password2")); - ums.setPassword("testcred",null,"password3"); - assertFalse("should still not be allowed to authenticate (disabled)",ums.authenticate("testcred","password3")); + assertFalse("should be expired", ums.authenticate("testcred", + "password")); + ums.setPassword("testcred", "password", "password2"); + assertTrue("should be allowed to authenticate", ums.authenticate( + "testcred", "password2")); + assertFalse("should not be allowed to authenticate (wrong password1)", + ums.authenticate("testcred", "password")); + assertFalse("should not be allowed to authenticate (wrong password2)", + ums.authenticate("testcred", "password")); + assertFalse("should not be allowed to authenticate (wrong password3)", + ums.authenticate("testcred", "password")); + assertFalse("should not be allowed to authenticate (disabled)", ums + .authenticate("testcred", "password2")); + ums.setPassword("testcred", null, "password3"); + assertFalse("should still not be allowed to authenticate (disabled)", + ums.authenticate("testcred", "password3")); ums.setPasswordEnabled("testcred", true); - assertTrue("should be allowed to authenticate again",ums.authenticate("testcred","password3")); + assertTrue("should be allowed to authenticate again", ums.authenticate( + "testcred", "password3")); } protected void initUser() throws Exception @@ -83,28 +98,30 @@ ums.addUser("testcred", "password"); loadUser(); } - + protected void loadUser() throws Exception { internalUser = securityAccess.getInternalUserPrincipal("testcred"); - credential = (InternalCredential)internalUser.getCredentials().iterator().next(); + credential = (InternalCredential) internalUser.getCredentials() + .iterator().next(); } - + protected void updateCredential() throws Exception { - securityAccess.setInternalUserPrincipal(internalUser,false); + securityAccess.setInternalUserPrincipal(internalUser, false); } protected void destroyUser() throws Exception { ums.removeUser("testcred"); } - + protected String[] getConfigurations() { String[] confs = super.getConfigurations(); List confList = new ArrayList(Arrays.asList(confs)); - confList.add("JETSPEED-INF/spring/TestPasswordExpirationAndMaxAuthenticationFailuresInterceptor.xml"); - return (String[])confList.toArray(new String[1]); - } + confList + .add("JETSPEED-INF/spring/TestPasswordExpirationAndMaxAuthenticationFailuresInterceptor.xml"); + return (String[]) confList.toArray(new String[1]); + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestPasswordHistoryInterceptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestPasswordHistoryInterceptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestPasswordHistoryInterceptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,18 +27,20 @@ import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; /** -* <p> + * <p> * TestInternalPasswordCredentialHistoryHandlingInterceptor * </p> * * @author <a href="mailto:ate ¡÷ apache.org">Ate Douma</a> - * @version $Id: TestPasswordHistoryInterceptor.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: TestPasswordHistoryInterceptor.java 516448 2007-03-09 16:25:47Z + * ate $ */ public class TestPasswordHistoryInterceptor extends AbstractSecurityTestcase { + protected void setUp() throws Exception { - super.setUp(); + super.setUp(); // cleanup for previously failed test destroyUser(); initUser(); @@ -60,47 +62,51 @@ // note that the automated test here must wait between // create user and set password operations to ensure that // passwords get unique timestamps - assertTrue("should be allowed to authenticate",ums.authenticate("testcred","password")); + assertTrue("should be allowed to authenticate", ums.authenticate( + "testcred", "password")); Thread.sleep(1000); - ums.setPassword("testcred","password","password1"); + ums.setPassword("testcred", "password", "password1"); Thread.sleep(1000); - ums.setPassword("testcred","password1","password2"); - assertTrue("should be allowed to authenticate",ums.authenticate("testcred","password2")); + ums.setPassword("testcred", "password1", "password2"); + assertTrue("should be allowed to authenticate", ums.authenticate( + "testcred", "password2")); try { Thread.sleep(1000); - ums.setPassword("testcred","password2","password"); + ums.setPassword("testcred", "password2", "password"); fail("Should not be allowed to reuse a password from password history"); } catch (SecurityException sex) { - assertTrue(SecurityException.PASSWORD_ALREADY_USED.equals(sex.getKeyedMessage())); + assertTrue(SecurityException.PASSWORD_ALREADY_USED.equals(sex + .getKeyedMessage())); } Thread.sleep(1000); - ums.setPassword("testcred","password2","password3"); + ums.setPassword("testcred", "password2", "password3"); Thread.sleep(1000); - ums.setPassword("testcred","password3","password4"); + ums.setPassword("testcred", "password3", "password4"); Thread.sleep(1000); - ums.setPassword("testcred","password4","password"); - - assertTrue("should be allowed to authenticate",ums.authenticate("testcred","password")); + ums.setPassword("testcred", "password4", "password"); + + assertTrue("should be allowed to authenticate", ums.authenticate( + "testcred", "password")); } protected void initUser() throws Exception { ums.addUser("testcred", "password"); } - + protected void destroyUser() throws Exception { ums.removeUser("testcred"); } - + protected String[] getConfigurations() { String[] confs = super.getConfigurations(); List confList = new ArrayList(Arrays.asList(confs)); confList.add("JETSPEED-INF/spring/TestPasswordHistoryInterceptor.xml"); - return (String[])confList.toArray(new String[1]); - } + return (String[]) confList.toArray(new String[1]); + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestRoleSecurityHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestRoleSecurityHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestRoleSecurityHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,13 +20,13 @@ import java.security.Permissions; import java.security.Principal; +import junit.framework.Test; +import junit.framework.TestSuite; + import org.apache.jetspeed.security.PortletPermission; import org.apache.jetspeed.security.impl.RolePrincipalImpl; import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; -import junit.framework.Test; -import junit.framework.TestSuite; - /** * <p> * Unit testing for {@link RoleSecurityHandler}. @@ -37,7 +37,6 @@ public class TestRoleSecurityHandler extends AbstractSecurityTestcase { - /** * @see junit.framework.TestCase#setUp() */ @@ -79,7 +78,7 @@ assertEquals("testusertorole1", principal.getName()); destroyRole(); } - + /** * <p> * Test <code>removeRolePrincipal</code>. @@ -94,18 +93,20 @@ // The group should still exist. assertTrue(gms.groupExists("mappedgroup")); // The permission should still exist. - assertTrue(pms.permissionExists(new PortletPermission("myportlet", "view"))); + assertTrue(pms.permissionExists(new PortletPermission("myportlet", + "view"))); // The user-role mapping should be gone. assertFalse(rms.isUserInRole("mappedroleuser", "mappedrole")); // The group-role mapping should be gone. assertFalse(rms.isGroupInRole("mappedgroup", "mappedroleuser")); // The permission-role mapping should be gone. - Permissions perms = pms.getPermissions(new RolePrincipalImpl("mappedrole")); + Permissions perms = pms.getPermissions(new RolePrincipalImpl( + "mappedrole")); assertFalse(perms.implies(new PortletPermission("myportlet", "view"))); - + destroyMappedRole(); } - + /** * <p> * Initialize role test object. @@ -125,7 +126,7 @@ { rms.removeRole("testusertorole1"); } - + protected void initMappedRole() throws Exception { destroyMappedRole(); @@ -133,27 +134,22 @@ rms.addRole("mappedrole"); rms.addRole("mappedrole.role1"); gms.addGroup("mappedgroup"); - + Permission perm = new PortletPermission("myportlet", "view"); pms.addPermission(perm); pms.grantPermission(new RolePrincipalImpl("mappedrole"), perm); - + rms.addRoleToUser("mappedroleuser", "mappedrole"); - rms.addRoleToGroup("mappedrole", "mappedgroup"); + rms.addRoleToGroup("mappedrole", "mappedgroup"); } - + protected void destroyMappedRole() throws Exception { - if (ums.userExists("mappedroleuser")) - ums.removeUser("mappedroleuser"); - if (rms.roleExists("mappedrole")) - rms.removeRole("mappedrole.role1"); - if (rms.roleExists("mappedrole.role1")) - rms.removeRole("mappedrole"); - if (gms.groupExists("mappedgroup")) - gms.removeGroup("mappedgroup"); + if (ums.userExists("mappedroleuser")) ums.removeUser("mappedroleuser"); + if (rms.roleExists("mappedrole")) rms.removeRole("mappedrole.role1"); + if (rms.roleExists("mappedrole.role1")) rms.removeRole("mappedrole"); + if (gms.groupExists("mappedgroup")) gms.removeGroup("mappedgroup"); PortletPermission pp = new PortletPermission("myportlet", "view"); - if (pms.permissionExists(pp)) - pms.removePermission(pp); + if (pms.permissionExists(pp)) pms.removePermission(pp); } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestSecurityMappingHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestSecurityMappingHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestSecurityMappingHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,11 +18,11 @@ import java.util.Set; -import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; - import junit.framework.Test; import junit.framework.TestSuite; +import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; + /** * <p> * Unit testing for {@link GroupSecurityHandler}. @@ -33,8 +33,6 @@ public class TestSecurityMappingHandler extends AbstractSecurityTestcase { - - /** * @see junit.framework.TestCase#setUp() */ @@ -83,7 +81,7 @@ assertEquals(3, principals.size()); } - + /** * <p> * Test <code>getUserPrincipal</code>. @@ -91,7 +89,7 @@ */ public void testGetGroupPrincipals() throws Exception { - + Set principals = smh.getGroupPrincipals("testuser"); assertNotNull(principals); // Hierarchy by generalization should return 3 roles. @@ -125,7 +123,7 @@ gms.removeGroup("testusertogroup2"); gms.removeGroup("testusertogroup2.group1"); } - + /** * <p> * Initialize user test object. @@ -133,7 +131,7 @@ */ protected void initRoleUser() throws Exception { - + rms.addRole("testusertorole1"); rms.addRole("testusertorole2.role1"); rms.addRoleToUser("testuser", "testusertorole1"); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestUserSecurityHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestUserSecurityHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/TestUserSecurityHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,11 +19,11 @@ import java.security.Principal; import java.util.Iterator; -import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; - import junit.framework.Test; import junit.framework.TestSuite; +import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; + /** * <p> * Unit testing for {@link UserSecurityHandler}. @@ -34,7 +34,6 @@ public class TestUserSecurityHandler extends AbstractSecurityTestcase { - /** * @see junit.framework.TestCase#setUp() */ @@ -77,7 +76,7 @@ assertNotNull(principal); assertEquals("testuser1", principal.getName()); } - + /** * <p> * Test <code>getUserPrincipals</code>. @@ -86,22 +85,22 @@ public void testGetUserPrincipals() throws Exception { Iterator principals = ush.getUserPrincipals("").iterator(); - boolean foundUser1 =false; - boolean foundUser2 =false; - + boolean foundUser1 = false; + boolean foundUser2 = false; + while (principals.hasNext()) { Principal principal = (Principal) principals.next(); assertNotNull(principal); - + if (principal.getName().equals("testuser1")) - { + { foundUser1 = true; } else if (principal.getName().equals("testuser2")) { - foundUser2 = true; - } + foundUser2 = true; + } } assertTrue(foundUser1 && foundUser2); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/AbstractLdapTest.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/AbstractLdapTest.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/AbstractLdapTest.java 2008-05-16 01:54:54 UTC (rev 940) @@ -50,16 +50,18 @@ * Abstract test case for LDAP providers. * </p> * - * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long </a>, <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> + * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long </a>, <a + * href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> * */ public abstract class AbstractLdapTest extends AbstractSpringTestCase { + /** The logger. */ private static final Log logger = LogFactory.getLog(AbstractLdapTest.class); - - private static final String LDAP_CONFIG = "openldap/setup2"; - + + private static final String LDAP_CONFIG = "openldap/setup2"; + /** The {@link UserSecurityHandler}. */ UserSecurityHandler userHandler; @@ -68,25 +70,25 @@ /** The {@link GroupSecurityHandler}. */ GroupSecurityHandler grHandler; - + /** The {@link RoleSecurityHandler}. */ - RoleSecurityHandler roleHandler; - + RoleSecurityHandler roleHandler; + /** The {@link SecurityMappingHandler}. */ SecurityMappingHandler secHandler; - + /** The {@link LdapUserPrincipalDao}. */ LdapUserPrincipalDao ldapPrincipalDao; - + /** The {@link LdapUserCredentialDao}. */ LdapUserCredentialDao ldapCredDao; - + /** The {@link LdapGroupDao}. */ LdapPrincipalDao ldapGroupDao; - + /** The {@link LdapGroupDao}. */ - LdapPrincipalDao ldapRoleDao; - + LdapPrincipalDao ldapRoleDao; + LdapMembershipDao ldapMembershipDao; /** Random seed. */ @@ -97,12 +99,12 @@ /** Group uid. */ protected String gpUid2 = "group2"; - + /** Role uid. */ protected String roleUid1 = "role1"; /** Role uid. */ - protected String roleUid2 = "role2"; + protected String roleUid2 = "role2"; /** User uid. */ protected String uid1 = "user1"; @@ -112,7 +114,6 @@ /** The test password. */ protected String password = "fred"; - /** * @see junit.framework.TestCase#setUp() @@ -120,7 +121,8 @@ protected void setUp() throws Exception { super.setUp(); - LdapBindingConfig ldapConfig = (LdapBindingConfig)ctx.getBean(LdapBindingConfig.class.getName()); + LdapBindingConfig ldapConfig = (LdapBindingConfig) ctx + .getBean(LdapBindingConfig.class.getName()); InitLdapSchema ldapSchema = new InitLdapSchema(ldapConfig); try { @@ -128,9 +130,9 @@ ldapSchema.initOu("OrgUnit1"); ldapSchema.initOu("People"); ldapSchema.initOu("Roles"); - ldapSchema.initOu("People","ou=OrgUnit1"); - ldapSchema.initOu("Groups","ou=OrgUnit1"); - ldapSchema.initOu("Roles","ou=OrgUnit1"); + ldapSchema.initOu("People", "ou=OrgUnit1"); + ldapSchema.initOu("Groups", "ou=OrgUnit1"); + ldapSchema.initOu("Roles", "ou=OrgUnit1"); } catch (NamingException se) @@ -146,7 +148,7 @@ crHandler = new LdapCredentialHandler(ldapCredDao); LdapDataHelper.setUserSecurityHandler(userHandler); LdapDataHelper.setCredentialHandler(crHandler); - + ldapGroupDao = new LdapGroupDaoImpl(ldapConfig); ldapRoleDao = new LdapRoleDaoImpl(ldapConfig); ldapMembershipDao = new LdapMemberShipDaoImpl(ldapConfig); @@ -154,8 +156,9 @@ roleHandler = new LdapRoleSecurityHandler(ldapRoleDao); LdapDataHelper.setGroupSecurityHandler(grHandler); LdapDataHelper.setRoleSecurityHandler(roleHandler); - - secHandler = new LdapSecurityMappingHandler(ldapPrincipalDao, ldapGroupDao, ldapRoleDao); + + secHandler = new LdapSecurityMappingHandler(ldapPrincipalDao, + ldapGroupDao, ldapRoleDao); } /** @@ -168,6 +171,8 @@ protected String[] getConfigurations() { - return new String[] {"JETSPEED-INF/directory/config/" + LDAP_CONFIG + "/security-spi-ldap.xml" }; - } + return new String[] + {"JETSPEED-INF/directory/config/" + LDAP_CONFIG + + "/security-spi-ldap.xml"}; + } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/LdapDataHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/LdapDataHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/LdapDataHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -36,6 +36,7 @@ */ public class LdapDataHelper { + /** The {@link UserSecurityHandler}. */ private static UserSecurityHandler userHandler; @@ -44,64 +45,65 @@ /** The {@link GroupSecurityHandler}. */ private static GroupSecurityHandler grHandler; - + /** The {@link RoleSecurityHandler}. */ - private static RoleSecurityHandler roleHandler; - - public static void seedUserData(String uid, String password) throws Exception + private static RoleSecurityHandler roleHandler; + + public static void seedUserData(String uid, String password) + throws Exception { UserPrincipal up = new UserPrincipalImpl(uid); userHandler.addUserPrincipal(up); crHandler.setPassword(uid, "", password); } - + public static void seedGroupData(String gpUid) throws Exception { GroupPrincipal gp = new GroupPrincipalImpl(gpUid); grHandler.setGroupPrincipal(gp); } - + public static void seedRoleData(String roleUid) throws Exception { RolePrincipal rp = new RolePrincipalImpl(roleUid); roleHandler.setRolePrincipal(rp); } - + public static void removeUserData(String uid) throws Exception { UserPrincipal up = new UserPrincipalImpl(uid); userHandler.removeUserPrincipal(up); } - + public static void removeGroupData(String gpUid) throws Exception { GroupPrincipal gp = new GroupPrincipalImpl(gpUid); grHandler.removeGroupPrincipal(gp); } - + public static void removeRoleData(String roleUid) throws Exception { RolePrincipal rp = new RolePrincipalImpl(roleUid); roleHandler.removeRolePrincipal(rp); - } - + } + public static void setUserSecurityHandler(UserSecurityHandler userHandlerVar) { userHandler = userHandlerVar; } - + public static void setCredentialHandler(CredentialHandler crHandlerVar) { crHandler = crHandlerVar; } - + public static void setGroupSecurityHandler(GroupSecurityHandler grHandlerVar) { grHandler = grHandlerVar; } - + public static void setRoleSecurityHandler(RoleSecurityHandler roleHandlerVar) { roleHandler = roleHandlerVar; - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapCredentialHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapCredentialHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapCredentialHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,12 +16,12 @@ */ package org.apache.jetspeed.security.spi.ldap; +import java.util.Set; + import org.apache.jetspeed.security.PasswordCredential; import org.apache.jetspeed.security.SecurityException; import org.apache.jetspeed.security.spi.impl.LdapCredentialHandler; -import java.util.Set; - /** * <p> * Test {@link LdapCredentialHandler}implementation of the SPI @@ -41,7 +41,7 @@ super.setUp(); LdapDataHelper.seedUserData(uid1, password); } - + /** * @see org.apache.jetspeed.security.spi.ldap.AbstractLdapTest#tearDown() */ @@ -56,15 +56,18 @@ * Test <code>getPrivateCredentials</code> * </p> * - * @throws Exception An {@link Exception}. + * @throws Exception + * An {@link Exception}. */ public void testGetPrivateCredentials() throws Exception { Set credentials = crHandler.getPrivateCredentials(uid1); - assertTrue("getPrivateCredentials found no credentials for user:" + uid1, credentials.size() > 0); + assertTrue("getPrivateCredentials found no credentials for user:" + + uid1, credentials.size() > 0); - PasswordCredential cred = (PasswordCredential) credentials.iterator().next(); + PasswordCredential cred = (PasswordCredential) credentials.iterator() + .next(); assertEquals(password, String.valueOf(cred.getPassword())); } @@ -74,15 +77,17 @@ * Test <code>getPrivateCredentials</code> for a user that does not exist. * </p> * - * @throws Exception An {@link Exception}. + * @throws Exception + * An {@link Exception}. */ public void testGetPrivateCredentialsForNonExistantUser() throws Exception { String nonExistantUser = Integer.toString(rand.nextInt()); Set credentials = crHandler.getPrivateCredentials(nonExistantUser); - assertTrue("getPrivateCredentials should not have found credentials for user:" + nonExistantUser, credentials - .isEmpty()); + assertTrue( + "getPrivateCredentials should not have found credentials for user:" + + nonExistantUser, credentials.isEmpty()); } /** @@ -90,12 +95,14 @@ * Test <code>setPassword</code>. * </p> * - * @throws Exception An {@link Exception}. + * @throws Exception + * An {@link Exception}. */ public void testSetPassword() throws Exception { crHandler.setPassword(uid1, password, "freddie"); - assertTrue("Failed to change the password.", crHandler.authenticate(uid1, "freddie")); + assertTrue("Failed to change the password.", crHandler.authenticate( + uid1, "freddie")); crHandler.setPassword(uid1, "freddie", password); } @@ -104,7 +111,8 @@ * Test <code>setPassword</code> with null password. * </p> * - * @throws Exception An {@link Exception}. + * @throws Exception + * An {@link Exception}. */ public void testVerifyNullSetPassword() throws Exception { @@ -116,11 +124,13 @@ * Test <code>authenticate</code> with correct login. * </p> * - * @throws Exception An {@link Exception}. + * @throws Exception + * An {@link Exception}. */ public void testGoodLogin() throws Exception { - assertTrue("The login failed for user.", crHandler.authenticate(uid1, password)); + assertTrue("The login failed for user.", crHandler.authenticate(uid1, + password)); } /** @@ -128,7 +138,8 @@ * Test <code>authenticate</code> with no password. * </p> * - * @throws Exception An {@link Exception}. + * @throws Exception + * An {@link Exception}. */ public void testCannotAuthenticateWithNoPassword() throws Exception { @@ -139,7 +150,9 @@ } catch (Exception e) { - assertTrue("Should have thrown an SecurityException but threw:" + e, e instanceof SecurityException); + assertTrue( + "Should have thrown an SecurityException but threw:" + e, + e instanceof SecurityException); } } @@ -148,7 +161,8 @@ * Test <code>authenticate</code> with bad uid. * </p> * - * @throws Exception An {@link Exception}. + * @throws Exception + * An {@link Exception}. */ public void testBadUID() throws Exception { @@ -161,7 +175,8 @@ } catch (Exception e) { - assertTrue("Should have thrown a SecurityException for a non-existant user.", + assertTrue( + "Should have thrown a SecurityException for a non-existant user.", e instanceof SecurityException); } } @@ -171,11 +186,12 @@ * Test <code>authenticate</code> with bad password. * </p> * - * @throws Exception An {@link Exception}. + * @throws Exception + * An {@link Exception}. */ public void testBadPassword() throws Exception { - assertFalse("Should not have authenticated with a bad password.", crHandler - .authenticate(uid1, password + "123")); + assertFalse("Should not have authenticated with a bad password.", + crHandler.authenticate(uid1, password + "123")); } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapGroupSecurityHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapGroupSecurityHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapGroupSecurityHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -52,11 +52,12 @@ public void testGetGroupPrincipal() throws Exception { String fullPath = (new GroupPrincipalImpl(gpUid1)).getFullPath(); - //GroupPrincipal groupPrincipal = grHandler.getGroupPrincipal(fullPath); + // GroupPrincipal groupPrincipal = + // grHandler.getGroupPrincipal(fullPath); GroupPrincipal groupPrincipal = grHandler.getGroupPrincipal(gpUid1); assertNotNull("Group was not found.", groupPrincipal); - assertEquals(gpUid1,groupPrincipal.getName()); - assertEquals(fullPath,groupPrincipal.getFullPath()); + assertEquals(gpUid1, groupPrincipal.getName()); + assertEquals(fullPath, groupPrincipal.getFullPath()); } /** @@ -66,9 +67,9 @@ { grHandler.setGroupPrincipal(new GroupPrincipalImpl(gpUid1)); List groups = grHandler.getGroupPrincipals(""); - assertEquals(1,groups.size()); + assertEquals(1, groups.size()); } - + /** * @throws Exception */ @@ -85,10 +86,12 @@ { GroupPrincipal gp = new GroupPrincipalImpl(gpUid1); grHandler.removeGroupPrincipal(gp); - GroupPrincipal groupPrincipal = grHandler.getGroupPrincipal(gp.getFullPath()); - assertNull("Group was found and should have been removed.", groupPrincipal); + GroupPrincipal groupPrincipal = grHandler.getGroupPrincipal(gp + .getFullPath()); + assertNull("Group was found and should have been removed.", + groupPrincipal); List groups = grHandler.getGroupPrincipals(""); - assertEquals(0,groups.size()); + assertEquals(0, groups.size()); } /** @@ -100,7 +103,7 @@ GroupPrincipal localPrin = new GroupPrincipalImpl(localUid); grHandler.removeGroupPrincipal(localPrin); List groups = grHandler.getGroupPrincipals(""); - assertEquals(1,groups.size()); + assertEquals(1, groups.size()); } /** @@ -111,17 +114,23 @@ try { LdapDataHelper.seedGroupData(gpUid2); - assertTrue("getUserPrincipals should have returned more than one user.", grHandler.getGroupPrincipals("*") - .size() > 1); + assertTrue( + "getUserPrincipals should have returned more than one user.", + grHandler.getGroupPrincipals("*").size() > 1); String fullPath = (new GroupPrincipalImpl(gpUid1)).getFullPath(); List groups = grHandler.getGroupPrincipals(fullPath); - assertTrue("getGroupPrincipals should have returned one group.", groups.size() == 1); - assertTrue("List should have consisted of GroupPrincipal objects.", groups.get(0) instanceof GroupPrincipal); + assertTrue("getGroupPrincipals should have returned one group.", + groups.size() == 1); + assertTrue("List should have consisted of GroupPrincipal objects.", + groups.get(0) instanceof GroupPrincipal); String localUid = Integer.toString(rand.nextInt()).toString(); - assertTrue("getGroupPrincipals should not have found any groups with the specified filter.", grHandler - .getGroupPrincipals(new GroupPrincipalImpl(localUid).getFullPath()).isEmpty()); + assertTrue( + "getGroupPrincipals should not have found any groups with the specified filter.", + grHandler.getGroupPrincipals( + new GroupPrincipalImpl(localUid).getFullPath()) + .isEmpty()); } finally { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapRoleSecurityHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapRoleSecurityHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapRoleSecurityHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -54,8 +54,8 @@ String fullPath = (new RolePrincipalImpl(roleUid1)).getFullPath(); RolePrincipal rolePrincipal = roleHandler.getRolePrincipal(roleUid1); assertNotNull("Role was not found.", rolePrincipal); - assertEquals(roleUid1,rolePrincipal.getName()); - assertEquals(fullPath,rolePrincipal.getFullPath()); + assertEquals(roleUid1, rolePrincipal.getName()); + assertEquals(fullPath, rolePrincipal.getFullPath()); } /** @@ -63,11 +63,11 @@ */ public void testAddDuplicateRolePrincipal() throws Exception { - roleHandler.setRolePrincipal(new RolePrincipalImpl(roleUid1)); + roleHandler.setRolePrincipal(new RolePrincipalImpl(roleUid1)); List roles = roleHandler.getRolePrincipals(""); - assertEquals(1,roles.size()); + assertEquals(1, roles.size()); } - + /** * @throws Exception */ @@ -84,10 +84,12 @@ { RolePrincipal gp = new RolePrincipalImpl(roleUid1); roleHandler.removeRolePrincipal(gp); - RolePrincipal rolePrincipal = roleHandler.getRolePrincipal(gp.getFullPath()); - assertNull("Role was found and should have been removed.", rolePrincipal); + RolePrincipal rolePrincipal = roleHandler.getRolePrincipal(gp + .getFullPath()); + assertNull("Role was found and should have been removed.", + rolePrincipal); List roles = roleHandler.getRolePrincipals(""); - assertEquals(0,roles.size()); + assertEquals(0, roles.size()); } /** @@ -99,7 +101,7 @@ RolePrincipal localPrin = new RolePrincipalImpl(localUid); roleHandler.removeRolePrincipal(localPrin); List roles = roleHandler.getRolePrincipals(""); - assertEquals(1,roles.size()); + assertEquals(1, roles.size()); } /** @@ -110,17 +112,23 @@ try { LdapDataHelper.seedRoleData(gpUid2); - assertTrue("getUserPrincipals should have returned more than one user.", roleHandler.getRolePrincipals("*") - .size() > 1); + assertTrue( + "getUserPrincipals should have returned more than one user.", + roleHandler.getRolePrincipals("*").size() > 1); String fullPath = (new RolePrincipalImpl(roleUid1)).getFullPath(); List roles = roleHandler.getRolePrincipals(fullPath); - assertTrue("getRolePrincipals should have returned one role.", roles.size() == 1); - assertTrue("List should have consisted of RolePrincipal objects.", roles.get(0) instanceof RolePrincipal); + assertTrue("getRolePrincipals should have returned one role.", + roles.size() == 1); + assertTrue("List should have consisted of RolePrincipal objects.", + roles.get(0) instanceof RolePrincipal); String localUid = Integer.toString(rand.nextInt()).toString(); - assertTrue("getRolePrincipals should not have found any roles with the specified filter.", roleHandler - .getRolePrincipals(new RolePrincipalImpl(localUid).getFullPath()).isEmpty()); + assertTrue( + "getRolePrincipals should not have found any roles with the specified filter.", + roleHandler.getRolePrincipals( + new RolePrincipalImpl(localUid).getFullPath()) + .isEmpty()); } finally { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapSecurityMappingHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapSecurityMappingHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapSecurityMappingHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,7 +16,6 @@ */ package org.apache.jetspeed.security.spi.ldap; - import java.util.Set; import org.apache.commons.logging.Log; @@ -34,24 +33,27 @@ * Test the LDAP implementation for the {@link SecurityMappingHandler}. * </p> * - * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long </a>, <a href="dlestrat ¡÷ apache.org">David Le Strat</a> + * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long </a>, <a + * href="dlestrat ¡÷ apache.org">David Le Strat</a> */ public class TestLdapSecurityMappingHandler extends AbstractLdapTest { + /** The logger. */ - private static final Log logger = LogFactory.getLog(TestLdapSecurityMappingHandler.class); + private static final Log logger = LogFactory + .getLog(TestLdapSecurityMappingHandler.class); /** The group principal for gpUid1. */ private GroupPrincipal gp1; - + /** The group principal for gpUid2. */ private GroupPrincipal gp2; - + /** The role principal for gpUid1. */ private RolePrincipal ro1; - + /** The role principal for gpUid2. */ - private RolePrincipal ro2; + private RolePrincipal ro2; /** * @see org.apache.jetspeed.security.spi.ldap.AbstractLdapTest#setUp() @@ -63,12 +65,12 @@ gp2 = new GroupPrincipalImpl(gpUid2); LdapDataHelper.seedGroupData(gpUid1); LdapDataHelper.seedGroupData(gpUid2); - + ro1 = new RolePrincipalImpl(roleUid1); - ro2 = new RolePrincipalImpl(roleUid2); + ro2 = new RolePrincipalImpl(roleUid2); LdapDataHelper.seedRoleData(roleUid1); LdapDataHelper.seedRoleData(roleUid2); - + LdapDataHelper.seedUserData(uid1, password); LdapDataHelper.seedUserData(uid2, password); } @@ -97,18 +99,20 @@ secHandler.setUserPrincipalInGroup(uid1, gp1.getName()); secHandler.setUserPrincipalInGroup(uid2, gp1.getName()); String fullPathName = new GroupPrincipalImpl(gpUid1).getName(); - logger.debug("Group full path name from testGetUserPrincipalsInGroup()[" + fullPathName + "]"); + logger + .debug("Group full path name from testGetUserPrincipalsInGroup()[" + + fullPathName + "]"); Set userPrincipals = secHandler.getUserPrincipalsInGroup(fullPathName); assertTrue(userPrincipals.contains(new UserPrincipalImpl(uid1))); assertTrue(userPrincipals.contains(new UserPrincipalImpl(uid2))); - - assertEquals("The user should have been in two groups.", 2, userPrincipals.size()); + + assertEquals("The user should have been in two groups.", 2, + userPrincipals.size()); } - - /** * Adds 1 user to 2 groups, and checks its presence in both groups + * * @throws Exception */ public void testSetUserPrincipalInGroup() throws Exception @@ -116,13 +120,14 @@ secHandler.setUserPrincipalInGroup(uid1, gp1.getName()); secHandler.setUserPrincipalInGroup(uid1, gp2.getName()); - assertEquals("The user should have been in two groups.", 2, secHandler.getGroupPrincipals(uid1).size()); - + assertEquals("The user should have been in two groups.", 2, secHandler + .getGroupPrincipals(uid1).size()); + } - /** * Adds 1 user to 2 groups, and checks its presence in both groups + * * @throws Exception */ public void testGetUserPrincipalInGroup() throws Exception @@ -131,7 +136,7 @@ secHandler.setUserPrincipalInGroup(uid1, gp2.getName()); secHandler.setUserPrincipalInRole(uid1, ro1.getName()); assertEquals(2, secHandler.getGroupPrincipals(uid1).size()); - } + } /** * @throws Exception @@ -141,29 +146,35 @@ secHandler.setUserPrincipalInGroup(uid1, gp1.getName()); secHandler.setUserPrincipalInGroup(uid1, gp2.getName()); - assertEquals("The user should have been in two groups.", 2, secHandler.getGroupPrincipals(uid1).size()); + assertEquals("The user should have been in two groups.", 2, secHandler + .getGroupPrincipals(uid1).size()); secHandler.removeUserPrincipalInGroup(uid1, gp2.getName()); - assertEquals("The user should have been in one groups.", 1, secHandler.getGroupPrincipals(uid1).size()); + assertEquals("The user should have been in one groups.", 1, secHandler + .getGroupPrincipals(uid1).size()); secHandler.removeUserPrincipalInGroup(uid1, gp1.getName()); - assertEquals("The user should have been in two groups.", 0, secHandler.getGroupPrincipals(uid1).size()); + assertEquals("The user should have been in two groups.", 0, secHandler + .getGroupPrincipals(uid1).size()); } /** * @throws Exception */ - public void testSetUserPrincipalInGroupForNonExistantUser() throws Exception + public void testSetUserPrincipalInGroupForNonExistantUser() + throws Exception { try { - secHandler.setUserPrincipalInGroup(Integer.toString(rand.nextInt()), gpUid1); + secHandler.setUserPrincipalInGroup( + Integer.toString(rand.nextInt()), gpUid1); fail("Trying to associate a group with a non-existant user should have thrown a SecurityException."); } catch (Exception e) { - assertTrue("Trying to associate a group with a non-existant user should have thrown a SecurityException.", + assertTrue( + "Trying to associate a group with a non-existant user should have thrown a SecurityException.", e instanceof SecurityException); } } @@ -171,21 +182,24 @@ /** * @throws Exception */ - public void testSetUserPrincipalInGroupForNonExistantGroup() throws Exception + public void testSetUserPrincipalInGroupForNonExistantGroup() + throws Exception { try { - secHandler.setUserPrincipalInGroup(uid1, Integer.toString(rand.nextInt())); + secHandler.setUserPrincipalInGroup(uid1, Integer.toString(rand + .nextInt())); fail("Trying to associate a user with a non-existant group should have thrown a SecurityException."); } catch (Exception e) { - assertTrue("Trying to associate a user with a non-existant group should have thrown a SecurityException.", + assertTrue( + "Trying to associate a user with a non-existant group should have thrown a SecurityException.", e instanceof SecurityException); } } - + /** * Adds 2 users to a group and checks their presence in the group * @@ -197,13 +211,15 @@ secHandler.setUserPrincipalInRole(uid2, ro1.getName()); String fullPathName = new RolePrincipalImpl(roleUid1).getName(); - logger.debug("Role full path name from testGetUserPrincipalsInRole()[" + fullPathName + "]"); + logger.debug("Role full path name from testGetUserPrincipalsInRole()[" + + fullPathName + "]"); Set userPrincipals = secHandler.getUserPrincipalsInRole(fullPathName); assertTrue(userPrincipals.contains(new UserPrincipalImpl(uid1))); assertTrue(userPrincipals.contains(new UserPrincipalImpl(uid2))); - assertEquals("The user should have been in two roles.", 2, userPrincipals.size()); + assertEquals("The user should have been in two roles.", 2, + userPrincipals.size()); } - + /** * Adds 2 users to a group and checks their presence in the group * @@ -214,14 +230,16 @@ secHandler.setRolePrincipalInGroup(gpUid1, ro1.getName()); secHandler.setRolePrincipalInGroup(gpUid1, ro2.getName()); secHandler.setRolePrincipalInGroup(gpUid2, ro1.getName()); - String fullPathName = new RolePrincipalImpl(roleUid1).getName(); - logger.debug("Role full path name from testGetUserPrincipalsInRole()[" + fullPathName + "]"); - assertEquals("The group should have 2 roles.", 2, secHandler.getRolePrincipalsInGroup(gpUid1).size()); - assertEquals("The group should have 1 role.", 1, secHandler.getRolePrincipalsInGroup(gpUid2).size()); + logger.debug("Role full path name from testGetUserPrincipalsInRole()[" + + fullPathName + "]"); + assertEquals("The group should have 2 roles.", 2, secHandler + .getRolePrincipalsInGroup(gpUid1).size()); + assertEquals("The group should have 1 role.", 1, secHandler + .getRolePrincipalsInGroup(gpUid2).size()); } - + /** * Adds 2 roles + 1 user to a group and checks their presence in the group. * @@ -232,16 +250,17 @@ secHandler.setRolePrincipalInGroup(gpUid1, ro1.getName()); secHandler.setRolePrincipalInGroup(gpUid1, ro2.getName()); secHandler.setRolePrincipalInGroup(gpUid2, ro1.getName()); - secHandler.setUserPrincipalInGroup(uid1,gpUid1); - + secHandler.setUserPrincipalInGroup(uid1, gpUid1); String fullPathName = new RolePrincipalImpl(roleUid1).getName(); - logger.debug("Role full path name from testGetUserPrincipalsInRole()[" + fullPathName + "]"); - assertEquals("The group should have 2 roles.", 2, secHandler.getRolePrincipalsInGroup(gpUid1).size()); - assertEquals("The group should have 1 role.", 1, secHandler.getRolePrincipalsInGroup(gpUid2).size()); - } - - + logger.debug("Role full path name from testGetUserPrincipalsInRole()[" + + fullPathName + "]"); + assertEquals("The group should have 2 roles.", 2, secHandler + .getRolePrincipalsInGroup(gpUid1).size()); + assertEquals("The group should have 1 role.", 1, secHandler + .getRolePrincipalsInGroup(gpUid2).size()); + } + /** * Adds 2 users to a group and checks their presence in the group * @@ -254,16 +273,18 @@ secHandler.setUserPrincipalInRole(uid1, ro1.getName()); secHandler.setUserPrincipalInRole(uid1, ro2.getName()); String fullPathName = new RolePrincipalImpl(gpUid1).getName(); - logger.debug("Role full path name from testGetUserPrincipalsInRole()[" + fullPathName + "]"); - assertEquals("The group should have contained 1 role.", 1, secHandler.getRolePrincipalsInGroup(gpUid1) - .size()); - assertEquals("The group should have contained 1 role.", 1, secHandler.getRolePrincipalsInGroup(gpUid1) - .size()); - - } + logger.debug("Role full path name from testGetUserPrincipalsInRole()[" + + fullPathName + "]"); + assertEquals("The group should have contained 1 role.", 1, secHandler + .getRolePrincipalsInGroup(gpUid1).size()); + assertEquals("The group should have contained 1 role.", 1, secHandler + .getRolePrincipalsInGroup(gpUid1).size()); + } + /** * Adds 1 user to 2 roles, and checks its presence in both roles + * * @throws Exception */ public void testSetUserPrincipalInRole() throws Exception @@ -271,14 +292,16 @@ secHandler.setUserPrincipalInRole(uid1, ro1.getName()); secHandler.setUserPrincipalInRole(uid1, ro2.getName()); Set rolePrinciples = secHandler.getRolePrincipals(uid1); - assertEquals("The user should have been in two roles.", 2, rolePrinciples.size()); + assertEquals("The user should have been in two roles.", 2, + rolePrinciples.size()); assertTrue(rolePrinciples.contains(ro1)); assertTrue(rolePrinciples.contains(ro2)); - + } - + /** * Adds 1 user to 2 roles & 1 group, and checks its presence in both roles + * * @throws Exception */ public void testSetUserPrincipalInRole2() throws Exception @@ -287,12 +310,13 @@ secHandler.setUserPrincipalInRole(uid1, ro2.getName()); secHandler.setUserPrincipalInGroup(uid1, gp1.getName()); Set rolePrinciples = secHandler.getRolePrincipals(uid1); - assertEquals("The user should have been in two roles.", 2, rolePrinciples.size()); + assertEquals("The user should have been in two roles.", 2, + rolePrinciples.size()); assertTrue(rolePrinciples.contains(ro1)); assertTrue(rolePrinciples.contains(ro2)); - - } + } + /** * @throws Exception */ @@ -300,16 +324,18 @@ { secHandler.setUserPrincipalInRole(uid1, ro1.getName()); secHandler.setUserPrincipalInRole(uid1, ro2.getName()); - assertEquals("The user should have been in two roles.", 2, secHandler.getRolePrincipals(uid1).size()); + assertEquals("The user should have been in two roles.", 2, secHandler + .getRolePrincipals(uid1).size()); secHandler.removeUserPrincipalInRole(uid1, ro1.getName()); - assertEquals("The user should have been in one roles.", 1, secHandler.getRolePrincipals(uid1).size()); + assertEquals("The user should have been in one roles.", 1, secHandler + .getRolePrincipals(uid1).size()); secHandler.removeUserPrincipalInRole(uid1, ro2.getName()); - assertEquals("The user should have been in zero roles.", 0, secHandler.getRolePrincipals(uid1).size()); + assertEquals("The user should have been in zero roles.", 0, secHandler + .getRolePrincipals(uid1).size()); } - - + /** * @throws Exception */ @@ -317,15 +343,17 @@ { secHandler.setRolePrincipalInGroup(gpUid1, ro1.getName()); secHandler.setRolePrincipalInGroup(gpUid1, ro2.getName()); - assertEquals("The role should have been in two groups.", 2, secHandler.getRolePrincipalsInGroup(gpUid1).size()); + assertEquals("The role should have been in two groups.", 2, secHandler + .getRolePrincipalsInGroup(gpUid1).size()); - secHandler.removeRolePrincipalInGroup(gpUid1,ro1.getName()); - assertEquals("The role should have been in one group.", 1, secHandler.getRolePrincipalsInGroup(gpUid1).size()); + secHandler.removeRolePrincipalInGroup(gpUid1, ro1.getName()); + assertEquals("The role should have been in one group.", 1, secHandler + .getRolePrincipalsInGroup(gpUid1).size()); secHandler.removeRolePrincipalInGroup(gpUid1, ro2.getName()); - assertEquals("The role should have been in 0 roles.", 0, secHandler.getRolePrincipalsInGroup(gpUid1).size()); + assertEquals("The role should have been in 0 roles.", 0, secHandler + .getRolePrincipalsInGroup(gpUid1).size()); } - /** * @throws Exception @@ -334,13 +362,15 @@ { try { - secHandler.setUserPrincipalInRole(Integer.toString(rand.nextInt()), roleUid1); + secHandler.setUserPrincipalInRole(Integer.toString(rand.nextInt()), + roleUid1); fail("Trying to associate a role with a non-existant user should have thrown a SecurityException."); } catch (Exception e) { - assertTrue("Trying to associate a role with a non-existant user should have thrown a SecurityException.", + assertTrue( + "Trying to associate a role with a non-existant user should have thrown a SecurityException.", e instanceof SecurityException); } } @@ -352,14 +382,16 @@ { try { - secHandler.setUserPrincipalInRole(uid1, Integer.toString(rand.nextInt())); + secHandler.setUserPrincipalInRole(uid1, Integer.toString(rand + .nextInt())); fail("Trying to associate a user with a non-existant role should have thrown a SecurityException."); } catch (Exception e) { - assertTrue("Trying to associate a user with a non-existant role should have thrown a SecurityException.", + assertTrue( + "Trying to associate a user with a non-existant role should have thrown a SecurityException.", e instanceof SecurityException); } - } + } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapUserCredentialDao.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapUserCredentialDao.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapUserCredentialDao.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,11 +32,13 @@ * Test the {@link LdapUserCredentialDao}. * </p> * - * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long </a>, <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> - * + * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long </a>, <a + * href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> + * */ public class TestLdapUserCredentialDao extends AbstractLdapTest { + /** Configuration for the number of threads performing login. */ private static int NUMBER_OF_LOGIN_THREADS = 5; @@ -47,7 +49,8 @@ private static Map loginThreads = new HashMap(); /** The logger. */ - private static final Log log = LogFactory.getLog(TestLdapUserCredentialDao.class); + private static final Log log = LogFactory + .getLog(TestLdapUserCredentialDao.class); /** * @see org.apache.jetspeed.security.spi.ldap.AbstractLdapTest#setUp() @@ -57,7 +60,7 @@ super.setUp(); LdapDataHelper.seedUserData(uid1, password); } - + /** * @see org.apache.jetspeed.security.spi.ldap.AbstractLdapTest#tearDown() */ @@ -72,16 +75,19 @@ * Test <code>authenticate</code> with correct login. * </p> * - * @throws Exception An {@link Exception}. + * @throws Exception + * An {@link Exception}. */ public void testGoodLogin() throws Exception { - assertTrue("The login failed for user.", ldapCredDao.authenticate(uid1, password)); + assertTrue("The login failed for user.", ldapCredDao.authenticate(uid1, + password)); } - + /** * <p> - * Test regular expression to match any of the following characters: ([{\^$|)?*+. + * Test regular expression to match any of the following characters: + * ([{\^$|)?*+. * </p> * * @throws Exception @@ -123,7 +129,8 @@ * <code>([{\^$|)?*+.</code> * </p> * - * @throws Exception An {@link Exception}. + * @throws Exception + * An {@link Exception}. */ public void testRegularExpessionInUid() throws Exception { @@ -147,9 +154,11 @@ * Test <code>authenticate</code> with incorrect character in uid. * </p> * - * @throws Exception An {@link Exception}. + * @throws Exception + * An {@link Exception}. */ - private void verifyRegularExpressionFails(String metaCharacter) throws Exception + private void verifyRegularExpressionFails(String metaCharacter) + throws Exception { try { @@ -169,7 +178,8 @@ * Test <code>authenticate</code> with no password. * </p> * - * @throws Exception An {@link Exception}. + * @throws Exception + * An {@link Exception}. */ public void testCannotAuthenticateWithNoPassword() throws Exception { @@ -181,7 +191,9 @@ catch (Exception e) { log.debug(e); - assertTrue("Should have thrown an SecurityException. Instead it threw:" + e.getClass().getName(), + assertTrue( + "Should have thrown an SecurityException. Instead it threw:" + + e.getClass().getName(), e instanceof SecurityException); } @@ -192,7 +204,8 @@ } catch (Exception e) { - assertTrue("Should have thrown an SecurityException." + e, e instanceof SecurityException); + assertTrue("Should have thrown an SecurityException." + e, + e instanceof SecurityException); } } @@ -201,7 +214,8 @@ * Test <code>authenticate</code> with bad uid. * </p> * - * @throws Exception An {@link Exception}. + * @throws Exception + * An {@link Exception}. */ public void testBadUID() throws Exception { @@ -213,7 +227,8 @@ } catch (Exception e) { - assertTrue("Should have thrown a SecurityException for a non-existant user.", + assertTrue( + "Should have thrown a SecurityException for a non-existant user.", e instanceof SecurityException); } @@ -224,11 +239,13 @@ * Test <code>authenticate</code> with bad password. * </p> * - * @throws Exception An {@link Exception}. + * @throws Exception + * An {@link Exception}. */ public void testBadPassword() throws Exception { - assertFalse("Should not have authenticated with bad password.", ldapCredDao.authenticate(uid1, password + "123")); + assertFalse("Should not have authenticated with bad password.", + ldapCredDao.authenticate(uid1, password + "123")); } /** @@ -236,7 +253,8 @@ * Test <code>authenticate</code> with concurrent logins. * </p> * - * @throws Exception An {@link Exception}. + * @throws Exception + * An {@link Exception}. */ public void testConcurrentLogins() throws Exception { @@ -248,9 +266,13 @@ } Thread.sleep(6000); - assertTrue("Not all login threads completed.", loginThreads.size() == NUMBER_OF_LOGIN_THREADS); - assertTrue("Not all login threads successfully ran all their logins().", allLoginThreadsCompletedTheirLogins()); - assertFalse("An exception was thrown by a login thread. This means there is a concurrency problem.", + assertTrue("Not all login threads completed.", + loginThreads.size() == NUMBER_OF_LOGIN_THREADS); + assertTrue( + "Not all login threads successfully ran all their logins().", + allLoginThreadsCompletedTheirLogins()); + assertFalse( + "An exception was thrown by a login thread. This means there is a concurrency problem.", exceptionThrownByLogin()); } @@ -266,7 +288,8 @@ while (loginThreadStatuses.hasNext()) { - LoginThreadStatus status = (LoginThreadStatus) loginThreadStatuses.next(); + LoginThreadStatus status = (LoginThreadStatus) loginThreadStatuses + .next(); if (status.isSomeExceptionThrown()) { @@ -289,7 +312,8 @@ while (loginThreadStatuses.hasNext()) { - LoginThreadStatus status = (LoginThreadStatus) loginThreadStatuses.next(); + LoginThreadStatus status = (LoginThreadStatus) loginThreadStatuses + .next(); if (status.getNumberOfSuccessfulLogins() < NUMBER_OF_LOGINS_PER_THREAD) { @@ -307,6 +331,7 @@ */ private class LoginThread extends Thread { + /** The login thread status. */ private LoginThreadStatus status = new LoginThreadStatus(); @@ -327,7 +352,8 @@ { try { - assertTrue("The login failed for user.", threadLdap.authenticate(uid1, password)); + assertTrue("The login failed for user.", threadLdap + .authenticate(uid1, password)); status.incrementNumberOfSuccessfulLogins(); } catch (Exception e) @@ -349,6 +375,7 @@ class LoginThreadStatus { + private int numberOfSuccessfulLogins; private boolean someExceptionThrown; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapUserSecurityDao.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapUserSecurityDao.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapUserSecurityDao.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,7 +24,8 @@ * Test the {@link LdapUserSecurityDao}. * </p> * - * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long </a>, <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> + * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long </a>, <a + * href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public class TestLdapUserSecurityDao extends AbstractLdapTest { @@ -37,7 +38,7 @@ super.setUp(); LdapDataHelper.seedUserData(uid1, password); } - + /** * @see org.apache.jetspeed.security.spi.ldap.AbstractLdapTest#tearDown() */ @@ -52,11 +53,13 @@ * Test <code>lookupByUid</code> with a good uid. * </p> * - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ public void testLookupByGoodUID() throws SecurityException { - assertFalse("The loookup failed for user.", StringUtils.isEmpty(ldapPrincipalDao.lookupByUid(uid1))); + assertFalse("The loookup failed for user.", StringUtils + .isEmpty(ldapPrincipalDao.lookupByUid(uid1))); } /** @@ -64,11 +67,12 @@ * Test <code>lookupByUid</code> with a bad uid. * </p> * - * @throws SecurityException A {@link SecurityException}. + * @throws SecurityException + * A {@link SecurityException}. */ public void testLookupByBadUID() throws SecurityException { - assertTrue("The lookup should have failed for user:" + uid1 + "123", StringUtils.isEmpty(ldapPrincipalDao.lookupByUid(uid1 - + "123"))); + assertTrue("The lookup should have failed for user:" + uid1 + "123", + StringUtils.isEmpty(ldapPrincipalDao.lookupByUid(uid1 + "123"))); } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapUserSecurityHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapUserSecurityHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/spi/ldap/TestLdapUserSecurityHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,25 +16,25 @@ */ package org.apache.jetspeed.security.spi.ldap; +import java.security.Principal; +import java.util.List; + import org.apache.jetspeed.security.SecurityException; import org.apache.jetspeed.security.UserPrincipal; import org.apache.jetspeed.security.impl.UserPrincipalImpl; -import java.security.Principal; - -import java.util.List; - /** * <p> - * LdapServerTest - This class tests the LdapServer. It assumes that the following three - * inetOrgPerson objects exist: uid:cbrewton password:maddie uid:dlong, password: uid:mlong, - * password:maddie + * LdapServerTest - This class tests the LdapServer. It assumes that the + * following three inetOrgPerson objects exist: uid:cbrewton password:maddie + * uid:dlong, password: uid:mlong, password:maddie * </p> * * @author <a href="mailto:mike.long ¡÷ dataline.com">Mike Long </a> */ public class TestLdapUserSecurityHandler extends AbstractLdapTest { + /** * @see org.apache.jetspeed.security.spi.ldap.AbstractLdapTest#setUp() */ @@ -66,8 +66,8 @@ */ public void testUserIsNotPrincipal() throws Exception { - assertFalse("User is principal and should not be.", userHandler.isUserPrincipal(Integer - .toString(rand.nextInt()).toString())); + assertFalse("User is principal and should not be.", userHandler + .isUserPrincipal(Integer.toString(rand.nextInt()).toString())); } /** @@ -82,7 +82,8 @@ } catch (Exception e) { - assertTrue("Adding an already existant user should have thrown a SecurityException.", + assertTrue( + "Adding an already existant user should have thrown a SecurityException.", e instanceof SecurityException); } } @@ -92,7 +93,8 @@ */ public void testAddUserPrincipal() throws Exception { - assertTrue("User not found.", userHandler.getUserPrincipal(uid1) != null); + assertTrue("User not found.", + userHandler.getUserPrincipal(uid1) != null); } /** @@ -102,7 +104,8 @@ { UserPrincipal up = new UserPrincipalImpl(uid1); userHandler.removeUserPrincipal(up); - assertTrue("User was found and should have been removed.", userHandler.getUserPrincipal(uid1) == null); + assertTrue("User was found and should have been removed.", userHandler + .getUserPrincipal(uid1) == null); } /** @@ -125,23 +128,28 @@ { LdapDataHelper.seedUserData(uid2, password); // With wild card search - assertTrue("getUserPrincipals should have returned more than one user.", userHandler.getUserPrincipals("*") - .size() > 1); - + assertTrue( + "getUserPrincipals should have returned more than one user.", + userHandler.getUserPrincipals("*").size() > 1); + // With empty string search - assertTrue("getUserPrincipals should have returned more than one user.", userHandler.getUserPrincipals("") - .size() > 1); + assertTrue( + "getUserPrincipals should have returned more than one user.", + userHandler.getUserPrincipals("").size() > 1); // With specific uid. List users = userHandler.getUserPrincipals(uid1); - assertTrue("getUserPrincipals should have returned one user.", users.size() == 1); - assertTrue("List should have consisted of Principal objects.", users.get(0) instanceof Principal); + assertTrue("getUserPrincipals should have returned one user.", + users.size() == 1); + assertTrue("List should have consisted of Principal objects.", + users.get(0) instanceof Principal); String localUid = Integer.toString(rand.nextInt()).toString(); - assertTrue("getUserPrincipals should not have found any users with the specified filter.", userHandler - .getUserPrincipals(localUid).isEmpty()); + assertTrue( + "getUserPrincipals should not have found any users with the specified filter.", + userHandler.getUserPrincipals(localUid).isEmpty()); } finally { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/util/TestPBEPasswordTool.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/util/TestPBEPasswordTool.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/security/src/test/org/apache/jetspeed/security/util/TestPBEPasswordTool.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,23 +30,32 @@ { /* - * Test method for 'org.apache.jetspeed.security.util.PBEPasswordTool.encode(String, String)' + * Test method for + * 'org.apache.jetspeed.security.util.PBEPasswordTool.encode(String, + * String)' */ public void testEncode() throws Exception { PBEPasswordTool pbe = new PBEPasswordTool("123"); - // check the same password is encoded differently for different usernames - assertNotSame("Encoded password should not be the same for different users", pbe.encode("user1","abc123"), pbe.encode("user2","abc123")); + // check the same password is encoded differently for different + // usernames + assertNotSame( + "Encoded password should not be the same for different users", + pbe.encode("user1", "abc123"), pbe.encode("user2", "abc123")); } /* - * Test method for 'org.apache.jetspeed.security.util.PBEPasswordTool.decode(String, String)' + * Test method for + * 'org.apache.jetspeed.security.util.PBEPasswordTool.decode(String, + * String)' */ public void testDecode() throws Exception { PBEPasswordTool pbe = new PBEPasswordTool("123"); - // check the same password is encoded differently for different usernames - assertEquals("Decoded password doesn't match original", "abc123", pbe.decode("user1", pbe.encode("user1","abc123"))); + // check the same password is encoded differently for different + // usernames + assertEquals("Decoded password doesn't match original", "abc123", pbe + .decode("user1", pbe.encode("user1", "abc123"))); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedDDLApplication.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedDDLApplication.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedDDLApplication.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,6 +26,7 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; + import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; @@ -42,6 +43,7 @@ import org.apache.jetspeed.serializer.objects.JSGroup; import org.apache.log4j.Level; import org.apache.log4j.Logger; + /** * Jetspeed Serializer DDL- Application * @@ -104,724 +106,744 @@ */ public class JetspeedDDLApplication { - public static final String JNDI_DS_NAME = "jetspeed"; - String propertyFileName = null; - String exludeFileName = null; - String orderFileName = null; + public static final String JNDI_DS_NAME = "jetspeed"; - String logLevel = null; + String propertyFileName = null; - PropertiesConfiguration configuration = null; + String exludeFileName = null; - boolean doImport = false; - boolean doExport = false; - String schemaDirectory = null; // if specified all xml files in that - // directory will be processed - String outputFile = null; // if specified the database schema will be - // exported to that file - boolean overwrite = false; // default, do not overwrite the database - // (ignored if only output) - String driverClass = null; // jdbc driver - String url = null; // jdbc url to database - String user = null; // user - String password = null; // password - String databaseName = null; - - String[] filesToProcess = null; + String orderFileName = null; - String mergeFile = null; //name of XSLT merge file - String[] args = null; + String logLevel = null; - public static void main(String[] args) throws Exception - { - JetspeedDDLApplication app = new JetspeedDDLApplication(); - app.processArguments(args); - } + PropertiesConfiguration configuration = null; - public JetspeedDDLApplication() - { - } + boolean doImport = false; - /** - * ensure that we have valid database settings - * - */ - private void checkDBSettings() - { - if (databaseName == null) - databaseName = System.getProperty( - "org.apache.jetspeed.database.databaseName", - "mysql"); - if (driverClass == null) - driverClass = System.getProperty( - "org.apache.jetspeed.database.driverClass", - "com.mysql.jdbc.Driver"); - if (url == null) - url = System.getProperty("org.apache.jetspeed.database.url", - "jdbc:mysql://localhost/j2test"); - if (user == null) - user = System.getProperty("org.apache.jetspeed.database.user", - "user"); - if (password == null) - password = System.getProperty( - "org.apache.jetspeed.database.password", "password"); + boolean doExport = false; - if (driverClass == null) - throw new IllegalArgumentException( - "Can't proceed without a valid driver"); - if (url == null) - throw new IllegalArgumentException( - "Can't proceed without a valid url to the target database"); - if (user == null) - throw new IllegalArgumentException( - "Can't proceed without a valid database user"); - return; - } + String schemaDirectory = null; // if specified all xml files in that - /** - * parse arguments for process instructions, order and exclude files as well - * as optional database arguments - * - */ - private void parseArguments() - { - // Parse all the command-Oine arguments - for (int n = 0; n < args.length; n++) - { - if (args[n].equals("-I")) - { - doImport = true; - schemaDirectory = args[++n]; - } else if (args[n].equals("-O")) - { - doExport = true; - outputFile = args[++n]; - } else if (args[n].equals("-s")) - { - orderFileName = args[++n]; - } - else if (args[n].equals("-x")) - { - exludeFileName = args[++n]; - } - else if (args[n].equals("-m")) - { - mergeFile = args[++n]; - } - else if (args[n].equals("-R")) - overwrite = true; - else if (args[n].equals("-dn")) + // directory will be processed + String outputFile = null; // if specified the database schema will be + + // exported to that file + boolean overwrite = false; // default, do not overwrite the database + + // (ignored if only output) + String driverClass = null; // jdbc driver + + String url = null; // jdbc url to database + + String user = null; // user + + String password = null; // password + + String databaseName = null; + + String[] filesToProcess = null; + + String mergeFile = null; // name of XSLT merge file + + String[] args = null; + + public static void main(String[] args) throws Exception + { + JetspeedDDLApplication app = new JetspeedDDLApplication(); + app.processArguments(args); + } + + public JetspeedDDLApplication() + { + } + + /** + * ensure that we have valid database settings + * + */ + private void checkDBSettings() + { + if (databaseName == null) + databaseName = System.getProperty( + "org.apache.jetspeed.database.databaseName", "mysql"); + if (driverClass == null) + driverClass = System.getProperty( + "org.apache.jetspeed.database.driverClass", + "com.mysql.jdbc.Driver"); + if (url == null) + url = System.getProperty("org.apache.jetspeed.database.url", + "jdbc:mysql://localhost/j2test"); + if (user == null) + user = System.getProperty("org.apache.jetspeed.database.user", + "user"); + if (password == null) + password = System.getProperty( + "org.apache.jetspeed.database.password", "password"); + + if (driverClass == null) + throw new IllegalArgumentException( + "Can't proceed without a valid driver"); + if (url == null) + throw new IllegalArgumentException( + "Can't proceed without a valid url to the target database"); + if (user == null) + throw new IllegalArgumentException( + "Can't proceed without a valid database user"); + return; + } + + /** + * parse arguments for process instructions, order and exclude files as well + * as optional database arguments + * + */ + private void parseArguments() + { + // Parse all the command-Oine arguments + for (int n = 0; n < args.length; n++) + { + if (args[n].equals("-I")) { - databaseName = args[++n]; + doImport = true; + schemaDirectory = args[++n]; } - else if (args[n].equals("-dc")) - driverClass = args[++n]; - else if (args[n].equals("-ds")) - url = args[++n]; - else if (args[n].equals("-du")) + else if (args[n].equals("-O")) { + doExport = true; + outputFile = args[++n]; + } + else if (args[n].equals("-s")) + { + orderFileName = args[++n]; + } + else if (args[n].equals("-x")) + { + exludeFileName = args[++n]; + } + else if (args[n].equals("-m")) + { + mergeFile = args[++n]; + } + else if (args[n].equals("-R")) + overwrite = true; + else if (args[n].equals("-dn")) + { + databaseName = args[++n]; + } + else if (args[n].equals("-dc")) + driverClass = args[++n]; + else if (args[n].equals("-ds")) + url = args[++n]; + else if (args[n].equals("-du")) + { if (((n + 1) >= args.length) || args[n + 1].startsWith("-d")) { user = ""; - } else + } + else { user = args[++n]; } - } - else if (args[n].equals("-dp")) + } + else if (args[n].equals("-dp")) { if (((n + 1) >= args.length) || args[n + 1].startsWith("-d")) { password = ""; - } else + } + else { password = args[++n]; } - } - else if (args[n].equals("-P")) - propertyFileName = args[++n]; - else if (args[n].equals("-l")) - logLevel = args[++n]; + } + else if (args[n].equals("-P")) + propertyFileName = args[++n]; + else if (args[n].equals("-l")) + logLevel = args[++n]; - else - throw new IllegalArgumentException("Unknown argument: " - + args[n]); - } + else + throw new IllegalArgumentException("Unknown argument: " + + args[n]); + } - } + } - /** - * process provided filename or directory name - * - * @return one or more files to be processed - */ - private String[] parseFiles() - { - String[] fileList = null; - try - { - File dir = new File(schemaDirectory); - if (!(dir.exists())) - return fileList; - if (!(dir.isDirectory())) - { - fileList = new String[1]; - fileList[0] = schemaDirectory; - return fileList; - } - // Handling a directory - LocalFilenameFilter filter = new LocalFilenameFilter( - exludeFileName, orderFileName); - File[] files = dir.listFiles(filter); - if (files == null) - return fileList; + /** + * process provided filename or directory name + * + * @return one or more files to be processed + */ + private String[] parseFiles() + { + String[] fileList = null; + try + { + File dir = new File(schemaDirectory); + if (!(dir.exists())) return fileList; + if (!(dir.isDirectory())) + { + fileList = new String[1]; + fileList[0] = schemaDirectory; + return fileList; + } + // Handling a directory + LocalFilenameFilter filter = new LocalFilenameFilter( + exludeFileName, orderFileName); + File[] files = dir.listFiles(filter); + if (files == null) return fileList; - fileList = new String[files.length]; - String sortorderFile = filter.getSortFile(); - if (sortorderFile == null) - { - for (int i = 0; i < files.length; i++) - fileList[i] = files[i].getAbsolutePath(); - return fileList; - } - try - { - ArrayList list = readOrderFile(sortorderFile); - fileList = new String[files.length]; - if ((list == null) || (list.size() == 0)) - { - for (int i = 0; i < files.length; i++) - fileList[i] = files[i].getAbsolutePath(); - return fileList; - } - String[] tempList = new String[files.length]; - for (int i = 0; i < files.length; i++) - tempList[i] = files[i].getName(); - Iterator _it = list.iterator(); - int j = 0; - while (_it.hasNext()) - { - String filename = null; - try - { - filename = ((JSGroup) _it.next()).getName(); - } catch (Exception eeee) - { - } - if (filename != null) - { - for (int i = 0; i < files.length; i++) - { - if (filename.equalsIgnoreCase(tempList[i])) - { - fileList[j++] = files[i].getAbsolutePath(); - tempList[i] = null; - } - } - } - } - for (int i = 0; i < files.length; i++) - { - if (tempList[i] != null) - fileList[j++] = files[i].getAbsolutePath(); - } - return fileList; - } catch (Exception eee) - { - eee.printStackTrace(); - return null; - } + fileList = new String[files.length]; + String sortorderFile = filter.getSortFile(); + if (sortorderFile == null) + { + for (int i = 0; i < files.length; i++) + fileList[i] = files[i].getAbsolutePath(); + return fileList; + } + try + { + ArrayList list = readOrderFile(sortorderFile); + fileList = new String[files.length]; + if ((list == null) || (list.size() == 0)) + { + for (int i = 0; i < files.length; i++) + fileList[i] = files[i].getAbsolutePath(); + return fileList; + } + String[] tempList = new String[files.length]; + for (int i = 0; i < files.length; i++) + tempList[i] = files[i].getName(); + Iterator _it = list.iterator(); + int j = 0; + while (_it.hasNext()) + { + String filename = null; + try + { + filename = ((JSGroup) _it.next()).getName(); + } + catch (Exception eeee) + { + } + if (filename != null) + { + for (int i = 0; i < files.length; i++) + { + if (filename.equalsIgnoreCase(tempList[i])) + { + fileList[j++] = files[i].getAbsolutePath(); + tempList[i] = null; + } + } + } + } + for (int i = 0; i < files.length; i++) + { + if (tempList[i] != null) + fileList[j++] = files[i].getAbsolutePath(); + } + return fileList; + } + catch (Exception eee) + { + eee.printStackTrace(); + return null; + } - } catch (Exception e) - { - e.printStackTrace(); - throw new IllegalArgumentException( - "Processing the schema-directory " + schemaDirectory - + " caused exception " + e.getLocalizedMessage()); - } + } + catch (Exception e) + { + e.printStackTrace(); + throw new IllegalArgumentException( + "Processing the schema-directory " + schemaDirectory + + " caused exception " + e.getLocalizedMessage()); + } - } + } - /** - * setup environment by processing all arguments and call requested process - * routine - * - * @param arguments - * @throws Exception - */ - private void processArguments(String[] arguments) throws Exception - { - this.args = arguments; - if (args == null) - throw new IllegalArgumentException( - "Either a schema directory, a schema file or an output filename have to be defined (-D followed by a driectory, -I or -O followed by the filename"); + /** + * setup environment by processing all arguments and call requested process + * routine + * + * @param arguments + * @throws Exception + */ + private void processArguments(String[] arguments) throws Exception + { + this.args = arguments; + if (args == null) + throw new IllegalArgumentException( + "Either a schema directory, a schema file or an output filename have to be defined (-D followed by a driectory, -I or -O followed by the filename"); - parseArguments(); + parseArguments(); - processPropertyFile(); + processPropertyFile(); - checkDBSettings(); + checkDBSettings(); - /** - * The only required argument is the filename for either export or - * import - */ - if ((!doImport) && (!doExport)) - throw new IllegalArgumentException( - "Either a schema directory, a schema file or an output filename have to be defined (-I or -O followed by the directory-/filename"); + /** + * The only required argument is the filename for either export or + * import + */ + if ((!doImport) && (!doExport)) + throw new IllegalArgumentException( + "Either a schema directory, a schema file or an output filename have to be defined (-I or -O followed by the directory-/filename"); - if (doImport) - { - filesToProcess = parseFiles(); - if (filesToProcess == null) - return; - } + if (doImport) + { + filesToProcess = parseFiles(); + if (filesToProcess == null) return; + } - /** create the instruction map */ - JetspeedDDLUtil ddlUtil = null; + /** create the instruction map */ + JetspeedDDLUtil ddlUtil = null; - HashMap context = new HashMap(); - context.put(JetspeedDDLUtil.DATASOURCE_DATABASENAME, databaseName); - context.put(JetspeedDDLUtil.DATASOURCE_DRIVER, driverClass); - context.put(JetspeedDDLUtil.DATASOURCE_URL, url); - context.put(JetspeedDDLUtil.DATASOURCE_USERNAME, user); - context.put(JetspeedDDLUtil.DATASOURCE_PASSWORD, password); + HashMap context = new HashMap(); + context.put(JetspeedDDLUtil.DATASOURCE_DATABASENAME, databaseName); + context.put(JetspeedDDLUtil.DATASOURCE_DRIVER, driverClass); + context.put(JetspeedDDLUtil.DATASOURCE_URL, url); + context.put(JetspeedDDLUtil.DATASOURCE_USERNAME, user); + context.put(JetspeedDDLUtil.DATASOURCE_PASSWORD, password); - Logger logger = Logger.getLogger("org.apache.ddlutils"); - Level level = logger.getLevel(); - if (logLevel == null) - logger.setLevel(Level.ERROR); - else if (logLevel.equalsIgnoreCase("INFO")) - logger.setLevel(Level.INFO); - else if (logLevel.equalsIgnoreCase("WARN")) - logger.setLevel(Level.WARN); - else - logger.setLevel(Level.ERROR); + Logger logger = Logger.getLogger("org.apache.ddlutils"); + Level level = logger.getLevel(); + if (logLevel == null) + logger.setLevel(Level.ERROR); + else if (logLevel.equalsIgnoreCase("INFO")) + logger.setLevel(Level.INFO); + else if (logLevel.equalsIgnoreCase("WARN")) + logger.setLevel(Level.WARN); + else + logger.setLevel(Level.ERROR); - try - { - ddlUtil = new JetspeedDDLUtil(); - ddlUtil.startUp(); - ddlUtil.init(context); - } catch (Exception e) - { - System.err.println("Failed to initialize Utility!!!!!"); - e.printStackTrace(); - System.exit(-1); - } - try - { - if (doImport) - processImport(ddlUtil); - if (doExport) - processExport(ddlUtil); - } catch (Exception e) - { - System.err.println("Failed to process XML " - + (doExport ? "export" : "import") + ":" + e); - e.printStackTrace(); - } finally - { - try - { - logger.setLevel(level); - if (ddlUtil != null) - ddlUtil.tearDown(); - } catch (Exception e1) - { - System.out - .println("starter framework teardown caused exception " - + e1.getLocalizedMessage()); - e1.printStackTrace(); + try + { + ddlUtil = new JetspeedDDLUtil(); + ddlUtil.startUp(); + ddlUtil.init(context); + } + catch (Exception e) + { + System.err.println("Failed to initialize Utility!!!!!"); + e.printStackTrace(); + System.exit(-1); + } + try + { + if (doImport) processImport(ddlUtil); + if (doExport) processExport(ddlUtil); + } + catch (Exception e) + { + System.err.println("Failed to process XML " + + (doExport ? "export" : "import") + ":" + e); + e.printStackTrace(); + } + finally + { + try + { + logger.setLevel(level); + if (ddlUtil != null) ddlUtil.tearDown(); + } + catch (Exception e1) + { + System.out + .println("starter framework teardown caused exception " + + e1.getLocalizedMessage()); + e1.printStackTrace(); - } - } + } + } - } + } - /** - * create/alter database - * - * @param ddlUtil - */ - private void processImport(JetspeedDDLUtil ddlUtil) - { - String file = null; - if ((filesToProcess == null) || (filesToProcess.length == 0)) - return; - if (filesToProcess.length > 1) - file = mergeFiles(filesToProcess); + /** + * create/alter database + * + * @param ddlUtil + */ + private void processImport(JetspeedDDLUtil ddlUtil) + { + String file = null; + if ((filesToProcess == null) || (filesToProcess.length == 0)) return; + if (filesToProcess.length > 1) file = mergeFiles(filesToProcess); - System.out.println("Importing " + file); - Database db = ddlUtil.createDatabaseSchemaFromXML(file); - try - { - if (overwrite) - ddlUtil.createDatabase(db); // overwrite existing - // database - else - ddlUtil.alterDatabase(db); - System.out.println("Importing " + file + " completed"); - } catch (Exception ePr) - { - ePr.printStackTrace(); - // continue with the process despite that one of the files was - // bad... - } + System.out.println("Importing " + file); + Database db = ddlUtil.createDatabaseSchemaFromXML(file); + try + { + if (overwrite) + ddlUtil.createDatabase(db); // overwrite existing + // database + else + ddlUtil.alterDatabase(db); + System.out.println("Importing " + file + " completed"); + } + catch (Exception ePr) + { + ePr.printStackTrace(); + // continue with the process despite that one of the files was + // bad... + } - } + } - /** - * Helper routine to create a temporary file - * - * @param suffix - * @return - */ - private File createTemp(String suffix) - { - try - { - // Create temp file. - File temp = File.createTempFile("tmp", suffix); + /** + * Helper routine to create a temporary file + * + * @param suffix + * @return + */ + private File createTemp(String suffix) + { + try + { + // Create temp file. + File temp = File.createTempFile("tmp", suffix); - // Delete temp file when program exits. - temp.deleteOnExit(); - return temp; - } catch (IOException e) - { - System.out.println("Failed to create temproary file with " - + e.getLocalizedMessage()); - e.printStackTrace(); - return null; - } + // Delete temp file when program exits. + temp.deleteOnExit(); + return temp; + } + catch (IOException e) + { + System.out.println("Failed to create temproary file with " + + e.getLocalizedMessage()); + e.printStackTrace(); + return null; + } - } - /** - * Open the merge file from disk - * - * @param fileName - * @return - */ - private File createXSLTFromFile(String fileName) - { - if (fileName == null) - return null; - try - { - File f = new File(fileName); - if (f.exists()) - return f; - return null; - } - catch (Exception e) - { - System.out.println("Failed to open merge template " + e.getLocalizedMessage()); - e.printStackTrace(); - return null; - } - } - /** - * If everything else fails, use a hardcoded XSLT here - * - * @return - */ - private File createXSLTFromMemory() - { - StringBuffer buffer = new StringBuffer(); + } - buffer.append("<?xml version=\"1.0\"?>"); - buffer - .append("<xslt:transform version=\"1.0\" xmlns:xslt=\"http://www.w3.org/1999/XSL/Transform\">"); - buffer - .append("<!-- Simple template to merge two database schemas into one -->"); - buffer.append("<xslt:param name=\"fileTwo\" />"); - buffer.append("<xslt:template match=\"/\">"); + /** + * Open the merge file from disk + * + * @param fileName + * @return + */ + private File createXSLTFromFile(String fileName) + { + if (fileName == null) return null; + try + { + File f = new File(fileName); + if (f.exists()) return f; + return null; + } + catch (Exception e) + { + System.out.println("Failed to open merge template " + + e.getLocalizedMessage()); + e.printStackTrace(); + return null; + } + } - buffer.append("<xslt:message>"); - buffer - .append("<xslt:text /> Merging input with '<xslt:value-of select=\"$fileTwo\"/>"); - buffer.append("<xslt:text>'</xslt:text>"); - buffer.append("</xslt:message>"); - buffer.append("<xslt:if test=\"string($fileTwo)=''\">"); - buffer.append("<xslt:message terminate=\"yes\">"); - buffer - .append("<xslt:text>No input file specified (parameter 'fileTwo')</xslt:text>"); - buffer.append("</xslt:message>"); - buffer.append("</xslt:if>"); - buffer.append("<database name=\"generic\">"); - buffer.append("<xslt:apply-templates />"); - buffer.append("</database>"); - buffer.append("</xslt:template>"); - buffer.append("<xslt:template match=\"database\">"); - buffer.append("<xslt:apply-templates />"); - buffer.append("<xslt:apply-templates select=\"document($fileTwo)/database/table\"/>"); - buffer.append("</xslt:template>"); + /** + * If everything else fails, use a hardcoded XSLT here + * + * @return + */ + private File createXSLTFromMemory() + { + StringBuffer buffer = new StringBuffer(); - buffer.append("<xslt:template match=\"@*|node()\">"); - buffer.append("<xslt:copy>"); - buffer.append("<xslt:apply-templates select=\"@*|node()\"/>"); - buffer.append("</xslt:copy>"); - buffer.append("</xslt:template>"); - buffer.append("</xslt:transform>"); + buffer.append("<?xml version=\"1.0\"?>"); + buffer + .append("<xslt:transform version=\"1.0\" xmlns:xslt=\"http://www.w3.org/1999/XSL/Transform\">"); + buffer + .append("<!-- Simple template to merge two database schemas into one -->"); + buffer.append("<xslt:param name=\"fileTwo\" />"); + buffer.append("<xslt:template match=\"/\">"); - File xslt = createTemp(".xslt"); - try - { - // Write to temp file + buffer.append("<xslt:message>"); + buffer + .append("<xslt:text /> Merging input with '<xslt:value-of select=\"$fileTwo\"/>"); + buffer.append("<xslt:text>'</xslt:text>"); + buffer.append("</xslt:message>"); + buffer.append("<xslt:if test=\"string($fileTwo)=''\">"); + buffer.append("<xslt:message terminate=\"yes\">"); + buffer + .append("<xslt:text>No input file specified (parameter 'fileTwo')</xslt:text>"); + buffer.append("</xslt:message>"); + buffer.append("</xslt:if>"); + buffer.append("<database name=\"generic\">"); + buffer.append("<xslt:apply-templates />"); + buffer.append("</database>"); + buffer.append("</xslt:template>"); + buffer.append("<xslt:template match=\"database\">"); + buffer.append("<xslt:apply-templates />"); + buffer + .append("<xslt:apply-templates select=\"document($fileTwo)/database/table\"/>"); + buffer.append("</xslt:template>"); - BufferedWriter out = new BufferedWriter(new FileWriter(xslt)); - out.write(buffer.toString()); - out.close(); - return xslt; - } catch (Exception e) - { - e.printStackTrace(); - return null; - } - } - /** - * process of merging two or more schema files into one schema file. - * - * @param fileList The filelist contains a (potentially) ordered list of schemas - * @return The name of the created temporary schema file - */ - private String mergeFiles(String[] fileList) - { - try - { - File xsltFile = createXSLTFromFile(mergeFile); - if (xsltFile == null) - xsltFile = createXSLTFromMemory(); - Source xslt = new StreamSource(xsltFile); - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(xslt); + buffer.append("<xslt:template match=\"@*|node()\">"); + buffer.append("<xslt:copy>"); + buffer.append("<xslt:apply-templates select=\"@*|node()\"/>"); + buffer.append("</xslt:copy>"); + buffer.append("</xslt:template>"); + buffer.append("</xslt:transform>"); - String sourceName = fileList[0]; - File target = null; - for (int i = 1; i < fileList.length; i++) - { - File soureFile = new File(sourceName); - Source source = new StreamSource(soureFile); - // JAXP reads data using the Source interface - target = createTemp(".xml"); + File xslt = createTemp(".xslt"); + try + { + // Write to temp file - Result targetResult = new StreamResult(target); - File f = new File(fileList[i]); - String other = "file:///" + f.getCanonicalPath(); // required on Win-platforms - other = other.replace('\\', '/'); + BufferedWriter out = new BufferedWriter(new FileWriter(xslt)); + out.write(buffer.toString()); + out.close(); + return xslt; + } + catch (Exception e) + { + e.printStackTrace(); + return null; + } + } - transformer.setParameter("fileTwo", other); - transformer.transform(source, targetResult); - sourceName = target.getAbsolutePath(); - } - return sourceName; + /** + * process of merging two or more schema files into one schema file. + * + * @param fileList + * The filelist contains a (potentially) ordered list of schemas + * @return The name of the created temporary schema file + */ + private String mergeFiles(String[] fileList) + { + try + { + File xsltFile = createXSLTFromFile(mergeFile); + if (xsltFile == null) xsltFile = createXSLTFromMemory(); + Source xslt = new StreamSource(xsltFile); + Transformer transformer = TransformerFactory.newInstance() + .newTransformer(xslt); - } catch (Exception e) - { - e.printStackTrace(); - return null; - } + String sourceName = fileList[0]; + File target = null; + for (int i = 1; i < fileList.length; i++) + { + File soureFile = new File(sourceName); + Source source = new StreamSource(soureFile); + // JAXP reads data using the Source interface + target = createTemp(".xml"); - } + Result targetResult = new StreamResult(target); + File f = new File(fileList[i]); + String other = "file:///" + f.getCanonicalPath(); // required + // on + // Win-platforms + other = other.replace('\\', '/'); - /** - * read database schema to file - * - */ - private void processExport(JetspeedDDLUtil ddlUtil) - { - // TODO: implement - ddlUtil.writeDatabaseSchematoFile(this.outputFile); + transformer.setParameter("fileTwo", other); + transformer.transform(source, targetResult); + sourceName = target.getAbsolutePath(); + } + return sourceName; - } + } + catch (Exception e) + { + e.printStackTrace(); + return null; + } - /** - * read the property file and read what has not yet been defined - */ - private void processPropertyFile() - { - /** get system property definition */ - if (propertyFileName == null) - propertyFileName = System.getProperty( - "org.apache.jetspeed.xml.ddlUtil.configuration", null); + } - if (propertyFileName == null) - return; - try - { - configuration = new PropertiesConfiguration(propertyFileName); - } catch (Exception e) - { - e.printStackTrace(); - return; - } - if (configuration != null) - { - /** only read what was not defined on the command line */ + /** + * read database schema to file + * + */ + private void processExport(JetspeedDDLUtil ddlUtil) + { + // TODO: implement + ddlUtil.writeDatabaseSchematoFile(this.outputFile); - if (driverClass == null) - driverClass = configuration.getString("driverClass"); - if (url == null) - url = configuration.getString("url"); - if (user == null) - user = configuration.getString("user"); - if (password == null) - password = configuration.getString("password"); - if (mergeFile == null) - mergeFile = configuration.getString("mergeFile"); - if (!(doImport)) - { - schemaDirectory = configuration.getString("schema"); - if (schemaDirectory != null) - doImport = true; - } - if (!(doExport)) - { - outputFile = configuration.getString("outputFile"); - if (outputFile != null) - doExport = true; - } - if (logLevel == null) - logLevel = configuration.getString("loglevel"); + } - } + /** + * read the property file and read what has not yet been defined + */ + private void processPropertyFile() + { + /** get system property definition */ + if (propertyFileName == null) + propertyFileName = System.getProperty( + "org.apache.jetspeed.xml.ddlUtil.configuration", null); - } + if (propertyFileName == null) return; + try + { + configuration = new PropertiesConfiguration(propertyFileName); + } + catch (Exception e) + { + e.printStackTrace(); + return; + } + if (configuration != null) + { + /** only read what was not defined on the command line */ + if (driverClass == null) + driverClass = configuration.getString("driverClass"); + if (url == null) url = configuration.getString("url"); + if (user == null) user = configuration.getString("user"); + if (password == null) + password = configuration.getString("password"); + if (mergeFile == null) + mergeFile = configuration.getString("mergeFile"); + if (!(doImport)) + { + schemaDirectory = configuration.getString("schema"); + if (schemaDirectory != null) doImport = true; + } + if (!(doExport)) + { + outputFile = configuration.getString("outputFile"); + if (outputFile != null) doExport = true; + } + if (logLevel == null) + logLevel = configuration.getString("loglevel"); + + } + + } + /* - private static String[] getTokens(String _line) - { - if ((_line == null) || (_line.length() == 0)) - return null; + * private static String[] getTokens(String _line) { if ((_line == null) || + * (_line.length() == 0)) return null; + * + * StringTokenizer st = new StringTokenizer(_line, ","); ArrayList list = + * new ArrayList(); + * + * while (st.hasMoreTokens()) list.add(st.nextToken()); String[] s = new + * String[list.size()]; for (int i = 0; i < list.size(); i++) s[i] = + * (String) list.get(i); return s; } + */ - StringTokenizer st = new StringTokenizer(_line, ","); - ArrayList list = new ArrayList(); + public List getRows(JetspeedDDLUtil ddlUtil, String tableName) + { + Table table = ddlUtil.getModel().findTable(tableName, + ddlUtil.getPlatform().isDelimitedIdentifierModeOn()); - while (st.hasMoreTokens()) - list.add(st.nextToken()); - String[] s = new String[list.size()]; - for (int i = 0; i < list.size(); i++) - s[i] = (String) list.get(i); - return s; - } - */ + return ddlUtil.getPlatform().fetch(ddlUtil.getModel(), + getSelectQueryForAllString(ddlUtil, table), new Table[] + {table}); + } - public List getRows(JetspeedDDLUtil ddlUtil, String tableName) - { - Table table = ddlUtil.getModel().findTable(tableName, - ddlUtil.getPlatform().isDelimitedIdentifierModeOn()); + public String getSelectQueryForAllString(JetspeedDDLUtil ddlUtil, + Table table) + { - return ddlUtil.getPlatform().fetch(ddlUtil.getModel(), - getSelectQueryForAllString(ddlUtil, table), new Table[] - {table}); - } + StringBuffer query = new StringBuffer(); - public String getSelectQueryForAllString(JetspeedDDLUtil ddlUtil, - Table table) - { + query.append("SELECT * FROM "); + if (ddlUtil.getPlatform().isDelimitedIdentifierModeOn()) + { + query.append(ddlUtil.getPlatform().getPlatformInfo() + .getDelimiterToken()); + } + query.append(table.getName()); + if (ddlUtil.getPlatform().isDelimitedIdentifierModeOn()) + { + query.append(ddlUtil.getPlatform().getPlatformInfo() + .getDelimiterToken()); + } + System.out.println(query.toString()); + return query.toString(); + } - StringBuffer query = new StringBuffer(); + /** + * read an xml file describing the basic order of the files to be processed + * + * @param importFileName + * @return + * @throws SerializerException + */ - query.append("SELECT * FROM "); - if (ddlUtil.getPlatform().isDelimitedIdentifierModeOn()) - { - query.append(ddlUtil.getPlatform().getPlatformInfo() - .getDelimiterToken()); - } - query.append(table.getName()); - if (ddlUtil.getPlatform().isDelimitedIdentifierModeOn()) - { - query.append(ddlUtil.getPlatform().getPlatformInfo() - .getDelimiterToken()); - } - System.out.println(query.toString()); - return query.toString(); - } + private ArrayList readOrderFile(String importFileName) + { + XMLObjectReader reader = null; - /** - * read an xml file describing the basic order of the files to be processed - * - * @param importFileName - * @return - * @throws SerializerException - */ + XMLBinding binding = new XMLBinding(); + binding.setAlias(ArrayList.class, "ProcessOrder"); + binding.setAlias(JSGroup.class, "File"); - private ArrayList readOrderFile(String importFileName) - { - XMLObjectReader reader = null; + ArrayList snap = null; + try + { + reader = XMLObjectReader.newInstance(new FileInputStream( + importFileName)); + } + catch (Exception e) + { + e.printStackTrace(); + return null; + } + try + { + reader.setBinding(binding); + snap = (ArrayList) reader.read("ProcessOrder", ArrayList.class); - XMLBinding binding = new XMLBinding(); - binding.setAlias(ArrayList.class, "ProcessOrder"); - binding.setAlias(JSGroup.class, "File"); + } + catch (Exception e) + { + e.printStackTrace(); + } + finally + { + /** ensure the reader is closed */ + try + { + reader.close(); + } + catch (Exception e1) + { + /** + * don't do anything with this exception - never let the bubble + * out of the finally block + */ + } + } + return snap; + } - ArrayList snap = null; - try - { - reader = XMLObjectReader.newInstance(new FileInputStream( - importFileName)); - } catch (Exception e) - { - e.printStackTrace(); - return null; - } - try - { - reader.setBinding(binding); - snap = (ArrayList) reader.read("ProcessOrder", ArrayList.class); + class LocalFilenameFilter implements FilenameFilter + { - } catch (Exception e) - { - e.printStackTrace(); - } finally - { - /** ensure the reader is closed */ - try - { - reader.close(); - } catch (Exception e1) - { - /** - * don't do anything with this exception - never let the bubble - * out of the finally block - */ - } - } - return snap; - } + String exclude = null; - class LocalFilenameFilter implements FilenameFilter - { + String sortFile = null; - String exclude = null; - String sortFile = null; - String sort = null; + String sort = null; - String getSortFile() - { - return sortFile; - } - LocalFilenameFilter(String exclude, String sort) - { - this.exclude = exclude; - this.sort = sort; + String getSortFile() + { + return sortFile; + } - } - public boolean accept(File dir, String name) - { - if (exclude != null) - if (name.equalsIgnoreCase(exclude)) - return false; - if (sort != null) - if (name.equalsIgnoreCase(sort)) - { - sortFile = dir.getAbsolutePath() + "/" + sort; - return false; - } + LocalFilenameFilter(String exclude, String sort) + { + this.exclude = exclude; + this.sort = sort; - return name.endsWith(".xml"); - } + } - } + public boolean accept(File dir, String name) + { + if (exclude != null) + if (name.equalsIgnoreCase(exclude)) return false; + if (sort != null) if (name.equalsIgnoreCase(sort)) + { + sortFile = dir.getAbsolutePath() + "/" + sort; + return false; + } + return name.endsWith(".xml"); + } + + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedDDLUtil.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedDDLUtil.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedDDLUtil.java 2008-05-16 01:54:54 UTC (rev 940) @@ -53,546 +53,568 @@ */ public class JetspeedDDLUtil { - public static final String DATASOURCE_DATABASENAME = "DATABASENAME".intern(); - public static final String DATASOURCE_CLASS = "DATASOURCE_CLASS".intern(); - public static final String DATASOURCE_DRIVER = "driverClassName".intern(); - public static final String DATASOURCE_URL = "url".intern(); - public static final String DATASOURCE_USERNAME = "username".intern(); - public static final String DATASOURCE_PASSWORD = "password".intern(); - + public static final String DATASOURCE_DATABASENAME = "DATABASENAME" + .intern(); + + public static final String DATASOURCE_CLASS = "DATASOURCE_CLASS".intern(); + + public static final String DATASOURCE_DRIVER = "driverClassName".intern(); + + public static final String DATASOURCE_URL = "url".intern(); + + public static final String DATASOURCE_USERNAME = "username".intern(); + + public static final String DATASOURCE_PASSWORD = "password".intern(); + /** Logger */ private static final Log log = LogFactory.getLog(JetspeedDDLUtil.class); - JdbcTypeCategoryEnum temEnum = null; - - Map parameters; + JdbcTypeCategoryEnum temEnum = null; - PlatformUtils utils; + Map parameters; - StringWriter writer; + PlatformUtils utils; - private Platform platform; + StringWriter writer; - /** The data source to test against. */ - private DataSource dataSource; - /** The database name. */ - private String _databaseName; - /** The database model. */ - private Database model; + private Platform platform; - private boolean connected = false; + /** The data source to test against. */ + private DataSource dataSource; - public JetspeedDDLUtil() - { + /** The database name. */ + private String _databaseName; - } + /** The database model. */ + private Database model; - public void startUp() - { + private boolean connected = false; - } + public JetspeedDDLUtil() + { - public void tearDown() - { - if (connected) - { - platform = null; - // todo: closeup - } - } + } - /** - * Tries to determine whether a the jdbc driver and connection url re - * supported. - * - * @param driverName - * The fully qualified name of the JDBC driver - * @param jdbcConnectionUrl - * The connection url - * @return True if this driver/url is supported - */ - public boolean isDatabaseSupported(String driverName, - String jdbcConnectionUrl) - { - if (utils.determineDatabaseType(driverName, jdbcConnectionUrl) != null) - return true; - else - return false; + public void startUp() + { - } + } - + public void tearDown() + { + if (connected) + { + platform = null; + // todo: closeup + } + } - /** - * Parses the database defined in the given XML file and creates a database - * schema (model) object - * - * @param fileName - */ - public void writeDatabaseSchematoFile(String fileName) - { - new DatabaseIO().write(model, fileName); - } + /** + * Tries to determine whether a the jdbc driver and connection url re + * supported. + * + * @param driverName + * The fully qualified name of the JDBC driver + * @param jdbcConnectionUrl + * The connection url + * @return True if this driver/url is supported + */ + public boolean isDatabaseSupported(String driverName, + String jdbcConnectionUrl) + { + if (utils.determineDatabaseType(driverName, jdbcConnectionUrl) != null) + return true; + else + return false; - - /** - * Parses the database defined in the given XML file and creates a database - * schema (model) object - * - * @param dbDef - * The database XML definition - * @return The database model - */ - protected Database createDatabaseSchemaFromXML(String fileName) - { - DatabaseIO io = new DatabaseIO(); - io.setValidateXml(false); - return io.read(fileName); - } + } - /** - * Parses the database defined in the given XML definition String and - * creates a database schema (model) object - * - * @param dbDef - * The database XML definition - * @return The database model - */ - protected Database createDatabaseSchemaFromString(String dbDef) - { - DatabaseIO dbIO = new DatabaseIO(); + /** + * Parses the database defined in the given XML file and creates a database + * schema (model) object + * + * @param fileName + */ + public void writeDatabaseSchematoFile(String fileName) + { + new DatabaseIO().write(model, fileName); + } - dbIO.setUseInternalDtd(true); - dbIO.setValidateXml(false); - return dbIO.read(new StringReader(dbDef)); - } + /** + * Parses the database defined in the given XML file and creates a database + * schema (model) object + * + * @param dbDef + * The database XML definition + * @return The database model + */ + protected Database createDatabaseSchemaFromXML(String fileName) + { + DatabaseIO io = new DatabaseIO(); + io.setValidateXml(false); + return io.read(fileName); + } - /** - * <p> - * Create a database connection (platform instance) from a data source - * </p> - * - * @param dataSource - */ - protected Platform connectToDatabase(DataSource dataSource) - { - return PlatformFactory.createNewPlatformInstance(dataSource); - } + /** + * Parses the database defined in the given XML definition String and + * creates a database schema (model) object + * + * @param dbDef + * The database XML definition + * @return The database model + */ + protected Database createDatabaseSchemaFromString(String dbDef) + { + DatabaseIO dbIO = new DatabaseIO(); - /** - * <p> - * Create a database connection (platform instance) from a (case - * insensitive) database type (like MySQL) - * </p> - * - * @param dataSource - */ - protected Platform connectToDatabase(String databaseType) - { - return PlatformFactory.createNewPlatformInstance(databaseType); - } - /** - * <p> - * Update a given database schema to match the schema of targetModel If - * alterDB is true, the routine attempts to modify the existing database - * shcema while preserving the data (as much as possible). If not, the - * existing tables are dropped prior to recreate - * - * @param targetModel - * The new database model - * @param alterDb - * if true, try to use alter database and preserve data - */ - protected void updateDatabaseSchema(Database targetModel, boolean alterDb) - throws SerializerException - { - try - { - platform.setSqlCommentsOn(false); - try - { - targetModel.resetDynaClassCache(); - } catch (Exception internalEx) - { - internalEx.printStackTrace(); - } - if (alterDb) - { - model.mergeWith(targetModel); - try - { - platform.alterTables(model, true); - } - catch (Exception aEX) - { - System.out.println("Error in ALTER DATABASE"); - aEX.printStackTrace(); - log.error(aEX); - } - } else - { - try - { - -// if (log.isDebugEnabled()) -// { -// String s = platform.getDropTablesSql(model, true); -// log.debug(s); -// } + dbIO.setUseInternalDtd(true); + dbIO.setValidateXml(false); + return dbIO.read(new StringReader(dbDef)); + } + + /** + * <p> + * Create a database connection (platform instance) from a data source + * </p> + * + * @param dataSource + */ + protected Platform connectToDatabase(DataSource dataSource) + { + return PlatformFactory.createNewPlatformInstance(dataSource); + } + + /** + * <p> + * Create a database connection (platform instance) from a (case + * insensitive) database type (like MySQL) + * </p> + * + * @param dataSource + */ + protected Platform connectToDatabase(String databaseType) + { + return PlatformFactory.createNewPlatformInstance(databaseType); + } + + /** + * <p> + * Update a given database schema to match the schema of targetModel If + * alterDB is true, the routine attempts to modify the existing database + * shcema while preserving the data (as much as possible). If not, the + * existing tables are dropped prior to recreate + * + * @param targetModel + * The new database model + * @param alterDb + * if true, try to use alter database and preserve data + */ + protected void updateDatabaseSchema(Database targetModel, boolean alterDb) + throws SerializerException + { + try + { + platform.setSqlCommentsOn(false); + try + { + targetModel.resetDynaClassCache(); + } + catch (Exception internalEx) + { + internalEx.printStackTrace(); + } + if (alterDb) + { + model.mergeWith(targetModel); + try + { + platform.alterTables(model, true); + } + catch (Exception aEX) + { + System.out.println("Error in ALTER DATABASE"); + aEX.printStackTrace(); + log.error(aEX); + } + } + else + { + try + { + + // if (log.isDebugEnabled()) + // { + // String s = platform.getDropTablesSql(model, true); + // log.debug(s); + // } if (model == null) { model = targetModel; } - platform.dropTables(model, true); - } - catch (Exception aEX) - { - log.error(aEX); - } - try - { - platform.createTables(model, false, true); + platform.dropTables(model, true); + } + catch (Exception aEX) + { + log.error(aEX); + } + try + { + platform.createTables(model, false, true); if (this._databaseName.startsWith("oracle")) { model = this.readModelFromDatabase(null); - modifyVarBinaryColumn(model, "PA_METADATA_FIELDS", "COLUMN_VALUE"); - modifyVarBinaryColumn(model, "PD_METADATA_FIELDS", "COLUMN_VALUE"); + modifyVarBinaryColumn(model, "PA_METADATA_FIELDS", + "COLUMN_VALUE"); + modifyVarBinaryColumn(model, "PD_METADATA_FIELDS", + "COLUMN_VALUE"); modifyVarBinaryColumn(model, "LANGUAGE", "KEYWORDS"); - modifyVarBinaryColumn(model, "PORTLET_CONTENT_TYPE", "MODES"); - modifyVarBinaryColumn(model, "PARAMETER", "PARAMETER_VALUE"); - modifyVarBinaryColumn(model, "LOCALIZED_DESCRIPTION", "DESCRIPTION"); - modifyVarBinaryColumn(model, "LOCALIZED_DISPLAY_NAME", "DISPLAY_NAME"); - modifyVarBinaryColumn(model, "CUSTOM_PORTLET_MODE", "DESCRIPTION"); - modifyVarBinaryColumn(model, "CUSTOM_WINDOW_STATE", "DESCRIPTION"); - modifyVarBinaryColumn(model, "MEDIA_TYPE", "DESCRIPTION"); - platform.alterTables(model, true); + modifyVarBinaryColumn(model, "PORTLET_CONTENT_TYPE", + "MODES"); + modifyVarBinaryColumn(model, "PARAMETER", + "PARAMETER_VALUE"); + modifyVarBinaryColumn(model, "LOCALIZED_DESCRIPTION", + "DESCRIPTION"); + modifyVarBinaryColumn(model, "LOCALIZED_DISPLAY_NAME", + "DISPLAY_NAME"); + modifyVarBinaryColumn(model, "CUSTOM_PORTLET_MODE", + "DESCRIPTION"); + modifyVarBinaryColumn(model, "CUSTOM_WINDOW_STATE", + "DESCRIPTION"); + modifyVarBinaryColumn(model, "MEDIA_TYPE", + "DESCRIPTION"); + platform.alterTables(model, true); } - } - catch (Exception aEX) - { + } + catch (Exception aEX) + { aEX.printStackTrace(); - log.error(aEX); - } - } - // TODO: DST: REMOVE, AINT WORKING IN ORACLE model = this.readModelFromDatabase(null); - } catch (Exception ex) - { - ex.printStackTrace(); - throw new SerializerException( - // TODO: HJB create exception - SerializerException.CREATE_OBJECT_FAILED.create(ex.getLocalizedMessage())); - } - } + log.error(aEX); + } + } + // TODO: DST: REMOVE, AINT WORKING IN ORACLE model = + // this.readModelFromDatabase(null); + } + catch (Exception ex) + { + ex.printStackTrace(); + throw new SerializerException( + // TODO: HJB create exception + SerializerException.CREATE_OBJECT_FAILED.create(ex + .getLocalizedMessage())); + } + } - private void modifyVarBinaryColumn(Database targetModel, String tableName, String columnName) + private void modifyVarBinaryColumn(Database targetModel, String tableName, + String columnName) { Table table = targetModel.findTable(tableName); Column c = table.findColumn(columnName); - c.setType("VARCHAR"); + c.setType("VARCHAR"); c.setSize("2000"); - System.out.println("updating column " + c.getName() + " for table " + table.getName()); + System.out.println("updating column " + c.getName() + " for table " + + table.getName()); } - /** - * Alter an existing database from the given model. Data is preserved as - * much as possible - * - * @param model - * The new database model - */ - public void alterDatabase(Database model) throws SerializerException - { - updateDatabaseSchema(model, true); - } - /** - * Creates a new database from the given model. Note that all data is LOST - * - * @param model - * The new database model - */ - public void createDatabase(Database model) throws SerializerException - { - updateDatabaseSchema(model, false); - } + /** + * Alter an existing database from the given model. Data is preserved as + * much as possible + * + * @param model + * The new database model + */ + public void alterDatabase(Database model) throws SerializerException + { + updateDatabaseSchema(model, true); + } - /** - * <p> - * Inserts data into the database. Data is expected to be in the format - * </p> - * <p> - * <?xml version='1.0' encoding='ISO-8859-1'?> <data> <TABLENAME - * FIELD1='TEXTVALUE' FIELD2=INTVALUE .... /> <TABLENAME FIELD1='TEXTVALUE' - * FIELD2=INTVALUE .... /> </data> - * </p> - * - * @param model - * The database model - * @param dataXml - * The data xml - * @return The database - */ - protected Database insertData(Database model, String dataXml) - throws DatabaseOperationException - { - try - { - DataReader dataReader = new DataReader(); + /** + * Creates a new database from the given model. Note that all data is LOST + * + * @param model + * The new database model + */ + public void createDatabase(Database model) throws SerializerException + { + updateDatabaseSchema(model, false); + } - dataReader.setModel(model); - dataReader.setSink(new DataToDatabaseSink(platform, model)); - dataReader.parse(new StringReader(dataXml)); - return model; - } catch (Exception ex) - { - throw new DatabaseOperationException(ex); - } - } + /** + * <p> + * Inserts data into the database. Data is expected to be in the format + * </p> + * <p> + * <?xml version='1.0' encoding='ISO-8859-1'?> <data> <TABLENAME + * FIELD1='TEXTVALUE' FIELD2=INTVALUE .... /> <TABLENAME FIELD1='TEXTVALUE' + * FIELD2=INTVALUE .... /> </data> + * </p> + * + * @param model + * The database model + * @param dataXml + * The data xml + * @return The database + */ + protected Database insertData(Database model, String dataXml) + throws DatabaseOperationException + { + try + { + DataReader dataReader = new DataReader(); - /** - * Drops the tables defined in the database model on this connection. - * - * @param model - * The database model - * - */ - protected void dropDatabaseTables(Database model) - throws DatabaseOperationException - { - platform.dropTables(model, true); - } + dataReader.setModel(model); + dataReader.setSink(new DataToDatabaseSink(platform, model)); + dataReader.parse(new StringReader(dataXml)); + return model; + } + catch (Exception ex) + { + throw new DatabaseOperationException(ex); + } + } - /** - * Reads the database model from a live database. - * - * @param platform - * The physical database connection - * @param databaseName - * The name of the resulting database - * @return The model - */ - public Database readModelFromDatabase(String databaseName) - { - return platform.readModelFromDatabase(databaseName); - } + /** + * Drops the tables defined in the database model on this connection. + * + * @param model + * The database model + * + */ + protected void dropDatabaseTables(Database model) + throws DatabaseOperationException + { + platform.dropTables(model, true); + } - /** - * datasource.class=org.apache.commons.dbcp.BasicDataSource - * datasource.driverClassName=com.mysql.jdbc.Driver - * datasource.url=jdbc:mysql://localhost/ddlutils datasource.username=root - * datasource.password=root123 - * - */ + /** + * Reads the database model from a live database. + * + * @param platform + * The physical database connection + * @param databaseName + * The name of the resulting database + * @return The model + */ + public Database readModelFromDatabase(String databaseName) + { + return platform.readModelFromDatabase(databaseName); + } - /** - * Initializes the datasource and the connection (platform) - */ - public void init(Map parameters) - { - if (connected) - tearDown(); + /** + * datasource.class=org.apache.commons.dbcp.BasicDataSource + * datasource.driverClassName=com.mysql.jdbc.Driver + * datasource.url=jdbc:mysql://localhost/ddlutils datasource.username=root + * datasource.password=root123 + * + */ - try - { - String dataSourceClass = (String) parameters.get(DATASOURCE_CLASS); - if (dataSourceClass == null) - dataSourceClass = BasicDataSource.class.getName(); + /** + * Initializes the datasource and the connection (platform) + */ + public void init(Map parameters) + { + if (connected) tearDown(); - dataSource = (DataSource) Class.forName(dataSourceClass) - .newInstance(); + try + { + String dataSourceClass = (String) parameters.get(DATASOURCE_CLASS); + if (dataSourceClass == null) + dataSourceClass = BasicDataSource.class.getName(); - for (Iterator it = parameters.entrySet().iterator(); it.hasNext();) - { - Map.Entry entry = (Map.Entry) it.next(); - String propName = (String) entry.getKey(); + dataSource = (DataSource) Class.forName(dataSourceClass) + .newInstance(); - if (!(propName.equals(DATASOURCE_CLASS))) - { - BeanUtils.setProperty(dataSource, propName, entry - .getValue()); - } - } - } catch (Exception ex) - { - throw new DatabaseOperationException(ex); - } - String databaseName = null; - _databaseName = null; - try - { - databaseName = (String) parameters.get(DATASOURCE_DATABASENAME); - if (databaseName != null) - { - platform = PlatformFactory.createNewPlatformInstance(databaseName); - if (platform != null) - _databaseName = databaseName; - } - } catch (Exception ex) - { - log.warn("Exception in trying to establish connection to " + databaseName + " : " + ex.getLocalizedMessage()); - log.warn(ex); - } - if (_databaseName == null) - { - _databaseName = new PlatformUtils().determineDatabaseType(dataSource); - if (_databaseName == null) - { - throw new DatabaseOperationException( - "Could not determine platform from datasource, please specify it in the jdbc.properties via the ddlutils.platform property"); - } - else - { - try - { - platform = PlatformFactory.createNewPlatformInstance(_databaseName); - } catch (Exception ex) - { - throw new DatabaseOperationException( - "Could not establish connection to " + _databaseName + " : " + ex.getLocalizedMessage(),ex); - } - } - } -// com.mysql.jdbc.Driver - - writer = new StringWriter(); - platform.getSqlBuilder().setWriter(writer); -// if (platform.getPlatformInfo().isDelimitedIdentifiersSupported()) -// { -// platform.setDelimitedIdentifierModeOn(true); -// } + for (Iterator it = parameters.entrySet().iterator(); it.hasNext();) + { + Map.Entry entry = (Map.Entry) it.next(); + String propName = (String) entry.getKey(); - - platform.setDataSource(dataSource); + if (!(propName.equals(DATASOURCE_CLASS))) + { + BeanUtils.setProperty(dataSource, propName, entry + .getValue()); + } + } + } + catch (Exception ex) + { + throw new DatabaseOperationException(ex); + } + String databaseName = null; + _databaseName = null; + try + { + databaseName = (String) parameters.get(DATASOURCE_DATABASENAME); + if (databaseName != null) + { + platform = PlatformFactory + .createNewPlatformInstance(databaseName); + if (platform != null) _databaseName = databaseName; + } + } + catch (Exception ex) + { + log.warn("Exception in trying to establish connection to " + + databaseName + " : " + ex.getLocalizedMessage()); + log.warn(ex); + } + if (_databaseName == null) + { + _databaseName = new PlatformUtils() + .determineDatabaseType(dataSource); + if (_databaseName == null) + { + throw new DatabaseOperationException( + "Could not determine platform from datasource, please specify it in the jdbc.properties via the ddlutils.platform property"); + } + else + { + try + { + platform = PlatformFactory + .createNewPlatformInstance(_databaseName); + } + catch (Exception ex) + { + throw new DatabaseOperationException( + "Could not establish connection to " + + _databaseName + " : " + + ex.getLocalizedMessage(), ex); + } + } + } + // com.mysql.jdbc.Driver + + writer = new StringWriter(); + platform.getSqlBuilder().setWriter(writer); + // if (platform.getPlatformInfo().isDelimitedIdentifiersSupported()) + // { + // platform.setDelimitedIdentifierModeOn(true); + // } + + platform.setDataSource(dataSource); System.out.println("reading model..."); - model = this.readModelFromDatabase(null); + model = this.readModelFromDatabase(null); System.out.println("done reading model..."); -/** - JdbcModelReader reader = platform.getModelReader(); - try - { - model = reader.getDatabase(platform.borrowConnection(), null); - } catch (Exception ex) - { - throw new DatabaseOperationException(ex); - } -*/ - - connected = true; - } + /** + * JdbcModelReader reader = platform.getModelReader(); try { model = + * reader.getDatabase(platform.borrowConnection(), null); } catch + * (Exception ex) { throw new DatabaseOperationException(ex); } + */ - /** - * Returns the database model. - * - * @return The model - */ - protected Database getModel() - { - return model; - } + connected = true; + } - /** - * Inserts data into the database. - * - * @param dataXml - * The data xml - * @return The database - */ - protected Database insertData(String dataXml) - throws DatabaseOperationException - { - try - { - DataReader dataReader = new DataReader(); + /** + * Returns the database model. + * + * @return The model + */ + protected Database getModel() + { + return model; + } - dataReader.setModel(model); - dataReader.setSink(new DataToDatabaseSink(platform, model)); - dataReader.parse(new StringReader(dataXml)); - return model; - } catch (Exception ex) - { - throw new DatabaseOperationException(ex); - } - } + /** + * Inserts data into the database. + * + * @param dataXml + * The data xml + * @return The database + */ + protected Database insertData(String dataXml) + throws DatabaseOperationException + { + try + { + DataReader dataReader = new DataReader(); - /** - * Drops the tables defined in the database model. - */ - protected void dropDatabase() throws DatabaseOperationException - { - platform.dropTables(model, true); - } + dataReader.setModel(model); + dataReader.setSink(new DataToDatabaseSink(platform, model)); + dataReader.parse(new StringReader(dataXml)); + return model; + } + catch (Exception ex) + { + throw new DatabaseOperationException(ex); + } + } - /** - * Determines the value of the bean's property that has the given name. - * Depending on the case-setting of the current builder, the case of teh - * name is considered or not. - * - * @param bean - * The bean - * @param propName - * The name of the property - * @return The value - */ - protected Object getPropertyValue(DynaBean bean, String propName) - { - if (platform.isDelimitedIdentifierModeOn()) - { - return bean.get(propName); - } else - { - DynaProperty[] props = bean.getDynaClass().getDynaProperties(); + /** + * Drops the tables defined in the database model. + */ + protected void dropDatabase() throws DatabaseOperationException + { + platform.dropTables(model, true); + } - for (int idx = 0; idx < props.length; idx++) - { - if (propName.equalsIgnoreCase(props[idx].getName())) - { - return bean.get(props[idx].getName()); - } - } - throw new IllegalArgumentException( - "The bean has no property with the name " + propName); - } - } + /** + * Determines the value of the bean's property that has the given name. + * Depending on the case-setting of the current builder, the case of teh + * name is considered or not. + * + * @param bean + * The bean + * @param propName + * The name of the property + * @return The value + */ + protected Object getPropertyValue(DynaBean bean, String propName) + { + if (platform.isDelimitedIdentifierModeOn()) + { + return bean.get(propName); + } + else + { + DynaProperty[] props = bean.getDynaClass().getDynaProperties(); - public DataSource getDataSource() - { - return dataSource; - } + for (int idx = 0; idx < props.length; idx++) + { + if (propName.equalsIgnoreCase(props[idx].getName())) { return bean + .get(props[idx].getName()); } + } + throw new IllegalArgumentException( + "The bean has no property with the name " + propName); + } + } - public Platform getPlatform() - { - return platform; - } - - - - public List getRows(String tableName) + public DataSource getDataSource() { - Table table = getModel().findTable(tableName, getPlatform().isDelimitedIdentifierModeOn()); - - return getPlatform().fetch(getModel(), getSelectQueryForAllString( table), new Table[] { table }); + return dataSource; } - - public String getSelectQueryForAllString( Table table) + public Platform getPlatform() { - - StringBuffer query = new StringBuffer(); - - query.append("SELECT * FROM "); - if (getPlatform().isDelimitedIdentifierModeOn()) - { - query.append(getPlatform().getPlatformInfo().getDelimiterToken()); - } - query.append(table.getName()); - if (getPlatform().isDelimitedIdentifierModeOn()) - { - query.append(getPlatform().getPlatformInfo().getDelimiterToken()); - } - return query.toString(); + return platform; } - - - - + + public List getRows(String tableName) + { + Table table = getModel().findTable(tableName, + getPlatform().isDelimitedIdentifierModeOn()); + + return getPlatform().fetch(getModel(), + getSelectQueryForAllString(table), new Table[] + {table}); + } + + public String getSelectQueryForAllString(Table table) + { + + StringBuffer query = new StringBuffer(); + + query.append("SELECT * FROM "); + if (getPlatform().isDelimitedIdentifierModeOn()) + { + query.append(getPlatform().getPlatformInfo().getDelimiterToken()); + } + query.append(table.getName()); + if (getPlatform().isDelimitedIdentifierModeOn()) + { + query.append(getPlatform().getPlatformInfo().getDelimiterToken()); + } + return query.toString(); + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerApplication.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerApplication.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerApplication.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,32 +27,51 @@ import org.apache.jetspeed.components.jndi.SpringJNDIStarter; import org.apache.log4j.Level; import org.apache.log4j.Logger; + /** * Jetspeed Serializer Application * - * invoke with mandatory - * <p>-E filename or -I filename to denote the export or the import file</p> - * <p>-I filename | directory, if a directory will process all XML files of pattern "*seed.xml"</p> + * invoke with mandatory + * <p> + * -E filename or -I filename to denote the export or the import file + * </p> + * <p> + * -I filename | directory, if a directory will process all XML files of pattern + * "*seed.xml" + * </p> * * invoke with (optional) parameters as - * <p>-p propertyFilename : overwrite the default filename defined in System.getProperty JetSpeed.Serializer.Configuration</p> - * <p>-a ApplicationPath : overwrite the default ./ or ApplicationPath property in properties file)</p> - * <p>-b bootPath : directory to Spring boot files, overwrite the default assembly/boot/ or bootPath property in properties file)</p> - * <p>-c configPath : directory to Spring config files, overwrite the default assembly/ or configPath property in properties file)</p> + * <p> + * -p propertyFilename : overwrite the default filename defined in + * System.getProperty JetSpeed.Serializer.Configuration + * </p> + * <p> + * -a ApplicationPath : overwrite the default ./ or ApplicationPath property in + * properties file) + * </p> + * <p> + * -b bootPath : directory to Spring boot files, overwrite the default + * assembly/boot/ or bootPath property in properties file) + * </p> + * <p> + * -c configPath : directory to Spring config files, overwrite the default + * assembly/ or configPath property in properties file) + * </p> * - * <p>-O optionstring : overwrite default "ALL,REPLACE"</p> - * <p>optionstring: - * ALL - extract/import all (with exception of PREFERENCES) - * USER - extract/import users, groups, roles - * CAPABILITIES - extract/import capabilities - * PROFILE = extract/import profile settings (for export requires USER) - * PERMISSIONS = extract/import permissions - * PREFS = extract/import portlet preferences (ignored if any of the above is set) - * - * NOOVERWRITE = don't overwrite existing file (for export) - * BACKUP = backup before process + * <p> + * -O optionstring : overwrite default "ALL,REPLACE" * </p> * <p> + * optionstring: ALL - extract/import all (with exception of PREFERENCES) USER - + * extract/import users, groups, roles CAPABILITIES - extract/import + * capabilities PROFILE = extract/import profile settings (for export requires + * USER) PERMISSIONS = extract/import permissions PREFS = extract/import portlet + * preferences (ignored if any of the above is set) + * + * NOOVERWRITE = don't overwrite existing file (for export) BACKUP = backup + * before process + * </p> + * <p> * -dc driverClass, for example com.mysql.jdbc.Driver * </p> * <p> @@ -67,7 +86,7 @@ * </p> * * <p> - * -l log4j-level, ERROR (default), WARN, INFO + * -l log4j-level, ERROR (default), WARN, INFO * </p> * * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> @@ -75,51 +94,52 @@ */ public class JetspeedSerializerApplication implements JetspeedSerializerFactory { - public static final String JNDI_DS_NAME = "jetspeed"; - + + public static final String JNDI_DS_NAME = "jetspeed"; + public JetspeedSerializerApplication() - { + { } - + public JetspeedSerializer create(String serializerType) { if (serializerType.equals(JetspeedSerializerFactory.SECONDARY)) return new JetspeedSerializerSecondaryImpl(); else - return new JetspeedSerializerImpl(); + return new JetspeedSerializerImpl(); } - + public static void main(String[] args) { String propertyFileName = null; - - String fileName = null; // XML filename - mandatory on command line + + String fileName = null; // XML filename - mandatory on command line String applicationPath = null; // configuration.getProperties("applicationPath"); String bootConfigFiles = null; // configuration.getProperties("bootConfigFiles"); String configFiles = null; // configuration.getProperties("configFiles"); String name = null; - + String options = null; - + PropertiesConfiguration configuration = null; - + String defaultIndent = null; - String driverClass = null; // jdbc driver - String url = null; // jdbc url to database - String user = null; // user - String password = null; // password + String driverClass = null; // jdbc driver + String url = null; // jdbc url to database + String user = null; // user + String password = null; // password String logLevel = null; - + boolean doImport = false; boolean doExport = false; - + if (args == null) - throw new IllegalArgumentException("Either import or export have to be defined (-I or -E follwoed by the filename"); + throw new IllegalArgumentException( + "Either import or export have to be defined (-I or -E follwoed by the filename"); - // Parse all the command-line arguments for (int n = 0; n < args.length; n++) { @@ -135,12 +155,12 @@ { doExport = true; fileName = args[++n]; - } + } else if (args[n].equals("-I")) { doImport = true; fileName = args[++n]; - } + } else if (args[n].equals("-N")) { name = args[++n]; @@ -158,46 +178,52 @@ if (((n + 1) >= args.length) || args[n + 1].startsWith("-d")) { user = ""; - } else + } + else { user = args[++n]; } - } + } else if (args[n].equals("-dp")) { if (((n + 1) >= args.length) || args[n + 1].startsWith("-d")) { password = ""; - } else + } + else { password = args[++n]; } - } + } else { throw new IllegalArgumentException("Unknown argument: " + args[n]); } } - - /** The only required argument is the filename for either export or import*/ + + /** + * The only required argument is the filename for either export or + * import + */ if ((!doImport) && (!doExport)) - throw new IllegalArgumentException("Either import or export have to be defined (-I or -E follwoed by the filename"); + throw new IllegalArgumentException( + "Either import or export have to be defined (-I or -E follwoed by the filename"); - /** But not both*/ + /** But not both */ if ((doImport) && (doExport)) - throw new IllegalArgumentException("Only one - either import or export - can be requested"); + throw new IllegalArgumentException( + "Only one - either import or export - can be requested"); if (name == null) name = fileName; - + /** get system property definition */ if (propertyFileName == null) propertyFileName = System.getProperty( - "org.apache.jetspeed.xml.importer.configuration", - null); - + "org.apache.jetspeed.xml.importer.configuration", null); + if (propertyFileName != null) - { + { try { configuration = new PropertiesConfiguration(propertyFileName); @@ -210,76 +236,81 @@ if (configuration != null) { /** only read what was not defined on the command line */ - - if (applicationPath == null) - applicationPath = configuration.getString("applicationPath"); - if (bootConfigFiles == null) - bootConfigFiles = configuration.getString("bootConfigFiles"); - if (configFiles == null) + + if (applicationPath == null) + applicationPath = configuration + .getString("applicationPath"); + if (bootConfigFiles == null) + bootConfigFiles = configuration + .getString("bootConfigFiles"); + if (configFiles == null) configFiles = configuration.getString("configFiles"); - if (options == null) + if (options == null) options = configuration.getString("options"); - if (defaultIndent == null) + if (defaultIndent == null) defaultIndent = configuration.getString("defaultIndent"); - if (driverClass == null) - driverClass = configuration.getString("driverClass"); - if (url == null) - url = configuration.getString("url"); - if (user == null) - user = configuration.getString("user"); - if (password == null) - password = configuration.getString("password"); - if (logLevel == null) - logLevel = configuration.getString("loglevel"); - - + if (driverClass == null) + driverClass = configuration.getString("driverClass"); + if (url == null) url = configuration.getString("url"); + if (user == null) user = configuration.getString("user"); + if (password == null) + password = configuration.getString("password"); + if (logLevel == null) + logLevel = configuration.getString("loglevel"); + } } // if we still miss some settings, use hardoced defaults - if (applicationPath == null) - applicationPath = "./"; - if (bootConfigFiles == null) - bootConfigFiles = "assembly/boot/"; - if (configFiles == null) - configFiles = "assembly/"; - if (logLevel == null) - logLevel = "ERROR"; - + if (applicationPath == null) applicationPath = "./"; + if (bootConfigFiles == null) bootConfigFiles = "assembly/boot/"; + if (configFiles == null) configFiles = "assembly/"; + if (logLevel == null) logLevel = "ERROR"; bootConfigFiles = bootConfigFiles + "*.xml"; configFiles = configFiles + "*.xml"; - + // ok - we are ready to rumble.... - + /** create the instruction map */ - + Map settings = null; int processHelper = 1; // default process SEED if (options != null) { settings = new HashMap(); settings.put(JetspeedSerializer.KEY_PROCESS_USERS, Boolean.FALSE); - settings.put(JetspeedSerializer.KEY_PROCESS_CAPABILITIES, Boolean.FALSE); - settings.put(JetspeedSerializer.KEY_PROCESS_PROFILER, Boolean.FALSE); - settings.put(JetspeedSerializer.KEY_PROCESS_USER_PREFERENCES, Boolean.FALSE); - settings.put(JetspeedSerializer.KEY_OVERWRITE_EXISTING, Boolean.TRUE); - settings.put(JetspeedSerializer.KEY_BACKUP_BEFORE_PROCESS, Boolean.FALSE); + settings.put(JetspeedSerializer.KEY_PROCESS_CAPABILITIES, + Boolean.FALSE); + settings + .put(JetspeedSerializer.KEY_PROCESS_PROFILER, Boolean.FALSE); + settings.put(JetspeedSerializer.KEY_PROCESS_USER_PREFERENCES, + Boolean.FALSE); + settings.put(JetspeedSerializer.KEY_OVERWRITE_EXISTING, + Boolean.TRUE); + settings.put(JetspeedSerializer.KEY_BACKUP_BEFORE_PROCESS, + Boolean.FALSE); String[] optionSet = getTokens(options); - + processHelper = 0; - + for (int i = 0; i < optionSet.length; i++) { String o = optionSet[i]; if (o.equalsIgnoreCase("all")) { - settings.put(JetspeedSerializer.KEY_PROCESS_USERS, Boolean.TRUE); - settings.put(JetspeedSerializer.KEY_PROCESS_CAPABILITIES, Boolean.TRUE); - settings.put(JetspeedSerializer.KEY_PROCESS_PROFILER, Boolean.TRUE); - settings.put(JetspeedSerializer.KEY_PROCESS_PERMISSIONS, Boolean.TRUE); - settings.put(JetspeedSerializer.KEY_PROCESS_USER_PREFERENCES, Boolean.FALSE); + settings.put(JetspeedSerializer.KEY_PROCESS_USERS, + Boolean.TRUE); + settings.put(JetspeedSerializer.KEY_PROCESS_CAPABILITIES, + Boolean.TRUE); + settings.put(JetspeedSerializer.KEY_PROCESS_PROFILER, + Boolean.TRUE); + settings.put(JetspeedSerializer.KEY_PROCESS_PERMISSIONS, + Boolean.TRUE); + settings.put( + JetspeedSerializer.KEY_PROCESS_USER_PREFERENCES, + Boolean.FALSE); processHelper = 1; } else if (o.equalsIgnoreCase("user")) @@ -287,93 +318,96 @@ settings.put(JetspeedSerializer.KEY_PROCESS_USERS, Boolean.TRUE); processHelper = 1; - } else if (o.equalsIgnoreCase("PREFS")) + } + else if (o.equalsIgnoreCase("PREFS")) { settings.put( JetspeedSerializer.KEY_PROCESS_USER_PREFERENCES, Boolean.TRUE); processHelper = 2; - } else if (o.equalsIgnoreCase("CAPABILITIES")) + } + else if (o.equalsIgnoreCase("CAPABILITIES")) { settings.put(JetspeedSerializer.KEY_PROCESS_CAPABILITIES, Boolean.TRUE); processHelper = 1; - } else if (o.equalsIgnoreCase("PROFILE")) + } + else if (o.equalsIgnoreCase("PROFILE")) { settings.put(JetspeedSerializer.KEY_PROCESS_PROFILER, Boolean.TRUE); processHelper = 1; - } else if (o.equalsIgnoreCase("PERMISSIONS")) + } + else if (o.equalsIgnoreCase("PERMISSIONS")) { settings.put(JetspeedSerializer.KEY_PROCESS_PERMISSIONS, Boolean.TRUE); - processHelper = 1; - } else if (o.equalsIgnoreCase("NOOVERWRITE")) + processHelper = 1; + } + else if (o.equalsIgnoreCase("NOOVERWRITE")) settings.put(JetspeedSerializer.KEY_OVERWRITE_EXISTING, Boolean.FALSE); else if (o.equalsIgnoreCase("BACKUP")) settings.put(JetspeedSerializer.KEY_BACKUP_BEFORE_PROCESS, Boolean.TRUE); - + } - + } JetspeedSerializer serializer = null; - if (driverClass == null) - driverClass = System.getProperty( - "org.apache.jetspeed.database.driverClass", - "com.mysql.jdbc.Driver"); - if (url == null) - url = System.getProperty("org.apache.jetspeed.database.url", - "jdbc:mysql://localhost/j2test"); - if (user == null) - user = System.getProperty("org.apache.jetspeed.database.user", - "user"); - if (password == null) - password = System.getProperty( - "org.apache.jetspeed.database.password", "password"); + if (driverClass == null) + driverClass = System.getProperty( + "org.apache.jetspeed.database.driverClass", + "com.mysql.jdbc.Driver"); + if (url == null) + url = System.getProperty("org.apache.jetspeed.database.url", + "jdbc:mysql://localhost/j2test"); + if (user == null) + user = System.getProperty("org.apache.jetspeed.database.user", + "user"); + if (password == null) + password = System.getProperty( + "org.apache.jetspeed.database.password", "password"); - if (driverClass == null) - throw new IllegalArgumentException( - "Can't proceed without a valid driver"); - if (url == null) - throw new IllegalArgumentException( - "Can't proceed without a valid url to the target database"); - if (user == null) - throw new IllegalArgumentException( - "Can't proceed without a valid database user"); + if (driverClass == null) + throw new IllegalArgumentException( + "Can't proceed without a valid driver"); + if (url == null) + throw new IllegalArgumentException( + "Can't proceed without a valid url to the target database"); + if (user == null) + throw new IllegalArgumentException( + "Can't proceed without a valid database user"); - - HashMap context = new HashMap(); - - context.put(SpringJNDIStarter.DATASOURCE_DRIVER, driverClass); - context.put(SpringJNDIStarter.DATASOURCE_URL, url); - context.put(SpringJNDIStarter.DATASOURCE_USERNAME, user); - context.put(SpringJNDIStarter.DATASOURCE_PASSWORD, password); - - Logger logger = Logger.getLogger("org.springframework"); - Level level = logger.getLevel(); - if (logLevel.equalsIgnoreCase("INFO")) - logger.setLevel(Level.INFO); - else - if (logLevel.equalsIgnoreCase("WARN")) - logger.setLevel(Level.WARN); - else - logger.setLevel(Level.ERROR); - -/** - * set the application root - */ + + context.put(SpringJNDIStarter.DATASOURCE_DRIVER, driverClass); + context.put(SpringJNDIStarter.DATASOURCE_URL, url); + context.put(SpringJNDIStarter.DATASOURCE_USERNAME, user); + context.put(SpringJNDIStarter.DATASOURCE_PASSWORD, password); + + Logger logger = Logger.getLogger("org.springframework"); + Level level = logger.getLevel(); + if (logLevel.equalsIgnoreCase("INFO")) + logger.setLevel(Level.INFO); + else if (logLevel.equalsIgnoreCase("WARN")) + logger.setLevel(Level.WARN); + else + logger.setLevel(Level.ERROR); + + /** + * set the application root + */ System.out.println("APP ROOT is " + applicationPath); - System.setProperty("applicationRoot",applicationPath); - System.setProperty("portal.name","jetspped"); - SpringJNDIStarter starter = new SpringJNDIStarter(context,applicationPath,getTokens(bootConfigFiles),getTokens(configFiles)); - + System.setProperty("applicationRoot", applicationPath); + System.setProperty("portal.name", "jetspped"); + SpringJNDIStarter starter = new SpringJNDIStarter(context, + applicationPath, getTokens(bootConfigFiles), + getTokens(configFiles)); + System.out.println("starter framework created " + starter); - - + try { starter.setUp(); @@ -386,147 +420,145 @@ System.out.println("starter framework established " + starter); String[] importList = null; - if (doImport) - importList = parseFiles(fileName); - + if (doImport) importList = parseFiles(fileName); + if ((doImport) && (importList != null) && (importList.length > 0)) { - for (int i = 0; i < importList.length; i++) - { - try - { - System.out.println("processing import " + importList[i]); - if (processHelper == 2) - { - serializer = new JetspeedSerializerSecondaryImpl(starter.getComponentManager()); - } - else - serializer = new JetspeedSerializerImpl(starter.getComponentManager()); - serializer.importData(importList[i], settings); - System.out.println("processing import " + importList[i] + " done"); - - } - catch (Exception e) - { - System.err.println("Failed to process XML import for " + importList[i] + ":" + e); - e.printStackTrace(); - } - finally - { - if (serializer != null) - serializer.closeUp(); - } - } + for (int i = 0; i < importList.length; i++) + { + try + { + System.out.println("processing import " + importList[i]); + if (processHelper == 2) + { + serializer = new JetspeedSerializerSecondaryImpl( + starter.getComponentManager()); + } + else + serializer = new JetspeedSerializerImpl(starter + .getComponentManager()); + serializer.importData(importList[i], settings); + System.out.println("processing import " + importList[i] + + " done"); + + } + catch (Exception e) + { + System.err.println("Failed to process XML import for " + + importList[i] + ":" + e); + e.printStackTrace(); + } + finally + { + if (serializer != null) serializer.closeUp(); + } + } } if (doExport) { - try - { - System.out.println("processing export to " + fileName); - if (processHelper == 2) - { - serializer = new JetspeedSerializerSecondaryImpl(starter.getComponentManager()); - } - else - serializer = new JetspeedSerializerImpl(starter.getComponentManager()); + try + { + System.out.println("processing export to " + fileName); + if (processHelper == 2) + { + serializer = new JetspeedSerializerSecondaryImpl(starter + .getComponentManager()); + } + else + serializer = new JetspeedSerializerImpl(starter + .getComponentManager()); - serializer.exportData(name, fileName, settings); - } - catch (Exception e) - { - System.err.println("Failed to process XML export of " + fileName + ": " + e); - e.printStackTrace(); - } - finally - { - if (serializer != null) - serializer.closeUp(); - } + serializer.exportData(name, fileName, settings); + } + catch (Exception e) + { + System.err.println("Failed to process XML export of " + + fileName + ": " + e); + e.printStackTrace(); + } + finally + { + if (serializer != null) serializer.closeUp(); + } } try { - starter.tearDown(); - logger.setLevel(level);; + starter.tearDown(); + logger.setLevel(level); + ; } catch (Exception e1) { - System.out.println("starter framework teardown caused exception " + e1.getLocalizedMessage()); + System.out.println("starter framework teardown caused exception " + + e1.getLocalizedMessage()); e1.printStackTrace(); - - } - System.out.println("DONE performing " + (doExport?"export":"import")+ " with " + fileName); + + } + System.out.println("DONE performing " + + (doExport ? "export" : "import") + " with " + fileName); } - - - - /** - * process provided filename or directory name - * - * @return one or more files to be processed - */ - static private String[] parseFiles(String schemaDirectory) - { - String[] fileList = null; - try - { - File dir = new File(schemaDirectory); - if (!(dir.exists())) + + /** + * process provided filename or directory name + * + * @return one or more files to be processed + */ + static private String[] parseFiles(String schemaDirectory) + { + String[] fileList = null; + try + { + File dir = new File(schemaDirectory); + if (!(dir.exists())) { return fileList; } + if (!(dir.isDirectory())) { - return fileList; + fileList = new String[1]; + fileList[0] = schemaDirectory; + return fileList; } - if (!(dir.isDirectory())) - { - fileList = new String[1]; - fileList[0] = schemaDirectory; - return fileList; - } - // Handling a directory - File[] files = dir.listFiles( - new FilenameFilter() { - public boolean accept(File dir, String name) - {String n = name.toLowerCase(); - return n.endsWith("seed.xml"); - } - }); - if (files == null) - return fileList; + // Handling a directory + File[] files = dir.listFiles(new FilenameFilter() + { - fileList = new String[files.length]; - for (int i = 0; i < files.length; i++) + public boolean accept(File dir, String name) + { + String n = name.toLowerCase(); + return n.endsWith("seed.xml"); + } + }); + if (files == null) return fileList; + + fileList = new String[files.length]; + for (int i = 0; i < files.length; i++) { - fileList[i] = files[i].getAbsolutePath(); + fileList[i] = files[i].getAbsolutePath(); } - return fileList; - } + return fileList; + } catch (Exception e) - { - e.printStackTrace(); - throw new IllegalArgumentException( - "Processing the schema-directory " + schemaDirectory - + " caused exception " - + e.getLocalizedMessage()); - } + { + e.printStackTrace(); + throw new IllegalArgumentException( + "Processing the schema-directory " + schemaDirectory + + " caused exception " + e.getLocalizedMessage()); + } - - } + } - - private static String[] getTokens(String _line) - { - if ((_line == null) || (_line.length() == 0)) - return null; - - StringTokenizer st = new StringTokenizer(_line, ","); - ArrayList list = new ArrayList(); + private static String[] getTokens(String _line) + { + if ((_line == null) || (_line.length() == 0)) return null; - while (st.hasMoreTokens()) - list.add(st.nextToken()); - String[] s = new String[list.size()]; - for (int i=0; i<list.size(); i++) - s[i] = (String)list.get(i); - return s; - } + StringTokenizer st = new StringTokenizer(_line, ","); + ArrayList list = new ArrayList(); - + while (st.hasMoreTokens()) + list.add(st.nextToken()); + String[] s = new String[list.size()]; + for (int i = 0; i < list.size(); i++) + s[i] = (String) list.get(i); + return s; + } + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerBase.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerBase.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerBase.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.serializer; import java.io.File; @@ -44,9 +44,11 @@ { /** Logger */ - protected static final Log log = LogFactory.getLog(JetspeedSerializer.class); + protected static final Log log = LogFactory + .getLog(JetspeedSerializer.class); private ComponentManager cm = null; + private Object sem = new Object(); int refCouter = 0; @@ -65,23 +67,22 @@ private String currentIndent = null; private static String ENCODING_STRING = "JETSPEED 2.1 - 2006"; + private static String JETSPEED = "JETSPEED"; - + protected final ComponentManager getCM() { if (cm == null) { cm = Jetspeed.getComponentManager(); } - return cm; + return cm; } - + public JetspeedSerializerBase() { } - - /** * hand over existing component manager * @@ -98,10 +99,11 @@ * component configuration files and the search path for the application * component configuration files. * <p> - * For example: new JetspeedSerializerSecondaryImpl("./", "assembly/boot/*.xml", - * "assembly/*.xml") will establish the current directory as the root, - * process all xml files in the assembly/boot directory before processing - * all xml files in the assembly directory itself. + * For example: new JetspeedSerializerSecondaryImpl("./", + * "assembly/boot/*.xml", "assembly/*.xml") will establish the current + * directory as the root, process all xml files in the assembly/boot + * directory before processing all xml files in the assembly directory + * itself. * * @param appRoot * working directory @@ -122,13 +124,11 @@ * * @see org.apache.jetspeed.serializer.JetspeedSerializer#nitializeComponentManager(String,String[],String[]) */ - public final void initializeComponentManager(String appRoot, String[] bootConfig, - String[] appConfig) throws SerializerException + public final void initializeComponentManager(String appRoot, + String[] bootConfig, String[] appConfig) throws SerializerException { - - - if (this.initialized) + if (this.initialized) throw new SerializerException( SerializerException.COMPONENT_MANAGER_EXISTS.create("")); SpringComponentManager cm = new SpringComponentManager(bootConfig, @@ -187,13 +187,13 @@ * @see org.apache.jetspeed.serializer.JetspeedSerializer#importData(String, * Map) */ - public final void importData(String importFileName, Map settings) + public final void importData(String importFileName, Map settings) throws SerializerException { if (cm == null) { cm = Jetspeed.getComponentManager(); - } + } /** pre-processing homework... */ XMLBinding binding = new XMLBinding(); setupAliases(binding); @@ -203,7 +203,7 @@ throw new SerializerException( SerializerException.FILE_PROCESSING_ERROR .create(new String[] - { importFileName, "Snapshot is NULL"})); + {importFileName, "Snapshot is NULL"})); if (!(getSnapshot().checkVersion())) throw new SerializerException( @@ -227,14 +227,13 @@ return; } - /* * (non-Javadoc) * * @see org.apache.jetspeed.serializer.JetspeedSerializer#exportData(String,String,Map) */ - public final void exportData(String name, String exportFileName, Map settings) - throws SerializerException + public final void exportData(String name, String exportFileName, + Map settings) throws SerializerException { /** pre-processing homework... */ XMLBinding binding = new XMLBinding(); @@ -258,23 +257,26 @@ try { logMe("*********Writing data*********"); - writer.write(getSnapshot(), getSerializerDataTag(), - getSerializerDataClass()); + writer.write(getSnapshot(), getSerializerDataTag(), + getSerializerDataClass()); - } catch (Exception e) + } + catch (Exception e) { throw new SerializerException( SerializerException.FILE_PROCESSING_ERROR .create(new String[] - { exportFileName, e.getMessage()})); - } finally + {exportFileName, e.getMessage()})); + } + finally { /** ensure the writer is closed */ try { logMe("*********closing up********"); writer.close(); - } catch (Exception e) + } + catch (Exception e) { logMe("Error in closing writer " + e.getMessage()); /** @@ -291,7 +293,8 @@ * create a backup of the current environment in case the import fails * */ - protected final void doBackupOfCurrent(String importFileName, Map currentSettings) + protected final void doBackupOfCurrent(String importFileName, + Map currentSettings) { // TODO: HJB create backup of current content } @@ -310,8 +313,8 @@ * @throws SerializerException */ - protected final JSSnapshot readFile(String importFileName, XMLBinding binding) - throws SerializerException + protected final JSSnapshot readFile(String importFileName, + XMLBinding binding) throws SerializerException { XMLObjectReader reader = null; JSSnapshot snap = null; @@ -319,32 +322,36 @@ { reader = XMLObjectReader.newInstance(new FileInputStream( importFileName)); - } catch (Exception e) + } + catch (Exception e) { throw new SerializerException(SerializerException.FILE_READER_ERROR .create(new String[] - { importFileName, e.getMessage()})); + {importFileName, e.getMessage()})); } try { if (binding != null) reader.setBinding(binding); snap = (JSSnapshot) reader.read(this.getSerializerDataTag(), - getSerializerDataClass()); + getSerializerDataClass()); - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); new SerializerException(SerializerException.FILE_PROCESSING_ERROR .create(new String[] - { importFileName, e.getMessage()})); - } finally + {importFileName, e.getMessage()})); + } + finally { /** ensure the reader is closed */ try { logMe("*********closing up reader ********"); reader.close(); - } catch (Exception e1) + } + catch (Exception e1) { logMe("Error in closing reader " + e1.getMessage()); /** @@ -355,11 +362,12 @@ } } return snap; - } + } + /** * create or open a given file for writing */ - protected final XMLObjectWriter openWriter(String filename) + protected final XMLObjectWriter openWriter(String filename) throws SerializerException { File f; @@ -367,12 +375,13 @@ try { f = new File(filename); - } catch (Exception e) + } + catch (Exception e) { throw new SerializerException( SerializerException.FILE_PROCESSING_ERROR .create(new String[] - { filename, e.getMessage()})); + {filename, e.getMessage()})); } boolean exists = f.exists(); @@ -398,11 +407,12 @@ XMLObjectWriter writer = XMLObjectWriter .newInstance(new FileOutputStream(filename)); return writer; - } catch (Exception e) + } + catch (Exception e) { throw new SerializerException(SerializerException.FILE_WRITER_ERROR .create(new String[] - { filename, e.getMessage()})); + {filename, e.getMessage()})); } } @@ -433,7 +443,6 @@ processSettings.put(key, (value ? Boolean.TRUE : Boolean.FALSE)); } - /** * set instruction flags to new settings * @@ -454,7 +463,8 @@ Object o = settings.get(key); if ((o != null) && (o instanceof Boolean)) setSetting(key, ((Boolean) o).booleanValue()); - } catch (Exception e) + } + catch (Exception e) { log.error("checkSettings", e); } @@ -478,18 +488,16 @@ */ protected void setSnapshotData() { - java.util.Date d1 = new java.util.Date(); + java.util.Date d1 = new java.util.Date(); Date d = new Date(d1.getTime()); getSnapshot().setDateCreated(d.toString()); getSnapshot().setSavedVersion(getSnapshot().getSoftwareVersion()); getSnapshot().setSavedSubversion(getSnapshot().getSoftwareSubVersion()); } - - - /** * simple lookup for object from a map + * * @param map * @param _fullPath * @return @@ -499,7 +507,6 @@ return map.get(_fullPath); } - /** * ++++++++++++++++++++++++++++++HELPERS * +++++++++++++++++++++++++++++++++++++++++++++ @@ -521,8 +528,7 @@ */ protected final void logMe(String text) { - if (log.isDebugEnabled()) - log.debug(text); + if (log.isDebugEnabled()) log.debug(text); } /** @@ -548,11 +554,14 @@ return null; } - /** - * convert a list of elements in a string, seperated by ',' into an arraylist of strings - * @param _line Strinbg containing one or more elements seperated by ',' - * @return list of elements of null - */ + /** + * convert a list of elements in a string, seperated by ',' into an + * arraylist of strings + * + * @param _line + * Strinbg containing one or more elements seperated by ',' + * @return list of elements of null + */ protected final ArrayList getTokens(String _line) { if ((_line == null) || (_line.length() == 0)) return null; @@ -565,22 +574,18 @@ return list; } - protected final String recreatePassword(char[] savedPassword) - { - if (savedPassword == null) - return null; - return new String(savedPassword); - } + { + if (savedPassword == null) return null; + return new String(savedPassword); + } - /** * reset instruction flags to default settings (all true) * */ protected abstract void resetSettings(); - /** * The workhorse for exporting data * @@ -590,7 +595,7 @@ * @throws SerializerException */ protected abstract void processExport(String name, XMLBinding binding) - throws SerializerException; + throws SerializerException; /** * The workhorse for importing data @@ -600,7 +605,7 @@ * @return * @throws SerializerException */ - protected abstract void processImport() throws SerializerException; + protected abstract void processImport() throws SerializerException; /** * Setup the binding for the different classes, mapping each extracted class @@ -610,32 +615,28 @@ */ protected abstract void setupAliases(XMLBinding binding); - - /** - * return the class for the serializer data , for example JSSeedData.class) - * - * @return - */ + /** + * return the class for the serializer data , for example JSSeedData.class) + * + * @return + */ protected abstract Class getSerializerDataClass(); - - /** - * return the XML tag for the serializer data , for example "JSSnapShot") - * - * @return - */ + /** + * return the XML tag for the serializer data , for example "JSSnapShot") + * + * @return + */ protected abstract String getSerializerDataTag(); - public JSSnapshot getSnapshot() - { - return snapshot; - } + public JSSnapshot getSnapshot() + { + return snapshot; + } + public void setSnapshot(JSSnapshot snapshot) + { + this.snapshot = snapshot; + } - - public void setSnapshot(JSSnapshot snapshot) - { - this.snapshot = snapshot; - } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -94,8 +94,8 @@ * standalone java application for seeding a new database or from a running * portal as an administrative backup/restore function. * <p> - * The XML file needs to indicate whether passwords used in credentials - * are plain text or whether they are encoded. The import algoritm can determine - + * The XML file needs to indicate whether passwords used in credentials are + * plain text or whether they are encoded. The import algoritm can determine - * prior to reading users - which encode/decode scheme was used and if <none> or * <implements PasswordEncodingService> then we store plain passwords (Note that * that alone requires the resulting XML to be encoded!!!!!) @@ -103,10 +103,10 @@ * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> * @version $Id: $ */ -public class JetspeedSerializerImpl extends JetspeedSerializerBase implements JetspeedSerializer +public class JetspeedSerializerImpl extends JetspeedSerializerBase implements + JetspeedSerializer { - private HashMap roleMap = new HashMap(); private HashMap groupMap = new HashMap(); @@ -114,11 +114,13 @@ private HashMap userMap = new HashMap(); private HashMap mimeMap = new HashMap(); + private HashMap mimeMapInt = new HashMap(); private HashMap mediaMap = new HashMap(); private HashMap capabilityMap = new HashMap(); + private HashMap capabilityMapInt = new HashMap(); private HashMap clientMap = new HashMap(); @@ -129,24 +131,23 @@ int refCouter = 0; - private static String ENCODING_STRING = "JETSPEED 2.1 - 2006"; + private static String JETSPEED = "JETSPEED"; - - + protected Class getSerializerDataClass() { - return JSSeedData.class; - } + return JSSeedData.class; + } protected String getSerializerDataTag() { - return TAG_SNAPSHOT; - } - + return TAG_SNAPSHOT; + } + public JetspeedSerializerImpl() { - super(); + super(); } /** @@ -156,7 +157,7 @@ */ public JetspeedSerializerImpl(ComponentManager cm) { - super(cm); + super(cm); } /** @@ -179,10 +180,10 @@ public JetspeedSerializerImpl(String appRoot, String[] bootConfig, String[] appConfig) throws SerializerException { - super(appRoot,bootConfig,appConfig); + super(appRoot, bootConfig, appConfig); } - /** + /** * reset instruction flags to default settings (all true) * */ @@ -196,7 +197,6 @@ setSetting(JetspeedSerializer.KEY_BACKUP_BEFORE_PROCESS, true); } - /** * On import, get the basic SnapShot data * @@ -208,289 +208,321 @@ logMe("software SUbVersion : " + getSnapshot().getSavedSubversion()); } - - - private void recreateCapabilities (Capabilities caps) throws SerializerException + private void recreateCapabilities(Capabilities caps) + throws SerializerException { - logMe("recreateCapabilities - processing"); - JSCapabilities capabilities = ((JSSeedData)getSnapshot()).getCapabilities(); - if ((capabilities != null) && (capabilities.size() > 0)) - { - Iterator _it = capabilities.iterator(); - while (_it.hasNext()) - { - JSCapability _c = (JSCapability)_it.next(); -// create a new Capability - try - { - Capability capability = caps.createCapability(_c.getName()); - /** THE KEY_OVERWRITE_EXISTING test is not required for capabilites, since they carry no other information than the name - * Used here for consistency, though - */ - if ((this.getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)) || (capability.getCapabilityId() == 0)) - { - caps.storeCapability(capability); - } - this.capabilityMap.put(_c.getName(), capability); - } - catch (Exception e) - { - throw new SerializerException( - SerializerException.CREATE_OBJECT_FAILED - .create("org.apache.jetspeed.capabilities.Capabilities",e.getLocalizedMessage())); - } - } - } - else - logMe("NO CAPABILITES?????"); - logMe("recreateCapabilities - done"); + logMe("recreateCapabilities - processing"); + JSCapabilities capabilities = ((JSSeedData) getSnapshot()) + .getCapabilities(); + if ((capabilities != null) && (capabilities.size() > 0)) + { + Iterator _it = capabilities.iterator(); + while (_it.hasNext()) + { + JSCapability _c = (JSCapability) _it.next(); + // create a new Capability + try + { + Capability capability = caps.createCapability(_c.getName()); + /** + * THE KEY_OVERWRITE_EXISTING test is not required for + * capabilites, since they carry no other information than + * the name Used here for consistency, though + */ + if ((this + .getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)) + || (capability.getCapabilityId() == 0)) + { + caps.storeCapability(capability); + } + this.capabilityMap.put(_c.getName(), capability); + } + catch (Exception e) + { + throw new SerializerException( + SerializerException.CREATE_OBJECT_FAILED + .create( + "org.apache.jetspeed.capabilities.Capabilities", + e.getLocalizedMessage())); + } + } + } + else + logMe("NO CAPABILITES?????"); + logMe("recreateCapabilities - done"); } - private void recreateMimeTypes (Capabilities caps) throws SerializerException + + private void recreateMimeTypes(Capabilities caps) + throws SerializerException { - logMe("recreateMimeTypes - processing"); - JSMimeTypes mimeTypes = ((JSSeedData)getSnapshot()).getMimeTypes(); - if ((mimeTypes != null) && (mimeTypes.size() > 0)) - { - Iterator _it = mimeTypes.iterator(); - while (_it.hasNext()) - { - JSMimeType _c = (JSMimeType)_it.next(); -// create a new Mime Type - try - { - MimeType mimeType = caps.createMimeType(_c.getName()); - /** THE KEY_OVERWRITE_EXISTING test is not required for mime types, since they carry no other information than the name - * Used here for consistency, though - */ - if ((this.getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)) || (mimeType.getMimetypeId() == 0)) - { - caps.storeMimeType(mimeType); - } - this.mimeMap.put(_c.getName(), mimeType); + logMe("recreateMimeTypes - processing"); + JSMimeTypes mimeTypes = ((JSSeedData) getSnapshot()).getMimeTypes(); + if ((mimeTypes != null) && (mimeTypes.size() > 0)) + { + Iterator _it = mimeTypes.iterator(); + while (_it.hasNext()) + { + JSMimeType _c = (JSMimeType) _it.next(); + // create a new Mime Type + try + { + MimeType mimeType = caps.createMimeType(_c.getName()); + /** + * THE KEY_OVERWRITE_EXISTING test is not required for mime + * types, since they carry no other information than the + * name Used here for consistency, though + */ + if ((this + .getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)) + || (mimeType.getMimetypeId() == 0)) + { + caps.storeMimeType(mimeType); + } + this.mimeMap.put(_c.getName(), mimeType); - } - catch (Exception e) - { - throw new SerializerException( - SerializerException.CREATE_OBJECT_FAILED - .create("org.apache.jetspeed.capabilities.MimeType",e.getLocalizedMessage())); - } - } - } - else - logMe("NO MIME TYPES?????"); - logMe("recreateMimeTypes - done"); + } + catch (Exception e) + { + throw new SerializerException( + SerializerException.CREATE_OBJECT_FAILED + .create( + "org.apache.jetspeed.capabilities.MimeType", + e.getLocalizedMessage())); + } + } + } + else + logMe("NO MIME TYPES?????"); + logMe("recreateMimeTypes - done"); } - private void recreateMediaTypes (Capabilities caps) throws SerializerException + private void recreateMediaTypes(Capabilities caps) + throws SerializerException { - String _line; - - logMe("recreateMediaTypes - processing"); - JSMediaTypes mediaTypes = ((JSSeedData)getSnapshot()).getMediaTypes(); - if ((mediaTypes != null) && (mediaTypes.size() > 0)) - { - Iterator _it = mediaTypes.iterator(); - while (_it.hasNext()) - { - JSMediaType _c = (JSMediaType)_it.next(); -// create a new Media - try - { - MediaType mediaType = caps.createMediaType(_c.getName()); - /** THE KEY_OVERWRITE_EXISTING test IS required for media types, since they carry no other information than the name - * Used here for consistency, though - */ - if ((this.getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)) || (mediaType.getMediatypeId() == 0)) - { -// set object fields - mediaType.setCharacterSet(_c.getCharacterSet()); - mediaType.setTitle(_c.getTitle()); - mediaType.setDescription(_c.getDescription()); - - try - { - _line = _c.getMimeTypesString().toString(); - ArrayList list = this.getTokens(_line); - if ((list != null) && (list.size()>0)) - { - Iterator _it1 = list.iterator(); - int added = 0; - while (_it1.hasNext()) - { - MimeType _mt = caps.createMimeType((String)_it1.next()); - if (_mt != null) - mediaType.addMimetype(_mt); - added++; - } - } - } - catch (Exception e1) - { - e1.printStackTrace(); - } - try - { - _line = _c.getCapabilitiesString().toString(); - ArrayList list = this.getTokens(_line); - if ((list != null) && (list.size()>0)) - { - Iterator _it1 = list.iterator(); - if ((list != null) && (list.size()>0)) - { - int added = 0; - while (_it1.hasNext()) - { - Capability _ct = caps.createCapability((String)_it1.next()); - if (_ct != null) - mediaType.addCapability(_ct); - added++; - } - } - } - } - catch (Exception e1) - { - e1.printStackTrace(); - } - caps.storeMediaType(mediaType); - } - this.mediaMap.put(_c.getName(), mediaType); - } - catch (Exception e) - { - throw new SerializerException( - SerializerException.CREATE_OBJECT_FAILED - .create("org.apache.jetspeed.capabilities.MediaType",e.getLocalizedMessage())); - } - } - } - else - logMe("NO MEDIA TYPES?????"); - logMe("recreateMediaTypes - done"); + String _line; + + logMe("recreateMediaTypes - processing"); + JSMediaTypes mediaTypes = ((JSSeedData) getSnapshot()).getMediaTypes(); + if ((mediaTypes != null) && (mediaTypes.size() > 0)) + { + Iterator _it = mediaTypes.iterator(); + while (_it.hasNext()) + { + JSMediaType _c = (JSMediaType) _it.next(); + // create a new Media + try + { + MediaType mediaType = caps.createMediaType(_c.getName()); + /** + * THE KEY_OVERWRITE_EXISTING test IS required for media + * types, since they carry no other information than the + * name Used here for consistency, though + */ + if ((this + .getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)) + || (mediaType.getMediatypeId() == 0)) + { + // set object fields + mediaType.setCharacterSet(_c.getCharacterSet()); + mediaType.setTitle(_c.getTitle()); + mediaType.setDescription(_c.getDescription()); + + try + { + _line = _c.getMimeTypesString().toString(); + ArrayList list = this.getTokens(_line); + if ((list != null) && (list.size() > 0)) + { + Iterator _it1 = list.iterator(); + int added = 0; + while (_it1.hasNext()) + { + MimeType _mt = caps + .createMimeType((String) _it1 + .next()); + if (_mt != null) + mediaType.addMimetype(_mt); + added++; + } + } + } + catch (Exception e1) + { + e1.printStackTrace(); + } + try + { + _line = _c.getCapabilitiesString().toString(); + ArrayList list = this.getTokens(_line); + if ((list != null) && (list.size() > 0)) + { + Iterator _it1 = list.iterator(); + if ((list != null) && (list.size() > 0)) + { + int added = 0; + while (_it1.hasNext()) + { + Capability _ct = caps + .createCapability((String) _it1 + .next()); + if (_ct != null) + mediaType.addCapability(_ct); + added++; + } + } + } + } + catch (Exception e1) + { + e1.printStackTrace(); + } + caps.storeMediaType(mediaType); + } + this.mediaMap.put(_c.getName(), mediaType); + } + catch (Exception e) + { + throw new SerializerException( + SerializerException.CREATE_OBJECT_FAILED + .create( + "org.apache.jetspeed.capabilities.MediaType", + e.getLocalizedMessage())); + } + } + } + else + logMe("NO MEDIA TYPES?????"); + logMe("recreateMediaTypes - done"); } - - - private void recreateClients (Capabilities caps) throws SerializerException + + private void recreateClients(Capabilities caps) throws SerializerException { - String _line; - - logMe("recreateClients - processing"); - JSClients clients = ((JSSeedData)getSnapshot()).getClients(); - if ((clients != null) && (clients.size() > 0)) - { - Iterator _it = clients.iterator(); - while (_it.hasNext()) - { - JSClient _c = (JSClient)_it.next(); -// create a new Media - try - { - Client client = caps.createClient(_c.getName()); - /** THE KEY_OVERWRITE_EXISTING test IS required for media types, since they carry no other information than the name - * Used here for consistency, though - */ - if ((this.getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)) || (client.getClientId() == 0)) - { -// set object fields - client.setUserAgentPattern(_c.getUserAgentPattern()); - client.setManufacturer(_c.getManufacturer()); - client.setModel(_c.getModel()); - client.setEvalOrder(_c.getEvalOrder()); - String myPrefMimeType = _c.getPreferredMimeTypeID(); - client.setVersion(_c.getVersion()); - try - { - _line = _c.getMimeTypesString().toString(); - ArrayList list = this.getTokens(_line); - if ((list != null) && (list.size()>0)) - { - Iterator _it1 = list.iterator(); - int added = 0; - while (_it1.hasNext()) - { - MimeType _mt = caps.createMimeType((String)_it1.next()); - if (_mt != null) - { - client.getMimetypes().add(_mt); - if (_mt.getMimetypeId() == 0) - { - caps.storeMimeType(_mt); - } - if (myPrefMimeType.equalsIgnoreCase(_mt.getName())) - client.setPreferredMimeTypeId(_mt.getMimetypeId()); - - } - added++; - } - } - } - catch (Exception e1) - { - e1.printStackTrace(); - } - try - { - _line = _c.getCapabilitiesString().toString(); - ArrayList list = this.getTokens(_line); - if ((list != null) && (list.size()>0)) - { - Iterator _it1 = list.iterator(); - if ((list != null) && (list.size()>0)) - { - int added = 0; - while (_it1.hasNext()) - { - Capability _ct = caps.createCapability((String)_it1.next()); - if (_ct != null) - client.getCapabilities().add(_ct); - added++; - } - } - } - } - catch (Exception e1) - { - e1.printStackTrace(); - } - caps.storeClient(client); - } - this.clientMap.put(_c.getName(), client); - } - catch (Exception e) - { - throw new SerializerException( - SerializerException.CREATE_OBJECT_FAILED - .create("org.apache.jetspeed.capabilities.Client",e.getLocalizedMessage())); - } - } - } - else - logMe("NO MEDIA TYPES?????"); - logMe("recreateClients - done"); + String _line; + + logMe("recreateClients - processing"); + JSClients clients = ((JSSeedData) getSnapshot()).getClients(); + if ((clients != null) && (clients.size() > 0)) + { + Iterator _it = clients.iterator(); + while (_it.hasNext()) + { + JSClient _c = (JSClient) _it.next(); + // create a new Media + try + { + Client client = caps.createClient(_c.getName()); + /** + * THE KEY_OVERWRITE_EXISTING test IS required for media + * types, since they carry no other information than the + * name Used here for consistency, though + */ + if ((this + .getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)) + || (client.getClientId() == 0)) + { + // set object fields + client.setUserAgentPattern(_c.getUserAgentPattern()); + client.setManufacturer(_c.getManufacturer()); + client.setModel(_c.getModel()); + client.setEvalOrder(_c.getEvalOrder()); + String myPrefMimeType = _c.getPreferredMimeTypeID(); + client.setVersion(_c.getVersion()); + try + { + _line = _c.getMimeTypesString().toString(); + ArrayList list = this.getTokens(_line); + if ((list != null) && (list.size() > 0)) + { + Iterator _it1 = list.iterator(); + int added = 0; + while (_it1.hasNext()) + { + MimeType _mt = caps + .createMimeType((String) _it1 + .next()); + if (_mt != null) + { + client.getMimetypes().add(_mt); + if (_mt.getMimetypeId() == 0) + { + caps.storeMimeType(_mt); + } + if (myPrefMimeType.equalsIgnoreCase(_mt + .getName())) + client.setPreferredMimeTypeId(_mt + .getMimetypeId()); + + } + added++; + } + } + } + catch (Exception e1) + { + e1.printStackTrace(); + } + try + { + _line = _c.getCapabilitiesString().toString(); + ArrayList list = this.getTokens(_line); + if ((list != null) && (list.size() > 0)) + { + Iterator _it1 = list.iterator(); + if ((list != null) && (list.size() > 0)) + { + int added = 0; + while (_it1.hasNext()) + { + Capability _ct = caps + .createCapability((String) _it1 + .next()); + if (_ct != null) + client.getCapabilities().add(_ct); + added++; + } + } + } + } + catch (Exception e1) + { + e1.printStackTrace(); + } + caps.storeClient(client); + } + this.clientMap.put(_c.getName(), client); + } + catch (Exception e) + { + throw new SerializerException( + SerializerException.CREATE_OBJECT_FAILED.create( + "org.apache.jetspeed.capabilities.Client", + e.getLocalizedMessage())); + } + } + } + else + logMe("NO MEDIA TYPES?????"); + logMe("recreateClients - done"); } - private void importCapabilitiesInfrastructure() throws SerializerException { - logMe("importCapabilitiesInfrastructure - processing"); - Capabilities caps = (Capabilities) getCM() - .getComponent("org.apache.jetspeed.capabilities.Capabilities"); + logMe("importCapabilitiesInfrastructure - processing"); + Capabilities caps = (Capabilities) getCM().getComponent( + "org.apache.jetspeed.capabilities.Capabilities"); if (caps == null) - throw new SerializerException( - SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST - .create("org.apache.jetspeed.capabilities.Capabilities")); - + throw new SerializerException( + SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST + .create("org.apache.jetspeed.capabilities.Capabilities")); + recreateCapabilities(caps); recreateMimeTypes(caps); recreateMediaTypes(caps); recreateClients(caps); - - - logMe("importCapabilitiesInfrastructure - processing done"); + + logMe("importCapabilitiesInfrastructure - processing done"); } - /** * import the groups, roles and finally the users to the current environment * @@ -498,287 +530,313 @@ */ private void recreateRolesGroupsUsers() throws SerializerException { - logMe("recreateRolesGroupsUsers"); - GroupManager groupManager = (GroupManager) getCM() - .getComponent("org.apache.jetspeed.security.GroupManager"); + logMe("recreateRolesGroupsUsers"); + GroupManager groupManager = (GroupManager) getCM().getComponent( + "org.apache.jetspeed.security.GroupManager"); if (groupManager == null) throw new SerializerException( SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST .create("org.apache.jetspeed.security.GroupManager")); - RoleManager roleManager = (RoleManager) getCM() - .getComponent("org.apache.jetspeed.security.RoleManager"); + RoleManager roleManager = (RoleManager) getCM().getComponent( + "org.apache.jetspeed.security.RoleManager"); if (roleManager == null) throw new SerializerException( SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST .create("org.apache.jetspeed.security.RoleManager")); - UserManager userManager = (UserManager) getCM() - .getComponent("org.apache.jetspeed.security.UserManager"); + UserManager userManager = (UserManager) getCM().getComponent( + "org.apache.jetspeed.security.UserManager"); if (userManager == null) - throw new SerializerException( - SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST - .create("org.apache.jetspeed.security.UserManager")); + throw new SerializerException( + SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST + .create("org.apache.jetspeed.security.UserManager")); - - - JSGroups groups = null; JSRoles roles = null; Iterator _it = null; - groups = ((JSSeedData)getSnapshot()).getGroups(); + groups = ((JSSeedData) getSnapshot()).getGroups(); if (groups != null) { - _it = groups.iterator(); - while (_it.hasNext()) - { - String name = ((JSGroup)_it.next()).getName(); + _it = groups.iterator(); + while (_it.hasNext()) + { + String name = ((JSGroup) _it.next()).getName(); - try - { - if (!(groupManager.groupExists(name))) - groupManager.addGroup(name); - Group group = groupManager.getGroup(name); - this.groupMap.put(name, group.getPrincipal()); - } catch (Exception e) - { - throw new SerializerException( - SerializerException.CREATE_OBJECT_FAILED - .create(new String[] - { "Group", e.getMessage()})); - } + try + { + if (!(groupManager.groupExists(name))) + groupManager.addGroup(name); + Group group = groupManager.getGroup(name); + this.groupMap.put(name, group.getPrincipal()); + } + catch (Exception e) + { + throw new SerializerException( + SerializerException.CREATE_OBJECT_FAILED + .create(new String[] + {"Group", e.getMessage()})); + } + } } - } - logMe("recreateGroups - done"); - logMe("processing roles"); + logMe("recreateGroups - done"); + logMe("processing roles"); - roles = ((JSSeedData)getSnapshot()).getRoles(); - if (roles!= null) - { - _it = roles.iterator(); - - while (_it.hasNext()) + roles = ((JSSeedData) getSnapshot()).getRoles(); + if (roles != null) { - String name = ((JSRole)_it.next()).getName(); + _it = roles.iterator(); - try - { - if (!(roleManager.roleExists(name))) - roleManager.addRole(name); - Role role = roleManager.getRole(name); - this.roleMap.put(name, role.getPrincipal()); - } catch (Exception e) - { - throw new SerializerException( - SerializerException.CREATE_OBJECT_FAILED - .create(new String[] - { "Role", e.getMessage()})); - } + while (_it.hasNext()) + { + String name = ((JSRole) _it.next()).getName(); + + try + { + if (!(roleManager.roleExists(name))) + roleManager.addRole(name); + Role role = roleManager.getRole(name); + this.roleMap.put(name, role.getPrincipal()); + } + catch (Exception e) + { + throw new SerializerException( + SerializerException.CREATE_OBJECT_FAILED + .create(new String[] + {"Role", e.getMessage()})); + } + } } - } logMe("recreateRoles - done"); - logMe("processing users"); + logMe("processing users"); - /** determine whether passwords can be reconstructed or not */ - int passwordEncoding = compareCurrentSecurityProvider((JSSeedData)getSnapshot()); + /** determine whether passwords can be reconstructed or not */ + int passwordEncoding = compareCurrentSecurityProvider((JSSeedData) getSnapshot()); JSUsers users = null; - users = ((JSSeedData)getSnapshot()).getUsers(); - if(users!=null) - {_it = users.iterator(); - while (_it.hasNext()) + users = ((JSSeedData) getSnapshot()).getUsers(); + if (users != null) { - - JSUser jsuser = (JSUser)_it.next(); + _it = users.iterator(); + while (_it.hasNext()) + { - try - { - User user = null; - if (userManager.userExists(jsuser.getName())) - { - user = userManager.getUser(jsuser.getName()); - } - if ((this.getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)) || (user == null)) - { - if (user == null) //create new one - { - String password = recreatePassword(jsuser.getPassword()); - logMe("add User "+ jsuser.getName() + " with password " + password); - userManager.importUser(jsuser.getName(), password,(passwordEncoding == PASSTHRU_REQUIRED)); - logMe("add User done "); - user = userManager.getUser(jsuser.getName()); - } - try - { - userManager.setPasswordEnabled(jsuser.getName(), jsuser.getPwEnabled()); - userManager.setPasswordUpdateRequired(jsuser.getName(), jsuser.getPwRequiredUpdate()); - java.sql.Date d = jsuser.getPwExpirationDate(); - if (d != null) - userManager.setPasswordExpiration(jsuser.getName(), d); - } - catch (Exception e) - { - // most likely caused by protected users (like "guest") - logMe("setting userinfo for "+ jsuser.getName() + " failed because of " + e.getLocalizedMessage()); - } - - //credentials - Subject subject = user.getSubject(); + JSUser jsuser = (JSUser) _it.next(); - ArrayList listTemp = jsuser.getPrivateCredentials(); - if ((listTemp != null) && (listTemp.size()>0)) - { - Iterator _itTemp = listTemp.iterator(); - while (_itTemp.hasNext()) - { - subject.getPrivateCredentials().add(_itTemp.next()); - } - } - listTemp = jsuser.getPublicCredentials(); - if ((listTemp != null) && (listTemp.size()>0)) - { - Iterator _itTemp = listTemp.iterator(); - while (_itTemp.hasNext()) - { - subject.getPublicCredentials().add(_itTemp.next()); - } - } - JSUserGroups jsUserGroups = jsuser.getGroupString(); - if (jsUserGroups != null) - listTemp = this.getTokens(jsUserGroups.toString()); - else - listTemp = null; - if ((listTemp != null) && (listTemp.size()>0)) - { - Iterator _itTemp = listTemp.iterator(); - while (_itTemp.hasNext()) - { - groupManager.addUserToGroup(jsuser.getName(), (String)_itTemp.next()); - } - } - JSUserRoles jsUserRoles = jsuser.getRoleString(); - if (jsUserRoles != null) - listTemp = this.getTokens(jsUserRoles.toString()); - else - listTemp = null; - if ((listTemp != null) && (listTemp.size()>0)) - { - Iterator _itTemp = listTemp.iterator(); - while (_itTemp.hasNext()) - { - roleManager.addRoleToUser(jsuser.getName(), (String)_itTemp.next()); - } - } - JSUserAttributes attributes = jsuser.getUserInfo(); - if (attributes != null) - { - Preferences userAttributes = user.getUserAttributes(); - HashMap map = attributes.getMyMap(); - if (map != null) - { - Iterator _itTemp = map.keySet().iterator(); - while (_itTemp.hasNext()) - { - String userAttrName = (String)_itTemp.next(); -// if ( userAttributes.get(userAttrName, "").equals("") - String userAttrValue = (String)map.get(userAttrName); - userAttributes.put(userAttrName, userAttrValue); - } - } - - } - - JSNVPElements jsNVP = jsuser.getPreferences(); - if ((jsNVP != null) && (jsNVP.getMyMap() != null)) - { - Preferences preferences = user.getPreferences(); - Iterator _itTemp = jsNVP.getMyMap().keySet().iterator(); - while (_itTemp.hasNext()) - { - String prefKey = (String)_itTemp.next(); - String prefValue = (String)(jsNVP.getMyMap().get(prefKey)); - preferences.put(prefKey,prefValue); - } - } - - this.userMap.put(jsuser.getName(), getUserPrincipal(user)); + try + { + User user = null; + if (userManager.userExists(jsuser.getName())) + { + user = userManager.getUser(jsuser.getName()); + } + if ((this + .getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING)) + || (user == null)) + { + if (user == null) // create new one + { + String password = recreatePassword(jsuser + .getPassword()); + logMe("add User " + jsuser.getName() + + " with password " + password); + userManager.importUser(jsuser.getName(), password, + (passwordEncoding == PASSTHRU_REQUIRED)); + logMe("add User done "); + user = userManager.getUser(jsuser.getName()); + } + try + { + userManager.setPasswordEnabled(jsuser.getName(), + jsuser.getPwEnabled()); + userManager.setPasswordUpdateRequired(jsuser + .getName(), jsuser.getPwRequiredUpdate()); + java.sql.Date d = jsuser.getPwExpirationDate(); + if (d != null) + userManager.setPasswordExpiration(jsuser + .getName(), d); + } + catch (Exception e) + { + // most likely caused by protected users (like + // "guest") + logMe("setting userinfo for " + jsuser.getName() + + " failed because of " + + e.getLocalizedMessage()); + } - } - } catch (Exception e) - { - e.printStackTrace(); - throw new SerializerException( - SerializerException.CREATE_OBJECT_FAILED - .create(new String[] - { "User", e.getMessage()})); - } + // credentials + Subject subject = user.getSubject(); + + ArrayList listTemp = jsuser.getPrivateCredentials(); + if ((listTemp != null) && (listTemp.size() > 0)) + { + Iterator _itTemp = listTemp.iterator(); + while (_itTemp.hasNext()) + { + subject.getPrivateCredentials().add( + _itTemp.next()); + } + } + listTemp = jsuser.getPublicCredentials(); + if ((listTemp != null) && (listTemp.size() > 0)) + { + Iterator _itTemp = listTemp.iterator(); + while (_itTemp.hasNext()) + { + subject.getPublicCredentials().add( + _itTemp.next()); + } + } + JSUserGroups jsUserGroups = jsuser.getGroupString(); + if (jsUserGroups != null) + listTemp = this.getTokens(jsUserGroups.toString()); + else + listTemp = null; + if ((listTemp != null) && (listTemp.size() > 0)) + { + Iterator _itTemp = listTemp.iterator(); + while (_itTemp.hasNext()) + { + groupManager.addUserToGroup(jsuser.getName(), + (String) _itTemp.next()); + } + } + JSUserRoles jsUserRoles = jsuser.getRoleString(); + if (jsUserRoles != null) + listTemp = this.getTokens(jsUserRoles.toString()); + else + listTemp = null; + if ((listTemp != null) && (listTemp.size() > 0)) + { + Iterator _itTemp = listTemp.iterator(); + while (_itTemp.hasNext()) + { + roleManager.addRoleToUser(jsuser.getName(), + (String) _itTemp.next()); + } + } + JSUserAttributes attributes = jsuser.getUserInfo(); + if (attributes != null) + { + Preferences userAttributes = user + .getUserAttributes(); + HashMap map = attributes.getMyMap(); + if (map != null) + { + Iterator _itTemp = map.keySet().iterator(); + while (_itTemp.hasNext()) + { + String userAttrName = (String) _itTemp + .next(); + // if ( userAttributes.get(userAttrName, + // "").equals("") + String userAttrValue = (String) map + .get(userAttrName); + userAttributes.put(userAttrName, + userAttrValue); + } + } + + } + + JSNVPElements jsNVP = jsuser.getPreferences(); + if ((jsNVP != null) && (jsNVP.getMyMap() != null)) + { + Preferences preferences = user.getPreferences(); + Iterator _itTemp = jsNVP.getMyMap().keySet() + .iterator(); + while (_itTemp.hasNext()) + { + String prefKey = (String) _itTemp.next(); + String prefValue = (String) (jsNVP.getMyMap() + .get(prefKey)); + preferences.put(prefKey, prefValue); + } + } + + this.userMap.put(jsuser.getName(), + getUserPrincipal(user)); + + } + } + catch (Exception e) + { + e.printStackTrace(); + throw new SerializerException( + SerializerException.CREATE_OBJECT_FAILED + .create(new String[] + {"User", e.getMessage()})); + } + } } - } - logMe("recreateUsers - done"); - return; + logMe("recreateUsers - done"); + return; } - + /** * called only after users have been established + * * @throws SerializerException */ private void recreateUserPrincipalRules() throws SerializerException { - logMe("recreateUserPrincipalRules - started"); - - Profiler pm = (Profiler) getCM() - .getComponent("org.apache.jetspeed.profiler.Profiler"); + logMe("recreateUserPrincipalRules - started"); + + Profiler pm = (Profiler) getCM().getComponent( + "org.apache.jetspeed.profiler.Profiler"); if (pm == null) - throw new SerializerException( - SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST - .create("org.apache.jetspeed.profiler.Profiler")); - UserManager userManager = (UserManager) getCM() - .getComponent("org.apache.jetspeed.security.UserManager"); + throw new SerializerException( + SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST + .create("org.apache.jetspeed.profiler.Profiler")); + UserManager userManager = (UserManager) getCM().getComponent( + "org.apache.jetspeed.security.UserManager"); if (userManager == null) - throw new SerializerException( - SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST - .create("org.apache.jetspeed.security.UserManager")); + throw new SerializerException( + SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST + .create("org.apache.jetspeed.security.UserManager")); // get Rules for each user - Iterator _itUsers = ((JSSeedData)getSnapshot()).getUsers().iterator(); + Iterator _itUsers = ((JSSeedData) getSnapshot()).getUsers().iterator(); while (_itUsers.hasNext()) { JSUser _user = (JSUser) _itUsers.next(); JSPrincipalRules jsRules = _user.getRules(); try { - User user = userManager.getUser(_user.getName()); - Principal principal = getUserPrincipal(user); - if (jsRules != null) - { - Iterator _itRoles = jsRules.iterator(); - while (_itRoles.hasNext()) - { - JSPrincipalRule pr = (JSPrincipalRule) _itRoles.next(); - ProfilingRule pRule = pm.getRule(pr.getRule()); - - try - { - PrincipalRule p1 = pm.createPrincipalRule(); - p1.setLocatorName(pr.getLocator()); - p1.setProfilingRule(pRule); - p1.setPrincipalName(principal.getName()); - pm.storePrincipalRule(p1); - } - catch (Exception eRole) - { - eRole.printStackTrace(); - } - } - } + User user = userManager.getUser(_user.getName()); + Principal principal = getUserPrincipal(user); + if (jsRules != null) + { + Iterator _itRoles = jsRules.iterator(); + while (_itRoles.hasNext()) + { + JSPrincipalRule pr = (JSPrincipalRule) _itRoles.next(); + ProfilingRule pRule = pm.getRule(pr.getRule()); + + try + { + PrincipalRule p1 = pm.createPrincipalRule(); + p1.setLocatorName(pr.getLocator()); + p1.setProfilingRule(pRule); + p1.setPrincipalName(principal.getName()); + pm.storePrincipalRule(p1); + } + catch (Exception eRole) + { + eRole.printStackTrace(); + } + } + } } - catch (Exception eUser) - { - eUser.printStackTrace(); - } + catch (Exception eUser) + { + eUser.printStackTrace(); + } } - logMe("recreateUserPrincipalRules - done"); + logMe("recreateUserPrincipalRules - done"); } + /** * recreates all permissions from the current snapshot * @@ -786,88 +844,90 @@ */ private void recreatePermissions() throws SerializerException { - logMe("recreatePermissions - started"); - PermissionManager pm = (PermissionManager) getCM() - .getComponent("org.apache.jetspeed.security.PermissionManager"); + logMe("recreatePermissions - started"); + PermissionManager pm = (PermissionManager) getCM().getComponent( + "org.apache.jetspeed.security.PermissionManager"); if (pm == null) throw new SerializerException( SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST .create("org.apache.jetspeed.security.PermissionManager")); Iterator list = null; - JSPermissions permissions = ((JSSeedData)getSnapshot()).getPermissions(); - + JSPermissions permissions = ((JSSeedData) getSnapshot()) + .getPermissions(); + if (permissions != null) { - list = permissions.iterator(); + list = permissions.iterator(); while (list.hasNext()) { - JSPermission _js = (JSPermission)list.next(); + JSPermission _js = (JSPermission) list.next(); PortalResourcePermission perm = _js.getPermissionForType(); - if ((perm != null) && (perm instanceof PortalResourcePermission)) + if ((perm != null) + && (perm instanceof PortalResourcePermission)) { - try + try { pm.addPermission(perm); ArrayList listTemp = null; - JSUserGroups jsUserGroups = _js.getGroupString(); - if (jsUserGroups != null) - listTemp = this.getTokens(jsUserGroups.toString()); - else - listTemp = null; - if ((listTemp != null) && (listTemp.size()>0)) - { - Iterator _itTemp = listTemp.iterator(); - while (_itTemp.hasNext()) - { - Principal p = (Principal)this.groupMap.get((String)_itTemp.next()); - if (p != null) - pm.grantPermission(p, perm); - } - } - JSUserRoles jsUserRoles = _js.getRoleString(); - if (jsUserRoles != null) - listTemp = this.getTokens(jsUserRoles.toString()); - else - listTemp = null; - if ((listTemp != null) && (listTemp.size()>0)) - { - Iterator _itTemp = listTemp.iterator(); - while (_itTemp.hasNext()) - { - Principal p = (Principal)this.roleMap.get((String)_itTemp.next()); - if (p != null) - pm.grantPermission(p, perm); - } - } - JSUserUsers jsUserUsers = _js.getUserString(); - if (jsUserUsers != null) - listTemp = this.getTokens(jsUserUsers.toString()); - else - listTemp = null; - if ((listTemp != null) && (listTemp.size()>0)) - { - Iterator _itTemp = listTemp.iterator(); - while (_itTemp.hasNext()) - { - Principal p = (Principal)this.userMap.get((String)_itTemp.next()); - if (p != null) - pm.grantPermission(p, perm); - } - } - - } - catch (Exception e) - { - throw new SerializerException( - SerializerException.CREATE_SERIALIZED_OBJECT_FAILED - .create(new String[] - { "Permissions", e.getMessage()})); - } + JSUserGroups jsUserGroups = _js.getGroupString(); + if (jsUserGroups != null) + listTemp = this.getTokens(jsUserGroups.toString()); + else + listTemp = null; + if ((listTemp != null) && (listTemp.size() > 0)) + { + Iterator _itTemp = listTemp.iterator(); + while (_itTemp.hasNext()) + { + Principal p = (Principal) this.groupMap + .get((String) _itTemp.next()); + if (p != null) pm.grantPermission(p, perm); + } + } + JSUserRoles jsUserRoles = _js.getRoleString(); + if (jsUserRoles != null) + listTemp = this.getTokens(jsUserRoles.toString()); + else + listTemp = null; + if ((listTemp != null) && (listTemp.size() > 0)) + { + Iterator _itTemp = listTemp.iterator(); + while (_itTemp.hasNext()) + { + Principal p = (Principal) this.roleMap + .get((String) _itTemp.next()); + if (p != null) pm.grantPermission(p, perm); + } + } + JSUserUsers jsUserUsers = _js.getUserString(); + if (jsUserUsers != null) + listTemp = this.getTokens(jsUserUsers.toString()); + else + listTemp = null; + if ((listTemp != null) && (listTemp.size() > 0)) + { + Iterator _itTemp = listTemp.iterator(); + while (_itTemp.hasNext()) + { + Principal p = (Principal) this.userMap + .get((String) _itTemp.next()); + if (p != null) pm.grantPermission(p, perm); + } + } + + } + catch (Exception e) + { + throw new SerializerException( + SerializerException.CREATE_SERIALIZED_OBJECT_FAILED + .create(new String[] + {"Permissions", e.getMessage()})); + } } } } - logMe("recreatePermissions - done"); + logMe("recreatePermissions - done"); } private Principal getUserPrincipal(User user) @@ -880,24 +940,23 @@ { BasePrincipal principal = (BasePrincipal) list.next(); String path = principal.getFullPath(); - if (path.startsWith("/user/")) - return principal; + if (path.startsWith("/user/")) return principal; } return null; } - + private void importProfiler() { System.out.println("importProfiler - processing"); try { - recreateProfilingRules(); + recreateProfilingRules(); } catch (Exception e) { - e.printStackTrace(); - } + e.printStackTrace(); + } } private void importUserGroupRoles() @@ -910,7 +969,7 @@ catch (Exception e) { e.printStackTrace(); - } + } } private void importUserPrincipals() @@ -923,9 +982,8 @@ catch (Exception e) { e.printStackTrace(); - } + } } - /** * The workhorse for importing data @@ -938,39 +996,41 @@ protected void processImport() throws SerializerException { this.logMe("*********reinstalling data*********"); - + // TODO: HJB Make sure to clean lookup tables before next run if (this.getSetting(JetspeedSerializer.KEY_PROCESS_CAPABILITIES)) { logMe("creating clients, mediatypes and mimetypes"); importCapabilitiesInfrastructure(); - } + } /** - * the order is important, since profiling rules are referenced by the user + * the order is important, since profiling rules are referenced by the + * user * - */ + */ if (this.getSetting(JetspeedSerializer.KEY_PROCESS_PROFILER)) { logMe("collecting permissions, profiling rules and users/proups etc. etc."); importProfiler(); - } + } if (this.getSetting(JetspeedSerializer.KEY_PROCESS_USERS)) { logMe("creating users/roles/groups"); this.importUserGroupRoles(); } - if (this.getSetting(JetspeedSerializer.KEY_PROCESS_PROFILER) || this.getSetting(JetspeedSerializer.KEY_PROCESS_USERS)) + if (this.getSetting(JetspeedSerializer.KEY_PROCESS_PROFILER) + || this.getSetting(JetspeedSerializer.KEY_PROCESS_USERS)) { logMe("collecting user principals"); this.importUserPrincipals(); - } - - if (this.getSetting(JetspeedSerializer.KEY_PROCESS_PERMISSIONS)) + } + + if (this.getSetting(JetspeedSerializer.KEY_PROCESS_PERMISSIONS)) { logMe("permissions, rules etc. skipped "); - recreatePermissions(); - } + recreatePermissions(); + } } /** @@ -987,7 +1047,7 @@ this.logMe("*********collecting data*********"); /** first create the snapshot file */ - setSnapshot(new JSSeedData(name)); + setSnapshot(new JSSeedData(name)); setSnapshotData(); @@ -995,30 +1055,34 @@ { logMe("collecting clients, mediatypes and mimetypes"); exportCapabilitiesInfrastructure(); - } else + } + else logMe("capabilities skipped"); if (this.getSetting(JetspeedSerializer.KEY_PROCESS_USERS)) { logMe("collecting users"); exportUsers(); - } else + } + else logMe("users skipped"); if (this.getSetting(JetspeedSerializer.KEY_PROCESS_PROFILER)) { logMe("collecting profiling rules"); this.getProfilingRules(); - } else + } + else logMe(" profiling rules skipped"); if (this.getSetting(JetspeedSerializer.KEY_PROCESS_PERMISSIONS)) { logMe("collecting permissions"); this.getPermissions(); - } else + } + else logMe(" permissions skipped"); - + } /** @@ -1064,15 +1128,16 @@ binding.setAlias(String.class, "String"); binding.setAlias(Integer.class, "int"); - - binding.setAlias(JSPWAttributes.class,"credentials"); + binding.setAlias(JSPWAttributes.class, "credentials"); + binding.setClassAttribute(null); } /** * simple lookup for principal object from a map + * * @param map * @param _fullPath * @return @@ -1083,14 +1148,12 @@ return getObjectBehindPath(map, _principal.getFullPath()); } - - - /** - * create a serializable wrapper for role - * - * @param role - * @return - */ + /** + * create a serializable wrapper for role + * + * @param role + * @return + */ private JSRole createJSRole(Role role) { JSRole _role = new JSRole(); @@ -1098,15 +1161,15 @@ return _role; } - /** - * export roles - * - * @return - */ + /** + * export roles + * + * @return + */ private void exportRoles() throws SerializerException { - RoleManager roleManager = (RoleManager) getCM() - .getComponent("org.apache.jetspeed.security.RoleManager"); + RoleManager roleManager = (RoleManager) getCM().getComponent( + "org.apache.jetspeed.security.RoleManager"); if (roleManager == null) throw new SerializerException( SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST @@ -1116,12 +1179,13 @@ try { list = roleManager.getRoles(""); - } catch (Exception e) + } + catch (Exception e) { throw new SerializerException( SerializerException.GET_EXISTING_OBJECTS .create(new String[] - { "Role", e.getMessage()})); + {"Role", e.getMessage()})); } while (list.hasNext()) { @@ -1134,15 +1198,16 @@ { _tempRole = createJSRole(role); roleMap.put(_tempRole.getName(), _tempRole); - ((JSSeedData)getSnapshot()).getRoles().add(_tempRole); + ((JSSeedData) getSnapshot()).getRoles().add(_tempRole); } - } catch (Exception e) + } + catch (Exception e) { throw new SerializerException( SerializerException.CREATE_SERIALIZED_OBJECT_FAILED .create(new String[] - { "Role", e.getMessage()})); + {"Role", e.getMessage()})); } } return; @@ -1166,8 +1231,8 @@ */ private void exportGroups() throws SerializerException { - GroupManager groupManager = (GroupManager) getCM() - .getComponent("org.apache.jetspeed.security.GroupManager"); + GroupManager groupManager = (GroupManager) getCM().getComponent( + "org.apache.jetspeed.security.GroupManager"); if (groupManager == null) throw new SerializerException( SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST @@ -1176,12 +1241,13 @@ try { list = groupManager.getGroups(""); - } catch (Exception e) + } + catch (Exception e) { throw new SerializerException( SerializerException.GET_EXISTING_OBJECTS .create(new String[] - { "Group", e.getMessage()})); + {"Group", e.getMessage()})); } while (list.hasNext()) { @@ -1195,15 +1261,16 @@ { _tempGroup = createJSGroup(group); groupMap.put(_tempGroup.getName(), _tempGroup); - ((JSSeedData)getSnapshot()).getGroups().add(_tempGroup); + ((JSSeedData) getSnapshot()).getGroups().add(_tempGroup); } - } catch (Exception e) + } + catch (Exception e) { throw new SerializerException( SerializerException.CREATE_SERIALIZED_OBJECT_FAILED .create(new String[] - { "Group", e.getMessage()})); + {"Group", e.getMessage()})); } } return; @@ -1230,9 +1297,12 @@ if (credential instanceof PasswordCredential) { PasswordCredential pw = (PasswordCredential) credential; - newUser.setUserCredential(pw.getUserName(), pw.getPassword(),pw.getExpirationDate(),pw.isEnabled(), pw.isExpired(), pw.isUpdateRequired()); + newUser.setUserCredential(pw.getUserName(), pw.getPassword(), pw + .getExpirationDate(), pw.isEnabled(), pw.isExpired(), pw + .isUpdateRequired()); return; - } else if (isPublic) + } + else if (isPublic) newUser.addPublicCredential(credential); else newUser.addPrivateCredential(credential); @@ -1265,7 +1335,8 @@ _newUser.addRole(_tempRole); } - } else + } + else { if (path.startsWith("/group/")) { @@ -1276,7 +1347,8 @@ _newUser.addGroup(_tempGroup); } - } else if (path.startsWith("/user/")) + } + else if (path.startsWith("/user/")) _newUser.setPrincipal(principal); } @@ -1303,11 +1375,11 @@ _newUser.setPreferences(preferences); preferences = user.getUserAttributes(); _newUser.setUserInfo(preferences); - //TODO: HJB, fix preferences...userinfo doesn't return values in prefs_property_value (in fact preferences.keys() is [] + // TODO: HJB, fix preferences...userinfo doesn't return values in + // prefs_property_value (in fact preferences.keys() is [] return _newUser; } - /** * Collect all the roles, groups and users from the current environment. * Include the current SecurityProvider to understand, whether the password @@ -1319,15 +1391,15 @@ private void exportUsers() throws SerializerException { /** set the security provider info in the snapshot file */ - ((JSSeedData)getSnapshot()).setEncryption(getEncryptionString()); + ((JSSeedData) getSnapshot()).setEncryption(getEncryptionString()); /** get the roles */ exportRoles(); /** get the groups */ exportGroups(); /** users */ - UserManager userManager = (UserManager) getCM() - .getComponent("org.apache.jetspeed.security.UserManager"); + UserManager userManager = (UserManager) getCM().getComponent( + "org.apache.jetspeed.security.UserManager"); if (userManager == null) throw new SerializerException( SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST @@ -1336,12 +1408,13 @@ try { list = userManager.getUsers(""); - } catch (Exception e) + } + catch (Exception e) { throw new SerializerException( SerializerException.GET_EXISTING_OBJECTS .create(new String[] - { "User", e.getMessage()})); + {"User", e.getMessage()})); } while (list.hasNext()) { @@ -1351,13 +1424,14 @@ User _user = (User) list.next(); JSUser _tempUser = createJSUser(_user); userMap.put(_tempUser.getName(), _tempUser); - ((JSSeedData)getSnapshot()).getUsers().add(_tempUser); - } catch (Exception e) + ((JSSeedData) getSnapshot()).getUsers().add(_tempUser); + } + catch (Exception e) { throw new SerializerException( SerializerException.CREATE_SERIALIZED_OBJECT_FAILED .create(new String[] - { "User", e.getMessage()})); + {"User", e.getMessage()})); } } @@ -1386,14 +1460,16 @@ JSCapability _jsC = new JSCapability(); _jsC.setName(_cp.getName()); this.capabilityMap.put(_jsC.getName(), _jsC); - this.capabilityMapInt.put(new Integer(_cp.getCapabilityId()), _jsC); - ((JSSeedData)getSnapshot()).getCapabilities().add(_jsC); - } catch (Exception e) + this.capabilityMapInt.put(new Integer(_cp.getCapabilityId()), + _jsC); + ((JSSeedData) getSnapshot()).getCapabilities().add(_jsC); + } + catch (Exception e) { throw new SerializerException( SerializerException.CREATE_SERIALIZED_OBJECT_FAILED .create(new String[] - { "C", e.getMessage()})); + {"C", e.getMessage()})); } } return; @@ -1422,13 +1498,14 @@ this.mimeMap.put(_jsM.getName(), _jsM); this.mimeMapInt.put(new Integer(_mt.getMimetypeId()), _jsM); - ((JSSeedData)getSnapshot()).getMimeTypes().add(_jsM); - } catch (Exception e) + ((JSSeedData) getSnapshot()).getMimeTypes().add(_jsM); + } + catch (Exception e) { throw new SerializerException( SerializerException.CREATE_SERIALIZED_OBJECT_FAILED .create(new String[] - { "MimeType", e.getMessage()})); + {"MimeType", e.getMessage()})); } } return; @@ -1457,14 +1534,14 @@ JSMimeType _mt = (JSMimeType) mimeMap.get(_m.getName()); if (_mt != null) jsC.getMimeTypes().add(_mt); } - - Integer id = new Integer(c.getPreferredMimeTypeId()); - JSMimeType _mt = (JSMimeType) mimeMapInt.get(id); - if (_mt != null) - jsC.setPreferredMimeTypeID(_mt.getName()); - else - jsC.setPreferredMimeTypeID("???"); + Integer id = new Integer(c.getPreferredMimeTypeId()); + JSMimeType _mt = (JSMimeType) mimeMapInt.get(id); + if (_mt != null) + jsC.setPreferredMimeTypeID(_mt.getName()); + else + jsC.setPreferredMimeTypeID("???"); + // find the capabilities Iterator _itC = c.getCapabilities().iterator(); while (_itC.hasNext()) @@ -1476,12 +1553,13 @@ } return jsC; - } catch (Exception e) + } + catch (Exception e) { throw new SerializerException( SerializerException.CREATE_SERIALIZED_OBJECT_FAILED .create(new String[] - { "Client", e.getMessage()})); + {"Client", e.getMessage()})); } } @@ -1513,9 +1591,9 @@ throw new SerializerException( SerializerException.CREATE_SERIALIZED_OBJECT_FAILED .create(new String[] - { "Client", "createClient returned NULL"})); + {"Client", "createClient returned NULL"})); this.clientMap.put(jsC.getName(), jsC); - ((JSSeedData)getSnapshot()).getClients().add(jsC); + ((JSSeedData) getSnapshot()).getClients().add(jsC); } return; } @@ -1555,14 +1633,15 @@ if (_ct != null) _jsM.getCapabilities().add(_ct); } this.mediaMap.put(_jsM.getName(), _jsM); - ((JSSeedData)getSnapshot()).getMediaTypes().add(_jsM); - } catch (Exception e) + ((JSSeedData) getSnapshot()).getMediaTypes().add(_jsM); + } + catch (Exception e) { // do whatever throw new SerializerException( SerializerException.CREATE_SERIALIZED_OBJECT_FAILED .create(new String[] - { "MediaType", e.getMessage()})); + {"MediaType", e.getMessage()})); } } return; @@ -1577,8 +1656,8 @@ private void exportCapabilitiesInfrastructure() throws SerializerException { - Capabilities caps = (Capabilities) getCM() - .getComponent("org.apache.jetspeed.capabilities.Capabilities"); + Capabilities caps = (Capabilities) getCM().getComponent( + "org.apache.jetspeed.capabilities.Capabilities"); if (caps == null) throw new SerializerException( SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST @@ -1604,8 +1683,8 @@ private void getPermissions() throws SerializerException { Object o = null; - PermissionManager pm = (PermissionManager) getCM() - .getComponent("org.apache.jetspeed.security.PermissionManager"); + PermissionManager pm = (PermissionManager) getCM().getComponent( + "org.apache.jetspeed.security.PermissionManager"); if (pm == null) throw new SerializerException( SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST @@ -1615,12 +1694,13 @@ try { list = pm.getPermissions().iterator(); - } catch (Exception e) + } + catch (Exception e) { throw new SerializerException( SerializerException.GET_EXISTING_OBJECTS .create(new String[] - { "Permissions", e.getMessage()})); + {"Permissions", e.getMessage()})); } while (list.hasNext()) @@ -1650,7 +1730,8 @@ _js.addRole(_tempRole); } - } else + } + else { if (path.startsWith("/group/")) { @@ -1662,7 +1743,8 @@ _js.addGroup(_tempGroup); } - } else + } + else { if (path.startsWith("/user/")) { @@ -1682,14 +1764,15 @@ } } this.permissionMap.put(_js.getType(), _js); - ((JSSeedData)getSnapshot()).getPermissions().add(_js); + ((JSSeedData) getSnapshot()).getPermissions().add(_js); - } catch (Exception e) + } + catch (Exception e) { throw new SerializerException( SerializerException.CREATE_SERIALIZED_OBJECT_FAILED .create(new String[] - { "Permissions", e.getMessage()})); + {"Permissions", e.getMessage()})); } } return; @@ -1702,12 +1785,11 @@ * @param p * @return */ - private JSProfilingRule createProfilingRule(ProfilingRule p, boolean standard) + private JSProfilingRule createProfilingRule(ProfilingRule p, + boolean standard) { JSProfilingRule rule = new JSProfilingRule(); - - - + rule.setStandardRule(standard); rule.setDescription(p.getTitle()); rule.setId(p.getId()); @@ -1732,8 +1814,8 @@ */ private void getProfilingRules() throws SerializerException { - Profiler pm = (Profiler) getCM() - .getComponent("org.apache.jetspeed.profiler.Profiler"); + Profiler pm = (Profiler) getCM().getComponent( + "org.apache.jetspeed.profiler.Profiler"); if (pm == null) throw new SerializerException( @@ -1742,27 +1824,28 @@ Class standardRuleClass = null; try { - ProfilingRule tempStandardRule = pm.createProfilingRule(true); - standardRuleClass = tempStandardRule.getClass(); + ProfilingRule tempStandardRule = pm.createProfilingRule(true); + standardRuleClass = tempStandardRule.getClass(); } catch (Exception e) { - throw new SerializerException( - SerializerException.CREATE_OBJECT_FAILED - .create(new String[] - { "Standard Rule", e.getMessage()})); + throw new SerializerException( + SerializerException.CREATE_OBJECT_FAILED + .create(new String[] + {"Standard Rule", e.getMessage()})); } - + Iterator list = null; try { list = pm.getRules().iterator(); - } catch (Exception e) + } + catch (Exception e) { throw new SerializerException( SerializerException.GET_EXISTING_OBJECTS .create(new String[] - { "ProfilingRules", e.getMessage()})); + {"ProfilingRules", e.getMessage()})); } while (list.hasNext()) { @@ -1771,24 +1854,26 @@ ProfilingRule p = (ProfilingRule) list.next(); if (!(this.rulesMap.containsKey(p.getId()))) { - JSProfilingRule rule = createProfilingRule(p, (standardRuleClass == p.getClass())); + JSProfilingRule rule = createProfilingRule(p, + (standardRuleClass == p.getClass())); rulesMap.put(rule.getId(), rule); - ((JSSeedData)getSnapshot()).getRules().add(rule); + ((JSSeedData) getSnapshot()).getRules().add(rule); } - } catch (Exception e) + } + catch (Exception e) { throw new SerializerException( SerializerException.CREATE_SERIALIZED_OBJECT_FAILED .create(new String[] - { "ProfilingRules", e.getMessage()})); + {"ProfilingRules", e.getMessage()})); } } // determine the defualt rule ProfilingRule defaultRule = pm.getDefaultRule(); if (defaultRule != null) - ((JSSeedData)getSnapshot()).setDefaultRule(defaultRule.getId()); + ((JSSeedData) getSnapshot()).setDefaultRule(defaultRule.getId()); // get Rules for each user @@ -1827,179 +1912,194 @@ String _fileEncryption = file.getEncryption(); if ((_fileEncryption == null) || (_fileEncryption.length() == 0)) return NO_DECODING; // passwords are in clear text - + if (_fileEncryption.equals(getEncryptionString())) - return PASSTHRU_REQUIRED; + return PASSTHRU_REQUIRED; else - return NO_DECODING; + return NO_DECODING; } private String getEncryptionString() { PasswordCredentialProvider provider = (PasswordCredentialProvider) getCM() - .getComponent("org.apache.jetspeed.security.spi.PasswordCredentialProvider"); - if (provider == null) - { - System.err - .println("Error!!! PasswordCredentialProvider not available"); - return ENCODING_STRING; - } - try - { - PasswordCredential credential = provider.create(JETSPEED,ENCODING_STRING); - if ((credential != null) && (credential.getPassword() != null)) - return new String(credential.getPassword()); - else - return ENCODING_STRING; - } - catch (Exception e) - { - e.printStackTrace(); - return ENCODING_STRING; - } + .getComponent( + "org.apache.jetspeed.security.spi.PasswordCredentialProvider"); + if (provider == null) + { + System.err + .println("Error!!! PasswordCredentialProvider not available"); + return ENCODING_STRING; + } + try + { + PasswordCredential credential = provider.create(JETSPEED, + ENCODING_STRING); + if ((credential != null) && (credential.getPassword() != null)) + return new String(credential.getPassword()); + else + return ENCODING_STRING; + } + catch (Exception e) + { + e.printStackTrace(); + return ENCODING_STRING; + } } - + /** * ++++++++++++++++++++++++++++++HELPERS * +++++++++++++++++++++++++++++++++++++++++++++ */ - - - /** * recreate a rule criterion object from the deserialized wrapper - * @param profiler established profile manager - * @param jsr deserialized object + * + * @param profiler + * established profile manager + * @param jsr + * deserialized object * @return new RuleCriterion with content set to deserialized wrapepr * @throws SerializerException */ - protected RuleCriterion recreateRuleCriterion(Profiler profiler, JSRuleCriterion jsr, ProfilingRule rule) - throws SerializerException, ClassNotFoundException - - { - try - { - - RuleCriterion c = profiler.createRuleCriterion(); - if (c == null) - throw new SerializerException( - SerializerException.CREATE_OBJECT_FAILED - .create("org.apache.jetspeed.profiler.rules.RuleCriterion","returned null")); - c.setFallbackOrder(jsr.getFallBackOrder()); - c.setFallbackType(jsr.getFallBackType()); - c.setName(jsr.getName()); - c.setType(jsr.getType()); - c.setValue(jsr.getValue()); - c.setRuleId(rule.getId()); - return c; - } - catch (Exception e) - { - SerializerException.CREATE_OBJECT_FAILED - .create("org.apache.jetspeed.profiler.rules.RuleCriterion",e.getLocalizedMessage()); - return null; - } - } - - /** - * recreate a profiling rule object from the deserialized wrapper and store it - * @param profiler established profile manager - * @param jsp deserialized object - * @ - * @throws SerializerException, ClassNotFoundException, ProfilerException + protected RuleCriterion recreateRuleCriterion(Profiler profiler, + JSRuleCriterion jsr, ProfilingRule rule) + throws SerializerException, ClassNotFoundException + + { + try + { + + RuleCriterion c = profiler.createRuleCriterion(); + if (c == null) + throw new SerializerException( + SerializerException.CREATE_OBJECT_FAILED + .create( + "org.apache.jetspeed.profiler.rules.RuleCriterion", + "returned null")); + c.setFallbackOrder(jsr.getFallBackOrder()); + c.setFallbackType(jsr.getFallBackType()); + c.setName(jsr.getName()); + c.setType(jsr.getType()); + c.setValue(jsr.getValue()); + c.setRuleId(rule.getId()); + return c; + } + catch (Exception e) + { + SerializerException.CREATE_OBJECT_FAILED.create( + "org.apache.jetspeed.profiler.rules.RuleCriterion", e + .getLocalizedMessage()); + return null; + } + } + + /** + * recreate a profiling rule object from the deserialized wrapper and store + * it + * + * @param profiler + * established profile manager + * @param jsp + * deserialized object @ + * @throws SerializerException, + * ClassNotFoundException, ProfilerException */ - protected ProfilingRule recreateRule(Profiler profiler, ProfilingRule existingRule, JSProfilingRule jsp) throws SerializerException, ClassNotFoundException, ProfilerException - { - ProfilingRule rule = null; - boolean existing = false; - - if (existingRule == null) - { - rule = profiler.getRule(jsp.getId()); - if (jsp.isStandardRule()) - rule = profiler.createProfilingRule(true); - else - rule = profiler.createProfilingRule(false); - rule.setId(jsp.getId()); - } - else - { - rule = existingRule; - existing = true; - } - - rule.setTitle(jsp.getDescription()); - - JSRuleCriterions col = jsp.getCriterions(); - - Iterator _it = col.iterator(); - while (_it.hasNext()) - { - RuleCriterion c = recreateRuleCriterion(profiler, (JSRuleCriterion) _it.next(),rule); - if (c != null) - { - Collection cHelp = rule.getRuleCriteria(); - if ((existing) && (cHelp.contains(c))) - cHelp.remove(c); //remove existing duplicate - cHelp.add(c); // add the current version back in - } - } - return rule; + protected ProfilingRule recreateRule(Profiler profiler, + ProfilingRule existingRule, JSProfilingRule jsp) + throws SerializerException, ClassNotFoundException, + ProfilerException + { + ProfilingRule rule = null; + boolean existing = false; - } - - - - private void recreateProfilingRules () throws SerializerException - { - logMe("recreateProfilingRules - processing"); - Profiler pm = (Profiler) getCM() - .getComponent("org.apache.jetspeed.profiler.Profiler"); - if (pm == null) - throw new SerializerException( - SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST - .create("org.apache.jetspeed.profiler.Profiler")); - JSProfilingRules rules = ((JSSeedData)getSnapshot()).getRules(); - if ((rules != null) && (rules.size() > 0)) - { - Iterator _it = rules.iterator(); - while (_it.hasNext()) - { - JSProfilingRule _c = (JSProfilingRule)_it.next(); + if (existingRule == null) + { + rule = profiler.getRule(jsp.getId()); + if (jsp.isStandardRule()) + rule = profiler.createProfilingRule(true); + else + rule = profiler.createProfilingRule(false); + rule.setId(jsp.getId()); + } + else + { + rule = existingRule; + existing = true; + } - try - { - ProfilingRule rule = null; - - rule = pm.getRule(_c.getId()); - if ((rule == null) || (this.getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING))) - { - rule = recreateRule(pm,rule, _c); - pm.storeProfilingRule(rule); - } - } - catch (Exception e) - { - throw new SerializerException( - SerializerException.CREATE_OBJECT_FAILED - .create("org.apache.jetspeed.capabilities.Capabilities",e.getLocalizedMessage())); - } - } - /** reset the default profiling rule */ - String defaultRuleID = ((JSSeedData)getSnapshot()).getDefaultRule(); - if (defaultRuleID != null) - { - ProfilingRule defaultRule = pm.getRule(defaultRuleID); - if (defaultRule != null) - pm.setDefaultRule(defaultRuleID); - } - } - else - logMe("NO PROFILING RULES?????"); - logMe("recreateProfilingRules - done"); - } + rule.setTitle(jsp.getDescription()); + JSRuleCriterions col = jsp.getCriterions(); + Iterator _it = col.iterator(); + while (_it.hasNext()) + { + RuleCriterion c = recreateRuleCriterion(profiler, + (JSRuleCriterion) _it.next(), rule); + if (c != null) + { + Collection cHelp = rule.getRuleCriteria(); + if ((existing) && (cHelp.contains(c))) cHelp.remove(c); // remove + // existing + // duplicate + cHelp.add(c); // add the current version back in + } + } + return rule; + } + + private void recreateProfilingRules() throws SerializerException + { + logMe("recreateProfilingRules - processing"); + Profiler pm = (Profiler) getCM().getComponent( + "org.apache.jetspeed.profiler.Profiler"); + if (pm == null) + throw new SerializerException( + SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST + .create("org.apache.jetspeed.profiler.Profiler")); + JSProfilingRules rules = ((JSSeedData) getSnapshot()).getRules(); + if ((rules != null) && (rules.size() > 0)) + { + Iterator _it = rules.iterator(); + while (_it.hasNext()) + { + JSProfilingRule _c = (JSProfilingRule) _it.next(); + + try + { + ProfilingRule rule = null; + + rule = pm.getRule(_c.getId()); + if ((rule == null) + || (this + .getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING))) + { + rule = recreateRule(pm, rule, _c); + pm.storeProfilingRule(rule); + } + } + catch (Exception e) + { + throw new SerializerException( + SerializerException.CREATE_OBJECT_FAILED + .create( + "org.apache.jetspeed.capabilities.Capabilities", + e.getLocalizedMessage())); + } + } + /** reset the default profiling rule */ + String defaultRuleID = ((JSSeedData) getSnapshot()) + .getDefaultRule(); + if (defaultRuleID != null) + { + ProfilingRule defaultRule = pm.getRule(defaultRuleID); + if (defaultRule != null) pm.setDefaultRule(defaultRuleID); + } + } + else + logMe("NO PROFILING RULES?????"); + logMe("recreateProfilingRules - done"); + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerSecondaryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerSecondaryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/JetspeedSerializerSecondaryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -59,587 +59,594 @@ * @version $Id: $ */ public class JetspeedSerializerSecondaryImpl extends JetspeedSerializerBase - implements - JetspeedSerializer + implements JetspeedSerializer { - boolean overwrite = true; - int refCouter = 0; + boolean overwrite = true; - private PortletEntityAccessComponent entityAccess = null; + int refCouter = 0; - private PortletRegistry registry; + private PortletEntityAccessComponent entityAccess = null; - private PreferencesProvider prefProvider; + private PortletRegistry registry; - protected Class getSerializerDataClass() - { - return JSSecondaryData.class; - } + private PreferencesProvider prefProvider; - protected String getSerializerDataTag() - { - return TAG_SECONDARYSNAPSHOT; - } + protected Class getSerializerDataClass() + { + return JSSecondaryData.class; + } - public JetspeedSerializerSecondaryImpl() - { - super(); - } + protected String getSerializerDataTag() + { + return TAG_SECONDARYSNAPSHOT; + } - /** - * hand over existing component manager - * - * @param cm - */ - public JetspeedSerializerSecondaryImpl(ComponentManager cm) - { - super(cm); - } + public JetspeedSerializerSecondaryImpl() + { + super(); + } - /** - * This constructor takes the application root, the search path for the boot - * component configuration files and the search path for the application - * component configuration files. - * <p> - * For example: new JetspeedSerializerImpl("./", "assembly/boot/*.xml", - * "assembly/*.xml") will establish the current directory as the root, - * process all xml files in the assembly/boot directory before processing - * all xml files in the assembly directory itself. - * - * @param appRoot - * working directory - * @param bootConfig - * boot (primary) file or files (wildcards are allowed) - * @param appConfig - * application (secondary) file or files (wildcards are allowed) - */ - public JetspeedSerializerSecondaryImpl(String appRoot, String[] bootConfig, - String[] appConfig) throws SerializerException - { - super(appRoot, bootConfig, appConfig); - } + /** + * hand over existing component manager + * + * @param cm + */ + public JetspeedSerializerSecondaryImpl(ComponentManager cm) + { + super(cm); + } - /** - * reset instruction flags to default settings (all true) - * - */ - protected void resetSettings() - { - setSetting(JetspeedSerializer.KEY_PROCESS_USERS, false); - setSetting(JetspeedSerializer.KEY_PROCESS_CAPABILITIES, false); - setSetting(JetspeedSerializer.KEY_PROCESS_PROFILER, false); + /** + * This constructor takes the application root, the search path for the boot + * component configuration files and the search path for the application + * component configuration files. + * <p> + * For example: new JetspeedSerializerImpl("./", "assembly/boot/*.xml", + * "assembly/*.xml") will establish the current directory as the root, + * process all xml files in the assembly/boot directory before processing + * all xml files in the assembly directory itself. + * + * @param appRoot + * working directory + * @param bootConfig + * boot (primary) file or files (wildcards are allowed) + * @param appConfig + * application (secondary) file or files (wildcards are allowed) + */ + public JetspeedSerializerSecondaryImpl(String appRoot, String[] bootConfig, + String[] appConfig) throws SerializerException + { + super(appRoot, bootConfig, appConfig); + } + + /** + * reset instruction flags to default settings (all true) + * + */ + protected void resetSettings() + { + setSetting(JetspeedSerializer.KEY_PROCESS_USERS, false); + setSetting(JetspeedSerializer.KEY_PROCESS_CAPABILITIES, false); + setSetting(JetspeedSerializer.KEY_PROCESS_PROFILER, false); setSetting(JetspeedSerializer.KEY_PROCESS_PERMISSIONS, false); setSetting(JetspeedSerializer.KEY_PROCESS_USER_PREFERENCES, false); - setSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING, true); - setSetting(JetspeedSerializer.KEY_BACKUP_BEFORE_PROCESS, true); - } + setSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING, true); + setSetting(JetspeedSerializer.KEY_BACKUP_BEFORE_PROCESS, true); + } - /** - * On import, get the basic SnapShot data - * - */ - protected void getSnapshotData() - { - logMe("date created : " - + ((JSSecondaryData) getSnapshot()).getDateCreated()); - logMe("software Version : " - + ((JSSecondaryData) getSnapshot()).getSavedVersion()); - logMe("software SUbVersion : " - + ((JSSecondaryData) getSnapshot()).getSavedSubversion()); - } + /** + * On import, get the basic SnapShot data + * + */ + protected void getSnapshotData() + { + logMe("date created : " + + ((JSSecondaryData) getSnapshot()).getDateCreated()); + logMe("software Version : " + + ((JSSecondaryData) getSnapshot()).getSavedVersion()); + logMe("software SUbVersion : " + + ((JSSecondaryData) getSnapshot()).getSavedSubversion()); + } - /** - * On export, set the basic SnapShot data - * - */ - protected void setSnapshotData() - { - super.setSnapshotData(); - } + /** + * On export, set the basic SnapShot data + * + */ + protected void setSnapshotData() + { + super.setSnapshotData(); + } - private JSPortlet exportPD(PortletDefinition pd) throws SerializerException - { + private JSPortlet exportPD(PortletDefinition pd) throws SerializerException + { - try - { - Collection col = entityAccess.getPortletEntities(pd); - if ((col == null) || (col.size() == 0)) - return null; - JSPortlet portlet = new JSPortlet(); - portlet.setName(pd.getName()); - Iterator list = null; - try - { - list = col.iterator(); - } catch (Exception e) - { - throw new SerializerException( - SerializerException.GET_EXISTING_OBJECTS - .create(new String[] - {"entityAccess", e.getMessage()})); - } - JSEntities entities = new JSEntities(); + try + { + Collection col = entityAccess.getPortletEntities(pd); + if ((col == null) || (col.size() == 0)) return null; + JSPortlet portlet = new JSPortlet(); + portlet.setName(pd.getName()); + Iterator list = null; + try + { + list = col.iterator(); + } + catch (Exception e) + { + throw new SerializerException( + SerializerException.GET_EXISTING_OBJECTS + .create(new String[] + {"entityAccess", e.getMessage()})); + } + JSEntities entities = new JSEntities(); - while (list.hasNext()) - { - MutablePortletEntity entity = (MutablePortletEntity) list - .next(); - JSEntity jsEntity = exportEntityPref(entity); - if (jsEntity != null) - entities.add(jsEntity); + while (list.hasNext()) + { + MutablePortletEntity entity = (MutablePortletEntity) list + .next(); + JSEntity jsEntity = exportEntityPref(entity); + if (jsEntity != null) entities.add(jsEntity); - } - System.out.println("-----processedAnyEntities for PD=" - + pd.getName()); - portlet.setEntities(entities); - return portlet; + } + System.out.println("-----processedAnyEntities for PD=" + + pd.getName()); + portlet.setEntities(entities); + return portlet; - } catch (Exception e) - { - throw new SerializerException( - SerializerException.CREATE_SERIALIZED_OBJECT_FAILED - .create(new String[] - {"Entity", e.getMessage()})); - } - } + } + catch (Exception e) + { + throw new SerializerException( + SerializerException.CREATE_SERIALIZED_OBJECT_FAILED + .create(new String[] + {"Entity", e.getMessage()})); + } + } - JSEntity exportEntityPref(MutablePortletEntity entity) - { - JSEntity jsEntity = new JSEntity(); - jsEntity.setId(entity.getId().toString()); - String rootForEntity = MutablePortletEntity.PORTLET_ENTITY_ROOT + "/" - + entity.getId(); - try - { - if (!(Preferences.userRoot().nodeExists(rootForEntity))) - { - // System.out.println("No preferences exist for entity "+ - // entity.getId()); - return jsEntity; - } + JSEntity exportEntityPref(MutablePortletEntity entity) + { + JSEntity jsEntity = new JSEntity(); + jsEntity.setId(entity.getId().toString()); + String rootForEntity = MutablePortletEntity.PORTLET_ENTITY_ROOT + "/" + + entity.getId(); + try + { + if (!(Preferences.userRoot().nodeExists(rootForEntity))) + { + // System.out.println("No preferences exist for entity "+ + // entity.getId()); + return jsEntity; + } - Preferences prefNode = Preferences.userRoot().node(rootForEntity); - String[] children = prefNode.childrenNames(); - if ((children != null) && (children.length > 0)) - { - JSEntityPreferences permissions = new JSEntityPreferences(); + Preferences prefNode = Preferences.userRoot().node(rootForEntity); + String[] children = prefNode.childrenNames(); + if ((children != null) && (children.length > 0)) + { + JSEntityPreferences permissions = new JSEntityPreferences(); - for (int i = 0; i < children.length; i++) - { - JSEntityPreference permission = processPreferenceNode( - entity, children[i]); - if (permission != null) - permissions.add(permission); - } - System.out.println("processed preferences for entity=" - + entity.getId()); - jsEntity.setEntityPreferences(permissions); - return jsEntity; - // processPreferenceNode(entity,prefNode,null); - } - return jsEntity; - } catch (Exception e) - { - e.printStackTrace(); - return null; - } + for (int i = 0; i < children.length; i++) + { + JSEntityPreference permission = processPreferenceNode( + entity, children[i]); + if (permission != null) permissions.add(permission); + } + System.out.println("processed preferences for entity=" + + entity.getId()); + jsEntity.setEntityPreferences(permissions); + return jsEntity; + // processPreferenceNode(entity,prefNode,null); + } + return jsEntity; + } + catch (Exception e) + { + e.printStackTrace(); + return null; + } - } + } - JSEntityPreference processPreferenceNode(MutablePortletEntity entity, - String child) - { - String prefNodePath = MutablePortletEntity.PORTLET_ENTITY_ROOT + "/" - + entity.getId() + "/" + child + "/" - + PrefsPreference.PORTLET_PREFERENCES_ROOT; - Preferences prefNode = Preferences.userRoot().node(prefNodePath); + JSEntityPreference processPreferenceNode(MutablePortletEntity entity, + String child) + { + String prefNodePath = MutablePortletEntity.PORTLET_ENTITY_ROOT + "/" + + entity.getId() + "/" + child + "/" + + PrefsPreference.PORTLET_PREFERENCES_ROOT; + Preferences prefNode = Preferences.userRoot().node(prefNodePath); - if (prefNode == null) - return null; - JSEntityPreference permission = new JSEntityPreference(); - permission.setName(child); + if (prefNode == null) return null; + JSEntityPreference permission = new JSEntityPreference(); + permission.setName(child); - try - { - PrefsPreferenceSetImpl preferenceSet = new PrefsPreferenceSetImpl( - prefNode); - if (preferenceSet.size() == 0) - return null; - Iterator it = preferenceSet.iterator(); - JSNVPElements v = new JSNVPElements(); + try + { + PrefsPreferenceSetImpl preferenceSet = new PrefsPreferenceSetImpl( + prefNode); + if (preferenceSet.size() == 0) return null; + Iterator it = preferenceSet.iterator(); + JSNVPElements v = new JSNVPElements(); - while (it.hasNext()) - { - Preference pref = (Preference) it.next(); - String name = pref.getName(); - Iterator ii = pref.getValues(); - while (ii.hasNext()) - { - Object o = ii.next(); - v.add(name, o.toString()); - } - } - if (v.size() > 0) - { - permission.setPreferences(v); - return permission; - } - return null; - } catch (Exception e) - { - e.printStackTrace(); - return null; + while (it.hasNext()) + { + Preference pref = (Preference) it.next(); + String name = pref.getName(); + Iterator ii = pref.getValues(); + while (ii.hasNext()) + { + Object o = ii.next(); + v.add(name, o.toString()); + } + } + if (v.size() > 0) + { + permission.setPreferences(v); + return permission; + } + return null; + } + catch (Exception e) + { + e.printStackTrace(); + return null; - } + } - } + } - private JSApplication exportPA(MutablePortletApplication pa) - throws SerializerException - { + private JSApplication exportPA(MutablePortletApplication pa) + throws SerializerException + { - JSApplication app = new JSApplication(); - System.out.println("--processed PA " + pa.getName() + " with id=" - + pa.getId()); - app.setID(pa.getId().toString()); - app.setName(pa.getName()); - /** - * while more PAs for each portletDef - * list:entityMan:getPortletEntity(pd) - */ - PortletDefinitionList portletList = pa.getPortletDefinitionList(); // .get(JetspeedObjectID.createFromString(TEST_PORTLET)); - Iterator pi = portletList.iterator(); - PortletDefinition pd = null; + JSApplication app = new JSApplication(); + System.out.println("--processed PA " + pa.getName() + " with id=" + + pa.getId()); + app.setID(pa.getId().toString()); + app.setName(pa.getName()); + /** + * while more PAs for each portletDef + * list:entityMan:getPortletEntity(pd) + */ + PortletDefinitionList portletList = pa.getPortletDefinitionList(); // .get(JetspeedObjectID.createFromString(TEST_PORTLET)); + Iterator pi = portletList.iterator(); + PortletDefinition pd = null; - JSPortlets portlets = new JSPortlets(); - while (pi.hasNext()) - { - try - { - pd = (PortletDefinition) pi.next(); - JSPortlet p = exportPD(pd); - if (p != null) - { - System.out.println("--processed PA " + pa.getName() - + " with pd=" + pd.getName()); - portlets.add(p); - } else - System.out.println("--processed PA " + pa.getName() - + " with NULL pd=" + pd.getName()); + JSPortlets portlets = new JSPortlets(); + while (pi.hasNext()) + { + try + { + pd = (PortletDefinition) pi.next(); + JSPortlet p = exportPD(pd); + if (p != null) + { + System.out.println("--processed PA " + pa.getName() + + " with pd=" + pd.getName()); + portlets.add(p); + } + else + System.out.println("--processed PA " + pa.getName() + + " with NULL pd=" + pd.getName()); - } catch (Exception e) - { - throw new SerializerException( - SerializerException.CREATE_SERIALIZED_OBJECT_FAILED - .create(new String[] - {"PortletDefinition", e.getMessage()})); - } - } - app.setPortlets(portlets); - return app; - } + } + catch (Exception e) + { + throw new SerializerException( + SerializerException.CREATE_SERIALIZED_OBJECT_FAILED + .create(new String[] + {"PortletDefinition", e.getMessage()})); + } + } + app.setPortlets(portlets); + return app; + } - private JSApplications exportEntities() throws SerializerException - { - registry = (PortletRegistry) getCM() - .getComponent( - "org.apache.jetspeed.components.portletregistry.PortletRegistry"); - if (registry == null) - throw new SerializerException( - SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST - .create("org.apache.jetspeed.components.portletregistry.PortletRegistry")); - Object o = getCM() - .getComponent( - "org.apache.jetspeed.components.portletentity.PortletEntityAccessComponent"); - this.entityAccess = (PortletEntityAccessComponent) o; - if (entityAccess == null) - throw new SerializerException( - SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST - .create("org.apache.jetspeed.components.portletentity.PortletEntityAccessComponent")); + private JSApplications exportEntities() throws SerializerException + { + registry = (PortletRegistry) getCM() + .getComponent( + "org.apache.jetspeed.components.portletregistry.PortletRegistry"); + if (registry == null) + throw new SerializerException( + SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST + .create("org.apache.jetspeed.components.portletregistry.PortletRegistry")); + Object o = getCM() + .getComponent( + "org.apache.jetspeed.components.portletentity.PortletEntityAccessComponent"); + this.entityAccess = (PortletEntityAccessComponent) o; + if (entityAccess == null) + throw new SerializerException( + SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST + .create("org.apache.jetspeed.components.portletentity.PortletEntityAccessComponent")); - JSApplications applications = new JSApplications(); + JSApplications applications = new JSApplications(); - Collection col = registry.getPortletApplications(); - if ((col == null) || (col.size() == 0)) - return applications; - Iterator list = null; - try - { - list = col.iterator(); - } catch (Exception e) - { - throw new SerializerException( - SerializerException.GET_EXISTING_OBJECTS - .create(new String[] - {"registry", e.getMessage()})); - } - while (list.hasNext()) - { - try - { - MutablePortletApplication pa = (MutablePortletApplication) list - .next(); - // PortletApplicationDefinition pa = - // (PortletApplicationDefinition)list.next(); - applications.add(exportPA(pa)); - } catch (Exception e) - { - throw new SerializerException( - SerializerException.CREATE_SERIALIZED_OBJECT_FAILED - .create(new String[] - {"PortletApplicationDefinition", e.getMessage()})); - } - } + Collection col = registry.getPortletApplications(); + if ((col == null) || (col.size() == 0)) return applications; + Iterator list = null; + try + { + list = col.iterator(); + } + catch (Exception e) + { + throw new SerializerException( + SerializerException.GET_EXISTING_OBJECTS + .create(new String[] + {"registry", e.getMessage()})); + } + while (list.hasNext()) + { + try + { + MutablePortletApplication pa = (MutablePortletApplication) list + .next(); + // PortletApplicationDefinition pa = + // (PortletApplicationDefinition)list.next(); + applications.add(exportPA(pa)); + } + catch (Exception e) + { + throw new SerializerException( + SerializerException.CREATE_SERIALIZED_OBJECT_FAILED + .create(new String[] + {"PortletApplicationDefinition", e.getMessage()})); + } + } - return applications; - } + return applications; + } - /** - * The workhorse for importing data - * - * @param binding - * established XML binding - * @return - * @throws SerializerException - */ - protected void processImport() throws SerializerException - { - this.logMe("*********reinstalling data*********"); + /** + * The workhorse for importing data + * + * @param binding + * established XML binding + * @return + * @throws SerializerException + */ + protected void processImport() throws SerializerException + { + this.logMe("*********reinstalling data*********"); - logMe("creating entities"); - importEntities(); - } + logMe("creating entities"); + importEntities(); + } - /** - * The workhorse for exporting data - * - * @param binding - * established XML binding - * @return - * @throws SerializerException - */ - protected void processExport(String name, XMLBinding binding) - throws SerializerException - { - this.logMe("*********collecting data*********"); - /** first create the snapshot file */ + /** + * The workhorse for exporting data + * + * @param binding + * established XML binding + * @return + * @throws SerializerException + */ + protected void processExport(String name, XMLBinding binding) + throws SerializerException + { + this.logMe("*********collecting data*********"); + /** first create the snapshot file */ - this.setSnapshot(new JSSecondaryData(name)); + this.setSnapshot(new JSSecondaryData(name)); - setSnapshotData(); + setSnapshotData(); - JSApplications apps = exportEntities(); - ((JSSecondaryData) this.getSnapshot()).setApplications(apps); - /** - * - * if (this.getSetting(JetspeedSerializer.KEY_PROCESS_ENTITIES)) { - * logMe("collecting entities"); exportEntities(); } else - * logMe("entities skipped"); - * - * if (this.getSetting(JetspeedSerializer.KEY_PROCESS_PREFERENCES)) { - * logMe("collecting preferences"); exportPreferences(); } else - * logMe("preferences skipped"); - */ + JSApplications apps = exportEntities(); + ((JSSecondaryData) this.getSnapshot()).setApplications(apps); + /** + * + * if (this.getSetting(JetspeedSerializer.KEY_PROCESS_ENTITIES)) { + * logMe("collecting entities"); exportEntities(); } else + * logMe("entities skipped"); + * + * if (this.getSetting(JetspeedSerializer.KEY_PROCESS_PREFERENCES)) { + * logMe("collecting preferences"); exportPreferences(); } else + * logMe("preferences skipped"); + */ - } + } - /** - * Setup the binding for the different classes, mapping each extracted class - * to a unique tag name in the XML - * - * @param binding - */ - protected void setupAliases(XMLBinding binding) - { - binding.setAlias(JSApplication.class, "PortletApplication"); - binding.setAlias(JSApplications.class, "PortletApplications"); - binding.setAlias(JSPortlet.class, "Portlet"); - binding.setAlias(JSPortlets.class, "Portlets"); - binding.setAlias(JSEntity.class, "Entity"); - binding.setAlias(JSEntities.class, "Entities"); - binding.setAlias(JSEntityPreference.class, "Principal"); - binding.setAlias(JSEntityPreferences.class, "Settings"); - binding.setAlias(JSSecondaryData.class, "RegistryData"); - binding.setAlias(JSNVPElements.class, "preferences"); + /** + * Setup the binding for the different classes, mapping each extracted class + * to a unique tag name in the XML + * + * @param binding + */ + protected void setupAliases(XMLBinding binding) + { + binding.setAlias(JSApplication.class, "PortletApplication"); + binding.setAlias(JSApplications.class, "PortletApplications"); + binding.setAlias(JSPortlet.class, "Portlet"); + binding.setAlias(JSPortlets.class, "Portlets"); + binding.setAlias(JSEntity.class, "Entity"); + binding.setAlias(JSEntities.class, "Entities"); + binding.setAlias(JSEntityPreference.class, "Principal"); + binding.setAlias(JSEntityPreferences.class, "Settings"); + binding.setAlias(JSSecondaryData.class, "RegistryData"); + binding.setAlias(JSNVPElements.class, "preferences"); - binding.setAlias(String.class, "String"); - binding.setAlias(Integer.class, "int"); - binding.setClassAttribute(null); + binding.setAlias(String.class, "String"); + binding.setAlias(Integer.class, "int"); + binding.setClassAttribute(null); - } + } - private void importEntities() throws SerializerException - { - overwrite = getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING); + private void importEntities() throws SerializerException + { + overwrite = getSetting(JetspeedSerializer.KEY_OVERWRITE_EXISTING); - registry = (PortletRegistry) getCM() - .getComponent( - "org.apache.jetspeed.components.portletregistry.PortletRegistry"); - if (registry == null) - throw new SerializerException( - SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST - .create("org.apache.jetspeed.components.portletregistry.PortletRegistry")); - Object o = getCM() - .getComponent( - "org.apache.jetspeed.components.portletentity.PortletEntityAccessComponent"); - this.entityAccess = (PortletEntityAccessComponent) o; - if (entityAccess == null) - throw new SerializerException( - SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST - .create("org.apache.jetspeed.components.portletentity.PortletEntityAccessComponent")); - - JSApplications applications = ((JSSecondaryData)this.getSnapshot()).getApplications(); + registry = (PortletRegistry) getCM() + .getComponent( + "org.apache.jetspeed.components.portletregistry.PortletRegistry"); + if (registry == null) + throw new SerializerException( + SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST + .create("org.apache.jetspeed.components.portletregistry.PortletRegistry")); + Object o = getCM() + .getComponent( + "org.apache.jetspeed.components.portletentity.PortletEntityAccessComponent"); + this.entityAccess = (PortletEntityAccessComponent) o; + if (entityAccess == null) + throw new SerializerException( + SerializerException.COMPONENTMANAGER_DOES_NOT_EXIST + .create("org.apache.jetspeed.components.portletentity.PortletEntityAccessComponent")); - if (applications == null) - { - System.out.println("NO DATA!!!!!!"); - return; - } - Iterator it = applications.iterator(); - while (it.hasNext()) - { - JSApplication app = (JSApplication)it.next(); - MutablePortletApplication portletApp = registry.getPortletApplication(app.getName()); - if (portletApp != null) - { - importPA(app,portletApp); - } - } - } + JSApplications applications = ((JSSecondaryData) this.getSnapshot()) + .getApplications(); - void importPA(JSApplication app, MutablePortletApplication pa) - throws SerializerException - { + if (applications == null) + { + System.out.println("NO DATA!!!!!!"); + return; + } + Iterator it = applications.iterator(); + while (it.hasNext()) + { + JSApplication app = (JSApplication) it.next(); + MutablePortletApplication portletApp = registry + .getPortletApplication(app.getName()); + if (portletApp != null) + { + importPA(app, portletApp); + } + } + } - - System.out.println("--processed PA " + pa.getName() + " with id=" - + pa.getId()); - /** - * while more PAs for each portletDef - * list:entityMan:getPortletEntity(pd) - */ - - Iterator pi = app.getPortlets().iterator(); - while (pi.hasNext()) - { - JSPortlet portlet = (JSPortlet)pi.next(); - PortletDefinition pd = pa.getPortletDefinitionByName(portlet.getName()); - if (pd != null) - { - importPD(portlet,pd); - } - } - } - - private void importPD(JSPortlet portlet, PortletDefinition pd) throws SerializerException - { + void importPA(JSApplication app, MutablePortletApplication pa) + throws SerializerException + { - JSEntities entities = portlet.getEntities(); - Iterator it = entities.iterator(); - while (it.hasNext()) - { - JSEntity entity = (JSEntity)it.next(); - MutablePortletEntity portletEntity = entityAccess.getPortletEntity(entity.getId()); - if (portletEntity == null) - { - portletEntity = entityAccess.newPortletEntityInstance(pd, entity.getId()); - try - { - entityAccess.storePortletEntity(portletEntity); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - // check preferences - - importEntityPref(entity , portletEntity); - } - } + System.out.println("--processed PA " + pa.getName() + " with id=" + + pa.getId()); + /** + * while more PAs for each portletDef + * list:entityMan:getPortletEntity(pd) + */ - private void importEntityPref(JSEntity entity , MutablePortletEntity portletEntity) - { + Iterator pi = app.getPortlets().iterator(); + while (pi.hasNext()) + { + JSPortlet portlet = (JSPortlet) pi.next(); + PortletDefinition pd = pa.getPortletDefinitionByName(portlet + .getName()); + if (pd != null) + { + importPD(portlet, pd); + } + } + } - // do I carry any preferences? - JSEntityPreferences preferences = entity.getEntityPreferences(); - if ((preferences == null) || (preferences.size() == 0)) - return; - - - //since I do have preferences let us make sure we have a root node - - String rootForEntity = MutablePortletEntity.PORTLET_ENTITY_ROOT + "/" - + portletEntity.getId(); - try - { - Preferences.userRoot().node(rootForEntity); // will create it if it doesn't exist - - - Iterator it = preferences.iterator(); - while (it.hasNext()) - { - JSEntityPreference preference = (JSEntityPreference)it.next(); - - // do we have preferences for this one? - importPreferenceNode(preference,portletEntity); - } - - - } catch (Exception e) - { - e.printStackTrace(); - return; - } + private void importPD(JSPortlet portlet, PortletDefinition pd) + throws SerializerException + { - } + JSEntities entities = portlet.getEntities(); + Iterator it = entities.iterator(); + while (it.hasNext()) + { + JSEntity entity = (JSEntity) it.next(); + MutablePortletEntity portletEntity = entityAccess + .getPortletEntity(entity.getId()); + if (portletEntity == null) + { + portletEntity = entityAccess.newPortletEntityInstance(pd, + entity.getId()); + try + { + entityAccess.storePortletEntity(portletEntity); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + // check preferences - private void importPreferenceNode(JSEntityPreference preference, MutablePortletEntity entity) - { + importEntityPref(entity, portletEntity); + } + } - String child = preference.getName(); - - String prefNodePath = MutablePortletEntity.PORTLET_ENTITY_ROOT + "/" - + entity.getId() + "/" + child + "/" - + PrefsPreference.PORTLET_PREFERENCES_ROOT; - Preferences prefNode = Preferences.userRoot().node(prefNodePath); + private void importEntityPref(JSEntity entity, + MutablePortletEntity portletEntity) + { - if (prefNode == null) - return ; + // do I carry any preferences? + JSEntityPreferences preferences = entity.getEntityPreferences(); + if ((preferences == null) || (preferences.size() == 0)) return; - JSNVPElements prefList = preference.getPreferences(); - try - { - PrefsPreferenceSetImpl preferenceSet = new PrefsPreferenceSetImpl( - prefNode); - - Iterator it = prefList.getMyMap().keySet().iterator(); - - while (it.hasNext()) - { - String key = (String)it.next(); - String value = (String)prefList.getMyMap().get(key); - Preference p = preferenceSet.get(key); - if ((p == null) || (overwrite)) - { - - Vector v = new Vector(); - v.add(value); - preferenceSet.add(key, v); -System.out.println("Entity " + entity.getId() + " updated with preference " + key + "=" + value); - } - } - preferenceSet.flush(); - return; - } catch (Exception e) - { - e.printStackTrace(); - return; + // since I do have preferences let us make sure we have a root node - } + String rootForEntity = MutablePortletEntity.PORTLET_ENTITY_ROOT + "/" + + portletEntity.getId(); + try + { + Preferences.userRoot().node(rootForEntity); // will create it if it + // doesn't exist - } - - + Iterator it = preferences.iterator(); + while (it.hasNext()) + { + JSEntityPreference preference = (JSEntityPreference) it.next(); + + // do we have preferences for this one? + importPreferenceNode(preference, portletEntity); + } + + } + catch (Exception e) + { + e.printStackTrace(); + return; + } + + } + + private void importPreferenceNode(JSEntityPreference preference, + MutablePortletEntity entity) + { + + String child = preference.getName(); + + String prefNodePath = MutablePortletEntity.PORTLET_ENTITY_ROOT + "/" + + entity.getId() + "/" + child + "/" + + PrefsPreference.PORTLET_PREFERENCES_ROOT; + Preferences prefNode = Preferences.userRoot().node(prefNodePath); + + if (prefNode == null) return; + + JSNVPElements prefList = preference.getPreferences(); + try + { + PrefsPreferenceSetImpl preferenceSet = new PrefsPreferenceSetImpl( + prefNode); + + Iterator it = prefList.getMyMap().keySet().iterator(); + + while (it.hasNext()) + { + String key = (String) it.next(); + String value = (String) prefList.getMyMap().get(key); + Preference p = preferenceSet.get(key); + if ((p == null) || (overwrite)) + { + + Vector v = new Vector(); + v.add(value); + preferenceSet.add(key, v); + System.out.println("Entity " + entity.getId() + + " updated with preference " + key + "=" + value); + } + } + preferenceSet.flush(); + return; + } + catch (Exception e) + { + e.printStackTrace(); + return; + + } + + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSApplication.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSApplication.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSApplication.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,22 +34,17 @@ private String id; - - private JSPortlets portlets = null; - public JSApplication() { } - public String getID() { return id; } - public void setID(String id) { this.id = id; @@ -60,14 +55,11 @@ this.name = name; } - public String getName() { return name; } - - /*************************************************************************** * SERIALIZER */ @@ -82,12 +74,13 @@ JSApplication g = (JSApplication) o; String s = g.getName(); if ((s != null) && (s.length() > 0)) - xml.setAttribute("name", s); - - xml.add(g.id, "ID",String.class); + xml.setAttribute("name", s); + + xml.add(g.id, "ID", String.class); xml.add(g.portlets); - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } @@ -98,26 +91,25 @@ try { JSApplication g = (JSApplication) o; - g.name = StringEscapeUtils.unescapeHtml(xml.getAttribute("name", "unknown")); - - - - Object o1 = xml.get("ID",String.class); - if (o1 instanceof String) g.id = StringEscapeUtils.unescapeHtml((String) o1); + g.name = StringEscapeUtils.unescapeHtml(xml.getAttribute( + "name", "unknown")); - while (xml.hasNext()) - { - o1 = xml.getNext(); // mime - - - if (o1 instanceof JSPortlets) - { - g.portlets = (JSPortlets) o1; - } + Object o1 = xml.get("ID", String.class); + if (o1 instanceof String) + g.id = StringEscapeUtils.unescapeHtml((String) o1); + + while (xml.hasNext()) + { + o1 = xml.getNext(); // mime + + if (o1 instanceof JSPortlets) + { + g.portlets = (JSPortlets) o1; + } } - - - } catch (Exception e) + + } + catch (Exception e) { e.printStackTrace(); } @@ -125,18 +117,14 @@ }; + public JSPortlets getPortlets() + { + return portlets; + } - + public void setPortlets(JSPortlets portlets) + { + this.portlets = portlets; + } - - public JSPortlets getPortlets() - { - return portlets; - } - - public void setPortlets(JSPortlets portlets) - { - this.portlets = portlets; - } - } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSApplications.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSApplications.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSApplications.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,11 +18,11 @@ import java.util.ArrayList; - /** * Simple wrapper class for XML serialization + * * @author hajo - * + * */ public class JSApplications extends ArrayList { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSCapabilities.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSCapabilities.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSCapabilities.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,11 +18,11 @@ import java.util.ArrayList; - /** * Jetspeed Serializer - Simple Cpabailities Wrapper * <p> - * Wrapper to process XML representation of a set of capabilities - used only for binding + * Wrapper to process XML representation of a set of capabilities - used only + * for binding * * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> * @version $Id: $ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSCapability.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSCapability.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSCapability.java 2008-05-16 01:54:54 UTC (rev 940) @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.jetspeed.serializer.objects; + /** * Jetspeed Serializer - Capability Wrapper * <p> Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClient.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClient.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClient.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,6 +26,7 @@ import org.apache.commons.lang.StringEscapeUtils; import org.apache.jetspeed.capabilities.Client; + /** * Jetspeed Serializer - Client Wrapper * <p> @@ -36,341 +37,348 @@ */ public class JSClient { - // private int refID; - private String name; + // private int refID; - private int id; + private String name; - private int evalOrder; + private int id; - private String manufacturer; + private int evalOrder; - private String model; + private String manufacturer; - private String preferredMimeTypeID; + private String model; - private String userAgentPattern; + private String preferredMimeTypeID; - private String version; + private String userAgentPattern; - private ArrayList capabilities; + private String version; - private ArrayList mimeTypes; + private ArrayList capabilities; - private JSClientCapabilities capabilitiesString; + private ArrayList mimeTypes; - private JSClientMimeTypes mimeTypesString; + private JSClientCapabilities capabilitiesString; - public JSClient() - { - // refID = id; - } + private JSClientMimeTypes mimeTypesString; - public JSClient(Client c) - { - this.id = c.getClientId(); - this.name = c.getName(); + public JSClient() + { + // refID = id; + } - this.userAgentPattern = c.getUserAgentPattern(); - this.version = c.getVersion(); - this.model = c.getModel(); + public JSClient(Client c) + { + this.id = c.getClientId(); + this.name = c.getName(); - this.evalOrder = c.getEvalOrder(); - this.manufacturer = c.getManufacturer(); + this.userAgentPattern = c.getUserAgentPattern(); + this.version = c.getVersion(); + this.model = c.getModel(); - capabilities = new ArrayList(); - mimeTypes = new ArrayList(); - } + this.evalOrder = c.getEvalOrder(); + this.manufacturer = c.getManufacturer(); - public static final String XML_TAG = "Client".intern(); - - /** - * All local attributes and list-type classes are bound here, - * referenced classes should return their own binding. + capabilities = new ArrayList(); + mimeTypes = new ArrayList(); + } + + public static final String XML_TAG = "Client".intern(); + + /** + * All local attributes and list-type classes are bound here, referenced + * classes should return their own binding. + * * @param binding */ - - public static void setupAliases(XMLBinding binding) -{ + + public static void setupAliases(XMLBinding binding) + { binding.setAlias(JSClient.class, JSClient.XML_TAG); } - - - - /*************************************************************************** - * SERIALIZER - */ - private static final XMLFormat XML = new XMLFormat(JSClient.class) - { - public void write(Object o, OutputElement xml) - throws XMLStreamException - { - try - { - JSClient g = (JSClient) o; - xml.setAttribute("name", g.name); - xml.setAttribute("evalOrder", g.evalOrder); - xml.setAttribute("preferredMimeTypeID", g.preferredMimeTypeID); - xml.add( g.userAgentPattern, "userAgentPattern",String.class); - xml.add(g.version,"version", String.class); - xml.add(g.model, "model", String.class); - xml.add(g.manufacturer, "manufacturer", String.class); + /*************************************************************************** + * SERIALIZER + */ + private static final XMLFormat XML = new XMLFormat(JSClient.class) + { - g.capabilitiesString = new JSClientCapabilities(g.putTokens(g.capabilities)); - g.mimeTypesString = new JSClientMimeTypes(g.putTokens(g.mimeTypes)); - xml.add(g.capabilitiesString); - xml.add(g.mimeTypesString); - // xml.add(g.groupString); + public void write(Object o, OutputElement xml) + throws XMLStreamException + { - } catch (Exception e) - { - e.printStackTrace(); - } - } + try + { + JSClient g = (JSClient) o; + xml.setAttribute("name", g.name); + xml.setAttribute("evalOrder", g.evalOrder); + xml.setAttribute("preferredMimeTypeID", g.preferredMimeTypeID); + xml.add(g.userAgentPattern, "userAgentPattern", String.class); + xml.add(g.version, "version", String.class); + xml.add(g.model, "model", String.class); + xml.add(g.manufacturer, "manufacturer", String.class); - public void read(InputElement xml, Object o) - { - try - { - JSClient g = (JSClient) o; - g.name = StringEscapeUtils.unescapeHtml(xml.getAttribute("name","")); - g.evalOrder = xml.getAttribute("evalOrder",0); - g.preferredMimeTypeID = StringEscapeUtils.unescapeHtml(xml.getAttribute("preferredMimeTypeID","0")); - - g.userAgentPattern = StringEscapeUtils.unescapeHtml((String)xml.get("userAgentPattern",String.class)); - g.version = StringEscapeUtils.unescapeHtml((String)xml.get("version",String.class)); - g.model = StringEscapeUtils.unescapeHtml((String)xml.get("model",String.class)); - g.manufacturer = StringEscapeUtils.unescapeHtml((String)xml.get("manufacturer",String.class)); + g.capabilitiesString = new JSClientCapabilities(g + .putTokens(g.capabilities)); + g.mimeTypesString = new JSClientMimeTypes(g + .putTokens(g.mimeTypes)); + xml.add(g.capabilitiesString); + xml.add(g.mimeTypesString); + // xml.add(g.groupString); + + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + public void read(InputElement xml, Object o) + { + try + { + JSClient g = (JSClient) o; + g.name = StringEscapeUtils.unescapeHtml(xml.getAttribute( + "name", "")); + g.evalOrder = xml.getAttribute("evalOrder", 0); + g.preferredMimeTypeID = StringEscapeUtils.unescapeHtml(xml + .getAttribute("preferredMimeTypeID", "0")); + + g.userAgentPattern = StringEscapeUtils + .unescapeHtml((String) xml.get("userAgentPattern", + String.class)); + g.version = StringEscapeUtils.unescapeHtml((String) xml.get( + "version", String.class)); + g.model = StringEscapeUtils.unescapeHtml((String) xml.get( + "model", String.class)); + g.manufacturer = StringEscapeUtils.unescapeHtml((String) xml + .get("manufacturer", String.class)); g.capabilitiesString = (JSClientCapabilities) xml.getNext(); g.mimeTypesString = (JSClientMimeTypes) xml.getNext(); - } catch (Exception e) - { - e.printStackTrace(); - } - } - }; + } + catch (Exception e) + { + e.printStackTrace(); + } + } + }; - /** - * @return Returns the capabilities. - */ - public List getCapabilities() - { - return capabilities; - } + /** + * @return Returns the capabilities. + */ + public List getCapabilities() + { + return capabilities; + } - /** - * @param capabilities - * The capabilities to set. - */ - public void setCapabilities(ArrayList capabilities) - { - this.capabilities = capabilities; - } + /** + * @param capabilities + * The capabilities to set. + */ + public void setCapabilities(ArrayList capabilities) + { + this.capabilities = capabilities; + } - /** - * @return Returns the evalOrder. - */ - public int getEvalOrder() - { - return evalOrder; - } + /** + * @return Returns the evalOrder. + */ + public int getEvalOrder() + { + return evalOrder; + } - /** - * @param evalOrder - * The evalOrder to set. - */ - public void setEvalOrder(int evalOrder) - { - this.evalOrder = evalOrder; - } + /** + * @param evalOrder + * The evalOrder to set. + */ + public void setEvalOrder(int evalOrder) + { + this.evalOrder = evalOrder; + } - /** - * @return Returns the id. - */ - public int getId() - { - return id; - } + /** + * @return Returns the id. + */ + public int getId() + { + return id; + } - /** - * @param id - * The id to set. - */ - public void setId(int id) - { - this.id = id; - } + /** + * @param id + * The id to set. + */ + public void setId(int id) + { + this.id = id; + } - /** - * @return Returns the manufacturer. - */ - public String getManufacturer() - { - return manufacturer; - } + /** + * @return Returns the manufacturer. + */ + public String getManufacturer() + { + return manufacturer; + } - /** - * @param manufacturer - * The manufacturer to set. - */ - public void setManufacturer(String manufacturer) - { - this.manufacturer = manufacturer; - } + /** + * @param manufacturer + * The manufacturer to set. + */ + public void setManufacturer(String manufacturer) + { + this.manufacturer = manufacturer; + } - /** - * @return Returns the mimeTypes. - */ - public List getMimeTypes() - { - return mimeTypes; - } + /** + * @return Returns the mimeTypes. + */ + public List getMimeTypes() + { + return mimeTypes; + } - /** - * @param mimeTypes - * The mimeTypes to set. - */ - public void setMimeTypes(ArrayList mimeTypes) - { - this.mimeTypes = mimeTypes; - } + /** + * @param mimeTypes + * The mimeTypes to set. + */ + public void setMimeTypes(ArrayList mimeTypes) + { + this.mimeTypes = mimeTypes; + } - /** - * @return Returns the model. - */ - public String getModel() - { - return model; - } + /** + * @return Returns the model. + */ + public String getModel() + { + return model; + } - /** - * @param model - * The model to set. - */ - public void setModel(String model) - { - this.model = model; - } + /** + * @param model + * The model to set. + */ + public void setModel(String model) + { + this.model = model; + } - /** - * @return Returns the name. - */ - public String getName() - { - return name; - } + /** + * @return Returns the name. + */ + public String getName() + { + return name; + } - /** - * @param name - * The name to set. - */ - public void setName(String name) - { - this.name = name; - } + /** + * @param name + * The name to set. + */ + public void setName(String name) + { + this.name = name; + } - /** - * @return Returns the preferredMimeTypeID. - */ - public String getPreferredMimeTypeID() - { - return preferredMimeTypeID; - } + /** + * @return Returns the preferredMimeTypeID. + */ + public String getPreferredMimeTypeID() + { + return preferredMimeTypeID; + } - /** - * @param preferredMimeTypeID - * The preferredMimeTypeID to set. - */ - public void setPreferredMimeTypeID(String preferredMimeTypeID) - { - this.preferredMimeTypeID = preferredMimeTypeID; - } + /** + * @param preferredMimeTypeID + * The preferredMimeTypeID to set. + */ + public void setPreferredMimeTypeID(String preferredMimeTypeID) + { + this.preferredMimeTypeID = preferredMimeTypeID; + } - /** - * @return Returns the userAgentPattern. - */ - public String getUserAgentPattern() - { - return userAgentPattern; - } + /** + * @return Returns the userAgentPattern. + */ + public String getUserAgentPattern() + { + return userAgentPattern; + } - /** - * @param userAgentPattern - * The userAgentPattern to set. - */ - public void setUserAgentPattern(String userAgentPattern) - { - this.userAgentPattern = userAgentPattern; - } + /** + * @param userAgentPattern + * The userAgentPattern to set. + */ + public void setUserAgentPattern(String userAgentPattern) + { + this.userAgentPattern = userAgentPattern; + } - /** - * @return Returns the version. - */ - public String getVersion() - { - return version; - } + /** + * @return Returns the version. + */ + public String getVersion() + { + return version; + } - /** - * @param version - * The version to set. - */ - public void setVersion(String version) - { - this.version = version; - } + /** + * @param version + * The version to set. + */ + public void setVersion(String version) + { + this.version = version; + } - private String append(JSCapability capability) - { - return capability.getName(); - } + private String append(JSCapability capability) + { + return capability.getName(); + } - private String append(JSMimeType mime) - { - return mime.getName(); - } + private String append(JSMimeType mime) + { + return mime.getName(); + } - private String append(Object s) - { - if (s instanceof JSCapability) - return append((JSCapability) s); - if (s instanceof JSMimeType) - return append((JSMimeType) s); + private String append(Object s) + { + if (s instanceof JSCapability) return append((JSCapability) s); + if (s instanceof JSMimeType) return append((JSMimeType) s); - return s.toString(); - } + return s.toString(); + } - private String putTokens(ArrayList _list) - { - if ((_list == null) || (_list.size() == 0)) - return ""; - boolean _start = true; - Iterator _it = _list.iterator(); - StringBuffer _sb = new StringBuffer(); - while (_it.hasNext()) - { - if (!_start) - _sb.append(','); - else - _start = false; + private String putTokens(ArrayList _list) + { + if ((_list == null) || (_list.size() == 0)) return ""; + boolean _start = true; + Iterator _it = _list.iterator(); + StringBuffer _sb = new StringBuffer(); + while (_it.hasNext()) + { + if (!_start) + _sb.append(','); + else + _start = false; - _sb.append(append(_it.next())); - } - return _sb.toString(); - } + _sb.append(append(_it.next())); + } + return _sb.toString(); + } - public JSClientCapabilities getCapabilitiesString() - { - return capabilitiesString; - } + public JSClientCapabilities getCapabilitiesString() + { + return capabilitiesString; + } - public JSClientMimeTypes getMimeTypesString() - { - return mimeTypesString; - } + public JSClientMimeTypes getMimeTypesString() + { + return mimeTypesString; + } - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClientCapabilities.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClientCapabilities.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClientCapabilities.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,12 +16,11 @@ */ package org.apache.jetspeed.serializer.objects; - - /** * Jetspeed Serializer - Simple Client-Capabilities Wrapper * <p> - * Wrapper to process XML representation of a set of client capabilities - used only for binding + * Wrapper to process XML representation of a set of client capabilities - used + * only for binding * * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> * @version $Id: $ @@ -30,13 +29,13 @@ public class JSClientCapabilities extends JSUserRoles { - /** - * - */ - public JSClientCapabilities(String s) - { - super(s); - } + /** + * + */ + public JSClientCapabilities(String s) + { + super(s); + } public JSClientCapabilities() { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClientMimeTypes.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClientMimeTypes.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClientMimeTypes.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,26 +16,26 @@ */ package org.apache.jetspeed.serializer.objects; - - /** -* Jetspeed Serializer - Simple mime types Wrapper -* <p> -* Wrapper to process XML representation of a set of mime types - used only for binding -* -* @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> -* @version $Id: $ -*/ + * Jetspeed Serializer - Simple mime types Wrapper + * <p> + * Wrapper to process XML representation of a set of mime types - used only for + * binding + * + * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> + * @version $Id: $ + */ public class JSClientMimeTypes extends JSUserRoles { - /** - * - */ - public JSClientMimeTypes(String s) - { - super(s); - } + /** + * + */ + public JSClientMimeTypes(String s) + { + super(s); + } + public JSClientMimeTypes() { super(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClients.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClients.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSClients.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,15 +18,15 @@ import java.util.ArrayList; - /** -* Jetspeed Serializer - Simple clients Wrapper -* <p> -* Wrapper to process XML representation of a set of clients - used only for binding -* -* @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> -* @version $Id: $ -*/ + * Jetspeed Serializer - Simple clients Wrapper + * <p> + * Wrapper to process XML representation of a set of clients - used only for + * binding + * + * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> + * @version $Id: $ + */ public class JSClients extends ArrayList { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntities.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntities.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntities.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,11 +18,11 @@ import java.util.ArrayList; - /** * Simple wrapper class for XML serialization + * * @author hajo - * + * */ public class JSEntities extends ArrayList { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntity.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntity.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntity.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,27 +32,23 @@ private String id; - private JSEntityPreferences entityPreferences = null; - public JSEntity() { } - public void setId(String id) { this.id = id; } - public String getId() { return id; } - /** + /** * @param entityPreferences * The entityPreferences to set. */ @@ -82,12 +78,13 @@ { JSEntity g = (JSEntity) o; String s = g.getId(); - if ((s != null) && (s.length() > 0)) - xml.setAttribute("id", s); - if ((g.entityPreferences != null) && (g.entityPreferences .size()>0)) - xml.add(g.entityPreferences); + if ((s != null) && (s.length() > 0)) xml.setAttribute("id", s); + if ((g.entityPreferences != null) + && (g.entityPreferences.size() > 0)) + xml.add(g.entityPreferences); - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } @@ -98,22 +95,21 @@ try { JSEntity g = (JSEntity) o; - g.id = StringEscapeUtils.unescapeHtml(xml.getAttribute("id", "unknown")); - - + g.id = StringEscapeUtils.unescapeHtml(xml.getAttribute("id", + "unknown")); + Object o1 = null; - - while (xml.hasNext()) - { - o1 = xml.getNext(); // mime - - if (o1 instanceof JSEntityPreferences) - g.entityPreferences = (JSEntityPreferences) o1; - } - - - } catch (Exception e) + while (xml.hasNext()) + { + o1 = xml.getNext(); // mime + + if (o1 instanceof JSEntityPreferences) + g.entityPreferences = (JSEntityPreferences) o1; + } + + } + catch (Exception e) { e.printStackTrace(); } @@ -121,5 +117,4 @@ }; - } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntityPreference.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntityPreference.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntityPreference.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,28 +34,22 @@ private String principalName; - private JSNVPElements preferences = null; - public JSEntityPreference() { } - - public void setName(String principalName) { this.principalName = principalName; } - public String getName() { return principalName; } - /** * @return Returns the preferences. */ @@ -73,7 +67,6 @@ this.preferences = new JSNVPElements(preferences); } - /** * @param preferences * The preferences to set. @@ -83,7 +76,6 @@ this.preferences = preferences; } - /*************************************************************************** * SERIALIZER */ @@ -99,10 +91,11 @@ String s = g.getName(); if ((s == null) || (s.length() == 0)) s = "no-principal"; xml.setAttribute("name", s); - if ((g.preferences != null) && (g.preferences.size()>0)) - xml.add(g.preferences); + if ((g.preferences != null) && (g.preferences.size() > 0)) + xml.add(g.preferences); - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } @@ -113,22 +106,21 @@ try { JSEntityPreference g = (JSEntityPreference) o; - g.principalName = StringEscapeUtils.unescapeHtml(xml.getAttribute("name", "no-principal")); - - + g.principalName = StringEscapeUtils.unescapeHtml(xml + .getAttribute("name", "no-principal")); + Object o1 = null; - - while (xml.hasNext()) - { - o1 = xml.getNext(); // mime - - if (o1 instanceof JSNVPElements) - g.preferences = (JSNVPElements) o1; + while (xml.hasNext()) + { + o1 = xml.getNext(); // mime + + if (o1 instanceof JSNVPElements) + g.preferences = (JSNVPElements) o1; } - - - } catch (Exception e) + + } + catch (Exception e) { e.printStackTrace(); } @@ -136,5 +128,4 @@ }; - } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntityPreferences.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntityPreferences.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSEntityPreferences.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,11 +18,11 @@ import java.util.ArrayList; - /** * Simple wrapper class for XML serialization + * * @author hajo - * + * */ public class JSEntityPreferences extends ArrayList { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSGroup.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSGroup.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSGroup.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,67 +16,74 @@ */ package org.apache.jetspeed.serializer.objects; -import javolution.xml.*; +import javolution.xml.XMLFormat; import javolution.xml.stream.XMLStreamException; import org.apache.commons.lang.StringEscapeUtils; -public class JSGroup +public class JSGroup { - // private int refID; - String name; + // private int refID; - public JSGroup() - { - // refID = id; - } + String name; - /*************************************************************************** - * SERIALIZER - */ - private static final XMLFormat XML = new XMLFormat(JSGroup.class) - { - public void write(Object o, OutputElement xml) throws XMLStreamException - { + public JSGroup() + { + // refID = id; + } - try - { - JSGroup g = (JSGroup) o; - xml.addText(g.getName()); - } catch (Exception e) - { - e.printStackTrace(); - } - } + /*************************************************************************** + * SERIALIZER + */ + private static final XMLFormat XML = new XMLFormat(JSGroup.class) + { - public void read(InputElement xml, Object o) - { - try - { - JSGroup g = (JSGroup) o; - g.setName(StringEscapeUtils.unescapeHtml(xml.getText().toString())); - } catch (Exception e) - { - e.printStackTrace(); - } - } - }; - /** - * @return Returns the name. - */ - public String getName() - { - return name; - } + public void write(Object o, OutputElement xml) + throws XMLStreamException + { - /** - * @param name - * The name to set. - */ - public void setName(String name) - { - this.name = name; - } + try + { + JSGroup g = (JSGroup) o; + xml.addText(g.getName()); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + public void read(InputElement xml, Object o) + { + try + { + JSGroup g = (JSGroup) o; + g.setName(StringEscapeUtils.unescapeHtml(xml.getText() + .toString())); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + }; + + /** + * @return Returns the name. + */ + public String getName() + { + return name; + } + + /** + * @param name + * The name to set. + */ + public void setName(String name) + { + this.name = name; + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSGroups.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSGroups.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSGroups.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,15 +18,15 @@ import java.util.ArrayList; - /** -* Jetspeed Serializer - Simple Groups Wrapper -* <p> -* Wrapper to process XML representation of a set of groups - used only for binding -* -* @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> -* @version $Id: $ -*/ + * Jetspeed Serializer - Simple Groups Wrapper + * <p> + * Wrapper to process XML representation of a set of groups - used only for + * binding + * + * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> + * @version $Id: $ + */ public class JSGroups extends ArrayList { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSMediaType.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSMediaType.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSMediaType.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,18 +28,19 @@ public class JSMediaType { - // private int refID; - private String name; + // private int refID; - private int id; + private String name; - private String characterSet; + private int id; - private String title; + private String characterSet; - private String description; + private String title; + private String description; + private ArrayList capabilities; private ArrayList mimeTypes; @@ -48,173 +49,185 @@ private JSClientMimeTypes mimeTypesString; + public JSMediaType() + { + // refID = id; + } - public JSMediaType() - { - // refID = id; - } + public JSMediaType(MediaType c) + { + this.id = c.getMediatypeId(); + this.name = c.getName(); - public JSMediaType(MediaType c) - { - this.id = c.getMediatypeId(); - this.name = c.getName(); - - this.characterSet = c.getCharacterSet(); - this.title = c.getTitle(); - this.description = c.getDescription(); + this.characterSet = c.getCharacterSet(); + this.title = c.getTitle(); + this.description = c.getDescription(); capabilities = new ArrayList(); mimeTypes = new ArrayList(); - - } - /*************************************************************************** - * SERIALIZER - */ - private static final XMLFormat XML = new XMLFormat(JSMediaType.class) - { - public void write(Object o, OutputElement xml) - throws XMLStreamException - { + } - try - { - JSMediaType g = (JSMediaType) o; + /*************************************************************************** + * SERIALIZER + */ + private static final XMLFormat XML = new XMLFormat(JSMediaType.class) + { + + public void write(Object o, OutputElement xml) + throws XMLStreamException + { + + try + { + JSMediaType g = (JSMediaType) o; /** attributes here */ - xml.setAttribute("name", g.name); + xml.setAttribute("name", g.name); /** named fields HERE */ - xml.add( g.characterSet, "charcterSet",String.class); - xml.add(g.title,"title", String.class); - xml.add(g.description, "description", String.class); + xml.add(g.characterSet, "charcterSet", String.class); + xml.add(g.title, "title", String.class); + xml.add(g.description, "description", String.class); /** implicitly named (through binding) fields here */ - g.capabilitiesString = new JSClientCapabilities(g.putTokens(g.capabilities)); - g.mimeTypesString = new JSClientMimeTypes(g.putTokens(g.mimeTypes)); + g.capabilitiesString = new JSClientCapabilities(g + .putTokens(g.capabilities)); + g.mimeTypesString = new JSClientMimeTypes(g + .putTokens(g.mimeTypes)); xml.add(g.capabilitiesString); xml.add(g.mimeTypesString); - // xml.add(g.groupString); + // xml.add(g.groupString); - } catch (Exception e) - { - e.printStackTrace(); - } - } + } + catch (Exception e) + { + e.printStackTrace(); + } + } - public void read(InputElement xml, Object o) - { - try - { - JSMediaType g = (JSMediaType) o; - g.name = StringEscapeUtils.unescapeHtml(xml.getAttribute("name","")); + public void read(InputElement xml, Object o) + { + try + { + JSMediaType g = (JSMediaType) o; + g.name = StringEscapeUtils.unescapeHtml(xml.getAttribute( + "name", "")); /** named fields HERE */ - Object o1 = xml.get("charcterSet",String.class); //characterSet + Object o1 = xml.get("charcterSet", String.class); // characterSet if ((o1 != null) && (o1 instanceof String)) - g.characterSet = StringEscapeUtils.unescapeHtml((String)o1); - g.title = StringEscapeUtils.unescapeHtml((String)xml.get("title", String.class)); //title; - g.description = StringEscapeUtils.unescapeHtml((String)xml.get("description", String.class)); //description; + g.characterSet = StringEscapeUtils + .unescapeHtml((String) o1); + g.title = StringEscapeUtils.unescapeHtml((String) xml.get( + "title", String.class)); // title; + g.description = StringEscapeUtils.unescapeHtml((String) xml + .get("description", String.class)); // description; while (xml.hasNext()) { o1 = xml.getNext(); // mime if (o1 instanceof JSClientCapabilities) - g.capabilitiesString = (JSClientCapabilities) o1; //capabilitiesString; - else - if (o1 instanceof JSClientMimeTypes) - g.mimeTypesString = (JSClientMimeTypes)o1; //mimeTypesString; + g.capabilitiesString = (JSClientCapabilities) o1; // capabilitiesString; + else if (o1 instanceof JSClientMimeTypes) + g.mimeTypesString = (JSClientMimeTypes) o1; // mimeTypesString; } - } catch (Exception e) - { - e.printStackTrace(); - } - } - }; + } + catch (Exception e) + { + e.printStackTrace(); + } + } + }; + /** + * @return Returns the characterSet. + */ + public String getCharacterSet() + { + return characterSet; + } - /** - * @return Returns the characterSet. - */ - public String getCharacterSet() - { - return characterSet; - } + /** + * @param characterSet + * The characterSet to set. + */ + public void setCharacterSet(String characterSet) + { + this.characterSet = characterSet; + } - /** - * @param characterSet The characterSet to set. - */ - public void setCharacterSet(String characterSet) - { - this.characterSet = characterSet; - } + /** + * @return Returns the description. + */ + public String getDescription() + { + return description; + } - /** - * @return Returns the description. - */ - public String getDescription() - { - return description; - } + /** + * @param description + * The description to set. + */ + public void setDescription(String description) + { + this.description = description; + } - /** - * @param description The description to set. - */ - public void setDescription(String description) - { - this.description = description; - } + /** + * @return Returns the id. + */ + public int getId() + { + return id; + } - /** - * @return Returns the id. - */ - public int getId() - { - return id; - } + /** + * @param id + * The id to set. + */ + public void setId(int id) + { + this.id = id; + } - /** - * @param id The id to set. - */ - public void setId(int id) - { - this.id = id; - } + /** + * @return Returns the name. + */ + public String getName() + { + return name; + } - /** - * @return Returns the name. - */ - public String getName() - { - return name; - } + /** + * @param name + * The name to set. + */ + public void setName(String name) + { + this.name = name; + } - /** - * @param name The name to set. - */ - public void setName(String name) - { - this.name = name; - } + /** + * @return Returns the title. + */ + public String getTitle() + { + return title; + } - /** - * @return Returns the title. - */ - public String getTitle() - { - return title; - } + /** + * @param title + * The title to set. + */ + public void setTitle(String titel) + { + this.title = titel; + } - /** - * @param title The title to set. - */ - public void setTitle(String titel) - { - this.title = titel; - } private String append(JSCapability capability) { return capability.getName(); @@ -227,18 +240,15 @@ private String append(Object s) { - if (s instanceof JSCapability) - return append((JSCapability) s); - if (s instanceof JSMimeType) - return append((JSMimeType) s); + if (s instanceof JSCapability) return append((JSCapability) s); + if (s instanceof JSMimeType) return append((JSMimeType) s); return s.toString(); } private String putTokens(ArrayList _list) { - if ((_list == null) || (_list.size() == 0)) - return ""; + if ((_list == null) || (_list.size() == 0)) return ""; boolean _start = true; Iterator _it = _list.iterator(); StringBuffer _sb = new StringBuffer(); @@ -288,14 +298,14 @@ this.mimeTypes = mimeTypes; } - public JSClientCapabilities getCapabilitiesString() - { - return capabilitiesString; - } + public JSClientCapabilities getCapabilitiesString() + { + return capabilitiesString; + } - public JSClientMimeTypes getMimeTypesString() - { - return mimeTypesString; - } + public JSClientMimeTypes getMimeTypesString() + { + return mimeTypesString; + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSMediaTypes.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSMediaTypes.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSMediaTypes.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,15 +18,15 @@ import java.util.ArrayList; - /** -* Jetspeed Serializer - Simple media types Wrapper -* <p> -* Wrapper to process XML representation of a set of media types - used only for binding -* -* @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> -* @version $Id: $ -*/ + * Jetspeed Serializer - Simple media types Wrapper + * <p> + * Wrapper to process XML representation of a set of media types - used only for + * binding + * + * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> + * @version $Id: $ + */ public class JSMediaTypes extends ArrayList { } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSMimeTypes.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSMimeTypes.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSMimeTypes.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,15 +18,15 @@ import java.util.ArrayList; - /** -* Jetspeed Serializer - Simple mime types Wrapper -* <p> -* Wrapper to process XML representation of a set of mime types - used only for binding -* -* @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> -* @version $Id: $ -*/ + * Jetspeed Serializer - Simple mime types Wrapper + * <p> + * Wrapper to process XML representation of a set of mime types - used only for + * binding + * + * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> + * @version $Id: $ + */ public class JSMimeTypes extends ArrayList { } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSNVPElement.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSNVPElement.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSNVPElement.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,57 +25,70 @@ public class JSNVPElement { - private String key; + private String value; - public JSNVPElement() {}; + + public JSNVPElement() + { + }; + public JSNVPElement(String key, String value) { - this.key = key; - this.value = value; + this.key = key; + this.value = value; } - private static final XMLFormat XML = new XMLFormat(JSNVPElement.class) + private static final XMLFormat XML = new XMLFormat(JSNVPElement.class) + { + + public boolean isReferencable() { - public boolean isReferencable() { - return false; // Always manipulates by value. - } - public void write(Object o, OutputElement xml) - throws XMLStreamException + return false; // Always manipulates by value. + } + + public void write(Object o, OutputElement xml) + throws XMLStreamException + { + // xml.add((String) g.get(_key), _key, String.class); + xml.add(((JSNVPElement) o).key, "name", String.class); + xml.add(((JSNVPElement) o).value, "value", String.class); + } + + public void read(InputElement xml, Object o) + { + try { - // xml.add((String) g.get(_key), _key, String.class); - xml.add(((JSNVPElement)o).key,"name",String.class); - xml.add(((JSNVPElement)o).value,"value",String.class); + JSNVPElement g = (JSNVPElement) o; + g.key = StringEscapeUtils.unescapeHtml((String) xml.get("name", + String.class)); + g.value = StringEscapeUtils.unescapeHtml((String) xml.get( + "value", String.class)); } - public void read(InputElement xml, Object o) + catch (Exception e) { - try - { - JSNVPElement g = (JSNVPElement) o; - g.key = StringEscapeUtils.unescapeHtml((String)xml.get("name", String.class)); - g.value = StringEscapeUtils.unescapeHtml((String)xml.get("value", String.class)); - } catch (Exception e) - { - e.printStackTrace(); - } + e.printStackTrace(); } - }; - public String getKey() - { - return key; - } - public void setKey(String key) - { - this.key = key; - } - public String getValue() - { - return value; - } - public void setValue(String value) - { - this.value = value; - } + } + }; + + public String getKey() + { + return key; } - - + + public void setKey(String key) + { + this.key = key; + } + + public String getValue() + { + return value; + } + + public void setValue(String value) + { + this.value = value; + } +} Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSNVPElements.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSNVPElements.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSNVPElements.java 2008-05-16 01:54:54 UTC (rev 940) @@ -38,25 +38,25 @@ public int size() { - return myMap.size(); - + return myMap.size(); + } + public JSNVPElements() { } - - + public HashMap getMyMap() - { - return myMap; - } + { + return myMap; + } public void add(String key, String value) { - myMap.put(key,value); + myMap.put(key, value); } - /** + /** * @param arg0 */ public JSNVPElements(Preferences preferences) @@ -71,7 +71,8 @@ myMap.put(strings[j], preferences.get(strings[j], "?????")); } - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } @@ -93,10 +94,12 @@ while (_it.hasNext()) { String _key = (String) _it.next(); - JSNVPElement elem = new JSNVPElement(_key,(String)g.myMap.get(_key)); - xml.add(elem,"preference",JSNVPElement.class); + JSNVPElement elem = new JSNVPElement(_key, (String) g.myMap + .get(_key)); + xml.add(elem, "preference", JSNVPElement.class); } - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } @@ -109,21 +112,21 @@ { JSNVPElements g = (JSNVPElements) o; while (xml.hasNext()) - { - JSNVPElement elem = (JSNVPElement)xml.get("preference",JSNVPElement.class); + { + JSNVPElement elem = (JSNVPElement) xml.get("preference", + JSNVPElement.class); g.myMap.put(elem.getKey(), elem.getValue()); - } - } catch (Exception e) + } + } + catch (Exception e) { /** - * while annoying invalid entries in the file should be - * just disregarded + * while annoying invalid entries in the file should be just + * disregarded */ e.printStackTrace(); } } }; - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSNameValuePairs.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSNameValuePairs.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSNameValuePairs.java 2008-05-16 01:54:54 UTC (rev 940) @@ -41,25 +41,25 @@ public int size() { - return myMap.size(); - + return myMap.size(); + } + public JSNameValuePairs() { } - - + public HashMap getMyMap() - { - return myMap; - } + { + return myMap; + } public void add(String key, String value) { - myMap.put(key,value); + myMap.put(key, value); } - /** + /** * @param arg0 */ public JSNameValuePairs(Preferences preferences) @@ -74,7 +74,8 @@ myMap.put(strings[j], preferences.get(strings[j], "?????")); } - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } @@ -99,7 +100,8 @@ // xml.add((String) g.get(_key), _key, String.class); xml.setAttribute(_key, (String) g.myMap.get(_key)); } - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } @@ -118,10 +120,13 @@ { try { - String _key = StringEscapeUtils.unescapeHtml(attribs.getLocalName(i).toString()); - String _value = StringEscapeUtils.unescapeHtml(attribs.getValue(i).toString()); + String _key = StringEscapeUtils.unescapeHtml(attribs + .getLocalName(i).toString()); + String _value = StringEscapeUtils.unescapeHtml(attribs + .getValue(i).toString()); g.myMap.put(_key, _value); - } catch (Exception e) + } + catch (Exception e) { /** * while annoying invalid entries in the file should be @@ -130,7 +135,8 @@ e.printStackTrace(); } } - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPWAttributes.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPWAttributes.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPWAttributes.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,7 +20,6 @@ public class JSPWAttributes extends JSNameValuePairs { - public JSPWAttributes() { super(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPermission.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPermission.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPermission.java 2008-05-16 01:54:54 UTC (rev 940) @@ -40,374 +40,371 @@ public class JSPermission { - private String type; + private String type; - private String resource; + private String resource; - private String actions; + private String actions; - private long id; + private long id; - private ArrayList roles = null; + private ArrayList roles = null; - private ArrayList groups = null; + private ArrayList groups = null; - private ArrayList users = null; + private ArrayList users = null; - private JSUserRoles roleString; + private JSUserRoles roleString; - private JSUserGroups groupString; + private JSUserGroups groupString; - private JSUserUsers userString; + private JSUserUsers userString; - public static final String TYPE_FOLDER = "folder".intern(); + public static final String TYPE_FOLDER = "folder".intern(); - public static final String TYPE_FRAGMENT = "fragment".intern(); + public static final String TYPE_FRAGMENT = "fragment".intern(); - public static final String TYPE_PAGE = "page".intern(); + public static final String TYPE_PAGE = "page".intern(); - public static final String TYPE_PORTALRESOURCE = "portalResource".intern(); + public static final String TYPE_PORTALRESOURCE = "portalResource".intern(); - public static final String TYPE_PORTALRESOURCECOLLECTION = "portalResource" - .intern(); + public static final String TYPE_PORTALRESOURCECOLLECTION = "portalResource" + .intern(); - public static final String TYPE_PORTAL = "portal".intern(); + public static final String TYPE_PORTAL = "portal".intern(); - public static final String TYPE_UNKNOWN = "unknown".intern(); + public static final String TYPE_UNKNOWN = "unknown".intern(); - public String getClassForType(String type) - { - if ((type == null) || (type.length() == 0) || (type.equals(TYPE_UNKNOWN))) - return ""; - if (type.equals(TYPE_FOLDER)) - return "org.apache.jetspeed.security.FolderPermission"; - if (type.equals(TYPE_FRAGMENT)) - return "org.apache.jetspeed.security.FragmentPermission"; - if (type.equals(TYPE_PAGE)) - return "org.apache.jetspeed.security.PagePermission"; - if (type.equals(TYPE_PORTALRESOURCE)) - return "org.apache.jetspeed.security.PortalResourcePermission"; - if (type.equals(TYPE_PORTALRESOURCECOLLECTION)) - return "org.apache.jetspeed.security.PortalResourcePermissionCollection"; - if (type.equals(TYPE_PORTAL)) - return "org.apache.jetspeed.security.PortletPermission"; - return ""; - } + public String getClassForType(String type) + { + if ((type == null) || (type.length() == 0) + || (type.equals(TYPE_UNKNOWN))) return ""; + if (type.equals(TYPE_FOLDER)) + return "org.apache.jetspeed.security.FolderPermission"; + if (type.equals(TYPE_FRAGMENT)) + return "org.apache.jetspeed.security.FragmentPermission"; + if (type.equals(TYPE_PAGE)) + return "org.apache.jetspeed.security.PagePermission"; + if (type.equals(TYPE_PORTALRESOURCE)) + return "org.apache.jetspeed.security.PortalResourcePermission"; + if (type.equals(TYPE_PORTALRESOURCECOLLECTION)) + return "org.apache.jetspeed.security.PortalResourcePermissionCollection"; + if (type.equals(TYPE_PORTAL)) + return "org.apache.jetspeed.security.PortletPermission"; + return ""; + } - public String getTypeForClass(String className) - { - if ((className == null) || (className.length() == 0)) - return TYPE_UNKNOWN; - if (className.equals("org.apache.jetspeed.security.FolderPermission")) - return TYPE_FOLDER; + public String getTypeForClass(String className) + { + if ((className == null) || (className.length() == 0)) + return TYPE_UNKNOWN; + if (className.equals("org.apache.jetspeed.security.FolderPermission")) + return TYPE_FOLDER; - if (className.equals("org.apache.jetspeed.security.FragmentPermission")) - return TYPE_FRAGMENT; - if (className.equals("org.apache.jetspeed.security.PagePermission")) - return TYPE_PAGE; - if (className.equals("org.apache.jetspeed.security.PortletPermission")) - return TYPE_PORTAL; + if (className.equals("org.apache.jetspeed.security.FragmentPermission")) + return TYPE_FRAGMENT; + if (className.equals("org.apache.jetspeed.security.PagePermission")) + return TYPE_PAGE; + if (className.equals("org.apache.jetspeed.security.PortletPermission")) + return TYPE_PORTAL; - if (className - .equals("org.apache.jetspeed.security.PortalResourcePermission")) - return TYPE_PORTALRESOURCE; - if (className - .equals("org.apache.jetspeed.security.PortalResourcePermissionCollection")) - return TYPE_PORTALRESOURCECOLLECTION; - return TYPE_UNKNOWN; + if (className + .equals("org.apache.jetspeed.security.PortalResourcePermission")) + return TYPE_PORTALRESOURCE; + if (className + .equals("org.apache.jetspeed.security.PortalResourcePermissionCollection")) + return TYPE_PORTALRESOURCECOLLECTION; + return TYPE_UNKNOWN; - } + } - public PortalResourcePermission getPermissionForType() - { - PortalResourcePermission newPermission = null; - if ((this.type == null) || (this.type.equals(TYPE_UNKNOWN))) - return null; - try - { - if (type.equals(TYPE_FOLDER)) - newPermission = new FolderPermission(this.resource,this.actions); - else if (type.equals(TYPE_FRAGMENT)) - newPermission = new FragmentPermission(this.resource,this.actions); - else if (type.equals(TYPE_PAGE)) - newPermission = new PagePermission(this.resource,this.actions); - else if (type.equals(TYPE_PORTAL)) - newPermission = new PortletPermission(this.resource,this.actions); - else return null; - return newPermission; - } - catch (Exception e) - { - e.printStackTrace(); - return null; - } - - } - public JSPermission() - { - } + public PortalResourcePermission getPermissionForType() + { + PortalResourcePermission newPermission = null; + if ((this.type == null) || (this.type.equals(TYPE_UNKNOWN))) + return null; + try + { + if (type.equals(TYPE_FOLDER)) + newPermission = new FolderPermission(this.resource, + this.actions); + else if (type.equals(TYPE_FRAGMENT)) + newPermission = new FragmentPermission(this.resource, + this.actions); + else if (type.equals(TYPE_PAGE)) + newPermission = new PagePermission(this.resource, this.actions); + else if (type.equals(TYPE_PORTAL)) + newPermission = new PortletPermission(this.resource, + this.actions); + else + return null; + return newPermission; + } + catch (Exception e) + { + e.printStackTrace(); + return null; + } - private String append(JSRole rule) - { - return rule.getName(); - } + } - private String append(JSGroup group) - { - return group.getName(); - } + public JSPermission() + { + } - private String append(JSUser user) - { - return user.getName(); - } + private String append(JSRole rule) + { + return rule.getName(); + } - private String append(Object s) - { - if (s instanceof JSRole) - return append((JSRole) s); - if (s instanceof JSGroup) - return append((JSGroup) s); - if (s instanceof JSUser) - return append((JSUser) s); + private String append(JSGroup group) + { + return group.getName(); + } - return s.toString(); - } + private String append(JSUser user) + { + return user.getName(); + } - private String putTokens(ArrayList _list) - { - if ((_list == null) || (_list.size() == 0)) - return ""; - boolean _start = true; - Iterator _it = _list.iterator(); - StringBuffer _sb = new StringBuffer(); - while (_it.hasNext()) - { - if (!_start) - _sb.append(','); - else - _start = false; + private String append(Object s) + { + if (s instanceof JSRole) return append((JSRole) s); + if (s instanceof JSGroup) return append((JSGroup) s); + if (s instanceof JSUser) return append((JSUser) s); - _sb.append(append(_it.next())); - } - return _sb.toString(); - } + return s.toString(); + } - /** - * @return Returns the actions. - */ - public String getActions() - { - return actions; - } + private String putTokens(ArrayList _list) + { + if ((_list == null) || (_list.size() == 0)) return ""; + boolean _start = true; + Iterator _it = _list.iterator(); + StringBuffer _sb = new StringBuffer(); + while (_it.hasNext()) + { + if (!_start) + _sb.append(','); + else + _start = false; - /** - * @param actions - * The actions to set. - */ - public void setActions(String actions) - { - this.actions = actions; - } + _sb.append(append(_it.next())); + } + return _sb.toString(); + } - /** - * @return Returns the groups. - */ - public ArrayList getGroups() - { - return groups; - } + /** + * @return Returns the actions. + */ + public String getActions() + { + return actions; + } - /** - * @param groups - * The groups to set. - */ - public void setGroups(ArrayList groups) - { - this.groups = groups; - } + /** + * @param actions + * The actions to set. + */ + public void setActions(String actions) + { + this.actions = actions; + } - /** - * @return Returns the resource. - */ - public String getResource() - { - return resource; - } + /** + * @return Returns the groups. + */ + public ArrayList getGroups() + { + return groups; + } - /** - * @param resource - * The resource to set. - */ - public void setResource(String resource) - { - this.resource = resource; - } + /** + * @param groups + * The groups to set. + */ + public void setGroups(ArrayList groups) + { + this.groups = groups; + } - /** - * @return Returns the roles. - */ - public ArrayList getRoles() - { - return roles; - } + /** + * @return Returns the resource. + */ + public String getResource() + { + return resource; + } - /** - * @param roles - * The roles to set. - */ - public void setRoles(ArrayList roles) - { - this.roles = roles; - } + /** + * @param resource + * The resource to set. + */ + public void setResource(String resource) + { + this.resource = resource; + } - /** - * @return Returns the type. - */ - public String getType() - { - return type; - } + /** + * @return Returns the roles. + */ + public ArrayList getRoles() + { + return roles; + } - /** - * @param type - * The type to set. - */ - public void setType(String type) - { - this.type = type; - } + /** + * @param roles + * The roles to set. + */ + public void setRoles(ArrayList roles) + { + this.roles = roles; + } - /** - * @return Returns the users. - */ - public ArrayList getUsers() - { - return users; - } + /** + * @return Returns the type. + */ + public String getType() + { + return type; + } - /** - * @param users - * The users to set. - */ - public void setUsers(ArrayList users) - { - this.users = users; - } + /** + * @param type + * The type to set. + */ + public void setType(String type) + { + this.type = type; + } + /** + * @return Returns the users. + */ + public ArrayList getUsers() + { + return users; + } - /** - * @return Returns the id. - */ - public long getId() - { - return id; - } + /** + * @param users + * The users to set. + */ + public void setUsers(ArrayList users) + { + this.users = users; + } - /** - * @param id - * The id to set. - */ - public void setId(long id) - { - this.id = id; - } + /** + * @return Returns the id. + */ + public long getId() + { + return id; + } - + /** + * @param id + * The id to set. + */ + public void setId(long id) + { + this.id = id; + } - public void addGroup(JSGroup group) - { - if (groups == null) - groups = new ArrayList(); - groups.add(group); - } + public void addGroup(JSGroup group) + { + if (groups == null) groups = new ArrayList(); + groups.add(group); + } - public void addRole(JSRole role) - { - if (roles == null) - roles = new ArrayList(); - roles.add(role); - } + public void addRole(JSRole role) + { + if (roles == null) roles = new ArrayList(); + roles.add(role); + } + public void addUser(JSUser user) + { + if (users == null) users = new ArrayList(); + users.add(user); + } - public void addUser(JSUser user) - { - if (users == null) - users = new ArrayList(); - users.add(user); - } + /*************************************************************************** + * SERIALIZER + */ + private static final XMLFormat XML = new XMLFormat(JSPermission.class) + { + public void write(Object o, OutputElement xml) + throws XMLStreamException + { + try + { + JSPermission g = (JSPermission) o; + xml.setAttribute("type", g.getType()); + xml.setAttribute("resource", g.getResource()); + xml.setAttribute("actions", g.getActions()); + g.groupString = new JSUserGroups(g.putTokens(g.getGroups())); + g.roleString = new JSUserRoles(g.putTokens(g.getRoles())); + g.userString = new JSUserUsers(g.putTokens(g.getUsers())); + xml.add(g.roleString); + xml.add(g.groupString); + xml.add(g.userString); - /*************************************************************************** - * SERIALIZER - */ - private static final XMLFormat XML = new XMLFormat(JSPermission.class) - { - public void write(Object o, OutputElement xml) - throws XMLStreamException - { - try - { - JSPermission g = (JSPermission) o; - xml.setAttribute("type", g.getType()); - xml.setAttribute("resource",g.getResource()); - xml.setAttribute("actions",g.getActions()); - g.groupString = new JSUserGroups(g.putTokens(g.getGroups())); - g.roleString = new JSUserRoles(g.putTokens(g.getRoles())); - g.userString = new JSUserUsers(g.putTokens(g.getUsers())); - xml.add(g.roleString); - xml.add(g.groupString); - xml.add(g.userString); + } + catch (Exception e) + { + e.printStackTrace(); + } + } - } catch (Exception e) - { - e.printStackTrace(); - } - } + public void read(InputElement xml, Object o) + { + try + { + JSPermission g = (JSPermission) o; + g.type = StringEscapeUtils.unescapeHtml(xml.getAttribute( + "type", "type_unknown")); + g.resource = StringEscapeUtils.unescapeHtml(xml.getAttribute( + "resource", "resource_unknown")); + g.actions = StringEscapeUtils.unescapeHtml(xml.getAttribute( + "actions", "unknown_actions")); - public void read(InputElement xml, Object o) - { - try - { - JSPermission g = (JSPermission) o; - g.type = StringEscapeUtils.unescapeHtml(xml.getAttribute("type", "type_unknown")); - g.resource = StringEscapeUtils.unescapeHtml(xml.getAttribute("resource", "resource_unknown")); - g.actions = StringEscapeUtils.unescapeHtml(xml.getAttribute("actions", "unknown_actions")); - - while (xml.hasNext()) - { - Object o1 = xml.getNext(); // mime + while (xml.hasNext()) + { + Object o1 = xml.getNext(); // mime - if (o1 instanceof JSUserGroups) - g.groupString = (JSUserGroups) o1; - else if (o1 instanceof JSUserUsers) - g.userString = (JSUserUsers) o1; - else if (o1 instanceof JSUserRoles) - g.roleString = (JSUserRoles) o1; - } - } catch (Exception e) - { - e.printStackTrace(); - } - } + if (o1 instanceof JSUserGroups) + g.groupString = (JSUserGroups) o1; + else if (o1 instanceof JSUserUsers) + g.userString = (JSUserUsers) o1; + else if (o1 instanceof JSUserRoles) + g.roleString = (JSUserRoles) o1; + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } - }; + }; - public JSUserGroups getGroupString() - { - return groupString; - } + public JSUserGroups getGroupString() + { + return groupString; + } - public JSUserRoles getRoleString() - { - return roleString; - } + public JSUserRoles getRoleString() + { + return roleString; + } - public JSUserUsers getUserString() - { - return userString; - } + public JSUserUsers getUserString() + { + return userString; + } - - } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPermissions.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPermissions.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPermissions.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,15 +18,15 @@ import java.util.ArrayList; - /** -* Jetspeed Serializer - Simple Permissions Wrapper -* <p> -* Wrapper to process XML representation of a set of permissions - used only for binding -* -* @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> -* @version $Id: $ -*/ + * Jetspeed Serializer - Simple Permissions Wrapper + * <p> + * Wrapper to process XML representation of a set of permissions - used only for + * binding + * + * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> + * @version $Id: $ + */ public class JSPermissions extends ArrayList { } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPortlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPortlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPortlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,27 +32,23 @@ private String name; - private JSEntities entities = null; - public JSPortlet() { } - public void setName(String name) { this.name = name; } - public String getName() { return name; } - /** + /** * @param entities * The entities to set. */ @@ -83,10 +79,11 @@ JSPortlet g = (JSPortlet) o; String s = g.getName(); if ((s != null) && (s.length() > 0)) - xml.setAttribute("name", s); + xml.setAttribute("name", s); xml.add(g.entities); - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } @@ -97,22 +94,20 @@ try { JSPortlet g = (JSPortlet) o; - g.name = StringEscapeUtils.unescapeHtml(xml.getAttribute("name", "unknown")); - - + g.name = StringEscapeUtils.unescapeHtml(xml.getAttribute( + "name", "unknown")); + Object o1 = null; - - while (xml.hasNext()) - { - o1 = xml.getNext(); // mime - - if (o1 instanceof JSEntities) - g.entities = (JSEntities) o1; - } - - - } catch (Exception e) + while (xml.hasNext()) + { + o1 = xml.getNext(); // mime + + if (o1 instanceof JSEntities) g.entities = (JSEntities) o1; + } + + } + catch (Exception e) { e.printStackTrace(); } @@ -120,5 +115,4 @@ }; - } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPortlets.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPortlets.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPortlets.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,11 +18,11 @@ import java.util.ArrayList; - /** * Simple wrapper class for XML serialization + * * @author hajo - * + * */ public class JSPortlets extends ArrayList { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPrincipalRule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPrincipalRule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPrincipalRule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.jetspeed.serializer.objects; + import javolution.xml.XMLFormat; import javolution.xml.stream.XMLStreamException; @@ -22,90 +23,95 @@ public class JSPrincipalRule { -// int refID; - private String locator; + // int refID; - private String rule; + private String locator; + private String rule; + public JSPrincipalRule() { } - public JSPrincipalRule(String locator, String rule) - { -// refID = id; - this.locator = locator; - this.rule = rule; - } - /*************************************************************************** - * SERIALIZER - */ - private static final XMLFormat XML = new XMLFormat(JSPrincipalRule.class) - { - public void write(Object o, OutputElement xml) - throws XMLStreamException - { - try - { - JSPrincipalRule g = (JSPrincipalRule) o; - xml.setAttribute("locator", g.locator); - xml.setAttribute("rule", g.rule); - } catch (Exception e) - { - e.printStackTrace(); - } - } + public JSPrincipalRule(String locator, String rule) + { + // refID = id; + this.locator = locator; + this.rule = rule; + } - public void read(InputElement xml, Object o) - { - try - { - JSPrincipalRule g = (JSPrincipalRule) o; - g.setLocator(StringEscapeUtils.unescapeHtml(xml.getAttribute("locator","unknown"))); - g.setRule(StringEscapeUtils.unescapeHtml(xml.getAttribute("rule","unknown"))); - - - } catch (Exception e) - { - e.printStackTrace(); - } - } + /*************************************************************************** + * SERIALIZER + */ + private static final XMLFormat XML = new XMLFormat(JSPrincipalRule.class) + { - }; + public void write(Object o, OutputElement xml) + throws XMLStreamException + { + try + { + JSPrincipalRule g = (JSPrincipalRule) o; + xml.setAttribute("locator", g.locator); + xml.setAttribute("rule", g.rule); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + public void read(InputElement xml, Object o) + { + try + { + JSPrincipalRule g = (JSPrincipalRule) o; + g.setLocator(StringEscapeUtils.unescapeHtml(xml.getAttribute( + "locator", "unknown"))); + g.setRule(StringEscapeUtils.unescapeHtml(xml.getAttribute( + "rule", "unknown"))); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + }; - /** - * @return Returns the locator. - */ - public String getLocator() - { - return locator; - } + /** + * @return Returns the locator. + */ + public String getLocator() + { + return locator; + } - /** - * @param locator The locator to set. - */ - public void setLocator(String locator) - { - this.locator = locator; - } + /** + * @param locator + * The locator to set. + */ + public void setLocator(String locator) + { + this.locator = locator; + } - /** - * @return Returns the rule. - */ - public String getRule() - { - return rule; - } + /** + * @return Returns the rule. + */ + public String getRule() + { + return rule; + } - /** - * @param rule The rule to set. - */ - public void setRule(String rule) - { - this.rule = rule; - } + /** + * @param rule + * The rule to set. + */ + public void setRule(String rule) + { + this.rule = rule; + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPrincipalRules.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPrincipalRules.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSPrincipalRules.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,15 +18,15 @@ import java.util.ArrayList; - /** -* Jetspeed Serializer - Simple Prinicpal Rules Wrapper -* <p> -* Wrapper to process XML representation of a set of principal rules - used only for binding -* -* @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> -* @version $Id: $ -*/ + * Jetspeed Serializer - Simple Prinicpal Rules Wrapper + * <p> + * Wrapper to process XML representation of a set of principal rules - used only + * for binding + * + * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> + * @version $Id: $ + */ public class JSPrincipalRules extends ArrayList { } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSProcessOrder.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSProcessOrder.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSProcessOrder.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,13 +22,13 @@ public class JSProcessOrder { + private JSMimeTypes ordererList; public JSProcessOrder() { } - /*************************************************************************** * SERIALIZER */ @@ -38,13 +38,14 @@ public void write(Object o, OutputElement xml) throws XMLStreamException { - + try { - JSProcessOrder g = (JSProcessOrder) o; + JSProcessOrder g = (JSProcessOrder) o; xml.add(g.getMimeTypes()); - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } @@ -54,7 +55,7 @@ { try { - JSProcessOrder g = (JSProcessOrder) o; + JSProcessOrder g = (JSProcessOrder) o; while (xml.hasNext()) { Object o1 = xml.getNext(); // mime @@ -62,14 +63,14 @@ if (o1 instanceof JSMimeTypes) g.ordererList = (JSMimeTypes) o1; } - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } } }; - /** * @return Returns the mimeTypes. */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSProfilingRule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSProfilingRule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSProfilingRule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,131 +24,123 @@ /** * Import ProfilingRule * - * <profilingRule name = j2> - * <description>whatever</description> - * <className>org.apache.jetspeed.profile.RuleImpl</className> - * <criteria> - * ... - * </criteria> - * </profilingRule> - * + * <profilingRule name = j2> <description>whatever</description> + * <className>org.apache.jetspeed.profile.RuleImpl</className> <criteria> ... + * </criteria> </profilingRule> + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ public class JSProfilingRule { + private String id; + private boolean standardRule; + private String description; + JSRuleCriterions criterions = new JSRuleCriterions(); - - + public JSProfilingRule() - { + { } - public boolean isStandardRule() { return standardRule; } - public void setStandardRule(boolean standard) { this.standardRule = standard; } - public String getDescription() { return description; } - public void setDescription(String description) { this.description = description; } - public String getId() { return id; } - public void setId(String id) { this.id = id; } - - - /*************************************************************************** - * SERIALIZER - */ - private static final XMLFormat XML = new XMLFormat(JSProfilingRule.class) - { - public void write(Object o, OutputElement xml) - throws XMLStreamException - { + /*************************************************************************** + * SERIALIZER + */ + private static final XMLFormat XML = new XMLFormat(JSProfilingRule.class) + { - try - { - JSProfilingRule g = (JSProfilingRule) o; - xml.setAttribute("id", g.id); - xml.setAttribute("standardRule", g.standardRule); - xml.add( g.description, "description",String.class); - xml.add(g.criterions); + public void write(Object o, OutputElement xml) + throws XMLStreamException + { - } catch (Exception e) - { - e.printStackTrace(); - } - } + try + { + JSProfilingRule g = (JSProfilingRule) o; + xml.setAttribute("id", g.id); + xml.setAttribute("standardRule", g.standardRule); + xml.add(g.description, "description", String.class); + xml.add(g.criterions); - public void read(InputElement xml, Object o) - { - try - { - JSProfilingRule g = (JSProfilingRule) o; - g.id = StringEscapeUtils.unescapeHtml(xml.getAttribute("id","unkwown_id")); - g.standardRule = xml.getAttribute("standardRule",false); - Object o1 = xml.get("description",String.class); - if (o1 instanceof String) - g.description = (String) o1; - while (xml.hasNext()) - { - o1 = xml.getNext(); // mime + } + catch (Exception e) + { + e.printStackTrace(); + } + } - if (o1 instanceof JSRuleCriterions) - g.criterions = (JSRuleCriterions) o1; - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - }; + public void read(InputElement xml, Object o) + { + try + { + JSProfilingRule g = (JSProfilingRule) o; + g.id = StringEscapeUtils.unescapeHtml(xml.getAttribute("id", + "unkwown_id")); + g.standardRule = xml.getAttribute("standardRule", false); + Object o1 = xml.get("description", String.class); + if (o1 instanceof String) g.description = (String) o1; + while (xml.hasNext()) + { + o1 = xml.getNext(); // mime + if (o1 instanceof JSRuleCriterions) + g.criterions = (JSRuleCriterions) o1; + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + }; - /** - * @return Returns the criterions. - */ - public JSRuleCriterions getCriterions() - { - return criterions; - } + /** + * @return Returns the criterions. + */ + public JSRuleCriterions getCriterions() + { + return criterions; + } + /** + * @param criterions + * The criterions to set. + */ + public void setCriterions(JSRuleCriterions criterions) + { + this.criterions = criterions; + } - /** - * @param criterions The criterions to set. - */ - public void setCriterions(JSRuleCriterions criterions) - { - this.criterions = criterions; - } - - } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSProfilingRules.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSProfilingRules.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSProfilingRules.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,15 +18,15 @@ import java.util.ArrayList; - /** -* Jetspeed Serializer - Simple Profiling Rules Wrapper -* <p> -* Wrapper to process XML representation of a set of profiling rules - used only for binding -* -* @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> -* @version $Id: $ -*/ + * Jetspeed Serializer - Simple Profiling Rules Wrapper + * <p> + * Wrapper to process XML representation of a set of profiling rules - used only + * for binding + * + * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> + * @version $Id: $ + */ public class JSProfilingRules extends ArrayList { } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSRoles.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSRoles.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSRoles.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,15 +18,15 @@ import java.util.ArrayList; - /** -* Jetspeed Serializer - Simple Rules Wrapper -* <p> -* Wrapper to process XML representation of a set of rules - used only for binding -* -* @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> -* @version $Id: $ -*/ + * Jetspeed Serializer - Simple Rules Wrapper + * <p> + * Wrapper to process XML representation of a set of rules - used only for + * binding + * + * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> + * @version $Id: $ + */ public class JSRoles extends ArrayList { } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSRuleCriterion.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSRuleCriterion.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSRuleCriterion.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,168 +24,178 @@ public class JSRuleCriterion { - // private int refID; - private String name; + // private int refID; + private String name; - private String type; + private String type; - private String value; + private String value; - private int fallBackOrder; + private int fallBackOrder; - private int fallBackType; + private int fallBackType; - public JSRuleCriterion() - { - // refID = id; - } + public JSRuleCriterion() + { + // refID = id; + } - public JSRuleCriterion(RuleCriterion c) - { - this.name = c.getName(); - this.type = c.getType(); - this.value = c.getValue(); - this.fallBackOrder = c.getFallbackOrder(); - this.fallBackType = c.getFallbackType(); - } + public JSRuleCriterion(RuleCriterion c) + { + this.name = c.getName(); + this.type = c.getType(); + this.value = c.getValue(); + this.fallBackOrder = c.getFallbackOrder(); + this.fallBackType = c.getFallbackType(); + } - /*************************************************************************** - * SERIALIZER - */ - private static final XMLFormat XML = new XMLFormat(JSRuleCriterion.class) - { - public void write(Object o, OutputElement xml) - throws XMLStreamException - { + /*************************************************************************** + * SERIALIZER + */ + private static final XMLFormat XML = new XMLFormat(JSRuleCriterion.class) + { - try - { - JSRuleCriterion g = (JSRuleCriterion) o; - xml.setAttribute("name", g.name); - xml.add( g.type, "type",String.class); - xml.add(g.value,"value", String.class); - xml.add(new Integer(g.fallBackOrder), "fallBackOrder", Integer.class); - xml.add(new Integer(g.fallBackType), "fallBackType", Integer.class); + public void write(Object o, OutputElement xml) + throws XMLStreamException + { - // xml.add(g.groupString); + try + { + JSRuleCriterion g = (JSRuleCriterion) o; + xml.setAttribute("name", g.name); + xml.add(g.type, "type", String.class); + xml.add(g.value, "value", String.class); + xml.add(new Integer(g.fallBackOrder), "fallBackOrder", + Integer.class); + xml.add(new Integer(g.fallBackType), "fallBackType", + Integer.class); - } catch (Exception e) - { - e.printStackTrace(); - } - } + // xml.add(g.groupString); - public void read(InputElement xml, Object o) - { - try - { - JSRuleCriterion g = (JSRuleCriterion) o; - g.name = StringEscapeUtils.unescapeHtml(xml.getAttribute("name","unknown_name")); - Object o1 = xml.get("type",String.class); - if (o1 instanceof String) g.type = StringEscapeUtils.unescapeHtml((String) o1); - o1 = xml.get("value",String.class); - if (o1 instanceof String) g.value = StringEscapeUtils.unescapeHtml((String) o1); + } + catch (Exception e) + { + e.printStackTrace(); + } + } - o1 = xml.get("fallBackOrder",String.class); - if (o1 instanceof String) - g.fallBackOrder = Integer.parseInt(((String) o1)); - o1 = xml.get("fallBackType",String.class); - if (o1 instanceof String) - g.fallBackType = Integer.parseInt(((String) o1)); + public void read(InputElement xml, Object o) + { + try + { + JSRuleCriterion g = (JSRuleCriterion) o; + g.name = StringEscapeUtils.unescapeHtml(xml.getAttribute( + "name", "unknown_name")); + Object o1 = xml.get("type", String.class); + if (o1 instanceof String) + g.type = StringEscapeUtils.unescapeHtml((String) o1); + o1 = xml.get("value", String.class); + if (o1 instanceof String) + g.value = StringEscapeUtils.unescapeHtml((String) o1); - while (xml.hasNext()) - { - } - } catch (Exception e) - { - e.printStackTrace(); - } - } - }; + o1 = xml.get("fallBackOrder", String.class); + if (o1 instanceof String) + g.fallBackOrder = Integer.parseInt(((String) o1)); + o1 = xml.get("fallBackType", String.class); + if (o1 instanceof String) + g.fallBackType = Integer.parseInt(((String) o1)); + while (xml.hasNext()) + { + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + }; - /** - * @return Returns the type. - */ - public String getType() - { - return type; - } + /** + * @return Returns the type. + */ + public String getType() + { + return type; + } - /** - * @param type The type to set. - */ - public void setType(String type) - { - this.type = type; - } + /** + * @param type + * The type to set. + */ + public void setType(String type) + { + this.type = type; + } - /** - * @return Returns the fallBackOrder. - */ - public int getFallBackOrder() - { - return fallBackOrder; - } + /** + * @return Returns the fallBackOrder. + */ + public int getFallBackOrder() + { + return fallBackOrder; + } - /** - * @param fallBackOrder The fallBackOrder to set. - */ - public void setFallBackOrder(int fallBackOrder) - { - this.fallBackOrder = fallBackOrder; - } - /** - * @return Returns the fallBackType. - */ - public int getFallBackType() - { - return fallBackType; - } + /** + * @param fallBackOrder + * The fallBackOrder to set. + */ + public void setFallBackOrder(int fallBackOrder) + { + this.fallBackOrder = fallBackOrder; + } - /** - * @param fallBackTye The fallBackType to set. - */ - public void setFallBackType(int fallBackType) - { - this.fallBackType = fallBackType; - } + /** + * @return Returns the fallBackType. + */ + public int getFallBackType() + { + return fallBackType; + } + /** + * @param fallBackTye + * The fallBackType to set. + */ + public void setFallBackType(int fallBackType) + { + this.fallBackType = fallBackType; + } + /** + * @return Returns the name. + */ + public String getName() + { + return name; + } - /** - * @return Returns the name. - */ - public String getName() - { - return name; - } + /** + * @param name + * The name to set. + */ + public void setName(String name) + { + this.name = name; + } - /** - * @param name The name to set. - */ - public void setName(String name) - { - this.name = name; - } + /** + * @return Returns the value. + */ + public String getValue() + { + return value; + } - /** - * @return Returns the value. - */ - public String getValue() - { - return value; - } + /** + * @param value + * The value to set. + */ + public void setValue(String value) + { + this.value = value; + } - /** - * @param value The value to set. - */ - public void setValue(String value) - { - this.value = value; - } - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSRuleCriterions.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSRuleCriterions.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSRuleCriterions.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,15 +18,15 @@ import java.util.ArrayList; - /** -* Jetspeed Serializer - Simple Rule Criterion Wrapper -* <p> -* Wrapper to process XML representation of a set of criteria - used only for binding -* -* @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> -* @version $Id: $ -*/ + * Jetspeed Serializer - Simple Rule Criterion Wrapper + * <p> + * Wrapper to process XML representation of a set of criteria - used only for + * binding + * + * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> + * @version $Id: $ + */ public class JSRuleCriterions extends ArrayList { } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSecondaryData.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSecondaryData.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSecondaryData.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,12 +27,10 @@ public static final int softwareSubVersion = 0; - private String encryption; + private String encryption; - private JSApplications applications; - /** * check the software version and subvversion against the saved * version...and verify whether it is compatible... @@ -43,7 +41,7 @@ { return true; } - + /** * @return Returns the softwareSubVersion. */ @@ -60,21 +58,19 @@ return softwareVersion; } - public JSSecondaryData() { - super(); + super(); System.out.println("JSSecondaryData Class created"); } public JSSecondaryData(String name) { super(); - + applications = new JSApplications(); } - /*************************************************************************** * SERIALIZER */ @@ -84,21 +80,20 @@ public void write(Object o, OutputElement xml) throws XMLStreamException { - + try { - JSSnapshot.XML.write(o,xml); + JSSnapshot.XML.write(o, xml); JSSecondaryData g = (JSSecondaryData) o; - - + /** implicitly named (through binding) fields here */ - xml.add(g.getApplications()); - + xml.add(g.getApplications()); - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } @@ -108,7 +103,7 @@ { try { - JSSnapshot.XML.read(xml, o); // Calls parent read. + JSSnapshot.XML.read(xml, o); // Calls parent read. JSSecondaryData g = (JSSecondaryData) o; while (xml.hasNext()) @@ -118,16 +113,14 @@ if (o1 instanceof JSApplications) g.applications = (JSApplications) o1; } - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } } }; - - - /** * @param applications * The applications to set. @@ -137,10 +130,9 @@ this.applications = applications; } - public JSApplications getApplications() - { - return applications; - } + public JSApplications getApplications() + { + return applications; + } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSeedData.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSeedData.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSeedData.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,11 +17,11 @@ package org.apache.jetspeed.serializer.objects; -import org.apache.commons.lang.StringEscapeUtils; - import javolution.xml.XMLFormat; import javolution.xml.stream.XMLStreamException; +import org.apache.commons.lang.StringEscapeUtils; + public class JSSeedData extends JSSnapshot { @@ -29,7 +29,7 @@ public static final int softwareSubVersion = 0; - private String encryption; + private String encryption; private JSMimeTypes mimeTypes; @@ -61,7 +61,7 @@ { return true; } - + /** * @return Returns the softwareSubVersion. */ @@ -78,17 +78,16 @@ return softwareVersion; } - public JSSeedData() { - super(); + super(); System.out.println("JSSeedData Class created"); } public JSSeedData(String name) { super(); - + mimeTypes = new JSMimeTypes(); mediaTypes = new JSMediaTypes(); clients = new JSClients(); @@ -100,7 +99,6 @@ rules = new JSProfilingRules(); } - /*************************************************************************** * SERIALIZER */ @@ -110,33 +108,34 @@ public void write(Object o, OutputElement xml) throws XMLStreamException { - + try { - JSSnapshot.XML.write(o,xml); + JSSnapshot.XML.write(o, xml); JSSeedData g = (JSSeedData) o; - + xml.add(g.getDefaultRule(), "default_rule", String.class); - xml.add(g.encryption,"encryption",String.class); - + xml.add(g.encryption, "encryption", String.class); + /** implicitly named (through binding) fields here */ xml.add(g.getMimeTypes()); xml.add(g.getMediaTypes()); xml.add(g.getCapabilities()); xml.add(g.getClients()); - - xml.add(g.getRoles()); + + xml.add(g.getRoles()); xml.add(g.getGroups()); - xml.add(g.getUsers()); - + xml.add(g.getUsers()); + xml.add(g.getPermissions()); xml.add(g.getRules()); - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } @@ -146,12 +145,14 @@ { try { - JSSnapshot.XML.read(xml, o); // Calls parent read. + JSSnapshot.XML.read(xml, o); // Calls parent read. JSSeedData g = (JSSeedData) o; - Object o1 = xml.get("default_rule",String.class); - if (o1 instanceof String) g.defaultRule = StringEscapeUtils.unescapeHtml((String) o1); - o1 = xml.get("encryption",String.class); - if (o1 instanceof String) g.encryption = StringEscapeUtils.unescapeHtml((String) o1); + Object o1 = xml.get("default_rule", String.class); + if (o1 instanceof String) + g.defaultRule = StringEscapeUtils.unescapeHtml((String) o1); + o1 = xml.get("encryption", String.class); + if (o1 instanceof String) + g.encryption = StringEscapeUtils.unescapeHtml((String) o1); while (xml.hasNext()) { @@ -176,14 +177,14 @@ else if (o1 instanceof JSProfilingRules) g.rules = (JSProfilingRules) o1; } - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } } }; - /** * @return Returns the groups. */ @@ -243,7 +244,6 @@ this.encryption = encryption; } - /** * @return Returns the capabilities. */ @@ -278,8 +278,6 @@ this.clients = clients; } - - /** * @return Returns the mediaTypes. */ @@ -314,9 +312,6 @@ this.mimeTypes = mimeTypes; } - - - /** * @param users * The users to set. Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSimpleIDName.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSimpleIDName.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSimpleIDName.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,92 +21,99 @@ import org.apache.commons.lang.StringEscapeUtils; -public class JSSimpleIDName +public class JSSimpleIDName { - // private int refID; - private String name; + // private int refID; - private int id; - - public JSSimpleIDName() - { - // refID = id; - } - - public JSSimpleIDName(int id, String name) - { - this.id = id; - this.name = name; - // refID = id; - } + private String name; - /*************************************************************************** - * SERIALIZER - */ - private static final XMLFormat XML = new XMLFormat(JSSimpleIDName.class) - { - public void write(Object o, OutputElement xml) throws XMLStreamException - { + private int id; - try - { - JSSimpleIDName g = (JSSimpleIDName) o; - xml.setAttribute("name",g.name ); - xml.setAttribute("id",g.id); - - } catch (Exception e) - { - e.printStackTrace(); - } - } + public JSSimpleIDName() + { + // refID = id; + } - public void read(InputElement xml, Object o) - { - try - { - JSSimpleIDName g = (JSSimpleIDName) o; - g.setName(StringEscapeUtils.unescapeHtml(xml.getAttribute("name","Unknown"))); - g.setId(xml.getAttribute("id",0)); - - } catch (Exception e) - { - e.printStackTrace(); - } - } - }; - /** - * @return Returns the name. - */ - public String getName() - { - return name; - } + public JSSimpleIDName(int id, String name) + { + this.id = id; + this.name = name; + // refID = id; + } - /** - * @param name - * The name to set. - */ - public void setName(String name) - { - this.name = name; - } + /*************************************************************************** + * SERIALIZER + */ + private static final XMLFormat XML = new XMLFormat(JSSimpleIDName.class) + { - /** - * @return Returns the id. - */ - public int getId() - { - return id; - } + public void write(Object o, OutputElement xml) + throws XMLStreamException + { - /** - * @param id The id to set. - */ - public void setId(int id) - { - this.id = id; - } + try + { + JSSimpleIDName g = (JSSimpleIDName) o; + xml.setAttribute("name", g.name); + xml.setAttribute("id", g.id); - + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + public void read(InputElement xml, Object o) + { + try + { + JSSimpleIDName g = (JSSimpleIDName) o; + g.setName(StringEscapeUtils.unescapeHtml(xml.getAttribute( + "name", "Unknown"))); + g.setId(xml.getAttribute("id", 0)); + + } + catch (Exception e) + { + e.printStackTrace(); + } + } + }; + + /** + * @return Returns the name. + */ + public String getName() + { + return name; + } + + /** + * @param name + * The name to set. + */ + public void setName(String name) + { + this.name = name; + } + + /** + * @return Returns the id. + */ + public int getId() + { + return id; + } + + /** + * @param id + * The id to set. + */ + public void setId(int id) + { + this.id = id; + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSnapshot.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSnapshot.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSSnapshot.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,149 +17,140 @@ package org.apache.jetspeed.serializer.objects; -import org.apache.commons.lang.StringEscapeUtils; - import javolution.xml.XMLFormat; import javolution.xml.stream.XMLStreamException; +import org.apache.commons.lang.StringEscapeUtils; + public abstract class JSSnapshot { - - private String name; + private String name; - private int savedVersion; + private int savedVersion; - private int savedSubversion; + private int savedSubversion; - private String dateCreated; + private String dateCreated; - private String dataSource; + private String dataSource; + /** + * check the software version and subvversion against the saved + * version...and verify whether it is compatible... + * + * @return the current software can process this file + */ + public boolean checkVersion() + { + return true; + } - /** - * check the software version and subvversion against the saved - * version...and verify whether it is compatible... - * - * @return the current software can process this file - */ - public boolean checkVersion() - { - return true; - } + public JSSnapshot() + { + System.out.println(this.getClass().getName() + " created"); + } - public JSSnapshot() - { - System.out.println(this.getClass().getName() + " created"); - } + public JSSnapshot(String name) + { + this.name = name; + } - public JSSnapshot(String name) - { - this.name = name; - } + /** + * @return Returns the name. + */ + public final String getName() + { + return name; + } - + /** + * @return Returns the softwareSubVersion. + */ + public abstract int getSoftwareSubVersion(); + /** + * @return Returns the softwareVersion. + */ + public abstract int getSoftwareVersion(); - /** - * @return Returns the name. - */ - public final String getName() - { - return name; - } + /** + * @return Returns the dataSource. + */ + public final String getDataSource() + { + return dataSource; + } + /** + * @param dataSource + * The dataSource to set. + */ + public final void setDataSource(String dataSource) + { + this.dataSource = dataSource; + } - /** - * @return Returns the softwareSubVersion. - */ - public abstract int getSoftwareSubVersion(); + /** + * @return Returns the dateCreated. + */ + public final String getDateCreated() + { + return dateCreated; + } - /** - * @return Returns the softwareVersion. - */ - public abstract int getSoftwareVersion(); + /** + * @param dateCreated + * The dateCreated to set. + */ + public final void setDateCreated(String dateCreated) + { + this.dateCreated = dateCreated; + } - /** - * @return Returns the dataSource. - */ - public final String getDataSource() - { - return dataSource; - } + /** + * @return Returns the savedSubversion. + */ + public final int getSavedSubversion() + { + return savedSubversion; + } - /** - * @param dataSource - * The dataSource to set. - */ - public final void setDataSource(String dataSource) - { - this.dataSource = dataSource; - } + /** + * @param savedSubversion + * The savedSubversion to set. + */ + public final void setSavedSubversion(int savedSubversion) + { + this.savedSubversion = savedSubversion; + } - /** - * @return Returns the dateCreated. - */ - public final String getDateCreated() - { - return dateCreated; - } + /** + * @return Returns the savedVersion. + */ + public final int getSavedVersion() + { + return savedVersion; + } - /** - * @param dateCreated - * The dateCreated to set. - */ - public final void setDateCreated(String dateCreated) - { - this.dateCreated = dateCreated; - } + /** + * @param savedVersion + * The savedVersion to set. + */ + public final void setSavedVersion(int savedVersion) + { + this.savedVersion = savedVersion; + } + /** + * @param name + * The name to set. + */ + public final void setName(String name) + { + this.name = name; + } - /** - * @return Returns the savedSubversion. - */ - public final int getSavedSubversion() - { - return savedSubversion; - } - - /** - * @param savedSubversion - * The savedSubversion to set. - */ - public final void setSavedSubversion(int savedSubversion) - { - this.savedSubversion = savedSubversion; - } - - /** - * @return Returns the savedVersion. - */ - public final int getSavedVersion() - { - return savedVersion; - } - - /** - * @param savedVersion - * The savedVersion to set. - */ - public final void setSavedVersion(int savedVersion) - { - this.savedVersion = savedVersion; - } - - /** - * @param name - * The name to set. - */ - public final void setName(String name) - { - this.name = name; - } - - - /*************************************************************************** * SERIALIZER */ @@ -169,7 +160,7 @@ public void write(Object o, OutputElement xml) throws XMLStreamException { - + try { JSSnapshot g = (JSSnapshot) o; @@ -184,7 +175,8 @@ "softwareVersion"); xml.add(String.valueOf(g.getSoftwareSubVersion()), "softwareSubVersion"); - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } @@ -195,19 +187,20 @@ try { JSSnapshot g = (JSSnapshot) o; - g.name = StringEscapeUtils.unescapeHtml(xml.getAttribute("name", "unknown")); - Object o1 = xml.get("softwareVersion",String.class); + g.name = StringEscapeUtils.unescapeHtml(xml.getAttribute( + "name", "unknown")); + Object o1 = xml.get("softwareVersion", String.class); if (o1 instanceof String) g.savedVersion = Integer.parseInt(((String) o1)); - o1 = xml.get("softwareSubVersion",String.class); + o1 = xml.get("softwareSubVersion", String.class); if (o1 instanceof String) g.savedSubversion = Integer.parseInt(((String) o1)); - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } } }; - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUser.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUser.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUser.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,8 +17,8 @@ package org.apache.jetspeed.serializer.objects; import java.security.Principal; -import java.util.ArrayList; import java.sql.Date; +import java.util.ArrayList; import java.util.Iterator; import java.util.prefs.Preferences; @@ -105,92 +105,88 @@ return password; } - public void setUserCredential(String name, char[] password, Date expirationDate, boolean isEnabled, boolean isExpired, boolean requireUpdate) + public void setUserCredential(String name, char[] password, + Date expirationDate, boolean isEnabled, boolean isExpired, + boolean requireUpdate) { setName(name); setPassword(password); pwData = new JSPWAttributes(); if (password != null) { - pwData.getMyMap().put("password",this.getPasswordString()); - if (expirationDate != null) - { - pwData.getMyMap().put("expirationDate",expirationDate.toString()); - } - pwData.getMyMap().put("enabled",(isEnabled?"TRUE":"FALSE")); - pwData.getMyMap().put("requiresUpdate",(requireUpdate?"TRUE":"FALSE")); + pwData.getMyMap().put("password", this.getPasswordString()); + if (expirationDate != null) + { + pwData.getMyMap().put("expirationDate", + expirationDate.toString()); + } + pwData.getMyMap().put("enabled", (isEnabled ? "TRUE" : "FALSE")); + pwData.getMyMap().put("requiresUpdate", + (requireUpdate ? "TRUE" : "FALSE")); } } protected void resetPassword() { - try - { - if (pwData != null) - { - Object o = pwData.getMyMap().get("password"); - - String pw = StringEscapeUtils.unescapeHtml((String)o); - if ((pw != null) && (pw.length()>0)) - password = pw.toCharArray(); - else - password = null; - } - } - catch (Exception e) - { - password = null; - } + try + { + if (pwData != null) + { + Object o = pwData.getMyMap().get("password"); + + String pw = StringEscapeUtils.unescapeHtml((String) o); + if ((pw != null) && (pw.length() > 0)) + password = pw.toCharArray(); + else + password = null; + } + } + catch (Exception e) + { + password = null; + } } - + public boolean getPwEnabled() { - return getPWBoolean("enabled",false); + return getPWBoolean("enabled", false); } + public boolean getPwRequiredUpdate() { - return getPWBoolean("requiresUpdate",false); + return getPWBoolean("requiresUpdate", false); } - - - - public Date getPwExpirationDate() { - if (pwData != null) - { - Object o = pwData.getMyMap().get("expirationDate"); - if (o == null) - return null; - if ( o instanceof Date) - return (Date)o; - - Date d = Date.valueOf((String)o); - return d; - - } - return null; + if (pwData != null) + { + Object o = pwData.getMyMap().get("expirationDate"); + if (o == null) return null; + if (o instanceof Date) return (Date) o; + + Date d = Date.valueOf((String) o); + return d; + + } + return null; } - - - private boolean getPWBoolean(String property, boolean defaultSetting) + + private boolean getPWBoolean(String property, boolean defaultSetting) { - if (pwData == null) - return defaultSetting; - try - { - Object o = pwData.getMyMap().get(property); - if (o == null) - return defaultSetting; - return ((String)o).equalsIgnoreCase("TRUE"); - } - catch (Exception e) - { - return defaultSetting; - } + if (pwData == null) return defaultSetting; + try + { + Object o = pwData.getMyMap().get(property); + if (o == null) return defaultSetting; + return ((String) o).equalsIgnoreCase("TRUE"); + } + catch (Exception e) + { + return defaultSetting; + } } - + public void setPassword(char[] password) { this.password = password; @@ -312,11 +308,10 @@ if ((s == null) || (s.length() == 0)) s = "guest"; xml.setAttribute("name", s); - xml.add(g.getPwData()); /** named fields HERE */ - + /** implicitly named (through binding) fields here */ g.groupString = new JSUserGroups(g.putTokens(g.getGroups())); g.roleString = new JSUserRoles(g.putTokens(g.getRoles())); @@ -327,7 +322,8 @@ xml.add(g.userInfo); xml.add(g.rules); - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); } @@ -338,41 +334,34 @@ try { JSUser g = (JSUser) o; - g.name = StringEscapeUtils.unescapeHtml(xml.getAttribute("name", "unknown")); - - + g.name = StringEscapeUtils.unescapeHtml(xml.getAttribute( + "name", "unknown")); + Object o1 = null; - - while (xml.hasNext()) - { - o1 = xml.getNext(); // mime - - - if (o1 instanceof JSPWAttributes) - { - g.pwData = (JSPWAttributes) o1; - g.resetPassword(); - } - else - if (o1 instanceof JSUserGroups) - g.groupString = (JSUserGroups) o1; - else - if (o1 instanceof JSUserRoles) - g.roleString = (JSUserRoles) o1; - else - if (o1 instanceof JSUserAttributes) - g.userInfo = (JSUserAttributes) o1; - else - if (o1 instanceof JSNVPElements) - g.preferences = (JSNVPElements) o1; - else - if (o1 instanceof JSPrincipalRules) - g.rules = (JSPrincipalRules) o1; + while (xml.hasNext()) + { + o1 = xml.getNext(); // mime + + if (o1 instanceof JSPWAttributes) + { + g.pwData = (JSPWAttributes) o1; + g.resetPassword(); + } + else if (o1 instanceof JSUserGroups) + g.groupString = (JSUserGroups) o1; + else if (o1 instanceof JSUserRoles) + g.roleString = (JSUserRoles) o1; + else if (o1 instanceof JSUserAttributes) + g.userInfo = (JSUserAttributes) o1; + else if (o1 instanceof JSNVPElements) + g.preferences = (JSNVPElements) o1; + else if (o1 instanceof JSPrincipalRules) + g.rules = (JSPrincipalRules) o1; } - - - } catch (Exception e) + + } + catch (Exception e) { e.printStackTrace(); } @@ -380,7 +369,6 @@ }; - private String append(JSRole rule) { return rule.getName(); @@ -459,24 +447,24 @@ this.principal = principal; } - public JSUserGroups getGroupString() - { - return groupString; - } + public JSUserGroups getGroupString() + { + return groupString; + } - public JSUserRoles getRoleString() - { - return roleString; - } + public JSUserRoles getRoleString() + { + return roleString; + } - public JSPWAttributes getPwData() - { - return pwData; - } + public JSPWAttributes getPwData() + { + return pwData; + } - public void setPwData(JSPWAttributes pwData) - { - this.pwData = pwData; - } + public void setPwData(JSPWAttributes pwData) + { + this.pwData = pwData; + } } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserAttributes.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserAttributes.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserAttributes.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,19 +17,19 @@ package org.apache.jetspeed.serializer.objects; -import java.util.prefs.*; +import java.util.prefs.Preferences; public class JSUserAttributes extends JSNVPElements { + /** + * @param preferences + */ + public JSUserAttributes(Preferences preferences) + { + super(preferences); + } - /** - * @param preferences - */ - public JSUserAttributes(Preferences preferences) - { - super(preferences); - } public JSUserAttributes() { super(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserGroups.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserGroups.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserGroups.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,28 +16,29 @@ */ package org.apache.jetspeed.serializer.objects; - - /** -* Jetspeed Serializer - Simple User Groups Wrapper -* <p> -* Wrapper to process XML representation of a set of user groups - used only for binding -* -* @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> -* @version $Id: $ -*/public class JSUserGroups extends JSUserRoles + * Jetspeed Serializer - Simple User Groups Wrapper + * <p> + * Wrapper to process XML representation of a set of user groups - used only for + * binding + * + * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> + * @version $Id: $ + */ +public class JSUserGroups extends JSUserRoles { public JSUserGroups() { super(); } - /** - * - */ - public JSUserGroups(String s) - { - super(s); - } + /** + * + */ + public JSUserGroups(String s) + { + super(s); + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserRoles.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserRoles.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserRoles.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,50 +16,52 @@ */ package org.apache.jetspeed.serializer.objects; -import org.apache.commons.lang.StringEscapeUtils; - import javolution.xml.XMLFormat; import javolution.xml.stream.XMLStreamException; +import org.apache.commons.lang.StringEscapeUtils; /** -* Jetspeed Serializer - Simple User Roles Wrapper -* <p> -* Wrapper to process XML representation of a set of user roles - used only for binding -* -* @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> -* @version $Id: $ -*/ + * Jetspeed Serializer - Simple User Roles Wrapper + * <p> + * Wrapper to process XML representation of a set of user roles - used only for + * binding + * + * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> + * @version $Id: $ + */ public class JSUserRoles { - String roles; - - + + String roles; + public JSUserRoles() { } + public JSUserRoles(String s) - { - roles = s; - } - public String toString() - { - return roles; - } + { + roles = s; + } - - + public String toString() + { + return roles; + } + private static final XMLFormat XML = new XMLFormat(JSUserRoles.class) - { - public void write(Object oo, OutputElement xml) - throws XMLStreamException - { - xml.addText(((JSUserRoles)oo).roles); - } - public void read(InputElement xml, Object oo) - throws XMLStreamException - { - ((JSUserRoles)oo).roles = StringEscapeUtils.unescapeHtml(xml.getText().toString()); - } - }; + { + + public void write(Object oo, OutputElement xml) + throws XMLStreamException + { + xml.addText(((JSUserRoles) oo).roles); + } + + public void read(InputElement xml, Object oo) throws XMLStreamException + { + ((JSUserRoles) oo).roles = StringEscapeUtils.unescapeHtml(xml + .getText().toString()); + } + }; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserUsers.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserUsers.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUserUsers.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,32 +16,33 @@ */ package org.apache.jetspeed.serializer.objects; - - /** -* Jetspeed Serializer - Simple User Wrapper to allow cross reference of users in a list -* <p> -* Wrapper to process XML representation of a set of users - used only for binding -* -* @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> -* @version $Id: $ -*/ + * Jetspeed Serializer - Simple User Wrapper to allow cross reference of users + * in a list + * <p> + * Wrapper to process XML representation of a set of users - used only for + * binding + * + * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> + * @version $Id: $ + */ public class JSUserUsers extends JSUserRoles { - /** - * - */ - public JSUserUsers(String s) - { - super(s); - } - /** - * - */ - public JSUserUsers() - { - super(); - } + /** + * + */ + public JSUserUsers(String s) + { + super(s); + } + /** + * + */ + public JSUserUsers() + { + super(); + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUsers.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUsers.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/serializer/src/java/org/apache/jetspeed/serializer/objects/JSUsers.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,11 +18,11 @@ import java.util.ArrayList; - /** * Simple wrapper class for XML serialization + * * @author hajo - * + * */ public class JSUsers extends ArrayList { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/PersistenceBrokerSSOProvider.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/PersistenceBrokerSSOProvider.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/PersistenceBrokerSSOProvider.java 2008-05-16 01:54:54 UTC (rev 940) @@ -62,244 +62,276 @@ import org.apache.ojb.broker.query.QueryByCriteria; import org.apache.ojb.broker.query.QueryFactory; - /** -* <p>Utility component to handle SSO requests</p> -* -* @author <a href="mailto:rogerrut ¡÷ apache.org">Roger Ruttimann</a> -*/ + * <p> + * Utility component to handle SSO requests + * </p> + * + * @author <a href="mailto:rogerrut ¡÷ apache.org">Roger Ruttimann</a> + */ public class PersistenceBrokerSSOProvider extends - InitablePersistenceBrokerDaoSupport implements SSOProvider -{ - /* Logging */ - private static final Log log = LogFactory.getLog(PersistenceBrokerSSOProvider.class); - - /* - * Cache for sites and Proxy sites - */ - private Hashtable mapSite = new Hashtable(); - private Hashtable clientProxy = new Hashtable(); - + InitablePersistenceBrokerDaoSupport implements SSOProvider +{ + + /* Logging */ + private static final Log log = LogFactory + .getLog(PersistenceBrokerSSOProvider.class); + + /* + * Cache for sites and Proxy sites + */ + private Hashtable mapSite = new Hashtable(); + + private Hashtable clientProxy = new Hashtable(); + private String USER_PATH = "/user/"; + private String GROUP_PATH = "/group/"; - /** + /** * PersitenceBrokerSSOProvider() - * @param repository Location of repository mapping file. Must be available within the classpath. - * @param prefsFactoryImpl <code>java.util.prefs.PreferencesFactory</code> implementation to use. - * @param enablePropertyManager Whether or not we chould be suing the property manager. - * @throws ClassNotFoundException if the <code>prefsFactoryImpl</code> argument does not reperesent - * a Class that exists in the current classPath. + * + * @param repository + * Location of repository mapping file. Must be available within + * the classpath. + * @param prefsFactoryImpl + * <code>java.util.prefs.PreferencesFactory</code> + * implementation to use. + * @param enablePropertyManager + * Whether or not we chould be suing the property manager. + * @throws ClassNotFoundException + * if the <code>prefsFactoryImpl</code> argument does not + * reperesent a Class that exists in the current classPath. */ - public PersistenceBrokerSSOProvider(String repositoryPath) throws ClassNotFoundException + public PersistenceBrokerSSOProvider(String repositoryPath) + throws ClassNotFoundException { - super(repositoryPath); + super(repositoryPath); } - - + /* - * (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOProvider#useSSO(java.lang.String, java.lang.String, java.lang.String) + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOProvider#useSSO(java.lang.String, + * java.lang.String, java.lang.String) */ - public String useSSO(Subject subject, String url, String SSOSite, boolean bRefresh) throws SSOException + public String useSSO(Subject subject, String url, String SSOSite, + boolean bRefresh) throws SSOException { - // Get the principal from the subject - BasePrincipal principal = (BasePrincipal)SecurityHelper.getBestPrincipal(subject, UserPrincipal.class); - String fullPath = principal.getFullPath(); - - /* ProxyID is used for the cache. The http client object will be cached for a - * given user site url combination - */ - String proxyID = fullPath + "_" + SSOSite; - - // Get the site - SSOSite ssoSite = getSSOSiteObject(SSOSite); - - if ( ssoSite != null) - { - SSOSite[] sites = new SSOSite[1]; - sites[0] = ssoSite; - - return this.getContentFromURL(proxyID, url, sites, bRefresh); - } - else - { - // Site doesn't exist -- log an error but continue - String msg = "SSO component -- useSSO can't retrive SSO credential because SSOSite [" + SSOSite + "] doesn't exist"; - log.error(msg); - SSOSite[] sites = new SSOSite[0]; - return this.getContentFromURL(proxyID, url, sites, bRefresh); - } - } - + // Get the principal from the subject + BasePrincipal principal = (BasePrincipal) SecurityHelper + .getBestPrincipal(subject, UserPrincipal.class); + String fullPath = principal.getFullPath(); + + /* + * ProxyID is used for the cache. The http client object will be cached + * for a given user site url combination + */ + String proxyID = fullPath + "_" + SSOSite; + + // Get the site + SSOSite ssoSite = getSSOSiteObject(SSOSite); + + if (ssoSite != null) + { + SSOSite[] sites = new SSOSite[1]; + sites[0] = ssoSite; + + return this.getContentFromURL(proxyID, url, sites, bRefresh); + } + else + { + // Site doesn't exist -- log an error but continue + String msg = "SSO component -- useSSO can't retrive SSO credential because SSOSite [" + + SSOSite + "] doesn't exist"; + log.error(msg); + SSOSite[] sites = new SSOSite[0]; + return this.getContentFromURL(proxyID, url, sites, bRefresh); + } + } + /* - * (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOProvider#useSSO(java.lang.String, java.lang.String) + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOProvider#useSSO(java.lang.String, + * java.lang.String) */ - public String useSSO(Subject subject, String url, boolean bRefresh) throws SSOException + public String useSSO(Subject subject, String url, boolean bRefresh) + throws SSOException { - // Get the principal from the subject - BasePrincipal principal = (BasePrincipal)SecurityHelper.getBestPrincipal(subject, UserPrincipal.class); - String fullPath = principal.getFullPath(); + // Get the principal from the subject + BasePrincipal principal = (BasePrincipal) SecurityHelper + .getBestPrincipal(subject, UserPrincipal.class); + String fullPath = principal.getFullPath(); - - /* ProxyID is used for the cache. The http client object will be cached for a - * given user - */ - String proxyID = fullPath; - - Collection sites = this.getSitesForPrincipal(fullPath); - - if (sites == null) - { - String msg = "SSO Component useSSO -- Couldn't find any SSO sites for user ["+fullPath+"]"; - log.error(msg); - throw new SSOException(msg); - } - - // Load all the sites - int siteSize = sites.size(); - int siteIndex =0; - SSOSite[] ssoSites = new SSOSite[siteSize]; - - Iterator itSites = sites.iterator(); - while(itSites.hasNext()) - { - SSOSite ssoSite = (SSOSite)itSites.next(); - if (ssoSite != null) - { - ssoSites[siteIndex] = ssoSite; - siteIndex++; - } - } - - return this.getContentFromURL(proxyID, url, ssoSites, bRefresh); + /* + * ProxyID is used for the cache. The http client object will be cached + * for a given user + */ + String proxyID = fullPath; + + Collection sites = this.getSitesForPrincipal(fullPath); + + if (sites == null) + { + String msg = "SSO Component useSSO -- Couldn't find any SSO sites for user [" + + fullPath + "]"; + log.error(msg); + throw new SSOException(msg); + } + + // Load all the sites + int siteSize = sites.size(); + int siteIndex = 0; + SSOSite[] ssoSites = new SSOSite[siteSize]; + + Iterator itSites = sites.iterator(); + while (itSites.hasNext()) + { + SSOSite ssoSite = (SSOSite) itSites.next(); + if (ssoSite != null) + { + ssoSites[siteIndex] = ssoSite; + siteIndex++; + } + } + + return this.getContentFromURL(proxyID, url, ssoSites, bRefresh); } - - /** + + /** * Retrive cookies for an user by User full path + * * @param fullPath * @return */ public Collection getCookiesForUser(String fullPath) { - // Get the SSO user identified by the fullPath - SSOPrincipal ssoPrincipal = this.getSSOPrincipal(fullPath); - - // For each remote user we'll get the cookie - Vector temp = new Vector(); - - Iterator itRemotePrincipal = ssoPrincipal.getRemotePrincipals().iterator(); - while (itRemotePrincipal.hasNext()) - { - InternalUserPrincipal rp = (InternalUserPrincipal)itRemotePrincipal.next(); - if (rp != null) - { - temp.add(rp.getFullPath()); - } - } - - if (temp.size() > 0) - { - - Criteria filter = new Criteria(); - filter.addIn("remotePrincipals.fullPath", temp); - - QueryByCriteria query = QueryFactory.newQuery(SSOCookieImpl.class, filter); - return getPersistenceBrokerTemplate().getCollectionByQuery(query); - } - else - { - return null; - } + // Get the SSO user identified by the fullPath + SSOPrincipal ssoPrincipal = this.getSSOPrincipal(fullPath); + // For each remote user we'll get the cookie + Vector temp = new Vector(); + + Iterator itRemotePrincipal = ssoPrincipal.getRemotePrincipals() + .iterator(); + while (itRemotePrincipal.hasNext()) + { + InternalUserPrincipal rp = (InternalUserPrincipal) itRemotePrincipal + .next(); + if (rp != null) + { + temp.add(rp.getFullPath()); + } + } + + if (temp.size() > 0) + { + + Criteria filter = new Criteria(); + filter.addIn("remotePrincipals.fullPath", temp); + + QueryByCriteria query = QueryFactory.newQuery(SSOCookieImpl.class, + filter); + return getPersistenceBrokerTemplate().getCollectionByQuery(query); + } + else + { + return null; + } + } - + /** * Retrive Cookies by Subject + * * @param user * @return */ public Collection getCookiesForUser(Subject user) { - // Get the principal from the subject - BasePrincipal principal = (BasePrincipal)SecurityHelper.getBestPrincipal(user, UserPrincipal.class); - String fullPath = principal.getFullPath(); - - // Call into API - return this.getCookiesForUser(fullPath); + // Get the principal from the subject + BasePrincipal principal = (BasePrincipal) SecurityHelper + .getBestPrincipal(user, UserPrincipal.class); + String fullPath = principal.getFullPath(); + + // Call into API + return this.getCookiesForUser(fullPath); } - public void setRealmForSite(String site, String realm) throws SSOException { - SSOSite ssoSite = getSSOSiteObject(site); - - if ( ssoSite != null) - { - try - { - ssoSite.setRealm(realm); - getPersistenceBrokerTemplate().store(ssoSite); - } - catch (Exception e) - { - throw new SSOException("Failed to set the realm for site [" + site + "] Error" +e ); - } - } + SSOSite ssoSite = getSSOSiteObject(site); + + if (ssoSite != null) + { + try + { + ssoSite.setRealm(realm); + getPersistenceBrokerTemplate().store(ssoSite); + } + catch (Exception e) + { + throw new SSOException("Failed to set the realm for site [" + + site + "] Error" + e); + } + } } - + public String getRealmForSite(String site) throws SSOException { - SSOSite ssoSite = getSSOSiteObject(site); - - if ( ssoSite != null) - { - return ssoSite.getRealm(); - } - - return null; + SSOSite ssoSite = getSSOSiteObject(site); + + if (ssoSite != null) { return ssoSite.getRealm(); } + + return null; } - + /** * Get all SSOSites that the principal has access to + * * @param userId * @return */ public Collection getSitesForPrincipal(String fullPath) { - - Criteria filter = new Criteria(); + + Criteria filter = new Criteria(); filter.addEqualTo("principals.fullPath", fullPath); - - QueryByCriteria query = QueryFactory.newQuery(SSOSiteImpl.class, filter); - return getPersistenceBrokerTemplate().getCollectionByQuery(query); + + QueryByCriteria query = QueryFactory + .newQuery(SSOSiteImpl.class, filter); + return getPersistenceBrokerTemplate().getCollectionByQuery(query); } - - public Iterator getSites(String filter) + + public Iterator getSites(String filter) { Criteria queryCriteria = new Criteria(); Query query = QueryFactory.newQuery(SSOSiteImpl.class, queryCriteria); - Collection c = getPersistenceBrokerTemplate().getCollectionByQuery(query); - return c.iterator(); + Collection c = getPersistenceBrokerTemplate().getCollectionByQuery( + query); + return c.iterator(); } - - /** + + /** * addCredentialsForSite() + * * @param fullPath * @param remoteUser * @param site * @param pwd * @throws SSOException */ - public void addCredentialsForSite(String fullPath, String remoteUser, String site, String pwd) throws SSOException + public void addCredentialsForSite(String fullPath, String remoteUser, + String site, String pwd) throws SSOException { - // Create a Subject for the given path and forward it to the API addCredentialsForSite() + // Create a Subject for the given path and forward it to the API + // addCredentialsForSite() Principal principal = null; String name = null; - + // Group or User - if (fullPath.indexOf("/group/") > -1 ) + if (fullPath.indexOf("/group/") > -1) { name = fullPath.substring(GROUP_PATH.length()); principal = new GroupPrincipalImpl(name); @@ -309,30 +341,34 @@ name = fullPath.substring(USER_PATH.length()); principal = new UserPrincipalImpl(name); } - + // Create Subject Set principals = new HashSet(); principals.add(principal); - Subject subject = new Subject(true, principals, new HashSet(), new HashSet()); - + Subject subject = new Subject(true, principals, new HashSet(), + new HashSet()); + // Call into the API addCredentialsForSite(subject, remoteUser, site, pwd); } - + /** * removeCredentialsForSite() + * * @param fullPath * @param site * @throws SSOException */ - public void removeCredentialsForSite(String fullPath, String site) throws SSOException + public void removeCredentialsForSite(String fullPath, String site) + throws SSOException { - // Create a Subject for the given path and forward it to the API addCredentialsForSite() + // Create a Subject for the given path and forward it to the API + // addCredentialsForSite() Principal principal = null; String name = null; - + // Group or User - if (fullPath.indexOf("/group/") > -1 ) + if (fullPath.indexOf("/group/") > -1) { name = fullPath.substring(GROUP_PATH.length()); principal = new GroupPrincipalImpl(name); @@ -342,721 +378,771 @@ name = fullPath.substring(USER_PATH.length()); principal = new UserPrincipalImpl(name); } - + // Create Subject Set principals = new HashSet(); principals.add(principal); - Subject subject = new Subject(true, principals, new HashSet(), new HashSet()); - + Subject subject = new Subject(true, principals, new HashSet(), + new HashSet()); + // Call into the API - this.removeCredentialsForSite(subject,site); + this.removeCredentialsForSite(subject, site); } - - - /** Retrive site information + + /** + * Retrive site information * - * getSiteURL + * getSiteURL */ - + public String getSiteURL(String site) { // The site is the URL return site; } - + /** * getSiteName */ public String getSiteName(String site) { SSOSite ssoSite = getSSOSiteObject(site); - - if ( ssoSite != null) - { - return ssoSite.getName(); - } - else - { - return null; - } + + if (ssoSite != null) + { + return ssoSite.getName(); + } + else + { + return null; + } } - - /* (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOProvider#hasSSOCredentials(javax.security.auth.Subject, java.lang.String) - */ - public boolean hasSSOCredentials(Subject subject, String site) { - // Initialization - SSOSite ssoSite = getSSOSiteObject(site); - - if ( ssoSite == null) - { - return false; // no entry for site - } - - // Get the principal from the subject - BasePrincipal principal = (BasePrincipal)SecurityHelper.getBestPrincipal(subject, UserPrincipal.class); - String fullPath = principal.getFullPath(); - - - // Get remotePrincipals for Site and match them with the Remote Principal for the Principal attached to site - Collection remoteForSite = ssoSite.getRemotePrincipals(); - Collection principalsForSite = ssoSite.getPrincipals(); // Users - - // If any of them don't exist just return - if (principalsForSite == null || remoteForSite== null ) - return false; // no entry - - Collection remoteForPrincipals = getRemotePrincipalsForPrincipal(principalsForSite, fullPath); - - if ( remoteForPrincipals == null) - return false; // no entry - - // Get remote Principal that matches the site and the principal - if (findRemoteMatch(remoteForPrincipals, remoteForSite) == null ) - { - return false; // No entry - } - else - { - return true; // Has an entry - } - } - /* (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOProvider#getCredentials(javax.security.auth.Subject, java.lang.String) - */ - public SSOContext getCredentials(Subject subject, String site) - throws SSOException { - - // Initialization - SSOSite ssoSite = getSSOSiteObject(site); - - if ( ssoSite == null) - throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); // no entry for site - - // Get the principal from the subject - BasePrincipal principal = (BasePrincipal)SecurityHelper.getBestPrincipal(subject, UserPrincipal.class); - String fullPath = principal.getFullPath(); - - // Filter the credentials for the given principals - SSOContext context = getCredential(ssoSite, fullPath); - - if ( context == null) - throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); // no entry for site - - return context; - } + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOProvider#hasSSOCredentials(javax.security.auth.Subject, + * java.lang.String) + */ + public boolean hasSSOCredentials(Subject subject, String site) + { + // Initialization + SSOSite ssoSite = getSSOSiteObject(site); - /* addCredential() - * Adds credentials for a user to the site. If the site doesn't exist it will be created - * @see org.apache.jetspeed.sso.SSOProvider#addCredentialsForSite(javax.security.auth.Subject, java.lang.String, java.lang.String) - */ - public void addCredentialsForSite(Subject subject, String remoteUser, String site, String pwd) - throws SSOException { - - // Check if an entry for the site already exists otherwise create a new one - SSOSite ssoSite = getSSOSiteObject(site); - if (ssoSite == null) - { - // Create a new site - ssoSite = new SSOSiteImpl(); - ssoSite.setSiteURL(site); - ssoSite.setName(site); - ssoSite.setCertificateRequired(false); - ssoSite.setAllowUserSet(true); - // By default we use ChallengeResponse Authentication - ssoSite.setChallengeResponseAuthentication(true); - ssoSite.setFormAuthentication(false); - - // Store the site so that we get a valid SSOSiteID - try - { - getPersistenceBrokerTemplate().store(ssoSite); - } - catch (Exception e) - { - e.printStackTrace(); - throw new SSOException(SSOException.FAILED_STORING_SITE_INFO_IN_DB + e.toString() ); - } - } - - // Get the Principal information (logged in user) - String fullPath = ((BasePrincipal)SecurityHelper.getBestPrincipal(subject, UserPrincipal.class)).getFullPath(); - String principalName = ((BasePrincipal)SecurityHelper.getBestPrincipal(subject, UserPrincipal.class)).getName(); - - // Add an entry for the principal to the site if it doesn't exist - SSOPrincipal principal = this.getPrincipalForSite(ssoSite, fullPath); - - if (principal == null ) - { - principal = getSSOPrincipal(fullPath); - ssoSite.addPrincipal(principal); - } - else - { - // Check if the entry the user likes to update exists already - Collection remoteForSite = ssoSite.getRemotePrincipals(); - Collection principalsForSite = ssoSite.getPrincipals(); - - if ( remoteForSite != null && principalsForSite != null) - { - Collection remoteForPrincipals = this.getRemotePrincipalsForPrincipal(principalsForSite, fullPath); - if ( remoteForPrincipals != null) - { - if (findRemoteMatch(remoteForPrincipals, remoteForSite) != null ) - { - // Entry exists can't to an add has to call update - throw new SSOException(SSOException.REMOTE_PRINCIPAL_EXISTS_CALL_UPDATE); - } - } - } - } - - if (principal == null) - throw new SSOException(SSOException.FAILED_ADDING_PRINCIPAL_TO_MAPPING_TABLE_FOR_SITE); - - // Create a remote principal and credentials - InternalUserPrincipalImpl remotePrincipal = new InternalUserPrincipalImpl(remoteUser); - - /* - * The RemotePrincipal (class InternalUserPrincipal) will have a fullPath that identifies the entry as an SSO credential. - * The entry has to be unique for a site and principal (GROUP -or- USER ) an therefore it needs to be encoded as following: - * The convention for the path is the following: /sso/SiteID/{user|group}/{user name | group name}/remote user name - */ - if ( fullPath.indexOf("/group/") > -1) - remotePrincipal.setFullPath("/sso/" + ssoSite.getSiteId() + "/group/"+ principalName + "/" + remoteUser); - else - remotePrincipal.setFullPath("/sso/" + ssoSite.getSiteId() + "/user/"+ principalName + "/" + remoteUser); - - // New credential object for remote principal - InternalCredentialImpl credential = - new InternalCredentialImpl(remotePrincipal.getPrincipalId(), - this.scramble(pwd), 0, DefaultPasswordCredentialImpl.class.getName()); - - if ( remotePrincipal.getCredentials() == null) - remotePrincipal.setCredentials(new ArrayList(0)); - - remotePrincipal.getCredentials().add( credential); - - // Add it to Principals remotePrincipals list - principal.addRemotePrincipal(remotePrincipal); + if (ssoSite == null) { return false; // no entry for site + } - // Update the site remotePrincipals list - ssoSite.getRemotePrincipals().add(remotePrincipal); - - - // Update database and reset cache - try - { - getPersistenceBrokerTemplate().store(ssoSite); - - // Persist Principal/Remote - getPersistenceBrokerTemplate().store(principal); - } - catch (Exception e) - { - e.printStackTrace(); - throw new SSOException(SSOException.FAILED_STORING_SITE_INFO_IN_DB + e.toString() ); - } - - // Add to site - this.mapSite.put(site, ssoSite); - } + // Get the principal from the subject + BasePrincipal principal = (BasePrincipal) SecurityHelper + .getBestPrincipal(subject, UserPrincipal.class); + String fullPath = principal.getFullPath(); - /* (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOProvider#removeCredentialsForSite(javax.security.auth.Subject, java.lang.String) - */ - public void removeCredentialsForSite(Subject subject, String site) - throws SSOException { - - // Initailization - InternalUserPrincipal remotePrincipal = null; - //Get the site - SSOSite ssoSite = getSSOSiteObject(site); - if (ssoSite == null) - { - throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); - } - - // Get the Principal information - String fullPath = ((BasePrincipal)SecurityHelper.getBestPrincipal(subject, UserPrincipal.class)).getFullPath(); - - try - { - // Get remotePrincipals for Site and match them with the Remote Principal for the Principal attached to site - Collection principalsForSite = ssoSite.getPrincipals(); - Collection remoteForSite = ssoSite.getRemotePrincipals(); - - // If any of them don't exist just return - if (principalsForSite == null || remoteForSite== null ) - throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); - - Collection remoteForPrincipals = getRemotePrincipalsForPrincipal(principalsForSite, fullPath); - - if ( remoteForPrincipals == null) - throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); - - // Get remote Principal that matches the site and the principal - if ((remotePrincipal = findRemoteMatch(remoteForPrincipals, remoteForSite)) == null ) - { - throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); - } + // Get remotePrincipals for Site and match them with the Remote + // Principal for the Principal attached to site + Collection remoteForSite = ssoSite.getRemotePrincipals(); + Collection principalsForSite = ssoSite.getPrincipals(); // Users - // Update assocation tables - ssoSite.getRemotePrincipals().remove(remotePrincipal); - - if (remoteForPrincipals.remove(remotePrincipal) == true) - - // Update the site - getPersistenceBrokerTemplate().store(ssoSite); + // If any of them don't exist just return + if (principalsForSite == null || remoteForSite == null) return false; // no + // entry - // delete the remote Principal from the SECURITY_PRINCIPAL table - getPersistenceBrokerTemplate().delete(remotePrincipal); - - - } - catch(SSOException ssoex) - { - throw new SSOException(ssoex); - } - catch (Exception e) + Collection remoteForPrincipals = getRemotePrincipalsForPrincipal( + principalsForSite, fullPath); + + if (remoteForPrincipals == null) return false; // no entry + + // Get remote Principal that matches the site and the principal + if (findRemoteMatch(remoteForPrincipals, remoteForSite) == null) { - e.printStackTrace(); - // current OJB model implementation isn't 100% correct, make sure no stale/broken state is left behind + return false; // No entry + } + else + { + return true; // Has an entry + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOProvider#getCredentials(javax.security.auth.Subject, + * java.lang.String) + */ + public SSOContext getCredentials(Subject subject, String site) + throws SSOException + { + + // Initialization + SSOSite ssoSite = getSSOSiteObject(site); + + if (ssoSite == null) + throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); // no + // entry + // for + // site + + // Get the principal from the subject + BasePrincipal principal = (BasePrincipal) SecurityHelper + .getBestPrincipal(subject, UserPrincipal.class); + String fullPath = principal.getFullPath(); + + // Filter the credentials for the given principals + SSOContext context = getCredential(ssoSite, fullPath); + + if (context == null) + throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); // no + // entry + // for + // site + + return context; + } + + /* + * addCredential() Adds credentials for a user to the site. If the site + * doesn't exist it will be created + * + * @see org.apache.jetspeed.sso.SSOProvider#addCredentialsForSite(javax.security.auth.Subject, + * java.lang.String, java.lang.String) + */ + public void addCredentialsForSite(Subject subject, String remoteUser, + String site, String pwd) throws SSOException + { + + // Check if an entry for the site already exists otherwise create a new + // one + SSOSite ssoSite = getSSOSiteObject(site); + if (ssoSite == null) + { + // Create a new site + ssoSite = new SSOSiteImpl(); + ssoSite.setSiteURL(site); + ssoSite.setName(site); + ssoSite.setCertificateRequired(false); + ssoSite.setAllowUserSet(true); + // By default we use ChallengeResponse Authentication + ssoSite.setChallengeResponseAuthentication(true); + ssoSite.setFormAuthentication(false); + + // Store the site so that we get a valid SSOSiteID + try + { + getPersistenceBrokerTemplate().store(ssoSite); + } + catch (Exception e) + { + e.printStackTrace(); + throw new SSOException( + SSOException.FAILED_STORING_SITE_INFO_IN_DB + + e.toString()); + } + } + + // Get the Principal information (logged in user) + String fullPath = ((BasePrincipal) SecurityHelper.getBestPrincipal( + subject, UserPrincipal.class)).getFullPath(); + String principalName = ((BasePrincipal) SecurityHelper + .getBestPrincipal(subject, UserPrincipal.class)).getName(); + + // Add an entry for the principal to the site if it doesn't exist + SSOPrincipal principal = this.getPrincipalForSite(ssoSite, fullPath); + + if (principal == null) + { + principal = getSSOPrincipal(fullPath); + ssoSite.addPrincipal(principal); + } + else + { + // Check if the entry the user likes to update exists already + Collection remoteForSite = ssoSite.getRemotePrincipals(); + Collection principalsForSite = ssoSite.getPrincipals(); + + if (remoteForSite != null && principalsForSite != null) + { + Collection remoteForPrincipals = this + .getRemotePrincipalsForPrincipal(principalsForSite, + fullPath); + if (remoteForPrincipals != null) + { + if (findRemoteMatch(remoteForPrincipals, remoteForSite) != null) + { + // Entry exists can't to an add has to call update + throw new SSOException( + SSOException.REMOTE_PRINCIPAL_EXISTS_CALL_UPDATE); + } + } + } + } + + if (principal == null) + throw new SSOException( + SSOException.FAILED_ADDING_PRINCIPAL_TO_MAPPING_TABLE_FOR_SITE); + + // Create a remote principal and credentials + InternalUserPrincipalImpl remotePrincipal = new InternalUserPrincipalImpl( + remoteUser); + + /* + * The RemotePrincipal (class InternalUserPrincipal) will have a + * fullPath that identifies the entry as an SSO credential. The entry + * has to be unique for a site and principal (GROUP -or- USER ) an + * therefore it needs to be encoded as following: The convention for the + * path is the following: /sso/SiteID/{user|group}/{user name | group + * name}/remote user name + */ + if (fullPath.indexOf("/group/") > -1) + remotePrincipal.setFullPath("/sso/" + ssoSite.getSiteId() + + "/group/" + principalName + "/" + remoteUser); + else + remotePrincipal.setFullPath("/sso/" + ssoSite.getSiteId() + + "/user/" + principalName + "/" + remoteUser); + + // New credential object for remote principal + InternalCredentialImpl credential = new InternalCredentialImpl( + remotePrincipal.getPrincipalId(), this.scramble(pwd), 0, + DefaultPasswordCredentialImpl.class.getName()); + + if (remotePrincipal.getCredentials() == null) + remotePrincipal.setCredentials(new ArrayList(0)); + + remotePrincipal.getCredentials().add(credential); + + // Add it to Principals remotePrincipals list + principal.addRemotePrincipal(remotePrincipal); + + // Update the site remotePrincipals list + ssoSite.getRemotePrincipals().add(remotePrincipal); + + // Update database and reset cache + try + { + getPersistenceBrokerTemplate().store(ssoSite); + + // Persist Principal/Remote + getPersistenceBrokerTemplate().store(principal); + } + catch (Exception e) + { + e.printStackTrace(); + throw new SSOException(SSOException.FAILED_STORING_SITE_INFO_IN_DB + + e.toString()); + } + + // Add to site + this.mapSite.put(site, ssoSite); + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOProvider#removeCredentialsForSite(javax.security.auth.Subject, + * java.lang.String) + */ + public void removeCredentialsForSite(Subject subject, String site) + throws SSOException + { + + // Initailization + InternalUserPrincipal remotePrincipal = null; + // Get the site + SSOSite ssoSite = getSSOSiteObject(site); + if (ssoSite == null) { throw new SSOException( + SSOException.NO_CREDENTIALS_FOR_SITE); } + + // Get the Principal information + String fullPath = ((BasePrincipal) SecurityHelper.getBestPrincipal( + subject, UserPrincipal.class)).getFullPath(); + + try + { + // Get remotePrincipals for Site and match them with the Remote + // Principal for the Principal attached to site + Collection principalsForSite = ssoSite.getPrincipals(); + Collection remoteForSite = ssoSite.getRemotePrincipals(); + + // If any of them don't exist just return + if (principalsForSite == null || remoteForSite == null) + throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); + + Collection remoteForPrincipals = getRemotePrincipalsForPrincipal( + principalsForSite, fullPath); + + if (remoteForPrincipals == null) + throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); + + // Get remote Principal that matches the site and the principal + if ((remotePrincipal = findRemoteMatch(remoteForPrincipals, + remoteForSite)) == null) { throw new SSOException( + SSOException.NO_CREDENTIALS_FOR_SITE); } + + // Update assocation tables + ssoSite.getRemotePrincipals().remove(remotePrincipal); + + if (remoteForPrincipals.remove(remotePrincipal) == true) + + // Update the site + getPersistenceBrokerTemplate().store(ssoSite); + + // delete the remote Principal from the SECURITY_PRINCIPAL table + getPersistenceBrokerTemplate().delete(remotePrincipal); + + } + catch (SSOException ssoex) + { + throw new SSOException(ssoex); + } + catch (Exception e) + { + e.printStackTrace(); + // current OJB model implementation isn't 100% correct, make sure no + // stale/broken state is left behind mapSite.remove(site); - throw new SSOException(SSOException.FAILED_STORING_SITE_INFO_IN_DB + e.toString() ); + throw new SSOException(SSOException.FAILED_STORING_SITE_INFO_IN_DB + + e.toString()); } - - // Update database - try - { - getPersistenceBrokerTemplate().store(ssoSite); - } - catch (Exception e) - { - e.printStackTrace(); - throw new SSOException(SSOException.FAILED_STORING_SITE_INFO_IN_DB + e.toString() ); - } - finally - { - // current OJB model implementation isn't 100% correct, make sure no stale/broken state is left behind - mapSite.remove(site); - } - - } - - /** - * updateCredentialsForSite - * @param subject Current subject - * @param remoteUser remote user login - * @param site URL or description of site - * @param pwd Password for credentail - */ - public void updateCredentialsForSite(Subject subject, String remoteUser, String site, String pwd) - throws SSOException - { - // Check if the the current user has a credential for the site - - // Update the credential - // Initailization - InternalUserPrincipal remotePrincipal = null; - - //Get the site - SSOSite ssoSite = getSSOSiteObject(site); - if (ssoSite == null) - { - throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); - } - - // Get the Principal information - String fullPath = ((BasePrincipal)SecurityHelper.getBestPrincipal(subject, UserPrincipal.class)).getFullPath(); - - // Get remotePrincipals for Site and match them with the Remote Principal for the Principal attached to site - Collection principalsForSite = ssoSite.getPrincipals(); - Collection remoteForSite = ssoSite.getRemotePrincipals(); - - // If any of them don't exist just return - if (principalsForSite == null || remoteForSite== null ) - throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); - - Collection remoteForPrincipals = getRemotePrincipalsForPrincipal(principalsForSite, fullPath); - - if ( remoteForPrincipals == null) - throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); - - // Get remote Principal that matches the site and the principal - if ((remotePrincipal = findRemoteMatch(remoteForPrincipals, remoteForSite)) == null ) - { - throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); - } - - // Update principal information - //remotePrincipal.setFullPath("/sso/" + ssoSite.getSiteId() + "/user/"+ principalName + "/" + remoteUser); - - InternalCredential credential = (InternalCredential)remotePrincipal.getCredentials().iterator().next(); - - // New credential object - if ( credential != null) - // Remove credential and principal from mapping - credential.setValue(this.scramble(pwd)); - - // Update database and reset cache - try - { - getPersistenceBrokerTemplate().store(credential); - } - catch (Exception e) - { - e.printStackTrace(); - throw new SSOException(SSOException.FAILED_STORING_SITE_INFO_IN_DB + e.toString() ); - } - } - - /* - * Helper utilities - * - */ - - /* - * getSSOSiteObject - * Obtains the Site information including the credentials for a site (url). - */ - - private SSOSite getSSOSiteObject(String site) - { - //Initialization - SSOSite ssoSite = null; - - //Check if the site is in the map - if (mapSite.containsKey(site) == false ) - { - // Go to the database and fetch the information for this site - // Find the MediaType by matching the Mimetype - - Criteria filter = new Criteria(); - filter.addEqualTo("siteURL", site); - - QueryByCriteria query = QueryFactory.newQuery(SSOSiteImpl.class, filter); - Collection ssoSiteCollection = getPersistenceBrokerTemplate().getCollectionByQuery(query); - - if ( ssoSiteCollection != null && ssoSiteCollection.isEmpty() != true) - { - Iterator itSite = ssoSiteCollection.iterator(); - // Get the site from the collection. There should be only one entry (uniqueness) - if (itSite.hasNext()) - { - ssoSite = (SSOSite) itSite.next(); - } - - // Add it to the map - mapSite.put(site, ssoSite); - } - else - { - // No entry for this site - return null; - } - } - else - { - ssoSite = (SSOSite)mapSite.get(site); - } - - return ssoSite; - } - - /* - * getCredential - * returns the credentials for a given user - */ - private SSOContext getCredential(SSOSite ssoSite, String fullPath) - { - InternalCredential credential = null; - InternalUserPrincipal remotePrincipal = null; - // Get remotePrincipals for Site and match them with the Remote Principal for the Principal attached to site - Collection principalsForSite = ssoSite.getPrincipals(); - Collection remoteForSite = ssoSite.getRemotePrincipals(); - - // If any of them don't exist just return - if ( principalsForSite == null || remoteForSite== null ) - return null; // no entry - - Collection remoteForPrincipals = getRemotePrincipalsForPrincipal(principalsForSite, fullPath); - - if ( remoteForPrincipals == null) - return null; // no entry - - // Get remote Principal that matches the site and the principal - if ((remotePrincipal = findRemoteMatch(remoteForPrincipals, remoteForSite)) == null ) - { - return null; // No entry - } - else - { - // Has an entry - if ( remotePrincipal.getCredentials() != null) - credential = (InternalCredential)remotePrincipal.getCredentials().iterator().next(); - - // Error checking -- should have a credential at this point - if ( credential == null) - { -// System.out.println("Warning: Remote User " + remotePrincipal.getFullPath() + " doesn't have a credential"); - return null; - } - } - - // Create new context - String name = stripPrincipalName(remotePrincipal.getFullPath()); - - SSOContext context = new SSOContextImpl(credential.getPrincipalId(), name, this.unscramble(credential.getValue())); - - return context; - } - + + // Update database + try + { + getPersistenceBrokerTemplate().store(ssoSite); + } + catch (Exception e) + { + e.printStackTrace(); + throw new SSOException(SSOException.FAILED_STORING_SITE_INFO_IN_DB + + e.toString()); + } + finally + { + // current OJB model implementation isn't 100% correct, make sure no + // stale/broken state is left behind + mapSite.remove(site); + } + + } + + /** + * updateCredentialsForSite + * + * @param subject + * Current subject + * @param remoteUser + * remote user login + * @param site + * URL or description of site + * @param pwd + * Password for credentail + */ + public void updateCredentialsForSite(Subject subject, String remoteUser, + String site, String pwd) throws SSOException + { + // Check if the the current user has a credential for the site + + // Update the credential + // Initailization + InternalUserPrincipal remotePrincipal = null; + + // Get the site + SSOSite ssoSite = getSSOSiteObject(site); + if (ssoSite == null) { throw new SSOException( + SSOException.NO_CREDENTIALS_FOR_SITE); } + + // Get the Principal information + String fullPath = ((BasePrincipal) SecurityHelper.getBestPrincipal( + subject, UserPrincipal.class)).getFullPath(); + + // Get remotePrincipals for Site and match them with the Remote + // Principal for the Principal attached to site + Collection principalsForSite = ssoSite.getPrincipals(); + Collection remoteForSite = ssoSite.getRemotePrincipals(); + + // If any of them don't exist just return + if (principalsForSite == null || remoteForSite == null) + throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); + + Collection remoteForPrincipals = getRemotePrincipalsForPrincipal( + principalsForSite, fullPath); + + if (remoteForPrincipals == null) + throw new SSOException(SSOException.NO_CREDENTIALS_FOR_SITE); + + // Get remote Principal that matches the site and the principal + if ((remotePrincipal = findRemoteMatch(remoteForPrincipals, + remoteForSite)) == null) { throw new SSOException( + SSOException.NO_CREDENTIALS_FOR_SITE); } + + // Update principal information + // remotePrincipal.setFullPath("/sso/" + ssoSite.getSiteId() + "/user/"+ + // principalName + "/" + remoteUser); + + InternalCredential credential = (InternalCredential) remotePrincipal + .getCredentials().iterator().next(); + + // New credential object + if (credential != null) + // Remove credential and principal from mapping + credential.setValue(this.scramble(pwd)); + + // Update database and reset cache + try + { + getPersistenceBrokerTemplate().store(credential); + } + catch (Exception e) + { + e.printStackTrace(); + throw new SSOException(SSOException.FAILED_STORING_SITE_INFO_IN_DB + + e.toString()); + } + } + + /* + * Helper utilities + * + */ + + /* + * getSSOSiteObject Obtains the Site information including the credentials + * for a site (url). + */ + + private SSOSite getSSOSiteObject(String site) + { + // Initialization + SSOSite ssoSite = null; + + // Check if the site is in the map + if (mapSite.containsKey(site) == false) + { + // Go to the database and fetch the information for this site + // Find the MediaType by matching the Mimetype + + Criteria filter = new Criteria(); + filter.addEqualTo("siteURL", site); + + QueryByCriteria query = QueryFactory.newQuery(SSOSiteImpl.class, + filter); + Collection ssoSiteCollection = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); + + if (ssoSiteCollection != null + && ssoSiteCollection.isEmpty() != true) + { + Iterator itSite = ssoSiteCollection.iterator(); + // Get the site from the collection. There should be only one + // entry (uniqueness) + if (itSite.hasNext()) + { + ssoSite = (SSOSite) itSite.next(); + } + + // Add it to the map + mapSite.put(site, ssoSite); + } + else + { + // No entry for this site + return null; + } + } + else + { + ssoSite = (SSOSite) mapSite.get(site); + } + + return ssoSite; + } + + /* + * getCredential returns the credentials for a given user + */ + private SSOContext getCredential(SSOSite ssoSite, String fullPath) + { + InternalCredential credential = null; + InternalUserPrincipal remotePrincipal = null; + // Get remotePrincipals for Site and match them with the Remote + // Principal for the Principal attached to site + Collection principalsForSite = ssoSite.getPrincipals(); + Collection remoteForSite = ssoSite.getRemotePrincipals(); + + // If any of them don't exist just return + if (principalsForSite == null || remoteForSite == null) return null; // no + // entry + + Collection remoteForPrincipals = getRemotePrincipalsForPrincipal( + principalsForSite, fullPath); + + if (remoteForPrincipals == null) return null; // no entry + + // Get remote Principal that matches the site and the principal + if ((remotePrincipal = findRemoteMatch(remoteForPrincipals, + remoteForSite)) == null) + { + return null; // No entry + } + else + { + // Has an entry + if (remotePrincipal.getCredentials() != null) + credential = (InternalCredential) remotePrincipal + .getCredentials().iterator().next(); + + // Error checking -- should have a credential at this point + if (credential == null) + { + // System.out.println("Warning: Remote User " + + // remotePrincipal.getFullPath() + " doesn't have a + // credential"); + return null; + } + } + + // Create new context + String name = stripPrincipalName(remotePrincipal.getFullPath()); + + SSOContext context = new SSOContextImpl(credential.getPrincipalId(), + name, this.unscramble(credential.getValue())); + + return context; + } + private String stripPrincipalName(String fullPath) { String name; int ix = fullPath.lastIndexOf('/'); - if ( ix != -1) + if (ix != -1) name = fullPath.substring(ix + 1); else name = new String(fullPath); - - return name; + + return name; } - /* - * Get a Collection of remote Principals for the logged in principal identified by the full path - * - private Collection getRemotePrincipalsForPrincipal(SSOSite ssoSite, String fullPath) - { - // The site orincipals list contains a list of remote principals for the user - Collection principals = ssoSite.getPrincipals(); - - if ( principals == null ) - return null; // No principals for this site - - Iterator ixPrincipals = principals.iterator(); - while (ixPrincipals.hasNext()) - { - SSOPrincipal principal = (SSOPrincipal)ixPrincipals.next(); - if ( principal != null - && principal.getFullPath().compareToIgnoreCase(fullPath) == 0 ) - { - // Found Principal -- extract remote principals - return principal.getRemotePrincipals(); - } - } - - // Principal is not in list - return null; - } - */ - - /* - * getPrincipalForSite() - * returns a principal that matches the full path for the site or creates a new entry if it doesn't exist - */ - private SSOPrincipal getPrincipalForSite(SSOSite ssoSite, String fullPath) - { - SSOPrincipal principal = null; - Collection principalsForSite = ssoSite.getPrincipals(); - - if ( principalsForSite != null) - { - Iterator itPrincipals = principalsForSite.iterator(); - while (itPrincipals.hasNext() && principal == null) - { - SSOPrincipal tmp = (SSOPrincipal)itPrincipals.next(); - if ( tmp != null - && tmp.getFullPath().compareToIgnoreCase(fullPath) == 0 ) - principal = tmp; // Found existing entry - } - } - - return principal; - } - - private SSOPrincipal getSSOPrincipal(String fullPath) - { - // FInd if the principal exists in the SECURITY_PRINCIPAL table - SSOPrincipal principal = null; - - Criteria filter = new Criteria(); - filter.addEqualTo("fullPath", fullPath); - - QueryByCriteria query = QueryFactory.newQuery(SSOPrincipalImpl.class, filter); - Collection principals = getPersistenceBrokerTemplate().getCollectionByQuery(query); - - if ( principals != null && principals.isEmpty() != true) - { - Iterator itPrincipals = principals.iterator(); - // Get the site from the collection. There should be only one entry (uniqueness) - if (itPrincipals.hasNext()) - { - principal = (SSOPrincipal) itPrincipals.next(); - } - } - - return principal; - } - - - - /** - * removeRemotePrincipalForPrincipal - * @param site - * @param fullPath - * @return - * - * removes remotePrincipal for a site & principal - * - private InternalUserPrincipal removeRemotePrincipalForPrincipal(SSOSite site, String fullPath) throws SSOException - { - if (site.getPrincipals() != null) - { - Iterator itPrincipals = site.getPrincipals().iterator(); - while (itPrincipals.hasNext()) - { - SSOPrincipal tmp = (SSOPrincipal)itPrincipals.next(); - if (tmp.getFullPath().compareToIgnoreCase(fullPath) == 0) - { - // Found -- get the remotePrincipal - Collection collRemotePrincipals = tmp.getRemotePrincipals() ; - if (collRemotePrincipals != null) - { - - Iterator itRemotePrincipals = collRemotePrincipals.iterator(); - if (itRemotePrincipals.hasNext()) - { - InternalUserPrincipal remotePrincipal = (InternalUserPrincipal)itRemotePrincipals.next(); - // Found remove the object - collRemotePrincipals.remove(remotePrincipal); - return remotePrincipal; - } - } - } - } - } - - throw new SSOException(SSOException.REQUESTED_PRINCIPAL_DOES_NOT_EXIST); - } - */ - - /* - * - * - */ - private InternalUserPrincipal findRemoteMatch(Collection remoteForPrincipals, Collection remoteForSite) - { - // Iterate over the lists and find match - Iterator itRemoteForPrincipals = remoteForPrincipals.iterator(); - while ( itRemoteForPrincipals.hasNext()) - { - InternalUserPrincipal remoteForPrincipal = (InternalUserPrincipal)itRemoteForPrincipals.next(); - - // Find a match in the site list - Iterator itRemoteForSite = remoteForSite.iterator(); - while ( itRemoteForSite.hasNext()) - { - InternalUserPrincipal tmp = (InternalUserPrincipal)itRemoteForSite.next(); - - if ( tmp.getPrincipalId() == remoteForPrincipal.getPrincipalId() ) - return remoteForPrincipal; - } - } - // No match found - return null; - } - - /* - * getRemotePrincipalsForPrincipals - * Checks if the user has any remote principals. If the principal is a group expand the group and - * check if the requesting user is a part of the group. - */ - private Collection getRemotePrincipalsForPrincipal(Collection principalsForSite, String fullPath) - { - if (principalsForSite != null ) - { - Iterator itPrincipalsForSite = principalsForSite.iterator(); - while (itPrincipalsForSite.hasNext()) - { - String principalFullPath = null; - SSOPrincipal principal = (SSOPrincipal)itPrincipalsForSite.next(); - principalFullPath = principal.getFullPath(); - - /* If the Principal is for a Group expand the Group and check if the user identified - * by the fullPath is a member of the Group. If the user is a member of the Group - * return the remote Credentials for the current Principal. - */ - if ( principalFullPath.indexOf("/group/") == -1) - { - // USER - if ( principalFullPath.compareToIgnoreCase(fullPath) == 0) - return principal.getRemotePrincipals(); - } - else - { - /* GROUP - * If the full path is for a group (delete/add) just return the the list of remotePrincipals - * For a lookup (hasCredentials) the user needs to be mapped against each member of the group - */ - if ( principalFullPath.compareToIgnoreCase(fullPath) == 0) - return principal.getRemotePrincipals(); - - /* Expand the Group and find a match */ - InternalGroupPrincipal groupPrincipal = getGroupPrincipals(principalFullPath); - - // Found Group that matches the name - if (groupPrincipal != null) - { - Collection usersInGroup = groupPrincipal.getUserPrincipals(); - Iterator itUsers = usersInGroup.iterator(); - while (itUsers.hasNext()) - { - InternalUserPrincipal user = (InternalUserPrincipal)itUsers.next(); - if (user.getFullPath().compareToIgnoreCase(fullPath) == 0) - { - // User is member of the group - return principal.getRemotePrincipals(); - } - } - } - } - } - } - - // No match found - return null; - } - + /* + * Get a Collection of remote Principals for the logged in principal + * identified by the full path + * + * private Collection getRemotePrincipalsForPrincipal(SSOSite ssoSite, + * String fullPath) { // The site orincipals list contains a list of remote + * principals for the user Collection principals = ssoSite.getPrincipals(); + * + * if ( principals == null ) return null; // No principals for this site + * + * Iterator ixPrincipals = principals.iterator(); while + * (ixPrincipals.hasNext()) { SSOPrincipal principal = + * (SSOPrincipal)ixPrincipals.next(); if ( principal != null && + * principal.getFullPath().compareToIgnoreCase(fullPath) == 0 ) { // Found + * Principal -- extract remote principals return + * principal.getRemotePrincipals(); } } // Principal is not in list return + * null; } + */ + + /* + * getPrincipalForSite() returns a principal that matches the full path for + * the site or creates a new entry if it doesn't exist + */ + private SSOPrincipal getPrincipalForSite(SSOSite ssoSite, String fullPath) + { + SSOPrincipal principal = null; + Collection principalsForSite = ssoSite.getPrincipals(); + + if (principalsForSite != null) + { + Iterator itPrincipals = principalsForSite.iterator(); + while (itPrincipals.hasNext() && principal == null) + { + SSOPrincipal tmp = (SSOPrincipal) itPrincipals.next(); + if (tmp != null + && tmp.getFullPath().compareToIgnoreCase(fullPath) == 0) + principal = tmp; // Found existing entry + } + } + + return principal; + } + + private SSOPrincipal getSSOPrincipal(String fullPath) + { + // FInd if the principal exists in the SECURITY_PRINCIPAL table + SSOPrincipal principal = null; + + Criteria filter = new Criteria(); + filter.addEqualTo("fullPath", fullPath); + + QueryByCriteria query = QueryFactory.newQuery(SSOPrincipalImpl.class, + filter); + Collection principals = getPersistenceBrokerTemplate() + .getCollectionByQuery(query); + + if (principals != null && principals.isEmpty() != true) + { + Iterator itPrincipals = principals.iterator(); + // Get the site from the collection. There should be only one entry + // (uniqueness) + if (itPrincipals.hasNext()) + { + principal = (SSOPrincipal) itPrincipals.next(); + } + } + + return principal; + } + + /** + * removeRemotePrincipalForPrincipal + * + * @param site + * @param fullPath + * @return + * + * removes remotePrincipal for a site & principal + * + * private InternalUserPrincipal removeRemotePrincipalForPrincipal(SSOSite + * site, String fullPath) throws SSOException { if (site.getPrincipals() != + * null) { Iterator itPrincipals = site.getPrincipals().iterator(); while + * (itPrincipals.hasNext()) { SSOPrincipal tmp = + * (SSOPrincipal)itPrincipals.next(); if + * (tmp.getFullPath().compareToIgnoreCase(fullPath) == 0) { // Found -- get + * the remotePrincipal Collection collRemotePrincipals = + * tmp.getRemotePrincipals() ; if (collRemotePrincipals != null) { + * + * Iterator itRemotePrincipals = collRemotePrincipals.iterator(); if + * (itRemotePrincipals.hasNext()) { InternalUserPrincipal remotePrincipal = + * (InternalUserPrincipal)itRemotePrincipals.next(); // Found remove the + * object collRemotePrincipals.remove(remotePrincipal); return + * remotePrincipal; } } } } } + * + * throw new SSOException(SSOException.REQUESTED_PRINCIPAL_DOES_NOT_EXIST); } + */ + + /* + * + * + */ + private InternalUserPrincipal findRemoteMatch( + Collection remoteForPrincipals, Collection remoteForSite) + { + // Iterate over the lists and find match + Iterator itRemoteForPrincipals = remoteForPrincipals.iterator(); + while (itRemoteForPrincipals.hasNext()) + { + InternalUserPrincipal remoteForPrincipal = (InternalUserPrincipal) itRemoteForPrincipals + .next(); + + // Find a match in the site list + Iterator itRemoteForSite = remoteForSite.iterator(); + while (itRemoteForSite.hasNext()) + { + InternalUserPrincipal tmp = (InternalUserPrincipal) itRemoteForSite + .next(); + + if (tmp.getPrincipalId() == remoteForPrincipal.getPrincipalId()) + return remoteForPrincipal; + } + } + // No match found + return null; + } + + /* + * getRemotePrincipalsForPrincipals Checks if the user has any remote + * principals. If the principal is a group expand the group and check if the + * requesting user is a part of the group. + */ + private Collection getRemotePrincipalsForPrincipal( + Collection principalsForSite, String fullPath) + { + if (principalsForSite != null) + { + Iterator itPrincipalsForSite = principalsForSite.iterator(); + while (itPrincipalsForSite.hasNext()) + { + String principalFullPath = null; + SSOPrincipal principal = (SSOPrincipal) itPrincipalsForSite + .next(); + principalFullPath = principal.getFullPath(); + + /* + * If the Principal is for a Group expand the Group and check if + * the user identified by the fullPath is a member of the Group. + * If the user is a member of the Group return the remote + * Credentials for the current Principal. + */ + if (principalFullPath.indexOf("/group/") == -1) + { + // USER + if (principalFullPath.compareToIgnoreCase(fullPath) == 0) + return principal.getRemotePrincipals(); + } + else + { + /* + * GROUP If the full path is for a group (delete/add) just + * return the the list of remotePrincipals For a lookup + * (hasCredentials) the user needs to be mapped against each + * member of the group + */ + if (principalFullPath.compareToIgnoreCase(fullPath) == 0) + return principal.getRemotePrincipals(); + + /* Expand the Group and find a match */ + InternalGroupPrincipal groupPrincipal = getGroupPrincipals(principalFullPath); + + // Found Group that matches the name + if (groupPrincipal != null) + { + Collection usersInGroup = groupPrincipal + .getUserPrincipals(); + Iterator itUsers = usersInGroup.iterator(); + while (itUsers.hasNext()) + { + InternalUserPrincipal user = (InternalUserPrincipal) itUsers + .next(); + if (user.getFullPath() + .compareToIgnoreCase(fullPath) == 0) + { + // User is member of the group + return principal.getRemotePrincipals(); + } + } + } + } + } + } + + // No match found + return null; + } + public SSOSite getSite(String siteUrl) { Criteria filter = new Criteria(); filter.addEqualTo("url", siteUrl); Query query = QueryFactory.newQuery(SSOSiteImpl.class, filter); - SSOSite site = (SSOSite) getPersistenceBrokerTemplate().getObjectByQuery(query); - return site; + SSOSite site = (SSOSite) getPersistenceBrokerTemplate() + .getObjectByQuery(query); + return site; } - - public void updateSite(SSOSite site) - throws SSOException + + public void updateSite(SSOSite site) throws SSOException { try { getPersistenceBrokerTemplate().store(site); - this.mapSite.put(site.getName(), site); + this.mapSite.put(site.getName(), site); } catch (Exception e) { String msg = "Unable to remove SSO Site: " + site.getName(); logger.error(msg, e); throw new SSOException(msg, e); - } + } } - + /** * Add a new site that uses Form Authentication + * * @param siteName * @param siteUrl * @param realm @@ -1064,10 +1150,11 @@ * @param pwdField * @throws SSOException */ - public void addSiteFormAuthenticated(String siteName, String siteUrl, String realm, String userField, String pwdField) - throws SSOException + public void addSiteFormAuthenticated(String siteName, String siteUrl, + String realm, String userField, String pwdField) + throws SSOException { - try + try { SSOSite ssoSite = new SSOSiteImpl(); ssoSite.setSiteURL(siteUrl); @@ -1079,27 +1166,28 @@ ssoSite.setFormUserField(userField); ssoSite.setFormPwdField(pwdField); getPersistenceBrokerTemplate().store(ssoSite); - this.mapSite.put(siteName, ssoSite); + this.mapSite.put(siteName, ssoSite); } catch (Exception e) { String msg = "Unable to add SSO Site: " + siteName; logger.error(msg, e); throw new SSOException(msg, e); - } + } } - + /** * Add a new site that uses ChallengeResponse Authentication + * * @param siteName * @param siteUrl * @param realm * @throws SSOException */ - public void addSiteChallengeResponse(String siteName, String siteUrl, String realm) - throws SSOException + public void addSiteChallengeResponse(String siteName, String siteUrl, + String realm) throws SSOException { - try + try { SSOSite ssoSite = new SSOSiteImpl(); ssoSite.setSiteURL(siteUrl); @@ -1108,19 +1196,18 @@ ssoSite.setAllowUserSet(true); ssoSite.setRealm(realm); ssoSite.setChallengeResponseAuthentication(true); - getPersistenceBrokerTemplate().store(ssoSite); - this.mapSite.put(siteName, ssoSite); + getPersistenceBrokerTemplate().store(ssoSite); + this.mapSite.put(siteName, ssoSite); } catch (Exception e) { String msg = "Unable to add SSO Site: " + siteName; logger.error(msg, e); throw new SSOException(msg, e); - } + } } - - public void addSite(String siteName, String siteUrl) - throws SSOException + + public void addSite(String siteName, String siteUrl) throws SSOException { try { @@ -1128,20 +1215,19 @@ ssoSite.setSiteURL(siteUrl); ssoSite.setName(siteName); ssoSite.setCertificateRequired(false); - ssoSite.setAllowUserSet(true); + ssoSite.setAllowUserSet(true); getPersistenceBrokerTemplate().store(ssoSite); - this.mapSite.put(siteName, ssoSite); + this.mapSite.put(siteName, ssoSite); } catch (Exception e) { String msg = "Unable to remove SSO Site: " + siteName; logger.error(msg, e); throw new SSOException(msg, e); - } + } } - - public void removeSite(SSOSite site) - throws SSOException + + public void removeSite(SSOSite site) throws SSOException { try { @@ -1154,31 +1240,31 @@ String msg = "Unable to remove SSO Site: " + site.getName(); logger.error(msg, e); throw new SSOException(msg, e); - } + } } - + public List getPrincipalsForSite(SSOSite site) { List list = new ArrayList(); Iterator principals = site.getRemotePrincipals().iterator(); while (principals.hasNext()) { - InternalUserPrincipal remotePrincipal = (InternalUserPrincipal)principals.next(); + InternalUserPrincipal remotePrincipal = (InternalUserPrincipal) principals + .next(); Iterator creds = remotePrincipal.getCredentials().iterator(); while (creds.hasNext()) { InternalCredential cred = (InternalCredential) creds.next(); - SSOContext context = new SSOContextImpl(remotePrincipal.getPrincipalId(), - stripPrincipalName(remotePrincipal.getFullPath()), - cred.getValue(), - stripPortalPrincipalName(remotePrincipal.getFullPath())); + SSOContext context = new SSOContextImpl(remotePrincipal + .getPrincipalId(), stripPrincipalName(remotePrincipal + .getFullPath()), cred.getValue(), + stripPortalPrincipalName(remotePrincipal.getFullPath())); list.add(context); } } return list; } - private String stripPortalPrincipalName(String fullPath) { StringTokenizer tokenizer = new StringTokenizer(fullPath, "/"); @@ -1187,256 +1273,312 @@ String token = tokenizer.nextToken(); if (token.equals("user") || token.equals("group")) { - if (tokenizer.hasMoreTokens()) - { - return tokenizer.nextToken(); - } + if (tokenizer.hasMoreTokens()) { return tokenizer.nextToken(); } } } - return fullPath; + return fullPath; } - - private InternalGroupPrincipal getGroupPrincipals(String principalFullPath) + + private InternalGroupPrincipal getGroupPrincipals(String principalFullPath) { // Get to the backend to return the group that matches the full path Criteria filter = new Criteria(); filter.addEqualTo("fullPath", principalFullPath); - Query query = QueryFactory.newQuery(InternalGroupPrincipalImpl.class, filter); - InternalGroupPrincipal group = (InternalGroupPrincipal) getPersistenceBrokerTemplate().getObjectByQuery(query); - return group; + Query query = QueryFactory.newQuery(InternalGroupPrincipalImpl.class, + filter); + InternalGroupPrincipal group = (InternalGroupPrincipal) getPersistenceBrokerTemplate() + .getObjectByQuery(query); + return group; } - + /* - private SSOSite getSiteForRemoteUser(String fullPath) + * private SSOSite getSiteForRemoteUser(String fullPath) { // Get Site for + * remote user Criteria filter = new Criteria(); + * filter.addEqualTo("remotePrincipals.fullPath", fullPath); Query query = + * QueryFactory.newQuery(SSOSiteImpl.class, filter); return (SSOSite) + * getPersistenceBrokerTemplate().getObjectByQuery(query); } + */ + + private String getContentFromURL(String proxyID, String destUrl, + SSOSite[] sites, boolean bRefresh) throws SSOException { - // Get Site for remote user - Criteria filter = new Criteria(); - filter.addEqualTo("remotePrincipals.fullPath", fullPath); - Query query = QueryFactory.newQuery(SSOSiteImpl.class, filter); - return (SSOSite) getPersistenceBrokerTemplate().getObjectByQuery(query); - } - */ - - private String getContentFromURL(String proxyID, String destUrl, SSOSite[] sites, boolean bRefresh ) throws SSOException - { - URL urlObj = null; - - // Result Buffer - //BufferedInputStream bis = null; - String resultPage; - - String strErrorMessage = "SSO Component Error. Failed to get content for URL " + destUrl; - - try - { - urlObj = new URL(destUrl); - } - catch (MalformedURLException e) - { - String msg = ("Error -- Malformed URL [" + destUrl +"] for SSO authenticated destination"); - log.error(msg); - throw new SSOException(msg, e); - } - - /* - * Setup HTTPClient - * Check if an HTTP Client already exists for the given /user/site - */ - HttpClient client = (HttpClient)this.clientProxy.get(proxyID); - GetMethod get = null; - - if (bRefresh == true || client == null) - { - if (log.isInfoEnabled()) - log.info("SSO Component -- Create new HTTP Client object for Principal/URL [" + proxyID+ "]"); - - client = new HttpClient(); - client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY); - - int numberOfSites = sites.length; - - // Do all the logins for the site - for (int i=0; i<numberOfSites; i++) - { - SSOSite site = sites[i]; - - if (site != null) - { - Iterator itRemotePrincipals = site.getRemotePrincipals().iterator(); - while (itRemotePrincipals.hasNext() ) - { - InternalUserPrincipal remotePrincipal = (InternalUserPrincipal)itRemotePrincipals.next(); - if (remotePrincipal != null) - { - InternalCredential credential = null; - if ( remotePrincipal.getCredentials() != null) - credential = (InternalCredential)remotePrincipal.getCredentials().iterator().next(); - - if (credential != null) - { - if (log.isInfoEnabled()) - log.info("SSOComponent -- Remote Principal ["+stripPrincipalName(remotePrincipal.getFullPath())+"] has credential ["+this.unscramble(credential.getValue())+ "]"); - - client.getState().setCredentials( - site.getRealm(), - urlObj.getHost(), - new UsernamePasswordCredentials(stripPrincipalName(remotePrincipal.getFullPath()), this.unscramble(credential.getValue())) - ); - - // Build URL if it's Form authentication - StringBuffer siteURL = new StringBuffer(site.getSiteURL()); - - // Check if it's form based or ChallengeResponse - if (site.isFormAuthentication()) - { - siteURL.append("?").append(site.getFormUserField()).append("=").append(stripPrincipalName(remotePrincipal.getFullPath())).append("&").append(site.getFormPwdField()).append("=").append(this.unscramble(credential.getValue())); - } - - get = new GetMethod(siteURL.toString()); - - // Tell the GET method to automatically handle authentication. The - // method will use any appropriate credentials to handle basic - // authentication requests. Setting this value to false will cause - // any request for authentication to return with a status of 401. - // It will then be up to the client to handle the authentication. - get.setDoAuthentication( true ); - try { - // execute the GET - int status = client.executeMethod( get ); - - if (log.isInfoEnabled() ) - log.info("Accessing site [" + site.getSiteURL() + "]. HTTP Status [" +status+ "]" ); - - /* - * If the destination URL and the SSO url match - * use the authentication process but return immediately - * the result page. - */ - if( destUrl.compareTo(site.getSiteURL()) == 0 && numberOfSites == 1) - { - if (log.isInfoEnabled() ) - log.info("SSO Component --SSO Site and destination URL match. Go and get the content." ); - - //try - //{ - //bis = new BufferedInputStream(get.getResponseBodyAsStream()); - resultPage = get.getResponseBodyAsString(); - //} - //catch(IOException ioe) - //{ - // log.error(strErrorMessage, ioe); - // throw new SSOException (strErrorMessage, ioe); - //} + URL urlObj = null; - get.releaseConnection(); - - // Add the client object to the cache - this.clientProxy.put(proxyID, client); - - //return bis; - return resultPage; - } - - } catch (Exception e) { - log.error("Exception while authentication. Error: " +e); - } - - get.releaseConnection(); - } - } - } - } - } - - // Add the client object to the cache - this.clientProxy.put(proxyID, client); - } - else - { - if (log.isInfoEnabled()) - log.info("SSO Component -- Use cached HTTP Client object for Principal/URL [" + proxyID+ "]"); - } - - // All the SSO authentication done go to the destination url - get = new GetMethod(destUrl); - try { + // Result Buffer + // BufferedInputStream bis = null; + String resultPage; + + String strErrorMessage = "SSO Component Error. Failed to get content for URL " + + destUrl; + + try + { + urlObj = new URL(destUrl); + } + catch (MalformedURLException e) + { + String msg = ("Error -- Malformed URL [" + destUrl + "] for SSO authenticated destination"); + log.error(msg); + throw new SSOException(msg, e); + } + + /* + * Setup HTTPClient Check if an HTTP Client already exists for the given + * /user/site + */ + HttpClient client = (HttpClient) this.clientProxy.get(proxyID); + GetMethod get = null; + + if (bRefresh == true || client == null) + { + if (log.isInfoEnabled()) + log + .info("SSO Component -- Create new HTTP Client object for Principal/URL [" + + proxyID + "]"); + + client = new HttpClient(); + client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY); + + int numberOfSites = sites.length; + + // Do all the logins for the site + for (int i = 0; i < numberOfSites; i++) + { + SSOSite site = sites[i]; + + if (site != null) + { + Iterator itRemotePrincipals = site.getRemotePrincipals() + .iterator(); + while (itRemotePrincipals.hasNext()) + { + InternalUserPrincipal remotePrincipal = (InternalUserPrincipal) itRemotePrincipals + .next(); + if (remotePrincipal != null) + { + InternalCredential credential = null; + if (remotePrincipal.getCredentials() != null) + credential = (InternalCredential) remotePrincipal + .getCredentials().iterator().next(); + + if (credential != null) + { + if (log.isInfoEnabled()) + log + .info("SSOComponent -- Remote Principal [" + + stripPrincipalName(remotePrincipal + .getFullPath()) + + "] has credential [" + + this + .unscramble(credential + .getValue()) + + "]"); + + client + .getState() + .setCredentials( + site.getRealm(), + urlObj.getHost(), + new UsernamePasswordCredentials( + stripPrincipalName(remotePrincipal + .getFullPath()), + this + .unscramble(credential + .getValue()))); + + // Build URL if it's Form authentication + StringBuffer siteURL = new StringBuffer(site + .getSiteURL()); + + // Check if it's form based or ChallengeResponse + if (site.isFormAuthentication()) + { + siteURL + .append("?") + .append(site.getFormUserField()) + .append("=") + .append( + stripPrincipalName(remotePrincipal + .getFullPath())) + .append("&").append( + site.getFormPwdField()) + .append("=").append( + this.unscramble(credential + .getValue())); + } + + get = new GetMethod(siteURL.toString()); + + // Tell the GET method to automatically handle + // authentication. The + // method will use any appropriate credentials + // to handle basic + // authentication requests. Setting this value + // to false will cause + // any request for authentication to return with + // a status of 401. + // It will then be up to the client to handle + // the authentication. + get.setDoAuthentication(true); + try + { + // execute the GET + int status = client.executeMethod(get); + + if (log.isInfoEnabled()) + log.info("Accessing site [" + + site.getSiteURL() + + "]. HTTP Status [" + status + + "]"); + + /* + * If the destination URL and the SSO url + * match use the authentication process but + * return immediately the result page. + */ + if (destUrl.compareTo(site.getSiteURL()) == 0 + && numberOfSites == 1) + { + if (log.isInfoEnabled()) + log + .info("SSO Component --SSO Site and destination URL match. Go and get the content."); + + // try + // { + // bis = new + // BufferedInputStream(get.getResponseBodyAsStream()); + resultPage = get + .getResponseBodyAsString(); + // } + // catch(IOException ioe) + // { + // log.error(strErrorMessage, ioe); + // throw new SSOException + // (strErrorMessage, ioe); + // } + + get.releaseConnection(); + + // Add the client object to the cache + this.clientProxy.put(proxyID, client); + + // return bis; + return resultPage; + } + + } + catch (Exception e) + { + log + .error("Exception while authentication. Error: " + + e); + } + + get.releaseConnection(); + } + } + } + } + } + + // Add the client object to the cache + this.clientProxy.put(proxyID, client); + } + else + { + if (log.isInfoEnabled()) + log + .info("SSO Component -- Use cached HTTP Client object for Principal/URL [" + + proxyID + "]"); + } + + // All the SSO authentication done go to the destination url + get = new GetMethod(destUrl); + try + { // execute the GET - int status = client.executeMethod( get ); - - log.info("Accessing site [" + destUrl + "]. HTTP Status [" +status+ "]" ); - - } catch (Exception e) { - log.error("Exception while authentication. Error: " +e); + int status = client.executeMethod(get); + + log.info("Accessing site [" + destUrl + "]. HTTP Status [" + status + + "]"); + } - - - try - { - //bis = new BufferedInputStream(get.getResponseBodyAsStream()); - resultPage = get.getResponseBodyAsString(); - } - catch(IOException ioe) - { - log.error(strErrorMessage, ioe); - throw new SSOException (strErrorMessage, ioe); + catch (Exception e) + { + log.error("Exception while authentication. Error: " + e); } - catch (Exception e) - { - log.error(strErrorMessage, e); - throw new SSOException (strErrorMessage, e); - - } + + try + { + // bis = new BufferedInputStream(get.getResponseBodyAsStream()); + resultPage = get.getResponseBodyAsString(); + } + catch (IOException ioe) + { + log.error(strErrorMessage, ioe); + throw new SSOException(strErrorMessage, ioe); + } + catch (Exception e) + { + log.error(strErrorMessage, e); + throw new SSOException(strErrorMessage, e); + + } finally { get.releaseConnection(); } - - //return bis; - return resultPage; + + // return bis; + return resultPage; } - + /* - * Simple encryption decryption routines since the API creates credentials - * together with an user. - * TODO: re-implement when Security API is more flexible + * Simple encryption decryption routines since the API creates credentials + * together with an user. TODO: re-implement when Security API is more + * flexible */ - static char[] scrambler ="Jestspeed-2 is getting ready for release".toCharArray(); - + static char[] scrambler = "Jestspeed-2 is getting ready for release" + .toCharArray(); + private String scramble(String pwd) { - // xor-ing persistent String values is dangerous because of the (uncommon) way Java encodes UTF-8 0x00 (and some other characters). + // xor-ing persistent String values is dangerous because of the + // (uncommon) way Java encodes UTF-8 0x00 (and some other characters). // See: http://en.wikipedia.org/wiki/UTF-8#Java - // On some database platforms, like PostgreSQL this can lead to something like: - // org.postgresql.util.PSQLException: ERROR: invalid byte sequence for encoding "UTF8": 0x00 + // On some database platforms, like PostgreSQL this can lead to + // something like: + // org.postgresql.util.PSQLException: ERROR: invalid byte sequence for + // encoding "UTF8": 0x00 // To prevent this, the resulting xored password is encoded in Base64 - String xored = new String(xor(pwd.toCharArray(), scrambler)); + String xored = new String(xor(pwd.toCharArray(), scrambler)); byte[] bytes = Base64.encodeBase64(xored.getBytes()); String scrambled = new String(bytes); return scrambled; } - + private String unscramble(String pwd) { - byte[] bytes = pwd.getBytes(); + byte[] bytes = pwd.getBytes(); bytes = Base64.decodeBase64(bytes); String chars = new String(bytes); String unscrambled = new String(xor(chars.toCharArray(), scrambler)); return unscrambled; } - - private char[] xor(char[] a, char[]b) + + private char[] xor(char[] a, char[] b) { - int len = Math.min(a.length, b.length); - char[] result = new char[len]; - for(int i=0; i<len;i++) - { - result[i] = (char) (a[i] ^ b[i]); - } - return result; + int len = Math.min(a.length, b.length); + char[] result = new char[len]; + for (int i = 0; i < len; i++) + { + result[i] = (char) (a[i] ^ b[i]); + } + return result; } - public void addCredentialsForSite(SSOSite ssoSite, Subject subject, String remoteUser, String pwd) - throws SSOException + public void addCredentialsForSite(SSOSite ssoSite, Subject subject, + String remoteUser, String pwd) throws SSOException { String fullPath = ((BasePrincipal) SecurityHelper.getBestPrincipal( subject, UserPrincipal.class)).getFullPath(); @@ -1450,7 +1592,8 @@ { principal = getSSOPrincipal(fullPath); ssoSite.addPrincipal(principal); - } else + } + else { // Check if the entry the user likes to update exists already Collection remoteForSite = ssoSite.getRemotePrincipals(); @@ -1519,12 +1662,13 @@ // Persist Principal/Remote getPersistenceBrokerTemplate().store(principal); - } catch (Exception e) + } + catch (Exception e) { e.printStackTrace(); throw new SSOException(SSOException.FAILED_STORING_SITE_INFO_IN_DB + e.toString()); } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOContextImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOContextImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOContextImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.sso.impl; @@ -22,69 +22,82 @@ import org.apache.jetspeed.sso.SSOContext; /** -* SSOContextImpl -* Class holding credential information -* -* @author <a href="mailto:rogerrut ¡÷ apache.org">Roger Ruttimann</a> -* @version $Id: SSOContextImpl.java 516448 2007-03-09 16:25:47Z ate $ -*/ + * SSOContextImpl Class holding credential information + * + * @author <a href="mailto:rogerrut ¡÷ apache.org">Roger Ruttimann</a> + * @version $Id: SSOContextImpl.java 516448 2007-03-09 16:25:47Z ate $ + */ public class SSOContextImpl implements SSOContext, Serializable { - private long remotePrincipalId; - private String remoteCredential; - private String remotePrincipal; + + private long remotePrincipalId; + + private String remoteCredential; + + private String remotePrincipal; + private String portalPrincipal; - - /** - * Constructor takes all arguments since members can't be altered - */ - public SSOContextImpl(long remotePrincipalId, String remotePrincipal, String remoteCredential) + + /** + * Constructor takes all arguments since members can't be altered + */ + public SSOContextImpl(long remotePrincipalId, String remotePrincipal, + String remoteCredential) { - super(); - this.remotePrincipalId = remotePrincipalId; - this.remotePrincipal = remotePrincipal; - this.remoteCredential = remoteCredential; - } + super(); + this.remotePrincipalId = remotePrincipalId; + this.remotePrincipal = remotePrincipal; + this.remoteCredential = remoteCredential; + } - public SSOContextImpl(long remotePrincipalId, String remotePrincipal, String remoteCredential, String portalPrincipal) + public SSOContextImpl(long remotePrincipalId, String remotePrincipal, + String remoteCredential, String portalPrincipal) { - super(); + super(); this.remotePrincipalId = remotePrincipalId; this.remotePrincipal = remotePrincipal; this.remoteCredential = remoteCredential; this.portalPrincipal = portalPrincipal; } - - /* (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOContext#getRemotePrincipalId() - */ - public long getRemotePrincipalId() - { - return this.remotePrincipalId; - } - /* (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOContext#getRemotePrincipal() - */ - public String getRemotePrincipalName() + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOContext#getRemotePrincipalId() + */ + public long getRemotePrincipalId() { - return this.remotePrincipal; - } + return this.remotePrincipalId; + } - /* (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOContext#getRemoteCredential() - */ - public String getRemoteCredential() - { - return this.remoteCredential; - } + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOContext#getRemotePrincipal() + */ + public String getRemotePrincipalName() + { + return this.remotePrincipal; + } - /* (non-Javadoc) + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOContext#getRemoteCredential() + */ + public String getRemoteCredential() + { + return this.remoteCredential; + } + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.sso.SSOContext#getPortalPrincipal() */ - public String getPortalPrincipalName() + public String getPortalPrincipalName() { return this.portalPrincipal; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOCookieImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOCookieImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOCookieImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /*Created on: Nov 23, 2005 */ @@ -27,76 +27,98 @@ /** * @author Roger Ruttimann <rogerrut ¡÷ apache.org> - * + * */ -public class SSOCookieImpl implements SSOCookie { - - /** - * Internal for storing object values - */ - - private int cookieId; - private String cookie; - private Timestamp createDate; - private Collection remotePrincipals = new Vector(); +public class SSOCookieImpl implements SSOCookie +{ - /* (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOCookie#setCookieId(int) - */ - public void setCookieId(int cookieId) { - this.cookieId = cookieId; - } + /** + * Internal for storing object values + */ - /* (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOCookie#getCookieId() - */ - public int getCookieId() { - return this.cookieId; - } + private int cookieId; - /* (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOCookie#setCookie(java.lang.String) - */ - public void setCookie(String cookieValue) { - this.cookie = cookieValue; - } + private String cookie; - /* (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOCookie#getCookie() - */ - public String getCookie() { - return this.cookie; - } + private Timestamp createDate; - /* (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOCookie#setCreateDate(java.sql.Timestamp) - */ - public void setCreateDate(Timestamp createDate) { - this.createDate = createDate; - } + private Collection remotePrincipals = new Vector(); - /* (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOCookie#getCreateDate() - */ - public Timestamp getCreateDate() { - return this.createDate; - } - - /** - * - * @return - */ - public Collection getRemotePrincipals() - { - return this.remotePrincipals; - } - - /** - * - * @param remotePrincipals - */ - public void setRemotePrincipals(Collection remotePrincipals) - { - this.remotePrincipals = remotePrincipals; - } + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOCookie#setCookieId(int) + */ + public void setCookieId(int cookieId) + { + this.cookieId = cookieId; + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOCookie#getCookieId() + */ + public int getCookieId() + { + return this.cookieId; + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOCookie#setCookie(java.lang.String) + */ + public void setCookie(String cookieValue) + { + this.cookie = cookieValue; + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOCookie#getCookie() + */ + public String getCookie() + { + return this.cookie; + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOCookie#setCreateDate(java.sql.Timestamp) + */ + public void setCreateDate(Timestamp createDate) + { + this.createDate = createDate; + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOCookie#getCreateDate() + */ + public Timestamp getCreateDate() + { + return this.createDate; + } + + /** + * + * @return + */ + public Collection getRemotePrincipals() + { + return this.remotePrincipals; + } + + /** + * + * @param remotePrincipals + */ + public void setRemotePrincipals(Collection remotePrincipals) + { + this.remotePrincipals = remotePrincipals; + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOPrincipalImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOPrincipalImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOPrincipalImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.sso.impl; @@ -25,249 +25,259 @@ import org.apache.jetspeed.sso.SSOPrincipal; /** -* <p> -* SSOPrincipalImpl -* Class used for mapping Principal information for a site. This is the short form of -* the InternalPrincipalImpl -* .</p> -* -* @author <a href="mailto:rogerrut @apache.org">Roger Ruttimann</a> -*/ -public class SSOPrincipalImpl implements SSOPrincipal { - /** The principal id. */ - private long principalId; + * <p> + * SSOPrincipalImpl Class used for mapping Principal information for a site. + * This is the short form of the InternalPrincipalImpl . + * </p> + * + * @author <a href="mailto:rogerrut + * @apache.org">Roger Ruttimann</a> + */ +public class SSOPrincipalImpl implements SSOPrincipal +{ - /** The class name. */ - private String classname; + /** The principal id. */ + private long principalId; - /** The is mapping only. */ - private boolean isMappingOnly = false; + /** The class name. */ + private String classname; - /** The full path. */ - private String fullPath; + /** The is mapping only. */ + private boolean isMappingOnly = false; - /** The creation date. */ - private Timestamp creationDate; + /** The full path. */ + private String fullPath; - /** The modified date. */ - private Timestamp modifiedDate; - - /** The enabled state. */ - private boolean enabled = true; - - /** Permissions not used by required by the interface*/ - private Collection permissions; - - /** Remote principals for Principal */ - private Collection remotePrincipals = new Vector(); - - /** SIteID for Remote principal */ - private int siteID; - + /** The creation date. */ + private Timestamp creationDate; - /** - * <p> - * The special attribute telling OJB the object's concrete type. - * </p> - * <p> - * NOTE: this attribute MUST be called ojbConcreteClass - * </p> - */ - protected String ojbConcreteClass; + /** The modified date. */ + private Timestamp modifiedDate; - /** - * <p> - * InternalPrincipal implementation default constructor. - * </p> - */ - public SSOPrincipalImpl() - { - } + /** The enabled state. */ + private boolean enabled = true; - /** - * <p> - * InternalPrincipal constructor given a classname and name. - * </p> - * - * @param classname The classname. - * @param fullPath The full path. - */ - public SSOPrincipalImpl(String classname, String fullPath) - { - this.ojbConcreteClass = classname; - this.classname = classname; - this.fullPath = fullPath; - this.permissions = null; // Not used - this.creationDate = new Timestamp(System.currentTimeMillis()); - this.modifiedDate = this.creationDate; - } - - /** - * addRemotePrincipal() - * adds a principal to the list of remote principals - */ - public void addRemotePrincipal(InternalUserPrincipal principal) - { - /* if (remotePrincipals == null) - { - remotePrincipals = new ArrayList(1); - } - */ - - remotePrincipals.add(principal); - } + /** Permissions not used by required by the interface */ + private Collection permissions; - /** - * @see org.apache.jetspeed.security.om.InternalPrincipal#getPrincipalId() - */ - public long getPrincipalId() - { - return this.principalId; - } + /** Remote principals for Principal */ + private Collection remotePrincipals = new Vector(); - /** - * @see org.apache.jetspeed.security.om.InternalPrincipal#setPrincipalId(int) - */ - public void setPrincipalId(long principalId) - { - this.principalId = principalId; - } + /** SIteID for Remote principal */ + private int siteID; - /** - * @see org.apache.jetspeed.security.om.InternalPrincipal#getClassname() - */ - public String getClassname() - { - return this.classname; - } + /** + * <p> + * The special attribute telling OJB the object's concrete type. + * </p> + * <p> + * NOTE: this attribute MUST be called ojbConcreteClass + * </p> + */ + protected String ojbConcreteClass; - /** - * @see org.apache.jetspeed.security.om.InternalPrincipal#setClassname(java.lang.String) - */ - public void setClassname(String classname) - { - this.ojbConcreteClass = classname; - this.classname = classname; - } + /** + * <p> + * InternalPrincipal implementation default constructor. + * </p> + */ + public SSOPrincipalImpl() + { + } - /** - * @return Returns the isMappingOnly. - */ - public boolean isMappingOnly() - { - return isMappingOnly; - } + /** + * <p> + * InternalPrincipal constructor given a classname and name. + * </p> + * + * @param classname + * The classname. + * @param fullPath + * The full path. + */ + public SSOPrincipalImpl(String classname, String fullPath) + { + this.ojbConcreteClass = classname; + this.classname = classname; + this.fullPath = fullPath; + this.permissions = null; // Not used + this.creationDate = new Timestamp(System.currentTimeMillis()); + this.modifiedDate = this.creationDate; + } - /** - * @param isMappingOnly The isMappingOnly to set. - */ - public void setMappingOnly(boolean isMappingOnly) - { - this.isMappingOnly = isMappingOnly; - } + /** + * addRemotePrincipal() adds a principal to the list of remote principals + */ + public void addRemotePrincipal(InternalUserPrincipal principal) + { + /* + * if (remotePrincipals == null) { remotePrincipals = new ArrayList(1); } + */ - /** - * @see org.apache.jetspeed.security.om.InternalPrincipal#getFullPath() - */ - public String getFullPath() - { - return this.fullPath; - } + remotePrincipals.add(principal); + } - /** - * @see org.apache.jetspeed.security.om.InternalPrincipal#setFullPath(java.lang.String) - */ - public void setFullPath(String fullPath) - { - this.fullPath = fullPath; - } + /** + * @see org.apache.jetspeed.security.om.InternalPrincipal#getPrincipalId() + */ + public long getPrincipalId() + { + return this.principalId; + } - /** - * @see org.apache.jetspeed.security.om.InternalPrincipal#getPermissions() - */ - public Collection getPermissions() - { - return this.permissions; - } + /** + * @see org.apache.jetspeed.security.om.InternalPrincipal#setPrincipalId(int) + */ + public void setPrincipalId(long principalId) + { + this.principalId = principalId; + } - /** - * @see org.apache.jetspeed.security.om.InternalPrincipal#setPermissions(java.util.Collection) - */ - public void setPermissions(Collection permissions) - { - this.permissions = permissions; - } + /** + * @see org.apache.jetspeed.security.om.InternalPrincipal#getClassname() + */ + public String getClassname() + { + return this.classname; + } - /** - * @see org.apache.jetspeed.security.om.InternalPrincipal#getCreationDate() - */ - public Timestamp getCreationDate() - { - return this.creationDate; - } + /** + * @see org.apache.jetspeed.security.om.InternalPrincipal#setClassname(java.lang.String) + */ + public void setClassname(String classname) + { + this.ojbConcreteClass = classname; + this.classname = classname; + } - /** - * @see org.apache.jetspeed.security.om.InternalPrincipal#setCreationDate(java.sql.Timestamp) - */ - public void setCreationDate(Timestamp creationDate) - { - this.creationDate = creationDate; - } + /** + * @return Returns the isMappingOnly. + */ + public boolean isMappingOnly() + { + return isMappingOnly; + } - /** - * @see org.apache.jetspeed.security.om.InternalPrincipal#getModifiedDate() - */ - public Timestamp getModifiedDate() - { - return this.modifiedDate; - } + /** + * @param isMappingOnly + * The isMappingOnly to set. + */ + public void setMappingOnly(boolean isMappingOnly) + { + this.isMappingOnly = isMappingOnly; + } - /** - * @see org.apache.jetspeed.security.om.InternalPrincipal#setModifiedDate(java.sql.Timestamp) - */ - public void setModifiedDate(Timestamp modifiedDate) - { - this.modifiedDate = modifiedDate; - } + /** + * @see org.apache.jetspeed.security.om.InternalPrincipal#getFullPath() + */ + public String getFullPath() + { + return this.fullPath; + } - /** - * @see org.apache.jetspeed.security.om.InternalPrincipal#isEnabled() - */ - public boolean isEnabled() - { - return enabled; - } - - /** - * @see org.apache.jetspeed.security.om.InternalPrincipal#setEnabled(boolean) - */ - public void setEnabled(boolean enabled) - { - this.enabled = enabled; - } - /** - * @return Returns the remotePrincipals. - */ - public Collection getRemotePrincipals() { - return remotePrincipals; - } - /** - * @param remotePrincipals The remotePrincipals to set. - */ - public void setRemotePrincipals(Collection remotePrincipals) { - this.remotePrincipals = remotePrincipals; - } /** + * @see org.apache.jetspeed.security.om.InternalPrincipal#setFullPath(java.lang.String) + */ + public void setFullPath(String fullPath) + { + this.fullPath = fullPath; + } + + /** + * @see org.apache.jetspeed.security.om.InternalPrincipal#getPermissions() + */ + public Collection getPermissions() + { + return this.permissions; + } + + /** + * @see org.apache.jetspeed.security.om.InternalPrincipal#setPermissions(java.util.Collection) + */ + public void setPermissions(Collection permissions) + { + this.permissions = permissions; + } + + /** + * @see org.apache.jetspeed.security.om.InternalPrincipal#getCreationDate() + */ + public Timestamp getCreationDate() + { + return this.creationDate; + } + + /** + * @see org.apache.jetspeed.security.om.InternalPrincipal#setCreationDate(java.sql.Timestamp) + */ + public void setCreationDate(Timestamp creationDate) + { + this.creationDate = creationDate; + } + + /** + * @see org.apache.jetspeed.security.om.InternalPrincipal#getModifiedDate() + */ + public Timestamp getModifiedDate() + { + return this.modifiedDate; + } + + /** + * @see org.apache.jetspeed.security.om.InternalPrincipal#setModifiedDate(java.sql.Timestamp) + */ + public void setModifiedDate(Timestamp modifiedDate) + { + this.modifiedDate = modifiedDate; + } + + /** + * @see org.apache.jetspeed.security.om.InternalPrincipal#isEnabled() + */ + public boolean isEnabled() + { + return enabled; + } + + /** + * @see org.apache.jetspeed.security.om.InternalPrincipal#setEnabled(boolean) + */ + public void setEnabled(boolean enabled) + { + this.enabled = enabled; + } + + /** + * @return Returns the remotePrincipals. + */ + public Collection getRemotePrincipals() + { + return remotePrincipals; + } + + /** + * @param remotePrincipals + * The remotePrincipals to set. + */ + public void setRemotePrincipals(Collection remotePrincipals) + { + this.remotePrincipals = remotePrincipals; + } + + /** * @return Returns the siteID. */ - public int getSiteID() { + public int getSiteID() + { return siteID; } + /** - * @param siteID The siteID to set. + * @param siteID + * The siteID to set. */ - public void setSiteID(int siteID) { + public void setSiteID(int siteID) + { this.siteID = siteID; } } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOSiteImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOSiteImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/java/org/apache/jetspeed/sso/impl/SSOSiteImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.sso.impl; @@ -22,285 +22,345 @@ import java.util.Vector; import org.apache.jetspeed.sso.SSOException; +import org.apache.jetspeed.sso.SSOPrincipal; import org.apache.jetspeed.sso.SSOSite; -import org.apache.jetspeed.sso.SSOPrincipal; /** -* SSOSiteImpl -* Class holding information about the Site and credentials for Single Sign on SSO. -* OJB will map the database entries into this class -* -* @author <a href="mailto:rogerrut ¡÷ apache.org">Roger Ruttimann</a> -* @version $Id: SSOSiteImpl.java 516448 2007-03-09 16:25:47Z ate $ -*/ + * SSOSiteImpl Class holding information about the Site and credentials for + * Single Sign on SSO. OJB will map the database entries into this class + * + * @author <a href="mailto:rogerrut ¡÷ apache.org">Roger Ruttimann</a> + * @version $Id: SSOSiteImpl.java 516448 2007-03-09 16:25:47Z ate $ + */ -public class SSOSiteImpl implements SSOSite { - - // Private member for OJB mapping - private int siteId; - private String name; - private String siteURL; - private boolean isAllowUserSet; - private boolean isCertificateRequired; - - private boolean isChallangeResponseAuthentication; - - /* Realm used to do ChallengeResponse Authentication */ - private String realm; - - private boolean isFormAuthentication; - - /* Names of fields for User and Password values. The names are up to the - * application developer and therefore it must be configurable for SSO*/ - private String formUserField; - private String formPwdField; - - private Collection principals = new Vector(); - private Collection remotePrincipals = new Vector(); - - /** - * - */ - public SSOSiteImpl() { - super(); - - } +public class SSOSiteImpl implements SSOSite +{ - /* - * Setters and getters for member variables - */ - - /** - * @return Returns the isAllowUserSet. - */ - public boolean isAllowUserSet() { - return isAllowUserSet; - } - /** - * @param isAllowUserSet The isAllowUserSet to set. - */ - public void setAllowUserSet(boolean isAllowUserSet) { - this.isAllowUserSet = isAllowUserSet; - } - /** - * @return Returns the isCertificateRequired. - */ - public boolean isCertificateRequired() { - return isCertificateRequired; - } - /** - * @param isCertificateRequired The isCertificateRequired to set. - */ - public void setCertificateRequired(boolean isCertificateRequired) { - this.isCertificateRequired = isCertificateRequired; - } - /** - * @return Returns the name. - */ - public String getName() { - return name; - } - /** - * @param name The name to set. - */ - public void setName(String name) { - this.name = name; - } - /** - * @return Returns the principals. - */ - public Collection getPrincipals() { - return this.principals; - } - /** - * @param principals The principals to set. - */ - public void setPrincipals(Collection principals) { - this.principals.addAll(principals); - } - /** - * @return Returns the siteId. - */ - public int getSiteId() { - return siteId; - } - /** - * @param siteId The siteId to set. - */ - public void setSiteId(int siteId) { - this.siteId = siteId; - } - /** - * @return Returns the siteURL. - */ - public String getSiteURL() { - return siteURL; - } - /** - * @param siteURL The siteURL to set. - */ - public void setSiteURL(String siteURL) { - this.siteURL = siteURL; - } - - /** - * Utility functions - * addCredential() - * Adds the credentail to the credentials collection - * - */ - - - - /** - * addPrincipal - * Adds the SSOPrincipal to the principals collection - * - */ - public void addPrincipal(SSOPrincipal principal) throws SSOException { - boolean bStatus = false; - - try - { - bStatus = principals.add(principal); - } - catch(Exception e) - { - // Adding credentail to coollection failed -- notify caller with SSOException - throw new SSOException(SSOException.FAILED_ADDING_PRINCIPAL_TO_MAPPING_TABLE_FOR_SITE + e.getMessage()); - } - - if ( bStatus == false) - throw new SSOException(SSOException.FAILED_ADDING_PRINCIPAL_TO_MAPPING_TABLE_FOR_SITE ); - } - - /** - * removePrincipal() - * removes a principal from the principals collection - * - */ - public void removePrincipal(long principalId) throws SSOException - { - boolean bStatus = false; - SSOPrincipal principalObj = null; - Iterator itSitePrincipals = principals.iterator(); - - while (itSitePrincipals.hasNext() ) - { - principalObj = (SSOPrincipal)itSitePrincipals.next(); - if ( principalObj.getPrincipalId() == principalId) - { - - try - { - bStatus = principals.remove(principalObj); - } - catch(Exception e) - { - // Adding credentail to coollection failed -- notify caller with SSOException - throw new SSOException(SSOException.FAILED_REMOVING_PRINCIPAL_FROM_MAPPING_TABLE_FOR_SITE + e.getMessage()); - } - - if ( bStatus == false) - throw new SSOException(SSOException.FAILED_REMOVING_PRINCIPAL_FROM_MAPPING_TABLE_FOR_SITE ); - } - - } - } + // Private member for OJB mapping + private int siteId; + + private String name; + + private String siteURL; + + private boolean isAllowUserSet; + + private boolean isCertificateRequired; + + private boolean isChallangeResponseAuthentication; + + /* Realm used to do ChallengeResponse Authentication */ + private String realm; + + private boolean isFormAuthentication; + + /* + * Names of fields for User and Password values. The names are up to the + * application developer and therefore it must be configurable for SSO + */ + private String formUserField; + + private String formPwdField; + + private Collection principals = new Vector(); + + private Collection remotePrincipals = new Vector(); + /** + * + */ + public SSOSiteImpl() + { + super(); + + } + + /* + * Setters and getters for member variables + */ + + /** + * @return Returns the isAllowUserSet. + */ + public boolean isAllowUserSet() + { + return isAllowUserSet; + } + + /** + * @param isAllowUserSet + * The isAllowUserSet to set. + */ + public void setAllowUserSet(boolean isAllowUserSet) + { + this.isAllowUserSet = isAllowUserSet; + } + + /** + * @return Returns the isCertificateRequired. + */ + public boolean isCertificateRequired() + { + return isCertificateRequired; + } + + /** + * @param isCertificateRequired + * The isCertificateRequired to set. + */ + public void setCertificateRequired(boolean isCertificateRequired) + { + this.isCertificateRequired = isCertificateRequired; + } + + /** + * @return Returns the name. + */ + public String getName() + { + return name; + } + + /** + * @param name + * The name to set. + */ + public void setName(String name) + { + this.name = name; + } + + /** + * @return Returns the principals. + */ + public Collection getPrincipals() + { + return this.principals; + } + + /** + * @param principals + * The principals to set. + */ + public void setPrincipals(Collection principals) + { + this.principals.addAll(principals); + } + + /** + * @return Returns the siteId. + */ + public int getSiteId() + { + return siteId; + } + + /** + * @param siteId + * The siteId to set. + */ + public void setSiteId(int siteId) + { + this.siteId = siteId; + } + + /** + * @return Returns the siteURL. + */ + public String getSiteURL() + { + return siteURL; + } + + /** + * @param siteURL + * The siteURL to set. + */ + public void setSiteURL(String siteURL) + { + this.siteURL = siteURL; + } + + /** + * Utility functions addCredential() Adds the credentail to the credentials + * collection + * + */ + + /** + * addPrincipal Adds the SSOPrincipal to the principals collection + * + */ + public void addPrincipal(SSOPrincipal principal) throws SSOException + { + boolean bStatus = false; + + try + { + bStatus = principals.add(principal); + } + catch (Exception e) + { + // Adding credentail to coollection failed -- notify caller with + // SSOException + throw new SSOException( + SSOException.FAILED_ADDING_PRINCIPAL_TO_MAPPING_TABLE_FOR_SITE + + e.getMessage()); + } + + if (bStatus == false) + throw new SSOException( + SSOException.FAILED_ADDING_PRINCIPAL_TO_MAPPING_TABLE_FOR_SITE); + } + + /** + * removePrincipal() removes a principal from the principals collection + * + */ + public void removePrincipal(long principalId) throws SSOException + { + boolean bStatus = false; + SSOPrincipal principalObj = null; + Iterator itSitePrincipals = principals.iterator(); + + while (itSitePrincipals.hasNext()) + { + principalObj = (SSOPrincipal) itSitePrincipals.next(); + if (principalObj.getPrincipalId() == principalId) + { + + try + { + bStatus = principals.remove(principalObj); + } + catch (Exception e) + { + // Adding credentail to coollection failed -- notify caller + // with SSOException + throw new SSOException( + SSOException.FAILED_REMOVING_PRINCIPAL_FROM_MAPPING_TABLE_FOR_SITE + + e.getMessage()); + } + + if (bStatus == false) + throw new SSOException( + SSOException.FAILED_REMOVING_PRINCIPAL_FROM_MAPPING_TABLE_FOR_SITE); + } + + } + } + + /** * @return Returns the remotePrincipals. */ - public Collection getRemotePrincipals() { + public Collection getRemotePrincipals() + { return remotePrincipals; } + /** - * @param remotePrincipals The remotePrincipals to set. + * @param remotePrincipals + * The remotePrincipals to set. */ - public void setRemotePrincipals(Collection remotePrincipals) { + public void setRemotePrincipals(Collection remotePrincipals) + { this.remotePrincipals = remotePrincipals; } - + /** - * Define the Authentication methods. - * Supported are: Challenge Response and From based + * Define the Authentication methods. Supported are: Challenge Response and + * From based */ /** - * Form authentication requires two fields that hold the credential + * Form authentication requires two fields that hold the credential * information for the request. */ public void setFormAuthentication(String formUserField, String formPwdField) { - // Set the fields for Form Authentication and clear other authentication methods - + // Set the fields for Form Authentication and clear other authentication + // methods + } - + /* * Uses Challenge Response mechanism for authentication */ public void setChallengeResponseAuthentication() { - // Set the fields for ChallengeResponse and clear other authentication methods - + // Set the fields for ChallengeResponse and clear other authentication + // methods + } /* Setters/Getters for Authentication settings */ - public String getFormPwdField() { - return formPwdField; - } + public String getFormPwdField() + { + return formPwdField; + } - public void setFormPwdField(String formPwdField) { - this.formPwdField = formPwdField; - } + public void setFormPwdField(String formPwdField) + { + this.formPwdField = formPwdField; + } - public String getFormUserField() { - return formUserField; - } + public String getFormUserField() + { + return formUserField; + } - public void setFormUserField(String formUserField) { - this.formUserField = formUserField; - } + public void setFormUserField(String formUserField) + { + this.formUserField = formUserField; + } - public boolean isChallangeResponseAuthentication() { - return isChallangeResponseAuthentication; - } + public boolean isChallangeResponseAuthentication() + { + return isChallangeResponseAuthentication; + } - public void setChallengeResponseAuthentication( - boolean isChallangeResponseAuthentication) { - this.isChallangeResponseAuthentication = isChallangeResponseAuthentication; - } + public void setChallengeResponseAuthentication( + boolean isChallangeResponseAuthentication) + { + this.isChallangeResponseAuthentication = isChallangeResponseAuthentication; + } - public boolean isFormAuthentication() { - return isFormAuthentication; - } + public boolean isFormAuthentication() + { + return isFormAuthentication; + } - public void setFormAuthentication(boolean isFormAuthentication) { - this.isFormAuthentication = isFormAuthentication; - } - - public void configFormAuthentication(String formUserField, String formPwdField) - { - this.isFormAuthentication = true; - this.setChallengeResponseAuthentication(false); - - this.formPwdField = formPwdField; - this.formUserField = formUserField; - } - - /* - * (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOSite#setRealm(java.lang.String) - */ - public void setRealm(String realm) - { - this.realm = realm; - } - - /* - * (non-Javadoc) - * @see org.apache.jetspeed.sso.SSOSite#getRealm() - */ - public String getRealm() - { - return this.realm; - } + public void setFormAuthentication(boolean isFormAuthentication) + { + this.isFormAuthentication = isFormAuthentication; + } + + public void configFormAuthentication(String formUserField, + String formPwdField) + { + this.isFormAuthentication = true; + this.setChallengeResponseAuthentication(false); + + this.formPwdField = formPwdField; + this.formUserField = formUserField; + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOSite#setRealm(java.lang.String) + */ + public void setRealm(String realm) + { + this.realm = realm; + } + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.sso.SSOSite#getRealm() + */ + public String getRealm() + { + return this.realm; + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/test/org/apache/jetspeed/sso/TestBasicSSO.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/test/org/apache/jetspeed/sso/TestBasicSSO.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/test/org/apache/jetspeed/sso/TestBasicSSO.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,6 +16,10 @@ */ package org.apache.jetspeed.sso; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; @@ -26,11 +30,6 @@ import org.apache.commons.httpclient.auth.HttpAuthenticator; import org.apache.commons.httpclient.methods.GetMethod; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - - /** * TestBasicSSO * @@ -39,6 +38,7 @@ */ public class TestBasicSSO extends TestCase { + public static Test suite() { return new TestSuite(TestBasicSSO.class); @@ -46,19 +46,22 @@ public void testBasicSSO() throws Exception { - System.out.println("Testing SSO"); + System.out.println("Testing SSO"); // connect("http://localhost:8080/demo/sso-basic", "tomcat", "tomcat"); } - - public void connect(String server, String username, String password) throws Exception + + public void connect(String server, String username, String password) + throws Exception { HttpClient client = new HttpClient(); - UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); + UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( + username, password); StringBuffer authenticationHeader = new StringBuffer("BASIC"); authenticationHeader.append(" realm=\""); authenticationHeader.append("jetspeed"); authenticationHeader.append("\""); - Header[] headers = { new Header("WWW-Authenticate", authenticationHeader.toString())}; + Header[] headers = + {new Header("WWW-Authenticate", authenticationHeader.toString())}; AuthScheme scheme = null; client.getState().setCredentials(null, null, credentials); @@ -69,41 +72,43 @@ try { scheme = HttpAuthenticator.selectAuthScheme(headers); - HttpConnection conn = client.getHttpConnectionManager().getConnection(get.getHostConfiguration()); - boolean authenticated = HttpAuthenticator.authenticate(scheme, get, conn, client.getState()); - if (!authenticated) - { - throw new Exception("Failed to create authentication headers to HTTP Connection"); - } + HttpConnection conn = client.getHttpConnectionManager() + .getConnection(get.getHostConfiguration()); + boolean authenticated = HttpAuthenticator.authenticate(scheme, get, + conn, client.getState()); + if (!authenticated) { throw new Exception( + "Failed to create authentication headers to HTTP Connection"); } client.executeMethod(get); - System.out.println("response = [" + get.getResponseBodyAsString() + "]"); + System.out.println("response = [" + get.getResponseBodyAsString() + + "]"); Cookie[] cookies = client.getState().getCookies(); Cookie mycookie = null; // Display the cookies System.out.println("Present cookies: "); - for (int i = 0; i < cookies.length; i++) + for (int i = 0; i < cookies.length; i++) { System.out.println(" - " + cookies[i].toExternalForm()); mycookie = cookies[i]; } - // get.releaseConnection(); - // client.endSession(); - - HttpState initialState = new HttpState(); + // get.releaseConnection(); + // client.endSession(); + + HttpState initialState = new HttpState(); initialState.addCookie(mycookie); // client.getParams().setCookiePolicy(CookiePolicy.RFC_2109); client = new HttpClient(); client.setState(initialState); get = new GetMethod(server); - + client.executeMethod(get); - System.out.println("response = [" + get.getResponseBodyAsString() + "]"); + System.out.println("response = [" + get.getResponseBodyAsString() + + "]"); cookies = client.getState().getCookies(); // Display the cookies System.out.println("Present cookies: "); - for (int i = 0; i < cookies.length; i++) + for (int i = 0; i < cookies.length; i++) { System.out.println(" - " + cookies[i].toExternalForm()); } @@ -111,8 +116,10 @@ } catch (Throwable t) { - throw new Exception("Unexpected exception in creating HTTP authentication headers", t); + throw new Exception( + "Unexpected exception in creating HTTP authentication headers", + t); } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/test/org/apache/jetspeed/sso/TestSSOComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/test/org/apache/jetspeed/sso/TestSSOComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/sso/src/test/org/apache/jetspeed/sso/TestSSOComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,17 +17,6 @@ package org.apache.jetspeed.sso; -import org.apache.jetspeed.security.SecurityException; -import org.apache.jetspeed.security.impl.GroupPrincipalImpl; -import org.apache.jetspeed.security.impl.UserPrincipalImpl; -import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; -import org.apache.jetspeed.sso.SSOProvider; - -import junit.framework.Test; -import junit.framework.TestSuite; - -import javax.security.auth.Subject; - import java.security.Principal; import java.util.ArrayList; import java.util.Arrays; @@ -36,14 +25,22 @@ import java.util.List; import java.util.Set; -import org.apache.jetspeed.sso.SSOException; -import java.lang.Exception; +import javax.security.auth.Subject; +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.apache.jetspeed.security.SecurityException; +import org.apache.jetspeed.security.impl.GroupPrincipalImpl; +import org.apache.jetspeed.security.impl.UserPrincipalImpl; +import org.apache.jetspeed.security.util.test.AbstractSecurityTestcase; + /** - * @author David Le Strat + * @author David Le Strat */ public class TestSSOComponent extends AbstractSecurityTestcase { + /** * test url for this UnitTest */ @@ -108,7 +105,8 @@ */ public void testSSOGroup() throws Exception { - System.out.println("*************************************\n" + "Start Unit Test for SSO Group Support" + System.out.println("*************************************\n" + + "Start Unit Test for SSO Group Support" + "\n*************************************"); // Create a user @@ -118,18 +116,21 @@ } catch (SecurityException sex) { - // assertTrue("user already exists. exception caught: " + sex, false); + // assertTrue("user already exists. exception caught: " + sex, + // false); } // Create a group try { gms.addGroup(TEST_GROUP); - System.out.println("Creating Group " + TEST_GROUP + " and adding User " + TEST_GROUP_USER + " succeeded!."); + System.out.println("Creating Group " + TEST_GROUP + + " and adding User " + TEST_GROUP_USER + " succeeded!."); } catch (SecurityException secex) { - System.out.println("Creating Group " + TEST_GROUP + " and adding User " + TEST_GROUP_USER + System.out.println("Creating Group " + TEST_GROUP + + " and adding User " + TEST_GROUP_USER + " failed. Group might already exist. Continue test..."); // secex.printStackTrace(); // throw new Exception(secex.getMessage()); @@ -149,26 +150,31 @@ Principal principal = new GroupPrincipalImpl(TEST_GROUP); Set principals = new HashSet(); principals.add(principal); - Subject subject = new Subject(true, principals, new HashSet(), new HashSet()); + Subject subject = new Subject(true, principals, new HashSet(), + new HashSet()); // Add SSO Credential for Group if (ssoBroker.hasSSOCredentials(subject, TEST_URL) == false) { try { - ssoBroker.addCredentialsForSite(subject, REMOTE_USER, TEST_URL, REMOTE_PWD_1); - System.out.println("SSO Credential added for Group:" + TEST_GROUP + " site: " + TEST_URL); + ssoBroker.addCredentialsForSite(subject, REMOTE_USER, TEST_URL, + REMOTE_PWD_1); + System.out.println("SSO Credential added for Group:" + + TEST_GROUP + " site: " + TEST_URL); } catch (SSOException ssoex) { - System.out.println("SSO Credential add FAILED for Group:" + TEST_GROUP + " site: " + TEST_URL); + System.out.println("SSO Credential add FAILED for Group:" + + TEST_GROUP + " site: " + TEST_URL); ssoex.printStackTrace(); throw new Exception(ssoex.getMessage()); } } else { - System.out.println("Group:" + TEST_GROUP + " site: " + TEST_URL + " has already a remote credential"); + System.out.println("Group:" + TEST_GROUP + " site: " + TEST_URL + + " has already a remote credential"); } // Create Principal for User @@ -181,7 +187,8 @@ if (ssoBroker.hasSSOCredentials(subject, TEST_URL) == false) { // Group expansion failed. User not recognized - System.out.println("No SSO Credential for user:" + TEST_GROUP_USER + " site: " + TEST_URL); + System.out.println("No SSO Credential for user:" + TEST_GROUP_USER + + " site: " + TEST_URL); // Test failure try @@ -191,7 +198,9 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and group. exception caught: " + sex, false); + assertTrue( + "could not remove user and group. exception caught: " + + sex, false); } throw new Exception("SSO Unit test for Group support failed"); @@ -199,26 +208,32 @@ else { // Group lookup succesful - System.out.println("SSO Test for Group support successful" + "\nSSO Credential for user:" + TEST_GROUP_USER - + " site: " + TEST_URL + " found. User is member of Group " + TEST_GROUP); + System.out.println("SSO Test for Group support successful" + + "\nSSO Credential for user:" + TEST_GROUP_USER + + " site: " + TEST_URL + " found. User is member of Group " + + TEST_GROUP); } // Cleanup test. /* - * For hypersonic the cascading deletes are not generated by Torque and the remove credentials fails with a - * constraint error. Comment test out for M1 release but the problem needs to be addressed for the upcoming - * releases + * For hypersonic the cascading deletes are not generated by Torque and + * the remove credentials fails with a constraint error. Comment test + * out for M1 release but the problem needs to be addressed for the + * upcoming releases */ try { // Remove credential for Site - ssoBroker.removeCredentialsForSite("/group/" + TEST_GROUP, TEST_URL); - System.out.println("SSO Credential removed for Group:" + TEST_GROUP + " site: " + TEST_URL); + ssoBroker + .removeCredentialsForSite("/group/" + TEST_GROUP, TEST_URL); + System.out.println("SSO Credential removed for Group:" + TEST_GROUP + + " site: " + TEST_URL); } catch (SSOException ssoex) { - System.out.println("SSO Credential remove FAILED for Group:" + TEST_GROUP + " site: " + TEST_URL); + System.out.println("SSO Credential remove FAILED for Group:" + + TEST_GROUP + " site: " + TEST_URL); throw new Exception(ssoex.getMessage()); } @@ -229,14 +244,16 @@ } catch (SecurityException sex) { - assertTrue("could not remove user and group. exception caught: " + sex, false); + assertTrue("could not remove user and group. exception caught: " + + sex, false); } } public void testSSO() throws Exception { - System.out.println("***************************\nStart Unit Test for SSO API\n***************************"); + System.out + .println("***************************\nStart Unit Test for SSO API\n***************************"); // Create a user try @@ -245,112 +262,139 @@ } catch (SecurityException sex) { - // assertTrue("user already exists. exception caught: " + sex, false); + // assertTrue("user already exists. exception caught: " + sex, + // false); } // Initialization Principal principal = new UserPrincipalImpl(TEST_USER); Set principals = new HashSet(); principals.add(principal); - Subject subject = new Subject(true, principals, new HashSet(), new HashSet()); + Subject subject = new Subject(true, principals, new HashSet(), + new HashSet()); if (ssoBroker.hasSSOCredentials(subject, TEST_URL) == false) { - System.out.println("No SSO Credential for user:" + TEST_USER + " site: " + TEST_URL); + System.out.println("No SSO Credential for user:" + TEST_USER + + " site: " + TEST_URL); // Add credential try { - ssoBroker.addCredentialsForSite(subject, REMOTE_USER, TEST_URL, REMOTE_PWD_1); - System.out.println("SSO Credential added for user:" + TEST_USER + " site: " + TEST_URL); + ssoBroker.addCredentialsForSite(subject, REMOTE_USER, TEST_URL, + REMOTE_PWD_1); + System.out.println("SSO Credential added for user:" + TEST_USER + + " site: " + TEST_URL); } catch (SSOException ssoex) { - System.out.println("SSO Credential add FAILED for user:" + TEST_USER + " site: " + TEST_URL); + System.out.println("SSO Credential add FAILED for user:" + + TEST_USER + " site: " + TEST_URL); ssoex.printStackTrace(); throw new Exception(ssoex.getMessage()); } } else { - System.out.println("SSO Credential found for user:" + TEST_USER + " site: " + TEST_URL); + System.out.println("SSO Credential found for user:" + TEST_USER + + " site: " + TEST_URL); } // Add another remote principal for the same user if (ssoBroker.hasSSOCredentials(subject, TEST_URL2) == false) { - System.out.println("No SSO Credential for user:" + TEST_USER + " site: " + TEST_URL2); + System.out.println("No SSO Credential for user:" + TEST_USER + + " site: " + TEST_URL2); // Add credential try { - ssoBroker.addCredentialsForSite(subject, REMOTE_USER2, TEST_URL2, REMOTE_PWD_2); + ssoBroker.addCredentialsForSite(subject, REMOTE_USER2, + TEST_URL2, REMOTE_PWD_2); ssoBroker.setRealmForSite(TEST_URL2, "Nagios Access"); - - System.out.println("SSO Credential added for user:" + TEST_USER + " site: " + TEST_URL2); + + System.out.println("SSO Credential added for user:" + TEST_USER + + " site: " + TEST_URL2); } catch (SSOException ssoex) { - System.out.println("SSO Credential add FAILED for user:" + TEST_USER + " site: " + TEST_URL2); + System.out.println("SSO Credential add FAILED for user:" + + TEST_USER + " site: " + TEST_URL2); ssoex.printStackTrace(); throw new Exception(ssoex.getMessage()); } } else { - System.out.println("SSO Credential found for user:" + TEST_USER + " site: " + TEST_URL2); + System.out.println("SSO Credential found for user:" + TEST_USER + + " site: " + TEST_URL2); } // Add the credentail again -- should get an error try { - ssoBroker.addCredentialsForSite(subject, REMOTE_USER2, TEST_URL2, REMOTE_PWD_2); - throw new Exception("Added same credentail twice -- API should prevent users from doing that."); + ssoBroker.addCredentialsForSite(subject, REMOTE_USER2, TEST_URL2, + REMOTE_PWD_2); + throw new Exception( + "Added same credentail twice -- API should prevent users from doing that."); } catch (SSOException ssoex) { - System.out.println("Adding same SSO Credential twice failed (as expected) Message :" + ssoex.getMessage()); + System.out + .println("Adding same SSO Credential twice failed (as expected) Message :" + + ssoex.getMessage()); } catch (Exception e) { - throw new Exception("Adding SSO Credential twice throw an unandled exception. Error: " + e.getMessage()); + throw new Exception( + "Adding SSO Credential twice throw an unandled exception. Error: " + + e.getMessage()); } // Test if the credential where persisted // Test credential update SSOContext ssocontext = ssoBroker.getCredentials(subject, TEST_URL); - System.out.println("SSO Credential: User:" + ssocontext.getRemotePrincipalName() + " Password: " + System.out.println("SSO Credential: User:" + + ssocontext.getRemotePrincipalName() + " Password: " + ssocontext.getRemoteCredential() + " for site: " + TEST_URL); - System.out.println("SSO Credential: User:" + ssocontext.getRemotePrincipalName() + " Password: " + System.out.println("SSO Credential: User:" + + ssocontext.getRemotePrincipalName() + " Password: " + ssocontext.getRemoteCredential() + " for site: " + TEST_URL2); try { // Update Remote credential System.out.println("SSO Credential Update"); - ssoBroker.updateCredentialsForSite(subject, REMOTE_USER, TEST_URL, REMOTE_PWD_2); + ssoBroker.updateCredentialsForSite(subject, REMOTE_USER, TEST_URL, + REMOTE_PWD_2); ssocontext = ssoBroker.getCredentials(subject, TEST_URL); - System.out.println("SSO Credential updated: User:" + ssocontext.getRemotePrincipalName() + " Password: " + System.out.println("SSO Credential updated: User:" + + ssocontext.getRemotePrincipalName() + " Password: " + ssocontext.getRemoteCredential()); } catch (SSOException ssoex) { - System.out.println("SSO Credential update FAILED for user:" + TEST_USER + " site: " + TEST_URL); + System.out.println("SSO Credential update FAILED for user:" + + TEST_USER + " site: " + TEST_URL); throw new Exception(ssoex.getMessage()); } - + /* - * For hypersonic the cascading deletes are not generated by Torque and the remove credentials fails with a - * constraint error. Comment test out for M1 release but the problem needs to be addressed for the upcoming - * releases try { // Remove credential for Site ssoBroker.removeCredentialsForSite(subject, TEST_URL); - * System.out.println("SSO Credential removed for user:" + TEST_USER+ " site: " + TEST_URL); } - * catch(SSOException ssoex) { System.out.println("SSO Credential remove FAILED for user:" + TEST_USER+ " site: " + - * TEST_URL); throw new Exception(ssoex.getMessage()); } + * For hypersonic the cascading deletes are not generated by Torque and + * the remove credentials fails with a constraint error. Comment test + * out for M1 release but the problem needs to be addressed for the + * upcoming releases try { // Remove credential for Site + * ssoBroker.removeCredentialsForSite(subject, TEST_URL); + * System.out.println("SSO Credential removed for user:" + TEST_USER+ " + * site: " + TEST_URL); } catch(SSOException ssoex) { + * System.out.println("SSO Credential remove FAILED for user:" + + * TEST_USER+ " site: " + TEST_URL); throw new + * Exception(ssoex.getMessage()); } */ Iterator sites = ssoBroker.getSites(""); @@ -362,14 +406,16 @@ // Cleanup try { - ssoBroker.removeCredentialsForSite(subject, TEST_URL); - ssoBroker.removeCredentialsForSite(subject, TEST_URL2); - System.out.println("SSO Credential removed for user:" + TEST_USER+ " sites: " + TEST_URL + " " + TEST_URL2); + ssoBroker.removeCredentialsForSite(subject, TEST_URL); + ssoBroker.removeCredentialsForSite(subject, TEST_URL2); + System.out.println("SSO Credential removed for user:" + TEST_USER + + " sites: " + TEST_URL + " " + TEST_URL2); } - catch(SSOException ssoex) - { - System.out.println("SSO Credential remove FAILED for user:" + TEST_USER+ " site: " + TEST_URL + " and " + TEST_URL2); - throw new Exception(ssoex.getMessage()); + catch (SSOException ssoex) + { + System.out.println("SSO Credential remove FAILED for user:" + + TEST_USER + " site: " + TEST_URL + " and " + TEST_URL2); + throw new Exception(ssoex.getMessage()); } } @@ -383,7 +429,8 @@ { // Cleanup any credentails added during the test /* - * try { } catch (SSOException ex) { System.out.println("SSOException" + ex); } + * try { } catch (SSOException ex) { System.out.println("SSOException" + + * ex); } */ } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/audit/impl/ActivityBean.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/audit/impl/ActivityBean.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/audit/impl/ActivityBean.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,119 +20,125 @@ public class ActivityBean { + private String activity; + private String category; + private String admin; + private String userName; + private Timestamp timestamp; + private String ipAddress; + private String name; + private String beforeValue; + private String afterValue; + private String description; - + public String getActivity() { return activity; } - + public void setActivity(String activity) { this.activity = activity; } - + public String getAdmin() { return admin; } - + public void setAdmin(String admin) { this.admin = admin; } - + public String getCategory() { return category; } - + public void setCategory(String category) { this.category = category; } - + public String getDescription() { return description; } - + public void setDescription(String description) { this.description = description; } - + public String getIpAddress() { return ipAddress; } - + public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } - + public String getName() { return name; } - + public void setName(String name) { this.name = name; } - + public Timestamp getTimestamp() { return timestamp; } - + public void setTimestamp(Timestamp timestamp) { this.timestamp = timestamp; } - + public String getUserName() { return userName; } - + public void setUserName(String userName) { this.userName = userName; } - public String getAfterValue() { return afterValue; } - public void setAfterValue(String afterValue) { this.afterValue = afterValue; } - public String getBeforeValue() { return beforeValue; } - public void setBeforeValue(String beforeValue) { this.beforeValue = beforeValue; } - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/audit/impl/AuditActivityImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/audit/impl/AuditActivityImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/audit/impl/AuditActivityImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,81 +30,103 @@ /** * <p> - * Gathers information about security auditing activity + * Gathers information about security auditing activity * </p> * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor </a> * @version $Id: $ */ -public class AuditActivityImpl extends PersistenceBrokerDaoSupport implements AuditActivity +public class AuditActivityImpl extends PersistenceBrokerDaoSupport implements + AuditActivity { + protected final static Log log = LogFactory.getLog(AuditActivityImpl.class); - + protected DataSource ds; + protected String anonymousUser = "guest"; + protected boolean enabled = true; public AuditActivityImpl(DataSource dataSource) { - this.ds = dataSource; + this.ds = dataSource; } - + public void setEnabled(boolean enabled) { this.enabled = enabled; } - + public boolean getEnabled() { return this.enabled; } - + public DataSource getDataSource() { return ds; } - - public void logAdminAttributeActivity(String adminName, String ipAddress, String targetUser, String activity, String name, String beforeValue, String afterValue, String description) + + public void logAdminAttributeActivity(String adminName, String ipAddress, + String targetUser, String activity, String name, + String beforeValue, String afterValue, String description) { if (enabled) { - logAdminActivity(adminName, ipAddress, targetUser, activity, description, AuditActivity.CAT_ADMIN_ATTRIBUTE_MAINTENANCE, name, beforeValue, afterValue); + logAdminActivity(adminName, ipAddress, targetUser, activity, + description, AuditActivity.CAT_ADMIN_ATTRIBUTE_MAINTENANCE, + name, beforeValue, afterValue); } } - public void logAdminCredentialActivity(String adminName, String ipAddress, String targetUser, String activity, String description) + public void logAdminCredentialActivity(String adminName, String ipAddress, + String targetUser, String activity, String description) { if (enabled) { - logAdminActivity(adminName, ipAddress, targetUser, activity, description, AuditActivity.CAT_ADMIN_CREDENTIAL_MAINTENANCE, "", "", ""); + logAdminActivity(adminName, ipAddress, targetUser, activity, + description, + AuditActivity.CAT_ADMIN_CREDENTIAL_MAINTENANCE, "", "", ""); } } - public void logAdminAuthorizationActivity(String adminName, String ipAddress, String targetUser, String activity, String value, String description) + public void logAdminAuthorizationActivity(String adminName, + String ipAddress, String targetUser, String activity, String value, + String description) { if (enabled) { - logAdminActivity(adminName, ipAddress, targetUser, activity, description, AuditActivity.CAT_ADMIN_AUTHORIZATION_MAINTENANCE, "", value, ""); + logAdminActivity(adminName, ipAddress, targetUser, activity, + description, + AuditActivity.CAT_ADMIN_AUTHORIZATION_MAINTENANCE, "", + value, ""); } } - - public void logAdminUserActivity(String adminName, String ipAddress, String targetUser, String activity, String description) + + public void logAdminUserActivity(String adminName, String ipAddress, + String targetUser, String activity, String description) { if (enabled) { - logAdminActivity(adminName, ipAddress, targetUser, activity, description, AuditActivity.CAT_ADMIN_USER_MAINTENANCE, "", "", ""); + logAdminActivity(adminName, ipAddress, targetUser, activity, + description, AuditActivity.CAT_ADMIN_USER_MAINTENANCE, "", + "", ""); } } - - protected void logAdminActivity(String adminName, String ipAddress, String targetUser, String activity, String description, String category, String name, String beforeValue, String afterValue) + + protected void logAdminActivity(String adminName, String ipAddress, + String targetUser, String activity, String description, + String category, String name, String beforeValue, String afterValue) { Connection con = null; - PreparedStatement stm = null; + PreparedStatement stm = null; try { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); con = ds.getConnection(); - stm = con.prepareStatement("INSERT INTO ADMIN_ACTIVITY (ACTIVITY, CATEGORY, ADMIN, USER_NAME, TIME_STAMP, IPADDRESS, ATTR_NAME, ATTR_VALUE_BEFORE, ATTR_VALUE_AFTER, DESCRIPTION) VALUES(?,?,?,?,?,?,?,?,?,?)"); + stm = con + .prepareStatement("INSERT INTO ADMIN_ACTIVITY (ACTIVITY, CATEGORY, ADMIN, USER_NAME, TIME_STAMP, IPADDRESS, ATTR_NAME, ATTR_VALUE_BEFORE, ATTR_VALUE_AFTER, DESCRIPTION) VALUES(?,?,?,?,?,?,?,?,?,?)"); stm.setString(1, activity); stm.setString(2, category); stm.setString(3, adminName); @@ -114,46 +136,55 @@ stm.setString(7, name); stm.setString(8, beforeValue); stm.setString(9, afterValue); - stm.setString(10, description); - stm.execute(); - } + stm.setString(10, description); + stm.execute(); + } catch (SQLException e) { log.error(e); - } + } finally { try { if (stm != null) stm.close(); - } - catch (SQLException se) - {} + } + catch (SQLException se) + { + } releaseConnection(con); } } - - public void logUserActivity(String userName, String ipAddress, String activity, String description) + + public void logUserActivity(String userName, String ipAddress, + String activity, String description) { - logUserActivities(userName, ipAddress, activity, "", "", "", description, AuditActivity.CAT_USER_AUTHENTICATION); + logUserActivities(userName, ipAddress, activity, "", "", "", + description, AuditActivity.CAT_USER_AUTHENTICATION); } - - public void logUserAttributeActivity(String userName, String ipAddress, String activity, String name, String beforeValue, String afterValue, String description) + + public void logUserAttributeActivity(String userName, String ipAddress, + String activity, String name, String beforeValue, + String afterValue, String description) { - logUserActivities(userName, ipAddress, activity, name, beforeValue, afterValue, description, AuditActivity.CAT_USER_ATTRIBUTE); + logUserActivities(userName, ipAddress, activity, name, beforeValue, + afterValue, description, AuditActivity.CAT_USER_ATTRIBUTE); } - - protected void logUserActivities(String userName, String ipAddress, String activity, String name, String beforeValue, String afterValue, String description, String category) + + protected void logUserActivities(String userName, String ipAddress, + String activity, String name, String beforeValue, + String afterValue, String description, String category) { if (enabled) { Connection con = null; - PreparedStatement stm = null; + PreparedStatement stm = null; try { Timestamp timestamp = new Timestamp(System.currentTimeMillis()); con = ds.getConnection(); - stm = con.prepareStatement("INSERT INTO USER_ACTIVITY (ACTIVITY, CATEGORY, USER_NAME, TIME_STAMP, IPADDRESS, ATTR_NAME, ATTR_VALUE_BEFORE, ATTR_VALUE_AFTER, DESCRIPTION) VALUES(?,?,?,?,?,?,?,?,?)"); + stm = con + .prepareStatement("INSERT INTO USER_ACTIVITY (ACTIVITY, CATEGORY, USER_NAME, TIME_STAMP, IPADDRESS, ATTR_NAME, ATTR_VALUE_BEFORE, ATTR_VALUE_AFTER, DESCRIPTION) VALUES(?,?,?,?,?,?,?,?,?)"); stm.setString(1, activity); stm.setString(2, category); stm.setString(3, userName); @@ -161,34 +192,36 @@ stm.setString(5, ipAddress); stm.setString(6, name); stm.setString(7, beforeValue); - stm.setString(8, afterValue); + stm.setString(8, afterValue); stm.setString(9, description); stm.executeUpdate(); - } + } catch (SQLException e) { // todo log to standard Jetspeed logger e.printStackTrace(); - } + } finally { try { if (stm != null) stm.close(); - } - catch (SQLException se) - {} + } + catch (SQLException se) + { + } releaseConnection(con); } } - } - + } + void releaseConnection(Connection con) { try { if (con != null) con.close(); - } catch (SQLException e) + } + catch (SQLException e) { } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/AggregateStatisticsImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/AggregateStatisticsImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/AggregateStatisticsImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -95,7 +95,6 @@ return this.minProcessingTime; } - /* * (non-Javadoc) * @@ -103,7 +102,7 @@ */ public void setHitCount(int hitCount) { - + this.hitcount = hitCount; } @@ -126,8 +125,10 @@ { this.minProcessingTime = Math.round(time); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.statistics.AggregateStatistics#setAvgProcessingTime(float) */ public void setAvgProcessingTime(float time) @@ -136,7 +137,6 @@ } - public String toString() { String s = "hit count = " + this.hitcount + "\n"; @@ -144,20 +144,24 @@ s = s + "min time = " + this.minProcessingTime + "\n"; s = s + "avg time = " + this.avgProcessingTime + "\n"; s = s + "stddev = " + this.stddevProcessingTime + "\n"; - String listStr =""; + String listStr = ""; Iterator it = this.statlist.iterator(); int count = 0; int size = statlist.size(); int max = 5; - while((it.hasNext()) && (count++<max)) { + while ((it.hasNext()) && (count++ < max)) + { Object o = it.next(); - listStr = listStr+"\t"+o+"\n"; + listStr = listStr + "\t" + o + "\n"; } - if(size > max) { - s = s + "\tlist (top "+max+"):\n"+listStr; - } else { - s = s + "\tlist ("+size+" entries):\n"+listStr; + if (size > max) + { + s = s + "\tlist (top " + max + "):\n" + listStr; } + else + { + s = s + "\tlist (" + size + " entries):\n" + listStr; + } return s; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/BatchedStatistics.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/BatchedStatistics.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/BatchedStatistics.java 2008-05-16 01:54:54 UTC (rev 940) @@ -50,13 +50,14 @@ } msLastFlushTime = System.currentTimeMillis(); thread = new Thread(this, name); - + } - - public void startThread() { - + + public void startThread() + { + thread.start(); - + // give a quick break until the thread is running // we know thread is running when done is false while (this.done) @@ -64,7 +65,8 @@ try { Thread.sleep(1); - } catch (InterruptedException e) + } + catch (InterruptedException e) { } } @@ -106,7 +108,7 @@ public void tellThreadToStop() { keepRunning = false; - //this.thread.notify(); + // this.thread.notify(); } private boolean done = true; @@ -124,7 +126,8 @@ { this.thread.wait(msElapsedTimeThreshold / 4); } - } catch (InterruptedException ie) + } + catch (InterruptedException ie) { keepRunning = false; } @@ -176,7 +179,7 @@ // only clear the records if we actually store them... logRecords.clear(); con.setAutoCommit(autoCommit); - } + } catch (SQLException e) { // todo log to standard Jetspeed logger @@ -185,14 +188,17 @@ { con.rollback(); } - catch (Exception e2) {} - } + catch (Exception e2) + { + } + } finally { try { if (stm != null) stm.close(); - } catch (SQLException se) + } + catch (SQLException se) { } releaseConnection(con); @@ -210,7 +216,8 @@ try { if (con != null) con.close(); - } catch (SQLException e) + } + catch (SQLException e) { } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/PortalStatisticsImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/PortalStatisticsImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/PortalStatisticsImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -62,6 +62,7 @@ public class PortalStatisticsImpl extends PersistenceBrokerDaoSupport implements PortalStatistics { + /* CLF logger */ protected final static Log logger = LogFactory .getLog(PortalStatisticsImpl.class); @@ -105,8 +106,8 @@ protected long maxTimeMsToFlush_Page = 10 * 1000; - //protected ConnectionRepositoryEntry jetspeedDSEntry; - + // protected ConnectionRepositoryEntry jetspeedDSEntry; + /* after this is NOT for injection */ protected DataSource ds; @@ -123,13 +124,13 @@ * Default constructor. * </p> */ - + public PortalStatisticsImpl(boolean logToCLF, boolean logToDatabase, int maxRecordToFlush_Portal, int maxRecordToFlush_User, int maxRecordToFlush_Page, long maxTimeMsToFlush_Portal, long maxTimeMsToFlush_User, long maxTimeMsToFlush_Page, DataSource dataSource) - //ConnectionRepositoryEntry jetspeedDSEntry) + // ConnectionRepositoryEntry jetspeedDSEntry) { this.logToCLF = logToCLF; @@ -140,8 +141,8 @@ this.maxTimeMsToFlush_Portlet = maxTimeMsToFlush_Portal; this.maxTimeMsToFlush_User = maxTimeMsToFlush_User; this.maxTimeMsToFlush_Page = maxTimeMsToFlush_Page; - //this.jetspeedDSEntry = jetspeedDSEntry; - this.ds = dataSource; + // this.jetspeedDSEntry = jetspeedDSEntry; + this.ds = dataSource; currentUsers = Collections.synchronizedMap(new TreeMap()); } @@ -195,7 +196,8 @@ { storeAccessToStats(record); } - } catch (Exception e) + } + catch (Exception e) { logger.error("Exception", e); } @@ -214,7 +216,8 @@ { portletBatch = new BatchedPortletStatistics(ds, this.maxRecordToFlush_Portlet, - this.maxTimeMsToFlush_Portlet, "portletLogBatcher"); + this.maxTimeMsToFlush_Portlet, + "portletLogBatcher"); portletBatch.startThread(); } } @@ -231,8 +234,8 @@ if (pageBatch == null) { pageBatch = new BatchedPageStatistics(ds, - this.maxRecordToFlush_Page, this.maxTimeMsToFlush_Page, - "pageLogBatcher"); + this.maxRecordToFlush_Page, + this.maxTimeMsToFlush_Page, "pageLogBatcher"); pageBatch.startThread(); } } @@ -249,8 +252,8 @@ if (userBatch == null) { userBatch = new BatchedUserStatistics(ds, - this.maxRecordToFlush_User, this.maxTimeMsToFlush_User, - "userLogBatcher"); + this.maxRecordToFlush_User, + this.maxTimeMsToFlush_User, "userLogBatcher"); userBatch.startThread(); } } @@ -262,13 +265,14 @@ protected void saveAccessToCLF(LogRecord record) { - Object[] args = {""}; + Object[] args = + {""}; String logMessage = ""; if (record instanceof PortletLogRecord) { PortletLogRecord rec = (PortletLogRecord) record; Object[] args1 = - { rec.getIpAddress(), "-", rec.getUserName(), rec.getTimeStamp(), + {rec.getIpAddress(), "-", rec.getUserName(), rec.getTimeStamp(), rec.getLogType(), formatter.format(rec.getTimeStamp()), rec.getPortletName(), new Integer(rec.getStatus()).toString(), @@ -281,7 +285,7 @@ { PageLogRecord rec = (PageLogRecord) record; Object[] args1 = - { rec.getIpAddress(), "-", rec.getUserName(), rec.getTimeStamp(), + {rec.getIpAddress(), "-", rec.getUserName(), rec.getTimeStamp(), rec.getLogType(), formatter.format(rec.getTimeStamp()), new Integer(rec.getStatus()).toString(), new Long(rec.getMsElapsedTime())}; @@ -292,7 +296,7 @@ { UserLogRecord rec = (UserLogRecord) record; Object[] args1 = - { rec.getIpAddress(), "-", rec.getUserName(), rec.getTimeStamp(), + {rec.getIpAddress(), "-", rec.getUserName(), rec.getTimeStamp(), rec.getLogType(), formatter.format(rec.getTimeStamp()), new Integer(rec.getStatus()).toString(), new Long(rec.getMsElapsedTime())}; @@ -337,7 +341,8 @@ storeAccessToStats(record); } - } catch (Exception e) + } + catch (Exception e) { logger.error("Exception", e); } @@ -358,24 +363,24 @@ { synchronized (currentUsers) { - UserStats userStats = null; - - Map users = (Map)currentUsers.get(userName); - if(users != null && users.size() > 0) - { - userStats = (UserStats) users.get(ipAddress); - } - - if(userStats != null) + UserStats userStats = null; + + Map users = (Map) currentUsers.get(userName); + if (users != null && users.size() > 0) { - // only decrement if user has been logged in - currentUserCount = currentUserCount - 1; - - userStats.setNumberOfSession(userStats - .getNumberOfSessions() - 1); + userStats = (UserStats) users.get(ipAddress); + } + + if (userStats != null) + { + // only decrement if user has been logged in + currentUserCount = currentUserCount - 1; + + userStats.setNumberOfSession(userStats + .getNumberOfSessions() - 1); if (userStats.getNumberOfSessions() <= 0) { - users.remove(ipAddress); + users.remove(ipAddress); currentUsers.put(userName, users); } } @@ -400,7 +405,8 @@ storeAccessToStats(record); } - } catch (Exception e) + } + catch (Exception e) { logger.error("Exception", e); } @@ -430,31 +436,31 @@ synchronized (currentUsers) { - - UserStats userStats = null; - - Map users = (Map)currentUsers.get(userName); - if(users != null && users.size() > 0) - { - userStats = (UserStats) users.get(ipAddress); - } - else - { - users = new TreeMap(); - } - - if(userStats == null) + + UserStats userStats = null; + + Map users = (Map) currentUsers.get(userName); + if (users != null && users.size() > 0) { + userStats = (UserStats) users.get(ipAddress); + } + else + { + users = new TreeMap(); + } + + if (userStats == null) + { userStats = new UserStatsImpl(); userStats.setNumberOfSession(0); userStats.setUsername(userName); - userStats.setInetAddressFromIp(ipAddress); + userStats.setInetAddressFromIp(ipAddress); } - + userStats.setNumberOfSession(userStats .getNumberOfSessions() + 1); users.put(ipAddress, userStats); - currentUsers.put(userName, users); + currentUsers.put(userName, users); } } @@ -473,7 +479,8 @@ storeAccessToStats(record); } - } catch (Exception e) + } + catch (Exception e) { logger.error("Exception", e); } @@ -544,7 +551,8 @@ try { Thread.sleep(2); - } catch (InterruptedException ie) + } + catch (InterruptedException ie) { } } @@ -571,29 +579,34 @@ String p = period.substring(0, period.length() - 1); int ret = Integer.parseInt(p); gcEnd.add(Calendar.MONTH, (ret * -1)); - } else if (period.endsWith("d")) + } + else if (period.endsWith("d")) { // days String p = period.substring(0, period.length() - 1); int ret = Integer.parseInt(p); gcEnd.add(Calendar.HOUR, (ret * 24 * -1)); - } else if (period.endsWith("h")) + } + else if (period.endsWith("h")) { // hours String p = period.substring(0, period.length() - 1); int ret = Integer.parseInt(p); gcEnd.add(Calendar.HOUR, (ret * -1)); - } else if (period.equals("all")) + } + else if (period.equals("all")) { gcEnd = new GregorianCalendar(); gcEnd.set(1968, 07, 15); - } else + } + else { // minutes int ret = Integer.parseInt(period); gcEnd.add(Calendar.MINUTE, (ret * -1)); } - } else + } + else { gcEnd = new GregorianCalendar(); gcEnd.set(1968, 07, 15); @@ -602,8 +615,9 @@ return gcEnd.getTime(); } - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.statistics.PortalStatistics#getDefaultEmptyStatisticsQueryCriteria() */ public StatisticsQueryCriteria createStatisticsQueryCriteria() @@ -611,7 +625,9 @@ return new StatisticsQueryCriteriaImpl(); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.statistics.PortalStatistics#getDefaultEmptyAggregateStatistics() */ public AggregateStatistics getDefaultEmptyAggregateStatistics() @@ -636,21 +652,23 @@ Date start = getStartDateFromPeriod(criteria.getTimePeriod(), end); String queryType = criteria.getQueryType(); - if (PortalStatistics.QUERY_TYPE_USER.equals(queryType)) { tableName = "USER_STATISTICS"; groupColumn = "USER_NAME"; - } else if (PortalStatistics.QUERY_TYPE_PORTLET.equals(queryType)) + } + else if (PortalStatistics.QUERY_TYPE_PORTLET.equals(queryType)) { tableName = "PORTLET_STATISTICS"; groupColumn = "PORTLET"; - } else if (PortalStatistics.QUERY_TYPE_PAGE.equals(queryType)) + } + else if (PortalStatistics.QUERY_TYPE_PAGE.equals(queryType)) { tableName = "PAGE_STATISTICS"; groupColumn = "PAGE"; - } else + } + else { throw new InvalidCriteriaException( " invalid queryType passed to queryStatistics"); @@ -669,7 +687,8 @@ + "from " + tableName + " where time_stamp > ? and time_stamp < ? group by " + groupColumn + " order by " + orderColumn + " " + ascDesc; - } else + } + else { query = "select count(*) as itemcount , MIN(ELAPSED_TIME) as amin,AVG(ELAPSED_TIME) as aavg ,MAX(ELAPSED_TIME) as amax from " + tableName @@ -694,7 +713,7 @@ if (PortalStatistics.QUERY_TYPE_USER.equals(queryType)) { denominator = 1000f * 60f; // this should convert from mS to - // minutes + // minutes } if (rs.next()) { @@ -714,17 +733,18 @@ int totalRows = 5; String listsizeStr = criteria.getListsize(); int temp = -1; - try + try { temp = Integer.parseInt(listsizeStr); - } - catch (NumberFormatException e) + } + catch (NumberFormatException e) { } - if(temp != -1) { + if (temp != -1) + { totalRows = temp; } - + while ((rs2.next()) && (rowCount < totalRows)) { Map row = new HashMap(); @@ -751,23 +771,23 @@ rowCount++; } - } + } catch (SQLException e) { throw new InvalidCriteriaException(e.toString()); } - finally + finally { - try + try { - if(con != null) + if (con != null) { con.close(); } - } - catch (SQLException e) + } + catch (SQLException e) { - logger.error("error releasing the connection",e); + logger.error("error releasing the connection", e); } } @@ -806,7 +826,6 @@ { return this.currentUserCount; } - /** * @see org.apache.jetspeed.statistics.PortalStatistics#forceFlush() @@ -826,5 +845,5 @@ this.userBatch.flush(); } } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/StatisticsQueryCriteriaImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/StatisticsQueryCriteriaImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/StatisticsQueryCriteriaImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.statistics.impl; import org.apache.jetspeed.statistics.StatisticsQueryCriteria; @@ -88,7 +88,9 @@ this.queryType = queryType; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.statistics.StatisticsQueryCriteria#getListsize() */ public String getListsize() @@ -96,7 +98,9 @@ return this.listsize; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.statistics.StatisticsQueryCriteria#getSorttype() */ public String getSorttype() @@ -104,7 +108,9 @@ return this.sorttype; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.statistics.StatisticsQueryCriteria#setListsize(java.lang.String) */ public void setListsize(String listsize) @@ -113,7 +119,9 @@ } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.statistics.StatisticsQueryCriteria#setSorttype(java.lang.String) */ public void setSorttype(String sorttype) @@ -121,7 +129,9 @@ this.sorttype = sorttype; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.statistics.StatisticsQueryCriteria#getSortorder() */ public String getSortorder() @@ -129,7 +139,9 @@ return this.sortorder; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.statistics.StatisticsQueryCriteria#setSortorder(java.lang.String) */ public void setSortorder(String sortorder) Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/UserStatsImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/UserStatsImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/java/org/apache/jetspeed/statistics/impl/UserStatsImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,7 +34,7 @@ private String username; private int numberOfSessions; - + private InetAddress inetAddress; /* @@ -80,39 +80,50 @@ } - /* (non-Javadoc) - * @see org.apache.jetspeed.statistics.UserStats#getInetAddress() - */ - public InetAddress getInetAddress() { - return inetAddress; - } + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.statistics.UserStats#getInetAddress() + */ + public InetAddress getInetAddress() + { + return inetAddress; + } - /* (non-Javadoc) - * @see org.apache.jetspeed.statistics.UserStats#setInetAddress(java.net.InetAddress) - */ - public void setInetAddress(InetAddress inetAddress) { - this.inetAddress = inetAddress; - } + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.statistics.UserStats#setInetAddress(java.net.InetAddress) + */ + public void setInetAddress(InetAddress inetAddress) + { + this.inetAddress = inetAddress; + } - /* (non-Javadoc) - * @see org.apache.jetspeed.statistics.UserStats#setInetAddressFromIp(java.lang.String) - */ - public void setInetAddressFromIp(String ip) throws UnknownHostException { - this.inetAddress = InetAddress.getByName(ip); - } + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.statistics.UserStats#setInetAddressFromIp(java.lang.String) + */ + public void setInetAddressFromIp(String ip) throws UnknownHostException + { + this.inetAddress = InetAddress.getByName(ip); + } - /** - * Checks whether these two object match. Simple check for - * just the ipaddresse and username. - * - * @param Object instanceof UserStats - */ - public boolean equals(Object obj) { - - if(!(obj instanceof UserStats)) - return false; - - UserStats userstat = (UserStats)obj; - return this.inetAddress.equals(userstat.getInetAddress()) && this.username.equals(userstat.getUsername()); - } + /** + * Checks whether these two object match. Simple check for just the + * ipaddresse and username. + * + * @param Object + * instanceof UserStats + */ + public boolean equals(Object obj) + { + + if (!(obj instanceof UserStats)) return false; + + UserStats userstat = (UserStats) obj; + return this.inetAddress.equals(userstat.getInetAddress()) + && this.username.equals(userstat.getUsername()); + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/test/org/apache/jetspeed/audit/TestAuditActivity.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/test/org/apache/jetspeed/audit/TestAuditActivity.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/test/org/apache/jetspeed/audit/TestAuditActivity.java 2008-05-16 01:54:54 UTC (rev 940) @@ -58,18 +58,19 @@ public static void main(String args[]) { junit.awtui.TestRunner.main(new String[] - { TestAuditActivity.class.getName()}); + {TestAuditActivity.class.getName()}); } protected void setUp() throws Exception { super.setUp(); - - this.audit = (AuditActivity) ctx.getBean("org.apache.jetspeed.audit.AuditActivity"); + + this.audit = (AuditActivity) ctx + .getBean("org.apache.jetspeed.audit.AuditActivity"); assertNotNull("audit activity service not found ", this.audit); } - + public void clearDBs() { try @@ -84,7 +85,8 @@ psmt.execute(); psmt.close(); if (con != null) con.close(); - } catch (SQLException e) + } + catch (SQLException e) { fail("problem with database connection:" + e.toString()); } @@ -106,7 +108,8 @@ } psmt.close(); if (con != null) con.close(); - } catch (SQLException e) + } + catch (SQLException e) { fail("problem with database connection:" + e.toString()); } @@ -122,7 +125,7 @@ { return count("SELECT count(*) from USER_ACTIVITY"); } - + public static Test suite() { // All methods starting with "test" will be executed in the test suite. @@ -136,79 +139,108 @@ audit.setEnabled(true); assertTrue(audit.getEnabled()); - + // Log User Activity - audit.logUserActivity(USER, IP1, AuditActivity.AUTHENTICATION_SUCCESS, MSG_AUTHENTICATION_SUCCESS); - audit.logUserActivity(USER, IP1, AuditActivity.AUTHENTICATION_FAILURE, MSG_AUTHENTICATION_FAILURE); - + audit.logUserActivity(USER, IP1, AuditActivity.AUTHENTICATION_SUCCESS, + MSG_AUTHENTICATION_SUCCESS); + audit.logUserActivity(USER, IP1, AuditActivity.AUTHENTICATION_FAILURE, + MSG_AUTHENTICATION_FAILURE); + int userCount = this.countUserActivity(); assertEquals(userCount, 2); - - ActivityBean userBean = lookupUserActivity(USER_QUERY, AuditActivity.AUTHENTICATION_SUCCESS); - assertEquals(userBean.getActivity(), AuditActivity.AUTHENTICATION_SUCCESS); - assertEquals(userBean.getCategory(), AuditActivity.CAT_USER_AUTHENTICATION); + + ActivityBean userBean = lookupUserActivity(USER_QUERY, + AuditActivity.AUTHENTICATION_SUCCESS); + assertEquals(userBean.getActivity(), + AuditActivity.AUTHENTICATION_SUCCESS); + assertEquals(userBean.getCategory(), + AuditActivity.CAT_USER_AUTHENTICATION); assertEquals(userBean.getUserName(), USER); assertNotNull(userBean.getTimestamp()); assertEquals(userBean.getIpAddress(), IP1); assertEquals(userBean.getDescription(), MSG_AUTHENTICATION_SUCCESS); - - userBean = lookupUserActivity(USER_QUERY, AuditActivity.AUTHENTICATION_FAILURE); - assertEquals(userBean.getActivity(), AuditActivity.AUTHENTICATION_FAILURE); - assertEquals(userBean.getCategory(), AuditActivity.CAT_USER_AUTHENTICATION); + + userBean = lookupUserActivity(USER_QUERY, + AuditActivity.AUTHENTICATION_FAILURE); + assertEquals(userBean.getActivity(), + AuditActivity.AUTHENTICATION_FAILURE); + assertEquals(userBean.getCategory(), + AuditActivity.CAT_USER_AUTHENTICATION); assertEquals(userBean.getUserName(), USER); assertNotNull(userBean.getTimestamp()); assertEquals(userBean.getIpAddress(), IP1); - assertEquals(userBean.getDescription(), MSG_AUTHENTICATION_FAILURE); + assertEquals(userBean.getDescription(), MSG_AUTHENTICATION_FAILURE); // Test logging User Attribute activity - audit.logUserAttributeActivity(USER, IP1, AuditActivity.USER_ADD_ATTRIBUTE, ATTRIBUTE_NAME_1, ATTRIBUTE_VALUE_BEFORE_1, ATTRIBUTE_VALUE_AFTER_1, MSG_ATTRIBUTE); - - userBean = lookupUserActivity(USER_QUERY, AuditActivity.USER_ADD_ATTRIBUTE); + audit.logUserAttributeActivity(USER, IP1, + AuditActivity.USER_ADD_ATTRIBUTE, ATTRIBUTE_NAME_1, + ATTRIBUTE_VALUE_BEFORE_1, ATTRIBUTE_VALUE_AFTER_1, + MSG_ATTRIBUTE); + + userBean = lookupUserActivity(USER_QUERY, + AuditActivity.USER_ADD_ATTRIBUTE); assertEquals(userBean.getActivity(), AuditActivity.USER_ADD_ATTRIBUTE); assertEquals(userBean.getCategory(), AuditActivity.CAT_USER_ATTRIBUTE); assertEquals(userBean.getUserName(), USER); assertNotNull(userBean.getTimestamp()); assertEquals(userBean.getIpAddress(), IP1); - assertEquals(userBean.getDescription(), MSG_ATTRIBUTE); + assertEquals(userBean.getDescription(), MSG_ATTRIBUTE); assertEquals(userBean.getBeforeValue(), ATTRIBUTE_VALUE_BEFORE_1); assertEquals(userBean.getAfterValue(), ATTRIBUTE_VALUE_AFTER_1); - - + // Log Admin Activity - audit.logAdminUserActivity(ADMIN_USER, IP1, USER, AuditActivity.USER_CREATE, MSG_ADDING_USER); - audit.logAdminCredentialActivity(ADMIN_USER, IP1, USER, AuditActivity.PASSWORD_CHANGE_SUCCESS, MSG_CHANGING_PW); - audit.logAdminAttributeActivity(ADMIN_USER, IP1, USER, AuditActivity.USER_ADD_ATTRIBUTE, ATTRIBUTE_NAME_1, ATTRIBUTE_VALUE_BEFORE_1, ATTRIBUTE_VALUE_AFTER_1, MSG_ATTRIBUTE); - + audit.logAdminUserActivity(ADMIN_USER, IP1, USER, + AuditActivity.USER_CREATE, MSG_ADDING_USER); + audit.logAdminCredentialActivity(ADMIN_USER, IP1, USER, + AuditActivity.PASSWORD_CHANGE_SUCCESS, MSG_CHANGING_PW); + audit.logAdminAttributeActivity(ADMIN_USER, IP1, USER, + AuditActivity.USER_ADD_ATTRIBUTE, ATTRIBUTE_NAME_1, + ATTRIBUTE_VALUE_BEFORE_1, ATTRIBUTE_VALUE_AFTER_1, + MSG_ATTRIBUTE); + int adminCount = this.countAdminActivity(); assertEquals(adminCount, 3); - - ActivityBean adminBean = lookupAdminActivity(ADMIN_QUERY, AuditActivity.USER_CREATE); + + ActivityBean adminBean = lookupAdminActivity(ADMIN_QUERY, + AuditActivity.USER_CREATE); assertEquals(adminBean.getActivity(), AuditActivity.USER_CREATE); - assertEquals(adminBean.getCategory(), AuditActivity.CAT_ADMIN_USER_MAINTENANCE); + assertEquals(adminBean.getCategory(), + AuditActivity.CAT_ADMIN_USER_MAINTENANCE); assertEquals(adminBean.getAdmin(), ADMIN_USER); assertEquals(adminBean.getUserName(), USER); assertNotNull(adminBean.getTimestamp()); assertEquals(adminBean.getIpAddress(), IP1); assertEquals(adminBean.getDescription(), MSG_ADDING_USER); - assertTrue(adminBean.getName() == null || adminBean.getName().equals("")); - assertTrue(adminBean.getBeforeValue() == null || adminBean.getBeforeValue().equals("")); - assertTrue(adminBean.getAfterValue() == null || adminBean.getAfterValue().equals("")); + assertTrue(adminBean.getName() == null + || adminBean.getName().equals("")); + assertTrue(adminBean.getBeforeValue() == null + || adminBean.getBeforeValue().equals("")); + assertTrue(adminBean.getAfterValue() == null + || adminBean.getAfterValue().equals("")); - adminBean = lookupAdminActivity(ADMIN_QUERY, AuditActivity.PASSWORD_CHANGE_SUCCESS); - assertEquals(adminBean.getActivity(), AuditActivity.PASSWORD_CHANGE_SUCCESS); - assertEquals(adminBean.getCategory(), AuditActivity.CAT_ADMIN_CREDENTIAL_MAINTENANCE); + adminBean = lookupAdminActivity(ADMIN_QUERY, + AuditActivity.PASSWORD_CHANGE_SUCCESS); + assertEquals(adminBean.getActivity(), + AuditActivity.PASSWORD_CHANGE_SUCCESS); + assertEquals(adminBean.getCategory(), + AuditActivity.CAT_ADMIN_CREDENTIAL_MAINTENANCE); assertEquals(adminBean.getAdmin(), ADMIN_USER); assertEquals(adminBean.getUserName(), USER); assertNotNull(adminBean.getTimestamp()); assertEquals(adminBean.getIpAddress(), IP1); assertEquals(adminBean.getDescription(), MSG_CHANGING_PW); - assertTrue(adminBean.getName() == null || adminBean.getName().equals("")); - assertTrue(adminBean.getBeforeValue() == null || adminBean.getBeforeValue().equals("")); - assertTrue(adminBean.getAfterValue() == null || adminBean.getAfterValue().equals("")); + assertTrue(adminBean.getName() == null + || adminBean.getName().equals("")); + assertTrue(adminBean.getBeforeValue() == null + || adminBean.getBeforeValue().equals("")); + assertTrue(adminBean.getAfterValue() == null + || adminBean.getAfterValue().equals("")); - adminBean = lookupAdminActivity(ADMIN_QUERY, AuditActivity.USER_ADD_ATTRIBUTE); + adminBean = lookupAdminActivity(ADMIN_QUERY, + AuditActivity.USER_ADD_ATTRIBUTE); assertEquals(adminBean.getActivity(), AuditActivity.USER_ADD_ATTRIBUTE); - assertEquals(adminBean.getCategory(), AuditActivity.CAT_ADMIN_ATTRIBUTE_MAINTENANCE); + assertEquals(adminBean.getCategory(), + AuditActivity.CAT_ADMIN_ATTRIBUTE_MAINTENANCE); assertEquals(adminBean.getAdmin(), ADMIN_USER); assertEquals(adminBean.getUserName(), USER); assertNotNull(adminBean.getTimestamp()); @@ -217,36 +249,49 @@ assertEquals(adminBean.getName(), ATTRIBUTE_NAME_1); assertEquals(adminBean.getBeforeValue(), ATTRIBUTE_VALUE_BEFORE_1); assertEquals(adminBean.getAfterValue(), ATTRIBUTE_VALUE_AFTER_1); - + audit.setEnabled(false); assertFalse(audit.getEnabled()); - audit.logAdminAttributeActivity(ADMIN_USER, IP1, USER, AuditActivity.USER_ADD_ATTRIBUTE, ATTRIBUTE_NAME_1, ATTRIBUTE_VALUE_BEFORE_1, ATTRIBUTE_VALUE_AFTER_1, MSG_ATTRIBUTE); + audit.logAdminAttributeActivity(ADMIN_USER, IP1, USER, + AuditActivity.USER_ADD_ATTRIBUTE, ATTRIBUTE_NAME_1, + ATTRIBUTE_VALUE_BEFORE_1, ATTRIBUTE_VALUE_AFTER_1, + MSG_ATTRIBUTE); adminCount = this.countAdminActivity(); - assertEquals(adminCount, 3); + assertEquals(adminCount, 3); } - + private static String USER_QUERY = "SELECT * FROM USER_ACTIVITY WHERE ACTIVITY = ?"; + private static String ADMIN_QUERY = "SELECT * FROM ADMIN_ACTIVITY WHERE ACTIVITY = ?"; - + private static String MSG_AUTHENTICATION_SUCCESS = "logging on via Jetspeed Portal"; + private static String MSG_AUTHENTICATION_FAILURE = "failure logging on via Jetspeed Portal"; + private static String MSG_ADDING_USER = "adding new user"; + private static String MSG_CHANGING_PW = "changing password"; + private static String MSG_ATTRIBUTE = "Attribute added for user"; - + private static String ADMIN_USER = "admin"; + private static String USER = "nelson"; + private static String IP1 = "123.234.145.156"; + private static String ATTRIBUTE_NAME_1 = "attribute1"; + private static String ATTRIBUTE_VALUE_BEFORE_1 = "value1BEFORE"; + private static String ATTRIBUTE_VALUE_AFTER_1 = "value1AFTER"; - - private ActivityBean lookupUserActivity(String query, String keyActivity) throws SQLException + private ActivityBean lookupUserActivity(String query, String keyActivity) + throws SQLException { Connection con = null; PreparedStatement pstmt = null; - ResultSet rs = null; + ResultSet rs = null; try { con = audit.getDataSource().getConnection(); @@ -262,7 +307,7 @@ bean.setIpAddress(rs.getString(5)); bean.setName(rs.getString(6)); bean.setBeforeValue(rs.getString(7)); - bean.setAfterValue(rs.getString(8)); + bean.setAfterValue(rs.getString(8)); bean.setDescription(rs.getString(9)); return bean; } @@ -279,7 +324,7 @@ if (rs != null) { rs.close(); - } + } if (con != null) { try @@ -287,12 +332,14 @@ con.close(); } catch (SQLException ee) - {} + { + } } - } + } } - private ActivityBean lookupAdminActivity(String query, String keyActivity) throws SQLException + private ActivityBean lookupAdminActivity(String query, String keyActivity) + throws SQLException { Connection con = null; PreparedStatement pstmt = null; @@ -338,21 +385,22 @@ con.close(); } catch (SQLException ee) - {} + { + } } - } - } + } + } protected String[] getConfigurations() { return new String[] - { "statistics.xml", "transaction.xml", "boot/datasource.xml"}; + {"statistics.xml", "transaction.xml", "boot/datasource.xml"}; } protected String[] getBootConfigurations() { return new String[] - { "boot/datasource.xml"}; + {"boot/datasource.xml"}; } - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/test/org/apache/jetspeed/statistics/TestStatistics.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/test/org/apache/jetspeed/statistics/TestStatistics.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/statistics/src/test/org/apache/jetspeed/statistics/TestStatistics.java 2008-05-16 01:54:54 UTC (rev 940) @@ -48,8 +48,9 @@ */ public class TestStatistics extends DatasourceEnabledSpringTestCase { - String USERNAME = "anotherFaker"; + String USERNAME = "anotherFaker"; + private PortalStatistics statistics = null; /* @@ -72,14 +73,14 @@ public static void main(String args[]) { junit.awtui.TestRunner.main(new String[] - { TestStatistics.class.getName()}); + {TestStatistics.class.getName()}); } protected void setUp() throws Exception { super.setUp(); - + this.statistics = (PortalStatistics) ctx.getBean("PortalStatistics"); assertNotNull("statistics not found ", statistics); } @@ -87,14 +88,16 @@ public void clearDBs() { - try { - DatabaseMetaData dmd = statistics.getDataSource().getConnection().getMetaData(); - System.out.println("Oh... just for reference we're running against "+dmd.getDatabaseProductName()); - System.out.println("with the driver = "+dmd.getDriverName()); - System.out.println(" with the url = "+dmd.getURL()); - + DatabaseMetaData dmd = statistics.getDataSource().getConnection() + .getMetaData(); + System.out + .println("Oh... just for reference we're running against " + + dmd.getDatabaseProductName()); + System.out.println("with the driver = " + dmd.getDriverName()); + System.out.println(" with the url = " + dmd.getURL()); + Connection con = statistics.getDataSource().getConnection(); PreparedStatement psmt = con @@ -108,7 +111,8 @@ psmt.execute(); psmt.close(); if (con != null) con.close(); - } catch (SQLException e) + } + catch (SQLException e) { fail("problem with database connection:" + e.toString()); } @@ -130,7 +134,8 @@ } psmt.close(); if (con != null) con.close(); - } catch (SQLException e) + } + catch (SQLException e) { fail("problem with database connection:" + e.toString()); } @@ -186,10 +191,9 @@ assertNotNull("list returned is null", l); assertEquals("wrong number of users in list", 1, l.size()); -// statistics.logUserLogout("123.234.145.156", "SuperFakeyUser", -// elapsedTime); - statistics.logUserLogout("123.234.145.156", USERNAME, - elapsedTime); + // statistics.logUserLogout("123.234.145.156", "SuperFakeyUser", + // elapsedTime); + statistics.logUserLogout("123.234.145.156", USERNAME, elapsedTime); statistics.forceFlush(); @@ -224,7 +228,7 @@ portlet.setName("TestPortlet"); portlet.setPortletApplicationDefinition(app); long elapsedTime = 123 + i; - //System.out.println("logging something, number "+i); + // System.out.println("logging something, number "+i); statistics.logPortletAccess(request, portlet.getUniqueName(), "401", elapsedTime); statistics.logPageAccess(request, "401", elapsedTime); @@ -235,14 +239,14 @@ assertNotNull("list returned is null", l); assertEquals("wrong number of users in list", 1, l.size()); -// statistics.logUserLogout("123.234.145.156", "SuperFakeyUser", -// elapsedTime); - statistics.logUserLogout("123.234.145.156", USERNAME, - elapsedTime); + // statistics.logUserLogout("123.234.145.156", "SuperFakeyUser", + // elapsedTime); + statistics.logUserLogout("123.234.145.156", USERNAME, elapsedTime); try { Thread.sleep(200); - } catch (InterruptedException ie) + } + catch (InterruptedException ie) { } } @@ -261,41 +265,40 @@ } - public void testQuerySystem() throws Exception { System.out.println("testing Query System"); StatisticsQueryCriteria sqc = new StatisticsQueryCriteriaImpl(); sqc.setQueryType(PortalStatistics.QUERY_TYPE_USER); int desired = 5; - sqc.setListsize(""+desired); + sqc.setListsize("" + desired); sqc.setSorttype("count"); sqc.setSortorder("desc"); AggregateStatistics as = statistics.queryStatistics(sqc); assertNotNull(as); System.out.println("user = " + as); int size = as.getStatlist().size(); - assertTrue( (size <=desired)); + assertTrue((size <= desired)); sqc.setQueryType(PortalStatistics.QUERY_TYPE_PORTLET); - sqc.setListsize(""+desired); + sqc.setListsize("" + desired); sqc.setSorttype("count"); sqc.setSortorder("desc"); as = statistics.queryStatistics(sqc); assertNotNull(as); System.out.println("portlet = " + as); size = as.getStatlist().size(); - assertTrue( (size <=desired)); + assertTrue((size <= desired)); sqc.setQueryType(PortalStatistics.QUERY_TYPE_PAGE); - sqc.setListsize(""+desired); + sqc.setListsize("" + desired); sqc.setSorttype("count"); sqc.setSortorder("desc"); as = statistics.queryStatistics(sqc); assertNotNull(as); System.out.println("page = " + as); size = as.getStatlist().size(); - assertTrue( (size <=desired)); + assertTrue((size <= desired)); } @@ -305,7 +308,7 @@ MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpSession session = new MockHttpSession(); -// Principal p = new UserPrincipalImpl("anotherFaker"); + // Principal p = new UserPrincipalImpl("anotherFaker"); Principal p = new UserPrincipalImpl(USERNAME); request.setUserPrincipal(p); @@ -326,13 +329,13 @@ protected String[] getConfigurations() { return new String[] - { "statistics.xml", "transaction.xml", "boot/datasource.xml"}; + {"statistics.xml", "transaction.xml", "boot/datasource.xml"}; } protected String[] getBootConfigurations() { return new String[] - { "boot/datasource.xml"}; + {"boot/datasource.xml"}; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/IFrameGenericPortlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/IFrameGenericPortlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/IFrameGenericPortlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -67,22 +67,27 @@ maxAttributes.put("STYLE", ""); } - private String getAttributePreference(PortletPreferences prefs, String attribute) + private String getAttributePreference(PortletPreferences prefs, + String attribute) { return this.getMappedAttributePreference(prefs, attribute, attributes); } - private String getMaxAttributePreference(PortletPreferences prefs, String attribute) + private String getMaxAttributePreference(PortletPreferences prefs, + String attribute) { - return this.getMappedAttributePreference(prefs, "MAX-" + attribute, maxAttributes); + return this.getMappedAttributePreference(prefs, "MAX-" + attribute, + maxAttributes); } - private String getMappedAttributePreference(PortletPreferences prefs, String attribute, Map map) + private String getMappedAttributePreference(PortletPreferences prefs, + String attribute, Map map) { return prefs.getValue(attribute, (String) map.get(attribute)); } - private void appendAttribute(PortletPreferences prefs, StringBuffer content, String attribute, Map map) + private void appendAttribute(PortletPreferences prefs, + StringBuffer content, String attribute, Map map) { String value; @@ -92,22 +97,26 @@ value = getAttributePreference(prefs, attribute); if (value == null || value.length() == 0) { return; } - content.append(" ").append(attribute).append("=\"").append(value).append("\""); + content.append(" ").append(attribute).append("=\"").append(value) + .append("\""); } - private void appendAttribute(PortletPreferences prefs, StringBuffer content, String attribute) + private void appendAttribute(PortletPreferences prefs, + StringBuffer content, String attribute) { appendAttribute(prefs, content, attribute, attributes); } - private void appendMaxAttribute(PortletPreferences prefs, StringBuffer content, String attribute) + private void appendMaxAttribute(PortletPreferences prefs, + StringBuffer content, String attribute) { appendAttribute(prefs, content, attribute, maxAttributes); } - public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException + public void doView(RenderRequest request, RenderResponse response) + throws PortletException, IOException { - String viewPage = (String)request.getAttribute(PARAM_VIEW_PAGE); + String viewPage = (String) request.getAttribute(PARAM_VIEW_PAGE); if (viewPage != null) { super.doView(request, response); @@ -118,7 +127,8 @@ } } - public void doEdit(RenderRequest request, RenderResponse response) throws PortletException, IOException + public void doEdit(RenderRequest request, RenderResponse response) + throws PortletException, IOException { response.setContentType("text/html"); doPreferencesEdit(request, response); @@ -127,7 +137,8 @@ /** * Render IFRAME content */ - protected void doIFrame(RenderRequest request, RenderResponse response) throws IOException + protected void doIFrame(RenderRequest request, RenderResponse response) + throws IOException { PortletPreferences prefs = request.getPreferences(); String source = getURLSource(request, response, prefs); @@ -135,12 +146,14 @@ StringBuffer content = new StringBuffer(4096); // fix JS2-349 - content.append("<TABLE CLASS='iframePortletTableContainer' WIDTH='100%'><TBODY CLASS='iframePortletTbodyContainer'><TR><TD>"); + content + .append("<TABLE CLASS='iframePortletTableContainer' WIDTH='100%'><TBODY CLASS='iframePortletTbodyContainer'><TR><TD>"); content.append("<IFRAME"); // special case source - content.append(" ").append("SRC").append("=\"").append(source).append("\""); + content.append(" ").append("SRC").append("=\"").append(source).append( + "\""); appendAttribute(prefs, content, "ALIGN"); appendAttribute(prefs, content, "CLASS"); @@ -164,8 +177,8 @@ appendAttribute(prefs, content, "STYLE"); } content.append(">"); - content.append("<P STYLE=\"textAlign:center\"><A HREF=\"").append(source).append("\">").append(source).append( - "</A></P>"); + content.append("<P STYLE=\"textAlign:center\"><A HREF=\"").append( + source).append("\">").append(source).append("</A></P>"); content.append("</IFRAME>"); // end fix JS2-349 @@ -176,7 +189,8 @@ response.getWriter().print(content.toString()); } - public String getURLSource(RenderRequest request, RenderResponse response, PortletPreferences prefs) + public String getURLSource(RenderRequest request, RenderResponse response, + PortletPreferences prefs) { String source = getAttributePreference(prefs, "SRC"); if (source == null) source = ""; @@ -186,8 +200,8 @@ /** * Save the prefs */ - public void processAction(ActionRequest request, ActionResponse actionResponse) throws PortletException, - IOException + public void processAction(ActionRequest request, + ActionResponse actionResponse) throws PortletException, IOException { processPreferencesAction(request, actionResponse); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/IFramePortlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/IFramePortlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/IFramePortlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,6 +17,7 @@ package org.apache.jetspeed.portlet; import java.io.IOException; + import javax.portlet.GenericPortlet; import javax.portlet.PortletConfig; import javax.portlet.PortletException; @@ -27,57 +28,90 @@ /** * IFramePortlet - * - * TODO: - * - add capabilities test for IFRAME - * - add locale specific "no iframes" message - * + * + * TODO: - add capabilities test for IFRAME - add locale specific "no iframes" + * message + * * @author <a href="mailto:rwatler ¡÷ finali.com">Randy Watler</a> * @version $Id: IFramePortlet.java 578925 2007-09-24 19:22:58Z smilek $ */ public class IFramePortlet extends GenericPortlet { + /** * Configuration constants. */ public static final String ENABLE_SOURCE_PREFERENCES_PARAM = "enableSourcePreferences"; + public static final String ENABLE_PREFERENCES_PARAM = "enablePreferences"; + public static final String CUSTOM_SOURCE_PARAM = "customSource"; + public static final String MAXIMIZED_CUSTOM_SOURCE_PARAM = "maximizedCustomSource"; + public static final String EDIT_SOURCE_PARAM = "editSource"; + public static final String MAXIMIZED_EDIT_SOURCE_PARAM = "maximizedEditSource"; + public static final String HELP_SOURCE_PARAM = "helpSource"; + public static final String MAXIMIZED_HELP_SOURCE_PARAM = "maximizedHelpSource"; + public static final String VIEW_SOURCE_PARAM = "viewSource"; + public static final String MAXIMIZED_VIEW_SOURCE_PARAM = "maximizedViewSource"; + public static final String ALIGN_ATTR_PARAM = "align"; + public static final String CLASS_ATTR_PARAM = "class"; + public static final String FRAME_BORDER_ATTR_PARAM = "frameBorder"; + public static final String HEIGHT_ATTR_PARAM = "height"; + public static final String ID_ATTR_PARAM = "id"; + public static final String MARGIN_HEIGHT_ATTR_PARAM = "marginHeight"; + public static final String MARGIN_WIDTH_ATTR_PARAM = "marginWidth"; + public static final String MAXIMIZED_HEIGHT_ATTR_PARAM = "maximizedHeight"; + public static final String MAXIMIZED_SCROLLING_ATTR_PARAM = "maximizedScrolling"; + public static final String MAXIMIZED_STYLE_ATTR_PARAM = "maximizedStyle"; + public static final String MAXIMIZED_WIDTH_ATTR_PARAM = "maximizedWidth"; + public static final String NAME_ATTR_PARAM = "name"; + public static final String SCROLLING_ATTR_PARAM = "scrolling"; + public static final String STYLE_ATTR_PARAM = "style"; + public static final String WIDTH_ATTR_PARAM = "width"; /** * Configuration default constants. */ public static final String ALIGN_ATTR_DEFAULT = "BOTTOM"; + public static final String FRAME_BORDER_ATTR_DEFAULT = "0"; + public static final String HEIGHT_ATTR_DEFAULT = ""; + public static final String MARGIN_HEIGHT_ATTR_DEFAULT = "0"; + public static final String MARGIN_WIDTH_ATTR_DEFAULT = "0"; + public static final String MAXIMIZED_HEIGHT_ATTR_DEFAULT = "100%"; + public static final String MAXIMIZED_SCROLLING_ATTR_DEFAULT = "AUTO"; + public static final String MAXIMIZED_WIDTH_ATTR_DEFAULT = "100%"; + public static final String SCROLLING_ATTR_DEFAULT = "NO"; + public static final String WIDTH_ATTR_DEFAULT = "100%"; /** @@ -89,31 +123,52 @@ * Default IFRAME source attribute members. */ private String defaultCustomSource; + private String defaultMaximizedCustomSource; + private String defaultEditSource; + private String defaultMaximizedEditSource; + private String defaultHelpSource; + private String defaultMaximizedHelpSource; + private String defaultViewSource; + private String defaultMaximizedViewSource; /** * Default IFRAME attribute members. */ private String defaultAlignAttr; + private String defaultClassAttr; + private String defaultFrameBorderAttr; + private String defaultHeightAttr; + private String defaultIdAttr; + private String defaultMarginHeightAttr; + private String defaultMarginWidthAttr; + private String defaultMaximizedHeightAttr; + private String defaultMaximizedScrollingAttr; + private String defaultMaximizedStyleAttr; + private String defaultMaximizedWidthAttr; + private String defaultNameAttr; + private String defaultScrollingAttr; + private String defaultStyleAttr; + private String defaultWidthAttr; /** @@ -126,15 +181,15 @@ /** * Initialize portlet configuration. */ - public void init(PortletConfig config) - throws PortletException + public void init(PortletConfig config) throws PortletException { super.init(config); String initParam = config.getInitParameter(ENABLE_PREFERENCES_PARAM); if (initParam == null) { - initParam = config.getInitParameter(ENABLE_SOURCE_PREFERENCES_PARAM); + initParam = config + .getInitParameter(ENABLE_SOURCE_PREFERENCES_PARAM); } if (initParam != null) { @@ -142,59 +197,78 @@ } defaultCustomSource = config.getInitParameter(CUSTOM_SOURCE_PARAM); - defaultMaximizedCustomSource = config.getInitParameter(MAXIMIZED_CUSTOM_SOURCE_PARAM); + defaultMaximizedCustomSource = config + .getInitParameter(MAXIMIZED_CUSTOM_SOURCE_PARAM); defaultEditSource = config.getInitParameter(EDIT_SOURCE_PARAM); - defaultMaximizedEditSource = config.getInitParameter(MAXIMIZED_EDIT_SOURCE_PARAM); + defaultMaximizedEditSource = config + .getInitParameter(MAXIMIZED_EDIT_SOURCE_PARAM); defaultHelpSource = config.getInitParameter(HELP_SOURCE_PARAM); - defaultMaximizedHelpSource = config.getInitParameter(MAXIMIZED_HELP_SOURCE_PARAM); + defaultMaximizedHelpSource = config + .getInitParameter(MAXIMIZED_HELP_SOURCE_PARAM); defaultViewSource = config.getInitParameter(VIEW_SOURCE_PARAM); - defaultMaximizedViewSource = config.getInitParameter(MAXIMIZED_VIEW_SOURCE_PARAM); + defaultMaximizedViewSource = config + .getInitParameter(MAXIMIZED_VIEW_SOURCE_PARAM); - defaultAlignAttr = getAttributeParam(config, ALIGN_ATTR_PARAM, ALIGN_ATTR_DEFAULT); + defaultAlignAttr = getAttributeParam(config, ALIGN_ATTR_PARAM, + ALIGN_ATTR_DEFAULT); defaultClassAttr = getAttributeParam(config, CLASS_ATTR_PARAM, null); - defaultFrameBorderAttr = getAttributeParam(config, FRAME_BORDER_ATTR_PARAM, FRAME_BORDER_ATTR_DEFAULT); - defaultHeightAttr = getAttributeParam(config, HEIGHT_ATTR_PARAM, HEIGHT_ATTR_DEFAULT); + defaultFrameBorderAttr = getAttributeParam(config, + FRAME_BORDER_ATTR_PARAM, FRAME_BORDER_ATTR_DEFAULT); + defaultHeightAttr = getAttributeParam(config, HEIGHT_ATTR_PARAM, + HEIGHT_ATTR_DEFAULT); defaultIdAttr = getAttributeParam(config, ID_ATTR_PARAM, null); - defaultMarginHeightAttr = getAttributeParam(config, MARGIN_HEIGHT_ATTR_PARAM, MARGIN_HEIGHT_ATTR_DEFAULT); - defaultMarginWidthAttr = getAttributeParam(config, MARGIN_WIDTH_ATTR_PARAM, MARGIN_WIDTH_ATTR_DEFAULT); - defaultMaximizedHeightAttr = getAttributeParam(config, MAXIMIZED_HEIGHT_ATTR_PARAM, MAXIMIZED_HEIGHT_ATTR_DEFAULT); - defaultMaximizedScrollingAttr = getAttributeParam(config, MAXIMIZED_SCROLLING_ATTR_PARAM, MAXIMIZED_SCROLLING_ATTR_DEFAULT); - defaultMaximizedStyleAttr = getAttributeParam(config, MAXIMIZED_STYLE_ATTR_PARAM, null); - defaultMaximizedWidthAttr = getAttributeParam(config, MAXIMIZED_WIDTH_ATTR_PARAM, MAXIMIZED_WIDTH_ATTR_DEFAULT); + defaultMarginHeightAttr = getAttributeParam(config, + MARGIN_HEIGHT_ATTR_PARAM, MARGIN_HEIGHT_ATTR_DEFAULT); + defaultMarginWidthAttr = getAttributeParam(config, + MARGIN_WIDTH_ATTR_PARAM, MARGIN_WIDTH_ATTR_DEFAULT); + defaultMaximizedHeightAttr = getAttributeParam(config, + MAXIMIZED_HEIGHT_ATTR_PARAM, MAXIMIZED_HEIGHT_ATTR_DEFAULT); + defaultMaximizedScrollingAttr = getAttributeParam(config, + MAXIMIZED_SCROLLING_ATTR_PARAM, + MAXIMIZED_SCROLLING_ATTR_DEFAULT); + defaultMaximizedStyleAttr = getAttributeParam(config, + MAXIMIZED_STYLE_ATTR_PARAM, null); + defaultMaximizedWidthAttr = getAttributeParam(config, + MAXIMIZED_WIDTH_ATTR_PARAM, MAXIMIZED_WIDTH_ATTR_DEFAULT); defaultNameAttr = getAttributeParam(config, NAME_ATTR_PARAM, null); - defaultScrollingAttr = getAttributeParam(config, SCROLLING_ATTR_PARAM, SCROLLING_ATTR_DEFAULT); + defaultScrollingAttr = getAttributeParam(config, SCROLLING_ATTR_PARAM, + SCROLLING_ATTR_DEFAULT); defaultStyleAttr = getAttributeParam(config, STYLE_ATTR_PARAM, null); - defaultWidthAttr = getAttributeParam(config, WIDTH_ATTR_PARAM, WIDTH_ATTR_DEFAULT); + defaultWidthAttr = getAttributeParam(config, WIDTH_ATTR_PARAM, + WIDTH_ATTR_DEFAULT); } - + /** * Generate IFRAME with custom source. */ public void doCustom(RenderRequest request, RenderResponse response) - throws PortletException, IOException + throws PortletException, IOException { // get IFRAME source String source = null; if (request.getWindowState().equals(WindowState.MAXIMIZED)) { - source = getPreferenceOrDefault(request, MAXIMIZED_CUSTOM_SOURCE_PARAM, defaultMaximizedCustomSource); + source = getPreferenceOrDefault(request, + MAXIMIZED_CUSTOM_SOURCE_PARAM, defaultMaximizedCustomSource); } if (source == null) { - source = getPreferenceOrDefault(request, CUSTOM_SOURCE_PARAM, defaultCustomSource); + source = getPreferenceOrDefault(request, CUSTOM_SOURCE_PARAM, + defaultCustomSource); } - if ((source == null) && request.getWindowState().equals(WindowState.MAXIMIZED)) + if ((source == null) + && request.getWindowState().equals(WindowState.MAXIMIZED)) { - source = getPreferenceOrDefault(request, MAXIMIZED_VIEW_SOURCE_PARAM, defaultMaximizedViewSource); + source = getPreferenceOrDefault(request, + MAXIMIZED_VIEW_SOURCE_PARAM, defaultMaximizedViewSource); } if (source == null) { - source = getPreferenceOrDefault(request, VIEW_SOURCE_PARAM, defaultViewSource); + source = getPreferenceOrDefault(request, VIEW_SOURCE_PARAM, + defaultViewSource); } - if (source == null) - { - throw new PortletException("IFRAME source not specified for custom portlet mode."); - } + if (source == null) { throw new PortletException( + "IFRAME source not specified for custom portlet mode."); } // render IFRAME content doIFrame(request, source, response); @@ -204,30 +278,33 @@ * Generate IFRAME with edit source. */ public void doEdit(RenderRequest request, RenderResponse response) - throws PortletException, IOException + throws PortletException, IOException { // get IFRAME source String source = null; if (request.getWindowState().equals(WindowState.MAXIMIZED)) { - source = getPreferenceOrDefault(request, MAXIMIZED_EDIT_SOURCE_PARAM, defaultMaximizedEditSource); + source = getPreferenceOrDefault(request, + MAXIMIZED_EDIT_SOURCE_PARAM, defaultMaximizedEditSource); } if (source == null) { - source = getPreferenceOrDefault(request, EDIT_SOURCE_PARAM, defaultEditSource); + source = getPreferenceOrDefault(request, EDIT_SOURCE_PARAM, + defaultEditSource); } - if ((source == null) && request.getWindowState().equals(WindowState.MAXIMIZED)) + if ((source == null) + && request.getWindowState().equals(WindowState.MAXIMIZED)) { - source = getPreferenceOrDefault(request, MAXIMIZED_VIEW_SOURCE_PARAM, defaultMaximizedViewSource); + source = getPreferenceOrDefault(request, + MAXIMIZED_VIEW_SOURCE_PARAM, defaultMaximizedViewSource); } if (source == null) { - source = getPreferenceOrDefault(request, VIEW_SOURCE_PARAM, defaultViewSource); + source = getPreferenceOrDefault(request, VIEW_SOURCE_PARAM, + defaultViewSource); } - if (source == null) - { - throw new PortletException("IFRAME source not specified for edit portlet mode."); - } + if (source == null) { throw new PortletException( + "IFRAME source not specified for edit portlet mode."); } // render IFRAME content doIFrame(request, source, response); @@ -237,30 +314,33 @@ * Generate IFRAME with help source. */ public void doHelp(RenderRequest request, RenderResponse response) - throws PortletException, IOException + throws PortletException, IOException { // get IFRAME source String source = null; if (request.getWindowState().equals(WindowState.MAXIMIZED)) { - source = getPreferenceOrDefault(request, MAXIMIZED_HELP_SOURCE_PARAM, defaultMaximizedHelpSource); + source = getPreferenceOrDefault(request, + MAXIMIZED_HELP_SOURCE_PARAM, defaultMaximizedHelpSource); } if (source == null) { - source = getPreferenceOrDefault(request, HELP_SOURCE_PARAM, defaultHelpSource); + source = getPreferenceOrDefault(request, HELP_SOURCE_PARAM, + defaultHelpSource); } - if ((source == null) && request.getWindowState().equals(WindowState.MAXIMIZED)) + if ((source == null) + && request.getWindowState().equals(WindowState.MAXIMIZED)) { - source = getPreferenceOrDefault(request, MAXIMIZED_VIEW_SOURCE_PARAM, defaultMaximizedViewSource); + source = getPreferenceOrDefault(request, + MAXIMIZED_VIEW_SOURCE_PARAM, defaultMaximizedViewSource); } if (source == null) { - source = getPreferenceOrDefault(request, VIEW_SOURCE_PARAM, defaultViewSource); + source = getPreferenceOrDefault(request, VIEW_SOURCE_PARAM, + defaultViewSource); } - if (source == null) - { - throw new PortletException("IFRAME source not specified for help portlet mode."); - } + if (source == null) { throw new PortletException( + "IFRAME source not specified for help portlet mode."); } // render IFRAME content doIFrame(request, source, response); @@ -270,22 +350,22 @@ * Generate IFRAME with view source. */ public void doView(RenderRequest request, RenderResponse response) - throws PortletException, IOException + throws PortletException, IOException { // get IFRAME source String source = null; if (request.getWindowState().equals(WindowState.MAXIMIZED)) { - source = getPreferenceOrDefault(request, MAXIMIZED_VIEW_SOURCE_PARAM, defaultMaximizedViewSource); + source = getPreferenceOrDefault(request, + MAXIMIZED_VIEW_SOURCE_PARAM, defaultMaximizedViewSource); } if (source == null) { - source = getPreferenceOrDefault(request, VIEW_SOURCE_PARAM, defaultViewSource); + source = getPreferenceOrDefault(request, VIEW_SOURCE_PARAM, + defaultViewSource); } - if (source == null) - { - throw new PortletException("IFRAME source not specified for view portlet mode."); - } + if (source == null) { throw new PortletException( + "IFRAME source not specified for view portlet mode."); } // render IFRAME content doIFrame(request, source, response); @@ -294,116 +374,146 @@ /** * Render IFRAME content */ - protected void doIFrame(RenderRequest request, String sourceAttr, RenderResponse response) - throws IOException + protected void doIFrame(RenderRequest request, String sourceAttr, + RenderResponse response) throws IOException { // generate HTML IFRAME content StringBuffer content = new StringBuffer(4096); // fix JS2-349 - content.append("<TABLE CLASS='iframePortletTableContainer' WIDTH='100%'><TBODY CLASS='iframePortletTbodyContainer'><TR><TD>"); - + content + .append("<TABLE CLASS='iframePortletTableContainer' WIDTH='100%'><TBODY CLASS='iframePortletTbodyContainer'><TR><TD>"); + content.append("<IFRAME"); content.append(" SRC=\"").append(sourceAttr).append("\""); - String alignAttr = getPreferenceOrDefault(request, ALIGN_ATTR_PARAM, defaultAlignAttr); + String alignAttr = getPreferenceOrDefault(request, ALIGN_ATTR_PARAM, + defaultAlignAttr); if (alignAttr != null) { content.append(" ALIGN=\"").append(alignAttr).append("\""); } - String classAttr = getPreferenceOrDefault(request, CLASS_ATTR_PARAM, defaultClassAttr); + String classAttr = getPreferenceOrDefault(request, CLASS_ATTR_PARAM, + defaultClassAttr); if (classAttr != null) { content.append(" CLASS=\"").append(classAttr).append("\""); } - String frameBorderAttr = getPreferenceOrDefault(request, FRAME_BORDER_ATTR_PARAM, defaultFrameBorderAttr); + String frameBorderAttr = getPreferenceOrDefault(request, + FRAME_BORDER_ATTR_PARAM, defaultFrameBorderAttr); if (frameBorderAttr != null) { - content.append(" FRAMEBORDER=\"").append(frameBorderAttr).append("\""); + content.append(" FRAMEBORDER=\"").append(frameBorderAttr).append( + "\""); } - String idAttr = getPreferenceOrDefault(request, ID_ATTR_PARAM, defaultIdAttr); + String idAttr = getPreferenceOrDefault(request, ID_ATTR_PARAM, + defaultIdAttr); if (idAttr != null) { content.append(" ID=\"").append(idAttr).append("\""); } - String marginHeightAttr = getPreferenceOrDefault(request, MARGIN_HEIGHT_ATTR_PARAM, defaultMarginHeightAttr); + String marginHeightAttr = getPreferenceOrDefault(request, + MARGIN_HEIGHT_ATTR_PARAM, defaultMarginHeightAttr); if (marginHeightAttr != null) { - content.append(" MARGINHEIGHT=\"").append(marginHeightAttr).append("\""); + content.append(" MARGINHEIGHT=\"").append(marginHeightAttr).append( + "\""); } - String marginWidthAttr = getPreferenceOrDefault(request, MARGIN_WIDTH_ATTR_PARAM, defaultMarginWidthAttr); + String marginWidthAttr = getPreferenceOrDefault(request, + MARGIN_WIDTH_ATTR_PARAM, defaultMarginWidthAttr); if (marginWidthAttr != null) { - content.append(" MARGINWIDTH=\"").append(marginWidthAttr).append("\""); + content.append(" MARGINWIDTH=\"").append(marginWidthAttr).append( + "\""); } - String nameAttr = getPreferenceOrDefault(request, NAME_ATTR_PARAM, defaultNameAttr); + String nameAttr = getPreferenceOrDefault(request, NAME_ATTR_PARAM, + defaultNameAttr); if (nameAttr != null) { content.append(" NAME=\"").append(nameAttr).append("\""); } if (request.getWindowState().equals(WindowState.MAXIMIZED)) { - String maximizedHeightAttr = getPreferenceOrDefault(request, MAXIMIZED_HEIGHT_ATTR_PARAM, defaultMaximizedHeightAttr); + String maximizedHeightAttr = getPreferenceOrDefault(request, + MAXIMIZED_HEIGHT_ATTR_PARAM, defaultMaximizedHeightAttr); if (maximizedHeightAttr == null) { - maximizedHeightAttr = getPreferenceOrDefault(request, HEIGHT_ATTR_PARAM, defaultHeightAttr); + maximizedHeightAttr = getPreferenceOrDefault(request, + HEIGHT_ATTR_PARAM, defaultHeightAttr); } if (maximizedHeightAttr != null) { - content.append(" HEIGHT=\"").append(maximizedHeightAttr).append("\""); + content.append(" HEIGHT=\"").append(maximizedHeightAttr) + .append("\""); } - String maximizedScrollingAttr = getPreferenceOrDefault(request, MAXIMIZED_SCROLLING_ATTR_PARAM, defaultMaximizedScrollingAttr); + String maximizedScrollingAttr = getPreferenceOrDefault(request, + MAXIMIZED_SCROLLING_ATTR_PARAM, + defaultMaximizedScrollingAttr); if (maximizedScrollingAttr == null) { - maximizedScrollingAttr = getPreferenceOrDefault(request, SCROLLING_ATTR_PARAM, defaultScrollingAttr); + maximizedScrollingAttr = getPreferenceOrDefault(request, + SCROLLING_ATTR_PARAM, defaultScrollingAttr); } if (maximizedScrollingAttr != null) { - content.append(" SCROLLING=\"").append(maximizedScrollingAttr).append("\""); + content.append(" SCROLLING=\"").append(maximizedScrollingAttr) + .append("\""); } - String maximizedStyleAttr = getPreferenceOrDefault(request, MAXIMIZED_STYLE_ATTR_PARAM, defaultMaximizedStyleAttr); + String maximizedStyleAttr = getPreferenceOrDefault(request, + MAXIMIZED_STYLE_ATTR_PARAM, defaultMaximizedStyleAttr); if (maximizedStyleAttr == null) { - maximizedStyleAttr = getPreferenceOrDefault(request, STYLE_ATTR_PARAM, defaultStyleAttr); + maximizedStyleAttr = getPreferenceOrDefault(request, + STYLE_ATTR_PARAM, defaultStyleAttr); } if (maximizedStyleAttr != null) { - content.append(" STYLE=\"").append(maximizedStyleAttr).append("\""); + content.append(" STYLE=\"").append(maximizedStyleAttr).append( + "\""); } - String maximizedWidthAttr = getPreferenceOrDefault(request, MAXIMIZED_WIDTH_ATTR_PARAM, defaultMaximizedWidthAttr); + String maximizedWidthAttr = getPreferenceOrDefault(request, + MAXIMIZED_WIDTH_ATTR_PARAM, defaultMaximizedWidthAttr); if (maximizedWidthAttr == null) { - maximizedWidthAttr = getPreferenceOrDefault(request, WIDTH_ATTR_PARAM, defaultWidthAttr); + maximizedWidthAttr = getPreferenceOrDefault(request, + WIDTH_ATTR_PARAM, defaultWidthAttr); } if (maximizedWidthAttr != null) { - content.append(" WIDTH=\"").append(maximizedWidthAttr).append("\""); + content.append(" WIDTH=\"").append(maximizedWidthAttr).append( + "\""); } } else { - String heightAttr = getPreferenceOrDefault(request, HEIGHT_ATTR_PARAM, defaultHeightAttr); + String heightAttr = getPreferenceOrDefault(request, + HEIGHT_ATTR_PARAM, defaultHeightAttr); if (heightAttr != null) { content.append(" HEIGHT=\"").append(heightAttr).append("\""); } - String scrollingAttr = getPreferenceOrDefault(request, SCROLLING_ATTR_PARAM, defaultScrollingAttr); + String scrollingAttr = getPreferenceOrDefault(request, + SCROLLING_ATTR_PARAM, defaultScrollingAttr); if (scrollingAttr != null) { - content.append(" SCROLLING=\"").append(scrollingAttr).append("\""); + content.append(" SCROLLING=\"").append(scrollingAttr).append( + "\""); } - String styleAttr = getPreferenceOrDefault(request, STYLE_ATTR_PARAM, defaultStyleAttr); + String styleAttr = getPreferenceOrDefault(request, + STYLE_ATTR_PARAM, defaultStyleAttr); if (styleAttr != null) { content.append(" STYLE=\"").append(styleAttr).append("\""); } - String widthAttr = getPreferenceOrDefault(request, WIDTH_ATTR_PARAM, defaultWidthAttr); + String widthAttr = getPreferenceOrDefault(request, + WIDTH_ATTR_PARAM, defaultWidthAttr); if (widthAttr != null) { content.append(" WIDTH=\"").append(widthAttr).append("\""); } } content.append(">"); - content.append("<P STYLE=\"textAlign:center\"><A HREF=\"").append(sourceAttr).append("\">").append(sourceAttr).append("</A></P>"); + content.append("<P STYLE=\"textAlign:center\"><A HREF=\"").append( + sourceAttr).append("\">").append(sourceAttr).append("</A></P>"); content.append("</IFRAME>"); // end fix JS2-349 @@ -417,26 +527,27 @@ /** * Get IFRAME attribute parameter. */ - private String getAttributeParam(PortletConfig config, String name, String defaultValue) + private String getAttributeParam(PortletConfig config, String name, + String defaultValue) { String value = config.getInitParameter(name); if (value == null) { value = defaultValue; } - return (((value != null) && (value.length() > 0) && ! value.equalsIgnoreCase("none")) ? value : null); + return (((value != null) && (value.length() > 0) && !value + .equalsIgnoreCase("none")) ? value : null); } /** * Get IFRAME preference value if enabled. */ - private String getPreferenceOrDefault(RenderRequest request, String name, String defaultValue) + private String getPreferenceOrDefault(RenderRequest request, String name, + String defaultValue) { - if (! enablePreferences) - { - return defaultValue; - } + if (!enablePreferences) { return defaultValue; } PortletPreferences prefs = request.getPreferences(); - return ((prefs != null) ? prefs.getValue(name, defaultValue) : defaultValue); + return ((prefs != null) ? prefs.getValue(name, defaultValue) + : defaultValue); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/SSOIFramePortlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/SSOIFramePortlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/SSOIFramePortlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -44,48 +44,58 @@ */ public class SSOIFramePortlet extends IFrameGenericPortlet { + public static final String SSO_TYPE = "sso.type"; + public static final String SSO_TYPE_URL = "url"; + public static final String SSO_TYPE_URL_BASE64 = "url.base64"; + public static final String SSO_TYPE_HTTP = "http"; + public static final String SSO_TYPE_CERTIFICATE = "certificate"; - + public static final String SSO_TYPE_URL_USERNAME = "sso.url.Principal"; + public static final String SSO_TYPE_URL_PASSWORD = "sso.url.Credential"; - + public static final String SSO_REQUEST_ATTRIBUTE_USERNAME = "sso.ra.username"; + public static final String SSO_REQUEST_ATTRIBUTE_PASSWORD = "sso.ra.password"; /* - * The constants must be used in your HTML form for the SSO principal and credential + * The constants must be used in your HTML form for the SSO principal and + * credential */ public static final String SSO_FORM_PRINCIPAL = "ssoPrincipal"; + public static final String SSO_FORM_CREDENTIAL = "ssoCredential"; - + private PortletContext context; + private SSOProvider sso; public void init(PortletConfig config) throws PortletException { super.init(config); context = getPortletContext(); - sso = (SSOProvider)context.getAttribute("cps:SSO"); - if (null == sso) - { - throw new PortletException("Failed to find SSO Provider on portlet initialization"); - } + sso = (SSOProvider) context.getAttribute("cps:SSO"); + if (null == sso) { throw new PortletException( + "Failed to find SSO Provider on portlet initialization"); } } public void doEdit(RenderRequest request, RenderResponse response) - throws PortletException, IOException + throws PortletException, IOException { try { - Subject subject = getSubject(); + Subject subject = getSubject(); String site = request.getPreferences().getValue("SRC", ""); SSOContext context = sso.getCredentials(subject, site); - getContext(request).put(SSO_FORM_PRINCIPAL, context.getRemotePrincipalName()); - getContext(request).put(SSO_FORM_CREDENTIAL, context.getRemoteCredential()); + getContext(request).put(SSO_FORM_PRINCIPAL, + context.getRemotePrincipalName()); + getContext(request).put(SSO_FORM_CREDENTIAL, + context.getRemoteCredential()); } catch (SSOException e) { @@ -100,31 +110,34 @@ { throw new PortletException(e); } - } - + } + super.doEdit(request, response); } - + public void doView(RenderRequest request, RenderResponse response) - throws PortletException, IOException + throws PortletException, IOException { String site = request.getPreferences().getValue("SRC", null); if (site == null) { // no credentials configured in SSO store // switch to SSO Configure View - request.setAttribute(PARAM_VIEW_PAGE, this.getPortletConfig().getInitParameter(PARAM_EDIT_PAGE)); + request.setAttribute(PARAM_VIEW_PAGE, this.getPortletConfig() + .getInitParameter(PARAM_EDIT_PAGE)); setupPreferencesEdit(request, response); super.doView(request, response); return; } - + try { - Subject subject = getSubject(); + Subject subject = getSubject(); SSOContext context = sso.getCredentials(subject, site); - request.setAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME, context.getRemotePrincipalName()); - request.setAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD, context.getRemoteCredential()); + request.setAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME, context + .getRemotePrincipalName()); + request.setAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD, context + .getRemoteCredential()); } catch (SSOException e) { @@ -132,102 +145,109 @@ { // no credentials configured in SSO store // switch to SSO Configure View - request.setAttribute(PARAM_VIEW_PAGE, this.getPortletConfig().getInitParameter(PARAM_EDIT_PAGE)); - setupPreferencesEdit(request, response); + request.setAttribute(PARAM_VIEW_PAGE, this.getPortletConfig() + .getInitParameter(PARAM_EDIT_PAGE)); + setupPreferencesEdit(request, response); } else { throw new PortletException(e); } - } - + } + super.doView(request, response); } - - public void processAction(ActionRequest request, ActionResponse actionResponse) - throws PortletException, IOException + + public void processAction(ActionRequest request, + ActionResponse actionResponse) throws PortletException, IOException { // save the prefs super.processAction(request, actionResponse); - + // get the POST params -- requires HTML post params named - // ssoUserName + // ssoUserName String ssoPrincipal = request.getParameter(SSO_FORM_PRINCIPAL); - String ssoCredential = request.getParameter(SSO_FORM_CREDENTIAL); + String ssoCredential = request.getParameter(SSO_FORM_CREDENTIAL); /* - if (ssoPrincipal == null || ssoCredential == null) - { - - actionResponse.setPortletMode(PortletMode.EDIT); // stay on edit - } - */ + * if (ssoPrincipal == null || ssoCredential == null) { + * + * actionResponse.setPortletMode(PortletMode.EDIT); // stay on edit } + */ String site = request.getPreferences().getValue("SRC", ""); try { Subject subject = getSubject(); if (sso.hasSSOCredentials(subject, site)) { - SSOContext context = sso.getCredentials(subject, site); - if (!context.getRemotePrincipalName().equals(ssoPrincipal)) - { - sso.removeCredentialsForSite(subject, site); - sso.addCredentialsForSite(subject, ssoPrincipal, site, ssoCredential); - } - else - { - sso.updateCredentialsForSite(subject, ssoPrincipal, site, ssoCredential); - } + SSOContext context = sso.getCredentials(subject, site); + if (!context.getRemotePrincipalName().equals(ssoPrincipal)) + { + sso.removeCredentialsForSite(subject, site); + sso.addCredentialsForSite(subject, ssoPrincipal, site, + ssoCredential); + } + else + { + sso.updateCredentialsForSite(subject, ssoPrincipal, site, + ssoCredential); + } } else { - sso.addCredentialsForSite(subject, ssoPrincipal, site, ssoCredential); + sso.addCredentialsForSite(subject, ssoPrincipal, site, + ssoCredential); } } catch (SSOException e) { throw new PortletException(e); } - + } - - public String getURLSource(RenderRequest request, RenderResponse response, PortletPreferences prefs) + + public String getURLSource(RenderRequest request, RenderResponse response, + PortletPreferences prefs) { String baseSource = super.getURLSource(request, response, prefs); String type = prefs.getValue(SSO_TYPE, SSO_TYPE_URL); if (type.equals(SSO_TYPE_URL) || type.equals(SSO_TYPE_URL_BASE64)) { - String userNameParam = prefs.getValue(SSO_TYPE_URL_USERNAME, "user"); - String passwordParam = prefs.getValue(SSO_TYPE_URL_PASSWORD, "password"); + String userNameParam = prefs + .getValue(SSO_TYPE_URL_USERNAME, "user"); + String passwordParam = prefs.getValue(SSO_TYPE_URL_PASSWORD, + "password"); StringBuffer source = new StringBuffer(baseSource); if (baseSource.indexOf("?") == -1) { source.append("?"); - } + } else { source.append("&"); } source.append(userNameParam); source.append("="); - - String userName = (String)request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); + + String userName = (String) request + .getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; - String password = (String)request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); + String password = (String) request + .getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; if (type.equals(SSO_TYPE_URL_BASE64)) { - Base64 encoder = new Base64() ; + Base64 encoder = new Base64(); userName = new String(encoder.encode(userName.getBytes())); password = new String(encoder.encode(password.getBytes())); - } - + } + source.append(userName); source.append("&"); source.append(passwordParam); source.append("="); source.append(password); - + return response.encodeURL(source.toString()); } else @@ -235,11 +255,11 @@ return baseSource; } } - + private Subject getSubject() { AccessControlContext context = AccessController.getContext(); - return JSSubject.getSubject(context); + return JSSubject.getSubject(context); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/SSOTicketPortlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/SSOTicketPortlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/SSOTicketPortlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,96 +18,116 @@ import org.apache.jetspeed.rewriter.TicketParamRewriter; import org.apache.jetspeed.rewriter.html.SwingParserAdaptor; -public class SSOTicketPortlet extends SSOWebContentPortlet +public class SSOTicketPortlet extends SSOWebContentPortlet { + public final static String SSO_PREF_TICKET_NAME = "ticket.name"; + // sso.type - protected Class adaptorHtmlClass = SwingParserAdaptor.class; - - //form Constants + protected Class adaptorHtmlClass = SwingParserAdaptor.class; + + // form Constants public static final String FORM_POST_METHOD = "post"; + public static final String FORM_GET_METHOD = "get"; + public static final String FORM_MULTIPART_METHOD = "multipart"; - - protected HttpMethodBase getHttpMethod(HttpClient client, String uri, Map params, String formMethod, RenderRequest request) throws IOException + + protected HttpMethodBase getHttpMethod(HttpClient client, String uri, + Map params, String formMethod, RenderRequest request) + throws IOException { - String postURI = (String)request.getPreferences().getValue(SSO_TYPE_FORM_ACTION_URL, ""); - String ticketName = (String)request.getPreferences().getValue(SSO_PREF_TICKET_NAME, ""); - if(uri.startsWith(postURI)) + String postURI = (String) request.getPreferences().getValue( + SSO_TYPE_FORM_ACTION_URL, ""); + String ticketName = (String) request.getPreferences().getValue( + SSO_PREF_TICKET_NAME, ""); + if (uri.startsWith(postURI)) { - if(!params.containsKey(ticketName)) + if (!params.containsKey(ticketName)) { - params.put(ticketName, new String[] - { requestTicket(uri, request, null) }); + params.put(ticketName, new String[] + {requestTicket(uri, request, null)}); } - } + } return super.getHttpMethod(client, uri, params, formMethod, request); } - private String requestTicket(String url, RenderRequest request, RenderResponse response) + private String requestTicket(String url, RenderRequest request, + RenderResponse response) { // ...set up URL and HttpClient stuff - String ticket = ""; - HttpClient client = new HttpClient(); + String ticket = ""; + HttpClient client = new HttpClient(); HttpMethodBase httpMethod = null; httpMethod = new PostMethod(); - //String useragentProperty = request.getProperty("User-Agent"); - httpMethod.addRequestHeader( "User-Agent", "Firefox" ); + // String useragentProperty = request.getProperty("User-Agent"); + httpMethod.addRequestHeader("User-Agent", "Firefox"); httpMethod.setPath(url); try { client.executeMethod(httpMethod); - int responseCode = httpMethod.getStatusCode(); + int responseCode = httpMethod.getStatusCode(); if (responseCode >= 300 && responseCode <= 399) { - // redirection that could not be handled automatically!!! (probably from a POST) - Header locationHeader = httpMethod.getResponseHeader("location"); - String redirectLocation = locationHeader != null ? locationHeader.getValue() : null ; + // redirection that could not be handled automatically!!! + // (probably from a POST) + Header locationHeader = httpMethod + .getResponseHeader("location"); + String redirectLocation = locationHeader != null ? locationHeader + .getValue() + : null; if (redirectLocation != null) { - // System.out.println("WebContentPortlet.doHttpWebContent() >>>handling redirect to: "+redirectLocation+"<<<"); - // one more time (assume most params are already encoded & new URL is using GET protocol!) - return requestTicket( redirectLocation,null,null) ; + // System.out.println("WebContentPortlet.doHttpWebContent() + // >>>handling redirect to: "+redirectLocation+"<<<"); + // one more time (assume most params are already encoded & + // new URL is using GET protocol!) + return requestTicket(redirectLocation, null, null); } else { - // The response is a redirect, but did not provide the new location for the resource. - throw new PortletException("Redirection code: "+responseCode+", but with no redirectionLocation set."); + // The response is a redirect, but did not provide the new + // location for the resource. + throw new PortletException("Redirection code: " + + responseCode + + ", but with no redirectionLocation set."); } } else if (responseCode == 200) - { - // String body = httpMethod.getResponseBodyAsString(); - // Header [] head = httpMethod.getResponseHeaders(); - TicketParamRewriter ticketWriter = new TicketParamRewriter(); - String ticketName = (String)request.getPreferences().getValue(SSO_PREF_TICKET_NAME, null); + { + // String body = httpMethod.getResponseBodyAsString(); + // Header [] head = httpMethod.getResponseHeaders(); + TicketParamRewriter ticketWriter = new TicketParamRewriter(); + String ticketName = (String) request.getPreferences().getValue( + SSO_PREF_TICKET_NAME, null); if (ticketName != null) { ticketWriter.setTicketName(ticketName); - Reader reader = new InputStreamReader(httpMethod.getResponseBodyAsStream()); + Reader reader = new InputStreamReader(httpMethod + .getResponseBodyAsStream()); createParserAdaptor().parse(ticketWriter, reader); ticket = ticketWriter.getTicket(); } } } - catch (Exception e) + catch (Exception e) { - e.printStackTrace(); - } - return ticket; + e.printStackTrace(); + } + return ticket; } public ParserAdaptor createParserAdaptor() throws RewriterException { try { - return (ParserAdaptor) adaptorHtmlClass.newInstance(); - + return (ParserAdaptor) adaptorHtmlClass.newInstance(); + } catch (Exception e) { log.error("Error creating rewriter class", e); } return null; - } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/SSOWebContentPortlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/SSOWebContentPortlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/SSOWebContentPortlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -51,7 +51,6 @@ import org.apache.jetspeed.sso.SSOProvider; import org.apache.portals.messaging.PortletMessaging; - /** * SSOWebContentPortlet * @@ -60,101 +59,126 @@ */ public class SSOWebContentPortlet extends WebContentPortlet { + // Constants - + // sso.type public static final String SSO_TYPE = "sso.type"; - - public static final String SSO_TYPE_HTTP = "http"; // BOZO - depricate in favor of 'basic' - public static final String SSO_TYPE_BASIC = "basic"; + + public static final String SSO_TYPE_HTTP = "http"; // BOZO - depricate in + + // favor of 'basic' + + public static final String SSO_TYPE_BASIC = "basic"; + public static final String SSO_TYPE_BASIC_PREEMPTIVE = "basic.preemptive"; - + public static final String SSO_TYPE_FORM = "form"; + public static final String SSO_TYPE_FORM_GET = "form.get"; + public static final String SSO_TYPE_FORM_POST = "form.post"; - + public static final String SSO_TYPE_URL = "url"; + public static final String SSO_TYPE_URL_BASE64 = "url.base64"; - + public static final String SSO_TYPE_CERTIFICATE = "certificate"; - - public static final String SSO_TYPE_DEFAULT = SSO_TYPE_BASIC; // handled well even if nothing but credentials are set (see: doRequestedAuthentication) - + + public static final String SSO_TYPE_DEFAULT = SSO_TYPE_BASIC; // handled + + // well even + // if + // nothing + // but + // credentials + // are set + // (see: + // doRequestedAuthentication) + // ...standardized auth types - - public static final String BASIC_AUTH_SCHEME_NAME = (new BasicScheme()).getSchemeName(); + public static final String BASIC_AUTH_SCHEME_NAME = (new BasicScheme()) + .getSchemeName(); + // supporting parameters - for various sso types - + // ...names of query args for sso.type=url|url.base64 - + public static final String SSO_TYPE_URL_USERNAME_PARAM = "sso.url.Principal"; + public static final String SSO_TYPE_URL_PASSWORD_PARAM = "sso.url.Credential"; - + // ...names of fields for sso.type=form|form.get|form.post - + public static final String SSO_TYPE_FORM_ACTION_URL = "sso.form.Action"; + public static final String SSO_TYPE_FORM_ACTION_ARGS = "sso.form.Args"; + public static final String SSO_TYPE_FORM_USERNAME_FIELD = "sso.form.Principal"; + public static final String SSO_TYPE_FORM_PASSWORD_FIELD = "sso.form.Credential"; - + // ...tags for passing creditials along on the current request object - + public static final String SSO_REQUEST_ATTRIBUTE_USERNAME = "sso.ra.username"; + public static final String SSO_REQUEST_ATTRIBUTE_PASSWORD = "sso.ra.password"; - + // ...field names for EDIT mode - + public static final String SSO_EDIT_FIELD_PRINCIPAL = "ssoPrincipal"; + public static final String SSO_EDIT_FIELD_CREDENTIAL = "ssoCredential"; - - // SSOWebContent session variables - public static final String FORM_AUTH_STATE = "ssowebcontent.form.authstate" ; - - + // SSOWebContent session variables + + public static final String FORM_AUTH_STATE = "ssowebcontent.form.authstate"; + // Class Data - - protected final static Log log = LogFactory.getLog(SSOWebContentPortlet.class); - - + + protected final static Log log = LogFactory + .getLog(SSOWebContentPortlet.class); + // Data Members - + protected PortletContext context; + protected SSOProvider sso; - - + // Methods public void init(PortletConfig config) throws PortletException { super.init(config); context = getPortletContext(); - sso = (SSOProvider)context.getAttribute("cps:SSO"); - if (null == sso) - { - throw new PortletException("Failed to find SSO Provider on portlet initialization"); - } + sso = (SSOProvider) context.getAttribute("cps:SSO"); + if (null == sso) { throw new PortletException( + "Failed to find SSO Provider on portlet initialization"); } } - - public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) - throws PortletException, IOException + + public void processAction(ActionRequest actionRequest, + ActionResponse actionResponse) throws PortletException, IOException { // grab parameters - they will be cleared in processing of edit response - String webContentParameter = actionRequest.getParameter(WebContentRewriter.ACTION_PARAMETER_URL); - String ssoPrincipal = actionRequest.getParameter(SSO_EDIT_FIELD_PRINCIPAL); - String ssoCredential = actionRequest.getParameter(SSO_EDIT_FIELD_CREDENTIAL); + String webContentParameter = actionRequest + .getParameter(WebContentRewriter.ACTION_PARAMETER_URL); + String ssoPrincipal = actionRequest + .getParameter(SSO_EDIT_FIELD_PRINCIPAL); + String ssoCredential = actionRequest + .getParameter(SSO_EDIT_FIELD_CREDENTIAL); // save the prefs super.processAction(actionRequest, actionResponse); - + // process credentials - if (webContentParameter == null || actionRequest.getPortletMode() == PortletMode.EDIT) + if (webContentParameter == null + || actionRequest.getPortletMode() == PortletMode.EDIT) { // processPreferencesAction(request, actionResponse); - // get the POST params -- requires HTML post params named above + // get the POST params -- requires HTML post params named above String site = actionRequest.getPreferences().getValue("SRC", ""); - + try { Subject subject = getSubject(); @@ -164,16 +188,19 @@ if (!context.getRemotePrincipalName().equals(ssoPrincipal)) { sso.removeCredentialsForSite(subject, site); - sso.addCredentialsForSite(subject, ssoPrincipal, site, ssoCredential); + sso.addCredentialsForSite(subject, ssoPrincipal, site, + ssoCredential); } else { - sso.updateCredentialsForSite(subject, ssoPrincipal, site, ssoCredential); + sso.updateCredentialsForSite(subject, ssoPrincipal, + site, ssoCredential); } } else { - sso.addCredentialsForSite(subject, ssoPrincipal, site, ssoCredential); + sso.addCredentialsForSite(subject, ssoPrincipal, site, + ssoCredential); } } catch (SSOException e) @@ -182,54 +209,61 @@ } } } - + public void doView(RenderRequest request, RenderResponse response) - throws PortletException, IOException + throws PortletException, IOException { String site = request.getPreferences().getValue("SRC", null); if (site == null) { // no SRC configured in prefs - switch to SSO Configure View - request.setAttribute(PARAM_VIEW_PAGE, this.getPortletConfig().getInitParameter(PARAM_EDIT_PAGE)); + request.setAttribute(PARAM_VIEW_PAGE, this.getPortletConfig() + .getInitParameter(PARAM_EDIT_PAGE)); setupPreferencesEdit(request, response); } - else try - { - Subject subject = getSubject(); - SSOContext context = sso.getCredentials(subject, site); - request.setAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME, context.getRemotePrincipalName()); - request.setAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD, context.getRemoteCredential()); - } - catch (SSOException e) - { - if (e.getMessage().equals(SSOException.NO_CREDENTIALS_FOR_SITE)) + else + try { - // no credentials configured in SSO store - // switch to SSO Configure View - request.setAttribute(PARAM_VIEW_PAGE, this.getPortletConfig().getInitParameter(PARAM_EDIT_PAGE)); - setupPreferencesEdit(request, response); + Subject subject = getSubject(); + SSOContext context = sso.getCredentials(subject, site); + request.setAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME, context + .getRemotePrincipalName()); + request.setAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD, context + .getRemoteCredential()); } - else + catch (SSOException e) { - throw new PortletException(e); + if (e.getMessage().equals(SSOException.NO_CREDENTIALS_FOR_SITE)) + { + // no credentials configured in SSO store + // switch to SSO Configure View + request.setAttribute(PARAM_VIEW_PAGE, this + .getPortletConfig().getInitParameter( + PARAM_EDIT_PAGE)); + setupPreferencesEdit(request, response); + } + else + { + throw new PortletException(e); + } } - } - + super.doView(request, response); } - public void doEdit(RenderRequest request, RenderResponse response) - throws PortletException, IOException + throws PortletException, IOException { try { - Subject subject = getSubject(); + Subject subject = getSubject(); String site = request.getPreferences().getValue("SRC", ""); SSOContext context = sso.getCredentials(subject, site); - getContext(request).put(SSO_EDIT_FIELD_PRINCIPAL, context.getRemotePrincipalName()); - getContext(request).put(SSO_EDIT_FIELD_CREDENTIAL, context.getRemoteCredential()); + getContext(request).put(SSO_EDIT_FIELD_PRINCIPAL, + context.getRemotePrincipalName()); + getContext(request).put(SSO_EDIT_FIELD_CREDENTIAL, + context.getRemoteCredential()); } catch (SSOException e) { @@ -244,53 +278,60 @@ { throw new PortletException(e); } - } - + } + super.doEdit(request, response); } private Subject getSubject() { AccessControlContext context = AccessController.getContext(); - return JSSubject.getSubject(context); + return JSSubject.getSubject(context); } - - protected byte[] doPreemptiveAuthentication(HttpClient client,HttpMethod method, RenderRequest request, RenderResponse response) + + protected byte[] doPreemptiveAuthentication(HttpClient client, + HttpMethod method, RenderRequest request, RenderResponse response) { - byte[] result = super.doPreemptiveAuthentication(client, method, request, response); - if ( result != null) + byte[] result = super.doPreemptiveAuthentication(client, method, + request, response); + if (result != null) { // already handled - return result ; + return result; } - + // System.out.println("SSOWebContentPortlet.doPreemptiveAuthentication..."); - + PortletPreferences prefs = request.getPreferences(); String type = getSingleSignOnAuthType(prefs); if (type.equalsIgnoreCase(SSO_TYPE_BASIC_PREEMPTIVE)) { // Preemptive, basic authentication - String userName = (String)request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); + String userName = (String) request + .getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; - String password = (String)request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); + String password = (String) request + .getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; - - // System.out.println("...performing preemptive basic authentication with userName: "+userName+", and password: "+password); + + // System.out.println("...performing preemptive basic authentication + // with userName: "+userName+", and password: "+password); method.setDoAuthentication(true); method.getHostAuthState().setPreemptive(); - client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); - + client.getState().setCredentials(AuthScope.ANY, + new UsernamePasswordCredentials(userName, password)); + // handled! - return result ; - + return result; + } else if (type.startsWith(SSO_TYPE_FORM)) { try { - Boolean formAuth = (Boolean)PortletMessaging.receive(request, FORM_AUTH_STATE); + Boolean formAuth = (Boolean) PortletMessaging.receive(request, + FORM_AUTH_STATE); if (formAuth != null) { // already been here, done that @@ -299,41 +340,61 @@ else { // stop recursion, but assume failure, ...for now - PortletMessaging.publish(request, FORM_AUTH_STATE, Boolean.FALSE); + PortletMessaging.publish(request, FORM_AUTH_STATE, + Boolean.FALSE); } - String formAction = prefs.getValue(SSO_TYPE_FORM_ACTION_URL, ""); + String formAction = prefs + .getValue(SSO_TYPE_FORM_ACTION_URL, ""); if (formAction == null || formAction.length() == 0) { - log.warn("sso.type specified as 'form', but no: "+SSO_TYPE_FORM_ACTION_URL+", action was specified - unable to preemptively authenticate by form."); - return null ; + log + .warn("sso.type specified as 'form', but no: " + + SSO_TYPE_FORM_ACTION_URL + + ", action was specified - unable to preemptively authenticate by form."); + return null; } - String userNameField = prefs.getValue(SSO_TYPE_FORM_USERNAME_FIELD, ""); + String userNameField = prefs.getValue( + SSO_TYPE_FORM_USERNAME_FIELD, ""); if (userNameField == null || userNameField.length() == 0) { - log.warn("sso.type specified as 'form', but no: "+SSO_TYPE_FORM_USERNAME_FIELD+", username field was specified - unable to preemptively authenticate by form."); - return null ; + log + .warn("sso.type specified as 'form', but no: " + + SSO_TYPE_FORM_USERNAME_FIELD + + ", username field was specified - unable to preemptively authenticate by form."); + return null; } - String passwordField = prefs.getValue(SSO_TYPE_FORM_PASSWORD_FIELD, "password"); + String passwordField = prefs.getValue( + SSO_TYPE_FORM_PASSWORD_FIELD, "password"); if (passwordField == null || passwordField.length() == 0) { - log.warn("sso.type specified as 'form', but no: "+SSO_TYPE_FORM_PASSWORD_FIELD+", password field was specified - unable to preemptively authenticate by form."); - return null ; + log + .warn("sso.type specified as 'form', but no: " + + SSO_TYPE_FORM_PASSWORD_FIELD + + ", password field was specified - unable to preemptively authenticate by form."); + return null; } - - String userName = (String)request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); + + String userName = (String) request + .getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; - String password = (String)request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); + String password = (String) request + .getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; // get submit method int i = type.indexOf('.'); - boolean isPost = i > 0 ? type.substring(i+1).equalsIgnoreCase("post") : true ; // default to post, since it is a form - + boolean isPost = i > 0 ? type.substring(i + 1) + .equalsIgnoreCase("post") : true; // default to post, + // since it is a + // form + // get parameter map HashMap formParams = new HashMap(); - formParams.put(userNameField,new String[]{ userName }); - formParams.put(passwordField,new String[]{ password }); + formParams.put(userNameField, new String[] + {userName}); + formParams.put(passwordField, new String[] + {password}); String formArgs = prefs.getValue(SSO_TYPE_FORM_ACTION_ARGS, ""); if (formArgs != null && formArgs.length() > 0) { @@ -341,20 +402,27 @@ while (iter.hasMoreTokens()) { String pair = iter.nextToken(); - i = pair.indexOf('=') ; + i = pair.indexOf('='); if (i > 0) - formParams.put(pair.substring(0,i), new String[]{pair.substring(i+1)}); + formParams.put(pair.substring(0, i), new String[] + {pair.substring(i + 1)}); } } - // resuse client - in case new cookies get set - but create a new method (for the formAction) - String formMethod = (isPost) ? FORM_POST_METHOD : FORM_GET_METHOD; - method = getHttpMethod(client, getURLSource(formAction, formParams, request, response), formParams, formMethod, request); + // resuse client - in case new cookies get set - but create a + // new method (for the formAction) + String formMethod = (isPost) ? FORM_POST_METHOD + : FORM_GET_METHOD; + method = getHttpMethod(client, getURLSource(formAction, + formParams, request, response), formParams, formMethod, + request); // System.out.println("...posting credentials"); - result = doHttpWebContent(client, method, 0, request, response) ; - // System.out.println("Result of attempted authorization: "+success); - PortletMessaging.publish(request, FORM_AUTH_STATE, Boolean.valueOf(result != null)); - return result ; + result = doHttpWebContent(client, method, 0, request, response); + // System.out.println("Result of attempted authorization: + // "+success); + PortletMessaging.publish(request, FORM_AUTH_STATE, Boolean + .valueOf(result != null)); + return result; } catch (Exception ex) { @@ -362,108 +430,136 @@ log.error("Form-based authentication failed", ex); } } - else if (type.equalsIgnoreCase(SSO_TYPE_URL) || type.equalsIgnoreCase(SSO_TYPE_URL_BASE64)) + else if (type.equalsIgnoreCase(SSO_TYPE_URL) + || type.equalsIgnoreCase(SSO_TYPE_URL_BASE64)) { // set user name and password parameters in the HttpMethod - String userNameParam = prefs.getValue(SSO_TYPE_URL_USERNAME_PARAM, ""); + String userNameParam = prefs.getValue(SSO_TYPE_URL_USERNAME_PARAM, + ""); if (userNameParam == null || userNameParam.length() == 0) { - log.warn("sso.type specified as 'url', but no: "+SSO_TYPE_URL_USERNAME_PARAM+", username parameter was specified - unable to preemptively authenticate by URL."); - return null ; + log + .warn("sso.type specified as 'url', but no: " + + SSO_TYPE_URL_USERNAME_PARAM + + ", username parameter was specified - unable to preemptively authenticate by URL."); + return null; } - String passwordParam = prefs.getValue(SSO_TYPE_URL_PASSWORD_PARAM, ""); + String passwordParam = prefs.getValue(SSO_TYPE_URL_PASSWORD_PARAM, + ""); if (passwordParam == null || passwordParam.length() == 0) { - log.warn("sso.type specified as 'url', but no: "+SSO_TYPE_URL_PASSWORD_PARAM+", password parameter was specified - unable to preemptively authenticate by URL."); - return null ; + log + .warn("sso.type specified as 'url', but no: " + + SSO_TYPE_URL_PASSWORD_PARAM + + ", password parameter was specified - unable to preemptively authenticate by URL."); + return null; } - String userName = (String)request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); + String userName = (String) request + .getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; - String password = (String)request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); + String password = (String) request + .getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; if (type.equalsIgnoreCase(SSO_TYPE_URL_BASE64)) { - Base64 encoder = new Base64() ; + Base64 encoder = new Base64(); userName = new String(encoder.encode(userName.getBytes())); password = new String(encoder.encode(password.getBytes())); } - + // GET and POST accept args differently - if ( method instanceof PostMethod ) + if (method instanceof PostMethod) { // add POST data - PostMethod postMethod = (PostMethod)method ; + PostMethod postMethod = (PostMethod) method; postMethod.addParameter(userNameParam, userName); postMethod.addParameter(passwordParam, password); } else { // augment GET query string - NameValuePair[] authPairs = new NameValuePair[]{ new NameValuePair(userNameParam, userName), new NameValuePair(passwordParam, password) } ; - String existingQuery = method.getQueryString() ; + NameValuePair[] authPairs = new NameValuePair[] + {new NameValuePair(userNameParam, userName), + new NameValuePair(passwordParam, password)}; + String existingQuery = method.getQueryString(); method.setQueryString(authPairs); if (existingQuery != null && existingQuery.length() > 0) { // augment existing query with new auth query - existingQuery = existingQuery + '&' + method.getQueryString(); + existingQuery = existingQuery + '&' + + method.getQueryString(); method.setQueryString(existingQuery); } } - - return result ; + + return result; } - // else System.out.println("...sso.type: "+type+", no pre-emptive authentication"); - + // else System.out.println("...sso.type: "+type+", no pre-emptive + // authentication"); + // not handled - return null ; + return null; } - protected boolean doRequestedAuthentication(HttpClient client,HttpMethod method, RenderRequest request, RenderResponse response) + protected boolean doRequestedAuthentication(HttpClient client, + HttpMethod method, RenderRequest request, RenderResponse response) { - if ( super.doRequestedAuthentication(client, method, request, response)) + if (super.doRequestedAuthentication(client, method, request, response)) { // already handled - return true ; + return true; } - + // System.out.println("SSOWebContentPortlet.doRequestedAuthentication..."); - - if (method.getHostAuthState().getAuthScheme().getSchemeName().equals(BASIC_AUTH_SCHEME_NAME)) + + if (method.getHostAuthState().getAuthScheme().getSchemeName().equals( + BASIC_AUTH_SCHEME_NAME)) { // Basic authentication being requested - String userName = (String)request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); + String userName = (String) request + .getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME); if (userName == null) userName = ""; - String password = (String)request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); + String password = (String) request + .getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD); if (password == null) password = ""; - - // System.out.println("...providing basic authentication with userName: "+userName+", and password: "+password); + + // System.out.println("...providing basic authentication with + // userName: "+userName+", and password: "+password); method.setDoAuthentication(true); AuthState state = method.getHostAuthState(); - AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, state.getRealm(), state.getAuthScheme().getSchemeName()) ; - client.getState().setCredentials(scope, new UsernamePasswordCredentials(userName, password)); - + AuthScope scope = new AuthScope(AuthScope.ANY_HOST, + AuthScope.ANY_PORT, state.getRealm(), state.getAuthScheme() + .getSchemeName()); + client.getState().setCredentials(scope, + new UsernamePasswordCredentials(userName, password)); + // handled! - return true ; + return true; } else { - log.warn("SSOWebContentPortlent.doAuthenticate() - unexpected authentication scheme: "+method.getHostAuthState().getAuthScheme().getSchemeName()); + log + .warn("SSOWebContentPortlent.doAuthenticate() - unexpected authentication scheme: " + + method.getHostAuthState().getAuthScheme() + .getSchemeName()); } // only know how to handle Basic authentication, in this context return false; } - + protected String getSingleSignOnAuthType(PortletPreferences prefs) { - String type = prefs.getValue(SSO_TYPE,SSO_TYPE_DEFAULT); - + String type = prefs.getValue(SSO_TYPE, SSO_TYPE_DEFAULT); + if (type != null && type.equalsIgnoreCase(SSO_TYPE_HTTP)) { - log.warn("sso.type: "+SSO_TYPE_HTTP+", has been deprecated - use: "+SSO_TYPE_BASIC+", or: "+SSO_TYPE_BASIC_PREEMPTIVE); - type = SSO_TYPE_BASIC ; + log.warn("sso.type: " + SSO_TYPE_HTTP + + ", has been deprecated - use: " + SSO_TYPE_BASIC + + ", or: " + SSO_TYPE_BASIC_PREEMPTIVE); + type = SSO_TYPE_BASIC; } - - return type ; + + return type; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/WebContentPortlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/WebContentPortlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/WebContentPortlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -71,7 +71,6 @@ import org.apache.portals.bridges.velocity.GenericVelocityPortlet; import org.apache.portals.messaging.PortletMessaging; - /** * WebContentPortlet * @@ -93,37 +92,45 @@ * Configuration constants. */ public static final String VIEW_SOURCE_PARAM = "viewSource"; + public static final String EDIT_SOURCE_PARAM = "editSource"; - + // ...browser action buttons - public static final String BROWSER_ACTION_PARAM = "wcBrowserAction"; - public static final String BROWSER_ACTION_PREVIOUS_PAGE = "previousPage"; - public static final String BROWSER_ACTION_REFRESH_PAGE = "refreshPage"; - public static final String BROWSER_ACTION_NEXT_PAGE = "nextPage"; + public static final String BROWSER_ACTION_PARAM = "wcBrowserAction"; + public static final String BROWSER_ACTION_PREVIOUS_PAGE = "previousPage"; + + public static final String BROWSER_ACTION_REFRESH_PAGE = "refreshPage"; + + public static final String BROWSER_ACTION_NEXT_PAGE = "nextPage"; + /** * Action Parameter */ - // WebContent session data + // WebContent session data + public static final String HISTORY = "webcontent.history"; - public static final String HISTORY = "webcontent.history"; public static final String HTTP_STATE = "webcontent.http.state"; - + // Class Data - + protected final static Log log = LogFactory.getLog(WebContentPortlet.class); + public final static String defaultEncoding = "UTF-8"; // Data Members - + private RulesetRewriter rewriter = null; + private RewriterController rewriteController = null; public static final String FORM_POST_METHOD = "post"; + public static final String FORM_GET_METHOD = "get"; + public static final String FORM_MULTIPART_METHOD = "multipart"; - + public WebContentPortlet() { super(); @@ -146,8 +153,8 @@ * @throws PortletException * @throws IOException */ - public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, - IOException + public void processAction(ActionRequest actionRequest, + ActionResponse actionResponse) throws PortletException, IOException { // check to see if it is a meta-navigation command String browserAction = actionRequest.getParameter(BROWSER_ACTION_PARAM); @@ -155,42 +162,51 @@ { if (!browserAction.equalsIgnoreCase(BROWSER_ACTION_REFRESH_PAGE)) { - // for Refresh, there is nothing special to do - current history page will be re-displayed - WebContentHistoryList history = (WebContentHistoryList)PortletMessaging.receive(actionRequest, HISTORY); - - if (browserAction.equalsIgnoreCase(BROWSER_ACTION_PREVIOUS_PAGE)) + // for Refresh, there is nothing special to do - current history + // page will be re-displayed + WebContentHistoryList history = (WebContentHistoryList) PortletMessaging + .receive(actionRequest, HISTORY); + + if (browserAction + .equalsIgnoreCase(BROWSER_ACTION_PREVIOUS_PAGE)) { - if (history.hasPreviousPage()) - history.getPreviousPage(); + if (history.hasPreviousPage()) history.getPreviousPage(); } - else if (browserAction.equalsIgnoreCase(BROWSER_ACTION_NEXT_PAGE)) + else if (browserAction + .equalsIgnoreCase(BROWSER_ACTION_NEXT_PAGE)) { - if (history.hasNextPage()) - history.getNextPage(); + if (history.hasNextPage()) history.getNextPage(); } } - - return ; // proceed to doView() with adjusted history + + return; // proceed to doView() with adjusted history } - - // Check if an action parameter was defined - String webContentURL = actionRequest.getParameter(WebContentRewriter.ACTION_PARAMETER_URL); - String webContentMethod = actionRequest.getParameter(WebContentRewriter.ACTION_PARAMETER_METHOD); - Map webContentParams = new HashMap(actionRequest.getParameterMap()) ; - + + // Check if an action parameter was defined + String webContentURL = actionRequest + .getParameter(WebContentRewriter.ACTION_PARAMETER_URL); + String webContentMethod = actionRequest + .getParameter(WebContentRewriter.ACTION_PARAMETER_METHOD); + Map webContentParams = new HashMap(actionRequest.getParameterMap()); + // defaults - if (webContentMethod == null) webContentMethod = "" ; // default to GET - - // parameter map includes the URL (as ACTION_PARAMETER_URL), but all actual params as well + if (webContentMethod == null) webContentMethod = ""; // default to + // GET + + // parameter map includes the URL (as ACTION_PARAMETER_URL), but all + // actual params as well webContentParams.remove(WebContentRewriter.ACTION_PARAMETER_URL); webContentParams.remove(WebContentRewriter.ACTION_PARAMETER_METHOD); - - if (webContentURL == null || actionRequest.getPortletMode() == PortletMode.EDIT) + + if (webContentURL == null + || actionRequest.getPortletMode() == PortletMode.EDIT) { - processPreferencesAction(actionRequest, actionResponse); - webContentURL = actionRequest.getPreferences().getValue("SRC", "http://portals.apache.org"); + processPreferencesAction(actionRequest, actionResponse); + webContentURL = actionRequest.getPreferences().getValue("SRC", + "http://portals.apache.org"); - // parameters are for the EDIT mode form, and should not be propagated to the subsequent GET in doView + // parameters are for the EDIT mode form, and should not be + // propagated to the subsequent GET in doView webContentParams.clear(); } @@ -200,10 +216,11 @@ if (webContentURL != null && webContentURL.length() > 0) { // new page visit - make it the current page in the history - WebContentHistoryList history = (WebContentHistoryList)PortletMessaging.receive(actionRequest, HISTORY); - if (history == null) - history = new WebContentHistoryList(); - history.visitPage(new WebContentHistoryPage(webContentURL,webContentParams,webContentMethod)); + WebContentHistoryList history = (WebContentHistoryList) PortletMessaging + .receive(actionRequest, HISTORY); + if (history == null) history = new WebContentHistoryList(); + history.visitPage(new WebContentHistoryPage(webContentURL, + webContentParams, webContentMethod)); PortletMessaging.publish(actionRequest, HISTORY, history); } } @@ -212,27 +229,30 @@ * doView Renders the URL in the following order 1) SESSION_PARAMETER * 2)cached version 3) defined for preference SRC */ - public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException + public void doView(RenderRequest request, RenderResponse response) + throws PortletException, IOException { - String viewPage = (String)request.getAttribute(PARAM_VIEW_PAGE); + String viewPage = (String) request.getAttribute(PARAM_VIEW_PAGE); if (viewPage != null) { super.doView(request, response); return; } - + // view the current page in the history - WebContentHistoryList history = (WebContentHistoryList)PortletMessaging.receive(request, HISTORY); - if (history == null) - history = new WebContentHistoryList(); + WebContentHistoryList history = (WebContentHistoryList) PortletMessaging + .receive(request, HISTORY); + if (history == null) history = new WebContentHistoryList(); WebContentHistoryPage currentPage = history.getCurrentPage(); if (currentPage == null) { String sourceURL = request.getPreferences().getValue("SRC", ""); if (sourceURL == null) { - // BOZO - switch to edit mode automatically here, instead of throwing exception! - throw new PortletException("WebContent source not specified. Go to edit mode and specify an URL."); + // BOZO - switch to edit mode automatically here, instead of + // throwing exception! + throw new PortletException( + "WebContent source not specified. Go to edit mode and specify an URL."); } currentPage = new WebContentHistoryPage(sourceURL); } @@ -240,7 +260,7 @@ // Initialize the controller if it's not already done if (rewriteController == null) { - PortletContext portletApplication = getPortletContext(); + PortletContext portletApplication = getPortletContext(); String path = portletApplication.getRealPath("/WEB-INF"); String contextPath = path + "/"; try @@ -252,60 +272,70 @@ { // Failed to create rewriter controller String msg = "WebContentPortlet failed to create rewriter controller."; - log.error(msg,e); + log.error(msg, e); throw new PortletException(e.getMessage()); } } // get content from current page response.setContentType("text/html"); - byte[] content = doWebContent(currentPage.getUrl(), currentPage.getParams(), currentPage.isPost(), request, response); + byte[] content = doWebContent(currentPage.getUrl(), currentPage + .getParams(), currentPage.isPost(), request, response); // System.out.println("Rewritten content is\n..."+new String(content)); - + // write the meta-control navigation header PrintWriter writer = response.getWriter(); writer.print("<block>"); if (history.hasPreviousPage()) { - PortletURL prevAction = response.createActionURL() ; - prevAction.setParameter(BROWSER_ACTION_PARAM, BROWSER_ACTION_PREVIOUS_PAGE); - writer.print(" [<a href=\"" + prevAction.toString() +"\">Previous Page</a>] "); + PortletURL prevAction = response.createActionURL(); + prevAction.setParameter(BROWSER_ACTION_PARAM, + BROWSER_ACTION_PREVIOUS_PAGE); + writer.print(" [<a href=\"" + prevAction.toString() + + "\">Previous Page</a>] "); } - PortletURL refreshAction = response.createActionURL() ; - refreshAction.setParameter(BROWSER_ACTION_PARAM, BROWSER_ACTION_REFRESH_PAGE); - writer.print(" [<a href=\"" + refreshAction.toString() +"\">Refresh Page</a>] "); + PortletURL refreshAction = response.createActionURL(); + refreshAction.setParameter(BROWSER_ACTION_PARAM, + BROWSER_ACTION_REFRESH_PAGE); + writer.print(" [<a href=\"" + refreshAction.toString() + + "\">Refresh Page</a>] "); if (history.hasNextPage()) { - PortletURL nextAction = response.createActionURL() ; - nextAction.setParameter(BROWSER_ACTION_PARAM, BROWSER_ACTION_NEXT_PAGE); - writer.print(" [<a href=\"" + nextAction.toString() +"\">Next Page</a>] "); + PortletURL nextAction = response.createActionURL(); + nextAction.setParameter(BROWSER_ACTION_PARAM, + BROWSER_ACTION_NEXT_PAGE); + writer.print(" [<a href=\"" + nextAction.toString() + + "\">Next Page</a>] "); } writer.print("</block><hr/>"); // drain the stream to the portlet window ByteArrayInputStream bais = new ByteArrayInputStream(content); - drain(new InputStreamReader(bais, WebContentPortlet.defaultEncoding), writer); + drain(new InputStreamReader(bais, WebContentPortlet.defaultEncoding), + writer); bais.close(); - + // done, cache results in the history and save the history history.visitPage(currentPage); PortletMessaging.publish(request, HISTORY, history); } - public void doEdit(RenderRequest request, RenderResponse response) throws PortletException, IOException + public void doEdit(RenderRequest request, RenderResponse response) + throws PortletException, IOException { response.setContentType("text/html"); doPreferencesEdit(request, response); } - + /* * Privaye helpers for generating WebContent */ - protected byte[] doWebContent(String sourceAttr, Map sourceParams, boolean isPost, RenderRequest request, RenderResponse response) - throws PortletException + protected byte[] doWebContent(String sourceAttr, Map sourceParams, + boolean isPost, RenderRequest request, RenderResponse response) + throws PortletException { - HttpMethod httpMethod = null ; - + HttpMethod httpMethod = null; + try { // Set the action and base URLs in the rewriter @@ -313,30 +343,39 @@ ((WebContentRewriter) rewriter).setActionURL(action); URL baseURL = new URL(sourceAttr); rewriter.setBaseUrl(baseURL.toString()); - + // ...file URLs may be used for testing if (baseURL.getProtocol().equals("file")) { - Reader reader = new InputStreamReader((InputStream)baseURL.getContent()); + Reader reader = new InputStreamReader((InputStream) baseURL + .getContent()); StringWriter writer = new StringWriter(); - rewriter.rewrite(rewriteController.createParserAdaptor("text/html"), reader, writer); + rewriter.rewrite(rewriteController + .createParserAdaptor("text/html"), reader, writer); writer.flush(); return writer.toString().getBytes(); } // else fall through to normal case (http/https)... - + // ...set up URL and HttpClient stuff - HttpClient httpClient = getHttpClient(request) ; + HttpClient httpClient = getHttpClient(request); String method = (isPost) ? FORM_POST_METHOD : FORM_GET_METHOD; - httpMethod = getHttpMethod(httpClient, getURLSource(sourceAttr, sourceParams, request, response), sourceParams, method, request); - byte[] result = doPreemptiveAuthentication(httpClient, httpMethod, request, response); - + httpMethod = getHttpMethod(httpClient, getURLSource(sourceAttr, + sourceParams, request, response), sourceParams, method, + request); + byte[] result = doPreemptiveAuthentication(httpClient, httpMethod, + request, response); + // ...get, cache, and return the content - if (result == null) { - return doHttpWebContent(httpClient, httpMethod, 0, request, response); - } else { - return result; + if (result == null) + { + return doHttpWebContent(httpClient, httpMethod, 0, request, + response); } + else + { + return result; + } } catch (PortletException pex) { @@ -345,157 +384,202 @@ } catch (Exception ex) { - String msg = "Exception while rewritting HTML content" ; - log.error(msg,ex); - throw new PortletException(msg+", Error: "+ex.getMessage()); + String msg = "Exception while rewritting HTML content"; + log.error(msg, ex); + throw new PortletException(msg + ", Error: " + ex.getMessage()); } finally { // release the http connection - if (httpMethod != null) - httpMethod.releaseConnection(); + if (httpMethod != null) httpMethod.releaseConnection(); } } - protected byte[] doHttpWebContent(HttpClient httpClient, HttpMethod httpMethod, int retryCount, RenderRequest request, RenderResponse response) - throws PortletException + protected byte[] doHttpWebContent(HttpClient httpClient, + HttpMethod httpMethod, int retryCount, RenderRequest request, + RenderResponse response) throws PortletException { try { // Get the input stream from the provided httpClient/httpMethod - // System.out.println("WebContentPortlet.doHttpWebContent() - from path: "+httpMethod.getPath()); - + // System.out.println("WebContentPortlet.doHttpWebContent() - from + // path: "+httpMethod.getPath()); + // ...set up URL and HttpClient stuff httpClient.executeMethod(httpMethod); - - // ...reset base URL with fully resolved path (e.g. if a directory, path will end with a /, which it may not have in the call to this method) - rewriter.setBaseUrl( rewriter.getBaseRelativeUrl( httpMethod.getPath() )) ; - // System.out.println("...reset base URL from final path: "+httpMethod.getPath()); - + + // ...reset base URL with fully resolved path (e.g. if a directory, + // path will end with a /, which it may not have in the call to this + // method) + rewriter.setBaseUrl(rewriter.getBaseRelativeUrl(httpMethod + .getPath())); + // System.out.println("...reset base URL from final path: + // "+httpMethod.getPath()); + // ...save updated state Cookie[] cookies = httpClient.getState().getCookies(); PortletMessaging.publish(request, HTTP_STATE, cookies); - // System.out.println("...saving: "+(cookies != null ? cookies.length : 0)+", cookies..."); - // for(int i=0,limit = cookies != null ? cookies.length : 0; i<limit; i++) System.out.println("...cookie["+i+"] is: "+cookies[i]); + // System.out.println("...saving: "+(cookies != null ? + // cookies.length : 0)+", cookies..."); + // for(int i=0,limit = cookies != null ? cookies.length : 0; + // i<limit; i++) System.out.println("...cookie["+i+"] is: + // "+cookies[i]); // ...check for manual redirects int responseCode = httpMethod.getStatusCode(); if (responseCode >= 300 && responseCode <= 399) { - // redirection that could not be handled automatically!!! (probably from a POST) - Header locationHeader = httpMethod.getResponseHeader("location"); - String redirectLocation = locationHeader != null ? locationHeader.getValue() : null ; + // redirection that could not be handled automatically!!! + // (probably from a POST) + Header locationHeader = httpMethod + .getResponseHeader("location"); + String redirectLocation = locationHeader != null ? locationHeader + .getValue() + : null; if (redirectLocation != null) { - // System.out.println("WebContentPortlet.doHttpWebContent() >>>handling redirect to: "+redirectLocation+"<<<"); - - // one more time (assume most params are already encoded & new URL is using GET protocol!) - return doWebContent( redirectLocation, new HashMap(), false, request, response ) ; + // System.out.println("WebContentPortlet.doHttpWebContent() + // >>>handling redirect to: "+redirectLocation+"<<<"); + + // one more time (assume most params are already encoded & + // new URL is using GET protocol!) + return doWebContent(redirectLocation, new HashMap(), false, + request, response); } else { - // The response is a redirect, but did not provide the new location for the resource. - throw new PortletException("Redirection code: "+responseCode+", but with no redirectionLocation set."); + // The response is a redirect, but did not provide the new + // location for the resource. + throw new PortletException("Redirection code: " + + responseCode + + ", but with no redirectionLocation set."); } } - else if ( responseCode >= 400 ) + else if (responseCode >= 400) { - if ( responseCode == 401 ) + if (responseCode == 401) { - if (httpMethod.getHostAuthState().isAuthRequested() && retryCount++ < 1 && doRequestedAuthentication( httpClient, httpMethod, request, response)) + if (httpMethod.getHostAuthState().isAuthRequested() + && retryCount++ < 1 + && doRequestedAuthentication(httpClient, + httpMethod, request, response)) { // try again, now that we are authorizied - return doHttpWebContent(httpClient, httpMethod, retryCount, request, response); + return doHttpWebContent(httpClient, httpMethod, + retryCount, request, response); } else { // could not authorize - throw new PortletException("Site requested authorization, but we are unable to provide credentials"); + throw new PortletException( + "Site requested authorization, but we are unable to provide credentials"); } } else if (retryCount++ < 3) { - log.info("WebContentPortlet.doHttpWebContent() - retrying: "+httpMethod.getPath()+", response code: "+responseCode); - + log + .info("WebContentPortlet.doHttpWebContent() - retrying: " + + httpMethod.getPath() + + ", response code: " + responseCode); + // retry - return doHttpWebContent(httpClient, httpMethod, retryCount, request, response); + return doHttpWebContent(httpClient, httpMethod, retryCount, + request, response); } else { // bad - throw new PortletException("Failure reading: "+httpMethod.getPath()+", response code: "+responseCode); + throw new PortletException("Failure reading: " + + httpMethod.getPath() + ", response code: " + + responseCode); } } - - // System.out.println("...response code: "+responseCode+", fetching content as stream and rewriting."); - + + // System.out.println("...response code: "+responseCode+", fetching + // content as stream and rewriting."); + // ...ok - *now* create the input stream and reader - BufferedInputStream bis = new BufferedInputStream(httpMethod.getResponseBodyAsStream()); - String encoding = ((HttpMethodBase)httpMethod).getResponseCharSet(); - if (encoding == null) - encoding = getContentCharSet(bis); + BufferedInputStream bis = new BufferedInputStream(httpMethod + .getResponseBodyAsStream()); + String encoding = ((HttpMethodBase) httpMethod) + .getResponseCharSet(); + if (encoding == null) encoding = getContentCharSet(bis); Reader htmlReader = new InputStreamReader(bis, encoding); - + // get the output buffer - if (encoding == null) - encoding = WebContentPortlet.defaultEncoding ; + if (encoding == null) encoding = WebContentPortlet.defaultEncoding; ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); - Writer htmlWriter = new OutputStreamWriter(byteOutputStream, encoding); + Writer htmlWriter = new OutputStreamWriter(byteOutputStream, + encoding); // rewrite and flush output - rewriter.rewrite(rewriteController.createParserAdaptor("text/html"), htmlReader, htmlWriter); + rewriter.rewrite( + rewriteController.createParserAdaptor("text/html"), + htmlReader, htmlWriter); htmlWriter.flush(); // Page has been rewritten // TODO: Write it to cache - //System.out.println(new String(byteOutputStream.toByteArray())); + // System.out.println(new String(byteOutputStream.toByteArray())); return byteOutputStream.toByteArray(); } catch (UnsupportedEncodingException ueex) { - throw new PortletException("Encoding " + defaultEncoding + " not supported. Error: " + ueex.getMessage()); + throw new PortletException("Encoding " + defaultEncoding + + " not supported. Error: " + ueex.getMessage()); } catch (RewriterException rwe) { - throw new PortletException("Failed to rewrite HTML page. Error: " + rwe.getMessage()); + throw new PortletException("Failed to rewrite HTML page. Error: " + + rwe.getMessage()); } catch (Exception e) { - throw new PortletException("Exception while rewritting HTML page. Error: " + e.getMessage()); + throw new PortletException( + "Exception while rewritting HTML page. Error: " + + e.getMessage()); } } - - protected String getURLSource(String source, Map params, RenderRequest request, RenderResponse response) + + protected String getURLSource(String source, Map params, + RenderRequest request, RenderResponse response) { - return source; + return source; } - - protected byte[] doPreemptiveAuthentication(HttpClient clent,HttpMethod method, RenderRequest request, RenderResponse response) + + protected byte[] doPreemptiveAuthentication(HttpClient clent, + HttpMethod method, RenderRequest request, RenderResponse response) { - // derived class responsibilty - return true, if credentials have been set - return null ; + // derived class responsibilty - return true, if credentials have been + // set + return null; } - - protected boolean doRequestedAuthentication(HttpClient clent,HttpMethod method, RenderRequest request, RenderResponse response) + + protected boolean doRequestedAuthentication(HttpClient clent, + HttpMethod method, RenderRequest request, RenderResponse response) { - // derived class responsibilty - return true, if credentials have been set - return false ; + // derived class responsibilty - return true, if credentials have been + // set + return false; } /* * Generate a rewrite controller using the basic rules file */ - private RewriterController getController(String contextPath) throws Exception + private RewriterController getController(String contextPath) + throws Exception { Class[] rewriterClasses = new Class[] - { WebContentRewriter.class, WebContentRewriter.class}; - + {WebContentRewriter.class, WebContentRewriter.class}; + Class[] adaptorClasses = new Class[] - { NekoParserAdaptor.class, SaxParserAdaptor.class}; - RewriterController rwc = new JetspeedRewriterController(contextPath + "conf/rewriter-rules-mapping.xml", Arrays + {NekoParserAdaptor.class, SaxParserAdaptor.class}; + RewriterController rwc = new JetspeedRewriterController(contextPath + + "conf/rewriter-rules-mapping.xml", Arrays .asList(rewriterClasses), Arrays.asList(adaptorClasses)); - FileReader reader = new FileReader(contextPath + "conf/default-rewriter-rules.xml"); + FileReader reader = new FileReader(contextPath + + "conf/default-rewriter-rules.xml"); Ruleset ruleset = rwc.loadRuleset(reader); reader.close(); @@ -503,54 +587,67 @@ return rwc; } - protected HttpClient getHttpClient(RenderRequest request) throws IOException + protected HttpClient getHttpClient(RenderRequest request) + throws IOException { // derived class hook (e.g. to set up Basic Authentication) HttpClient client = new HttpClient(); - + // reuse existing state, if we have been here before - Cookie[] cookies = (Cookie[])PortletMessaging.receive(request, HTTP_STATE); + Cookie[] cookies = (Cookie[]) PortletMessaging.receive(request, + HTTP_STATE); if (cookies != null) { - // ...so far, just saving cookies - may need a more complex Serializable object here + // ...so far, just saving cookies - may need a more complex + // Serializable object here client.getState().addCookies(cookies); - // System.out.println("WebContentPortlet.getHttpClient() - reusing: "+cookies.length+", cookies..."); - // for(int i=0,limit = cookies.length; i<limit; i++) System.out.println("...cookie["+i+"] is: "+cookies[i]); + // System.out.println("WebContentPortlet.getHttpClient() - reusing: + // "+cookies.length+", cookies..."); + // for(int i=0,limit = cookies.length; i<limit; i++) + // System.out.println("...cookie["+i+"] is: "+cookies[i]); } - - return client ; + + return client; } - - protected HttpMethodBase getHttpMethod(HttpClient client, String uri, Map params, String formMethod, RenderRequest request) throws IOException + + protected HttpMethodBase getHttpMethod(HttpClient client, String uri, + Map params, String formMethod, RenderRequest request) + throws IOException { formMethod = FORM_MULTIPART_METHOD; HttpMethodBase httpMethod = null; String useragentProperty = request.getProperty("User-Agent"); - if(formMethod.equalsIgnoreCase(FORM_MULTIPART_METHOD)){ + if (formMethod.equalsIgnoreCase(FORM_MULTIPART_METHOD)) + { // http mutipart - MultipartPostMethod mutlitPart = (MultipartPostMethod)( httpMethod = new MultipartPostMethod(uri)) ; + MultipartPostMethod mutlitPart = (MultipartPostMethod) (httpMethod = new MultipartPostMethod( + uri)); if (params != null && !params.isEmpty()) { Iterator iter = params.entrySet().iterator(); while (iter.hasNext()) { - Map.Entry entry = (Map.Entry)iter.next(); - String name = (String)entry.getKey(); - String[] values = (String[])entry.getValue(); + Map.Entry entry = (Map.Entry) iter.next(); + String name = (String) entry.getKey(); + String[] values = (String[]) entry.getValue(); if (values != null) - for (int i=0,limit=values.length; i<limit; i++) + for (int i = 0, limit = values.length; i < limit; i++) { - // System.out.println("...adding >>>POST parameter: "+name+", with value: "+values[i]+"<<<"); - + // System.out.println("...adding >>>POST parameter: + // "+name+", with value: "+values[i]+"<<<"); + mutlitPart.addParameter(name, values[i]); } - } + } } - - }else if (formMethod.equalsIgnoreCase(FORM_GET_METHOD)){ - - // System.out.println("WebContentPortlet.getHttpMethod() - HTTP GET from URL: "+uri); + + } + else if (formMethod.equalsIgnoreCase(FORM_GET_METHOD)) + { + + // System.out.println("WebContentPortlet.getHttpMethod() - HTTP GET + // from URL: "+uri); // http GET httpMethod = new GetMethod(uri); if (params != null && !params.isEmpty()) @@ -559,82 +656,73 @@ Iterator iter = params.entrySet().iterator(); while (iter.hasNext()) { - Map.Entry entry = (Map.Entry)iter.next() ; - String name = (String)entry.getKey() ; - String[] values = (String [])entry.getValue() ; + Map.Entry entry = (Map.Entry) iter.next(); + String name = (String) entry.getKey(); + String[] values = (String[]) entry.getValue(); if (values != null) - for (int i = 0,limit = values.length; i < limit; i++) + for (int i = 0, limit = values.length; i < limit; i++) { - // System.out.println("...adding >>>GET parameter: "+name+", with value: "+values[i]+"<<<"); + // System.out.println("...adding >>>GET parameter: + // "+name+", with value: "+values[i]+"<<<"); pairs.add(new NameValuePair(name, values[i])); } } - httpMethod.setQueryString((NameValuePair[])pairs.toArray(new NameValuePair[pairs.size()])); + httpMethod.setQueryString((NameValuePair[]) pairs + .toArray(new NameValuePair[pairs.size()])); } - - // automatically follow redirects (NOTE: not supported in POST - will throw exeception if you ask for it, then sees a redirect!!) + + // automatically follow redirects (NOTE: not supported in POST - + // will throw exeception if you ask for it, then sees a redirect!!) httpMethod.setFollowRedirects(true); - }else if (formMethod.equalsIgnoreCase(FORM_POST_METHOD)) { - // System.out.println("WebContentPortlet.getHttpMethod() - HTTP POST to URL: "+uri); - + } + else if (formMethod.equalsIgnoreCase(FORM_POST_METHOD)) + { + // System.out.println("WebContentPortlet.getHttpMethod() - HTTP POST + // to URL: "+uri); + // http POST - PostMethod postMethod = (PostMethod)( httpMethod = new PostMethod(uri)) ; + PostMethod postMethod = (PostMethod) (httpMethod = new PostMethod( + uri)); if (params != null && !params.isEmpty()) { Iterator iter = params.entrySet().iterator(); while (iter.hasNext()) { - Map.Entry entry = (Map.Entry)iter.next(); - String name = (String)entry.getKey(); - String[] values = (String[])entry.getValue(); + Map.Entry entry = (Map.Entry) iter.next(); + String name = (String) entry.getKey(); + String[] values = (String[]) entry.getValue(); if (values != null) - for (int i=0,limit=values.length; i<limit; i++) + for (int i = 0, limit = values.length; i < limit; i++) { - // System.out.println("...adding >>>POST parameter: "+name+", with value: "+values[i]+"<<<"); - + // System.out.println("...adding >>>POST parameter: + // "+name+", with value: "+values[i]+"<<<"); + postMethod.addParameter(name, values[i]); } - } + } } } - - // propagate User-Agent, so target site does not think we are a D.O.S. attack - httpMethod.addRequestHeader( "User-Agent", useragentProperty ); - - // BOZO - DON'T do this. default policy seems to be more flexible!!! - //httpMethod.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); - + + // propagate User-Agent, so target site does not think we are a D.O.S. + // attack + httpMethod.addRequestHeader("User-Agent", useragentProperty); + + // BOZO - DON'T do this. default policy seems to be more flexible!!! + // httpMethod.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); + // ...ready to use! - return httpMethod ; + return httpMethod; } - - - static final int BLOCK_SIZE = 4096; /* - private void drain(InputStream reader, OutputStream writer) throws IOException - { - byte[] bytes = new byte[BLOCK_SIZE]; - try - { - int length = reader.read(bytes); - while (length != -1) - { - if (length != 0) - { - writer.write(bytes, 0, length); - } - length = reader.read(bytes); - } - } - finally - { - bytes = null; - } - } - */ + * private void drain(InputStream reader, OutputStream writer) throws + * IOException { byte[] bytes = new byte[BLOCK_SIZE]; try { int length = + * reader.read(bytes); while (length != -1) { if (length != 0) { + * writer.write(bytes, 0, length); } length = reader.read(bytes); } } + * finally { bytes = null; } } + */ private void drain(Reader r, Writer w) throws IOException { @@ -659,20 +747,13 @@ } /* - private void drain(Reader r, OutputStream os) throws IOException - { - Writer w = new OutputStreamWriter(os); - drain(r, w); - w.flush(); - } - */ + * private void drain(Reader r, OutputStream os) throws IOException { Writer + * w = new OutputStreamWriter(os); drain(r, w); w.flush(); } + */ private String getContentCharSet(InputStream is) throws IOException { - if (!is.markSupported()) - { - return null; - } + if (!is.markSupported()) { return null; } byte[] buf = new byte[BLOCK_SIZE]; try @@ -698,17 +779,16 @@ { String element = st.nextToken(); String lowerCaseElement = element.toLowerCase(); - if (lowerCaseElement.startsWith("meta") && lowerCaseElement.indexOf("content-type") > 0) + if (lowerCaseElement.startsWith("meta") + && lowerCaseElement.indexOf("content-type") > 0) { - StringTokenizer est = new StringTokenizer(element, " =\"\';"); + StringTokenizer est = new StringTokenizer(element, + " =\"\';"); while (est.hasMoreTokens()) { if (est.nextToken().equalsIgnoreCase("charset")) { - if (est.hasMoreTokens()) - { - return est.nextToken(); - } + if (est.hasMoreTokens()) { return est.nextToken(); } } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/sso/SSOProxyPortlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/sso/SSOProxyPortlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/sso/SSOProxyPortlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /*Created on: Dec 5, 2005 */ @@ -22,6 +22,7 @@ import java.io.IOException; import java.security.AccessControlContext; import java.security.AccessController; + import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletConfig; @@ -39,167 +40,163 @@ import org.apache.portals.bridges.velocity.GenericVelocityPortlet; /** - * SSOProxyPortlet - * This portlet can be used as a bridge to any URL. - * It acts as a http client and therefore it can store - * cookies. - * The main purpose is that the SSOProxy portlet authenticates - * any SSO credential for the principal user not knowing in advance - * what URL the user might select. No login prompt will appear for any url - * in the portlet for that an SSO entry exists and the principal user has permissions. + * SSOProxyPortlet This portlet can be used as a bridge to any URL. It acts as a + * http client and therefore it can store cookies. The main purpose is that the + * SSOProxy portlet authenticates any SSO credential for the principal user not + * knowing in advance what URL the user might select. No login prompt will + * appear for any url in the portlet for that an SSO entry exists and the + * principal user has permissions. * * @author Roger Ruttimann <rogerrut ¡÷ apache.org> - * + * */ -public class SSOProxyPortlet extends GenericVelocityPortlet { +public class SSOProxyPortlet extends GenericVelocityPortlet +{ + private PortletContext context; + private SSOProvider sso; - + /* Re-use Proxy client inside the SSO Component */ private boolean isAuthenticated = false; - - /** Default encoding UTF-8*/ + + /** Default encoding UTF-8 */ public String defaultEncoding = "UTF-8"; - + /** Block Size */ static final int BLOCK_SIZE = 4096; - - /** ACTION_PARAMETER_SSOPROXY*/ + + /** ACTION_PARAMETER_SSOPROXY */ static final String ACTION_PARAMETER_SSOPROXY = "SSOProxy"; - + /** Preference values */ /** DestinationURL */ static final String DESTINATION_URL = "DestinationURL"; - + /** SSOSite */ static final String SSO_SITE = "SSOSite"; - - /** ForceSSORefresh*/ + + /** ForceSSORefresh */ static final String FORCE_SSO_REFRESH = "ForceSSORefresh"; - - /** Encoding*/ + + /** Encoding */ static final String ENCODING = "Encoding"; - + private String destinationURL; + private String ssoSite; + private String encoding; public void init(PortletConfig config) throws PortletException { super.init(config); context = getPortletContext(); - sso = (SSOProvider)context.getAttribute("cps:SSO"); - if (null == sso) - { - throw new PortletException("Failed to find SSO Provider on portlet initialization"); - } - + sso = (SSOProvider) context.getAttribute("cps:SSO"); + if (null == sso) { throw new PortletException( + "Failed to find SSO Provider on portlet initialization"); } + } - - public void processAction(ActionRequest request, ActionResponse actionResponse) - throws PortletException, IOException + + public void processAction(ActionRequest request, + ActionResponse actionResponse) throws PortletException, IOException { - String ssoProxyAction = request.getParameter(ACTION_PARAMETER_SSOPROXY); -// System.out.println("SSOProxy Action value [" + ssoProxyAction + "]"); - - if ( ssoProxyAction != null && ssoProxyAction.length() > 0) - this.destinationURL = ssoProxyAction; - else - this.destinationURL = request.getParameter(DESTINATION_URL); - - + String ssoProxyAction = request.getParameter(ACTION_PARAMETER_SSOPROXY); + // System.out.println("SSOProxy Action value [" + ssoProxyAction + "]"); + + if (ssoProxyAction != null && ssoProxyAction.length() > 0) + this.destinationURL = ssoProxyAction; + else + this.destinationURL = request.getParameter(DESTINATION_URL); + this.ssoSite = request.getParameter(SSO_SITE); this.encoding = request.getParameter(ENCODING); - if (this.encoding == null) - this.encoding = this.defaultEncoding; + if (this.encoding == null) this.encoding = this.defaultEncoding; // save the prefs super.processAction(request, actionResponse); } - + public void doView(RenderRequest request, RenderResponse response) - throws PortletException, IOException + throws PortletException, IOException { - String forceRefresh = request.getPreferences().getValue(FORCE_SSO_REFRESH, "false"); + String forceRefresh = request.getPreferences().getValue( + FORCE_SSO_REFRESH, "false"); if (destinationURL == null || destinationURL.length() == 0) { // No destination configured Switch to configure View - request.setAttribute(PARAM_VIEW_PAGE, this.getPortletConfig().getInitParameter(PARAM_EDIT_PAGE)); + request.setAttribute(PARAM_VIEW_PAGE, this.getPortletConfig() + .getInitParameter(PARAM_EDIT_PAGE)); setupPreferencesEdit(request, response); super.doView(request, response); return; } - -// Set the content type + + // Set the content type response.setContentType("text/html"); - + /* * Call into the SSO Proxy and process the result page */ boolean doRefresh = false; - if ( (forceRefresh.compareToIgnoreCase("TRUE") == 0) || this.isAuthenticated == false) - doRefresh = true; - + if ((forceRefresh.compareToIgnoreCase("TRUE") == 0) + || this.isAuthenticated == false) doRefresh = true; + try { - StringBuffer page= new StringBuffer(); - Subject subject = getSubject(); - if (ssoSite == null || ssoSite.length() ==0) - page.append(sso.useSSO(subject, destinationURL,doRefresh)); + StringBuffer page = new StringBuffer(); + Subject subject = getSubject(); + if (ssoSite == null || ssoSite.length() == 0) + page.append(sso.useSSO(subject, destinationURL, doRefresh)); else - page.append(sso.useSSO(subject, destinationURL,ssoSite, doRefresh)); - + page.append(sso.useSSO(subject, destinationURL, ssoSite, + doRefresh)); + // Authentication done at least once this.isAuthenticated = true; /* - bis.mark(BLOCK_SIZE); - String pageEncoding = getContentCharSet(bis); - if (pageEncoding == null) - { - pageEncoding = encoding; - } - - Reader read = new InputStreamReader(bis, encoding); - - - char[] bytes = new char[BLOCK_SIZE]; - - int len = read.read(bytes, 0, BLOCK_SIZE); - while (len > 0) - { - page.append(bytes, 0, len); - len = read.read(bytes, 0, BLOCK_SIZE); - } - - //Done - read.close(); - */ + * bis.mark(BLOCK_SIZE); String pageEncoding = + * getContentCharSet(bis); if (pageEncoding == null) { pageEncoding = + * encoding; } + * + * Reader read = new InputStreamReader(bis, encoding); + * + * + * char[] bytes = new char[BLOCK_SIZE]; + * + * int len = read.read(bytes, 0, BLOCK_SIZE); while (len > 0) { + * page.append(bytes, 0, len); len = read.read(bytes, 0, + * BLOCK_SIZE); } + * + * //Done read.close(); + */ // Rewrite - // Post Process for generated page - PortletURL actionURL = response.createActionURL(); - ScriptPostProcess processor = new ScriptPostProcess(); - processor.setInitalPage(page); - processor.postProcessPage(actionURL, ACTION_PARAMETER_SSOPROXY); - String finalPage = processor.getFinalizedPage(); - - // Write the page - response.getWriter().println(finalPage); - + // Post Process for generated page + PortletURL actionURL = response.createActionURL(); + ScriptPostProcess processor = new ScriptPostProcess(); + processor.setInitalPage(page); + processor.postProcessPage(actionURL, ACTION_PARAMETER_SSOPROXY); + String finalPage = processor.getFinalizedPage(); + + // Write the page + response.getWriter().println(finalPage); + } catch (SSOException e) { - response.getWriter().println("<P>Error rendering page. Error message<BR>" + e.getMessage() + "</P>"); - - this.destinationURL =""; - } + response.getWriter().println( + "<P>Error rendering page. Error message<BR>" + + e.getMessage() + "</P>"); + + this.destinationURL = ""; + } } - public void doEdit(RenderRequest request, RenderResponse response) - throws PortletException, IOException + throws PortletException, IOException { - super.doEdit(request, response); + super.doEdit(request, response); } /* @@ -208,65 +205,32 @@ private Subject getSubject() { AccessControlContext context = AccessController.getContext(); - return JSSubject.getSubject(context); + return JSSubject.getSubject(context); } - + /* - private String getContentCharSet(InputStream is) throws IOException - { - if (!is.markSupported()) - { - return null; - } + * private String getContentCharSet(InputStream is) throws IOException { if + * (!is.markSupported()) { return null; } + * + * byte[] buf = new byte[BLOCK_SIZE]; try { is.read(buf, 0, BLOCK_SIZE); + * String content = new String(buf, "ISO-8859-1"); String lowerCaseContent = + * content.toLowerCase(); int startIndex = lowerCaseContent.indexOf("<head"); + * if (startIndex == -1) { startIndex = 0; } int endIndex = + * lowerCaseContent.indexOf("</head"); if (endIndex == -1) { endIndex = + * content.length(); } content = content.substring(startIndex, endIndex); + * + * StringTokenizer st = new StringTokenizer(content, "<>"); while + * (st.hasMoreTokens()) { String element = st.nextToken(); String + * lowerCaseElement = element.toLowerCase(); if + * (lowerCaseElement.startsWith("meta") && + * lowerCaseElement.indexOf("content-type") > 0) { StringTokenizer est = new + * StringTokenizer(element, " =\"\';"); while (est.hasMoreTokens()) { if + * (est.nextToken().equalsIgnoreCase("charset")) { if (est.hasMoreTokens()) { + * is.reset(); return est.nextToken(); } } } } } } catch (IOException e) { } + * + * is.reset(); + * + * return null; } + */ - byte[] buf = new byte[BLOCK_SIZE]; - try - { - is.read(buf, 0, BLOCK_SIZE); - String content = new String(buf, "ISO-8859-1"); - String lowerCaseContent = content.toLowerCase(); - int startIndex = lowerCaseContent.indexOf("<head"); - if (startIndex == -1) - { - startIndex = 0; - } - int endIndex = lowerCaseContent.indexOf("</head"); - if (endIndex == -1) - { - endIndex = content.length(); - } - content = content.substring(startIndex, endIndex); - - StringTokenizer st = new StringTokenizer(content, "<>"); - while (st.hasMoreTokens()) - { - String element = st.nextToken(); - String lowerCaseElement = element.toLowerCase(); - if (lowerCaseElement.startsWith("meta") && lowerCaseElement.indexOf("content-type") > 0) - { - StringTokenizer est = new StringTokenizer(element, " =\"\';"); - while (est.hasMoreTokens()) - { - if (est.nextToken().equalsIgnoreCase("charset")) - { - if (est.hasMoreTokens()) - { - is.reset(); - return est.nextToken(); - } - } - } - } - } - } - catch (IOException e) - { - } - - is.reset(); - - return null; - } - */ - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/webcontent/WebContentHistoryList.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/webcontent/WebContentHistoryList.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/webcontent/WebContentHistoryList.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,104 +21,113 @@ import java.util.ArrayList; import java.util.List; - /** * A history of content navigations in the WebContentPortlet - * + * * @author <a href="mailto:dyoung ¡÷ phase2systems.com">David L Young</a> - * @version $Id: $ + * @version $Id: $ */ -public class WebContentHistoryList extends Object - implements Serializable +public class WebContentHistoryList extends Object implements Serializable { + int maxLength; + List history; + int currentIndex; - + // Constructors public WebContentHistoryList() { - this( -1 ); + this(-1); } - public WebContentHistoryList( int maxLength ) + + public WebContentHistoryList(int maxLength) { super(); - + this.maxLength = maxLength; this.history = new ArrayList(); this.currentIndex = -1; } - + // Methods - + public boolean isEmpty() { return this.history.isEmpty(); } + public boolean hasCurrentPage() { return this.currentIndex >= 0; } + public boolean hasPreviousPage() { - return !isEmpty() && this.currentIndex-1 >= 0; + return !isEmpty() && this.currentIndex - 1 >= 0; } + public boolean hasNextPage() { - return !isEmpty() && this.currentIndex+1 < this.history.size(); + return !isEmpty() && this.currentIndex + 1 < this.history.size(); } - + public WebContentHistoryPage getCurrentPage() { - if (!hasCurrentPage()) - return null ; - return (WebContentHistoryPage)this.history.get(this.currentIndex); + if (!hasCurrentPage()) return null; + return (WebContentHistoryPage) this.history.get(this.currentIndex); } + public WebContentHistoryPage getPreviousPage() { - if (!hasPreviousPage()) - return null; - this.currentIndex = this.currentIndex-1; + if (!hasPreviousPage()) return null; + this.currentIndex = this.currentIndex - 1; return getCurrentPage(); } + public WebContentHistoryPage getNextPage() { - if (!hasNextPage()) - return null; - this.currentIndex = this.currentIndex+1; + if (!hasNextPage()) return null; + this.currentIndex = this.currentIndex + 1; return getCurrentPage(); } - + public void visitPage(WebContentHistoryPage page) { - if (page==null) - throw new IllegalArgumentException("WebContentHistoryList.addPage() - non-null page required."); - + if (page == null) + throw new IllegalArgumentException( + "WebContentHistoryList.addPage() - non-null page required."); + int i = this.history.indexOf(page); - if (i >= 0 && i == this.currentIndex) + if (i >= 0 && i == this.currentIndex) { // just visiting the current page return; } - + // otherwise - new page... while (hasNextPage()) { - // ...visiting a page discards any pages we have visited by going "back" - this.history.remove(this.currentIndex+1); + // ...visiting a page discards any pages we have visited by going + // "back" + this.history.remove(this.currentIndex + 1); } if (i >= 0 && i < history.size()) { - // ...actually, new visit to an old page, only keep one reference to it + // ...actually, new visit to an old page, only keep one reference to + // it this.history.remove(i); } - + // add in the new page, at the end this.history.add(page); - this.currentIndex = this.history.size()-1; - - // System.out.println("WebContentHistoryList.visitPage() - current index is: "+this.currentIndex+"\nhistory list..."+ArrayUtils.toString(this.history)); + this.currentIndex = this.history.size() - 1; + + // System.out.println("WebContentHistoryList.visitPage() - current index + // is: "+this.currentIndex+"\nhistory + // list..."+ArrayUtils.toString(this.history)); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/webcontent/WebContentHistoryPage.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/webcontent/WebContentHistoryPage.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/webcontent/WebContentHistoryPage.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,75 +24,83 @@ import org.apache.commons.lang.ArrayUtils; - /** * Information required to re-visit a page in the WebContentPortlet - * + * * @author <a href="mailto:dyoung ¡÷ phase2systems.com">David L Young</a> - * @version $Id: $ + * @version $Id: $ */ -public class WebContentHistoryPage extends Object - implements Serializable +public class WebContentHistoryPage extends Object implements Serializable { + private String url; + private Map params; + private boolean is_post; // Constructors - + public WebContentHistoryPage(String url) { this(url, null, null); } + public WebContentHistoryPage(String url, Map params, String method) { super(); // guarantee non-null, so that equals() is well-behaved - if (url==null) - throw new IllegalArgumentException("WebContentHistoryPage() - url required"); - + if (url == null) + throw new IllegalArgumentException( + "WebContentHistoryPage() - url required"); + this.url = url; this.params = params != null ? params : new HashMap(); this.is_post = method != null && method.equalsIgnoreCase("post"); } - + // Base Class Protocol - + public boolean equals(Object o) { - if (o == null || !(o instanceof WebContentHistoryPage)) - return false ; + if (o == null || !(o instanceof WebContentHistoryPage)) return false; - WebContentHistoryPage page = (WebContentHistoryPage)o; - - return page.url.equals(this.url) && page.params.equals(this.params) && page.isPost() == this.isPost() ; + WebContentHistoryPage page = (WebContentHistoryPage) o; + + return page.url.equals(this.url) && page.params.equals(this.params) + && page.isPost() == this.isPost(); } + public String toString() { StringBuffer buff = new StringBuffer(); - buff.append( "[" ).append(isPost() ? "POST: " : "GET: ").append( getUrl() ).append( ", " ).append( getParams().size() ).append(" params: {"); + buff.append("[").append(isPost() ? "POST: " : "GET: ").append(getUrl()) + .append(", ").append(getParams().size()).append(" params: {"); Iterator iter = getParams().entrySet().iterator(); - while ( iter.hasNext() ) + while (iter.hasNext()) { - Map.Entry entry = (Map.Entry)iter.next(); - buff.append("(").append(entry.getKey()).append(" . ").append(ArrayUtils.toString(entry.getKey())).append(")"); + Map.Entry entry = (Map.Entry) iter.next(); + buff.append("(").append(entry.getKey()).append(" . ").append( + ArrayUtils.toString(entry.getKey())).append(")"); } buff.append("}]"); return buff.toString(); } - + // Data Access - + public String getUrl() { return this.url; } + public Map getParams() { return this.params; } + public boolean isPost() { return this.is_post; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/webcontent/WebContentResource.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/webcontent/WebContentResource.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/web-content/src/java/org/apache/jetspeed/portlet/webcontent/WebContentResource.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,27 +20,34 @@ import java.io.Serializable; /** - * A cached resource object, stored in memory to optimize access to static resources - * such as images and style sheets. - * + * A cached resource object, stored in memory to optimize access to static + * resources such as images and style sheets. + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> - * @version $Id: WebContentResource.java 517719 2007-03-13 15:05:48Z ate $ + * @version $Id: WebContentResource.java 517719 2007-03-13 15:05:48Z ate $ */ public class WebContentResource implements Serializable { + private transient byte[] content = null; + private String url = null; + private String lastUrl = null; /** - * Constructor for a cached resource. - * - * @param contentType The HTTP content type for a cached resource as defined - * in WebPageHelper, i.e. WebPageHelper.CT_HTML, WebPageHelper.CT_IMAGE.... - * @param content The byte array of content this cached. This content can be - * binary images, or static text such as scripts and style sheets. - * + * Constructor for a cached resource. + * + * @param contentType + * The HTTP content type for a cached resource as defined in + * WebPageHelper, i.e. WebPageHelper.CT_HTML, + * WebPageHelper.CT_IMAGE.... + * @param content + * The byte array of content this cached. This content can be + * binary images, or static text such as scripts and style + * sheets. + * */ public WebContentResource(String url, byte[] content) { @@ -54,7 +61,7 @@ /** * Gets the content of this resource in a byte array. - * + * * @return A byte array of the resource's content. */ public byte[] getContent() @@ -62,7 +69,6 @@ return content; } - /** * @return Returns the lastUrl. */ @@ -70,13 +76,16 @@ { return lastUrl; } + /** - * @param lastUrl The lastUrl to set. + * @param lastUrl + * The lastUrl to set. */ public void setLastUrl(String lastUrl) { this.lastUrl = lastUrl; } + /** * @return Returns the url. */ @@ -84,8 +93,10 @@ { return url; } + /** - * @param url The url to set. + * @param url + * The url to set. */ public void setUrl(String url) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/webapp-logging/src/java/org/apache/jetspeed/webapp/logging/IsolatedLog4JLogger.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/webapp-logging/src/java/org/apache/jetspeed/webapp/logging/IsolatedLog4JLogger.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/webapp-logging/src/java/org/apache/jetspeed/webapp/logging/IsolatedLog4JLogger.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,130 +25,145 @@ import org.apache.log4j.Hierarchy; /** - * IsolatedLog4JLogger routes all commons-logging logging using Log4J to an ContextClassLoader - * specific Hierarchy. + * IsolatedLog4JLogger routes all commons-logging logging using Log4J to an + * ContextClassLoader specific Hierarchy. * </p> * <p> * For web or application servers providing (and enforcing) commons-logging and - * Log4J from a shared context (like JBoss), configuring Log4J loggers and appenders - * from within a (web) application overrides and resets the global + * Log4J from a shared context (like JBoss), configuring Log4J loggers and + * appenders from within a (web) application overrides and resets the global * Log4J LoggerRepository. * </p> * <p> - * Capturing root logging for logging events from within the web application - * for example isn't possible using a Log4J propery or xml configuration without - * routing <em>ALL</em> root logging through the new (web application specific) - * configuration. + * Capturing root logging for logging events from within the web application for + * example isn't possible using a Log4J propery or xml configuration without + * routing <em>ALL</em> root logging through the new (web application + * specific) configuration. * </p> * <p> * <em>It is possible using the Log4J API directly instead of configuration files, * but that requires hardcoded knowledge about how the logging is to be done.</em> * </p> * <p> - * Furthermore, if another application later on reconfigures the root logging again, the - * current root logging configuration is closed, detached and rerouted to the new configuration. + * Furthermore, if another application later on reconfigures the root logging + * again, the current root logging configuration is closed, detached and + * rerouted to the new configuration. * </p> * <p> - * The same applies of course to common named loggers like capturing springframework logging. + * The same applies of course to common named loggers like capturing + * springframework logging. * </p> * <p> - * The only way to prevent this <em>stealing</em> of logging configuration is allowing only - * one log4J configuration for the whole web or application server.<br/> - * As this has to be done in a web or application server specific manner, setting up Jetspeed - * for different servers will become rather complex and difficult to automate. + * The only way to prevent this <em>stealing</em> of logging configuration is + * allowing only one log4J configuration for the whole web or application + * server.<br/> As this has to be done in a web or application server specific + * manner, setting up Jetspeed for different servers will become rather complex + * and difficult to automate. * </p> * <p> - * The IsolatedLog4JLogger solves these problems by routing all logging through a statically - * configured ContextClassLoader isolated LoggerRepository. + * The IsolatedLog4JLogger solves these problems by routing all logging through + * a statically configured ContextClassLoader isolated LoggerRepository. * </p> - * Using this class requires a commons-logging.properties file in the WEB-INF/classes - * folder containing: + * Using this class requires a commons-logging.properties file in the + * WEB-INF/classes folder containing: + * * <pre> - * org.apache.commons.logging.Log=org.apache.jetspeed.util.IsolatedLog4JLogger + * org.apache.commons.logging.Log = org.apache.jetspeed.util.IsolatedLog4JLogger * </pre> + * * </p> * <p> - * During web application initialization, preferably from a ServletContextListener or - * a Servlet init method loaded with a load-on-startup value of 0 (zero), a new - * ContextClassLoader (e.g. web application) specific LoggerRepository as well as - * the initialization of Log4J should be configured as follows: + * During web application initialization, preferably from a + * ServletContextListener or a Servlet init method loaded with a load-on-startup + * value of 0 (zero), a new ContextClassLoader (e.g. web application) specific + * LoggerRepository as well as the initialization of Log4J should be configured + * as follows: + * * <pre> - * Properties p = new Properties(); - * p.load(new FileInputStream(log4jFile)); - * // Create a new LoggerRepository - * Hierarchy h = new Hierarchy(new RootCategory(Level.INFO)); - * // Configure the LoggerRepository with our own Log4J configuration - * new PropertyConfigurator().doConfigure(p,h); - * // set the LoggerRepository to be used for the current ContextClassLoader - * IsolatedLog4JLogger.setHierarchy(h); + * Properties p = new Properties(); + * p.load(new FileInputStream(log4jFile)); + * // Create a new LoggerRepository + * Hierarchy h = new Hierarchy(new RootCategory(Level.INFO)); + * // Configure the LoggerRepository with our own Log4J configuration + * new PropertyConfigurator().doConfigure(p, h); + * // set the LoggerRepository to be used for the current ContextClassLoader + * IsolatedLog4JLogger.setHierarchy(h); * </pre> - * Instead of using a PropertyConfigurator a DomConfigurator could be used likewise. + * + * Instead of using a PropertyConfigurator a DomConfigurator could be used + * likewise. * </p> * <p> - * TODO: It might be useful to have this utility class available for usage by Portlet - * Applications too. Because this class <em>must</em> be included within a web application - * classpath, a separate jetspeed-tools or jetspeed-utils library will have to be created - * for it (and possibly other utility classes as well) which then can be put in the web - * application lib folder. + * TODO: It might be useful to have this utility class available for usage by + * Portlet Applications too. Because this class <em>must</em> be included + * within a web application classpath, a separate jetspeed-tools or + * jetspeed-utils library will have to be created for it (and possibly other + * utility classes as well) which then can be put in the web application lib + * folder. * </p> + * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id: IsolatedLog4JLogger.java 531463 2007-04-23 13:35:58Z taylor $ */ public class IsolatedLog4JLogger implements Log { + private static Hierarchy hierarchy; + private static HashMap notIsolatedLoggers = new HashMap(); - - private Log4JLogger logger; // the wrapped Log4JLogger - + + private Log4JLogger logger; // the wrapped Log4JLogger + public static void setHierarchy(Hierarchy hierarchy) { synchronized (IsolatedLog4JLogger.class) { - if ( IsolatedLog4JLogger.hierarchy == null ) + if (IsolatedLog4JLogger.hierarchy == null) { IsolatedLog4JLogger.hierarchy = hierarchy; - if ( notIsolatedLoggers.size() > 0 ) + if (notIsolatedLoggers.size() > 0) { // Reroute existing IsolatedLog4JLogger instances // which were created before the new LoggerRepository. // Note: This situation should be prevented as much as - // possible by calling setHierarchy from - // a ServletContextListener or a Servlet its init method - // which has a load-on-startup value of 0 (zero). + // possible by calling setHierarchy from + // a ServletContextListener or a Servlet its init method + // which has a load-on-startup value of 0 (zero). Iterator iter = notIsolatedLoggers.entrySet().iterator(); while (iter.hasNext()) { - Map.Entry entry = (Map.Entry)iter.next(); - IsolatedLog4JLogger logger = (IsolatedLog4JLogger)entry.getKey(); - logger.setLogger(new Log4JLogger(hierarchy.getLogger((String)entry.getValue()))); + Map.Entry entry = (Map.Entry) iter.next(); + IsolatedLog4JLogger logger = (IsolatedLog4JLogger) entry + .getKey(); + logger.setLogger(new Log4JLogger(hierarchy + .getLogger((String) entry.getValue()))); } } notIsolatedLoggers = null; } } } - + public IsolatedLog4JLogger(String name) { synchronized (IsolatedLog4JLogger.class) { - if ( hierarchy == null ) + if (hierarchy == null) { // A LogFactory.getLog(name) is called before // our ContextClassLoader Hierarchy could be set. // Temporarily save this instance so it can be // rerouted one the Hierarchy is set. logger = new Log4JLogger(name); - notIsolatedLoggers.put(this,name); + notIsolatedLoggers.put(this, name); } else { - logger = new Log4JLogger(hierarchy.getLogger(name)); + logger = new Log4JLogger(hierarchy.getLogger(name)); } } } - + private void setLogger(Log4JLogger logger) { this.logger = logger; @@ -162,135 +177,154 @@ public void debug(Object arg0) { Log4JLogger logger = getLogger(); - if ( logger != null ) + if (logger != null) { logger.debug(arg0); } } + public void debug(Object arg0, Throwable arg1) { Log4JLogger logger = getLogger(); - if ( logger != null ) + if (logger != null) { - logger.debug(arg0,arg1); + logger.debug(arg0, arg1); } } + public boolean equals(Object obj) { Log4JLogger logger = getLogger(); return logger != null ? logger.equals(obj) : false; } + public void error(Object arg0) { Log4JLogger logger = getLogger(); - if ( logger != null ) + if (logger != null) { logger.error(arg0); } } + public void error(Object arg0, Throwable arg1) { Log4JLogger logger = getLogger(); - if ( logger != null ) + if (logger != null) { logger.error(arg0, arg1); } } + public void fatal(Object arg0) { Log4JLogger logger = getLogger(); - if ( logger != null ) + if (logger != null) { logger.fatal(arg0); } } + public void fatal(Object arg0, Throwable arg1) { Log4JLogger logger = getLogger(); - if ( logger != null ) + if (logger != null) { logger.fatal(arg0, arg1); } } + public void info(Object arg0) { Log4JLogger logger = getLogger(); - if ( logger != null ) + if (logger != null) { logger.info(arg0); } } + public void info(Object arg0, Throwable arg1) { Log4JLogger logger = getLogger(); - if ( logger != null ) + if (logger != null) { logger.info(arg0, arg1); } } + public boolean isDebugEnabled() { Log4JLogger logger = getLogger(); return logger != null ? logger.isDebugEnabled() : false; } + public boolean isErrorEnabled() { Log4JLogger logger = getLogger(); return logger != null ? logger.isErrorEnabled() : false; } + public boolean isFatalEnabled() { Log4JLogger logger = getLogger(); return logger != null ? logger.isFatalEnabled() : false; } + public boolean isInfoEnabled() { Log4JLogger logger = getLogger(); return logger != null ? logger.isInfoEnabled() : false; } + public boolean isTraceEnabled() { Log4JLogger logger = getLogger(); return logger != null ? logger.isTraceEnabled() : false; } + public boolean isWarnEnabled() { Log4JLogger logger = getLogger(); return logger != null ? logger.isWarnEnabled() : false; } + public String toString() { Log4JLogger logger = getLogger(); return logger != null ? logger.toString() : null; } + public void trace(Object arg0) { Log4JLogger logger = getLogger(); - if ( logger != null ) + if (logger != null) { logger.trace(arg0); } } + public void trace(Object arg0, Throwable arg1) { Log4JLogger logger = getLogger(); - if ( logger != null ) + if (logger != null) { logger.trace(arg0, arg1); } } + public void warn(Object arg0) { Log4JLogger logger = getLogger(); - if ( logger != null ) + if (logger != null) { logger.warn(arg0); } } + public void warn(Object arg0, Throwable arg1) { Log4JLogger logger = getLogger(); - if ( logger != null ) + if (logger != null) { logger.warn(arg0, arg1); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/webapp-logging/src/java/org/apache/jetspeed/webapp/logging/Log4JConfigurator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/webapp-logging/src/java/org/apache/jetspeed/webapp/logging/Log4JConfigurator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/webapp-logging/src/java/org/apache/jetspeed/webapp/logging/Log4JConfigurator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,65 +32,80 @@ public class Log4JConfigurator implements ServletContextListener { - /** The optional web.xml context parameter name for the Log4J Config File (location). - * The specified location is interpreted as begin (webapp) context relative. + + /** + * The optional web.xml context parameter name for the Log4J Config File + * (location). The specified location is interpreted as begin (webapp) + * context relative. */ public static final String LOG4J_CONFIG_FILE = "log4j.config.file"; /** The default value for the Log4J Config File (location) */ public static final String LOG4J_CONFIG_FILE_DEFAULT = "/WEB-INF/log4j.properties"; - /** The optional web.xml context parameter name for the Log4J Config webApplicationRoot (property) */ + /** + * The optional web.xml context parameter name for the Log4J Config + * webApplicationRoot (property) + */ public static final String LOG4J_CONFIG_WEB_APPLICATION_ROOT_KEY = "log4j.config.webApplicationRoot.key"; /** The default value for the Log4J Config webApplicationRoot (property) */ public static final String LOG4J_CONFIG_WEB_APPLICATION_ROOT_KEY_DEFAULT = "webApplicationRoot"; - + private Hierarchy isolatedHierarchy; - + private static Log log; public void contextInitialized(ServletContextEvent event) { - String log4JConfigFile = event.getServletContext().getInitParameter(LOG4J_CONFIG_FILE); - if ( log4JConfigFile == null || log4JConfigFile.length() == 0 ) + String log4JConfigFile = event.getServletContext().getInitParameter( + LOG4J_CONFIG_FILE); + if (log4JConfigFile == null || log4JConfigFile.length() == 0) { log4JConfigFile = LOG4J_CONFIG_FILE_DEFAULT; } String rootPath = event.getServletContext().getRealPath(""); - InputStream input = event.getServletContext().getResourceAsStream(log4JConfigFile); - if ( input != null ) + InputStream input = event.getServletContext().getResourceAsStream( + log4JConfigFile); + if (input != null) { try { Properties p = new Properties(); p.load(input); - String waRootKey = event.getServletContext().getInitParameter(LOG4J_CONFIG_WEB_APPLICATION_ROOT_KEY); - if ( waRootKey == null || waRootKey.length() == 0 ) + String waRootKey = event.getServletContext().getInitParameter( + LOG4J_CONFIG_WEB_APPLICATION_ROOT_KEY); + if (waRootKey == null || waRootKey.length() == 0) { waRootKey = LOG4J_CONFIG_WEB_APPLICATION_ROOT_KEY_DEFAULT; } - p.setProperty(waRootKey,rootPath); + p.setProperty(waRootKey, rootPath); isolatedHierarchy = new Hierarchy(new RootCategory(Level.INFO)); - new PropertyConfigurator().doConfigure(p,isolatedHierarchy); + new PropertyConfigurator().doConfigure(p, isolatedHierarchy); IsolatedLog4JLogger.setHierarchy(isolatedHierarchy); log = LogFactory.getLog(this.getClass()); log.info("IsolatedLog4JLogger configured"); } catch (IOException ioe) { - event.getServletContext().log("Failed to configure Log4J from "+event.getServletContext().getServletContextName(),ioe); + event.getServletContext().log( + "Failed to configure Log4J from " + + event.getServletContext() + .getServletContextName(), ioe); } } else { - event.getServletContext().log(event.getServletContext().getServletContextName()+" Log4JConfigurator: "+rootPath+log4JConfigFile+" not found."); + event.getServletContext().log( + event.getServletContext().getServletContextName() + + " Log4JConfigurator: " + rootPath + + log4JConfigFile + " not found."); } } public void contextDestroyed(ServletContextEvent event) { - if ( log != null ) + if (log != null) { log.info("Shutting down IsolatedLog4JLogger"); log = null; @@ -98,10 +113,11 @@ // flush Logger cache which might be kept in a shared context if // commons-logging isn't loaded through this ContextClassLoader LogFactory.release(Thread.currentThread().getContextClassLoader()); - // shutdown Log4J hierarchy (log4J keeps log files locked on Windows otherwise) + // shutdown Log4J hierarchy (log4J keeps log files locked on Windows + // otherwise) if (isolatedHierarchy != null) { - isolatedHierarchy.shutdown(); + isolatedHierarchy.shutdown(); } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/webapp-logging/src/java/org/apache/jetspeed/webapp/logging/velocity/CommonsLoggingLog4JLogSystem.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/webapp-logging/src/java/org/apache/jetspeed/webapp/logging/velocity/CommonsLoggingLog4JLogSystem.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/webapp-logging/src/java/org/apache/jetspeed/webapp/logging/velocity/CommonsLoggingLog4JLogSystem.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,74 +22,91 @@ import org.apache.velocity.runtime.log.LogSystem; /** - * Implementation of a LogSystem using Commons Logging to route Velocity message - * through a IsolatedLog4JLogger setup. + * Implementation of a LogSystem using Commons Logging to route Velocity message + * through a IsolatedLog4JLogger setup. * <p> * Configure the following in your velocity.properties: * <ul> - * <li>runtime.log.logsystem.class=org.apache.jetspeed.webapp.logging.velocity.CommonsLoggingLog4JLogSystem</li> - * <li>runtime.log.logsystem.log4j.category=<a Log4J Category name to capture Velocity message, default value: "velocity"></li> + * <li>runtime.log.logsystem.class=org.apache.jetspeed.webapp.logging.velocity.CommonsLoggingLog4JLogSystem</li> + * <li>runtime.log.logsystem.log4j.category=<a Log4J Category name to + * capture Velocity message, default value: "velocity"></li> * </ul> - * For further information about setting up and configuring velocity: - * <a href="http://jakarta.apache.org/velocity/docs/developer-guide.html">Velocity - Developer's Guide</a> + * For further information about setting up and configuring velocity: <a + * href="http://jakarta.apache.org/velocity/docs/developer-guide.html">Velocity - + * Developer's Guide</a> * </p> * <p> - * If you want to use a VelocityEngine instantiated by Spring using its org.springframework.ui.velocity.VelocityEngineFactoryBean - * then you can also configure the above properties inline in its defintion or point it to your velocity.properties file.<br/> - * But, beware of the following: the VelocityEngineFactoryBean by default overrides logging any configuration and hooks up their own - * CommonsLoggingLogSystem. Which works fine just as this one, but uses as (hard coded) logging category the VelocityEngine class name. - * So, if you do want to route your Velocity logging using your own category (or our default "velocity"), then you need to override the - * VelocityEngineFactoryBean default logging setup by setting its "overrideLogging" property to false. + * If you want to use a VelocityEngine instantiated by Spring using its + * org.springframework.ui.velocity.VelocityEngineFactoryBean then you can also + * configure the above properties inline in its defintion or point it to your + * velocity.properties file.<br/> But, beware of the following: the + * VelocityEngineFactoryBean by default overrides logging any configuration and + * hooks up their own CommonsLoggingLogSystem. Which works fine just as this + * one, but uses as (hard coded) logging category the VelocityEngine class name. + * So, if you do want to route your Velocity logging using your own category (or + * our default "velocity"), then you need to override the + * VelocityEngineFactoryBean default logging setup by setting its + * "overrideLogging" property to false. * </p> * <p> * </p> + * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id$ */ public class CommonsLoggingLog4JLogSystem implements LogSystem { + public static final String DEFAULT_CATEGORY = "velocity"; - + private Log logger; - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.velocity.runtime.log.LogSystem#init(org.apache.velocity.runtime.RuntimeServices) */ public void init(RuntimeServices rs) throws Exception { - String categoryname = (String) rs.getProperty("runtime.log.logsystem.log4j.category"); + String categoryname = (String) rs + .getProperty("runtime.log.logsystem.log4j.category"); - if ( categoryname == null ) + if (categoryname == null) { categoryname = DEFAULT_CATEGORY; } logger = LogFactory.getLog(categoryname); - logVelocityMessage( DEBUG_ID, "CommonsLoggingLog4JLogSystem using category '" + categoryname + "'"); + logVelocityMessage(DEBUG_ID, + "CommonsLoggingLog4JLogSystem using category '" + categoryname + + "'"); } - /* (non-Javadoc) - * @see org.apache.velocity.runtime.log.LogSystem#logVelocityMessage(int, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.apache.velocity.runtime.log.LogSystem#logVelocityMessage(int, + * java.lang.String) */ public void logVelocityMessage(int level, String message) { - switch (level) + switch (level) { - case LogSystem.WARN_ID: - logger.warn( message ); - break; - case LogSystem.INFO_ID: - logger.info(message); - break; - case LogSystem.DEBUG_ID: - logger.debug(message); - break; - case LogSystem.ERROR_ID: - logger.error(message); - break; - default: - logger.debug(message); - break; + case LogSystem.WARN_ID: + logger.warn(message); + break; + case LogSystem.INFO_ID: + logger.info(message); + break; + case LogSystem.DEBUG_ID: + logger.debug(message); + break; + case LogSystem.ERROR_ID: + logger.error(message); + break; + default: + logger.debug(message); + break; } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/CommonPortletServices.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/CommonPortletServices.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/CommonPortletServices.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,42 +17,74 @@ package org.apache.jetspeed; /** - * CPS: Common Portlet Services provided by Jetspeed available to portlet applications - * + * CPS: Common Portlet Services provided by Jetspeed available to portlet + * applications + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: CommonPortletServices.java 592266 2007-11-06 04:30:15Z taylor $ */ public interface CommonPortletServices { + public final static String CPS_SEARCH_COMPONENT = "cps:SearchComponent"; + public final static String CPS_REGISTRY_COMPONENT = "cps:PortletRegistryComponent"; + public final static String CPS_USER_MANAGER_COMPONENT = "cps:UserManager"; + public final static String CPS_PAGE_MANAGER_COMPONENT = "cps:PageManager"; + public final static String CPS_ROLE_MANAGER_COMPONENT = "cps:RoleManager"; + public final static String CPS_GROUP_MANAGER_COMPONENT = "cps:GroupManager"; + public final static String CPS_PROFILER_COMPONENT = "cps:Profiler"; - public final static String CPS_SSO_COMPONENT = "cps:SSO"; + + public final static String CPS_SSO_COMPONENT = "cps:SSO"; + public final static String CPS_APPLICATION_SERVER_MANAGER_COMPONENT = "cps:ApplicationServerManager"; - public final static String CPS_PORTLET_FACTORY_COMPONENT = "cps:PortletFactory"; - public final static String CPS_DEPLOYMENT_MANAGER_COMPONENT = "cps:DeploymentManager"; + + public final static String CPS_PORTLET_FACTORY_COMPONENT = "cps:PortletFactory"; + + public final static String CPS_DEPLOYMENT_MANAGER_COMPONENT = "cps:DeploymentManager"; + public final static String CPS_ENTITY_ACCESS_COMPONENT = "cps:EntityAccessor"; + public final static String CPS_WINDOW_ACCESS_COMPONENT = "cps:WindowAccessor"; + public final static String CPS_ID_GENERATOR_COMPONENT = "cps:IdGenerator"; + public final static String CPS_JETSPEED_POWERTOOL_FACTORY = "cps:Powertools"; + public final static String CPS_HEADER_RESOURCE_FACTORY = "cps:HeaderResource"; + public final static String CPS_PERMISSION_MANAGER = "cps:PermissionManager"; + public final static String CPS_PORTAL_STATISTICS = "cps:PortalStatistics"; + public final static String CPS_PORTAL_ADMINISTRATION = "cps:PortalAdministration"; + public final static String CPS_PREFERENCES_PROVIDER = "cps:PreferencesProvider"; + public final static String CPS_DECORATION_FACTORY = "cps:DecorationFactory"; + public final static String CPS_DESKTOP = "cps:Desktop"; + public final static String CPS_PASSWORD_ENCODER_COMPONENT = "cps:PasswordEncodingService"; + public final static String CPS_SECURITY_ACCESS_CONTROLLER = "cps:SecurityAccessController"; + public final static String CPS_PORTLET_TRACKING_MANAGER = "cps:PortletTrackingManager"; + public final static String CPS_PORTAL_CONFIGURATION = "cps:PortalConfiguration"; + public final static String CPS_IMPORTER_MANAGER = "cps:ImporterManager"; + public final static String CPS_DECORATOR_CACHE = "cps:decorationContentCache"; + public final static String CPS_PORTLET_CACHE = "cps:portletContentCache"; + public final static String CPS_AUDIT_ACTIVITY = "cps:AuditActivity"; + public final static String CPS_JETSPEED_SERIALIZER_FACTORY = "cps:JetspeedSerializerFactory"; } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/JetspeedActions.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/JetspeedActions.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/JetspeedActions.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,46 +26,68 @@ import javax.portlet.PortletMode; import javax.portlet.WindowState; - /** * Jestpeed Action Declarations - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id: JetspeedActions.java 593513 2007-11-09 12:48:34Z woonsan $ */ public class JetspeedActions { + public static final PortletMode ABOUT_MODE = new PortletMode("about"); + public static final PortletMode CONFIG_MODE = new PortletMode("config"); - public static final PortletMode EDIT_DEFAULTS_MODE = new PortletMode("edit_defaults"); - //public static final PortletMode PREVIEW_MODE = new PortletMode("preview"); + + public static final PortletMode EDIT_DEFAULTS_MODE = new PortletMode( + "edit_defaults"); + + // public static final PortletMode PREVIEW_MODE = new + // PortletMode("preview"); public static final PortletMode PRINT_MODE = new PortletMode("print"); + public static final WindowState SOLO_STATE = new WindowState("solo"); - - public static final int MASK_MINIMIZE = 0x01; + + public static final int MASK_MINIMIZE = 0x01; + public static final int MASK_MAXIMIZE = 0x02; + public static final int MASK_NORMAL = 0x04; + public static final int MASK_VIEW = 0x08; + public static final int MASK_EDIT = 0x10; + public static final int MASK_HELP = 0x20; - + public static final String VIEW = PortletMode.VIEW.toString(); + public static final String EDIT = PortletMode.EDIT.toString(); + public static final String HELP = PortletMode.HELP.toString(); + public static final String ABOUT = ABOUT_MODE.toString(); + public static final String CONFIG = CONFIG_MODE.toString(); + public static final String EDIT_DEFAULTS = EDIT_DEFAULTS_MODE.toString(); - //public static final String PREVIEW = PREVIEW_MODE.toString(); + + // public static final String PREVIEW = PREVIEW_MODE.toString(); public static final String PRINT = PRINT_MODE.toString(); + public static final String NORMAL = WindowState.NORMAL.toString(); + public static final String MINIMIZE = WindowState.MINIMIZED.toString(); + public static final String MAXIMIZE = WindowState.MAXIMIZED.toString(); + public static final String SOLO = SOLO_STATE.toString(); - + private static final List standardPortletModes; + private static final List standardWindowStates; - + static { ArrayList list = new ArrayList(3); @@ -80,82 +102,88 @@ standardWindowStates = Collections.unmodifiableList(list); } - private static JetspeedActions instance = new JetspeedActions(new String[]{}, new String[]{}); - + private static JetspeedActions instance = new JetspeedActions(new String[] + {}, new String[] + {}); + private final List extendedPortletModes; + private final List extendedWindowStates; + private final Map actionsMap; + private final Object[] actions; - + public static List getStandardPortletModes() { return standardPortletModes; } - + public static List getStandardWindowStates() { return standardWindowStates; } - - public JetspeedActions(String[] supportedPortletModes, String[] supportedWindowStates) + + public JetspeedActions(String[] supportedPortletModes, + String[] supportedWindowStates) { int index = 0; - + ArrayList actionsList = new ArrayList(); - + actionsMap = new HashMap(); - - actionsMap.put(WindowState.MINIMIZED.toString(),new Integer(index++)); + + actionsMap.put(WindowState.MINIMIZED.toString(), new Integer(index++)); actionsList.add(WindowState.MINIMIZED); - actionsMap.put(WindowState.MAXIMIZED.toString(),new Integer(index++)); + actionsMap.put(WindowState.MAXIMIZED.toString(), new Integer(index++)); actionsList.add(WindowState.MAXIMIZED); - actionsMap.put(WindowState.NORMAL.toString(),new Integer(index++)); + actionsMap.put(WindowState.NORMAL.toString(), new Integer(index++)); actionsList.add(WindowState.NORMAL); actionsMap.put(PortletMode.VIEW.toString(), new Integer(index++)); actionsList.add(PortletMode.VIEW); - actionsMap.put(PortletMode.EDIT.toString(),new Integer(index++)); + actionsMap.put(PortletMode.EDIT.toString(), new Integer(index++)); actionsList.add(PortletMode.EDIT); - actionsMap.put(PortletMode.HELP.toString(),new Integer(index++)); + actionsMap.put(PortletMode.HELP.toString(), new Integer(index++)); actionsList.add(PortletMode.HELP); - + ArrayList list = new ArrayList(); - - for (int i=0; index < 32 && i<supportedWindowStates.length; i++) + + for (int i = 0; index < 32 && i < supportedWindowStates.length; i++) { WindowState state = new WindowState(supportedWindowStates[i]); - if ( !actionsMap.containsKey(state.toString()) ) + if (!actionsMap.containsKey(state.toString())) { actionsMap.put(state.toString(), new Integer(index++)); actionsList.add(state); list.add(state); } - else if (!standardWindowStates.contains(state)) - { - throw new IllegalArgumentException("WindowState "+state+" already defined as extended PortletMode or WindowState"); - } + else if (!standardWindowStates.contains(state)) { throw new IllegalArgumentException( + "WindowState " + + state + + " already defined as extended PortletMode or WindowState"); } } extendedWindowStates = Collections.unmodifiableList(list); - + list = new ArrayList(); - - for (int i=0; index < 32 && i<supportedPortletModes.length; i++) + + for (int i = 0; index < 32 && i < supportedPortletModes.length; i++) { PortletMode mode = new PortletMode(supportedPortletModes[i]); - if ( !actionsMap.containsKey(mode.toString()) ) + if (!actionsMap.containsKey(mode.toString())) { actionsMap.put(mode.toString(), new Integer(index++)); actionsList.add(mode); list.add(mode); } - else if (!standardPortletModes.contains(mode)) - { - throw new IllegalArgumentException("PortletMode "+mode+" already defined as extended PortletMode or WindowState"); - } + else if (!standardPortletModes.contains(mode)) { throw new IllegalArgumentException( + "PortletMode " + + mode + + " already defined as extended PortletMode or WindowState"); } } extendedPortletModes = Collections.unmodifiableList(list); - + actions = actionsList.toArray(); - + instance = this; } @@ -163,39 +191,38 @@ { return instance.extendedPortletModes; } - + public static List getExtendedWindowStates() { return instance.extendedWindowStates; } - + public static int getContainerActionMask(String action) { - Integer index = (Integer)instance.actionsMap.get(action); - if ( index == null ) - { - throw new IllegalArgumentException("Unknown action: "+action); - } - return 1<<index.intValue(); + Integer index = (Integer) instance.actionsMap.get(action); + if (index == null) { throw new IllegalArgumentException( + "Unknown action: " + action); } + return 1 << index.intValue(); } - + public static String getContainerAction(int index) { JetspeedActions ja = JetspeedActions.instance; - return index > -1 && index < ja.actions.length ? ja.actions[index].toString() : null; + return index > -1 && index < ja.actions.length ? ja.actions[index] + .toString() : null; } - + public static String getContainerActions(int mask) { JetspeedActions ja = JetspeedActions.instance; StringBuffer buffer = new StringBuffer(); boolean append = false; - - for ( int i = 0, j=1<<i; i < ja.actions.length; i++, j=1<<i ) + + for (int i = 0, j = 1 << i; i < ja.actions.length; i++, j = 1 << i) { - if ( (mask & j) == j ) + if ((mask & j) == j) { - if ( append ) + if (append) buffer.append(", "); else append = true; @@ -204,27 +231,28 @@ } return buffer.toString(); } - + public static int getContainerActionsMask(String actions) { int mask = 0; - - if ( actions != null ) + + if (actions != null) { JetspeedActions ja = JetspeedActions.instance; - + StringTokenizer tokenizer = new StringTokenizer(actions, ",\t "); Integer index; while (tokenizer.hasMoreTokens()) { String action = tokenizer.nextToken(); - index = (Integer)ja.actionsMap.get(action); - if ( index == null ) - throw new IllegalArgumentException("Unknown action: " + action); + index = (Integer) ja.actionsMap.get(action); + if (index == null) + throw new IllegalArgumentException("Unknown action: " + + action); mask |= (1 << index.intValue()); } - } + } return mask; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/PortalContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/PortalContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/PortalContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,37 +24,44 @@ /** * Portal Context associated with running thread of the engine - * + * * @author <a href="mailto:david ¡÷ bluesunrise.com">David Sean Taylor</a> * @version $Id: PortalContext.java 185962 2004-03-08 01:03:33Z jford $ */ public interface PortalContext extends javax.portlet.PortalContext { + public Engine getEngine(); public PortalConfiguration getConfiguration(); + public void setConfiguration(PortalConfiguration configuration); public String getConfigurationProperty(String key); + public String getConfigurationProperty(String key, String defaultValue); public void setAttribute(String name, Object value); + public Object getAttribute(String name); /** * Returns the application root for this Jetspeed engine context. - * - * @return a <code>String</code> containing the application root path for this Jetspeed context. + * + * @return a <code>String</code> containing the application root path for + * this Jetspeed context. */ public String getApplicationRoot(); /** * Sets the application root path for this Jetspeed engine context. - * - * @param applicationRoot - the applicationRoot path on the file system. + * + * @param applicationRoot - + * the applicationRoot path on the file system. */ public void setApplicationRoot(String applicationRoot); - + public boolean isPortletModeAllowed(PortletMode mode); + public boolean isWindowStateAllowed(WindowState state); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/PortalReservedParameters.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/PortalReservedParameters.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/PortalReservedParameters.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,58 +17,101 @@ package org.apache.jetspeed; /** - * PortalReservedParameters. The constants here define HTTP request parameters + * PortalReservedParameters. The constants here define HTTP request parameters * reserved for use by the Jetspeed Portal. - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> - * @version $Id: PortalReservedParameters.java 569464 2007-08-24 17:43:28Z taylor $ + * @version $Id: PortalReservedParameters.java 569464 2007-08-24 17:43:28Z + * taylor $ */ public interface PortalReservedParameters { + public final static String PORTLET = "portlet"; - public final static String PORTLET_ENTITY = "entity"; + + public final static String PORTLET_ENTITY = "entity"; + public final static String PAGE = "page"; + public final static String PIPELINE = "pipeline"; + public final static String DEFAULT_PIPELINE = "jetspeed-pipeline"; + public final static String PORTLET_PIPELINE = "portlet-pipeline"; + public final static String ACTION_PIPELINE = "action-pipeline"; + public final static String LOGIN_PIPELINE = "login-pipeline"; + public final static String CONFIG_PIPELINE = "config-pipeline"; + public final static String DESKTOP_CONFIG_PIPELINE = "dtconfig-pipeline"; + public final static String CONFIG_PIPELINE_NAME = "ConfigurePipeline"; + public final static String DESKTOP_CONFIG_PIPELINE_NAME = "DesktopConfigurePipeline"; + public final static String JETSPEED_CONFIG_PIPELINE_NAME = "JetspeedPipeline"; - + // Session and Request attribute keys public static final String PAGE_ATTRIBUTE = "org.apache.jetspeed.Page"; + public static final String PAGE_EDIT_ACCESS_ATTRIBUTE = "org.apache.jetspeed.decoration.PageEditAccess"; + public static final String SESSION_KEY_SUBJECT = "org.apache.jetspeed.security.subject"; + public static final String REQUEST_CONTEXT_ATTRIBUTE = "org.apache.jetspeed.request.RequestContext"; + public static final String REQUEST_CONTEXT_OBJECTS = "org.apache.jetspeed.request.RequestContextObjects"; + public static final String FRAGMENT_ATTRIBUTE = "org.apache.jetspeed.Fragment"; - public static final String MAXIMIZED_FRAGMENT_ATTRIBUTE = "org.apache.jetspeed.maximized.Fragment"; + + public static final String MAXIMIZED_FRAGMENT_ATTRIBUTE = "org.apache.jetspeed.maximized.Fragment"; + public static final String MAXIMIZED_LAYOUT_ATTRIBUTE = "org.apache.jetspeed.maximized.Layout"; + public static final String JETSPEED_POWER_TOOL_REQ_ATTRIBUTE = "org.apache.jetspeed.velocity.JetspeedPowerTool"; + public static final String PREFERED_LANGUAGE_ATTRIBUTE = "org.apache.jetspeed.prefered.language"; + public static final String PREFERED_LOCALE_ATTRIBUTE = "org.apache.jetspeed.prefered.locale"; + public static final String PREFERED_CHARACTERENCODING_ATTRIBUTE = "org.apache.jetspeed.prefered.characterencoding"; + public static final String CONTENT_DISPATCHER_ATTRIBUTE = "org.apache.jetspeed.ContentDispatcher"; + public static final String OVERRIDE_PORTLET_TITLE_ATTR = "org.apache.jetspeed.portlet.title"; + public static final String HEADER_RESOURCE_ATTRIBUTE = "org.apache.jetspeed.headerresource"; + public static final String HEADER_CONFIGURATION_ATTRIBUTE = "org.apache.jetspeed.headerconfiguration"; + public static final String HEADER_NAMED_RESOURCE_ATTRIBUTE = "org.apache.jetspeed.headernamedresource"; + public static final String HEADER_NAMED_RESOURCE_ADDED_FRAGMENTS_ATTRIBUTE = "org.apache.jetspeed.headernamedresourceaddedfragments"; + public static final String HEADER_NAMED_RESOURCE_REGISTRY_ATTRIBUTE = "org.apache.jetspeed.headernamedresourceregistry"; + public static final String PATH_ATTRIBUTE = "org.apache.jetspeed.Path"; + public static final String PARAMETER_ALREADY_DECODED_ATTRIBUTE = "org.apache.jetspeed.parameterAlreadyDecoded"; + public static final String RESOVLER_CACHE_ATTR = "org.apache.jetspeed.resovler.cache"; + public static final String PORTLET_DEFINITION_ATTRIBUTE = "org.apache.jetspeed.portlet.definition"; + public static final String PORTLET_WINDOW_ATTRIBUTE = "org.apache.jetspeed.portlet.window"; + public static final String PAGE_THEME_ATTRIBUTE = "org.apache.jetspeed.theme"; + public static final String PAGE_LAYOUT_VIEW = "org.apache.jetspeed.layout.view"; + public static final String PAGE_LAYOUT_MAX = "org.apache.jetspeed.layout.max"; + public static final String PAGE_LAYOUT_HELP = "org.apache.jetspeed.layout.help"; + public static final String PAGE_LAYOUT_EDIT = "org.apache.jetspeed.layout.edit"; + public static final String PAGE_LAYOUT_SOLO = "org.apache.jetspeed.layout.solo"; /** @@ -76,77 +119,89 @@ * psml. Sample values are "Simple", "tigris", "jetspeed" */ public static final String PAGE_THEME_OVERRIDE_ATTRIBUTE = "org.apache.jetspeed.theme.override"; + public static final String PORTAL_FILTER_ATTRIBUTE = "org.apache.jetspeed.login.filter.PortalFilter"; - + // // Settings for Metadata on jetspeed-portlet.xml // /** * Actions can be marked as non-standard if they don't participate in - * JSR-168 standard action behavior. By default, actions are supposed - * to clear the cache of all other portlets on the page. - * By setting this parameter, we can ignore the standard behavior - * and not clear the cache on actions. This is useful for portlets - * which never participate with other portlets. + * JSR-168 standard action behavior. By default, actions are supposed to + * clear the cache of all other portlets on the page. By setting this + * parameter, we can ignore the standard behavior and not clear the cache on + * actions. This is useful for portlets which never participate with other + * portlets. */ public static final String PORTLET_EXTENDED_DESCRIPTOR_NON_STANDARD_ACTION = "nonStandardAction"; + /** - * A portlet can have a specific setting for the timeout duration that the portal will wait - * before it gives up on rendering the portlet. This value overrides the system setting. - * The timeout value is in milliseconds + * A portlet can have a specific setting for the timeout duration that the + * portal will wait before it gives up on rendering the portlet. This value + * overrides the system setting. The timeout value is in milliseconds */ public static final String PORTLET_EXTENDED_DESCRIPTOR_RENDER_TIMEOUT = "timeout"; - + /** - * Until version 2.1, Jetspeed merged portal request parameters with portlet specific - * parameters, effectively allowing "shared" parameters. - * <p> - * This is not compliant with the JSR-168 PLT.11, so by default this is now disabled - * through global settings in jetspeed.properties: - * <pre> + * Until version 2.1, Jetspeed merged portal request parameters with portlet + * specific parameters, effectively allowing "shared" parameters. + * <p> + * This is not compliant with the JSR-168 PLT.11, so by default this is now + * disabled through global settings in jetspeed.properties: + * + * <pre> * merge.portal.parameters.with.portlet.parameters=false * merge.portal.parameters.before.portlet.parameters=false - * </pre> - * <p> - * To support legacy portlets still relying on the "old" behavior these default global - * settings can be overridden by defining these values in the portlet Metadata too. - * </p> - * <p> - * Setting merge.portal.parameters.with.portlet.parameters=true will "restore" the old behavior and - * merge the portal parameters with the portlet parameters. - * </p> + * </pre> + * + * <p> + * To support legacy portlets still relying on the "old" behavior these + * default global settings can be overridden by defining these values in the + * portlet Metadata too. + * </p> + * <p> + * Setting merge.portal.parameters.with.portlet.parameters=true will + * "restore" the old behavior and merge the portal parameters with the + * portlet parameters. + * </p> */ public static final String PORTLET_EXTENDED_DESCRIPTOR_MERGE_PORTAL_PARAMETERS_WITH_PORTLET_PARAMETERS = "merge.portal.parameters.with.portlet.parameters"; /** - * Until version 2.1, Jetspeed merged portal request parameters with portlet specific - * parameters, effectively allowing "shared" parameters. - * <p> - * This is not compliant with the JSR-168 PLT.11, so by default this is now disabled - * through global settings in jetspeed.properties: - * <pre> + * Until version 2.1, Jetspeed merged portal request parameters with portlet + * specific parameters, effectively allowing "shared" parameters. + * <p> + * This is not compliant with the JSR-168 PLT.11, so by default this is now + * disabled through global settings in jetspeed.properties: + * + * <pre> * merge.portal.parameters.with.portlet.parameters=false * merge.portal.parameters.before.portlet.parameters=false - * </pre> - * <p> - * To support legacy portlets still relying on the "old" behavior these default global - * settings can be overridden by defining these values in the portlet Metadata too. - * </p> - * <p> - * In the situation of portal and portlet parameters with the same name, by default - * the portlet parameters will be provided first in the values array, but this - * can be overridden by setting merge.portal.parameters.before.portlet.parameters=true. - * </p> + * </pre> + * + * <p> + * To support legacy portlets still relying on the "old" behavior these + * default global settings can be overridden by defining these values in the + * portlet Metadata too. + * </p> + * <p> + * In the situation of portal and portlet parameters with the same name, by + * default the portlet parameters will be provided first in the values + * array, but this can be overridden by setting + * merge.portal.parameters.before.portlet.parameters=true. + * </p> */ - public static final String PORTLET_EXTENDED_DESCRIPTOR_MERGE_PORTAL_PARAMETERS_BEFORE_PORTLET_PARAMETERS = "merge.portal.parameters.before.portlet.parameters"; - - /** - * Preliminary Portlet API 2.0 ResourceURL support. - * By setting the RenderURL parameter PORTLET_RESOURCE_URL_REQUEST_PARAMETER (with whatever value) the Jetspeed encoded PortletURL - * will be marked as a ResourceURL (the parameter itself will not be stored). - * By invoking such a Render/ResourceURL, NavigationalState.getPortletWindowOfResource() will be set, and with an custom Valve - * (example implementation o.a.j.resource.ResourceValveImpl) this PortletWindow can be invoked directly, - * similar as an ActionURL but as a direct Portlet Render request. - */ - public static final String PORTLET_RESOURCE_URL_REQUEST_PARAMETER = "org.apache.jetspeed.portlet.resource.url"; + public static final String PORTLET_EXTENDED_DESCRIPTOR_MERGE_PORTAL_PARAMETERS_BEFORE_PORTLET_PARAMETERS = "merge.portal.parameters.before.portlet.parameters"; + + /** + * Preliminary Portlet API 2.0 ResourceURL support. By setting the RenderURL + * parameter PORTLET_RESOURCE_URL_REQUEST_PARAMETER (with whatever value) + * the Jetspeed encoded PortletURL will be marked as a ResourceURL (the + * parameter itself will not be stored). By invoking such a + * Render/ResourceURL, NavigationalState.getPortletWindowOfResource() will + * be set, and with an custom Valve (example implementation + * o.a.j.resource.ResourceValveImpl) this PortletWindow can be invoked + * directly, similar as an ActionURL but as a direct Portlet Render request. + */ + public static final String PORTLET_RESOURCE_URL_REQUEST_PARAMETER = "org.apache.jetspeed.portlet.resource.url"; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/AdministrationEmailException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/AdministrationEmailException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/AdministrationEmailException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,12 +27,14 @@ */ public class AdministrationEmailException extends JetspeedException { + public AdministrationEmailException() { super(); } - public AdministrationEmailException(KeyedMessage keyedMessage, Throwable nested) + public AdministrationEmailException(KeyedMessage keyedMessage, + Throwable nested) { super(keyedMessage, nested); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalAdministration.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalAdministration.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalAdministration.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,57 +22,55 @@ import javax.portlet.PortletConfig; import javax.portlet.PortletRequest; import javax.portlet.PortletResponse; + import org.apache.jetspeed.security.User; /** * PortalAdministration * - * Aggregate portal administration functions: - * - Emails - * - Registration - * - Password Generation + * Aggregate portal administration functions: - Emails - Registration - Password + * Generation * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ public interface PortalAdministration -{ +{ + /** - * Registers and creates a new user, assigning userInfo, roles, groups, + * Registers and creates a new user, assigning userInfo, roles, groups, * profiling rules and a folder template. If any values are null, defaults * are used from the system wide configuration. * - * @param userName Unique user principal identifier - * @param password Password for this user - * @param roles A list of roles to assign to this user - * @param groups A list of groups to assign to this user - * @param userInfo Portlet API User Information Attributes name value pairs (PLT.D) - * @param rules A map of name value pairs of profiling rules. - * Well known rules names are 'page' and 'menu' - * @param folderTemplate The full PSML path name of a folder to be deep - * copied as the new user's set of folders, pages, links - * @param subsite The subsite folder to place the new user in - * @since 2.1.2 + * @param userName + * Unique user principal identifier + * @param password + * Password for this user + * @param roles + * A list of roles to assign to this user + * @param groups + * A list of groups to assign to this user + * @param userInfo + * Portlet API User Information Attributes name value pairs + * (PLT.D) + * @param rules + * A map of name value pairs of profiling rules. Well known rules + * names are 'page' and 'menu' + * @param folderTemplate + * The full PSML path name of a folder to be deep copied as the + * new user's set of folders, pages, links + * @param subsite + * The subsite folder to place the new user in + * @since 2.1.2 */ - void registerUser(String userName, - String password, - List roles, - List groups, - Map userInfo, - Map rules, - String template, - String subsiteFolder) - throws RegistrationException; + void registerUser(String userName, String password, List roles, + List groups, Map userInfo, Map rules, String template, + String subsiteFolder) throws RegistrationException; - void registerUser(String userName, - String password, - List roles, - List groups, - Map userInfo, - Map rules, - String template) - throws RegistrationException; - + void registerUser(String userName, String password, List roles, + List groups, Map userInfo, Map rules, String template) + throws RegistrationException; + /** * Register a new user using all default values * @@ -80,88 +78,101 @@ * @param password */ void registerUser(String userName, String password) - throws RegistrationException; - + throws RegistrationException; + /** * Generate a unique password * * @return unique password */ String generatePassword(); - + /** * Helper to send an email to a recipient * - * @param recipient the email address of the recipient - * @param localizedSubject the subject of the email as a localized string - * @param message the email message content + * @param recipient + * the email address of the recipient + * @param localizedSubject + * the subject of the email as a localized string + * @param message + * the email message content * @parm userAttributes map of user attributes * @throws AdministrationEmailException */ - public void sendEmail(PortletConfig portletConfig, - String emailAddress, - String localizedSubject, - String templatePath, - Map userAttributes) - throws AdministrationEmailException; - + public void sendEmail(PortletConfig portletConfig, String emailAddress, + String localizedSubject, String templatePath, Map userAttributes) + throws AdministrationEmailException; + /** - * Helper to send an email to a recipient without the portal default sender, and without mail merge + * Helper to send an email to a recipient without the portal default sender, + * and without mail merge * - * @param from the email address of the sender - * @param subject the subject of the email - * @param to the recipient email address - * @param text the message text + * @param from + * the email address of the sender + * @param subject + * the subject of the email + * @param to + * the recipient email address + * @param text + * the message text * @throws AdministrationEmailException */ - public void sendEmail(String from, String subject, String to, String text) throws AdministrationEmailException; - + public void sendEmail(String from, String subject, String to, String text) + throws AdministrationEmailException; + /** * Lookup a user given an email address * - * @param email Given email address + * @param email + * Given email address * @return a Jetspeed <code>User</code>, or throw exception if not found * @throws AdministrationEmailException */ public User lookupUserFromEmail(String email) - throws AdministrationEmailException; - + throws AdministrationEmailException; + /** - * Provide a common way to get portal URLs - * Necessary for generating return URLs for features such as - * forgotten password. The URL generated will be a combination - * of the Jetspeed base URL plus the path parameter appended - * Example: - * base URL = http://www.apache.org/jetspeed/portal - * path = /system/forgotten-password.psml - * Returns: - * http://www.apache.org/jetspeed/portal/system/forgotten-password.psml - * - * @param request The portlet request. - * @param response The portlet response, used to encode the path - * @param path The relative path to a portal resource + * Provide a common way to get portal URLs Necessary for generating return + * URLs for features such as forgotten password. The URL generated will be a + * combination of the Jetspeed base URL plus the path parameter appended + * Example: base URL = http://www.apache.org/jetspeed/portal path = + * /system/forgotten-password.psml Returns: + * http://www.apache.org/jetspeed/portal/system/forgotten-password.psml + * + * @param request + * The portlet request. + * @param response + * The portlet response, used to encode the path + * @param path + * The relative path to a portal resource * @return the base Jetspeed portal URL plus the appended path parameter */ - String getPortalURL(PortletRequest request, PortletResponse response, String path); - - + String getPortalURL(PortletRequest request, PortletResponse response, + String path); + /** - * @param guid The ID which is passed throughte URL to the user + * @param guid + * The ID which is passed throughte URL to the user * @return */ public Map getNewLoginInfo(String guid); + /** - * @param guid the ID which is passed through the URL to the user.. - * @param info a Map, info from which will be used to reset the password - * the password in this case is NOT encrypted, but this should probably - * change if this information is stored on disk... ie a database + * @param guid + * the ID which is passed through the URL to the user.. + * @param info + * a Map, info from which will be used to reset the password the + * password in this case is NOT encrypted, but this should + * probably change if this information is stored on disk... ie a + * database */ public void putNewLoginInfo(String guid, Map info); - + /** - * @param guid the ID which will be removed from the storage when the info is no longer valid + * @param guid + * the ID which will be removed from the storage when the info is + * no longer valid */ public void removeNewLoginInfo(String guid); - + } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalAuthenticationConfiguration.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalAuthenticationConfiguration.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalAuthenticationConfiguration.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,7 +16,6 @@ */ package org.apache.jetspeed.administration; - /** * PortalAdministration * @@ -26,38 +25,41 @@ * @version $Id: $ */ public interface PortalAuthenticationConfiguration -{ +{ + /** * Is the session hard limit expiration feature enabled + * * @return */ public boolean isMaxSessionHardLimitEnabled(); - + /** * hard session timeout limit in seconds, regardless of (in)activity * * @return */ public int getMaxSessionHardLimit(); - - + /** * Get the session hard limit in milliseconds * * @return session hard limit in milliseconds */ public long getMsMaxSessionHardLimit(); - + /** - * redirect location for hard session expiration, must be used with Max Session Hard Limit turned on + * redirect location for hard session expiration, must be used with Max + * Session Hard Limit turned on * * @return */ public String getTimeoutRedirectLocation(); /** - * redirect location for hard session expiration, must be used with Max Session Hard Limit turned on - * + * redirect location for hard session expiration, must be used with Max + * Session Hard Limit turned on + * * @param timeoutRedirectLocation */ public void setTimeoutRedirectLocation(String timeoutRedirectLocation); @@ -68,6 +70,5 @@ * @return */ public boolean isCreateNewSessionOnLogin(); - + } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalConfiguration.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalConfiguration.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalConfiguration.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,10 +22,10 @@ /** * Portal Configuration * - * Retrieve basic data types from the jetspeed.properties configuration - * This is a subset of Commons Configuration functionality - * Not the best solution wrappering commons configuration, but it does continue - * with the requirements of interface-driven development and zero dependencies in API + * Retrieve basic data types from the jetspeed.properties configuration This is + * a subset of Commons Configuration functionality Not the best solution + * wrappering commons configuration, but it does continue with the requirements + * of interface-driven development and zero dependencies in API * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @since 2.1.2 @@ -33,20 +33,36 @@ */ public interface PortalConfiguration { + boolean getBoolean(String key); - boolean getBoolean(String key, boolean defaultValue); + + boolean getBoolean(String key, boolean defaultValue); + String getString(String key); - String getString(String key, String defaultValue); + + String getString(String key, String defaultValue); + double getDouble(String key); - double getDouble(String key, double defaultValue); + + double getDouble(String key, double defaultValue); + float getFloat(String key); - float getFloat(String key, float defaultValue); + + float getFloat(String key, float defaultValue); + int getInt(String key); - int getInt(String key, int defaultValue); - List getList(String key); + + int getInt(String key, int defaultValue); + + List getList(String key); + long getLong(String key); - long getLong(String key, long defaultValue); + + long getLong(String key, long defaultValue); + String[] getStringArray(String key); + Iterator getKeys(); + void setString(String key, String value); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalConfigurationConstants.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalConfigurationConstants.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/PortalConfigurationConstants.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,60 +17,82 @@ package org.apache.jetspeed.administration; /** - * PortalConfiguration portal configuration contants - * TODO: integrate Configuration with JMX + * PortalConfiguration portal configuration contants TODO: integrate + * Configuration with JMX * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ public interface PortalConfigurationConstants { + /** EMAIL */ /** email of the system administrator */ static final String EMAIL_ADMIN = "email.admin"; + /** email of the system manager */ static final String EMAIL_MANAGER = "email.manager"; + /** email sender */ static final String EMAIL_SENDER = "email.sender"; - /** email user info attribute **/ + + /** email user info attribute * */ static final String EMAIL_USERINFO_ATTRIBUTE = "email.userinfo.attribute"; - + /** LAYOUT */ /** the default page layout if none is specified */ static final String LAYOUT_PAGE_DEFAULT = "layout.page.default"; - + /** Decorators */ /** default page decorator if none specified */ static final String DECORATOR_PAGE_DEFAULT = "decorator.page.default"; - /** default portlet decorator if none specified */ + + /** default portlet decorator if none specified */ static final String DECORATOR_PORTLET_DEFAULT = "decorator.portlet.default"; - - /** PSML **/ + + /** PSML * */ /** default psml page */ static final String PSML_PAGE_DEFAULT = "psml.page.default"; - + /** PSML Templates */ /** PSML Folder Template to copy during new user creation and registration */ static final String PSML_TEMPLATE_FOLDER = "psml.template.folder"; - - /** PROFILER **/ + + /** PROFILER * */ static final String PROFILER_RULE_NAMES_DEFAULT = "profiler.rule.names.default"; + static final String PROFILER_RULE_VALUES_DEFAULT = "profiler.rule.values.default"; - - /** Registration */ - /** Registration default Roles assigned during registration or new user creation **/ + + /** Registration */ + /** + * Registration default Roles assigned during registration or new user + * creation * + */ static final String REGISTRATION_ROLES_DEFAULT = "registration.roles.default"; - /** Registration default groups assigned during registration or new user creation **/ + + /** + * Registration default groups assigned during registration or new user + * creation * + */ static final String REGISTRATION_GROUPS_DEFAULT = "registration.groups.default"; - /** Registration default profiling rules assigned during registration or new user creation **/ + + /** + * Registration default profiling rules assigned during registration or new + * user creation * + */ static final String REGISTRATION_RULES_DEFAULT = "registration.rules.default"; - + /** Users */ static final String USERS_DEFAULT_ADMIN = "default.admin.user"; - static final String USERS_DEFAULT_GUEST = "default.user.principal"; - static final String ROLES_DEFAULT_ADMIN = "default.admin.role"; + + static final String USERS_DEFAULT_GUEST = "default.user.principal"; + + static final String ROLES_DEFAULT_ADMIN = "default.admin.role"; + static final String ROLES_DEFAULT_MANAGER = "default.manager.role"; + static final String ROLES_DEFAULT_USER = "default.user.role"; + static final String ROLES_DEFAULT_GUEST = "default.guest.role"; - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/RegistrationException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/RegistrationException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/administration/RegistrationException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,6 +27,7 @@ */ public class RegistrationException extends JetspeedException { + public RegistrationException() { super(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/Aggregator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/Aggregator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/Aggregator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,18 +23,19 @@ /** * Basic aggregation interface - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: Aggregator.java 516448 2007-03-09 16:25:47Z ate $ */ -public interface Aggregator +public interface Aggregator { + /** * Builds the portlet set defined in the context into a portlet tree. - * + * * @return Unique Portlet Entity ID */ - public void build(RequestContext context) - throws JetspeedException, IOException; + public void build(RequestContext context) throws JetspeedException, + IOException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/ContentDispatcher.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/ContentDispatcher.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/ContentDispatcher.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,23 +19,26 @@ import org.apache.jetspeed.om.page.Fragment; /** - * <p>The ContentDispatcher allows customer classes to retrieved - * rendered content for a specific fragment</p> - * + * <p> + * The ContentDispatcher allows customer classes to retrieved rendered content + * for a specific fragment + * </p> + * * @author <a href="mailto:raphael ¡÷ apache.org">Rapha?l Luta</a> * @version $Id: ContentDispatcher.java 516448 2007-03-09 16:25:47Z ate $ */ public interface ContentDispatcher { + /** * * <p> * getPortletContent * </p> - * + * * @param fragment * @return */ PortletContent getPortletContent(Fragment fragment); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/ContentDispatcherCtrl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/ContentDispatcherCtrl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/ContentDispatcherCtrl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,32 +23,38 @@ import org.apache.pluto.om.window.PortletWindow; /** - * <p>The ContentDispatcher control interface used for updating the content of - * a ContentDispatcher</p> - * + * <p> + * The ContentDispatcher control interface used for updating the content of a + * ContentDispatcher + * </p> + * * @author <a href="mailto:raphael ¡÷ apache.org">Rapha?l Luta</a> * @version $Id: ContentDispatcherCtrl.java 516448 2007-03-09 16:25:47Z ate $ */ public interface ContentDispatcherCtrl extends ContentDispatcher { + /** - * Return the HttpServletResponse to use for a given PortletWindow - * in order to be able to capture parallel rendering portlets + * Return the HttpServletResponse to use for a given PortletWindow in order + * to be able to capture parallel rendering portlets */ - public HttpServletResponse getResponseForWindow(PortletWindow window, RequestContext request); - + public HttpServletResponse getResponseForWindow(PortletWindow window, + RequestContext request); + /** * * <p> * getResponseForFragment * </p> * <p> - * Return the HttpServletResponse to use for a given Fragment - * in order to be able to capture parallel rendering portlets + * Return the HttpServletResponse to use for a given Fragment in order to be + * able to capture parallel rendering portlets * </p> + * * @param fragment * @param request * @return */ - public HttpServletResponse getResponseForFragment( Fragment fragment, RequestContext request ); + public HttpServletResponse getResponseForFragment(Fragment fragment, + RequestContext request); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/ContentServerAdapter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/ContentServerAdapter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/ContentServerAdapter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,37 +21,43 @@ /** * <p> - * The Content Server Adapter encapsulates all aggregated related - * activities related to aggregation, lessening the coupling of the - * aggregator to the content server, which can be disabled. + * The Content Server Adapter encapsulates all aggregated related activities + * related to aggregation, lessening the coupling of the aggregator to the + * content server, which can be disabled. * </p> - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ -public interface ContentServerAdapter +public interface ContentServerAdapter { + /** - * Pre page aggregation event, prepares the content paths for the - * given decorators of the current page being aggregated. Preparing - * content paths is the process of putting in the correct decorator - * paths so that the content server can correctly find the decorator - * resources. + * Pre page aggregation event, prepares the content paths for the given + * decorators of the current page being aggregated. Preparing content paths + * is the process of putting in the correct decorator paths so that the + * content server can correctly find the decorator resources. * - * @param context Jetspeed portal per request context. - * @param page The current page being aggregated. + * @param context + * Jetspeed portal per request context. + * @param page + * The current page being aggregated. */ void prepareContentPaths(RequestContext context, ContentPage page); - + /** - * Adds stylesheets into the response header for a decoration - * using the Header Resource component. - * Styles can be gathered from both page and portlet decorators. + * Adds stylesheets into the response header for a decoration using the + * Header Resource component. Styles can be gathered from both page and + * portlet decorators. * - * @param context Jetspeed portal per request context. - * @param decoratorName Name of the decorator holding the style. - * @param decoratorType Type of decorator, either portlet or page. + * @param context + * Jetspeed portal per request context. + * @param decoratorName + * Name of the decorator holding the style. + * @param decoratorType + * Type of decorator, either portlet or page. */ - void addStyle(RequestContext context, String decoratorName, String decoratorType); - + void addStyle(RequestContext context, String decoratorName, + String decoratorType); + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/FailedToRenderFragmentException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/FailedToRenderFragmentException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/FailedToRenderFragmentException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /* * Created on Jul 27, 2004 * @@ -29,11 +29,13 @@ * FailedToRenderFragmentException * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: FailedToRenderFragmentException.java 516881 2007-03-11 10:34:21Z ate $ - * + * @version $Id: FailedToRenderFragmentException.java 516881 2007-03-11 + * 10:34:21Z ate $ + * */ public class FailedToRenderFragmentException extends JetspeedException { @@ -49,7 +51,7 @@ /** * @param message */ - public FailedToRenderFragmentException( String message ) + public FailedToRenderFragmentException(String message) { super(message); } @@ -57,7 +59,7 @@ /** * @param nested */ - public FailedToRenderFragmentException( Throwable nested ) + public FailedToRenderFragmentException(Throwable nested) { super(nested); } @@ -66,7 +68,7 @@ * @param msg * @param nested */ - public FailedToRenderFragmentException( String msg, Throwable nested ) + public FailedToRenderFragmentException(String msg, Throwable nested) { super(msg, nested); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PageAggregator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PageAggregator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PageAggregator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,10 +18,10 @@ /** * Page aggregation handles pipeline requests for pages of portlets. - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: PageAggregator.java 516448 2007-03-09 16:25:47Z ate $ */ -public interface PageAggregator extends Aggregator +public interface PageAggregator extends Aggregator { } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletAccessDeniedException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletAccessDeniedException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletAccessDeniedException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * Created on Jan 16, 2004 * @@ -31,19 +31,18 @@ * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ - * + * */ public class PortletAccessDeniedException extends JetspeedException { - /** * */ public PortletAccessDeniedException() { super(); - + } /** @@ -52,7 +51,7 @@ public PortletAccessDeniedException(String message) { super(message); - + } /** @@ -61,7 +60,7 @@ public PortletAccessDeniedException(Throwable nested) { super(nested); - + } /** @@ -71,7 +70,7 @@ public PortletAccessDeniedException(String msg, Throwable nested) { super(msg, nested); - + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletAggregator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletAggregator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletAggregator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,11 +17,12 @@ package org.apache.jetspeed.aggregator; /** - * Portlet aggregation handles pipeline requests for single portlets and entities. - * + * Portlet aggregation handles pipeline requests for single portlets and + * entities. + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: PortletAggregator.java 516448 2007-03-09 16:25:47Z ate $ */ -public interface PortletAggregator extends Aggregator +public interface PortletAggregator extends Aggregator { } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletContent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletContent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletContent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /* * Created on Jan 11, 2005 * @@ -31,77 +31,85 @@ * PortletContent * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @author <a href="mailto:taylor ¡÷ apache.org">David S. Taylor</a> + * @author <a href="mailto:taylor ¡÷ apache.org">David S. Taylor</a> * @version $Id: PortletContent.java 648465 2008-04-16 00:23:47Z taylor $ - * + * */ public interface PortletContent { + /** * Retrieve the actual content of a portlet as a string * * @return */ String getContent(); - - /** + + /** * Has the renderer completed rendering the content? * * @return */ boolean isComplete(); - + /** * Notify that this content is completed. - * + * */ void complete(); - + /** * Notify that this content is complete with error - * + * */ void completeWithError(); - + /** * Get a writer to the content to stream content into this object + * * @return */ PrintWriter getWriter(); - + /** * Get the expiration setting for this content if it is cached. + * * @return */ int getExpiration(); + void setExpiration(int expiration); - + /** * Get the cache key used to cache this content - * @since 2.1.2 + * + * @since 2.1.2 * @return */ ContentCacheKey getCacheKey(); - + /** * Get the title of the portlet, used during caching * * @return */ String getTitle(); - + /** * Set the title of this portlet, used during caching + * * @param title */ void setTitle(String title); /** - * Release the buffers used by the portlet content cache. Note the actual release may not occur until garbage collection. - * + * Release the buffers used by the portlet content cache. Note the actual + * release may not occur until garbage collection. + * */ - void release(); + void release(); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletRenderer.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletRenderer.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletRenderer.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,87 +29,102 @@ /** * <h4>PortletRendererService<br /> * Jetspeed-2 Rendering service.</h4> - * <p>This service process all portlet rendering requests and interfaces with the portlet - * container to generate the resulting markup</p> - * + * <p> + * This service process all portlet rendering requests and interfaces with the + * portlet container to generate the resulting markup + * </p> + * * @author <a href="mailto:raphael ¡÷ apache.org">Rapha?l Luta</a> * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @author <a>Woonsan Ko</a> * @version $Id: PortletRenderer.java 591867 2007-11-05 02:20:06Z woonsan $ */ -public interface PortletRenderer +public interface PortletRenderer { + /** - Render the specified Page fragment. - Result is returned in the PortletResponse. + * Render the specified Page fragment. Result is returned in the + * PortletResponse. + * * @throws FailedToRenderFragmentException * @throws FailedToRetrievePortletWindow * @throws UnknownPortletDefinitionException * @throws PortletAccessDeniedException */ - public void renderNow(ContentFragment fragment, RequestContext request) ; + public void renderNow(ContentFragment fragment, RequestContext request); /** - Render the specified Page fragment. - Result is returned in the PortletResponse. + * Render the specified Page fragment. Result is returned in the + * PortletResponse. + * * @throws FailedToRenderFragmentException * @throws FailedToRetrievePortletWindow * @throws UnknownPortletDefinitionException * @throws PortletAccessDeniedException */ - public void renderNow(ContentFragment fragment, HttpServletRequest request, HttpServletResponse response) ; + public void renderNow(ContentFragment fragment, HttpServletRequest request, + HttpServletResponse response); - /** + /** * - * Render the specified Page fragment. - * The method returns before rendering is complete, rendered content can be - * accessed through the ContentDispatcher + * Render the specified Page fragment. The method returns before rendering + * is complete, rendered content can be accessed through the + * ContentDispatcher + * * @return the asynchronous portlet rendering job to synchronize * @deprecated */ public RenderingJob render(ContentFragment fragment, RequestContext request); - /** + /** * - * Create a rendering job for the specified Page fragment. - * The method returns a rendering job which should be passed to 'processRenderingJob(RenderingJob job)' method. + * Create a rendering job for the specified Page fragment. The method + * returns a rendering job which should be passed to + * 'processRenderingJob(RenderingJob job)' method. + * * @return portlet rendering job to pass to render(RenderingJob job) method * @throws FailedToRetrievePortletWindow * @throws UnknownPortletDefinitionException * @throws PortletAccessDeniedException */ - public RenderingJob createRenderingJob(ContentFragment fragment, RequestContext request); + public RenderingJob createRenderingJob(ContentFragment fragment, + RequestContext request); - /** + /** * - * Render the specified rendering job. - * The method returns before rendering is complete when the job is processed in parallel mode. - * When the job is not parallel mode, it returns after rendering is complete. + * Render the specified rendering job. The method returns before rendering + * is complete when the job is processed in parallel mode. When the job is + * not parallel mode, it returns after rendering is complete. + * * @throws FailedToRenderFragmentException */ public void processRenderingJob(RenderingJob job); - + /** - * Wait for all rendering jobs in the collection to finish successfully or otherwise. - * @param renderingJobs the Collection of rendering job objects to wait for. + * Wait for all rendering jobs in the collection to finish successfully or + * otherwise. + * + * @param renderingJobs + * the Collection of rendering job objects to wait for. */ public void waitForRenderingJobs(List renderingJobs); - + /** * Retrieve the ContentDispatcher for the specified request */ - public ContentDispatcher getDispatcher(RequestContext request, boolean isParallel); + public ContentDispatcher getDispatcher(RequestContext request, + boolean isParallel); /** - * Notify that content completed by worker jobs - * So that renderer can update its state + * Notify that content completed by worker jobs So that renderer can update + * its state * * @param content */ public void notifyContentComplete(PortletContent content); /** - * Set title of portlet window. + * Set title of portlet window. * * @param portletWindow * @param fragment @@ -118,10 +133,11 @@ * @param dispatcher * @param isCacheTitle */ - public void addTitleToHeader( PortletWindow portletWindow, ContentFragment fragment, - HttpServletRequest request, HttpServletResponse response, - ContentDispatcherCtrl dispatcher, boolean isCacheTitle ); + public void addTitleToHeader(PortletWindow portletWindow, + ContentFragment fragment, HttpServletRequest request, + HttpServletResponse response, ContentDispatcherCtrl dispatcher, + boolean isCacheTitle); PortletTrackingManager getPortletTrackingManager(); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletTrackingManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletTrackingManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/PortletTrackingManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,52 +20,56 @@ import org.apache.pluto.om.window.PortletWindow; - /** * <h4>PortletRendererService<br /> * Jetspeed-2 Rendering service.</h4> - * <p>This service process all portlet rendering requests and interfaces with the portlet - * container to generate the resulting markup</p> - * + * <p> + * This service process all portlet rendering requests and interfaces with the + * portlet container to generate the resulting markup + * </p> + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ public interface PortletTrackingManager { + /** - * Get the default timeout for rendering a portlet in milliseconds - * + * Get the default timeout for rendering a portlet in milliseconds + * */ long getDefaultPortletTimeout(); /** - * Out of service limit, if a portlet entity times out past its limit (or default limit) n consecutive times, - * it is taken out of service - * + * Out of service limit, if a portlet entity times out past its limit (or + * default limit) n consecutive times, it is taken out of service + * * @return */ int getOutOfServiceLimit(); - + boolean isOutOfService(PortletWindow window); - + boolean exceededTimeout(long renderTime, PortletWindow window); - + void incrementRenderTimeoutCount(PortletWindow window); void setExpiration(PortletWindow window, long expiration); - + void success(PortletWindow window); - + void takeOutOfService(PortletWindow window); - + void putIntoService(PortletWindow window); + /** * - * @param fullPortletNames a list of Strings of full portlet names + * @param fullPortletNames + * a list of Strings of full portlet names */ void putIntoService(List fullPortletNames); - + List getOutOfServiceList(String fullPortletName); - + List getOutOfServiceList(); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/RenderTrackable.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/RenderTrackable.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/RenderTrackable.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,15 +17,21 @@ package org.apache.jetspeed.aggregator; /** - * Track rendering statistics - * For starter we need to have an object store its render timeout statistics + * Track rendering statistics For starter we need to have an object store its + * render timeout statistics */ public interface RenderTrackable -{ +{ + int getRenderTimeoutCount(); + void incrementRenderTimeoutCount(); + void setExpiration(long expiration); + long getExpiration(); - void success(); + + void success(); + void setRenderTimeoutCount(int count); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/RenderingJob.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/RenderingJob.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/RenderingJob.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,16 +28,17 @@ * Worker thread processes jobs and notify its WorkerMonitor when completed. * When no work is available, the worker simply sets itself in a waiting mode * pending reactivation by the WorkerMonitor - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ public interface RenderingJob extends Runnable { + void execute(); - - PortletWindow getWindow(); + PortletWindow getWindow(); + PortletContent getPortletContent(); void setTimeout(long portletTimeout); @@ -45,7 +46,7 @@ long getTimeout(); boolean isTimeout(); - + PortletDefinition getPortletDefinition(); HttpServletRequest getRequest(); @@ -61,11 +62,10 @@ ContentDispatcherCtrl getDispatcher(); boolean isContentCached(); - + void setWorkerAttribute(String name, Object value); - + Object getWorkerAttribute(String name); - + void removeWorkerAttribute(String name); } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/UnknownPortletDefinitionException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/UnknownPortletDefinitionException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/UnknownPortletDefinitionException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * Created on Jan 16, 2004 * @@ -30,20 +30,20 @@ * </p> * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: UnknownPortletDefinitionException.java 516881 2007-03-11 10:34:21Z ate $ - * + * @version $Id: UnknownPortletDefinitionException.java 516881 2007-03-11 + * 10:34:21Z ate $ + * */ public class UnknownPortletDefinitionException extends JetspeedException { - /** * */ public UnknownPortletDefinitionException() { super(); - + } /** @@ -52,7 +52,7 @@ public UnknownPortletDefinitionException(String message) { super(message); - + } /** @@ -61,7 +61,7 @@ public UnknownPortletDefinitionException(Throwable nested) { super(nested); - + } /** @@ -71,7 +71,7 @@ public UnknownPortletDefinitionException(String msg, Throwable nested) { super(msg, nested); - + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/UnrenderedContentException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/UnrenderedContentException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/UnrenderedContentException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /* * Created on Dec 22, 2004 * @@ -29,11 +29,13 @@ * UnrenderedContentException * </p> * <p> - * This excpetion is raised when trying to access portlet content that did not render correctly or not at all. + * This excpetion is raised when trying to access portlet content that did not + * render correctly or not at all. * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: UnrenderedContentException.java 516881 2007-03-11 10:34:21Z ate $ - * + * */ public class UnrenderedContentException extends JetspeedException { @@ -50,7 +52,7 @@ /** * @param message */ - public UnrenderedContentException( String message ) + public UnrenderedContentException(String message) { super(message); // TODO Auto-generated constructor stub @@ -59,7 +61,7 @@ /** * @param nested */ - public UnrenderedContentException( Throwable nested ) + public UnrenderedContentException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -69,7 +71,7 @@ * @param msg * @param nested */ - public UnrenderedContentException( String msg, Throwable nested ) + public UnrenderedContentException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/Worker.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/Worker.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/Worker.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,44 +22,45 @@ * Worker thread processes jobs and notify its WorkerMonitor when completed. * When no work is available, the worker simply sets itself in a waiting mode * pending reactivation by the WorkerMonitor - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ -public interface Worker +public interface Worker { - int getJobCount(); + int getJobCount(); + /** * Reset the processed job counter */ - void resetJobCount(); + void resetJobCount(); /** * Sets the running status of this Worker. If set to false, the Worker will * stop after processing its current job. */ - void setRunning(boolean status); - + void setRunning(boolean status); + /** * Sets the moitor of this worker */ - void setMonitor(WorkerMonitor monitor); - + void setMonitor(WorkerMonitor monitor); + /** * Sets the job to execute in security context */ - void setJob(Runnable job, AccessControlContext context); + void setJob(Runnable job, AccessControlContext context); /** * Sets the job to execute */ - void setJob(Runnable job); + void setJob(Runnable job); /** * Retrieves the job to execute */ - Runnable getJob(); - - void start(); + Runnable getJob(); + + void start(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/WorkerMonitor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/WorkerMonitor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/aggregator/WorkerMonitor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,57 +19,61 @@ import java.util.List; /** - * The Worker Monitor is a thread manager and monitor for async portlet aggregation - * and rendering. - * + * The Worker Monitor is a thread manager and monitor for async portlet + * aggregation and rendering. + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ -public interface WorkerMonitor +public interface WorkerMonitor { + /** * Start processing the worker monitor - * + * */ void start(); - + /** - * Stop processing the worker monitor - * Finish all jobs - * + * Stop processing the worker monitor Finish all jobs + * */ void stop(); - + /** * Retrieves a snapshot of job count in the waiting (backlogged) queue * * @return snapshot count of waiting jobs */ int getQueuedJobsCount(); - + /** * Returns a snapshot count of the available jobs + * * @return available jobs count */ int getAvailableJobsCount(); - + /** * Returns a snapshot count of the jobs currently running * * @return snapshot count of running jobs */ int getRunningJobsCount(); - - /** + + /** * Start processing a job, assign it to a worker thread. * * @param job */ void process(RenderingJob job); - + /** - * Wait for all rendering jobs in the collection to finish successfully or otherwise. - * @param renderingJobs the Collection of rendering job objects to wait for. + * Wait for all rendering jobs in the collection to finish successfully or + * otherwise. + * + * @param renderingJobs + * the Collection of rendering job objects to wait for. */ public void waitForRenderingJobs(List renderingJobs); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AJAXRequest.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AJAXRequest.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AJAXRequest.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,19 +26,20 @@ * Request used for AJAX services. * * @author <href a="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * + * */ public interface AJAXRequest { - String getServiceName(); - - String getMethodName(); - - List getParameters(); - - HttpServletRequest getServletRequest(); - - HttpServletResponse getServletResponse(); - - ServletContext getContext(); + + String getServiceName(); + + String getMethodName(); + + List getParameters(); + + HttpServletRequest getServletRequest(); + + HttpServletResponse getServletResponse(); + + ServletContext getContext(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AJAXResponse.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AJAXResponse.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AJAXResponse.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,14 +16,14 @@ */ package org.apache.jetspeed.ajax; - /** * Response object used for AJAX services. * * @author <href a="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * + * */ public interface AJAXResponse { + void complete() throws AJAXException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AJAXService.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AJAXService.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AJAXService.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,13 +17,14 @@ package org.apache.jetspeed.ajax; /** - * Performs invocation of the actual AJAX request and returns - * a result object to converted into XML. + * Performs invocation of the actual AJAX request and returns a result object to + * converted into XML. * * @author <href a="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * + * */ public interface AJAXService { + AJAXResponse processRequest(AJAXRequest request) throws AJAXException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AjaxAction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AjaxAction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AjaxAction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,50 +16,56 @@ */ package org.apache.jetspeed.ajax; -import org.apache.jetspeed.request.RequestContext; import java.util.Map; +import org.apache.jetspeed.request.RequestContext; + /** - * An Ajax request is made up of an action and builder phases. - * Implement this interface for the Ajax action phase. - * The action should put any parameters or results it wants - * passed on to the builders in the resultMap - * + * An Ajax request is made up of an action and builder phases. Implement this + * interface for the Ajax action phase. The action should put any parameters or + * results it wants passed on to the builders in the resultMap + * * @author <href a="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> */ public interface AjaxAction { - + /** - * The action should put any parameters or results it wants - * passed on to the builders in the resultMap - * This method runs an Ajax action. - * - * @param requestContext The Jetspeed Request Context - * @param resultMap map of action parameters passed to the builder context + * The action should put any parameters or results it wants passed on to the + * builders in the resultMap This method runs an Ajax action. + * + * @param requestContext + * The Jetspeed Request Context + * @param resultMap + * map of action parameters passed to the builder context * @return success is true, failure is false * @throws Exception */ - public boolean run(RequestContext requestContext, Map resultMap) throws AJAXException; + public boolean run(RequestContext requestContext, Map resultMap) + throws AJAXException; /** - * Same as run method, but runs in batch mode, as a hint to the action - * that it is running a multiple action and can delay its update - * runBatch currently supports pageManager.updatePage - * - * @param requestContext The Jetspeed Request Context - * @param resultMap map of action parameters passed to the builder context + * Same as run method, but runs in batch mode, as a hint to the action that + * it is running a multiple action and can delay its update runBatch + * currently supports pageManager.updatePage + * + * @param requestContext + * The Jetspeed Request Context + * @param resultMap + * map of action parameters passed to the builder context * @return success is true, failure is false * @throws Exception - */ - public boolean runBatch(RequestContext requestContext, Map resultMap) throws AJAXException; - + */ + public boolean runBatch(RequestContext requestContext, Map resultMap) + throws AJAXException; + /** - * Checks to see if the current subject has access to to execute this action. + * Checks to see if the current subject has access to to execute this + * action. * * @param context * @return true if access granted, false if denied. */ public boolean checkAccess(RequestContext context, String action); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AjaxBuilder.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AjaxBuilder.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AjaxBuilder.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,19 +17,20 @@ package org.apache.jetspeed.ajax; import java.util.Map; + import org.apache.jetspeed.request.RequestContext; /** - * An Ajax request is made up of an action and builder phases. - * Implement this interface for the Ajax builder phase. - * The builder can add additional information to the requiest context, - * and it also provides the template used for building the result stream - * sent back over the Ajax request. - * + * An Ajax request is made up of an action and builder phases. Implement this + * interface for the Ajax builder phase. The builder can add additional + * information to the requiest context, and it also provides the template used + * for building the result stream sent back over the Ajax request. + * * @author <href a="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> */ public interface AjaxBuilder -{ +{ + /** * @return the name of the template used for this builder */ @@ -37,24 +38,29 @@ /** * @return the name of the error template used for this builder - */ + */ public String getErrorTemplate(); - + /** * Build the normal context template * - * @param requestContext The Jetspeed Request Context - * @param contextVars Context variables to be substituted into template + * @param requestContext + * The Jetspeed Request Context + * @param contextVars + * Context variables to be substituted into template * @return true on success false onerror */ public boolean buildContext(RequestContext requestContext, Map contextVars); - + /** * Build the error context template * - * @param requestContext The Jetspeed Request Context - * @param contextVars Context variables to be substituted into template + * @param requestContext + * The Jetspeed Request Context + * @param contextVars + * Context variables to be substituted into template * @return true on success false onerror */ - public boolean buildErrorContext(RequestContext requestContext, Map contextVars); + public boolean buildErrorContext(RequestContext requestContext, + Map contextVars); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AjaxRequestService.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AjaxRequestService.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/ajax/AjaxRequestService.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,14 +21,16 @@ import org.apache.jetspeed.request.RequestContext; /** - * An Ajax request is made up of an action and builder phases. - * This interface defines the entry point into Ajax Request processing - * typically used in a Jetspeed pipeline. - * + * An Ajax request is made up of an action and builder phases. This interface + * defines the entry point into Ajax Request processing typically used in a + * Jetspeed pipeline. + * * @author <href a="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> */ -public interface AjaxRequestService +public interface AjaxRequestService { + public void process(RequestContext requestContext) throws AJAXException; + public Map getActionMap(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/audit/AuditActivity.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/audit/AuditActivity.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/audit/AuditActivity.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,61 +26,90 @@ */ public interface AuditActivity { + // user activities public static final String AUTHENTICATION_SUCCESS = "login-success"; + public static final String AUTHENTICATION_FAILURE = "login-failure"; + public static final String PASSWORD_CHANGE_SUCCESS = "password-success"; + public static final String PASSWORD_CHANGE_FAILURE = "password-failure"; - + // admin activities public static final String USER_CREATE = "user-create"; + public static final String USER_UPDATE = "user-update"; + public static final String USER_DELETE = "user-delete"; + public static final String USER_DISABLE = "user-disable"; - public static final String USER_EXTEND = "user-extend"; - public static final String USER_EXTEND_UNLIMITED = "user-extend-unlimited"; + public static final String USER_EXTEND = "user-extend"; + + public static final String USER_EXTEND_UNLIMITED = "user-extend-unlimited"; + public static final String PASSWORD_EXPIRE = "password-expire"; + public static final String PASSWORD_RESET = "password-reset"; - public static final String PASSWORD_ACTIVATE = "password-activate"; - public static final String PASSWORD_ENABLED = "password-enabled"; - public static final String PASSWORD_DISABLED = "password-disabled"; + + public static final String PASSWORD_ACTIVATE = "password-activate"; + + public static final String PASSWORD_ENABLED = "password-enabled"; + + public static final String PASSWORD_DISABLED = "password-disabled"; + public static final String PASSWORD_UPDATE_REQUIRED = "password-update-req"; + public static final String PASSWORD_EXTEND = "password-extend"; + public static final String PASSWORD_UNLIMITED = "password-unlimited"; - + public static final String USER_ADD_ROLE = "user-add-role"; + public static final String USER_DELETE_ROLE = "user-delete-role"; + public static final String USER_ADD_GROUP = "user-add-group"; + public static final String USER_DELETE_GROUP = "user-delete-group"; + public static final String USER_ADD_PROFILE = "user-add-profile"; + public static final String USER_DELETE_PROFILE = "user-delete-profile"; public static final String USER_ADD_ATTRIBUTE = "user-add-attr"; + public static final String USER_DELETE_ATTRIBUTE = "user-delete-attr"; + public static final String USER_UPDATE_ATTRIBUTE = "user-update-attr"; - + // General Categories public static final String CAT_USER_AUTHENTICATION = "authentication"; + public static final String CAT_USER_ATTRIBUTE = "user-attribute"; + public static final String CAT_ADMIN_USER_MAINTENANCE = "user"; + public static final String CAT_ADMIN_CREDENTIAL_MAINTENANCE = "credential"; + public static final String CAT_ADMIN_ATTRIBUTE_MAINTENANCE = "attribute"; - public static final String CAT_ADMIN_AUTHORIZATION_MAINTENANCE = "authorization"; - + + public static final String CAT_ADMIN_AUTHORIZATION_MAINTENANCE = "authorization"; + /** * Enable or disable the service at runtime * * @param enabled */ public void setEnabled(boolean enabled); - + /** * Get the enabled state of this service + * * @return */ public boolean getEnabled(); - + /** * Log user security-audit-related activity * @@ -89,7 +118,8 @@ * @param activity * @param description */ - public void logUserActivity(String username, String ipaddress, String activity, String description); + public void logUserActivity(String username, String ipaddress, + String activity, String description); /** * Log auditable activity by an administrator on behalf of another user @@ -100,10 +130,12 @@ * @param activity * @param description */ - public void logAdminUserActivity(String username, String ipaddress, String targetUser, String activity, String description); + public void logAdminUserActivity(String username, String ipaddress, + String targetUser, String activity, String description); /** - * Log auditable activity by an administrator on credentials on behalf of a user + * Log auditable activity by an administrator on credentials on behalf of a + * user * * @param adminName * @param ipaddress @@ -111,12 +143,16 @@ * @param activity * @param description */ - public void logAdminCredentialActivity(String username, String ipaddress, String targetUser, String activity, String description); - - public void logAdminAuthorizationActivity(String username, String ipaddress, String targetUser, String activity, String name, String description); - + public void logAdminCredentialActivity(String username, String ipaddress, + String targetUser, String activity, String description); + + public void logAdminAuthorizationActivity(String username, + String ipaddress, String targetUser, String activity, String name, + String description); + /** - * Log auditable activity by an administrator on attirbutes on behalf of a user + * Log auditable activity by an administrator on attirbutes on behalf of a + * user * * @param username * @param ipaddress @@ -127,10 +163,13 @@ * @param afterValue * @param description */ - public void logAdminAttributeActivity(String username, String ipaddress, String targetUser, String activity, String name, String beforeValue, String afterValue, String description); + public void logAdminAttributeActivity(String username, String ipaddress, + String targetUser, String activity, String name, + String beforeValue, String afterValue, String description); /** - * Log auditable activity by an administrator on attirbutes on behalf of a user + * Log auditable activity by an administrator on attirbutes on behalf of a + * user * * @param username * @param ipaddress @@ -140,11 +179,13 @@ * @param afterValue * @param description */ - public void logUserAttributeActivity(String username, String ipaddress, String activity, String name, String beforeValue, String afterValue, String description); + public void logUserAttributeActivity(String username, String ipaddress, + String activity, String name, String beforeValue, + String afterValue, String description); /** * @return DataSource in use by the logger useful for writing decent tests */ public DataSource getDataSource(); - -} \ No newline at end of file + +} \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/CacheElement.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/CacheElement.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/CacheElement.java 2008-05-16 01:54:54 UTC (rev 940) @@ -15,13 +15,12 @@ * limitations under the License. */ - package org.apache.jetspeed.cache; /** * <p> - * Provides interface to cached elements - * Abstraction around atual cache implementation + * Provides interface to cached elements Abstraction around atual cache + * implementation * </p> * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> @@ -29,37 +28,39 @@ */ public interface CacheElement { - public static int ActionAdded = 1; - public static int ActionChanged = 2; - public static int ActionRemoved = -1; - public static int ActionEvicted = -2; - public static int ActionExpired = -3; - - + + public static int ActionAdded = 1; + + public static int ActionChanged = 2; + + public static int ActionRemoved = -1; + + public static int ActionEvicted = -2; + + public static int ActionExpired = -3; + /** * * @return the idle time in seconds for this cache element */ int getTimeToIdleSeconds(); - + /** * * @return the idle time in seconds for this cache element */ - int getTimeToLiveSeconds(); - + int getTimeToLiveSeconds(); + void setTimeToLiveSeconds(int timeToLive); - + void setTimeToIdleSeconds(int timeToIdle); - + Object getContent(); - + Object getKey(); - + boolean isEternal(); - + void setEternal(boolean eternal); - - - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/ContentCacheElement.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/ContentCacheElement.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/ContentCacheElement.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,7 +18,7 @@ /** * <p> - * specialized portlet content cache key + * specialized portlet content cache key * </p> * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> @@ -26,5 +26,6 @@ */ public interface ContentCacheElement extends CacheElement { + ContentCacheKey getContentCacheKey(); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/ContentCacheKey.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/ContentCacheKey.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/ContentCacheKey.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,10 +18,9 @@ import java.io.Serializable; - /** * <p> - * Provides interface to all Content Caches (Portlet API cache) + * Provides interface to all Content Caches (Portlet API cache) * </p> * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> @@ -29,50 +28,55 @@ */ public interface ContentCacheKey extends Serializable { + /** * Get the username or null if not used + * * @return */ String getUsername(); - + /** * Get the pipeline name or null if not used + * * @return */ String getPipeline(); - + /** * Get the window (portlet fragment) id + * * @return */ String getWindowId(); - + /** * Get the session id or null if not used * * @return */ String getSessionId(); - + /** * * @return */ String getRequestParameter(); - + /** * * @return */ String getSessionAttribute(); - + /** * Return the full key as a string + * * @return */ String getKey(); - + void createFromUser(String username, String pipeline, String windowId); - + void createFromSession(String sessionid, String pipeline, String windowId); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/ContentCacheKeyGenerator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/ContentCacheKeyGenerator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/ContentCacheKeyGenerator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,7 +20,7 @@ /** * <p> - * Provides interface to Jetspeed for content cache key generation + * Provides interface to Jetspeed for content cache key generation * </p> * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> @@ -28,47 +28,55 @@ */ public interface ContentCacheKeyGenerator { + /** * Normalized and pluggable cache key generator * * @param context - * @param windowId The window id of the portlet to be cached. + * @param windowId + * The window id of the portlet to be cached. * @since 2.1.2 * @return */ ContentCacheKey createCacheKey(RequestContext context, String windowId); - + /** - * Create a cache key without request context information, but by providing required parameters username and windowid + * Create a cache key without request context information, but by providing + * required parameters username and windowid * * @param username - * @param pipeline "desktop" or "portal" + * @param pipeline + * "desktop" or "portal" * @param windowId * @return */ - ContentCacheKey createUserCacheKey(String username, String pipeline, String windowId); + ContentCacheKey createUserCacheKey(String username, String pipeline, + String windowId); /** - * Create a cache key without request context information, but by providing required parameters sessinid and windowid + * Create a cache key without request context information, but by providing + * required parameters sessinid and windowid * * @param sessionid - * @param pipeline "desktop" or "portal" + * @param pipeline + * "desktop" or "portal" * @param windowId * @return */ - ContentCacheKey createSessionCacheKey(String sessionid, String pipeline, String windowId); - + ContentCacheKey createSessionCacheKey(String sessionid, String pipeline, + String windowId); + /** - * return true if caching is by session id, not username - * + * return true if caching is by session id, not username + * * @return */ boolean isCacheBySessionId(); - + /** - * return true if caching is by username, not sessionid - * + * return true if caching is by username, not sessionid + * * @return - */ + */ boolean isCacheByUsername(); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/DistributedCacheObject.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/DistributedCacheObject.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/DistributedCacheObject.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,15 +20,16 @@ /** * <p> - * Provides interface to the object referenced in the cached Element - * Abstraction around atual cache implementation + * Provides interface to the object referenced in the cached Element Abstraction + * around atual cache implementation * </p> * - * @author + * @author * @version $Id: $ */ public interface DistributedCacheObject extends Serializable { + public void notifyChange(int action); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/JetspeedCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/JetspeedCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/JetspeedCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,8 +20,8 @@ /** * <p> - * Provides interface to Jetspeed for cache related activities - * Abstraction around actual cache implementation + * Provides interface to Jetspeed for cache related activities Abstraction + * around actual cache implementation * </p> * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> @@ -29,44 +29,48 @@ */ public interface JetspeedCache { + /** * Retrieve an object from the cache * - * @param key The key used to find the object + * @param key + * The key used to find the object * @return the found object or null */ CacheElement get(Object key); - + /** * clear all content in the cache - * + * */ void clear(); - + /** * Put an object into the cache, adding it, or replacing if exists + * * @param object */ void put(CacheElement object); - + /** - * Create a cached element + * Create a cached element * * @param key * @param content * @return */ CacheElement createElement(Object key, Object content); - + boolean isKeyInCache(Object key); - + /** * Remove an object from the cache + * * @param key * @return true if the object was removed, false otherwise */ boolean remove(Object key); - + /** * Remove object from cache, do not notify listeners * @@ -74,13 +78,13 @@ * @return trie if the object was removed, false otherwise */ boolean removeQuiet(Object key); - + /** * * @return the default idle time in seconds for this cache */ int getTimeToIdleSeconds(); - + /** * * @return the default idle time in seconds for this cache @@ -88,21 +92,24 @@ int getTimeToLiveSeconds(); /** - * Evict all cached content for the given username + * Evict all cached content for the given username * - * @param username unique user identifier + * @param username + * unique user identifier */ void evictContentForUser(String username); /** - * Evict all cached content for the given session identifier + * Evict all cached content for the given session identifier * - * @param sessionid unique session identifier - */ + * @param sessionid + * unique session identifier + */ void evictContentForSession(String sessionId); - + /** - * Create a portlet content cache key based on dynamic request context information and a window id + * Create a portlet content cache key based on dynamic request context + * information and a window id * * @param rc * @param windowId @@ -110,14 +117,16 @@ * @return */ ContentCacheKey createCacheKey(RequestContext rc, String windowId); - + /** - * Add a cache listener for supported cache events, either for local or remote cache events + * Add a cache listener for supported cache events, either for local or + * remote cache events * * @param listener - * @param local if true, listen to local events, if false, listen to remote - */ + * @param local + * if true, listen to local events, if false, listen to remote + */ void addEventListener(JetspeedCacheEventListener listener, boolean local); - + void removeEventListener(JetspeedCacheEventListener listener, boolean local); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/JetspeedCacheEventListener.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/JetspeedCacheEventListener.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/JetspeedCacheEventListener.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,84 +27,84 @@ public interface JetspeedCacheEventListener { - /** - * REMOVE notification for cache listeners - * - * @param cache - * the Cache repoorting the change - * @param local - * true if action was local, false if initiated by remote cache - * @param key - * key of object - * @param element - * content of object - * - */ - void notifyElementRemoved(JetspeedCache cache, boolean local, Object key, - Object element); + /** + * REMOVE notification for cache listeners + * + * @param cache + * the Cache repoorting the change + * @param local + * true if action was local, false if initiated by remote cache + * @param key + * key of object + * @param element + * content of object + * + */ + void notifyElementRemoved(JetspeedCache cache, boolean local, Object key, + Object element); - /** - * ADDED notification for cache listeners - * - * @param cache - * the Cache repoorting the change - * @param local - * true if action was local, false if initiated by remote cache - * @param key - * key of object - * @param element - * content of object - * - */ - void notifyElementAdded(JetspeedCache cache, boolean local, Object key, - Object element); + /** + * ADDED notification for cache listeners + * + * @param cache + * the Cache repoorting the change + * @param local + * true if action was local, false if initiated by remote cache + * @param key + * key of object + * @param element + * content of object + * + */ + void notifyElementAdded(JetspeedCache cache, boolean local, Object key, + Object element); - /** - * CHANGE notification for cache listeners - * - * @param cache - * the Cache repoorting the change - * @param local - * true if action was local, false if initiated by remote cache - * @param key - * key of object - * @param element - * content of object - * - */ - void notifyElementChanged(JetspeedCache cache, boolean local, Object key, - Object element); + /** + * CHANGE notification for cache listeners + * + * @param cache + * the Cache repoorting the change + * @param local + * true if action was local, false if initiated by remote cache + * @param key + * key of object + * @param element + * content of object + * + */ + void notifyElementChanged(JetspeedCache cache, boolean local, Object key, + Object element); - /** - * EVICTED notification for cache listeners - * - * @param cache - * the Cache repoorting the change - * @param local - * true if action was local, false if initiated by remote cache - * @param key - * key of object - * @param element - * content of object - * - */ - void notifyElementEvicted(JetspeedCache cache, boolean local, Object key, - Object element); + /** + * EVICTED notification for cache listeners + * + * @param cache + * the Cache repoorting the change + * @param local + * true if action was local, false if initiated by remote cache + * @param key + * key of object + * @param element + * content of object + * + */ + void notifyElementEvicted(JetspeedCache cache, boolean local, Object key, + Object element); - /** - * EXPIRED notification for cache listeners - * - * @param cache - * the Cache repoorting the change - * @param local - * true if action was local, false if initiated by remote cache - * @param key - * key of object - * @param element - * content of object - * - */ - void notifyElementExpired(JetspeedCache cache, boolean local, Object key, - Object element); + /** + * EXPIRED notification for cache listeners + * + * @param cache + * the Cache repoorting the change + * @param local + * true if action was local, false if initiated by remote cache + * @param key + * key of object + * @param element + * content of object + * + */ + void notifyElementExpired(JetspeedCache cache, boolean local, Object key, + Object element); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/JetspeedContentCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/JetspeedContentCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/JetspeedContentCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,8 +20,8 @@ /** * <p> - * Provides interface to Jetspeed for cache related activities - * Abstraction around actual cache implementation + * Provides interface to Jetspeed for cache related activities Abstraction + * around actual cache implementation * </p> * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> @@ -29,16 +29,19 @@ */ public interface JetspeedContentCache extends JetspeedCache { + /** - * Creates a session key used to store associated information in the session. + * Creates a session key used to store associated information in the + * session. * * @param context * @return */ String createSessionKey(RequestContext context); - - /** - * remove from the cache and invalidate any associated caches or session attributes + + /** + * remove from the cache and invalidate any associated caches or session + * attributes * * @param context * @param key Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/PortletWindowCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/PortletWindowCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/PortletWindowCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,66 +23,75 @@ import org.apache.pluto.om.window.PortletWindow; /** - * {@link org.apache.jetspeed.cache.impl.PortletWindowCache} is an abstraction of a caching mechanism for use - * within {@link org.apache.jetspeed.container.window.impl.PortletWindowAccessorImpl}. + * {@link org.apache.jetspeed.cache.impl.PortletWindowCache} is an abstraction + * of a caching mechanism for use within + * {@link org.apache.jetspeed.container.window.impl.PortletWindowAccessorImpl}. * * @author <a href="mailto:scott.t.weaver ¡÷ gmail.com">Scott T. Weaver</a> - * @see PortletWindowAccessorImpl - * @see EhPortletWindowCache * */ public interface PortletWindowCache { + /** * Gets a {@link PortletWindow} from the cache. * - * @param windowId Id of the window to get from the cache. - * @return {@link PortletWindow} whose <code>id</code> to - * {@link PortletWindow#getId()} or <code>null</code> if no window exists that matches - * <code>windowId</code>. + * @param windowId + * Id of the window to get from the cache. + * @return {@link PortletWindow} whose <code>id</code> to + * {@link PortletWindow#getId()} or <code>null</code> if no window + * exists that matches <code>windowId</code>. */ PortletWindow getPortletWindow(String windowId); - + /** * Gets a {@link PortletWindow} from the cache whose {@link PortletEntity}'s ({@link PortletWindow#getPortletEntity()}) * equals <code>portletEntityId</code>. * - * @param portletEntityId id of {@link PortletEntity} whose window want want to retrieve from cache. - * @return {@link PortletWindow} whose {@link PortletEntity}'s id equals <code>portletEntityId</code> - * or <code>null</code> if no windows exists in the cache that match said criteria. + * @param portletEntityId + * id of {@link PortletEntity} whose window want want to retrieve + * from cache. + * @return {@link PortletWindow} whose {@link PortletEntity}'s id equals + * <code>portletEntityId</code> or <code>null</code> if no + * windows exists in the cache that match said criteria. */ PortletWindow getPortletWindowByEntityId(String portletEntityId); - + /** - * Stores a {@link PortletWindow} in the cache using the {@link PortletWindow#getId()#toString()} - * as the key for the cache. + * Stores a {@link PortletWindow} in the cache using the + * {@link PortletWindow#getId()#toString()} as the key for the cache. * - * @param window {@link PortletWindow} to put into the cache. + * @param window + * {@link PortletWindow} to put into the cache. */ void putPortletWindow(PortletWindow window); - + /** - * Removes a {@link PortletWindow} from cache using the <code>windowId</code> - * as the cache key. + * Removes a {@link PortletWindow} from cache using the + * <code>windowId</code> as the cache key. * - * @param windowId Id of the {@link PortletWindow} we want to remove from the cache. + * @param windowId + * Id of the {@link PortletWindow} we want to remove from the + * cache. */ void removePortletWindow(String windowId); /** - * Removes a {@link PortletWindow} from the cache whose {@link PortletEntity}'s id - * matches <code>portletEntityId</code>. + * Removes a {@link PortletWindow} from the cache whose + * {@link PortletEntity}'s id matches <code>portletEntityId</code>. * - * @param portletEntityId id of the {@link PortletEntity} whose parent {@link PortletWindow} - * is to be removed from the cache. + * @param portletEntityId + * id of the {@link PortletEntity} whose parent + * {@link PortletWindow} is to be removed from the cache. */ void removePortletWindowByPortletEntityId(String portletEntityId); - + /** * - * @return {@link List} of all the {@link PortletWindow}s in the cache. If no cache - * entries exist an empty list is returned. Never returns <code>null</code>. + * @return {@link List} of all the {@link PortletWindow}s in the cache. If + * no cache entries exist an empty list is returned. Never returns + * <code>null</code>. */ Set getAllPortletWindows(); -} \ No newline at end of file +} Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/file/FileCacheEntry.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/file/FileCacheEntry.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/file/FileCacheEntry.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,62 +21,68 @@ /** * @author <a href="weaver ¡÷ apache.org">Scott T. Weaver</a> - * + * */ public interface FileCacheEntry { + /** * Get the file descriptor - * + * * @return the file descriptor */ File getFile(); /** * Set the file descriptor - * - * @param file the new file descriptor + * + * @param file + * the new file descriptor */ - void setFile( File file ); + void setFile(File file); /** * Set the cache's last accessed stamp - * - * @param lastAccessed the cache's last access stamp + * + * @param lastAccessed + * the cache's last access stamp */ - void setLastAccessed( long lastAccessed ); + void setLastAccessed(long lastAccessed); /** * Get the cache's lastAccessed stamp - * + * * @return the cache's last accessed stamp */ long getLastAccessed(); /** * Set the cache's last modified stamp - * - * @param lastModified the cache's last modified stamp + * + * @param lastModified + * the cache's last modified stamp */ - void setLastModified( Date lastModified ); + void setLastModified(Date lastModified); /** - * Get the entry's lastModified stamp (which may be stale compared to file's stamp) - * + * Get the entry's lastModified stamp (which may be stale compared to file's + * stamp) + * * @return the last modified stamp */ Date getLastModified(); /** * Set the Document in the cache - * - * @param document the document being cached + * + * @param document + * the document being cached */ - void setDocument( Object document ); + void setDocument(Object document); /** * Get the Document - * + * * @return the document being cached */ Object getDocument(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/file/FileCacheEventListener.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/file/FileCacheEventListener.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/file/FileCacheEventListener.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,12 +17,11 @@ package org.apache.jetspeed.cache.file; - /** * FileCacheEventListener on notifications sent when FileCache events occur - * - * @author David S. Taylor <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> - * @version $Id: FileCacheEventListener.java 516448 2007-03-09 16:25:47Z ate $ + * + * @author David S. Taylor <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> + * @version $Id: FileCacheEventListener.java 516448 2007-03-09 16:25:47Z ate $ */ public interface FileCacheEventListener @@ -30,19 +29,18 @@ /** * Refresh event, called when the entry is being refreshed from file system. - * - * @param entry the entry being refreshed. + * + * @param entry + * the entry being refreshed. */ void refresh(FileCacheEntry entry) throws Exception; /** * Evict event, called when the entry is being evicted out of the cache - * - * @param entry the entry being refreshed. + * + * @param entry + * the entry being refreshed. */ void evict(FileCacheEntry entry) throws Exception; } - - - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/general/GeneralCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/general/GeneralCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cache/general/GeneralCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,59 +21,59 @@ * GeneralCache * </p> * <p> - * A very general, re-useable interface to wrap or create different caching implementations. + * A very general, re-useable interface to wrap or create different caching + * implementations. * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: GeneralCache.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface GeneralCache { - + /** * * <p> * get * </p> - * + * * @param key * @return */ Object get(String key); - + /** * * <p> * put * </p> - * + * * @param key * @param value */ void put(String key, Object value); - + /** * * <p> * contains * </p> - * + * * @param key * @return */ boolean contains(String key); - + /** * * <p> * remove * </p> - * + * * @param key * @return */ Object remove(String key); - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/Capabilities.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/Capabilities.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/Capabilities.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,69 +21,84 @@ /** * Capabilities Component Interface - * + * * @author <a href="mailto:roger.ruttimann ¡÷ earthlink.net">Roger Ruttimann</a> * @version $Id: Capabilities.java 516448 2007-03-09 16:25:47Z ate $ */ -public interface Capabilities +public interface Capabilities { /** - * Creates a Capability Map with Capabilities, Mimetypes and mediaTypes for the given UserAgentPattern - * @param userAgent Agent from the request - * @return CapabilityMap populated with Capabilities, Mimetypes and Mediatype - * that match the userAgent. Never returns <code>null</code> - * @throws UnableToBuildCapabilityMapException If a capability could not be created + * Creates a Capability Map with Capabilities, Mimetypes and mediaTypes for + * the given UserAgentPattern + * + * @param userAgent + * Agent from the request + * @return CapabilityMap populated with Capabilities, Mimetypes and + * Mediatype that match the userAgent. Never returns + * <code>null</code> + * @throws UnableToBuildCapabilityMapException + * If a capability could not be created */ - CapabilityMap getCapabilityMap(String userAgent) throws UnableToBuildCapabilityMapException; + CapabilityMap getCapabilityMap(String userAgent) + throws UnableToBuildCapabilityMapException; /** * Obtain an iterator of all existing clients. + * * @return Returns an iterator for all existing Clients */ Iterator getClients(); /** * Finds a client for a given userAgentPattern + * * @param userAgent * @return Client that matches agent or null if no match is found - * + * */ Client findClient(String userAgent); /** - * Returns a collection of MediaTypes that matches the MimeTypes defined in the mimetype parameter + * Returns a collection of MediaTypes that matches the MimeTypes defined in + * the mimetype parameter + * * @param Mimetype - * + * * @return Collection of Mediatypes that matches the mimetypes */ Collection getMediaTypesForMimeTypes(Iterator mimetypes); /** - * Clears CapabilityMap cache - * TODO: Roger, why is this on the public interface. It seems to be impl specific + * Clears CapabilityMap cache TODO: Roger, why is this on the public + * interface. It seems to be impl specific */ void deleteCapabilityMapCache(); /** * Given a media type string, look up the corresponding media type object. * - * @param mediaType The string representation of a media type. + * @param mediaType + * The string representation of a media type. * @return The found media type object or if not found, null. */ MediaType getMediaType(String mediaType); /** * Given a Mimetype string lookup the corresponding media type object - * @param mimeTypeName to use for lookup - * @return MediaTypeEntry that matches the lookup in the MEDIATYPE_TO_MIMETYPE table + * + * @param mimeTypeName + * to use for lookup + * @return MediaTypeEntry that matches the lookup in the + * MEDIATYPE_TO_MIMETYPE table */ public MediaType getMediaTypeForMimeType(String mimeTypeName); /** * Given a capability string, look up the corresponding capability object. * - * @param capability The string representation of a capability. + * @param capability + * The string representation of a capability. * @return The found capability object or if not found, null. */ Capability getCapability(String capability); @@ -91,180 +106,216 @@ /** * Given a mime type string, look up the corresponding mime type object. * - * @param mimeType The string representation of a mime type. + * @param mimeType + * The string representation of a mime type. * @return The found mime type object or if not found, null. */ MimeType getMimeType(String mimeType); + /** * Given a client name, look up the corresponding client object. * - * @param clientName The name of the client. + * @param clientName + * The name of the client. * @return The found client object or if not found, null. */ Client getClient(String clientName); /** * Obtain an iterator of all existing capabilities. - * @return Returns an iterator for all existing Capabilities of type <code>Capability</code> + * + * @return Returns an iterator for all existing Capabilities of type + * <code>Capability</code> */ Iterator getCapabilities(); - + /** * Obtain an iterator of all existing mime types. - * @return Returns an iterator for all existing Mime Types of type <code>MimeType</code> + * + * @return Returns an iterator for all existing Mime Types of type + * <code>MimeType</code> */ Iterator getMimeTypes(); - + /** * Obtain an iterator of all existing media types. - * @return Returns an iterator for all existing media types of type <code>MediaType</code> + * + * @return Returns an iterator for all existing media types of type + * <code>MediaType</code> */ Iterator getMediaTypes(); - /** - * Obtain the name of the CapabilityBean reference + * Obtain the name of the CapabilityBean reference + * * @return ref-id of the capability bean */ - public String getCapabilityBeanName(); + public String getCapabilityBeanName(); /** - * Set the name of the CapabilityBean reference - used exclusively in IoC - * @param capabilityBeanName The ref-id of the capability bean. + * Set the name of the CapabilityBean reference - used exclusively in IoC + * + * @param capabilityBeanName + * The ref-id of the capability bean. */ - public void setCapabilityBeanName(String capabilityBeanName); + public void setCapabilityBeanName(String capabilityBeanName); - /** - * Obtain the name of the ClientBean reference + * Obtain the name of the ClientBean reference + * * @return ref-id of the client bean */ - public String getClientBeanName(); + public String getClientBeanName(); /** - * Set the name of the ClientBean reference - used exclusively in IoC - * @param clientBeanName The ref-id of the client bean. + * Set the name of the ClientBean reference - used exclusively in IoC + * + * @param clientBeanName + * The ref-id of the client bean. */ - public void setClientBeanName(String clientBeanName); + public void setClientBeanName(String clientBeanName); /** - * Obtain the name of the Media Type reference + * Obtain the name of the Media Type reference + * * @return ref-id of the media type bean */ - public String getMediaTypeBeanName(); + public String getMediaTypeBeanName(); - /** - * Set the name of the MediaType bean reference - used exclusively in IoC - * @param mediaTypeBeanName The ref-id of the mediaType bean. + /** + * Set the name of the MediaType bean reference - used exclusively in IoC + * + * @param mediaTypeBeanName + * The ref-id of the mediaType bean. */ - public void setMediaTypeBeanName(String mediaTypeBeanName); + public void setMediaTypeBeanName(String mediaTypeBeanName); - /** - * Obtain the name of the Mime Type reference + /** + * Obtain the name of the Mime Type reference + * * @return ref-id of the mime type bean */ - public String getMimeTypeBeanName(); + public String getMimeTypeBeanName(); - /** - * Set the name of the MimeType bean reference - used exclusively in IoC - * @param mimeTypeBeanName The ref-id of the mimeType bean. + /** + * Set the name of the MimeType bean reference - used exclusively in IoC + * + * @param mimeTypeBeanName + * The ref-id of the mimeType bean. */ - public void setMimeTypeBeanName(String mimeTypeBeanName); - - - /** - * Create a new capability in the system or return the existing one if already exists - * @param capabilityName The string describing the capability + public void setMimeTypeBeanName(String mimeTypeBeanName); + + /** + * Create a new capability in the system or return the existing one if + * already exists + * + * @param capabilityName + * The string describing the capability * @return A new (or existing) capability - */ - public Capability createCapability(String capabilityName) throws ClassNotFoundException; - + */ + public Capability createCapability(String capabilityName) + throws ClassNotFoundException; - /** - * Create a new mimetype in the system or return the existing one if already exists - * @param mimeTypeName The string describing the mimeType + /** + * Create a new mimetype in the system or return the existing one if already + * exists + * + * @param mimeTypeName + * The string describing the mimeType * @return A new (or existing) MimeType - */ - public MimeType createMimeType(String mimeTypeName)throws ClassNotFoundException; + */ + public MimeType createMimeType(String mimeTypeName) + throws ClassNotFoundException; - /** - * Create a new mediaType in the system or return the existing one if already exists - * @param mediaTypeName The string describing the mediaType + /** + * Create a new mediaType in the system or return the existing one if + * already exists + * + * @param mediaTypeName + * The string describing the mediaType * @return A new (or existing) MediaType - */ - public MediaType createMediaType(String mediaTypeName)throws ClassNotFoundException; + */ + public MediaType createMediaType(String mediaTypeName) + throws ClassNotFoundException; - /** - * Create a new client in the system or return the existing one if already exists - * @param clientName The string describing the client + /** + * Create a new client in the system or return the existing one if already + * exists + * + * @param clientName + * The string describing the client * @return A new (or existing) client - */ - public Client createClient(String clientName)throws ClassNotFoundException; + */ + public Client createClient(String clientName) throws ClassNotFoundException; - - - /** + /** * Save media type to backend storage * - * @param mediaType valid mediatype object + * @param mediaType + * valid mediatype object */ - public void storeMediaType(MediaType mediaType) throws CapabilitiesException; - //TODO: change CapabilitiesException to better indicate cause - - /** + public void storeMediaType(MediaType mediaType) + throws CapabilitiesException; + + // TODO: change CapabilitiesException to better indicate cause + + /** * delete existing media type from backend storage * - * @param mediaType valid mediatype object + * @param mediaType + * valid mediatype object */ public void deleteMediaType(MediaType mediaType) throws CapabilitiesException; - - /** + /** * Save capability to backend storage * - * @param capability valid capability object + * @param capability + * valid capability object */ - public void storeCapability(Capability capability) throws CapabilitiesException; + public void storeCapability(Capability capability) + throws CapabilitiesException; /** * delete existing capability from backend storage * - * @param capability valid capability object + * @param capability + * valid capability object */ public void deleteCapability(Capability capability) throws CapabilitiesException; - /** + /** * Save mime type to backend storage * - * @param mimeType valid mimetype object + * @param mimeType + * valid mimetype object */ public void storeMimeType(MimeType mimeType) throws CapabilitiesException; - - /** + + /** * delete existing mime type from backend storage * - * @param mimeType valid mimetype object + * @param mimeType + * valid mimetype object */ - public void deleteMimeType(MimeType mimeType) - throws CapabilitiesException; + public void deleteMimeType(MimeType mimeType) throws CapabilitiesException; - - - /** + /** * Save client to backend storage * - * @param client valid Client object + * @param client + * valid Client object */ public void storeClient(Client client) throws CapabilitiesException; /** * delete existing client from backend storage * - * @param client valid client object + * @param client + * valid client object */ - public void deleteClient(Client client) - throws CapabilitiesException; + public void deleteClient(Client client) throws CapabilitiesException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/CapabilitiesException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/CapabilitiesException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/CapabilitiesException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,30 +20,31 @@ /** * CapabilitiesException - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ public class CapabilitiesException extends JetspeedException { - public CapabilitiesException() + + public CapabilitiesException() { super(); } - public CapabilitiesException( String message ) + public CapabilitiesException(String message) { - super( message ); + super(message); } public CapabilitiesException(Throwable nested) { super(nested); } - + public CapabilitiesException(String msg, Throwable nested) { super(msg, nested); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/Capability.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/Capability.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/Capability.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,12 +19,13 @@ /** * Capability class. - * + * * @author <a href="mailto:roger.ruttimann ¡÷ earthlink.net">Roger Ruttimann</a> * @version $Id: Capability.java 516448 2007-03-09 16:25:47Z ate $ */ public interface Capability { + /** * Set CapabilityId * Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/CapabilityMap.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/CapabilityMap.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/CapabilityMap.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,9 +19,9 @@ import java.util.Iterator; /** - * This interface provides lookup features on the capabilities supported - * by a client user agent. - * + * This interface provides lookup features on the capabilities supported by a + * client user agent. + * * @author <a href="mailto:raphael ¡÷ apache.org">Rapha\u00ebl Luta</a> * @author <a href="mailto:burton ¡÷ apache.org">Kevin A. Burton</a> * @version $Id: CapabilityMap.java 516448 2007-03-09 16:25:47Z ate $ @@ -31,36 +31,38 @@ /** * Sets the client for the CapabilityMap - * - * @param client The client associated with this map + * + * @param client + * The client associated with this map */ public void setClient(Client client); /** - * Returns the Client for the CapabilityMap - * + * Returns the Client for the CapabilityMap + * * @return The client associated with this map */ public Client getClient(); /** * Add capability to the CapabilityMap - * + * * @param capability */ public void addCapability(Capability capability); /** * Add Mimetype to the MimetypeMap - * + * * @param mimetype */ public void addMimetype(MimeType mimetype); /** * Add MediaType to the MediaTypeMap - * - * @param Mediatype to add + * + * @param Mediatype + * to add */ public void addMediaType(MediaType mediatype); @@ -76,13 +78,14 @@ /** * Sets the preferred MediaType for this CapabilityMap + * * @param MediaTypeEntry */ public void setPreferredMediaType(MediaType type); /** - * Returns an ordered list of supported media-types, from most preferred - * to least preferred + * Returns an ordered list of supported media-types, from most preferred to + * least preferred */ public Iterator listMediaTypes(); @@ -93,7 +96,7 @@ /** * @parm userAgent Agent from the request - * + * * Set the userAgent in the capabilityMap */ public void setAgent(String userAgent); @@ -112,24 +115,25 @@ /** * Get the mime types that this CapabilityMap supports. + * * @return Returns an Iterator over the MimeType map */ public Iterator getMimeTypes(); /** - * @param MimeType + * @param MimeType * @return Return true if this CapabilityMap supports the given MimeType */ public boolean supportsMimeType(MimeType mimeType); /** * Return true if this CapabilityMap supports the given media type - * - * @param media the name of a media type registered in the - * MediaType registry - * + * + * @param media + * the name of a media type registered in the MediaType registry + * * @return true is the capabilities of this agent at least match those - * required by the media type + * required by the media type */ public boolean supportsMediaType(String media); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/Client.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/Client.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/Client.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,98 +20,104 @@ /** * <P> - * The <CODE>ClientEntry</CODE> interface represents one client inside - * of the client registry. It is accessed by the portlet container - * to get information about the clients. + * The <CODE>ClientEntry</CODE> interface represents one client inside of the + * client registry. It is accessed by the portlet container to get information + * about the clients. * </P> - * + * * @author <a href="shesmer ¡÷ raleigh.ibm.com">Stephan Hesmer</a> * @author <a href="raphael ¡÷ apache.org">Rapha\u00ebl Luta</a> * @author <a href="mailto:roger.ruttimann ¡÷ earthlink.net">Roger Ruttimann</a> */ public interface Client { + /** * Set Client ID -- Assigns the Client ID + * * @param id */ public void setClientId(int id); /** * Get Client ID + * * @return Client ID */ public int getClientId(); public int getEvalOrder(); - + public void setEvalOrder(int evalOrder); - + /** - * Returns the pattern parameter of this client. The pattern is used - * to match a client to the user agent used to access the portal. If - * the pattern matches the user agent string, this client is recognized - * as the one the user is currently working with. - * + * Returns the pattern parameter of this client. The pattern is used to + * match a client to the user agent used to access the portal. If the + * pattern matches the user agent string, this client is recognized as the + * one the user is currently working with. + * * @return the pattern of this client */ public String getUserAgentPattern(); /** * Sets the pattern used to match the user agent. - * + * * @param useragentpattern - * the new pattern + * the new pattern */ public void setUserAgentPattern(String useragentpattern); /** * Returns the manufacturer of this client - * + * * @return the manufacturer of this client */ public String getManufacturer(); /** * Sets the new manufacturer of this client - * - * @param name the new manufacturer + * + * @param name + * the new manufacturer */ public void setManufacturer(String name); /** * Returns the model of this client - * + * * @return the model of this client */ public String getModel(); /** * Sets the new model of this client - * - * @param name the new model + * + * @param name + * the new model */ public void setModel(String name); /** * Returns the version of this client - * + * * @return the version of this client */ public String getVersion(); /** * Sets the new version of this client - * - * @param name the new version + * + * @param name + * the new version */ public void setVersion(String name); /** - * Returns all supported mimetypes as <CODE>MimeTypeMap</CODE>. - * The <CODE>MimeTypeMap</CODE> contains all mimetypes in decreasing - * order of importance. - * + * Returns all supported mimetypes as <CODE>MimeTypeMap</CODE>. The + * <CODE>MimeTypeMap</CODE> contains all mimetypes in decreasing order of + * importance. + * * @return the MimeTypeMap * @see MimeTypeMap */ @@ -119,18 +125,20 @@ /** * Set MimeTypes + * * @param mimetypes */ public void setMimetypes(Collection mimetypes); String getName(); + void setName(String name); /** - * Returns all supported capablities as <CODE>CapabilityMap</CODE>. - * The <CODE>CapabilityMap</CODE> contains all capabilities in arbitrary + * Returns all supported capablities as <CODE>CapabilityMap</CODE>. The + * <CODE>CapabilityMap</CODE> contains all capabilities in arbitrary * order. - * + * * @return the CapabilityMap * @see CapabilityMap */ @@ -138,19 +146,23 @@ /** * Assigns a list of capabilities + * * @param capabilities */ public void setCapabilities(Collection capabilities); /** * getPreferredMimeTypeId + * * @return mimeTypeId */ public int getPreferredMimeTypeId(); /** * setPreferredMimeTypeId - * @param mimeTypeId to be set as preferred mimeType + * + * @param mimeTypeId + * to be set as preferred mimeType */ public void setPreferredMimeTypeId(int mimeTypeId); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/MediaType.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/MediaType.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/MediaType.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,25 +19,28 @@ import java.util.Collection; /** - * This entry describes all the properties that should be present in - * a RegistryEntry describing a MediaType - * - * FIXME: we should add some additionnal attrbutes for separating 2 versions - * of the same mime type - * + * This entry describes all the properties that should be present in a + * RegistryEntry describing a MediaType + * + * FIXME: we should add some additionnal attrbutes for separating 2 versions of + * the same mime type + * * @author <a href="mailto:raphael ¡÷ apache.org">Rapha\u00ebl Luta</a> * @version $Id: MediaType.java 517121 2007-03-12 07:45:49Z ate $ */ public interface MediaType { + /** * Set MediaType ID -- Assigns ID + * * @param id */ public void setMediatypeId(int id); /** * Get MediaType ID -- Return ID + * * @return MediaTypeID */ public int getMediatypeId(); @@ -49,97 +52,112 @@ public void setCharacterSet(String charSet); /** - * Returns all supported capablities as <CODE>CapabilityMap</CODE>. - * The <CODE>CapabilityMap</CODE> contains all capabilities in arbitrary + * Returns all supported capablities as <CODE>CapabilityMap</CODE>. The + * <CODE>CapabilityMap</CODE> contains all capabilities in arbitrary * order. - * + * * @return a collection of capabilities */ public Collection getCapabilities(); /** * Set the capabilities - * @param vector of capabilities + * + * @param vector + * of capabilities */ public void setCapabilities(Collection capabilities); /** - * Returns all supported mimetypes as <CODE>MimeTypeMap</CODE>. - * The <CODE>MimeTypeMap</CODE> contains all mimetypes in decreasing - * order of importance. - * - * @return the MimeTypeMap - * @see MimeTypeMap - */ + * Returns all supported mimetypes as <CODE>MimeTypeMap</CODE>. The + * <CODE>MimeTypeMap</CODE> contains all mimetypes in decreasing order of + * importance. + * + * @return the MimeTypeMap + * @see MimeTypeMap + */ public Collection getMimetypes(); /** * Set mime types + * * @param mimetypes */ public void setMimetypes(Collection mimetypes); /** - * Removes the MimeType to the MimeType map - * @param name of MimeType to remove + * Removes the MimeType to the MimeType map + * + * @param name + * of MimeType to remove */ public void removeMimetype(String name); /** - * Add MimeType to the MimeType map + * Add MimeType to the MimeType map + * * @param name - - public void addMimetype(String name); - */ + * + * public void addMimetype(String name); + */ /** - * Add MimeType to the MimeType map - * @param mimeType mimetype object to add - */ + * Add MimeType to the MimeType map + * + * @param mimeType + * mimetype object to add + */ public void addMimetype(MimeType mimeType); - - + /** - * Add Capability to the Capability collection - * @param capability capability object to add - */ + * Add Capability to the Capability collection + * + * @param capability + * capability object to add + */ public void addCapability(Capability capability); - - - + /** * Set Name of MediaType - * @param name Name of MediaType + * + * @param name + * Name of MediaType */ public void setName(String name); /** * Get Name of MediaType + * * @return Name of MediaType */ public String getName(); /** * Get Title of MediaType + * * @return Title of MediaType */ public String getTitle(); /** * Set MediaType title + * * @param title */ public void setTitle(String title); /** * Get MediaType description + * * @return Returns description of MediaType */ public String getDescription(); /** * Set description of MediaType - * @param desc Description string + * + * @param desc + * Description string */ public void setDescription(String desc); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/MimeType.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/MimeType.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/MimeType.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,37 +18,38 @@ /** * MimeType - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: MimeType.java 516448 2007-03-09 16:25:47Z ate $ */ public interface MimeType { + /** * Set MimetypeId * * @param id */ public void setMimetypeId(int id); - + /** * Get CapabilityId * * @return capabilityId */ public int getMimetypeId(); - + /** * Set Capability name * * @param name */ public void setName(String name); - + /** * Get CapabilityId * * @return capability string */ - public String getName(); + public String getName(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/UnableToBuildCapabilityMapException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/UnableToBuildCapabilityMapException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/capabilities/UnableToBuildCapabilityMapException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,11 +23,13 @@ * UnableToBuildCapabilityMapException * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: UnableToBuildCapabilityMapException.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: UnableToBuildCapabilityMapException.java 516448 2007-03-09 + * 16:25:47Z ate $ + * */ public class UnableToBuildCapabilityMapException extends JetspeedException { @@ -44,7 +46,7 @@ /** * @param message */ - public UnableToBuildCapabilityMapException( String message ) + public UnableToBuildCapabilityMapException(String message) { super(message); // TODO Auto-generated constructor stub @@ -53,7 +55,7 @@ /** * @param nested */ - public UnableToBuildCapabilityMapException( Throwable nested ) + public UnableToBuildCapabilityMapException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -63,7 +65,7 @@ * @param msg * @param nested */ - public UnableToBuildCapabilityMapException( String msg, Throwable nested ) + public UnableToBuildCapabilityMapException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cluster/NodeInformation.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cluster/NodeInformation.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cluster/NodeInformation.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,70 +17,74 @@ package org.apache.jetspeed.cluster; import java.util.Date; + import org.apache.pluto.om.common.ObjectID; /** * Node Information Interface - * + * * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> - * @version + * @version */ public interface NodeInformation { - /** - * Getter for ContextName - * @return - */ - public String getContextName(); - /** - * setter for context name - * - * @param id - */ - public void setContextName(String contextName); + /** + * Getter for ContextName + * + * @return + */ + public String getContextName(); - - /** - * Getter for ObjectID - * @return - */ - public Long getId(); + /** + * setter for context name + * + * @param id + */ + public void setContextName(String contextName); - /** - * setter for ObjectID - * - * @param id - */ - public void setId(ObjectID id); + /** + * Getter for ObjectID + * + * @return + */ + public Long getId(); - /** - * setter for ObjectID - * - * @param id - */ - public void setId(Long id); - /** - * setter for ObjectID - * - * @param id - */ - public void setId(long id); + /** + * setter for ObjectID + * + * @param id + */ + public void setId(ObjectID id); - /** - * Getter for Last Deploy Date - * @return - */ - public Date getLastDeployDate(); + /** + * setter for ObjectID + * + * @param id + */ + public void setId(Long id); + /** + * setter for ObjectID + * + * @param id + */ + public void setId(long id); - /** - * setter for last deploy date - * - * @param id - */ - public void setLastDeployDate(Date lastDeployDate); - - public String toString (); + /** + * Getter for Last Deploy Date + * + * @return + */ + public Date getLastDeployDate(); + + /** + * setter for last deploy date + * + * @param id + */ + public void setLastDeployDate(Date lastDeployDate); + + public String toString(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cluster/NodeManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cluster/NodeManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/cluster/NodeManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,48 +18,56 @@ /** * Node Manager Interface - * + * * @author <a href="mailto:hajo ¡÷ bluesunrise.com">Hajo Birthelmer</a> - * @version + * @version */ public interface NodeManager { - public static final int INVALID_NODE_REQUEST = -1; - public static final int NODE_SAVED = 0; - public static final int NODE_OUTDATED = 1; - public static final int NODE_NEW = 2; + public static final int INVALID_NODE_REQUEST = -1; - /** - * Returns the current "knowledge" about a given node (i.e. the portlet application). - * If the contextName doesn't exist NODE_NEW is returned. - * An id requested newer than what is stored is indicated by NODE_OUTDATED. - * @param id - * @param contextName - * @return - */ - public int checkNode(Long id, String contextName); + public static final int NODE_SAVED = 0; - /** - * Add a new node or update the id of an existing one...(i.e. the portlet application) to the local info - * @param id - * @param contextName - * @throws Exception - */ - public void addNode(Long id, String contextName) throws Exception; + public static final int NODE_OUTDATED = 1; - /** - * return the number of currently stored nodes - * @return - */ - public int getNumberOfNodes(); + public static final int NODE_NEW = 2; - /** - * Remove a node - * @param id - * @param contextName - * @throws Exception - */ - public void removeNode(String contextName) throws Exception; + /** + * Returns the current "knowledge" about a given node (i.e. the portlet + * application). If the contextName doesn't exist NODE_NEW is returned. An + * id requested newer than what is stored is indicated by NODE_OUTDATED. + * + * @param id + * @param contextName + * @return + */ + public int checkNode(Long id, String contextName); + /** + * Add a new node or update the id of an existing one...(i.e. the portlet + * application) to the local info + * + * @param id + * @param contextName + * @throws Exception + */ + public void addNode(Long id, String contextName) throws Exception; + + /** + * return the number of currently stored nodes + * + * @return + */ + public int getNumberOfNodes(); + + /** + * Remove a node + * + * @param id + * @param contextName + * @throws Exception + */ + public void removeNode(String contextName) throws Exception; + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/ComponentManagement.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/ComponentManagement.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/ComponentManagement.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,15 +18,16 @@ /** * ComponentManagement - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: ComponentManagement.java 225607 2005-07-27 20:25:36Z weaver $ */ public interface ComponentManagement { + Object getComponent(Object componentName); - + Object getComponent(Object containerName, Object componentName); - - void addComponent(String name, Object bean); + + void addComponent(String name, Object bean); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/ComponentManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/ComponentManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/ComponentManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,13 +21,15 @@ * ComponentManager * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: ComponentManager.java 187034 2004-07-20 13:42:06Z weaver $ - * + * */ -public interface ComponentManager extends ComponentManagement, ContainerManagement +public interface ComponentManager extends ComponentManagement, + ContainerManagement { } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/ContainerManagement.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/ContainerManagement.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/ContainerManagement.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,19 +20,20 @@ /** * ContainerManagement - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: ContainerManagement.java 225607 2005-07-27 20:25:36Z weaver $ */ public interface ContainerManagement -{ +{ + Object getContainer(String containerName); - + Object getRootContainer(); - + Collection getContainers(); - + void stop(); - - void start(); + + void start(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/Filter.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/Filter.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/Filter.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,88 +21,92 @@ /** * <p> * Filter - * </p> - * - * - * @ + * </p> @ * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $ $ - * + * */ public interface Filter { - /** - * @see org.apache.ojb.broker.query.Criteria#addBetween(java.lang.String, java.lang.Object, java.lang.Object) - */ - public abstract void addBetween(String arg0, Object arg1, Object arg2); - /** - * @see org.apache.ojb.broker.query.Criteria#addEqualTo(java.lang.String, java.lang.Object) - */ - public abstract void addEqualTo(String arg0, Object arg1); + /** + * @see org.apache.ojb.broker.query.Criteria#addBetween(java.lang.String, + * java.lang.Object, java.lang.Object) + */ + public abstract void addBetween(String arg0, Object arg1, Object arg2); - /** - * @see org.apache.ojb.broker.query.Criteria#addGreaterOrEqualThan(java.lang.String, java.lang.Object) - */ - public abstract void addGreaterOrEqualThan(String arg0, Object arg1); + /** + * @see org.apache.ojb.broker.query.Criteria#addEqualTo(java.lang.String, + * java.lang.Object) + */ + public abstract void addEqualTo(String arg0, Object arg1); - /** - * @see org.apache.ojb.broker.query.Criteria#addGreaterThan(java.lang.String, java.lang.Object) - */ - public abstract void addGreaterThan(String arg0, Object arg1); + /** + * @see org.apache.ojb.broker.query.Criteria#addGreaterOrEqualThan(java.lang.String, + * java.lang.Object) + */ + public abstract void addGreaterOrEqualThan(String arg0, Object arg1); - /** - * @see org.apache.ojb.broker.query.Criteria#addIn(java.lang.String, java.util.Collection) - */ - public abstract void addIn(String attribute, Collection values); + /** + * @see org.apache.ojb.broker.query.Criteria#addGreaterThan(java.lang.String, + * java.lang.Object) + */ + public abstract void addGreaterThan(String arg0, Object arg1); - /** - * @see org.apache.ojb.broker.query.Criteria#addLessOrEqualThan(java.lang.String, java.lang.Object) - */ - public abstract void addLessOrEqualThan(String arg0, Object arg1); + /** + * @see org.apache.ojb.broker.query.Criteria#addIn(java.lang.String, + * java.util.Collection) + */ + public abstract void addIn(String attribute, Collection values); - /** - * @see org.apache.ojb.broker.query.Criteria#addLike(java.lang.Object, java.lang.Object) - */ - public abstract void addLike(Object arg0, Object arg1); + /** + * @see org.apache.ojb.broker.query.Criteria#addLessOrEqualThan(java.lang.String, + * java.lang.Object) + */ + public abstract void addLessOrEqualThan(String arg0, Object arg1); - /** - * @see org.apache.ojb.broker.query.Criteria#addNotBetween(java.lang.String, java.lang.Object, java.lang.Object) - */ - public abstract void addNotBetween(String arg0, Object arg1, Object arg2); + /** + * @see org.apache.ojb.broker.query.Criteria#addLike(java.lang.Object, + * java.lang.Object) + */ + public abstract void addLike(Object arg0, Object arg1); - /** - * @see org.apache.ojb.broker.query.Criteria#addNotEqualTo(java.lang.String, java.lang.Object) - */ - public abstract void addNotEqualTo(String arg0, Object arg1); + /** + * @see org.apache.ojb.broker.query.Criteria#addNotBetween(java.lang.String, + * java.lang.Object, java.lang.Object) + */ + public abstract void addNotBetween(String arg0, Object arg1, Object arg2); - /** - * @see org.apache.ojb.broker.query.Criteria#addNotLike(java.lang.String, java.lang.Object) - */ - public abstract void addNotLike(String arg0, Object arg1); + /** + * @see org.apache.ojb.broker.query.Criteria#addNotEqualTo(java.lang.String, + * java.lang.Object) + */ + public abstract void addNotEqualTo(String arg0, Object arg1); - /** - * @see org.apache.ojb.broker.query.Criteria#addNotNull(java.lang.String) - */ - public abstract void addNotNull(String arg0); + /** + * @see org.apache.ojb.broker.query.Criteria#addNotLike(java.lang.String, + * java.lang.Object) + */ + public abstract void addNotLike(String arg0, Object arg1); - /** - * @see org.apache.ojb.broker.query.Criteria#addOrCriteria(org.apache.ojb.broker.query.Criteria) - */ - public abstract void addOrFilter(Filter arg0); + /** + * @see org.apache.ojb.broker.query.Criteria#addNotNull(java.lang.String) + */ + public abstract void addNotNull(String arg0); - /** - * @see org.apache.ojb.broker.query.Criteria#addOrderByAscending(java.lang.String) - */ - public abstract void addOrderByAscending(String arg0); + /** + * @see org.apache.ojb.broker.query.Criteria#addOrCriteria(org.apache.ojb.broker.query.Criteria) + */ + public abstract void addOrFilter(Filter arg0); - /** - * @see org.apache.ojb.broker.query.Criteria#addOrderByDescending(java.lang.String) - */ - public abstract void addOrderByDescending(String arg0); + /** + * @see org.apache.ojb.broker.query.Criteria#addOrderByAscending(java.lang.String) + */ + public abstract void addOrderByAscending(String arg0); + /** + * @see org.apache.ojb.broker.query.Criteria#addOrderByDescending(java.lang.String) + */ + public abstract void addOrderByDescending(String arg0); - - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/LockFailedException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/LockFailedException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/LockFailedException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,17 +18,13 @@ import org.apache.jetspeed.exception.JetspeedException; - /** * <p> * LockFailedException - * </p> - * - * - * @ + * </p> @ * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $ $ - * + * */ public class LockFailedException extends JetspeedException { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStore.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStore.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStore.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,91 +19,86 @@ import java.util.Collection; import java.util.Iterator; -import org.apache.jetspeed.components.persistence.store.LockFailedException; - /** * <p> * PersistenceStore * </p> * * <p> - * The persistence store allows access to the persistent - * storage mechanism within the application. - * <br/> - * PersistenceStore instances <strong>ARE NOT</strong> - * thread safe. The best practices approach for using - * the persistence store is to use - * <code>PersistenceStoreContainer.getStoreForThread()</code> - * any time the store is to be accessed. - * - * </p> + * The persistence store allows access to the persistent storage mechanism + * within the application. <br/> PersistenceStore instances <strong>ARE NOT</strong> + * thread safe. The best practices approach for using the persistence store is + * to use <code>PersistenceStoreContainer.getStoreForThread()</code> any time + * the store is to be accessed. * - * @ + * </p> @ * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $ $ - * + * */ public interface PersistenceStore { - /** + + /** * No lock at all aka the object is read only changes WILL NOT be persisted * at checkPoints or commits. */ int LOCK_NO_LOCK = 0; - /** - * changes to the object will be written to the database, in this case the lock - * will be automatically upgraded to the write lock on transaction + /** + * changes to the object will be written to the database, in this case the + * lock will be automatically upgraded to the write lock on transaction */ int LOCK_READ = 1; /** - * changes to the object will be written to the database. + * changes to the object will be written to the database. */ int LOCK_PESSIMISTIC = 2; - - void addEventListener(PersistenceStoreEventListener listener); - + + void addEventListener(PersistenceStoreEventListener listener); + void close(); void deletePersistent(Object obj) throws LockFailedException; - - void deleteAll(Object query) throws LockFailedException; + void deleteAll(Object query) throws LockFailedException; + Collection getCollectionByQuery(Object query); Collection getCollectionByQuery(Object query, int lockLevel); - - Object getObjectByQuery(Object query); - Object getObjectByQuery(Object query, int lockLevel); - - Object getObjectByIdentity(Object object) throws LockFailedException; + Object getObjectByQuery(Object query); - Object getObjectByIdentity(Object object, int lockLevel) throws LockFailedException; + Object getObjectByQuery(Object query, int lockLevel); + Object getObjectByIdentity(Object object) throws LockFailedException; + + Object getObjectByIdentity(Object object, int lockLevel) + throws LockFailedException; + int getCount(Object query); - Iterator getIteratorByQuery(Object query) ; + Iterator getIteratorByQuery(Object query); Iterator getIteratorByQuery(Object query, int lockLevel); - + /** * * <p> * isClosed * </p> * <p> - * indicates whether or not this <code>PersistenceStore</code> - * instance has been closed. A closed store will generally - * throw exceptions when any operation is performed upon it. + * indicates whether or not this <code>PersistenceStore</code> instance + * has been closed. A closed store will generally throw exceptions when any + * operation is performed upon it. * </p> * * @return - * + * */ boolean isClosed(); - + /** * * <p> @@ -111,35 +106,34 @@ * </p> * <p> * Returns the current <code>Transaction</code> for thsis - * <code>PersistenceStore</code> instance. The transaction - * will always be the same for the lifetime of the - * <code>PersistenceStore</code> instance. + * <code>PersistenceStore</code> instance. The transaction will always be + * the same for the lifetime of the <code>PersistenceStore</code> + * instance. * </p> * - * @return <code>Transaction</code> for this - * <code>PersistenceStore</code> - * + * @return <code>Transaction</code> for this <code>PersistenceStore</code> + * */ Transaction getTransaction(); - + void invalidate(Object obj) throws LockFailedException; - + void invalidateAll() throws LockFailedException; - + void invalidateExtent(Class clazz) throws LockFailedException; - - void invalidateByQuery(Object query) throws LockFailedException; - + + void invalidateByQuery(Object query) throws LockFailedException; + void lockForWrite(Object obj) throws LockFailedException; - + void makePersistent(Object obj) throws LockFailedException; - + Filter newFilter(); - + Object newQuery(Class clazz, Filter filter); - + Collection getExtent(Class clazz); - - Collection getExtent(Class clazz, int lockLevel); + Collection getExtent(Class clazz, int lockLevel); + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreAware.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreAware.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreAware.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,23 +21,24 @@ * PersistenceStoreAware * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: PersistenceStoreAware.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface PersistenceStoreAware { + /** - * - * <p> - * getPersistenceStore - * </p> - * - * @return the PersistenceStore sued to persist registry - * information. - * - */ + * + * <p> + * getPersistenceStore + * </p> + * + * @return the PersistenceStore sued to persist registry information. + * + */ PersistenceStore getPersistenceStore(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreEvent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreEvent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreEvent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,17 +19,15 @@ /** * <p> * PersistenceStoreEvent - * </p> - * - * - * @ + * </p> @ * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $ $ - * + * */ public interface PersistenceStoreEvent extends TransactionEvent { - PersistenceStore getPersistenceStore(); - - Object getTarget(); + + PersistenceStore getPersistenceStore(); + + Object getTarget(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreEventListener.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreEventListener.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreEventListener.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,16 +19,14 @@ /** * <p> * PersistenceStoreEventListener - * </p> - * - * - * @ + * </p> @ * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $ $ - * + * */ public interface PersistenceStoreEventListener extends TransactionEventListener { + void afterLookup(PersistenceStoreEvent event); void beforeLookup(PersistenceStoreEvent event); @@ -40,9 +38,9 @@ void afterMakePersistent(PersistenceStoreEvent event); void beforeMakePersistent(PersistenceStoreEvent event); - + void beforeClose(PersistenceStoreEvent event); - - void afterClose(PersistenceStoreEvent event); + void afterClose(PersistenceStoreEvent event); + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreInitializationException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreInitializationException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreInitializationException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,13 +19,10 @@ /** * <p> * PersistenceStoreInitializationException - * </p> - * - * - * @ + * </p> @ * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $ $ - * + * */ public class PersistenceStoreInitializationException extends Exception { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreRuntimeExcpetion.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreRuntimeExcpetion.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/PersistenceStoreRuntimeExcpetion.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,9 +21,9 @@ /** * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * - * Thrown when an unexpected problem arises while performing a - * persistence operation. - * + * Thrown when an unexpected problem arises while performing a persistence + * operation. + * */ public class PersistenceStoreRuntimeExcpetion extends JetspeedRuntimeException { @@ -39,7 +39,7 @@ /** * @param message */ - public PersistenceStoreRuntimeExcpetion( String message ) + public PersistenceStoreRuntimeExcpetion(String message) { super(message); } @@ -47,7 +47,7 @@ /** * @param nested */ - public PersistenceStoreRuntimeExcpetion( Throwable nested ) + public PersistenceStoreRuntimeExcpetion(Throwable nested) { super(nested); } @@ -56,7 +56,7 @@ * @param msg * @param nested */ - public PersistenceStoreRuntimeExcpetion( String msg, Throwable nested ) + public PersistenceStoreRuntimeExcpetion(String msg, Throwable nested) { super(msg, nested); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/RemovalAware.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/RemovalAware.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/RemovalAware.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,15 +17,16 @@ package org.apache.jetspeed.components.persistence.store; /** - *@author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * - * Classes implementing this interface can specificy operations - * performed before and after removal operations via the PersistenceStore. - * + * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> + * + * Classes implementing this interface can specificy operations performed before + * and after removal operations via the PersistenceStore. + * */ public interface RemovalAware { + void preRemoval(PersistenceStore store); - + void postRemoval(PersistenceStore store); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/Transaction.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/Transaction.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/Transaction.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,28 +19,26 @@ /** * <p> * Transaction - * </p> - * - * - * @ + * </p> @ * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $ $ - * + * */ public interface Transaction { - void begin(); - - void commit(); - - void rollback(); - - void checkpoint(); - - boolean isOpen(); - - Object getWrappedTransaction(); - - void addEventListener(TransactionEventListener listener); + void begin(); + + void commit(); + + void rollback(); + + void checkpoint(); + + boolean isOpen(); + + Object getWrappedTransaction(); + + void addEventListener(TransactionEventListener listener); + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/TransactionEvent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/TransactionEvent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/TransactionEvent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,15 +19,13 @@ /** * <p> * TransactionEvent - * </p> - * - * - * @ + * </p> @ * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $ $ - * + * */ public interface TransactionEvent { - Transaction getTransaction(); + + Transaction getTransaction(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/TransactionEventListener.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/TransactionEventListener.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/TransactionEventListener.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,16 +19,14 @@ /** * <p> * TransactionEventListener - * </p> - * - * - * @ + * </p> @ * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $ $ - * + * */ public interface TransactionEventListener { + void afterCommit(PersistenceStoreEvent event); void beforeCommit(PersistenceStoreEvent event); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/UpdateAware.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/UpdateAware.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/persistence/store/UpdateAware.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,15 +17,16 @@ package org.apache.jetspeed.components.persistence.store; /** - *@author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * - * Classes implementing this interface can specificy operations - * performed before and after update operations via the PersistenceStore. - * + * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> + * + * Classes implementing this interface can specificy operations performed before + * and after update operations via the PersistenceStore. + * */ public interface UpdateAware { + void preUpdate(PersistenceStore store); - + void postUpdate(PersistenceStore store); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityAccessComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityAccessComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityAccessComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,177 +33,191 @@ * </p> * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: PortletEntityAccessComponent.java,v 1.8 2005/04/29 13:59:46 weaver Exp $ - * + * @version $Id: PortletEntityAccessComponent.java,v 1.8 2005/04/29 13:59:46 + * weaver Exp $ + * */ public interface PortletEntityAccessComponent { + /** * * <p> * getPortletEntity * </p> - * + * * @param id * @return */ - MutablePortletEntity getPortletEntity(ObjectID id); - + MutablePortletEntity getPortletEntity(ObjectID id); + MutablePortletEntity getPortletEntity(String id); - - /** - * - * <p> - * generateEntityFromFragment - * </p> - * - * @param fragment - * @param principal - * @return - * @throws PortletEntityNotGeneratedException - */ - MutablePortletEntity generateEntityFromFragment(ContentFragment fragment, String principal) throws PortletEntityNotGeneratedException; - - /** - * - * <p> - * generateEntityFromFragment - * </p> - * - * @param fragment - * @return - * @throws PortletEntityNotGeneratedException - */ - MutablePortletEntity generateEntityFromFragment(ContentFragment fragment) throws PortletEntityNotGeneratedException; - - /** - * - * <p> - * generateEntityKey - * </p> - * - * @param fragment - * @param principal - * @return - */ - ObjectID generateEntityKey(Fragment fragment, String principal); - /** - * - * <p> - * newPortletEntityInstance - * </p> - * - * @param portletDefinition - * @return - */ - MutablePortletEntity newPortletEntityInstance(PortletDefinition portletDefinition); - MutablePortletEntity newPortletEntityInstance(PortletDefinition portletDefinition, String id); - - /** - * - * <p> - * getPortletEntityForFragment - * </p> - * - * @param fragment - * @param principal - * @return - * @throws PortletEntityNotStoredException - */ - MutablePortletEntity getPortletEntityForFragment(ContentFragment fragment, String principal) throws PortletEntityNotStoredException; - - /** - * - * <p> - * getPortletEntityForFragment - * </p> - * - * @param fragment - * @return - * @throws PortletEntityNotStoredException - */ - MutablePortletEntity getPortletEntityForFragment(ContentFragment fragment) throws PortletEntityNotStoredException; - - /** - * - * <p> - * removePortletEntity - * </p> - * - * @param portletEntity - * @throws PortletEntityNotDeletedException - */ - void removePortletEntity(PortletEntity portletEntity) throws PortletEntityNotDeletedException; - - /** - * - * <p> - * removeFromCache - * </p> - * Removes a PortletEntity from the cache. - * @param entity - */ - void removeFromCache(PortletEntity entity); + /** + * + * <p> + * generateEntityFromFragment + * </p> + * + * @param fragment + * @param principal + * @return + * @throws PortletEntityNotGeneratedException + */ + MutablePortletEntity generateEntityFromFragment(ContentFragment fragment, + String principal) throws PortletEntityNotGeneratedException; /** + * * <p> + * generateEntityFromFragment + * </p> + * + * @param fragment + * @return + * @throws PortletEntityNotGeneratedException + */ + MutablePortletEntity generateEntityFromFragment(ContentFragment fragment) + throws PortletEntityNotGeneratedException; + + /** + * + * <p> + * generateEntityKey + * </p> + * + * @param fragment + * @param principal + * @return + */ + ObjectID generateEntityKey(Fragment fragment, String principal); + + /** + * + * <p> + * newPortletEntityInstance + * </p> + * + * @param portletDefinition + * @return + */ + MutablePortletEntity newPortletEntityInstance( + PortletDefinition portletDefinition); + + MutablePortletEntity newPortletEntityInstance( + PortletDefinition portletDefinition, String id); + + /** + * + * <p> + * getPortletEntityForFragment + * </p> + * + * @param fragment + * @param principal + * @return + * @throws PortletEntityNotStoredException + */ + MutablePortletEntity getPortletEntityForFragment(ContentFragment fragment, + String principal) throws PortletEntityNotStoredException; + + /** + * + * <p> + * getPortletEntityForFragment + * </p> + * + * @param fragment + * @return + * @throws PortletEntityNotStoredException + */ + MutablePortletEntity getPortletEntityForFragment(ContentFragment fragment) + throws PortletEntityNotStoredException; + + /** + * + * <p> + * removePortletEntity + * </p> + * + * @param portletEntity + * @throws PortletEntityNotDeletedException + */ + void removePortletEntity(PortletEntity portletEntity) + throws PortletEntityNotDeletedException; + + /** + * + * <p> + * removeFromCache + * </p> + * Removes a PortletEntity from the cache. + * + * @param entity + */ + void removeFromCache(PortletEntity entity); + + /** + * <p> * updatePortletEntity * </p> - * - * Updates portlet definition associated with the portlet - * entity to match the fragment configuration - * + * + * Updates portlet definition associated with the portlet entity to match + * the fragment configuration + * * @param portletEntity - * @param fragment - * @throws PortletEntityNotStoredException + * @param fragment + * @throws PortletEntityNotStoredException */ - void updatePortletEntity(PortletEntity portletEntity, ContentFragment fragment) throws PortletEntityNotStoredException; + void updatePortletEntity(PortletEntity portletEntity, + ContentFragment fragment) throws PortletEntityNotStoredException; /** * * <p> * storePortletEntity * </p> - * + * * @param portletEntity * @throws PortletEntityNotStoredException */ - void storePortletEntity(PortletEntity portletEntity) throws PortletEntityNotStoredException; - - /** - * - * <p> - * getPortletEntities - * </p> - * - * @param portletDefinition - * @return - */ - Collection getPortletEntities(PortletDefinition portletDefinition); - - Collection getPortletEntities( String portletUniqueName ); - - /** - * - * <p> - * removePortletEntities - * </p> - * - * @param portletDefinition - * @throws PortletEntityNotDeletedException - */ - void removePortletEntities(PortletDefinition portletDefinition) throws PortletEntityNotDeletedException; - - - void storePreferenceSet(PreferenceSet prefSet, PortletEntity entity) throws IOException; + void storePortletEntity(PortletEntity portletEntity) + throws PortletEntityNotStoredException; - /** - * All preferences were shared. With JS2-449, preferences are now - * stored 'per user'. The username is stored in the preferences FULL_PATH - * To turn on mergeSharedPreferences configure this property to true - * in your Spring configuration. This will NOT turn off per user prefs, - * but instead merge with them, where user prefs override. - */ + /** + * + * <p> + * getPortletEntities + * </p> + * + * @param portletDefinition + * @return + */ + Collection getPortletEntities(PortletDefinition portletDefinition); + + Collection getPortletEntities(String portletUniqueName); + + /** + * + * <p> + * removePortletEntities + * </p> + * + * @param portletDefinition + * @throws PortletEntityNotDeletedException + */ + void removePortletEntities(PortletDefinition portletDefinition) + throws PortletEntityNotDeletedException; + + void storePreferenceSet(PreferenceSet prefSet, PortletEntity entity) + throws IOException; + + /** + * All preferences were shared. With JS2-449, preferences are now stored + * 'per user'. The username is stored in the preferences FULL_PATH To turn + * on mergeSharedPreferences configure this property to true in your Spring + * configuration. This will NOT turn off per user prefs, but instead merge + * with them, where user prefs override. + */ boolean isMergeSharedPreferences(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityNotDeletedException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityNotDeletedException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityNotDeletedException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /** * Created on Nov 26, 2003 * @@ -30,8 +30,9 @@ * </p> * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: PortletEntityNotDeletedException.java 516881 2007-03-11 10:34:21Z ate $ - * + * @version $Id: PortletEntityNotDeletedException.java 516881 2007-03-11 + * 10:34:21Z ate $ + * */ public class PortletEntityNotDeletedException extends JetspeedException { @@ -41,7 +42,7 @@ */ public PortletEntityNotDeletedException() { - super(); + super(); } /** @@ -49,7 +50,7 @@ */ public PortletEntityNotDeletedException(String message) { - super(message); + super(message); } /** @@ -57,7 +58,7 @@ */ public PortletEntityNotDeletedException(Throwable nested) { - super(nested); + super(nested); } /** @@ -66,7 +67,7 @@ */ public PortletEntityNotDeletedException(String msg, Throwable nested) { - super(msg, nested); + super(msg, nested); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityNotGeneratedException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityNotGeneratedException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityNotGeneratedException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,9 +17,10 @@ package org.apache.jetspeed.components.portletentity; /** - * + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: PortletEntityNotGeneratedException.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: PortletEntityNotGeneratedException.java 516448 2007-03-09 + * 16:25:47Z ate $ */ public class PortletEntityNotGeneratedException extends Exception @@ -37,7 +38,7 @@ /** * @param arg0 */ - public PortletEntityNotGeneratedException( String arg0 ) + public PortletEntityNotGeneratedException(String arg0) { super(arg0); // TODO Auto-generated constructor stub @@ -46,7 +47,7 @@ /** * @param arg0 */ - public PortletEntityNotGeneratedException( Throwable arg0 ) + public PortletEntityNotGeneratedException(Throwable arg0) { super(arg0); // TODO Auto-generated constructor stub @@ -56,7 +57,7 @@ * @param arg0 * @param arg1 */ - public PortletEntityNotGeneratedException( String arg0, Throwable arg1 ) + public PortletEntityNotGeneratedException(String arg0, Throwable arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityNotStoredException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityNotStoredException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletentity/PortletEntityNotStoredException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,8 +24,9 @@ * </p> * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: PortletEntityNotStoredException.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: PortletEntityNotStoredException.java 516448 2007-03-09 + * 16:25:47Z ate $ + * */ public class PortletEntityNotStoredException extends JetspeedException { @@ -35,7 +36,7 @@ */ public PortletEntityNotStoredException() { - super(); + super(); } /** @@ -43,7 +44,7 @@ */ public PortletEntityNotStoredException(String message) { - super(message); + super(message); } /** @@ -51,7 +52,7 @@ */ public PortletEntityNotStoredException(Throwable nested) { - super(nested); + super(nested); } /** @@ -60,7 +61,7 @@ */ public PortletEntityNotStoredException(String msg, Throwable nested) { - super(msg, nested); + super(msg, nested); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/FailedToStorePortletDefinitionException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/FailedToStorePortletDefinitionException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/FailedToStorePortletDefinitionException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /* * Created on Oct 22, 2004 * @@ -29,11 +29,13 @@ * FailedToStorePortletDefinitionException * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: FailedToStorePortletDefinitionException.java 516881 2007-03-11 10:34:21Z ate $ - * + * @version $Id: FailedToStorePortletDefinitionException.java 516881 2007-03-11 + * 10:34:21Z ate $ + * */ public class FailedToStorePortletDefinitionException extends RegistryException { @@ -44,46 +46,50 @@ public FailedToStorePortletDefinitionException() { super(); - + } /** * @param message */ - public FailedToStorePortletDefinitionException( String message ) + public FailedToStorePortletDefinitionException(String message) { super(message); - + } /** * @param nested */ - public FailedToStorePortletDefinitionException( Throwable nested ) + public FailedToStorePortletDefinitionException(Throwable nested) { super(nested); - + } /** * @param msg * @param nested */ - public FailedToStorePortletDefinitionException( String msg, Throwable nested ) + public FailedToStorePortletDefinitionException(String msg, Throwable nested) { super(msg, nested); - + } - - public FailedToStorePortletDefinitionException( PortletDefinition portlet, Throwable nested ) - { - this("Unable to store portlet definition "+portlet.getName()+". Reason: "+nested.toString(), nested); - + + public FailedToStorePortletDefinitionException(PortletDefinition portlet, + Throwable nested) + { + this("Unable to store portlet definition " + portlet.getName() + + ". Reason: " + nested.toString(), nested); + } - - public FailedToStorePortletDefinitionException( PortletDefinition portlet, String reason ) - { - this("Unable to store portlet definition "+portlet.getName()+". Resaon: "+reason); + + public FailedToStorePortletDefinitionException(PortletDefinition portlet, + String reason) + { + this("Unable to store portlet definition " + portlet.getName() + + ". Resaon: " + reason); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/PortletRegistry.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/PortletRegistry.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/PortletRegistry.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,170 +29,188 @@ /** * <p> * PortletRegistryComponentImpl - * </p> - * - * - * @ + * </p> @ * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $ $ - * + * */ public interface PortletRegistry { - Language createLanguage( Locale locale, String title, String shortTitle, String description, Collection keywords ) - throws RegistryException; + Language createLanguage(Locale locale, String title, String shortTitle, + String description, Collection keywords) throws RegistryException; Collection getAllPortletDefinitions(); /** - * Retreives a PortletApplication by it's unique ObjectID. - * The unqiue ObjectID is generally a function of the native - * storage mechanism of the container whether it be auto-generated - * by an RDBMS, O/R tool or some other mechanism. - * This is different than the portlet applaiction's unique indentfier - * which is specified within the portlet.xml - * @param id + * Retreives a PortletApplication by it's unique ObjectID. The unqiue + * ObjectID is generally a function of the native storage mechanism of the + * container whether it be auto-generated by an RDBMS, O/R tool or some + * other mechanism. This is different than the portlet applaiction's unique + * indentfier which is specified within the portlet.xml + * + * @param id * @return */ - MutablePortletApplication getPortletApplication( ObjectID id ); + MutablePortletApplication getPortletApplication(ObjectID id); /** - * Retreives a PortletApplication by it's unique name. We use - * PortletApplicationComposite interface which extends the PortletApplication - * and adds additional functionallity to it. - * @param id + * Retreives a PortletApplication by it's unique name. We use + * PortletApplicationComposite interface which extends the + * PortletApplication and adds additional functionallity to it. + * + * @param id * @return PortletApplicationComposite */ - MutablePortletApplication getPortletApplication( String name ); + MutablePortletApplication getPortletApplication(String name); /** - * Locates a portlet application using it's unique <code>identifier</code> + * Locates a portlet application using it's unique <code>identifier</code> * field. - * @param identifier Unique id for this portlet application + * + * @param identifier + * Unique id for this portlet application * @return portlet application matching this unique id. */ - MutablePortletApplication getPortletApplicationByIdentifier( String identifier ); + MutablePortletApplication getPortletApplicationByIdentifier( + String identifier); Collection getPortletApplications(); /** - * Locates a portlet using it's unique <code>identifier</code> - * field. - * <br/> - * This method automatically calls {@link getStoreableInstance(PortletDefinitionComposite portlet)} - * on the returned <code>PortletEntityInstance</code> - * @param identifier Unique id for this portlet + * Locates a portlet using it's unique <code>identifier</code> field. + * <br/> This method automatically calls + * {@link getStoreableInstance(PortletDefinitionComposite portlet)} on the + * returned <code>PortletEntityInstance</code> + * + * @param identifier + * Unique id for this portlet * @return Portlet matching this unique id. - * @throws java.lang.IllegalStateException If <code>PortletDefinitionComposite != null</code> AND - * <code>PortletDefinitionComposite.getPortletApplicationDefinition() == null</code>. - * The reason for this is that every PortletDefinition is required to - * have a parent PortletApplicationDefinition + * @throws java.lang.IllegalStateException + * If <code>PortletDefinitionComposite != null</code> AND + * <code>PortletDefinitionComposite.getPortletApplicationDefinition() == null</code>. + * The reason for this is that every PortletDefinition is + * required to have a parent PortletApplicationDefinition */ - PortletDefinitionComposite getPortletDefinitionByIdentifier( String identifier ); - - + PortletDefinitionComposite getPortletDefinitionByIdentifier( + String identifier); + /** - * Locates the portlet defintion by its unique <code>ObjectID</code>. - * The ObjectID is generated internally by the portal when the portlet + * Locates the portlet defintion by its unique <code>ObjectID</code>. The + * ObjectID is generated internally by the portal when the portlet * definition is first registered and has no connection to the information * stored within the <code>portlet.xml</code>. + * * @param id * @return PortletDefinitionComposite */ PortletDefinitionComposite getPortletDefinition(ObjectID id); - /** - * unique name is a string formed by the combination of a portlet's - * unique within it's parent application plus the parent application's - * unique name within the portlet container using ":" as a delimiter. - * <br/> + * unique name is a string formed by the combination of a portlet's unique + * within it's parent application plus the parent application's unique name + * within the portlet container using ":" as a delimiter. <br/> * <strong>FORMAT: </strong> <i>application name</i>::<i>portlet name</i> - * <br/> - * <strong>EXAMPLE: </strong> com.myapp.portletApp1::weather-portlet - * <br/> - * This methos automatically calls {@link getStoreableInstance(PortletDefinitionComposite portlet)} - * on the returned <code>PortletEntityInstance</code> - * @param name portlets unique name. - * @return Portlet that matches the unique name - * @throws java.lang.IllegalStateException If <code>PortletDefinitionComposite != null</code> AND - * <code>PortletDefinitionComposite.getPortletApplicationDefinition() == null</code>. - * The reason for this is that every PortletDefinition is required to - * have a parent PortletApplicationDefinition + * <br/> <strong>EXAMPLE: </strong> com.myapp.portletApp1::weather-portlet + * <br/> This methos automatically calls + * {@link getStoreableInstance(PortletDefinitionComposite portlet)} on the + * returned <code>PortletEntityInstance</code> * + * @param name + * portlets unique name. + * @return Portlet that matches the unique name + * @throws java.lang.IllegalStateException + * If <code>PortletDefinitionComposite != null</code> AND + * <code>PortletDefinitionComposite.getPortletApplicationDefinition() == null</code>. + * The reason for this is that every PortletDefinition is + * required to have a parent PortletApplicationDefinition + * */ - PortletDefinitionComposite getPortletDefinitionByUniqueName( String name ); + PortletDefinitionComposite getPortletDefinitionByUniqueName(String name); /** - * Checks whether or not a portlet application with this identity has all ready - * been registered to the container. - * @param appIdentity portlet application indetity to check for. - * @return boolean <code>true</code> if a portlet application with this identity - * is alreay registered, <code>false</code> if it has not. + * Checks whether or not a portlet application with this identity has all + * ready been registered to the container. + * + * @param appIdentity + * portlet application indetity to check for. + * @return boolean <code>true</code> if a portlet application with this + * identity is alreay registered, <code>false</code> if it has + * not. */ - boolean portletApplicationExists( String appIentity ); - + boolean portletApplicationExists(String appIentity); + /** * * <p> * namedPortletApplicationExists * </p> - * + * * @param appName * @return */ - boolean namedPortletApplicationExists( String appName ); + boolean namedPortletApplicationExists(String appName); /** - * Checks whether or not a portlet with this identity has all ready - * been registered to the container. - * @param portletIndentity portlet indetity to check for. - * @return boolean <code>true</code> if a portlet with this identity - * is alreay registered, <code>false</code> if it has not. + * Checks whether or not a portlet with this identity has all ready been + * registered to the container. + * + * @param portletIndentity + * portlet indetity to check for. + * @return boolean <code>true</code> if a portlet with this identity is + * alreay registered, <code>false</code> if it has not. */ - boolean portletDefinitionExists( String portletIndentity ); + boolean portletDefinitionExists(String portletIndentity); /** - * Checks whether or not a portlet with this identity has all ready - * been registered to the PortletApplication. - * @param portletIndentity portlet indetity to check for. - * @param app PortletApplication to check . - * @return boolean <code>true</code> if a portlet with this identity - * is alreay registered, <code>false</code> if it has not. + * Checks whether or not a portlet with this identity has all ready been + * registered to the PortletApplication. + * + * @param portletIndentity + * portlet indetity to check for. + * @param app + * PortletApplication to check . + * @return boolean <code>true</code> if a portlet with this identity is + * alreay registered, <code>false</code> if it has not. */ - boolean portletDefinitionExists( String portletName, MutablePortletApplication app ); + boolean portletDefinitionExists(String portletName, + MutablePortletApplication app); /** - * Creates a new <code>PortletApplicationDefinition</code> - * within the Portal. + * Creates a new <code>PortletApplicationDefinition</code> within the + * Portal. + * * @param newApp */ - void registerPortletApplication( PortletApplicationDefinition newApp ) throws RegistryException; + void registerPortletApplication(PortletApplicationDefinition newApp) + throws RegistryException; - void removeApplication( PortletApplicationDefinition app ) throws RegistryException; + void removeApplication(PortletApplicationDefinition app) + throws RegistryException; /** * Makes any changes to the <code>PortletApplicationDefinition</code> * persistent. + * * @param app */ - void updatePortletApplication( PortletApplicationDefinition app ) throws RegistryException; - + void updatePortletApplication(PortletApplicationDefinition app) + throws RegistryException; + /** * * <p> * savePortletDefinition * </p> - * + * * @param portlet * @throws FailedToStorePortletDefinitionException */ - void savePortletDefinition(PortletDefinition portlet) throws FailedToStorePortletDefinitionException; - + void savePortletDefinition(PortletDefinition portlet) + throws FailedToStorePortletDefinitionException; + void addRegistryListener(RegistryEventListener listener); - + void removeRegistryEventListner(RegistryEventListener listener); - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/RegistryEventListener.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/RegistryEventListener.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/RegistryEventListener.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,46 +20,51 @@ import org.apache.jetspeed.om.common.portlet.PortletDefinitionComposite; /** - * This interface describes the page manager event listener - * that is notified when a managed node is updated or removed + * This interface describes the page manager event listener that is notified + * when a managed node is updated or removed * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ public interface RegistryEventListener { + /** - * applicationUpdated - invoked when the definition of a portlet application is - * updated by the registry or when the - * state modification is otherwise detected - * - * @param MutablePortletApplicaiton new managed application + * applicationUpdated - invoked when the definition of a portlet application + * is updated by the registry or when the state modification is otherwise + * detected + * + * @param MutablePortletApplicaiton + * new managed application */ void applicationUpdated(MutablePortletApplication app); /** * portletUpdated - invoked when the definition of a portlet definition is - * updated by the registry or when the - * state modification is otherwise detected - * - * @param PortletDefinitionComposite new managed portlet definition + * updated by the registry or when the state modification is otherwise + * detected + * + * @param PortletDefinitionComposite + * new managed portlet definition */ void portletUpdated(PortletDefinitionComposite def); /** - * applicationRemoved - invoked when the definition of a portlet application is - * removed by the registry - * - * @param MutablePortletApplicaiton removed portlet application + * applicationRemoved - invoked when the definition of a portlet application + * is removed by the registry + * + * @param MutablePortletApplicaiton + * removed portlet application */ void applicationRemoved(MutablePortletApplication app); /** * portletUpdated - invoked when the definition of a portlet definition is - * removed by the registry - * - * @param PortletDefinitionComposite new managed portlet definition if known + * removed by the registry + * + * @param PortletDefinitionComposite + * new managed portlet definition if known */ void portletRemoved(PortletDefinitionComposite def); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/RegistryException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/RegistryException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/components/portletregistry/RegistryException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,40 +18,36 @@ import org.apache.jetspeed.exception.JetspeedException; - /** -Occurs when anything unexpected happens within Jetspeed and its Registry. Any + * Occurs when anything unexpected happens within Jetspeed and its Registry. Any + * + * @author <a href="mailto:burton ¡÷ apache.org">Kevin A. Burton</a> + * @version $Id: RegistryException.java 516448 2007-03-09 16:25:47Z ate $ + */ - ¡÷ author <a href="mailto:burton ¡÷ apache.org">Kevin A. Burton</a> - ¡÷ version $Id: RegistryException.java 516448 2007-03-09 16:25:47Z ate $ -*/ - public class RegistryException extends JetspeedException - { +{ - public static final String REGISTRY_NOT_FOUND - = "The specified registry does not exist."; + public static final String REGISTRY_NOT_FOUND = "The specified registry does not exist."; - public RegistryException() + public RegistryException() { super(); } - public RegistryException( String message ) + public RegistryException(String message) { - super( message ); + super(message); } public RegistryException(Throwable nested) { super(nested); } - + public RegistryException(String msg, Throwable nested) { super(msg, nested); } - } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/invoker/PortletRequestResponseUnwrapper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/invoker/PortletRequestResponseUnwrapper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/invoker/PortletRequestResponseUnwrapper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,30 +22,33 @@ import javax.servlet.ServletResponse; /** - * PortletRequestResponseUnwrapper finds servlet request or servlet response - * from portlet request or portlet response by unwrapping. - * Third-party module can provide an implementation to decorate the real request - * or response object of a servlet container. - * For example, the real request object of a servlet container can be decorated - * because it is not thread-safe under Jetspeed parallel rendering mode. - * + * PortletRequestResponseUnwrapper finds servlet request or servlet response + * from portlet request or portlet response by unwrapping. Third-party module + * can provide an implementation to decorate the real request or response object + * of a servlet container. For example, the real request object of a servlet + * container can be decorated because it is not thread-safe under Jetspeed + * parallel rendering mode. + * * @author <a href="mailto:woonsan ¡÷ apache.org">Woonsan Ko</a> * @version $Id: $ */ public interface PortletRequestResponseUnwrapper { + /** * Unwraps portlet request to find the real servlet request. * - * @param portletRequest The portlet request to be unwrapped. + * @param portletRequest + * The portlet request to be unwrapped. * @return servletRequest The servlet request found by unwrapping. */ ServletRequest unwrapPortletRequest(PortletRequest portletRequest); - + /** * Unwraps portlet response to find the real servlet response. * - * @param portletResponse The portlet response to be unwrapped. + * @param portletResponse + * The portlet response to be unwrapped. * @return servletResponse The servlet response found by unwrapping. */ ServletResponse unwrapPortletResponse(PortletResponse portletResponse); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/session/PortalSessionMonitor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/session/PortalSessionMonitor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/session/PortalSessionMonitor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,16 +24,21 @@ /** * PortalSessionMonitor - * + * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id: $ */ -public interface PortalSessionMonitor extends HttpSessionBindingListener, HttpSessionActivationListener, Serializable +public interface PortalSessionMonitor extends HttpSessionBindingListener, + HttpSessionActivationListener, Serializable { + String SESSION_KEY = PortalSessionMonitor.class.getName(); - + long getSessionKey(); + String getSessionId(); + void invalidateSession(); + HttpSession getSession(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/session/PortalSessionsManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/session/PortalSessionsManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/session/PortalSessionsManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,24 +20,36 @@ /** * PortalSessionsMonitor - * + * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id: $ */ public interface PortalSessionsManager { + String SERVICE_NAME = PortalSessionsManager.class.getName(); - + void portalSessionCreated(HttpSession portalSession); + void portalSessionWillPassivate(PortalSessionMonitor psm); + void portalSessionDidActivate(PortalSessionMonitor psm); + void portalSessionDestroyed(PortalSessionMonitor psm); - void checkMonitorSession(String contextPath, HttpSession portalSession, HttpSession paSession); - void sessionWillPassivate(PortletApplicationSessionMonitor pasm); - void sessionDidActivate(PortletApplicationSessionMonitor pasm); - void sessionDestroyed(PortletApplicationSessionMonitor pasm); + + void checkMonitorSession(String contextPath, HttpSession portalSession, + HttpSession paSession); + + void sessionWillPassivate(PortletApplicationSessionMonitor pasm); + + void sessionDidActivate(PortletApplicationSessionMonitor pasm); + + void sessionDestroyed(PortletApplicationSessionMonitor pasm); + /** - * Returns the number of current sessions. Used to track the number guest users in portal. + * Returns the number of current sessions. Used to track the number guest + * users in portal. + * * @return Number of currently created sessions in the registry */ int sessionCount(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/session/PortletApplicationSessionMonitor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/session/PortletApplicationSessionMonitor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/session/PortletApplicationSessionMonitor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,16 +24,23 @@ /** * PortletApplicationSessionMonitor - * + * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id: $ */ -public interface PortletApplicationSessionMonitor extends HttpSessionBindingListener, HttpSessionActivationListener, Serializable +public interface PortletApplicationSessionMonitor extends + HttpSessionBindingListener, HttpSessionActivationListener, Serializable { - String SESSION_KEY = PortletApplicationSessionMonitor.class.getName(); + + String SESSION_KEY = PortletApplicationSessionMonitor.class.getName(); + long getPortalSessionKey(); + String getPortalSessionId(); + String getContextPath(); + void invalidateSession(); + HttpSession getSession(); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/FailedToCreateNavStateException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/FailedToCreateNavStateException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/FailedToCreateNavStateException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,12 +23,14 @@ * FailedToCreateNavStateException * </p> * <p> - * Thrown if an attempt to create a {@link NavigationalState} met with an unexpected - * failure. + * Thrown if an attempt to create a {@link NavigationalState} met with an + * unexpected failure. * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: FailedToCreateNavStateException.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: FailedToCreateNavStateException.java 516448 2007-03-09 + * 16:25:47Z ate $ + * */ public class FailedToCreateNavStateException extends JetspeedRuntimeException { @@ -45,7 +47,7 @@ /** * @param arg0 */ - public FailedToCreateNavStateException( String arg0 ) + public FailedToCreateNavStateException(String arg0) { super(arg0); // TODO Auto-generated constructor stub @@ -54,7 +56,7 @@ /** * @param arg0 */ - public FailedToCreateNavStateException( Throwable arg0 ) + public FailedToCreateNavStateException(Throwable arg0) { super(arg0); // TODO Auto-generated constructor stub @@ -64,7 +66,7 @@ * @param arg0 * @param arg1 */ - public FailedToCreateNavStateException( String arg0, Throwable arg1 ) + public FailedToCreateNavStateException(String arg0, Throwable arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/FailedToCreatePortalUrlException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/FailedToCreatePortalUrlException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/FailedToCreatePortalUrlException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,12 +23,13 @@ * FailedToCreatePortalUrl * </p> * <p> - * Thrown if an attempt to create a Portal URL met with an unexpected - * failure. + * Thrown if an attempt to create a Portal URL met with an unexpected failure. * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: FailedToCreatePortalUrlException.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: FailedToCreatePortalUrlException.java 516448 2007-03-09 + * 16:25:47Z ate $ + * */ public class FailedToCreatePortalUrlException extends JetspeedRuntimeException { @@ -45,7 +46,7 @@ /** * @param arg0 */ - public FailedToCreatePortalUrlException( String arg0 ) + public FailedToCreatePortalUrlException(String arg0) { super(arg0); // TODO Auto-generated constructor stub @@ -54,7 +55,7 @@ /** * @param arg0 */ - public FailedToCreatePortalUrlException( Throwable arg0 ) + public FailedToCreatePortalUrlException(Throwable arg0) { super(arg0); // TODO Auto-generated constructor stub @@ -64,7 +65,7 @@ * @param arg0 * @param arg1 */ - public FailedToCreatePortalUrlException( String arg0, Throwable arg1 ) + public FailedToCreatePortalUrlException(String arg0, Throwable arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/FailedToCreatedNavStateCodecException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/FailedToCreatedNavStateCodecException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/FailedToCreatedNavStateCodecException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,14 +21,17 @@ /** * FailedToCreateNavStateCodecException * - * Thrown if an attempt to create a NavigationalStateCodec met with an unexpected - * failure. + * Thrown if an attempt to create a NavigationalStateCodec met with an + * unexpected failure. * </p> + * * @author <a href="mailto:ate ¡÷ apache.org">Ate Douma</a> - * @version $Id: FailedToCreatedNavStateCodecException.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: FailedToCreatedNavStateCodecException.java 516448 2007-03-09 + * 16:25:47Z ate $ + * */ -public class FailedToCreatedNavStateCodecException extends JetspeedRuntimeException +public class FailedToCreatedNavStateCodecException extends + JetspeedRuntimeException { /** Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/MutableNavigationalState.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/MutableNavigationalState.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/MutableNavigationalState.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,34 +23,40 @@ /** * MutableNavigationalState - * + * * Allows changing the PortletMode and/or WindowState of a PortletWindow state. * <br> - * This interface extends the {@link NavigationState} interface to cleanly define the immutable contract of the latter. + * This interface extends the {@link NavigationState} interface to cleanly + * define the immutable contract of the latter. <br> + * Note: this is actually an ugly hack into the Portal as formally (per the + * portlet specs) the PortletMode and/or WindowState are only to be modified + * *and* then retained for the *next* subsequent renderRequest. <br> + * This interface is used for support of the Pluto required PortalActionProvider + * implementation (which definition is not undisputed, see: [todo: link to + * pluto-dev "Why PortalActionProvider?" mail discussion]). <br> + * Furthermore, this interface is also used by the Jetspeed-1 + * JetspeedFusionPortlet to synchronize the NavigationalState. Under which + * conditions that is done isn't clear yet (to me) but possibly that can/should + * be done differently also. <br> + * Modifying the Navigational State *during* a renderRequest (before the actual) + * rendering can result in a lost of these new states on a subsequent refresh of + * the Portlet if that doesn't trigger changing them again, because the state of + * these changes is only saved in PortletURLs created during the renderRequest, + * *not* in the session (if SessionNavigationalState is used). The session state + * has already been synchronized (if done) *before* these methods can be called. * <br> - * Note: this is actually an ugly hack into the Portal as formally (per the portlet specs) the PortletMode and/or - * WindowState are only to be modified *and* then retained for the *next* subsequent renderRequest. - * <br> - * This interface is used for support of the Pluto required PortalActionProvider implementation (which definition - * is not undisputed, see: [todo: link to pluto-dev "Why PortalActionProvider?" mail discussion]). - * <br> - * Furthermore, this interface is also used by the Jetspeed-1 JetspeedFusionPortlet to synchronize the NavigationalState. - * Under which conditions that is done isn't clear yet (to me) but possibly that can/should be done differently also. - * <br> - * Modifying the Navigational State *during* a renderRequest (before the actual) rendering can result in a lost of these new states on a - * subsequent refresh of the Portlet if that doesn't trigger changing them again, because the state of these changes is - * only saved in PortletURLs created during the renderRequest, *not* in the session (if SessionNavigationalState is used). - * The session state has already been synchronized (if done) *before* these methods can be called. - * <br> - * Modifying the Navigational State *during* an actionRequest, as done by Pluto through the PortalActionProvider - * interface just before it sends a redirect, is kinda strange as it can more cleanly be done through the - * its PortalURLProvider interface (see above link to the mail discussion about this). - * + * Modifying the Navigational State *during* an actionRequest, as done by Pluto + * through the PortalActionProvider interface just before it sends a redirect, + * is kinda strange as it can more cleanly be done through the its + * PortalURLProvider interface (see above link to the mail discussion about + * this). + * * @author <a href="mailto:ate ¡÷ apache.org">Ate Douma</a> * @version $Id: MutableNavigationalState.java 554926 2007-07-10 13:12:26Z ate $ */ public interface MutableNavigationalState extends NavigationalState { + /** * Sets the window state for the given portlet window. * @@ -58,7 +64,7 @@ * @param windowState */ void setState(PortletWindow window, WindowState windowState); - + /** * Sets the portlet mode for the given portlet window. * @@ -66,14 +72,14 @@ * @param portletMode */ void setMode(PortletWindow window, PortletMode portletMode); - + /** * Clear the request parameters to emulate an action reset * * @param window */ void clearParameters(PortletWindow window); - + /** * Remove state for the given (possibly invalid) portlet window */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/NavigationalState.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/NavigationalState.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/NavigationalState.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,36 +27,41 @@ import org.apache.pluto.om.window.PortletWindow; /** - * NavigationalState gives readonly access to the state of the Portal URL and all navigational state context - * as well as encoding a new State for usage in a Portal URL. - * <br> - * Note: Support for changing the PortletMode and/or WindowState of a PortletWindow, other than for encoding a new State - * is moved down to the {@link MutableNavigationState} interface to cleanly define the immutable contract of this - * interface. + * NavigationalState gives readonly access to the state of the Portal URL and + * all navigational state context as well as encoding a new State for usage in a + * Portal URL. <br> + * Note: Support for changing the PortletMode and/or WindowState of a + * PortletWindow, other than for encoding a new State is moved down to the + * {@link MutableNavigationState} interface to cleanly define the immutable + * contract of this interface. * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: NavigationalState.java 554926 2007-07-10 13:12:26Z ate $ */ -public interface NavigationalState +public interface NavigationalState { + public static final String NAVSTATE_SESSION_KEY = "org.apache.jetspeed.navstate"; /* * Decodes an encoded Navigational State as retrieved from a Portal URL. - * <br> - * Note: Initializing is done only once. Subsequent init requests are ignored. + * <br> Note: Initializing is done only once. Subsequent init requests are + * ignored. * - * @param encodedState encoded Navigational State as retrieved from a Portal URL. - * @param characterEncoding String containing the name of the chararacter encoding + * @param encodedState encoded Navigational State as retrieved from a Portal + * URL. @param characterEncoding String containing the name of the + * chararacter encoding */ - void init(String encodedState, String characterEncoding) throws UnsupportedEncodingException; - + void init(String encodedState, String characterEncoding) + throws UnsupportedEncodingException; + /** - * Synchronize the Navigational State with saved state (if used). - * <br> - * Should be called by the PortalURL impl right after calling {@link #init(String)} - * - * @param context The RequestContext for this Navigational State + * Synchronize the Navigational State with saved state (if used). <br> + * Should be called by the PortalURL impl right after calling + * {@link #init(String)} + * + * @param context + * The RequestContext for this Navigational State */ void sync(RequestContext context); @@ -66,16 +71,16 @@ * @param window * @return */ - WindowState getState(PortletWindow window); - + WindowState getState(PortletWindow window); + /** * Gets the internal (portal) window state for given portlet window. * * @param window * @return */ - WindowState getMappedState(PortletWindow window); - + WindowState getMappedState(PortletWindow window); + /** * Gets the window state for given portlet window id. * @@ -83,16 +88,16 @@ * @return * @deprecated */ - WindowState getState(String windowId); - + WindowState getState(String windowId); + /** * Gets the internal (portal) window state for given portlet window id. * * @param windowId * @return */ - WindowState getMappedState(String windowId); - + WindowState getMappedState(String windowId); + /** * Gets the portlet mode for the given portlet window. * @@ -100,7 +105,7 @@ * @return */ PortletMode getMode(PortletWindow window); - + /** * Gets the internal (portal) portlet mode for the given portlet window. * @@ -108,7 +113,7 @@ * @return */ PortletMode getMappedMode(PortletWindow window); - + /** * Gets the portlet mode for the given portlet window id. * @@ -117,7 +122,7 @@ * @deprecated */ PortletMode getMode(String windowId); - + /** * Gets the internal (portal) portlet mode for the given portlet window id. * @@ -125,65 +130,79 @@ * @return */ PortletMode getMappedMode(String windowId); - + /** - * For the current request return the (first) maximized window or - * return null if no windows are maximized. + * For the current request return the (first) maximized window or return + * null if no windows are maximized. * * @return The maximized window or null */ PortletWindow getMaximizedWindow(); - + Iterator getParameterNames(PortletWindow window); - + String[] getParameterValues(PortletWindow window, String parameterName); PortletWindow getPortletWindowOfAction(); - + PortletWindow getPortletWindowOfResource(); + /** - * Returns an iterator of Portlet Window ids of all the Portlet Windows - * within the NavigationalState. - * <br/> - * Note: for an ActionRequest, this will include the window id of - * the PortletWindowOfAction. + * Returns an iterator of Portlet Window ids of all the Portlet Windows + * within the NavigationalState. <br/> Note: for an ActionRequest, this will + * include the window id of the PortletWindowOfAction. + * * @return iterator of portletWindow ids (String) */ Iterator getWindowIdIterator(); - + /** - * Encodes the Navigational State with overrides for a specific PortletWindow into a string to be embedded within a - * PortalURL. + * Encodes the Navigational State with overrides for a specific + * PortletWindow into a string to be embedded within a PortalURL. * - * @param window the PortalWindow - * @param parameters the new request or action parameters for the PortalWindow - * @param mode the new PortletMode for the PortalWindow - * @param state the new WindowState for the PortalWindow - * @param action indicates if to be used in an actionURL or renderURL + * @param window + * the PortalWindow + * @param parameters + * the new request or action parameters for the PortalWindow + * @param mode + * the new PortletMode for the PortalWindow + * @param state + * the new WindowState for the PortalWindow + * @param action + * indicates if to be used in an actionURL or renderURL * @return encoded new Navigational State */ - String encode(PortletWindow window, Map parameters, PortletMode mode, WindowState state, boolean action) throws UnsupportedEncodingException; + String encode(PortletWindow window, Map parameters, PortletMode mode, + WindowState state, boolean action) + throws UnsupportedEncodingException; /** - * Encodes the Navigational State with overrides for a specific PortletWindow while retaining its (request) - * parameters into a string to be embedded within a renderURL. + * Encodes the Navigational State with overrides for a specific + * PortletWindow while retaining its (request) parameters into a string to + * be embedded within a renderURL. * - * @param window the PortalWindow - * @param mode the new PortletMode for the PortalWindow - * @param state the new WindowState for the PortalWindow - * @return encoded new Navigational State + * @param window + * the PortalWindow + * @param mode + * the new PortletMode for the PortalWindow + * @param state + * the new WindowState for the PortalWindow + * @return encoded new Navigational State */ - String encode(PortletWindow window, PortletMode mode, WindowState state) throws UnsupportedEncodingException; - + String encode(PortletWindow window, PortletMode mode, WindowState state) + throws UnsupportedEncodingException; + /** - * Encodes the current navigational State into a string to be embedded within a PortalURL. + * Encodes the current navigational State into a string to be embedded + * within a PortalURL. * - * @return encoded new Navigational State + * @return encoded new Navigational State */ String encode() throws UnsupportedEncodingException; - + /** - * @return true if WindowStates and PortletModes will be saved in the Session + * @return true if WindowStates and PortletModes will be saved in the + * Session */ boolean isNavigationalParameterStateFull(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/NavigationalStateComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/NavigationalStateComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/state/NavigationalStateComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,63 +24,73 @@ /** * NavigationalState - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: NavigationalStateComponent.java 516448 2007-03-09 16:25:47Z ate $ */ public interface NavigationalStateComponent -{ +{ + /** - * Creates a navigational state. - * Depending on the implementation, a navigational state context can be retrieved from - * a persistence store to recover the state of a page such as portlet modes - * and window states of portlets on a page. - * - * @return A new navigational state. This method will never return <code>null</code> - * @throws FailedToCreateNavStateException if the nav state could not be created. Under normal - * circumstances, this should not happen. + * Creates a navigational state. Depending on the implementation, a + * navigational state context can be retrieved from a persistence store to + * recover the state of a page such as portlet modes and window states of + * portlets on a page. + * + * @return A new navigational state. This method will never return + * <code>null</code> + * @throws FailedToCreateNavStateException + * if the nav state could not be created. Under normal + * circumstances, this should not happen. */ NavigationalState create(); /** * Creates a Portal URL representing the URL of the request. * - * @param request The ubiqitious request. - * @param characterEncoding String containing the name of the chararacter encoding - * @return A new Portal URL. This method will never return <code>null</code>; - * @throws FailedToCreatePortalUrlException if the portelt url could not be created. Under normal - * circumstances, this should not happen. + * @param request + * The ubiqitious request. + * @param characterEncoding + * String containing the name of the chararacter encoding + * @return A new Portal URL. This method will never return <code>null</code>; + * @throws FailedToCreatePortalUrlException + * if the portelt url could not be created. Under normal + * circumstances, this should not happen. */ PortalURL createURL(HttpServletRequest request, String characterEncoding); - + /** - * Given a window state name, look up its object. - * Ensures that we always use the same objects for WindowStates - * allowing for comparison by value. + * Given a window state name, look up its object. Ensures that we always use + * the same objects for WindowStates allowing for comparison by value. * - * @param name The string representation of the window state. + * @param name + * The string representation of the window state. * @return The corresponding WindowState object */ WindowState lookupWindowState(String name); /** - * Given a portlet mode name, look up its object. - * Ensures that we always use the same objects for Portlet Modes - * allowing for comparison by value. + * Given a portlet mode name, look up its object. Ensures that we always use + * the same objects for Portlet Modes allowing for comparison by value. * - * @param name The string representation of the portlet mode. + * @param name + * The string representation of the portlet mode. * @return The corresponding PortletMode object - */ - PortletMode lookupPortletMode(String name); + */ + PortletMode lookupPortletMode(String name); /** * Creates a Desktop Portal URL representing the URL of the request. * - * @param request The ubiqitious request. - * @param characterEncoding String containing the name of the chararacter encoding - * @return A new Portal URL. This method will never return <code>null</code>; - * @throws FailedToCreatePortalUrlException if the portelt url could not be created. Under normal - * circumstances, this should not happen. - */ - PortalURL createDesktopURL(HttpServletRequest request, String characterEncoding); + * @param request + * The ubiqitious request. + * @param characterEncoding + * String containing the name of the chararacter encoding + * @return A new Portal URL. This method will never return <code>null</code>; + * @throws FailedToCreatePortalUrlException + * if the portelt url could not be created. Under normal + * circumstances, this should not happen. + */ + PortalURL createDesktopURL(HttpServletRequest request, + String characterEncoding); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/url/BasePortalURL.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/url/BasePortalURL.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/url/BasePortalURL.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,23 +19,31 @@ /** * <p> * BasePortalURL defines the interface for manipulating Base URLs in a portal. - * Base URLs contain the isSecure flag, server name, server port, and server scheme. - * This abstraction was necessary for wiring the entire portal's base URL via another - * mechanism than retrieving from the servlet request. + * Base URLs contain the isSecure flag, server name, server port, and server + * scheme. This abstraction was necessary for wiring the entire portal's base + * URL via another mechanism than retrieving from the servlet request. * </p> * * @author <a href="mailto:david ¡÷ bluesunrise.com">David Sean Taylor</a> * @version $Id: $ - * + * */ public interface BasePortalURL { - boolean isSecure(); - void setSecure(boolean secure); - String getServerName(); + + boolean isSecure(); + + void setSecure(boolean secure); + + String getServerName(); + void setServerName(String serverName); - int getServerPort(); - void setServerPort(int serverPort); - String getServerScheme(); - void setServerScheme(String serverScheme); + + int getServerPort(); + + void setServerPort(int serverPort); + + String getServerScheme(); + + void setServerScheme(String serverScheme); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/url/PortalURL.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/url/PortalURL.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/url/PortalURL.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,35 +27,37 @@ /** * <p> - * PortalURL defines the interface for manipulating Jetspeed Portal URLs. - * These URLs are used internally by the portal and are not available to - * Portlet Applications. + * PortalURL defines the interface for manipulating Jetspeed Portal URLs. These + * URLs are used internally by the portal and are not available to Portlet + * Applications. * </p> * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @author <a href="mailto:david ¡÷ bluesunrise.com">David Sean Taylor</a> * @version $Id: PortalURL.java 605989 2007-12-20 18:26:54Z ate $ - * + * */ public interface PortalURL { + /** HTTP protocol. */ public static final String HTTP = "http"; /** HTTPS protocol. */ public static final String HTTPS = "https"; - + /** - * @return true if only relative urls should be generated (without scheme, servername, port) + * @return true if only relative urls should be generated (without scheme, + * servername, port) */ boolean isRelativeOnly(); - + /** * Gets the Base URL for this portal. * * @return The Base URL of the portal. */ - String getBaseURL(); + String getBaseURL(); /** * Gets a secure version of the Base URL for this portal. @@ -65,29 +67,28 @@ String getBaseURL(boolean secure); /** - * Gets the global navigational path of the current request. - * <br> + * Gets the global navigational path of the current request. <br> * The path does not contain the NavigationalState parameter * * @return The the global navigational path of the current request. */ String getPath(); - + /** - * Returns the current Portal base path. - * <br> - * This path can be used as base for root relative pages and resources which don't need - * the NavigationalState. + * Returns the current Portal base path. <br> + * This path can be used as base for root relative pages and resources which + * don't need the NavigationalState. + * * @return the current Portal base path without NavigationalState */ String getBasePath(); /** * Returns the current Portal Page base path without possible encoded - * NavigationalState parameter. - * <br> - * This path can be used as base for page relative resources which don't need - * the NavigationalState. + * NavigationalState parameter. <br> + * This path can be used as base for page relative resources which don't + * need the NavigationalState. + * * @return the current Portal Page base path without NavigationalState */ String getPageBasePath(); @@ -98,90 +99,117 @@ boolean isSecure(); /** - * Gets the NavigationalState for access to the current request portal control parameters + * Gets the NavigationalState for access to the current request portal + * control parameters + * * @return the NavigationalState of the PortalURL */ - NavigationalState getNavigationalState(); + NavigationalState getNavigationalState(); /** - * Create a new PortletURL for a PortletWindow including request or action parameters. - * <br> + * Create a new PortletURL for a PortletWindow including request or action + * parameters. <br> * The Portal Navigational State is encoded within the URL * - * @param window the PortalWindow - * @param parameters the new request or action parameters for the PortalWindow - * @param mode the new PortletMode for the PortalWindow - * @param state the new WindowState for the PortalWindow - * @param action indicates if an actionURL or renderURL is created - * @param secure indicates if a secure url is required + * @param window + * the PortalWindow + * @param parameters + * the new request or action parameters for the PortalWindow + * @param mode + * the new PortletMode for the PortalWindow + * @param state + * the new WindowState for the PortalWindow + * @param action + * indicates if an actionURL or renderURL is created + * @param secure + * indicates if a secure url is required * @return a new actionURL or renderURL as String */ - String createPortletURL(PortletWindow window, Map parameters, PortletMode mode, WindowState state, boolean action, boolean secure); + String createPortletURL(PortletWindow window, Map parameters, + PortletMode mode, WindowState state, boolean action, boolean secure); /** - * Create a new PortletURL for a PortletWindow retaining its (request) parameters. - * <br> + * Create a new PortletURL for a PortletWindow retaining its (request) + * parameters. <br> * The Portal Navigational State is encoded within the URL * - * @param window the PortalWindow - * @param mode the new PortletMode for the PortalWindow - * @param state the new WindowState for the PortalWindow + * @param window + * the PortalWindow + * @param mode + * the new PortletMode for the PortalWindow + * @param state + * the new WindowState for the PortalWindow * @param secure - * @param secure indicates if a secure url is required + * @param secure + * indicates if a secure url is required * @return a new renderURL as String */ - String createPortletURL(PortletWindow window, PortletMode mode, WindowState state, boolean secure); - + String createPortletURL(PortletWindow window, PortletMode mode, + WindowState state, boolean secure); + /** - * Sets the @link{javax.servlet.http.HttpServletRequest} that will be used - * to generate urls. + * Sets the + * + * @link{javax.servlet.http.HttpServletRequest} that will be used to + * generate urls. * @param request */ void setRequest(HttpServletRequest request); - + void setCharacterEncoding(String characterEncoding); - + /** - * Creates the navigational encoding for a given window - * Similiar to createPortletURL above + * Creates the navigational encoding for a given window Similiar to + * createPortletURL above * - * @param window the PortalWindow - * @param parameters the new request or action parameters for the PortalWindow - * @param mode the new PortletMode for the PortalWindow - * @param state the new WindowState for the PortalWindow - * @param action indicates if an actionURL or renderURL is created - * @param secure indicates if a secure url is required + * @param window + * the PortalWindow + * @param parameters + * the new request or action parameters for the PortalWindow + * @param mode + * the new PortletMode for the PortalWindow + * @param state + * the new WindowState for the PortalWindow + * @param action + * indicates if an actionURL or renderURL is created + * @param secure + * indicates if a secure url is required * @return a new navigational state as String */ - String createNavigationalEncoding(PortletWindow window, Map parameters, PortletMode mode, WindowState state, boolean action); - + String createNavigationalEncoding(PortletWindow window, Map parameters, + PortletMode mode, WindowState state, boolean action); + /** - * Creates the navigational encoding for a given window - * Similiar to createPortletURL above + * Creates the navigational encoding for a given window Similiar to + * createPortletURL above * - * @param window the PortalWindow - * @param mode the new PortletMode for the PortalWindow - * @param state the new WindowState for the PortalWindow + * @param window + * the PortalWindow + * @param mode + * the new PortletMode for the PortalWindow + * @param state + * the new WindowState for the PortalWindow * @param secure - * @param secure indicates if a secure url is required + * @param secure + * indicates if a secure url is required * @return a new renderURL as String - */ - String createNavigationalEncoding(PortletWindow window, PortletMode mode, WindowState state); + */ + String createNavigationalEncoding(PortletWindow window, PortletMode mode, + WindowState state); /** * @return a Portal URL with encoded current navigational state */ String getPortalURL(); - + /** * @return true if navigational state was provided on the url */ boolean hasEncodedNavState(); - + /** * @return true if navigational state is encoded as pathInfo */ boolean isPathInfoEncodingNavState(); - } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/window/FailedToCreateWindowException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/window/FailedToCreateWindowException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/window/FailedToCreateWindowException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,17 +23,17 @@ * FailedToCreateWindowException * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: FailedToCreateWindowException.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: FailedToCreateWindowException.java 516448 2007-03-09 16:25:47Z + * ate $ + * */ public class FailedToCreateWindowException extends JetspeedException { - - /** * */ @@ -41,25 +41,28 @@ { super(); } + /** * @param message */ - public FailedToCreateWindowException( String message ) + public FailedToCreateWindowException(String message) { super(message); } + /** * @param msg * @param nested */ - public FailedToCreateWindowException( String msg, Throwable nested ) + public FailedToCreateWindowException(String msg, Throwable nested) { super(msg, nested); } + /** * @param nested */ - public FailedToCreateWindowException( Throwable nested ) + public FailedToCreateWindowException(Throwable nested) { super(nested); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/window/FailedToRetrievePortletWindow.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/window/FailedToRetrievePortletWindow.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/window/FailedToRetrievePortletWindow.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,11 +23,13 @@ * FailedToRetrievePortletWindow * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: FailedToRetrievePortletWindow.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: FailedToRetrievePortletWindow.java 516448 2007-03-09 16:25:47Z + * ate $ + * */ public class FailedToRetrievePortletWindow extends JetspeedException { @@ -44,7 +46,7 @@ /** * @param message */ - public FailedToRetrievePortletWindow( String message ) + public FailedToRetrievePortletWindow(String message) { super(message); // TODO Auto-generated constructor stub @@ -53,7 +55,7 @@ /** * @param nested */ - public FailedToRetrievePortletWindow( Throwable nested ) + public FailedToRetrievePortletWindow(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -63,7 +65,7 @@ * @param msg * @param nested */ - public FailedToRetrievePortletWindow( String msg, Throwable nested ) + public FailedToRetrievePortletWindow(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/window/PortletWindowAccessor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/window/PortletWindowAccessor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/container/window/PortletWindowAccessor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,40 +25,47 @@ /** * Portlet Window Accessor - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: PortletWindowAccessor.java,v 1.7 2005/04/29 13:59:46 weaver Exp $ */ -public interface PortletWindowAccessor +public interface PortletWindowAccessor { + /** * Get a portlet window for the given fragment * * @param fragment * @return * @throws FailedToRetrievePortletWindow - * @throws PortletEntityNotStoredException - * @throws InconsistentWindowStateException If the window references a non-existsent PortletEntity + * @throws PortletEntityNotStoredException + * @throws InconsistentWindowStateException + * If the window references a non-existsent PortletEntity */ - PortletWindow getPortletWindow(ContentFragment fragment) throws FailedToRetrievePortletWindow, PortletEntityNotStoredException; - + PortletWindow getPortletWindow(ContentFragment fragment) + throws FailedToRetrievePortletWindow, + PortletEntityNotStoredException; + /** * Get the portlet window for a fragment and given principal + * * @param fragment * @param principal * @return * @throws FailedToCreateWindowException * @throws FailedToRetrievePortletWindow - * @throws PortletEntityNotStoredException - * @throws InconsistentWindowStateException If the window references a non-existsent PortletEntity + * @throws PortletEntityNotStoredException + * @throws InconsistentWindowStateException + * If the window references a non-existsent PortletEntity */ - PortletWindow getPortletWindow(ContentFragment fragment, String principal) throws FailedToCreateWindowException, FailedToRetrievePortletWindow, PortletEntityNotStoredException; + PortletWindow getPortletWindow(ContentFragment fragment, String principal) + throws FailedToCreateWindowException, + FailedToRetrievePortletWindow, PortletEntityNotStoredException; /** - * Lookup a portlet window in the cache - * If not found, return null + * Lookup a portlet window in the cache If not found, return null * - * @param windowId + * @param windowId * @return the window from the cache or null */ PortletWindow getPortletWindow(String windowId); @@ -73,14 +80,14 @@ PortletWindow createPortletWindow(PortletEntity entity, String windowId); /** - * Create a temporary portlet window - * This window does not have an entity associated with it. + * Create a temporary portlet window This window does not have an entity + * associated with it. * * @param windowId * @return */ PortletWindow createPortletWindow(String windowId); - + /** * * <p> @@ -89,11 +96,11 @@ * * Removes all <code>PortletWindow</code>s associated with this * <code>PortletEntity</code> - * + * * @param portletEntity */ void removeWindows(PortletEntity portletEntity); - + /** * * <p> @@ -101,16 +108,17 @@ * </p> * * Removes a <code>PortletWindow</code> from the window cache. - * + * * @param window */ void removeWindow(PortletWindow window); - + /** - * Gets a {@link Set} of currently available {@link PortletWindow}s within - * the current engine instance. - * - * @return {@link Set} of {@link PortletWindow}s, never returns <code>null</code> + * Gets a {@link Set} of currently available {@link PortletWindow}s within + * the current engine instance. + * + * @return {@link Set} of {@link PortletWindow}s, never returns + * <code>null</code> */ Set getPortletWindows(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/Decoration.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/Decoration.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/Decoration.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,44 +23,46 @@ /** * * @author <href a="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * + * */ public interface Decoration { + /** Default style sheet location */ String DEFAULT_COMMON_STYLE_SHEET = "css/styles.css"; + String DEFAULT_PORTAL_STYLE_SHEET = "css/portal.css"; + String DEFAULT_DESKTOP_STYLE_SHEET = "css/desktop.css"; - + /** Decoration configuration filename */ String CONFIG_FILE_NAME = "decorator.properties"; - + /** Decoration desktop configuration filename */ String CONFIG_DESKTOP_FILE_NAME = "decoratordesktop.properties"; - + /** Property which indicates whether or not decoration supports desktop mode */ String DESKTOP_SUPPORTED_PROPERTY = "desktop.supported"; /** - * Property for specifying the base CSS class to be used to - * create a proper CSS cascade and style isolation for a decoration. + * Property for specifying the base CSS class to be used to create a proper + * CSS cascade and style isolation for a decoration. */ String BASE_CSS_CLASS_PROP = "base.css.class"; /** Property which specifies the resource bundle locator prefix */ String RESOURCE_BUNDLE_PROP = "resource.file"; - + /** Property which specifies the directory name for resource bundle */ String RESOURCES_DIRECTORY_NAME = "resources"; - /** * The name of this Decoration. - * + * * @return Name of this decoration. */ String getName(); - + /** * <p> * Returns the base path for the decoration. @@ -69,25 +71,26 @@ * @return the base path for the decoration. */ String getBasePath(); - + /** * <p> - * Returns the base path for the decoration - * with the relativePath argument added. + * Returns the base path for the decoration with the relativePath argument + * added. * </p> * * @param relativePath - * @return the base path for the decoration with the relativePath argument added. + * @return the base path for the decoration with the relativePath argument + * added. */ - String getBasePath( String relativePath ); - + String getBasePath(String relativePath); + /** * <p> - * Returns the correct path to the resource based on the - * relative <code>path</code> argument. This usually entails - * locating the resource that is most appropriate for the - * current users client and locale. + * Returns the correct path to the resource based on the relative + * <code>path</code> argument. This usually entails locating the resource + * that is most appropriate for the current users client and locale. * </p> + * * <pre> * Example Criterion: * @@ -99,18 +102,18 @@ * </pre> * * <p> - * The implementation should now attempt to resolve the resource using - * logic that starts at the most specific and ends at the most general - * path. + * The implementation should now attempt to resolve the resource using logic + * that starts at the most specific and ends at the most general path. * </p> * * <p> * For exmaples sake, lets say we are concerned with finding the image, - * myimage.gif, within the layout decoration, tigris. The logical progression - * to find the resourc, myimage.gif, would be as follows: + * myimage.gif, within the layout decoration, tigris. The logical + * progression to find the resourc, myimage.gif, would be as follows: * </p> * - * <pre> + * <pre> + * * /decorations/layout/tigris/html/en/US/images/myimage.gif * /decorations/layout/tigris/html/en/images/myimage.gif * /decorations/layout/tigris/html/images/myimage.gif @@ -120,32 +123,31 @@ * </pre> * * @param path - * @return the correct path to the resource based on the - * relative <code>path</code> argument. + * @return the correct path to the resource based on the relative + * <code>path</code> argument. */ String getResource(String path); - + /** * - * @return The appropriate stylesheet to be used with this - * decoration. + * @return The appropriate stylesheet to be used with this decoration. */ String getStyleSheet(); - + /** * - * @return the /portal specific stylesheet to be used with this - * decoration; defined only when decoration supports /desktop. + * @return the /portal specific stylesheet to be used with this decoration; + * defined only when decoration supports /desktop. */ String getStyleSheetPortal(); - + /** * - * @return the /desktop specific stylesheet to be used with this - * decoration; defined only when decoration supports /desktop. + * @return the /desktop specific stylesheet to be used with this decoration; + * defined only when decoration supports /desktop. */ String getStyleSheetDesktop(); - + /** * Returns the list of <code>DecoratorAction</code>s to be displayed * within the portlet window. @@ -153,32 +155,33 @@ * @see org.apache.jetspeed.decoration.DecoratorAction * * @return the list of <code>DecoratorAction</code>s to be displayed - * within the portlet window. + * within the portlet window. */ List getActions(); - + /** - * Set the list of <code>DecoratorAction</code>s to be displayed - * within the portlet window. + * Set the list of <code>DecoratorAction</code>s to be displayed within + * the portlet window. + * * @see org.apache.jetspeed.decoration.DecoratorAction * - * @param actions actions to displayed within this portlet window. + * @param actions + * actions to displayed within this portlet window. */ void setActions(List actions); - + /** - * Allows access to abritrary properties configured - * within your <code>decorator.properties</code> config - * file. + * Allows access to abritrary properties configured within your + * <code>decorator.properties</code> config file. + * * @param name * @return value of decoration property which matches name argument. */ String getProperty(String name); - + /** - * Returns the base CSS class the template should use to - * create a proper CSS cascade and style isolation for a - * decoration. + * Returns the base CSS class the template should use to create a proper CSS + * cascade and style isolation for a decoration. * * @return the base CSS class the template should use. */ @@ -195,30 +198,31 @@ * Set the name of the currently active mode action * */ - void setCurrentModeAction( String currentModeAction ); - + void setCurrentModeAction(String currentModeAction); + /** * Returns the name of the currently active state action * * @return the name of the currently active state action */ String getCurrentStateAction(); - + /** * Set the name of the currently active state action * */ - void setCurrentStateAction( String currentStateAction ); - + void setCurrentStateAction(String currentStateAction); + /** * @return the resource bundle locator prefix. */ String getResourceBundleName(); - + /** * @return the resource bundle for the given Locale and RequestContext. */ - ResourceBundle getResourceBundle( Locale locale, org.apache.jetspeed.request.RequestContext context ); + ResourceBundle getResourceBundle(Locale locale, + org.apache.jetspeed.request.RequestContext context); /** * Indicates whether the decorator supports /desktop Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/DecorationFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/DecorationFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/DecorationFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,8 +24,8 @@ import org.apache.jetspeed.request.RequestContext; /** - * Factory class used for locating Decorations and Themes for - * Fragments and pages. + * Factory class used for locating Decorations and Themes for Fragments and + * pages. * * @see org.apache.jetspeed.decoration.Decoration * @see org.apache.jetspeed.decoration.PortletDecoration @@ -33,100 +33,119 @@ * @see org.apache.jetspeed.decoration.Theme * * @author <href a="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * + * */ public interface DecorationFactory { + /** Default nested layout portlet decorator */ String DEFAULT_NESTED_LAYOUT_PORTLET_DECORATOR = "clear"; - + /** - * Returns a theme containing all of the Decorations for all of - * the layouts on the current page. + * Returns a theme containing all of the Decorations for all of the layouts + * on the current page. * - * @param page Page whose theme we are requesting - * @param requestContext Current portal request. + * @param page + * Page whose theme we are requesting + * @param requestContext + * Current portal request. * @return Theme for this page based on the current portal request. * * @see Theme * @see RequestContext */ Theme getTheme(Page page, RequestContext requestContext); - + /** - * Returns a names portlet Decoration appropriate to the - * current request conetext. + * Returns a names portlet Decoration appropriate to the current request + * conetext. * - * @param name Formal name of the decoration. - * @param requestContext Current portal request. + * @param name + * Formal name of the decoration. + * @param requestContext + * Current portal request. * - * @return Decoration requested. If the decoration does not exist, an - * empty Decoration will be created "in memory" and a message should be logged - * informing the admin that non-existent decoration has been requested. + * @return Decoration requested. If the decoration does not exist, an empty + * Decoration will be created "in memory" and a message should be + * logged informing the admin that non-existent decoration has been + * requested. * * @see RequestContext * @see PortletDecoration */ - PortletDecoration getPortletDecoration(String name, RequestContext requestContext); - + PortletDecoration getPortletDecoration(String name, + RequestContext requestContext); + /** - * Returns a named layout Decoration appropriate to the - * current request conetext. + * Returns a named layout Decoration appropriate to the current request + * conetext. * - * @param name Formal name of the decoration. - * @param requestContext Current portal request. + * @param name + * Formal name of the decoration. + * @param requestContext + * Current portal request. * - * @return Decoration requested. If the decoration does not exist, an - * empty Decoration will be created "in memory" and a message should be logged - * informing the admin that non-existent decoration has been requested. + * @return Decoration requested. If the decoration does not exist, an empty + * Decoration will be created "in memory" and a message should be + * logged informing the admin that non-existent decoration has been + * requested. * * @see LayoutDecoration * @see RequestContext */ - LayoutDecoration getLayoutDecoration(String name, RequestContext requestContext); - + LayoutDecoration getLayoutDecoration(String name, + RequestContext requestContext); + /** * Returns a Decoration for a specific <code>Fragment</code> contained * within the specified <code>Page</code>. * - * @param page Current page - * @param fragment Fragment whose decoration we require. - * @param requestContext Current portal request. + * @param page + * Current page + * @param fragment + * Fragment whose decoration we require. + * @param requestContext + * Current portal request. * - * @return Decoration requested. If the decoration does not exist, an - * empty Decoration will be created "in memory" and a message should be logged - * informing the admin that non-existent decoration has been requested. + * @return Decoration requested. If the decoration does not exist, an empty + * Decoration will be created "in memory" and a message should be + * logged informing the admin that non-existent decoration has been + * requested. * * @see Page * @see Fragment * @see RequestContext */ - Decoration getDecoration(Page page, Fragment fragment, RequestContext requestContext); - + Decoration getDecoration(Page page, Fragment fragment, + RequestContext requestContext); + /** * Indicates whether /desktop is enabled for the current portal request. - * Located here due to range of jetspeed components which need this information and - * already have a DecorationFactory reference. + * Located here due to range of jetspeed components which need this + * information and already have a DecorationFactory reference. * - * @param requestContext current portal request. + * @param requestContext + * current portal request. * - * @return true if /desktop is enabled for the current portal request, otherwise false + * @return true if /desktop is enabled for the current portal request, + * otherwise false */ - boolean isDesktopEnabled( RequestContext requestContext ); - + boolean isDesktopEnabled(RequestContext requestContext); + /** - * Clears the lookup cache of all previous located pathes. This only - * clears the cache the <code>RequestContext</code>'s current user. This - * will generally delegate the cache operation to the <code>PathResolverCache</code> - * currently in use. + * Clears the lookup cache of all previous located pathes. This only clears + * the cache the <code>RequestContext</code>'s current user. This will + * generally delegate the cache operation to the + * <code>PathResolverCache</code> currently in use. * - * @param requestContext Current portal request. + * @param requestContext + * Current portal request. * * @see RequestContext * @see PathResolverCache */ void clearCache(RequestContext requestContext); - + /** * Get the portal-wide list of page decorations. * @@ -138,69 +157,69 @@ * Get the portal-wide list of portlet decorations. * * @return A list of portlet decorations of type <code>String</code> - */ + */ Set getPortletDecorations(RequestContext request); - + /** * Get the portal-wide list of available layouts. * * @return A list of layout portlets of type <code>LayoutInfo</code> - */ + */ List getLayouts(RequestContext request); - + /** * Get the portal-wide list of available desktop page decorations. * * @return A list of desktop skins of type <code>String</code> - */ + */ Set getDesktopPageDecorations(RequestContext request); - + /** * Get the portal-wide list of desktop portlet decorations. * * @return A list of desktop skins of type <code>String</code> */ Set getDesktopPortletDecorations(RequestContext request); - + /** * Get the path to the layout decorations directory. * * @return path to layout decorations directory */ String getLayoutDecorationsBasePath(); - + /** * Get the path to the portlet decorations directory. * * @return path to portlet decorations directory */ String getPortletDecorationsBasePath(); - + /** - * Get the default desktop layout decoration to be used when - * selected layout decoration does not support /desktop. + * Get the default desktop layout decoration to be used when selected layout + * decoration does not support /desktop. * * @return default desktop layout decoration. */ String getDefaultDesktopLayoutDecoration(); - + /** - * Set the default desktop layout decoration to be used when - * selected layout decoration does not support /desktop. + * Set the default desktop layout decoration to be used when selected layout + * decoration does not support /desktop. */ - void setDefaultDesktopLayoutDecoration( String newOne ); - + void setDefaultDesktopLayoutDecoration(String newOne); + /** - * Get the default desktop portlet decoration to be used when - * selected portlet decoration does not support /desktop. + * Get the default desktop portlet decoration to be used when selected + * portlet decoration does not support /desktop. * * @return default desktop portlet decoration. */ String getDefaultDesktopPortletDecoration(); - + /** - * Set the default desktop portlet decoration to be used when - * selected portlet decoration does not support /desktop. + * Set the default desktop portlet decoration to be used when selected + * portlet decoration does not support /desktop. */ - void setDefaultDesktopPortletDecoration( String newOne ); + void setDefaultDesktopPortletDecoration(String newOne); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/LayoutDecoration.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/LayoutDecoration.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/LayoutDecoration.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,21 +20,22 @@ * Decoration specifically targeted at decorating layouts. * * @author <href a="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * + * */ public interface LayoutDecoration extends Decoration { + /** * The header or "banner" template used to decorate the top of a page. * * @return String fully resolved path to the header template. */ String getHeader(); - + /** * The footer" template used to decorate the bottom of a page. * * @return String fully resolved path to the footer template. */ String getFooter(); -} +} Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/LayoutInfo.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/LayoutInfo.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/LayoutInfo.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,9 +18,10 @@ public interface LayoutInfo { + String getName(); - + String getDescription(); - + String getDisplayName(); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/PageEditAccess.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/PageEditAccess.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/PageEditAccess.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,22 +22,26 @@ * @author <href a="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id$ */ -public interface PageEditAccess +public interface PageEditAccess { + /** * @return true if page editing is allowed */ boolean isEditAllowed(); - + /** * @return true if page in edit mode */ boolean isEditing(); - + /** * Switch the Page edit state. - * @param editing intended Page edit state - * @throws SecurityException when trying to set edit state while not allowed + * + * @param editing + * intended Page edit state + * @throws SecurityException + * when trying to set edit state while not allowed */ void setEditing(boolean editing) throws SecurityException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/PathResolverCache.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/PathResolverCache.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/PathResolverCache.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,51 +17,54 @@ package org.apache.jetspeed.decoration; /** - * Simple caching mechanism for storing pathed that were previously located - * by a <code>ResourceValidator</code>. This allows a Decoration to bypass - * hitting the ResourceValidator repeatedly after a path is already known - * to exist. + * Simple caching mechanism for storing pathed that were previously located by a + * <code>ResourceValidator</code>. This allows a Decoration to bypass hitting + * the ResourceValidator repeatedly after a path is already known to exist. * * @author <href a="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * * @see org.apache.jetspeed.decoration.ResourceValidator - * + * */ public interface PathResolverCache { + /** - * Adds a recolved <code>path</code> to the the cache using - * its relative path as the <code>key</code> - * @param key key relative path of the resource. - * @param path full path to resource + * Adds a recolved <code>path</code> to the the cache using its relative + * path as the <code>key</code> + * + * @param key + * key relative path of the resource. + * @param path + * full path to resource */ void addPath(String key, String path); - + /** - * Returns a previously located path using its retlative path - * as the <code>code</code>. - * - * @param key relative path of the resource. - * @return full path to resource or <code>null</code> if no resource - * for the key exists. + * Returns a previously located path using its retlative path as the + * <code>code</code>. + * + * @param key + * relative path of the resource. + * @return full path to resource or <code>null</code> if no resource for + * the key exists. */ String getPath(String key); - + /** - * Removes a full path to a resource from the cache using its - * relative path as the <code>key</code>. + * Removes a full path to a resource from the cache using its relative path + * as the <code>key</code>. * * @param key - * @return The full path to the resource or <code>null</code> - * if the resource path was not cached. + * @return The full path to the resource or <code>null</code> if the + * resource path was not cached. */ String removePath(String key); - - + /** * Clears the entire contents of this cache object. - * + * */ void clear(); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/PortletDecoration.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/PortletDecoration.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/PortletDecoration.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,12 +20,13 @@ * Decoration specifically targeted at decorating portlets. * * @author <href a="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * + * */ public interface PortletDecoration extends Decoration { + /** - * path to the template object used to decorated an individual portlet + * path to the template object used to decorated an individual portlet * window. * * @return Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/ResourceValidator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/ResourceValidator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/ResourceValidator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,16 +21,18 @@ * Validates whether or not a resource exists. * * @author <href a="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * + * */ public interface ResourceValidator { + /** * Validates whether or not a resource exists. * - * @param path Path to verify. - * @return <code>true</code> if a resource exists at the path specified, - * otherwise returns <code>false.</code> + * @param path + * Path to verify. + * @return <code>true</code> if a resource exists at the path specified, + * otherwise returns <code>false.</code> */ boolean resourceExists(String path); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/Theme.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/Theme.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/decoration/Theme.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,35 +24,37 @@ import org.apache.jetspeed.request.RequestContext; /** - * Theme provides a simple aggregation of all of the decorations - * within the current "page." + * Theme provides a simple aggregation of all of the decorations within the + * current "page." * * @author <href a="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * + * */ -public interface Theme +public interface Theme { + /** * - * @return Set of all of the stylesheets needed to properly - * render of the decorations in this theme. + * @return Set of all of the stylesheets needed to properly render of the + * decorations in this theme. */ Set getStyleSheets(); - + /** * Returns a a Decoration for the requested fragment. * - * @param fragment whose decoration we want to retrieve. + * @param fragment + * whose decoration we want to retrieve. * @return Decroration for this fragment. * * @see Decoration * @see Fragment */ Decoration getDecoration(Fragment fragment); - + /** - * Get a list of portlet decoration names used by - * portlets on the current page. + * Get a list of portlet decoration names used by portlets on the current + * page. * * @return unmodifiable list for portlet decoration names. * @@ -60,25 +62,22 @@ * @see Fragment */ Collection getPortletDecorationNames(); - - + /** - * Returns the the top most, "root" layout fragment's - * decoration. + * Returns the the top most, "root" layout fragment's decoration. * - * @return the the top most, "root" layout fragment's - * decoration. + * @return the the top most, "root" layout fragment's decoration. */ LayoutDecoration getPageLayoutDecoration(); - + /** * Initialize a page theme * * @param context */ void init(Page page, DecorationFactory decoration, RequestContext context); - + boolean isInvalidated(); - + void setInvalidated(boolean flag); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentEvent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentEvent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentEvent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,44 +16,50 @@ */ package org.apache.jetspeed.deployment; - /** * <p> * DeploymentEvent * </p> * <p> - * A <code>DeploymentEvent</code> is fired when a DeploymentEventDispatcher is notified that - * a deployment event has occurred, for example, a JAR file being drop into a specific directory. + * A <code>DeploymentEvent</code> is fired when a DeploymentEventDispatcher is + * notified that a deployment event has occurred, for example, a JAR file being + * drop into a specific directory. * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: DeploymentEvent.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public interface DeploymentEvent extends DeploymentStatus +public interface DeploymentEvent extends DeploymentStatus { + /** - * - * <p> - * getDeploymentObject - * </p> - * @see org.apache.jetspeed.deployment.DeploymentObject - * - * @return An instance of <code>org.apache.jetspeed.deployment.DeploymentObject</code> - */ - DeploymentObject getDeploymentObject(); - - /** - * - * <p> - * setStatus - * </p> - * - * Sets the status of this event. @see getEvent() - * @param status - */ - void setStatus(int status); - - String getName(); - - String getPath(); + * + * <p> + * getDeploymentObject + * </p> + * + * @see org.apache.jetspeed.deployment.DeploymentObject + * + * @return An instance of + * <code>org.apache.jetspeed.deployment.DeploymentObject</code> + */ + DeploymentObject getDeploymentObject(); + + /** + * + * <p> + * setStatus + * </p> + * + * Sets the status of this event. + * + * @see getEvent() + * @param status + */ + void setStatus(int status); + + String getName(); + + String getPath(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentEventListener.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentEventListener.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentEventListener.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,10 +23,12 @@ * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: DeploymentEventListener.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface DeploymentEventListener { - public void initialize(); - public void invokeDeploy(DeploymentEvent event) throws DeploymentException; + + public void initialize(); + + public void invokeDeploy(DeploymentEvent event) throws DeploymentException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,7 +23,7 @@ * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: DeploymentException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class DeploymentException extends Exception { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,35 +18,38 @@ import java.io.File; - /** * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * * Interface that provides for firing and dispatching deployment realted events. - * + * */ public interface DeploymentManager { + DeploymentStatus deploy(File aFile) throws DeploymentException; + /** * * <p> * fireDeploymentEvent * </p> * Fires all deployment events registered to this DeploymentManager. - * + * */ void fireDeploymentEvent(); - + /** * * <p> * dispatch * </p> * - * dispatches the DeploymentEvent to all registered deployment event listeners. - * - * @param event {@link DeploymentEvent} to dispatch. + * dispatches the DeploymentEvent to all registered deployment event + * listeners. + * + * @param event + * {@link DeploymentEvent} to dispatch. */ - void dispatch( DeploymentEvent event ); + void dispatch(DeploymentEvent event); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentObject.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentObject.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentObject.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,58 +24,63 @@ * <p> * DeploymentObject * </p> - * <p> - * Object representation of a deployment artifact of some type. + * <p> + * Object representation of a deployment artifact of some type. * </p> * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: DeploymentObject.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface DeploymentObject { - /** - * Closes any resources that may have been opend during the use - * of this ObjectHandler. - * @throws IOException - */ - void close() throws IOException; - - /** - * retreives the the configuration for this deployment artifact - * based on the artifact-relative <code>configPath</code> - * provided. - * @param configPath artifact-relative path to the confiuration file - * @return Configuration of this artificat or <code>null</code> if the - * configuration is not present in the artifact. - * @throws IOException error opening the configuration - */ - InputStream getConfiguration(String configPath) throws IOException; - /** - * - * <p> - * getName - * </p> - * - * @return name of the deployment object. Yeilds the same result as if you were - * to invoke: <code>new java.io.File(getPath()).getName()</code> - */ - String getName(); - - /** - * - * <p> - * getPath - * </p> - * - * @return path the deployment object's source directory or jar/war file. - */ - String getPath(); - - /** - * - * @return the underlying File object - */ - File getFile(); + /** + * Closes any resources that may have been opend during the use of this + * ObjectHandler. + * + * @throws IOException + */ + void close() throws IOException; + + /** + * retreives the the configuration for this deployment artifact based on the + * artifact-relative <code>configPath</code> provided. + * + * @param configPath + * artifact-relative path to the confiuration file + * @return Configuration of this artificat or <code>null</code> if the + * configuration is not present in the artifact. + * @throws IOException + * error opening the configuration + */ + InputStream getConfiguration(String configPath) throws IOException; + + /** + * + * <p> + * getName + * </p> + * + * @return name of the deployment object. Yeilds the same result as if you + * were to invoke: + * <code>new java.io.File(getPath()).getName()</code> + */ + String getName(); + + /** + * + * <p> + * getPath + * </p> + * + * @return path the deployment object's source directory or jar/war file. + */ + String getPath(); + + /** + * + * @return the underlying File object + */ + File getFile(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentStatus.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentStatus.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/deployment/DeploymentStatus.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,16 +20,18 @@ * <p> * DeploymentStatus * </p> + * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id: DeploymentStatus.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface DeploymentStatus { - int STATUS_OKAY = 1; - int STATUS_EVAL = 0; + int STATUS_OKAY = 1; + int STATUS_EVAL = 0; + int STATUS_FAILED = -1; /** @@ -37,10 +39,12 @@ * <p> * getStatus * </p> - * - * @return The status of the deployment. <code>STATUS_OKAY</code> if the deployment was successful, - * <code>STATUS_FAILED</code> if there was a problem deploying the deployment object or <code>-1</code> - * if the status was never set (i.e. this event was never acted upon by a listener). + * + * @return The status of the deployment. <code>STATUS_OKAY</code> if the + * deployment was successful, <code>STATUS_FAILED</code> if there + * was a problem deploying the deployment object or <code>-1</code> + * if the status was never set (i.e. this event was never acted upon + * by a listener). */ int getStatus(); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/desktop/JetspeedDesktop.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/desktop/JetspeedDesktop.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/desktop/JetspeedDesktop.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,24 +20,30 @@ import org.apache.jetspeed.request.RequestContext; /** - * Jetspeed Desktop - * + * Jetspeed Desktop + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ -public interface JetspeedDesktop +public interface JetspeedDesktop { + String DESKTOP_ENABLED_REQUEST_ATTRIBUTE = "desktop.enabled"; - + String DESKTOP_ENCODER_REQUEST_PARAMETER = "encoder"; + String DESKTOP_ENCODER_REQUEST_PARAMETER_VALUE = "desktop"; - + String DESKTOP_AJAX_REQUEST_PARAMETER = "jsdajax"; + String DESKTOP_REQUEST_NOT_AJAX_PARAMETER = "org.apache.jetspeed.desktop.request.not.ajax"; - + String DEFAULT_DESKTOP_PIPELINE_PATH = "/desktop"; + String DEFAULT_DESKTOP_ACTION_PIPELINE_PATH = "/action"; + String DEFAULT_DESKTOP_RENDER_PIPELINE_PATH = "/render"; + String DEFAULT_DESKTOP_CONFIGURE_PIPELINE_PATH = "/dtconfigure"; /** @@ -46,86 +52,96 @@ * @param request */ void render(RequestContext request); - + /** * Indicates whether /desktop is enabled for the current portal request. - * Located here due to range of jetspeed components which need this information and - * already have a DecorationFactory reference. + * Located here due to range of jetspeed components which need this + * information and already have a DecorationFactory reference. * - * @param requestContext current portal request. + * @param requestContext + * current portal request. * - * @return true if /desktop is enabled for the current portal request, otherwise false + * @return true if /desktop is enabled for the current portal request, + * otherwise false */ - boolean isDesktopEnabled( RequestContext requestContext ); - + boolean isDesktopEnabled(RequestContext requestContext); + /** * Retrieve the header resource factory * * @return header resource factory */ HeaderResourceFactory getHeaderResourceFactory(); - + /** * Desktop servlet path ( e.g. /desktop ) * * @return portal base url */ public String getDesktopServletPath(); - + /** * Portal base url ( e.g. http://localhost:8080/jetspeed ) * * @return portal base url */ - public String getPortalBaseUrl( RequestContext requestContext ); - + public String getPortalBaseUrl(RequestContext requestContext); + /** * Portal base url ( e.g. http://localhost:8080/jetspeed ) * * @return portal base url */ - public String getPortalBaseUrl( RequestContext requestContext, boolean encode ); - + public String getPortalBaseUrl(RequestContext requestContext, boolean encode); + /** - * Portal base url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/javascript/dojo/ ) + * Portal base url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/javascript/dojo/ ) * * @return portal base url with relativePath argument appended */ - public String getPortalResourceUrl( RequestContext requestContext, String relativePath ); - + public String getPortalResourceUrl(RequestContext requestContext, + String relativePath); + /** - * Portal base url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/javascript/dojo/ ) + * Portal base url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/javascript/dojo/ ) * * @return portal base url with relativePath argument appended */ - public String getPortalResourceUrl( RequestContext requestContext, String relativePath, boolean encode ); - + public String getPortalResourceUrl(RequestContext requestContext, + String relativePath, boolean encode); + /** * Portal base servlet url ( e.g. http://localhost:8080/jetspeed/desktop/ ) * * @return portal base servlet url */ - public String getPortalUrl( RequestContext requestContext ); - + public String getPortalUrl(RequestContext requestContext); + /** * Portal base servlet url ( e.g. http://localhost:8080/jetspeed/desktop/ ) * * @return portal base servlet url */ - public String getPortalUrl( RequestContext requestContext, boolean encode ); - + public String getPortalUrl(RequestContext requestContext, boolean encode); + /** - * Portal base servlet url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/desktop/default-page.psml ) + * Portal base servlet url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/desktop/default-page.psml ) * * @return portal base servlet url with relativePath argument appended */ - public String getPortalUrl( RequestContext requestContext, String relativePath ); - + public String getPortalUrl(RequestContext requestContext, + String relativePath); + /** - * Portal base servlet url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/desktop/default-page.psml ) + * Portal base servlet url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/desktop/default-page.psml ) * * @return portal base servlet url with relativePath argument appended */ - public String getPortalUrl( RequestContext requestContext, String relativePath, boolean encode ); - + public String getPortalUrl(RequestContext requestContext, + String relativePath, boolean encode); + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/desktop/JetspeedDesktopContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/desktop/JetspeedDesktopContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/desktop/JetspeedDesktopContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,83 +22,92 @@ import org.apache.jetspeed.headerresource.HeaderResource; /** - * Jetspeed Desktop - * + * Jetspeed Desktop + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @author <a href="mailto:smilek ¡÷ apache.org">Steve Milek</a> * @version $Id: JetspeedDesktopContext.java $ */ public interface JetspeedDesktopContext { + String DESKTOP_CONTEXT_ATTRIBUTE = "jetspeedDesktop"; + String DESKTOP_REQUEST_CONTEXT_ATTRIBUTE = "JS2RequestContext"; + String DESKTOP_COMPONENT_MANAGER_ATTRIBUTE = "JS2ComponentManager"; - + String LAYOUT_TEMPLATE_EXTENSION_PROP = "template.extension"; + String LAYOUT_DESKTOP_TEMPLATE_EXTENSION_PROP = "desktop.template.extension"; - + String LAYOUT_TEMPLATE_ID_PROP = "template.id"; + String LAYOUT_PRINT_TEMPLATE_ID_PROP = "template.print.id"; + String LAYOUT_PORTALUSER_TEMPLATE_ID_PROP = "template.portaluser.id"; - + String LAYOUT_TEMPLATE_ID_DEFAULT = "desktop"; - /** * Portal base url ( e.g. http://localhost:8080/jetspeed ) * * @return portal base url */ public String getPortalBaseUrl(); - + /** * Portal base url ( e.g. http://localhost:8080/jetspeed ) * * @return portal base url */ - public String getPortalBaseUrl( boolean encode ); - + public String getPortalBaseUrl(boolean encode); + /** - * Portal base url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/javascript/dojo/ ) + * Portal base url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/javascript/dojo/ ) * * @return portal base url with relativePath argument appended */ - public String getPortalResourceUrl( String relativePath ); - + public String getPortalResourceUrl(String relativePath); + /** - * Portal base url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/javascript/dojo/ ) + * Portal base url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/javascript/dojo/ ) * * @return portal base url with relativePath argument appended */ - public String getPortalResourceUrl( String relativePath, boolean encode ); - + public String getPortalResourceUrl(String relativePath, boolean encode); + /** * Portal base servlet url ( e.g. http://localhost:8080/jetspeed/desktop/ ) * * @return portal base servlet url */ public String getPortalUrl(); - + /** * Portal base servlet url ( e.g. http://localhost:8080/jetspeed/desktop/ ) * * @return portal base servlet url */ - public String getPortalUrl( boolean encode ); - + public String getPortalUrl(boolean encode); + /** - * Portal base servlet url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/desktop/default-page.psml ) + * Portal base servlet url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/desktop/default-page.psml ) * * @return portal base servlet url with relativePath argument appended */ - public String getPortalUrl( String relativePath ); - + public String getPortalUrl(String relativePath); + /** - * Portal base servlet url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/desktop/default-page.psml ) + * Portal base servlet url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/desktop/default-page.psml ) * * @return portal base servlet url with relativePath argument appended */ - public String getPortalUrl( String relativePath, boolean encode ); + public String getPortalUrl(String relativePath, boolean encode); /** * Gets the layout decoration name @@ -106,7 +115,7 @@ * @return */ public String getLayoutDecorationName(); - + /** * <p> * Get the path to the layout decoration desktop template file. @@ -118,16 +127,15 @@ /** * <p> - * Get the path to the layout decoration desktop template file. - * The property name parameter is provided to allow for an alternate - * property value to be used as the filename (without extension) - * of the desktop template file. + * Get the path to the layout decoration desktop template file. The property + * name parameter is provided to allow for an alternate property value to be + * used as the filename (without extension) of the desktop template file. * </p> * * @return the desktop template file path. */ - public String getLayoutTemplatePath( String layoutTemplateIdPropertyName ); - + public String getLayoutTemplatePath(String layoutTemplateIdPropertyName); + /** * <p> * Returns the base path for the layout decoration. @@ -136,18 +144,19 @@ * @return the base path for the layout decoration. */ public String getLayoutBasePath(); - + /** * <p> - * Returns the base path for the layout decoration - * with the relativePath argument added. + * Returns the base path for the layout decoration with the relativePath + * argument added. * </p> * * @param relativePath - * @return the base path for the layout decoration with the relativePath argument added. + * @return the base path for the layout decoration with the relativePath + * argument added. */ - public String getLayoutBasePath( String relativePath ); - + public String getLayoutBasePath(String relativePath); + /** * <p> * Returns the base url for the layout decoration. @@ -156,23 +165,24 @@ * @return the base url for the layout decoration. */ public String getLayoutBaseUrl(); - + /** * <p> - * Returns the base url for the layout decoration - * with the relativePath argument added. + * Returns the base url for the layout decoration with the relativePath + * argument added. * </p> * * @param relativePath - * @return the base url for the layout decoration with the relativePath argument added. + * @return the base url for the layout decoration with the relativePath + * argument added. */ - public String getLayoutBaseUrl( String relativePath ); - + public String getLayoutBaseUrl(String relativePath); + /** * @return the layout decoration resource bundle for the given Locale. */ - public ResourceBundle getLayoutResourceBundle( Locale locale ); - + public ResourceBundle getLayoutResourceBundle(Locale locale); + /** * @return the HeaderResource component. */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/engine/Engine.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/engine/Engine.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/engine/Engine.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,40 +26,42 @@ import org.apache.pluto.services.PortletContainerEnvironment; import org.apache.pluto.services.factory.FactoryManagerService; - /** * Engine Abstraction - to run from both unit tests and servlet - * + * * @author <a href="mailto:david ¡÷ bluesunrise.com">David Sean Taylor</a> * @version $Id: Engine.java 187178 2004-08-02 19:00:15Z weaver $ */ -public interface Engine extends JetspeedEngineConstants, FactoryManagerService, PortletContainerEnvironment +public interface Engine extends JetspeedEngineConstants, FactoryManagerService, + PortletContainerEnvironment { + /** - * Initializes the engine with a commons configuration, starting all early initable services. - * - * @throws JetspeedException when the engine fails to initilialize + * Initializes the engine with a commons configuration, starting all early + * initable services. + * + * @throws JetspeedException + * when the engine fails to initilialize */ - public void start() - throws JetspeedException; + public void start() throws JetspeedException; - /** * Shuts down the Jetspeed engine and all associated services - * - * @throws JetspeedException when the engine fails to shutdown + * + * @throws JetspeedException + * when the engine fails to shutdown */ - public void shutdown() - throws JetspeedException; + public void shutdown() throws JetspeedException; /** * Makes a service request to the engine. - * - * @param context a <code>RequestContext</code> with the state of the request. - * @throws JetspeedException when the engine fails to initilialize + * + * @param context + * a <code>RequestContext</code> with the state of the request. + * @throws JetspeedException + * when the engine fails to initilialize */ - public void service(RequestContext context) - throws JetspeedException; + public void service(RequestContext context) throws JetspeedException; /** * Gets the engine's request default pipeline. @@ -67,14 +69,14 @@ * @return Pipeline The engine's request pipeline. */ public Pipeline getPipeline(); - + /** * Gets the specified engine's request pipeline. * * @return Pipeline A specific request pipeline. - */ + */ public Pipeline getPipeline(String pipelineName); - + /** * Get the Portal Context associated with running thread of the engine * @@ -85,28 +87,29 @@ /** * Gets the real path to an application relative resource * - * @param path The application relative resource + * @param path + * The application relative resource * @return String The real path to that resource */ public String getRealPath(String path); - + /** - * Get the servlet configuration if this engine is running under a servlet container. + * Get the servlet configuration if this engine is running under a servlet + * container. * * @return config The servlet configuration - */ + */ public ServletConfig getServletConfig(); - + /** - * Returns the the RequestContext associated with the current - * thread. This can be accessed throught <code>org.apache.jetspeed.Jetspeed</code> + * Returns the the RequestContext associated with the current thread. This + * can be accessed throught <code>org.apache.jetspeed.Jetspeed</code> * environment class. + * * @return RequestContext associated with the current thread. */ public RequestContext getCurrentRequestContext(); public ComponentManager getComponentManager(); - - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/engine/JetspeedEngineConstants.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/engine/JetspeedEngineConstants.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/engine/JetspeedEngineConstants.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,21 +18,25 @@ /** * This interface contains all the constants for the engine. - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: JetspeedEngineConstants.java 516448 2007-03-09 16:25:47Z ate $ */ public interface JetspeedEngineConstants { + /** - * <p>The prefix used to denote the namespace reserved for and - * used by Jetspeed-specific configuration parameters (such as - * those passed in via servlet container's config file - * (<code>server.xml</code>), or the web app deployment descriptor - * (<code>web.xml</code>).</p> - * - * <p>For example, a parameter in the Jetspeed namespace would be - * <code>org.apache.jetspeed.loggingRoot</code>.</p> + * <p> + * The prefix used to denote the namespace reserved for and used by + * Jetspeed-specific configuration parameters (such as those passed in via + * servlet container's config file (<code>server.xml</code>), or the web + * app deployment descriptor (<code>web.xml</code>). + * </p> + * + * <p> + * For example, a parameter in the Jetspeed namespace would be + * <code>org.apache.jetspeed.loggingRoot</code>. + * </p> */ public static final String CONFIG_NAMESPACE = "org.apache.jetspeed"; @@ -44,6 +48,7 @@ /** This is the default log file to be used for logging */ public static final String DEFAULT_LOGGER = "jetspeed"; + public static final String CONSOLE_LOGGER = "console"; /** @@ -56,16 +61,18 @@ */ public static final String MAIL_SERVER_KEY = "mail.server"; - /** Default Value for the Logging Directory, relative to the webroot */ public static final String LOGGING_ROOT_DEFAULT = "/logs"; + public static final String LOGGING_ROOT = "loggingRoot"; public static final String JETSPEED_PROPERTIES_KEY = "properties"; + public static final String JETSPEED_PROPERTIES_DEFAULT = "/WEB-INF/conf/jetspeed.properties"; - /** If this value is set as applicationRoot, then the webContext is used - * as application root + /** + * If this value is set as applicationRoot, then the webContext is used as + * application root */ public static final String WEB_CONTEXT = "webContext"; @@ -75,23 +82,26 @@ /** Default Value for the Path to the Resources.properties File */ public static final String APPLICATION_ROOT_DEFAULT = WEB_CONTEXT; - /** This is the key used in the jetspeed.properties to access resources + /** + * This is the key used in the jetspeed.properties to access resources * relative to the Web Application root. It might differ from the - * Application root, but the normal case is, that the webapp root - * and the application root point to the same path. + * Application root, but the normal case is, that the webapp root and the + * application root point to the same path. */ public static final String WEBAPP_ROOT_KEY = "webappRoot"; public static final String PIPELINE_CLASS = "pipeline.class"; + public static final String PIPELINE_DEFAULT = "pipeline.default"; + public static final String PIPELINE_DIRECTORY = "pipeline.directory"; /** - * This specifies the factory to use the Jetspeed java.util.prefs.Preferences - * implementation. + * This specifies the factory to use the Jetspeed + * java.util.prefs.Preferences implementation. */ public static final String PREFERENCES_FACTORY = "preferences.factory"; - public static final String PREFERENCES_FACTORY_DEFAULT = - "org.apache.jetspeed.spi.services.prefs.impl.PreferencesFactoryImpl"; + public static final String PREFERENCES_FACTORY_DEFAULT = "org.apache.jetspeed.spi.services.prefs.impl.PreferencesFactoryImpl"; + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/exception/JetspeedException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/exception/JetspeedException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/exception/JetspeedException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,82 +21,73 @@ import org.apache.jetspeed.i18n.KeyedMessage; - /** - * Occurs when anything unexpected happens within Jetspeed.Any defined exceptions - * within Jetspeed should always extend from this. + * Occurs when anything unexpected happens within Jetspeed.Any defined + * exceptions within Jetspeed should always extend from this. * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: JetspeedException.java 516448 2007-03-09 16:25:47Z ate $ - **/ + */ -public class JetspeedException extends Exception +public class JetspeedException extends Exception { + public static final String KEYED_MESSAGE_BUNDLE = "org.apache.jetspeed.exception.JetspeedExceptionMessages"; - + private KeyedMessage keyedMessage; - - public JetspeedException() + + public JetspeedException() { super(); } - - public JetspeedException(String message) + + public JetspeedException(String message) { super(message); } - - public JetspeedException(KeyedMessage typedMessage) + + public JetspeedException(KeyedMessage typedMessage) { super(typedMessage.getMessage()); this.keyedMessage = typedMessage; } - + public JetspeedException(Throwable nested) { super(nested); } - + public JetspeedException(String msg, Throwable nested) { super(msg, nested); } - + public JetspeedException(KeyedMessage keyedMessage, Throwable nested) { super(keyedMessage.getMessage(), nested); this.keyedMessage = keyedMessage; } - + public KeyedMessage getKeyedMessage() { return keyedMessage; } - + public String getMessage() { - if ( keyedMessage != null ) - { - return keyedMessage.getMessage(); - } + if (keyedMessage != null) { return keyedMessage.getMessage(); } return super.getMessage(); } - + public String getMessage(ResourceBundle bundle) { - if ( keyedMessage != null ) - { - return keyedMessage.getMessage(bundle); - } + if (keyedMessage != null) { return keyedMessage.getMessage(bundle); } return super.getMessage(); } public String getMessage(Locale locale) { - if ( keyedMessage != null ) - { - return keyedMessage.getMessage(locale); - } + if (keyedMessage != null) { return keyedMessage.getMessage(locale); } return super.getMessage(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/exception/JetspeedRuntimeException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/exception/JetspeedRuntimeException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/exception/JetspeedRuntimeException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,18 +21,18 @@ import org.apache.jetspeed.i18n.KeyedMessage; - /** * Base exception for all RuntimeExceptions defined within Jetspeed. + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> */ public class JetspeedRuntimeException extends RuntimeException { public static final String KEYED_MESSAGE_BUNDLE = "org.apache.jetspeed.exception.JetspeedExceptionMessages"; - + private KeyedMessage keyedMessage; - + /** * */ @@ -49,12 +49,12 @@ super(arg0); } - public JetspeedRuntimeException(KeyedMessage typedMessage) + public JetspeedRuntimeException(KeyedMessage typedMessage) { super(typedMessage.getMessage()); this.keyedMessage = typedMessage; } - + /** * @param arg0 */ @@ -77,36 +77,27 @@ super(keyedMessage.getMessage(), nested); this.keyedMessage = keyedMessage; } - + public KeyedMessage getKeyedMessage() { return keyedMessage; } - + public String getMessage() { - if ( keyedMessage != null ) - { - return keyedMessage.getMessage(); - } + if (keyedMessage != null) { return keyedMessage.getMessage(); } return super.getMessage(); } - + public String getMessage(ResourceBundle bundle) { - if ( keyedMessage != null ) - { - return keyedMessage.getMessage(bundle); - } + if (keyedMessage != null) { return keyedMessage.getMessage(bundle); } return super.getMessage(); } public String getMessage(Locale locale) { - if ( keyedMessage != null ) - { - return keyedMessage.getMessage(locale); - } + if (keyedMessage != null) { return keyedMessage.getMessage(locale); } return super.getMessage(); } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/factory/PortletFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/factory/PortletFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/factory/PortletFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -33,15 +33,24 @@ * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver </a> * @version $Id: PortletFactory.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface PortletFactory { - void registerPortletApplication(PortletApplication pa, ClassLoader paClassLoader); + + void registerPortletApplication(PortletApplication pa, + ClassLoader paClassLoader); + void unregisterPortletApplication(PortletApplication pa); + boolean isPortletApplicationRegistered(PortletApplication pa); + ClassLoader getPortletApplicationClassLoader(PortletApplication pa); - PortletInstance getPortletInstance( ServletContext servletContext, PortletDefinition pd ) throws PortletException; - PreferencesValidator getPreferencesValidator(PortletDefinition pd ); + + PortletInstance getPortletInstance(ServletContext servletContext, + PortletDefinition pd) throws PortletException; + + PreferencesValidator getPreferencesValidator(PortletDefinition pd); + void updatePortletConfig(PortletDefinition pd); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/factory/PortletInstance.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/factory/PortletInstance.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/factory/PortletInstance.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,10 +24,12 @@ * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id: PortletInstance.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface PortletInstance extends Portlet { + PortletConfig getConfig(); + Portlet getRealPortlet(); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/headerresource/HeaderResource.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/headerresource/HeaderResource.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/headerresource/HeaderResource.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,105 +27,176 @@ */ public interface HeaderResource { + // header section types public final static String HEADER_TYPE_SCRIPT_BLOCK_START = "script-start"; + public final static int HEADER_TYPE_ID_SCRIPT_BLOCK_START = 1; - + public final static String HEADER_TYPE_SCRIPT_BLOCK = "script"; + public final static int HEADER_TYPE_ID_SCRIPT_BLOCK = 2; - + public final static String HEADER_TYPE_SCRIPT_BLOCK_END = "script-end"; + public final static int HEADER_TYPE_ID_SCRIPT_BLOCK_END = 3; - + public final static String HEADER_TYPE_SCRIPT_TAG = "script-tag"; + public final static int HEADER_TYPE_ID_SCRIPT_TAG = 4; - + public final static String HEADER_TYPE_STYLE_BLOCK = "style"; + public final static int HEADER_TYPE_ID_STYLE_BLOCK = 5; - + public final static String HEADER_TYPE_LINK_TAG = "link-tag"; + public final static int HEADER_TYPE_ID_LINK_TAG = 6; - + public final static String HEADER_TYPE_BASE_TAG = "base-tag"; + public final static int HEADER_TYPE_ID_BASE_TAG = 7; - + // header section configuration public final static String HEADER_CONFIG_ORDER = "header.order"; + public final static String HEADER_CONFIG_TYPES = "header.types"; + public final static String HEADER_CONFIG_REQUIREDFLAG = "header.requiredflag"; + public final static String HEADER_CONFIG_DOJO = "dojo"; + public final static String HEADER_CONFIG_DESKTOP = "desktop"; - - public final static String HEADER_INTERNAL_INCLUDED_NAMES = "header.internal.names"; // internal use - not a configuration entry name - + + public final static String HEADER_INTERNAL_INCLUDED_NAMES = "header.internal.names"; // internal + + // use + // - + // not + // a + // configuration + // entry + // name + // header section predefined names public final static String HEADER_SECTION_BASE_TAG = "header.basetag"; + public final static String HEADER_SECTION_NAME_PREFIX_DOJO = "header.dojo."; + public final static String HEADER_SECTION_DOJO_PARAMETERS = "header.dojo.parameters"; + public final static String HEADER_SECTION_DOJO_PREINIT = "header.dojo.preinit"; + public final static String HEADER_SECTION_DOJO_CONFIG = "header.dojo.config"; + public final static String HEADER_SECTION_DOJO_INIT = "header.dojo.init"; + public final static String HEADER_SECTION_DOJO_REQUIRES_CORE = "header.dojo.requires.core"; + public final static String HEADER_SECTION_DOJO_MODULES_PATH = "header.dojo.modules.path"; + public final static String HEADER_SECTION_DOJO_REQUIRES_MODULES = "header.dojo.requires.modules"; + public final static String HEADER_SECTION_DOJO_WRITEINCLUDES = "header.dojo.writeincludes"; + public final static String HEADER_SECTION_DOJO_MODULES_NAMESPACE = "header.dojo.modules.namespace"; + public final static String HEADER_SECTION_DOJO_STYLE_BODYEXPAND = "header.dojo.style.bodyexpand"; + public final static String HEADER_SECTION_DOJO_STYLE_BODYEXPAND_NOSCROLL = "header.dojo.style.bodyexpand.noscroll"; + public final static String HEADER_SECTION_DESKTOP_STYLE_LAYOUT = "header.desktop.style.layout"; + public final static String HEADER_SECTION_DESKTOP_INIT = "header.desktop.init"; - + public final static String HEADER_INTERNAL_JETSPEED_VAR_NAME = "jetspeed"; - public final static String HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME = "djConfig." + HEADER_INTERNAL_JETSPEED_VAR_NAME; // internal use - not a configuration entry name - public final static String HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE = HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + "."; // internal use - not a configuration entry name - - + + public final static String HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME = "djConfig." + + HEADER_INTERNAL_JETSPEED_VAR_NAME; // internal use - not a + + // configuration entry name + + public final static String HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME_SCOPE = HEADER_INTERNAL_DOJO_CONFIG_JETSPEED_VAR_NAME + + "."; // internal use - not a configuration entry name + // header configuration - dojo public final static String HEADER_CONFIG_DOJO_ENABLE = "dojo.enable"; + public final static String HEADER_CONFIG_DOJO_PATH = "dojo.path"; + public final static String HEADER_CONFIG_DOJO_PARAM_ISDEBUG = "dojo.parameter.isDebug"; + public final static String HEADER_CONFIG_DOJO_PARAM_DEBUGALLCOSTS = "dojo.parameter.debugAtAllCosts"; + public final static String HEADER_CONFIG_DOJO_PARAM_PREVENT_BACKBUTTON_FIX = "dojo.parameter.preventBackButtonFix"; + public final static String HEADER_CONFIG_DOJO_PARAMS = "dojo.parameters"; + public final static String HEADER_CONFIG_DOJO_REQUIRES_CORE = "dojo.requires.core"; + public final static String HEADER_CONFIG_DOJO_MODULES_PATH = "dojo.modules.path"; + public final static String HEADER_CONFIG_DOJO_MODULES_NAMESPACE = "dojo.modules.namespace"; + public final static String HEADER_CONFIG_DOJO_REQUIRES_MODULES = "dojo.requires.modules"; - + // header configuration - desktop public final static String HEADER_CONFIG_DESKTOP_LAYOUT_DECORATION_DEFAULT = "decoration.layout"; + public final static String HEADER_CONFIG_DESKTOP_PORTLET_DECORATION_DEFAULT = "decoration.portlet"; + public final static String HEADER_CONFIG_DESKTOP_PAGE_AJAXNAVIGATION = "page.ajaxnavigation"; + public final static String HEADER_CONFIG_DESKTOP_PAGE_ACTION_BUTTON_TOOLTIP = "page.action.button.tooltip"; + public final static String HEADER_CONFIG_DESKTOP_WINDOW_TILING = "window.tiling"; + public final static String HEADER_CONFIG_DESKTOP_WINDOW_HEIGHT_EXPAND = "window.heightexpand"; + public final static String HEADER_CONFIG_DESKTOP_WINDOW_HEIGHT = "window.height"; + public final static String HEADER_CONFIG_DESKTOP_WINDOW_WIDTH = "window.width"; + public final static String HEADER_CONFIG_DESKTOP_WINDOW_ACTION_BUTTON_ORDER = "window.action.button.order"; + public final static String HEADER_CONFIG_DESKTOP_WINDOW_ACTION_NOIMAGE = "window.action.noimage"; + public final static String HEADER_CONFIG_DESKTOP_WINDOW_ACTION_MENU_ORDER = "window.action.menu.order"; + public final static String HEADER_CONFIG_DESKTOP_WINDOW_ACTION_BUTTON_MAX = "window.action.button.maximum"; + public final static String HEADER_CONFIG_DESKTOP_WINDOW_ACTION_BUTTON_TOOLTIP = "window.action.button.tooltip"; + public final static String HEADER_CONFIG_DESKTOP_WINDOW_ICON_ENABLED = "window.icon.enabled"; + public final static String HEADER_CONFIG_DESKTOP_WINDOW_ICON_PATH = "window.icon.path"; + public final static String HEADER_CONFIG_DESKTOP_WINDOW_TITLEBAR_ENABLED = "window.titlebar.enabled"; + public final static String HEADER_CONFIG_DESKTOP_WINDOW_RESIZEBAR_ENABLED = "window.resizebar.enabled"; - + public final static String DESKTOP_JSON_WINDOW_ACTION_BUTTON_ORDER = "windowActionButtonOrder"; + public final static String DESKTOP_JSON_WINDOW_ACTION_NOIMAGE = "windowActionNoImage"; + public final static String DESKTOP_JSON_WINDOW_ACTION_MENU_ORDER = "windowActionMenuOrder"; + public final static String DESKTOP_JSON_WINDOW_ACTION_BUTTON_MAX = "windowActionButtonMax"; + public final static String DESKTOP_JSON_WINDOW_ACTION_BUTTON_TOOLTIP = "windowActionButtonTooltip"; + public final static String DESKTOP_JSON_WINDOW_ICON_ENABLED = "windowIconEnabled"; + public final static String DESKTOP_JSON_WINDOW_ICON_PATH = "windowIconPath"; + public final static String DESKTOP_JSON_WINDOW_TITLEBAR_ENABLED = "windowTitlebar"; + public final static String DESKTOP_JSON_WINDOW_RESIZEBAR_ENABLED = "windowResizebar"; - - + public final static String HEADER_INTERNAL_CONFIG_DESKTOP_WINDOW_ACTION = "desktop.window.action"; - + public final static String HEADER_DEBUG_REQUIRES = "jetspeed.desktop.debug"; - + /** * Output all content (that has not already been output) * @@ -139,215 +210,233 @@ * @return content string for inclusion in html <head> */ public String getContent(); - + /** * Output all unnamed content (that has not already been output) * * @return content string for inclusion in html <head> */ public String getUnnamedContent(); - + /** * Output all getHeaderSections() content (that has not already been output) * * @return content string for inclusion in html <head> */ public String getNamedContent(); - + /** - * Output the one getHeaderSections() content entry with a key that matches headerName (if it has not already been output) + * Output the one getHeaderSections() content entry with a key that matches + * headerName (if it has not already been output) * * @return content string for inclusion in html <head> */ - public String getNamedContent( String headerName ); - + public String getNamedContent(String headerName); + /** - * Output getHeaderSections() content entries with key prefixes that match headerNamePrefix (if it has not already been output) + * Output getHeaderSections() content entries with key prefixes that match + * headerNamePrefix (if it has not already been output) * * @return content string for inclusion in html <head> */ - public String getNamedContentForPrefix( String headerNamePrefix ); - + public String getNamedContentForPrefix(String headerNamePrefix); + /** - * Add text argument to the getHeaderSections() content entry with a key that matches addToHeaderName argument + * Add text argument to the getHeaderSections() content entry with a key + * that matches addToHeaderName argument * */ - public void addHeaderSectionFragment( String addToHeaderName, String text ); - + public void addHeaderSectionFragment(String addToHeaderName, String text); + /** - * If no previous call using value of headerFragmentName argument has been added to any getHeaderSections() content entry, - * add text argument to the getHeaderSections() content entry with a key that matches addToHeaderName argument + * If no previous call using value of headerFragmentName argument has been + * added to any getHeaderSections() content entry, add text argument to the + * getHeaderSections() content entry with a key that matches addToHeaderName + * argument * */ - public void addHeaderSectionFragment( String headerFragmentName, String addToHeaderName, String text ); - + public void addHeaderSectionFragment(String headerFragmentName, + String addToHeaderName, String text); + /** - * Indicate whether value of headerFragmentName argument has been used to add to any getHeaderSections() content entry + * Indicate whether value of headerFragmentName argument has been used to + * add to any getHeaderSections() content entry * - * @return true if headerFragmentName argument has been used to add to any getHeaderSections() content entry + * @return true if headerFragmentName argument has been used to add to any + * getHeaderSections() content entry */ - public boolean hasHeaderSectionFragment( String headerFragmentName ); - + public boolean hasHeaderSectionFragment(String headerFragmentName); + /** * Indicate whether value of headerName is an included header section * * @return true if headerName argument is an included header section */ - public boolean isHeaderSectionIncluded( String headerName ); + public boolean isHeaderSectionIncluded(String headerName); /** - * Get the type of the getHeaderSections() content entry with a key that matches headerName argument + * Get the type of the getHeaderSections() content entry with a key that + * matches headerName argument * * @return type of header section */ - public String getHeaderSectionType( String headerName ); - + public String getHeaderSectionType(String headerName); + /** - * Set the type of the getHeaderSections() content entry with a key that matches headerName argument - * to the value of the headerType argument + * Set the type of the getHeaderSections() content entry with a key that + * matches headerName argument to the value of the headerType argument */ - public void setHeaderSectionType( String headerName, String headerType ); - + public void setHeaderSectionType(String headerName, String headerType); + /** - * Get the requiredflag of the getHeaderSections() content entry with a key that matches headerName argument + * Get the requiredflag of the getHeaderSections() content entry with a key + * that matches headerName argument * * @return requiredflag for header section */ - public String getHeaderSectionRequiredFlag( String headerName ); - - + public String getHeaderSectionRequiredFlag(String headerName); + /** - * Set the requiredflag of the getHeaderSections() content entry with a key that matches headerName argument - * to the value of the headerReqFlag argument + * Set the requiredflag of the getHeaderSections() content entry with a key + * that matches headerName argument to the value of the headerReqFlag + * argument */ - public void setHeaderSectionRequiredFlag( String headerName, String headerReqFlag ); - + public void setHeaderSectionRequiredFlag(String headerName, + String headerReqFlag); + /** * Access modifiable header configuration settings * - * @return Map containing modifiable header configuration settings + * @return Map containing modifiable header configuration settings */ public Map getHeaderDynamicConfiguration(); - + /** * Access complete header configuration settings * - * @return unmodifiable Map containing complete header configuration settings + * @return unmodifiable Map containing complete header configuration + * settings */ public Map getHeaderConfiguration(); - + /** * Is request for /desktop rather than /portal * * @return true if request is for /desktop, false if request is for /portal */ public boolean isDesktop(); - + /** * Portal base url ( e.g. http://localhost:8080/jetspeed ) * * @return portal base url */ public String getPortalBaseUrl(); - + /** * Portal base url ( e.g. http://localhost:8080/jetspeed ) * * @return portal base url */ - public String getPortalBaseUrl( boolean encode ); - + public String getPortalBaseUrl(boolean encode); + /** - * Portal base url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/javascript/dojo/ ) + * Portal base url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/javascript/dojo/ ) * * @return portal base url with relativePath argument appended */ - public String getPortalResourceUrl( String relativePath ); - + public String getPortalResourceUrl(String relativePath); + /** - * Portal base url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/javascript/dojo/ ) + * Portal base url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/javascript/dojo/ ) * * @return portal base url with relativePath argument appended */ - public String getPortalResourceUrl( String relativePath, boolean encode ); - + public String getPortalResourceUrl(String relativePath, boolean encode); + /** * Portal base servlet url ( e.g. http://localhost:8080/jetspeed/desktop/ ) * * @return portal base servlet url */ public String getPortalUrl(); - + /** * Portal base servlet url ( e.g. http://localhost:8080/jetspeed/desktop/ ) * * @return portal base servlet url */ - public String getPortalUrl( boolean encode ); - + public String getPortalUrl(boolean encode); + /** - * Portal base servlet url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/desktop/default-page.psml ) + * Portal base servlet url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/desktop/default-page.psml ) * * @return portal base servlet url with relativePath argument appended */ - public String getPortalUrl( String relativePath ); - + public String getPortalUrl(String relativePath); + /** - * Portal base servlet url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/desktop/default-page.psml ) + * Portal base servlet url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/desktop/default-page.psml ) * * @return portal base servlet url with relativePath argument appended */ - public String getPortalUrl( String relativePath, boolean encode ); - - - - // dojo - special convenience methods - + public String getPortalUrl(String relativePath, boolean encode); + + // dojo - special convenience methods + /** - * If no previous call using value of dojoRequire argument has been added to any getHeaderSections() content entry, - * add text argument to getHeaderSections() content entry for dojo core require statements + * If no previous call using value of dojoRequire argument has been added to + * any getHeaderSections() content entry, add text argument to + * getHeaderSections() content entry for dojo core require statements * */ - public void dojoAddCoreLibraryRequire( String dojoRequire ); - + public void dojoAddCoreLibraryRequire(String dojoRequire); + /** - * Split dojoRequires argument using ';' delimiter and for each resulting dojoRequire value, if no previous call - * using dojoRequire value has been added to any getHeaderSections() content entry, - * add text argument to getHeaderSections() content entry for dojo core require statements + * Split dojoRequires argument using ';' delimiter and for each resulting + * dojoRequire value, if no previous call using dojoRequire value has been + * added to any getHeaderSections() content entry, add text argument to + * getHeaderSections() content entry for dojo core require statements * */ - public void dojoAddCoreLibraryRequires( String dojoRequires ); - + public void dojoAddCoreLibraryRequires(String dojoRequires); + /** - * If no previous call using value of dojoRequire argument has been added to any getHeaderSections() content entry, - * add text argument to getHeaderSections() content entry for dojo library module require statements + * If no previous call using value of dojoRequire argument has been added to + * any getHeaderSections() content entry, add text argument to + * getHeaderSections() content entry for dojo library module require + * statements * */ - public void dojoAddModuleLibraryRequire( String dojoRequire ); - + public void dojoAddModuleLibraryRequire(String dojoRequire); + /** - * Split dojoRequires argument using ';' delimiter and for each resulting dojoRequire value, if no previous call - * using dojoRequire value has been added to any getHeaderSections() content entry, - * add text argument to getHeaderSections() content entry for dojo library module require statements + * Split dojoRequires argument using ';' delimiter and for each resulting + * dojoRequire value, if no previous call using dojoRequire value has been + * added to any getHeaderSections() content entry, add text argument to + * getHeaderSections() content entry for dojo library module require + * statements * */ - public void dojoAddModuleLibraryRequires( String dojoRequires ); - + public void dojoAddModuleLibraryRequires(String dojoRequires); + /** * Assure that header section name for dojo body expand style is included * */ - public void dojoAddBodyExpandStyle( boolean omitWindowScrollbars ); - + public void dojoAddBodyExpandStyle(boolean omitWindowScrollbars); + /** - * Enable dojo by setting appropriate modifiable header configuration setting + * Enable dojo by setting appropriate modifiable header configuration + * setting * */ public void dojoEnable(); - - - - + /** * Add tag information to this instance. * @@ -357,43 +446,49 @@ * * Java code is: * - * HashMap map=new HashMap(); - * map.put("a","1"); - * map.put("b","2"); + * HashMap map=new HashMap(); map.put("a","1"); map.put("b","2"); * headerResouce.addHeaderInfo("foo",map,"FOO FOO"); * - * @param elementName Tag's name - * @param attributes Tag's attributes - * @param text Tag's content + * @param elementName + * Tag's name + * @param attributes + * Tag's attributes + * @param text + * Tag's content */ public void addHeaderInfo(String elementName, Map attributes, String text); /** * Add text as-is to this instance. * - * @param text content + * @param text + * content */ public void addHeaderInfo(String text); - + /** * Convenient method to add <script> tag with defer option. * - * @param path Javascript file path - * @param defer defer attributes for <script> tag. + * @param path + * Javascript file path + * @param defer + * defer attributes for <script> tag. */ public void addJavaScript(String path, boolean defer); /** * Convenient method to add <script> tag. * - * @param path Javascript file path + * @param path + * Javascript file path */ public void addJavaScript(String path); /** * Convenient method to add <link> tag. * - * @param path CSS file path + * @param path + * CSS file path */ public void addStyleSheet(String path); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/headerresource/HeaderResourceFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/headerresource/HeaderResourceFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/headerresource/HeaderResourceFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,7 +32,8 @@ * jetspeed-spring.xml. * * @author <a href="mailto:shinsuke ¡÷ yahoo.co.jp">Shinsuke Sugaya</a> - * @version $Id: PortalReservedParameters.java 188569 2005-05-13 13:35:18Z weaver $ + * @version $Id: PortalReservedParameters.java 188569 2005-05-13 13:35:18Z + * weaver $ */ public interface HeaderResourceFactory { @@ -43,15 +44,18 @@ * @param requestContext * @return */ - public abstract HeaderResource getHeaderResouce(RequestContext requestContext); - + public abstract HeaderResource getHeaderResouce( + RequestContext requestContext); + /** * Provides HeaderResource instance from RequestContext. * * @param requestContext * @return */ - public abstract HeaderResource getHeaderResource( RequestContext requestContext, BasePortalURL baseUrlAccess, boolean isDesktop, Map headerConfiguration ); + public abstract HeaderResource getHeaderResource( + RequestContext requestContext, BasePortalURL baseUrlAccess, + boolean isDesktop, Map headerConfiguration); /** * Provides HeaderResource instance from PortletRequest. Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/headerresource/HeaderResourceLib.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/headerresource/HeaderResourceLib.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/headerresource/HeaderResourceLib.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,10 +16,10 @@ */ package org.apache.jetspeed.headerresource; +import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Collection; import javax.servlet.http.HttpServletRequest; @@ -34,205 +34,235 @@ */ public class HeaderResourceLib { - protected final static String EOL = "\r\n"; // html eol + + protected final static String EOL = "\r\n"; // html eol + private final static String MAILTO_URL_SCHEME = "mailto"; + private final static int MAILTO_URL_SCHEME_LEN = MAILTO_URL_SCHEME.length(); - - public static int getHeaderTypeId( String headerType ) + + public static int getHeaderTypeId(String headerType) { int headerTypeNumber = -1; - if ( headerType != null ) + if (headerType != null) { - if ( headerType.equals( HeaderResource.HEADER_TYPE_SCRIPT_BLOCK ) ) + if (headerType.equals(HeaderResource.HEADER_TYPE_SCRIPT_BLOCK)) { headerTypeNumber = HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK; } - else if ( headerType.equals( HeaderResource.HEADER_TYPE_SCRIPT_BLOCK_START ) ) + else if (headerType + .equals(HeaderResource.HEADER_TYPE_SCRIPT_BLOCK_START)) { headerTypeNumber = HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK_START; } - else if ( headerType.equals( HeaderResource.HEADER_TYPE_SCRIPT_TAG ) ) + else if (headerType.equals(HeaderResource.HEADER_TYPE_SCRIPT_TAG)) { headerTypeNumber = HeaderResource.HEADER_TYPE_ID_SCRIPT_TAG; } - else if ( headerType.equals( HeaderResource.HEADER_TYPE_SCRIPT_BLOCK_END ) ) + else if (headerType + .equals(HeaderResource.HEADER_TYPE_SCRIPT_BLOCK_END)) { headerTypeNumber = HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK_END; } - else if ( headerType.equals( HeaderResource.HEADER_TYPE_STYLE_BLOCK ) ) + else if (headerType.equals(HeaderResource.HEADER_TYPE_STYLE_BLOCK)) { headerTypeNumber = HeaderResource.HEADER_TYPE_ID_STYLE_BLOCK; } - else if ( headerType.equals( HeaderResource.HEADER_TYPE_LINK_TAG ) ) + else if (headerType.equals(HeaderResource.HEADER_TYPE_LINK_TAG)) { headerTypeNumber = HeaderResource.HEADER_TYPE_ID_LINK_TAG; } - else if ( headerType.equals( HeaderResource.HEADER_TYPE_BASE_TAG ) ) + else if (headerType.equals(HeaderResource.HEADER_TYPE_BASE_TAG)) { headerTypeNumber = HeaderResource.HEADER_TYPE_ID_BASE_TAG; } } return headerTypeNumber; } - - public static String getHeaderType( Integer headerTypeId ) + + public static String getHeaderType(Integer headerTypeId) { String headerType = null; - if ( headerTypeId != null ) + if (headerTypeId != null) { int typeid = headerTypeId.intValue(); - if ( typeid == HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK ) + if (typeid == HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK) { headerType = HeaderResource.HEADER_TYPE_SCRIPT_BLOCK; } - else if ( typeid == HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK_START ) + else if (typeid == HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK_START) { - headerType = HeaderResource.HEADER_TYPE_SCRIPT_BLOCK_START ; + headerType = HeaderResource.HEADER_TYPE_SCRIPT_BLOCK_START; } - else if ( typeid == HeaderResource.HEADER_TYPE_ID_SCRIPT_TAG ) + else if (typeid == HeaderResource.HEADER_TYPE_ID_SCRIPT_TAG) { headerType = HeaderResource.HEADER_TYPE_SCRIPT_TAG; } - else if ( typeid == HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK_END ) + else if (typeid == HeaderResource.HEADER_TYPE_ID_SCRIPT_BLOCK_END) { headerType = HeaderResource.HEADER_TYPE_SCRIPT_BLOCK_END; } - else if ( typeid == HeaderResource.HEADER_TYPE_ID_STYLE_BLOCK ) + else if (typeid == HeaderResource.HEADER_TYPE_ID_STYLE_BLOCK) { headerType = HeaderResource.HEADER_TYPE_STYLE_BLOCK; } - else if ( typeid == HeaderResource.HEADER_TYPE_ID_LINK_TAG ) + else if (typeid == HeaderResource.HEADER_TYPE_ID_LINK_TAG) { headerType = HeaderResource.HEADER_TYPE_LINK_TAG; } - else if ( typeid == HeaderResource.HEADER_TYPE_ID_BASE_TAG ) + else if (typeid == HeaderResource.HEADER_TYPE_ID_BASE_TAG) { headerType = HeaderResource.HEADER_TYPE_BASE_TAG; } } return headerType; } - - // get portal urls - these are here as an attempt to reduce as much code duplication as possible - // - some of the methods are constructed oddly due to their dual goal of reducing - // duplication while allowing for caller caching - + + // get portal urls - these are here as an attempt to reduce as much code + // duplication as possible + // - some of the methods are constructed oddly due to their dual goal of + // reducing + // duplication while allowing for caller caching + /** * Portal base url ( e.g. http://localhost:8080/jetspeed ) * * @return portal base url */ - public static String getPortalBaseUrl( RequestContext requestContext ) + public static String getPortalBaseUrl(RequestContext requestContext) { - return getPortalBaseUrl( requestContext, null ); + return getPortalBaseUrl(requestContext, null); } - + /** * Portal base url ( e.g. http://localhost:8080/jetspeed ) * - * The optional BasePortalURL argument is provided to allow the common BasePortalURL usage by various jetspeed components - * to be properly supported in this url generation + * The optional BasePortalURL argument is provided to allow the common + * BasePortalURL usage by various jetspeed components to be properly + * supported in this url generation * * @return portal base url */ - public static String getPortalBaseUrl( RequestContext requestContext, BasePortalURL baseUrlAccessOverride ) + public static String getPortalBaseUrl(RequestContext requestContext, + BasePortalURL baseUrlAccessOverride) { return getPortalBaseUrl(requestContext, baseUrlAccessOverride, false); } - + /** * Portal base url ( e.g. http://localhost:8080/jetspeed ) * - * The optional BasePortalURL argument is provided to allow the common BasePortalURL usage by various jetspeed components - * to be properly supported in this url generation + * The optional BasePortalURL argument is provided to allow the common + * BasePortalURL usage by various jetspeed components to be properly + * supported in this url generation * - * When the fullUrl parameter is true, the scheme, servername and port will be provided in the baseUrl, - * regardless if global property portalurl.relative.only is set to true in jetspeed.properties. - * This is needed for HeaderResourceImpl.jetspeedGenerateBasetag() for rendering a valid base tag (for which IE requires an absolute url to work). - * <br/> - * Note: if portalurl.relative.only is set to true to support a Proxy based front end, better remove de (default) "header.basetag" rendering setting - * from assembly/headtag.xml, otherwise the desktop still won't work properly behind the Proxy. + * When the fullUrl parameter is true, the scheme, servername and port will + * be provided in the baseUrl, regardless if global property + * portalurl.relative.only is set to true in jetspeed.properties. This is + * needed for HeaderResourceImpl.jetspeedGenerateBasetag() for rendering a + * valid base tag (for which IE requires an absolute url to work). <br/> + * Note: if portalurl.relative.only is set to true to support a Proxy based + * front end, better remove de (default) "header.basetag" rendering setting + * from assembly/headtag.xml, otherwise the desktop still won't work + * properly behind the Proxy. * * @return portal base url */ - public static String getPortalBaseUrl( RequestContext requestContext, BasePortalURL baseUrlAccessOverride, boolean fullUrl ) + public static String getPortalBaseUrl(RequestContext requestContext, + BasePortalURL baseUrlAccessOverride, boolean fullUrl) { HttpServletRequest request = requestContext.getRequest(); StringBuffer baseurl = new StringBuffer(); - if ( fullUrl || !requestContext.getPortalURL().isRelativeOnly() ) + if (fullUrl || !requestContext.getPortalURL().isRelativeOnly()) { - if ( baseUrlAccessOverride == null ) + if (baseUrlAccessOverride == null) { - baseurl.append( request.getScheme() ).append( "://" ).append( request.getServerName() ).append( ":" ).append( request.getServerPort() ); + baseurl.append(request.getScheme()).append("://").append( + request.getServerName()).append(":").append( + request.getServerPort()); } else { - baseurl.append( baseUrlAccessOverride.getServerScheme() ).append( "://" ).append( baseUrlAccessOverride.getServerName() ).append( ":" ).append( baseUrlAccessOverride.getServerPort() ); + baseurl.append(baseUrlAccessOverride.getServerScheme()).append( + "://").append(baseUrlAccessOverride.getServerName()) + .append(":").append( + baseUrlAccessOverride.getServerPort()); } } baseurl.append(request.getContextPath()); return baseurl.toString(); } - + /** * Portal base servlet url ( e.g. http://localhost:8080/jetspeed/desktop/ ) - * Expects portalBaseUrl argument to be defined (ie. it does not call getPortalBaseUrl) + * Expects portalBaseUrl argument to be defined (ie. it does not call + * getPortalBaseUrl) * * @return portal base servlet url */ - public static String getPortalUrl( String portalBaseUrl, RequestContext requestContext ) + public static String getPortalUrl(String portalBaseUrl, + RequestContext requestContext) { HttpServletRequest request = requestContext.getRequest(); StringBuffer portalurl = new StringBuffer(); - return portalurl.append( portalBaseUrl ).append( request.getServletPath() ).toString(); + return portalurl.append(portalBaseUrl).append(request.getServletPath()) + .toString(); } - + /** * Portal base servlet url ( e.g. http://localhost:8080/jetspeed/desktop/ ) - * Expects portalBaseUrl argument to be defined (ie. it does not call getPortalBaseUrl) - * Also expects servletPath argument to be defined + * Expects portalBaseUrl argument to be defined (ie. it does not call + * getPortalBaseUrl) Also expects servletPath argument to be defined * * @return portal base servlet url */ - public static String getPortalUrl( String portalBaseUrl, RequestContext requestContext, String servletPath ) + public static String getPortalUrl(String portalBaseUrl, + RequestContext requestContext, String servletPath) { HttpServletRequest request = requestContext.getRequest(); StringBuffer portalurl = new StringBuffer(); - return portalurl.append( portalBaseUrl ).append( ( servletPath == null ) ? request.getServletPath() : servletPath ).toString(); + return portalurl.append(portalBaseUrl).append( + (servletPath == null) ? request.getServletPath() : servletPath) + .toString(); } - + /** - * Portal base servlet url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/desktop/default-page.psml ) - * Expects portalUrl argument to be defined (ie. it does not call getPortalUrl) + * Portal base servlet url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/desktop/default-page.psml ) Expects + * portalUrl argument to be defined (ie. it does not call getPortalUrl) * * @return portal base servlet url with relativePath argument appended */ - public static String getPortalUrl( String relativePath, String portalUrl ) + public static String getPortalUrl(String relativePath, String portalUrl) { - return getPortalUrl( relativePath, portalUrl, false, null ); + return getPortalUrl(relativePath, portalUrl, false, null); } - + /** - * Portal base servlet url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/desktop/default-page.psml ) - * Expects portalUrl argument to be defined (ie. it does not call getPortalUrl) - * RequestContext argument is needed only when encode argument is true (it's needed to call HttpServletResponse.encodeURL()) + * Portal base servlet url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/desktop/default-page.psml ) Expects + * portalUrl argument to be defined (ie. it does not call getPortalUrl) + * RequestContext argument is needed only when encode argument is true (it's + * needed to call HttpServletResponse.encodeURL()) * - * Method signature/behavior is a bit strange because this is a static method trying to accomodate - * callers that lazy cache portalUrl string + * Method signature/behavior is a bit strange because this is a static + * method trying to accomodate callers that lazy cache portalUrl string * * @return portal base servlet url with relativePath argument appended */ - public static String getPortalUrl( String relativePath, String portalUrl, boolean encode, RequestContext requestContext ) + public static String getPortalUrl(String relativePath, String portalUrl, + boolean encode, RequestContext requestContext) { - if ( relativePath == null ) - relativePath = ""; - if ( relativePath.indexOf( "://" ) == -1 && relativePath.indexOf( "mailto:" ) == -1 ) + if (relativePath == null) relativePath = ""; + if (relativePath.indexOf("://") == -1 + && relativePath.indexOf("mailto:") == -1) { StringBuffer path = new StringBuffer(); - String portalurl = path.append( portalUrl ).append( relativePath ).toString(); - if ( encode && requestContext != null ) + String portalurl = path.append(portalUrl).append(relativePath) + .toString(); + if (encode && requestContext != null) { - return requestContext.getResponse().encodeURL( portalurl ); + return requestContext.getResponse().encodeURL(portalurl); } else { @@ -241,53 +271,63 @@ } return relativePath; } - + /** - * Portal base url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/javascript/dojo/ ) - * Expects portalBaseUrl argument to be defined (ie. it does not call getPortalBaseUrl) + * Portal base url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/javascript/dojo/ ) Expects portalBaseUrl + * argument to be defined (ie. it does not call getPortalBaseUrl) * * @return portal base url with relativePath argument appended */ - public static String getPortalResourceUrl( String relativePath, String portalBaseUrl ) + public static String getPortalResourceUrl(String relativePath, + String portalBaseUrl) { - return getPortalResourceUrl( relativePath, portalBaseUrl, false, null ); + return getPortalResourceUrl(relativePath, portalBaseUrl, false, null); } - + /** - * Portal base url with relativePath argument appended ( e.g. http://localhost:8080/jetspeed/javascript/dojo/ ) - * Expects portalBaseUrl argument to be defined (ie. it does not call getPortalBaseUrl) - * RequestContext argument is needed only when encode argument is true (it's needed to call HttpServletResponse.encodeURL()) + * Portal base url with relativePath argument appended ( e.g. + * http://localhost:8080/jetspeed/javascript/dojo/ ) Expects portalBaseUrl + * argument to be defined (ie. it does not call getPortalBaseUrl) + * RequestContext argument is needed only when encode argument is true (it's + * needed to call HttpServletResponse.encodeURL()) * - * Method signature/behavior is a bit strange because this is a static method trying to accomodate - * callers that lazy cache portalBaseUrl string + * Method signature/behavior is a bit strange because this is a static + * method trying to accomodate callers that lazy cache portalBaseUrl string * * @return portal base url with relativePath argument appended */ - public static String getPortalResourceUrl( String relativePath, String portalBaseUrl, boolean encode, RequestContext requestContext ) + public static String getPortalResourceUrl(String relativePath, + String portalBaseUrl, boolean encode, RequestContext requestContext) { - if ( relativePath == null ) - relativePath = ""; + if (relativePath == null) relativePath = ""; boolean isPathRelative = true; - int colonPos = relativePath.indexOf( ':' ); - if ( colonPos != -1 ) + int colonPos = relativePath.indexOf(':'); + if (colonPos != -1) { int pathLen = relativePath.length(); - if ( colonPos <= ( pathLen - 3 ) && relativePath.charAt( colonPos + 1 ) == '/' && relativePath.charAt( colonPos + 2 ) == '/' ) + if (colonPos <= (pathLen - 3) + && relativePath.charAt(colonPos + 1) == '/' + && relativePath.charAt(colonPos + 2) == '/') { isPathRelative = false; } - else if ( colonPos >= MAILTO_URL_SCHEME_LEN && relativePath.substring( colonPos - MAILTO_URL_SCHEME_LEN, colonPos ).equals( MAILTO_URL_SCHEME ) ) + else if (colonPos >= MAILTO_URL_SCHEME_LEN + && relativePath.substring(colonPos - MAILTO_URL_SCHEME_LEN, + colonPos).equals(MAILTO_URL_SCHEME)) { isPathRelative = false; } } - if ( isPathRelative ) + if (isPathRelative) { StringBuffer path = new StringBuffer(); - String resourceurl = path.append( portalBaseUrl ).append( relativePath.startsWith( "/" ) ? "" : "/" ).append( relativePath ).toString(); - if ( encode && requestContext != null ) + String resourceurl = path.append(portalBaseUrl).append( + relativePath.startsWith("/") ? "" : "/").append( + relativePath).toString(); + if (encode && requestContext != null) { - return requestContext.getResponse().encodeURL( resourceurl ); + return requestContext.getResponse().encodeURL(resourceurl); } else { @@ -296,163 +336,177 @@ } return relativePath; } - - public static StringBuffer makeJSONObject( Map objectMap, boolean whenEmptyReturnNewObject ) + + public static StringBuffer makeJSONObject(Map objectMap, + boolean whenEmptyReturnNewObject) { - return makeJSONObject( null, new Map[] { objectMap }, whenEmptyReturnNewObject ); + return makeJSONObject(null, new Map[] + {objectMap}, whenEmptyReturnNewObject); } - public static StringBuffer makeJSONObject( Map[] objectMaps, boolean whenEmptyReturnNewObject ) + + public static StringBuffer makeJSONObject(Map[] objectMaps, + boolean whenEmptyReturnNewObject) { - return makeJSONObject( null, objectMaps, whenEmptyReturnNewObject ); + return makeJSONObject(null, objectMaps, whenEmptyReturnNewObject); } - public static StringBuffer makeJSONObject( StringBuffer jsonBuffer, Map objectMap, boolean whenEmptyReturnNewObject ) + + public static StringBuffer makeJSONObject(StringBuffer jsonBuffer, + Map objectMap, boolean whenEmptyReturnNewObject) { - return makeJSONObject( jsonBuffer, new Map[] { objectMap }, whenEmptyReturnNewObject ); + return makeJSONObject(jsonBuffer, new Map[] + {objectMap}, whenEmptyReturnNewObject); } - public static StringBuffer makeJSONObject( StringBuffer jsonBuffer, Map[] objectMaps, boolean whenEmptyReturnNewObject ) + + public static StringBuffer makeJSONObject(StringBuffer jsonBuffer, + Map[] objectMaps, boolean whenEmptyReturnNewObject) { - if ( jsonBuffer == null ) - jsonBuffer = new StringBuffer(); - - int added = 0; - int objMapsLen = ( objectMaps == null ? 0 : objectMaps.length ); - if ( objMapsLen > 0 ) - { - for ( int i = 0 ; i < objMapsLen ; i++ ) - { - Map objectMap = objectMaps[i]; - if ( objectMap != null && objectMap.size() > 0 ) - { - if ( added == 0 ) - jsonBuffer.append( "{" ); - Map.Entry objEntry; - Object objKey, objVal; - Iterator objMapIter = objectMap.entrySet().iterator(); - while ( objMapIter.hasNext() ) - { - objEntry = (Map.Entry)objMapIter.next(); - objKey = objEntry.getKey(); - if ( objKey != null ) - { - if ( added > 0 ) - jsonBuffer.append( ", " ); - jsonBuffer.append( "\"" ).append( objKey.toString() ).append( "\":" ); - objVal = objEntry.getValue(); - if ( objVal == null ) - objVal = ""; - jsonBuffer.append( "\"" ).append( objVal.toString() ).append( "\"" ); - added++; - } - } - } - } - } - if ( added > 0 ) - { - jsonBuffer.append( "}" ); - } - else if ( whenEmptyReturnNewObject ) + if (jsonBuffer == null) jsonBuffer = new StringBuffer(); + + int added = 0; + int objMapsLen = (objectMaps == null ? 0 : objectMaps.length); + if (objMapsLen > 0) { - jsonBuffer.append( "{}" ); + for (int i = 0; i < objMapsLen; i++) + { + Map objectMap = objectMaps[i]; + if (objectMap != null && objectMap.size() > 0) + { + if (added == 0) jsonBuffer.append("{"); + Map.Entry objEntry; + Object objKey, objVal; + Iterator objMapIter = objectMap.entrySet().iterator(); + while (objMapIter.hasNext()) + { + objEntry = (Map.Entry) objMapIter.next(); + objKey = objEntry.getKey(); + if (objKey != null) + { + if (added > 0) jsonBuffer.append(", "); + jsonBuffer.append("\"").append(objKey.toString()) + .append("\":"); + objVal = objEntry.getValue(); + if (objVal == null) objVal = ""; + jsonBuffer.append("\"").append(objVal.toString()) + .append("\""); + added++; + } + } + } + } } + if (added > 0) + { + jsonBuffer.append("}"); + } + else if (whenEmptyReturnNewObject) + { + jsonBuffer.append("{}"); + } else { - return null; + return null; } - return jsonBuffer; + return jsonBuffer; } - - public static String makeJavascriptStatement( String statement, String indent, boolean addEOL ) + + public static String makeJavascriptStatement(String statement, + String indent, boolean addEOL) { StringBuffer statementOut = new StringBuffer(); - if ( statement != null ) + if (statement != null) { statement = statement.trim(); - if ( statement.length() > 0 ) + if (statement.length() > 0) { - if ( indent != null ) + if (indent != null) { - statementOut.append( indent ); + statementOut.append(indent); } - statementOut.append( statement ); - if ( statement.charAt( statement.length()-1 ) != ';' ) + statementOut.append(statement); + if (statement.charAt(statement.length() - 1) != ';') { - statementOut.append( ";" ); + statementOut.append(";"); } - if ( addEOL ) + if (addEOL) { - statementOut.append( EOL ); + statementOut.append(EOL); } } } return statementOut.toString(); } - public static String makeJSONStringArray( Collection stringList ) + + public static String makeJSONStringArray(Collection stringList) { - return makeJSONStringArray( stringList, null ); + return makeJSONStringArray(stringList, null); } - public static String makeJSONStringArray( Collection stringList, List compiledUniqueValues ) + + public static String makeJSONStringArray(Collection stringList, + List compiledUniqueValues) { - if ( stringList != null && stringList.size() > 0 ) + if (stringList != null && stringList.size() > 0) { StringBuffer stringListContent = new StringBuffer(); Iterator stringListIter = stringList.iterator(); - while ( stringListIter.hasNext() ) + while (stringListIter.hasNext()) { - String value = (String)stringListIter.next(); - if ( value != null && value.length() > 0 ) + String value = (String) stringListIter.next(); + if (value != null && value.length() > 0) { - if ( stringListContent.length() > 0 ) + if (stringListContent.length() > 0) { - stringListContent.append( ", " ); + stringListContent.append(", "); } else { - stringListContent.append( "[ " ); + stringListContent.append("[ "); } - stringListContent.append( "\"" ).append( value ).append( "\"" ); - if ( compiledUniqueValues != null ) + stringListContent.append("\"").append(value).append("\""); + if (compiledUniqueValues != null) { - if ( ! compiledUniqueValues.contains( value ) ) + if (!compiledUniqueValues.contains(value)) { - compiledUniqueValues.add( value ); + compiledUniqueValues.add(value); } } } } - if ( stringListContent.length() > 0 ) + if (stringListContent.length() > 0) { - stringListContent.append( " ]" ); + stringListContent.append(" ]"); return stringListContent.toString(); } } return null; } - public static String makeJSONInteger( Object source, boolean quote ) + + public static String makeJSONInteger(Object source, boolean quote) { - String sourceStr = ( ( source == null ) ? (String)null : source.toString() ); - if ( sourceStr != null ) + String sourceStr = ((source == null) ? (String) null : source + .toString()); + if (sourceStr != null) { try { - Integer.parseInt( sourceStr ); - if ( quote ) + Integer.parseInt(sourceStr); + if (quote) { sourceStr = "\"" + sourceStr + "\""; } } - catch ( NumberFormatException nex ) + catch (NumberFormatException nex) { sourceStr = null; } } return sourceStr; } - - public static String makeJSONBoolean( Object source ) + + public static String makeJSONBoolean(Object source) { - String boolStr = ( ( source == null ) ? (String)null : source.toString() ); - if ( boolStr != null && ( ! boolStr.equals( "false" ) ) && ( ! boolStr.equals( "true" ) ) ) + String boolStr = ((source == null) ? (String) null : source.toString()); + if (boolStr != null && (!boolStr.equals("false")) + && (!boolStr.equals("true"))) { boolStr = null; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/i18n/CurrentLocale.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/i18n/CurrentLocale.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/i18n/CurrentLocale.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,25 +26,29 @@ */ public final class CurrentLocale { + private static ThreadLocal currentLocale = new ThreadLocal(); - + private CurrentLocale() - { + { } - - /** @return the currently {@link #set(Locale) set} Locale in this Thread or Locale.getDefault() otherwise + + /** + * @return the currently {@link #set(Locale) set} Locale in this Thread or + * Locale.getDefault() otherwise */ public static Locale get() { - Locale locale = (Locale)currentLocale.get(); + Locale locale = (Locale) currentLocale.get(); return locale != null ? locale : Locale.getDefault(); } - + /** - * Sets a Locale for this Thread. - * <br> - * Use a null parameter to revert back to Locale.getDefault() - * @param locale Locale for this Thread + * Sets a Locale for this Thread. <br> + * Use a null parameter to revert back to Locale.getDefault() + * + * @param locale + * Locale for this Thread */ public static void set(Locale locale) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/i18n/KeyedMessage.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/i18n/KeyedMessage.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/i18n/KeyedMessage.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,99 +24,116 @@ import java.util.Locale; import java.util.ResourceBundle; -import org.apache.jetspeed.exception.JetspeedException; // for javadoc ref -import org.apache.jetspeed.security.SecurityException; // for javadoc ref +import org.apache.jetspeed.exception.JetspeedException; +import org.apache.jetspeed.security.SecurityException; /** - * KeyedMessage provides an automatically derived i18n message key based on its static instance definition and can be - * used as comparable constant too. + * KeyedMessage provides an automatically derived i18n message key based on its + * static instance definition and can be used as comparable constant too. * <h3>Purpose</h3> * <p> - * With a KeyedMessage a named constant message (format) can be statically defined which automatically translate - * themselves for a specific locale using an automatically derived ResourceBundle or even a specified one. + * With a KeyedMessage a named constant message (format) can be statically + * defined which automatically translate themselves for a specific locale using + * an automatically derived ResourceBundle or even a specified one. * </p> * <h3>Key derivation</h3> * <p> - * Because KeyedMessages are created with a default message (format), even if no ResourceBundle or its key is defined or - * can't be found, message translation is still possible. + * Because KeyedMessages are created with a default message (format), even if no + * ResourceBundle or its key is defined or can't be found, message translation + * is still possible. * </p> * <p> - * A KeyedMessage automatically derives the ResourceBundle lookup key from its (statically defined) instance field name - * using the following format: <br/><br/><code> + * A KeyedMessage automatically derives the ResourceBundle lookup key from its + * (statically defined) instance field name using the following format: <br/><br/><code> *   <containingClass.name>.<staticInstanceField.name> * </code> * <br/> * </p> * <p> - * The containingClass is derived at construction time by analyzing the StackTraceElements of a thrown exception. This - * <em><b>requires</b></em> the instance to be defined as a public static field! + * The containingClass is derived at construction time by analyzing the + * StackTraceElements of a thrown exception. This <em><b>requires</b></em> + * the instance to be defined as a public static field! * </p> * <p> - * At first access, the key is resolved by inspecting the derived containingClass for the <em>declared</em> field - * defining this instance. + * At first access, the key is resolved by inspecting the derived + * containingClass for the <em>declared</em> field defining this instance. * </p> * <p> - * If the KeyedMessage instance <em><b>wasn't</b></em> defined as public static field, the key can't be resolved and - * message translation using a ResourceBundle won't be possible. Translation using the default message will still work - * though. Furthermore, this instance can't be used as comparable named constant as the {@link #equals(Object)}method - * will always return false in this case. + * If the KeyedMessage instance <em><b>wasn't</b></em> defined as public + * static field, the key can't be resolved and message translation using a + * ResourceBundle won't be possible. Translation using the default message will + * still work though. Furthermore, this instance can't be used as comparable + * named constant as the {@link #equals(Object)}method will always return false + * in this case. * </p> * <h3>Default ResourceBundle name derivation</h3> * <p> - * When the key of a KeyedMessage is resolved, the default ResourceBundle name for message translation is retrieved from - * the defined public static String field named {@link #KEYED_MESSAGE_BUNDLE_FIELD_NAME "KEYED_MESSAGE_BUNDLE"}defined + * When the key of a KeyedMessage is resolved, the default ResourceBundle name + * for message translation is retrieved from the defined public static String + * field named {@link #KEYED_MESSAGE_BUNDLE_FIELD_NAME "KEYED_MESSAGE_BUNDLE"}defined * in its containingClass or one of its superClasses or interfaces. * </p> * <p> - * If this field cannot be found, the fully qualified name of the containingClass is used. + * If this field cannot be found, the fully qualified name of the + * containingClass is used. * </p> * <p> - * ResourceBundle names are cached in a Map for each containingClass and only derived for the first KeyedMessage defined - * in a containingClass. + * ResourceBundle names are cached in a Map for each containingClass and only + * derived for the first KeyedMessage defined in a containingClass. * </p> * <p> * <em>Again: only <b>resolved</b> instances can use a ResourceBundle for message translation.</em> * </p> * <h3>Default Locale lookup</h3> * <p> - * When a message is translated without a specified Locale, {@link CurrentLocale#get()}is used to determine the default - * Locale for the current Thread. + * When a message is translated without a specified Locale, + * {@link CurrentLocale#get()}is used to determine the default Locale for the + * current Thread. * </p> * <p> - * In Jetspeed, the <code>LocalizationValve</code> initializes the {@link CurrentLocale} on each request. - * KeyedMessages accessed within the context of an Jetspeed request therefore will always be translated using the + * In Jetspeed, the <code>LocalizationValve</code> initializes the + * {@link CurrentLocale} on each request. KeyedMessages accessed within the + * context of an Jetspeed request therefore will always be translated using the * current user Locale with the {@link #getMessage()}or {@link #toString()}methods. * </p> * <h3>Default ResourceBundle lookup</h3> * <p> - * If a message translation is done using the default ResourceBundle name the ResourceBundle is retrieved using the - * ClassLoader of the containingClass. This means the bundle(s) must be provided in the same context as from where the - * containingClass is loaded. Usually (and preferably), this will be from the shared classpath of the webserver. + * If a message translation is done using the default ResourceBundle name the + * ResourceBundle is retrieved using the ClassLoader of the containingClass. + * This means the bundle(s) must be provided in the same context as from where + * the containingClass is loaded. Usually (and preferably), this will be from + * the shared classpath of the webserver. * </p> * <h3>MessageFormat parameters</h3> * <p> - * MessageFormat patterns can also be used for a KeyedMessage.<br/> - * With the {@link #create(Object[])}method a specialized copy of a KeyedMessage instance can be created containing the - * arguments to be used during message translation. + * MessageFormat patterns can also be used for a KeyedMessage.<br/> With the + * {@link #create(Object[])}method a specialized copy of a KeyedMessage + * instance can be created containing the arguments to be used during message + * translation. * </p> * <p> - * This new copy remains {@link equals(Object)}to its source and can still be used for named constant comparison. + * This new copy remains {@link equals(Object)}to its source and can still be + * used for named constant comparison. * </p> * <p> * For simplified usage, three {@link #create(Object)},{@link #create(Object, Object)}and - * {@link #create(Object, Object, Object)}methods are provided which delegate to {@link #create(Object[])}with their - * argument(s) transformed into an Object array. + * {@link #create(Object, Object, Object)}methods are provided which delegate + * to {@link #create(Object[])}with their argument(s) transformed into an + * Object array. * </p> * <h3>Extending KeyedMessage</h3> * <p> - * An statically defined KeyedMessage can be used as a "simple" named constant. <br/>If additional metadata is required - * like some kind of status, level or type indication, the KeyedMessage class can easily be extended by providing a - * specialized version of the {@link #create(KeyedMessage, Object[])}copy factory. + * An statically defined KeyedMessage can be used as a "simple" named constant. + * <br/>If additional metadata is required like some kind of status, level or + * type indication, the KeyedMessage class can easily be extended by providing a + * specialized version of the {@link #create(KeyedMessage, Object[])}copy + * factory. * </p> * <h3>Usage</h3> * <p> - * KeyedMessage has been used to replace the hardcoded {@link SecurityException} String constants. <br/>The - * ResourceBundle name used is defined by {@link JetspeedException#KEYED_MESSAGE_BUNDLE} which is the superClass of + * KeyedMessage has been used to replace the hardcoded {@link SecurityException} + * String constants. <br/>The ResourceBundle name used is defined by + * {@link JetspeedException#KEYED_MESSAGE_BUNDLE} which is the superClass of * {@link SecurityException}.<br/> * <p> * <em>For a different ResourceBundle to be used for SecurityException messages a KEYED_MESSAGE_BUNDLE field can be defined @@ -125,6 +142,7 @@ * <p> * Example: * </p> + * * <pre> * public class JetspeedException extends Exception { * public static final String KEYED_MESSAGE_BUNDLE = "org.apache.jetspeed.exception.JetspeedExceptionMessages"; @@ -173,58 +191,65 @@ */ public class KeyedMessage implements Serializable { + /** - * Static String Field name searched for in the class defining a KeyedMessage containing the default resource bundle - * to use for translation. <br/><em>Note: this Field is looked up using definingClass.getField thus it may also be + * Static String Field name searched for in the class defining a + * KeyedMessage containing the default resource bundle to use for + * translation. <br/><em>Note: this Field is looked up using definingClass.getField thus it may also be * defined in a superclass or interface of the definingClass.</em> */ - public static final String KEYED_MESSAGE_BUNDLE_FIELD_NAME = "KEYED_MESSAGE_BUNDLE"; + public static final String KEYED_MESSAGE_BUNDLE_FIELD_NAME = "KEYED_MESSAGE_BUNDLE"; /** * Key value for an unresolved KeyMessage. */ - private static final String UNRESOLVED_KEY = KeyedMessage.class.getName() + ".<unresolved>"; + private static final String UNRESOLVED_KEY = KeyedMessage.class.getName() + + ".<unresolved>"; /** * Map caching default resource bundle names keyed on containingClass */ - private static final HashMap resourceNameMap = new HashMap(); + private static final HashMap resourceNameMap = new HashMap(); /** - * Default message used when key couldn't be looked up in the default or a specified resource bundle + * Default message used when key couldn't be looked up in the default or a + * specified resource bundle */ - private String message; + private String message; /** - * Dynamically derived key based on the definingClass name, postfixed with the static field name of this instance - * </br> + * Dynamically derived key based on the definingClass name, postfixed with + * the static field name of this instance </br> * * @see #getKey() */ - private String key; + private String key; /** - * Optional message format arguments which can only be set using a derived KeyedMessage using the - * {@link #create(Object[])}method(s). + * Optional message format arguments which can only be set using a derived + * KeyedMessage using the {@link #create(Object[])}method(s). */ - private Object[] arguments; + private Object[] arguments; /** * The class in which this instance is defined as a static Field. */ - private Class containingClass; + private Class containingClass; /** * Indicates if this instance could be {@link #resolve() resolved}. */ - private boolean resolved; + private boolean resolved; /** - * Constructs a derived KeyedMessage from another KeyedMessage to provide additional message format arguments. + * Constructs a derived KeyedMessage from another KeyedMessage to provide + * additional message format arguments. * * @see #create(Object[]) - * @param source the KeyedMessage to derive this instance from - * @param arguments this instance specific message format arguments + * @param source + * the KeyedMessage to derive this instance from + * @param arguments + * this instance specific message format arguments */ protected KeyedMessage(KeyedMessage source, Object[] arguments) { @@ -236,10 +261,12 @@ } /** - * Constructs a new KeyedMessage which will dynamically derive its own {@link #getKey()}. + * Constructs a new KeyedMessage which will dynamically derive its own + * {@link #getKey()}. * - * @param message the default message used when the {@link #getKey()}could not be found in the default or a - * specified resource bundle. + * @param message + * the default message used when the {@link #getKey()}could not + * be found in the default or a specified resource bundle. */ public KeyedMessage(String message) { @@ -255,7 +282,9 @@ String containingClassName = elements[1].getClassName(); try { - containingClass = Thread.currentThread().getContextClassLoader().loadClass(containingClassName); + containingClass = Thread.currentThread() + .getContextClassLoader().loadClass( + containingClassName); } catch (ClassNotFoundException e1) { @@ -281,33 +310,42 @@ { if (key == null) { - // search for this instance as a statically declared field in the containingClass to find out the name + // search for this instance as a statically declared field in the + // containingClass to find out the name // to use. Field[] fields = containingClass.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { try { - if (fields[i].getType() == this.getClass() && Modifier.isStatic(fields[i].getModifiers()) - && fields[i].get(null) == this) + if (fields[i].getType() == this.getClass() + && Modifier.isStatic(fields[i].getModifiers()) + && fields[i].get(null) == this) { // resolved: save the key - key = containingClass.getName() + "." + fields[i].getName(); + key = containingClass.getName() + "." + + fields[i].getName(); resolved = true; - // Now derive the default resource bundle if not already done before + // Now derive the default resource bundle if not already + // done before synchronized (resourceNameMap) { if (getResourceName() == null) { - // Find resource bundle name by looking up the statically defined - // KEYED_MESSAGE_BUNDLE_FIELD_NAME String field in the containingClass. + // Find resource bundle name by looking up the + // statically defined + // KEYED_MESSAGE_BUNDLE_FIELD_NAME String field + // in the containingClass. String resourceName = null; try { - Field field = containingClass.getField(KEYED_MESSAGE_BUNDLE_FIELD_NAME); - if (field != null && field.getType() == String.class - && Modifier.isStatic(field.getModifiers())) + Field field = containingClass + .getField(KEYED_MESSAGE_BUNDLE_FIELD_NAME); + if (field != null + && field.getType() == String.class + && Modifier.isStatic(field + .getModifiers())) { resourceName = (String) field.get(null); } @@ -317,10 +355,12 @@ } if (resourceName == null) { - // fallback to containingClass name as resource bundle name + // fallback to containingClass name as + // resource bundle name resourceName = containingClass.getName(); } - resourceNameMap.put(containingClass, resourceName); + resourceNameMap.put(containingClass, + resourceName); } } @@ -339,9 +379,11 @@ } /** - * Formats a message using MessageFormat if arguments are defined, otherwise simply returns the argument. + * Formats a message using MessageFormat if arguments are defined, otherwise + * simply returns the argument. * - * @param message the message format + * @param message + * the message format * @return formatted message */ private String format(String message) @@ -359,8 +401,10 @@ /** * Extendable KeyedMessage factory * - * @param source the source to copy from - * @param arguments the optional message format arguments + * @param source + * the source to copy from + * @param arguments + * the optional message format arguments * @return copied instance with new arguments set */ protected KeyedMessage create(KeyedMessage source, Object[] arguments) @@ -369,12 +413,16 @@ } /** - * Creates a derived KeyedMessage from this instance to provide additional message format arguments. <br/>The new - * instance will be {@link #equals(Object)}to this instance with only different arguments. <br/><br/>Note: the - * argument objects should be lightweight types and preferably Serializable instances + * Creates a derived KeyedMessage from this instance to provide additional + * message format arguments. <br/>The new instance will be + * {@link #equals(Object)}to this instance with only different arguments. + * <br/><br/>Note: the argument objects should be lightweight types and + * preferably Serializable instances * - * @param arguments The derived instance specific message format arguments - * @return derived KeyedMessage {@link #equals(Object) equal}to this with its own message format arguments + * @param arguments + * The derived instance specific message format arguments + * @return derived KeyedMessage {@link #equals(Object) equal}to this with + * its own message format arguments */ public KeyedMessage create(Object[] arguments) { @@ -384,45 +432,55 @@ /** * Simplied version of {@link #create(Object[])}with only one argument * - * @param single message format argument + * @param single + * message format argument * @see #create(Object[]) - * @return derived KeyedMessage {@link #equals(Object) equal}to this with its own message format argument + * @return derived KeyedMessage {@link #equals(Object) equal}to this with + * its own message format argument */ public KeyedMessage create(Object o) { - return create(new Object[] { o }); + return create(new Object[] + {o}); } /** * Simplied version of {@link #create(Object[])}with only two arguments * - * @param single message format argument + * @param single + * message format argument * @see #create(Object[]) - * @return derived KeyedMessage {@link #equals(Object) equal}to this with its own message format arguments + * @return derived KeyedMessage {@link #equals(Object) equal}to this with + * its own message format arguments */ public KeyedMessage create(Object o1, Object o2) { - return create(new Object[] { o1, o2 }); + return create(new Object[] + {o1, o2}); } /** * Simplied version of {@link #create(Object[])}with only three arguments * - * @param single message format argument + * @param single + * message format argument * @see #create(Object[]) - * @return derived KeyedMessage {@link #equals(Object) equal}to this with its own message format arguments + * @return derived KeyedMessage {@link #equals(Object) equal}to this with + * its own message format arguments */ public KeyedMessage create(Object o1, Object o2, Object o3) { - return create(new Object[] { o1, o2, o3 }); + return create(new Object[] + {o1, o2, o3}); } /** - * Dynamically derived key based on the definingClass name, postfixed with the static field name of this instance. - * <br/><br/>Format: <br/><code> + * Dynamically derived key based on the definingClass name, postfixed with + * the static field name of this instance. <br/><br/>Format: <br/><code> *   <containingClass.name>.<staticInstanceField.name> * </code> - * <br/><br/>If this instance couldn't be resolved, generic value UNRESOLVED_KEY will have been set. + * <br/><br/>If this instance couldn't be resolved, generic value + * UNRESOLVED_KEY will have been set. * * @return derived key */ @@ -433,11 +491,15 @@ } /** - * Loads and returns a Locale specific default ResourceBundle for this instance. <br/>If this instance couldn't be - * {@link #resolve() resolved}or the bundle couldn't be loadednull will be returned. <br/>The ResourceBundle will - * be loaded using the {@link #containingClass}its ClassLoader. + * Loads and returns a Locale specific default ResourceBundle for this + * instance. <br/>If this instance couldn't be {@link #resolve() resolved}or + * the bundle couldn't be loadednull will be returned. <br/>The + * ResourceBundle will be loaded using the {@link #containingClass}its + * ClassLoader. * - * @param locale the Locale to lookup the locale specific default ResourceBundle + * @param locale + * the Locale to lookup the locale specific default + * ResourceBundle * @return a Locale specific default ResourceBundle */ public ResourceBundle getBundle(Locale locale) @@ -447,7 +509,8 @@ { try { - return ResourceBundle.getBundle(getResourceName(), locale, containingClass.getClassLoader()); + return ResourceBundle.getBundle(getResourceName(), locale, + containingClass.getClassLoader()); } catch (RuntimeException e) { @@ -471,7 +534,8 @@ } /** - * @return formatted message using the default ResourceBundle using the {@link CurrentLocale current Locale}. + * @return formatted message using the default ResourceBundle using the + * {@link CurrentLocale current Locale}. * @see #getBundle() */ public String getMessage() @@ -480,7 +544,9 @@ } /** - * @param bundle a specific ResourceBundle defining this instance {@link #getKey() key} + * @param bundle + * a specific ResourceBundle defining this instance + * {@link #getKey() key} * @return formatted message using a specific ResourceBundle. */ public String getMessage(ResourceBundle bundle) @@ -502,8 +568,10 @@ } /** - * @param locale a specific Locale - * @return formatted message using the default ResourceBundle using a specific Locale. + * @param locale + * a specific Locale + * @return formatted message using the default ResourceBundle using a + * specific Locale. */ public String getMessage(Locale locale) { @@ -520,7 +588,8 @@ } /** - * @param index argument number + * @param index + * argument number * @return an argument defined for this {@link #create(Object[]) derived}instance */ public Object getArgument(int index) @@ -529,7 +598,8 @@ } /** - * @return formatted message using the default ResourceBundle using the {@link CurrentLocale current Locale}. + * @return formatted message using the default ResourceBundle using the + * {@link CurrentLocale current Locale}. * @see #getMessage() */ public String toString() @@ -538,8 +608,10 @@ } /** - * @param otherObject KeyedMessage instance to compare with - * @return true only if otherObject is a KeyedMessage {@link create(Object[]) derived}from this instance (or visa + * @param otherObject + * KeyedMessage instance to compare with + * @return true only if otherObject is a KeyedMessage + * {@link create(Object[]) derived}from this instance (or visa * versa) and (thus both are) {@link #resolve() resolved}. * @see #create(Object[]) * @see #resolve() @@ -549,7 +621,8 @@ if (otherObject != null && otherObject instanceof KeyedMessage) { resolve(); - return (resolved && key.equals(((KeyedMessage) otherObject).getKey())); + return (resolved && key.equals(((KeyedMessage) otherObject) + .getKey())); } return false; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/idgenerator/IdGenerator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/idgenerator/IdGenerator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/idgenerator/IdGenerator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,21 +16,20 @@ */ package org.apache.jetspeed.idgenerator; - /** * This service handles the generation of unique identifiers - * + * * @author <a href="mailto:paulsp ¡÷ apache.org">Paul Spencer</a> * @version $Id: IdGenerator.java 516448 2007-03-09 16:25:47Z ate $ */ public interface IdGenerator { + /** * Generate a Unique Portlet Entity ID - * + * * @return Unique Portlet Entity ID - */ + */ public String getNextPeid(); - -} +} Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/Coordinate.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/Coordinate.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/Coordinate.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,16 +17,20 @@ package org.apache.jetspeed.layout; /** - * Abstracts coordinate parameters for portlet placement - * + * Abstracts coordinate parameters for portlet placement + * * @author <a>David Gurney</a> * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ -public interface Coordinate +public interface Coordinate { - public int getOldCol(); - public int getOldRow(); - public int getNewCol(); - public int getNewRow(); + + public int getOldCol(); + + public int getOldRow(); + + public int getNewCol(); + + public int getNewRow(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/JetspeedPowerTool.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/JetspeedPowerTool.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/JetspeedPowerTool.java 2008-05-16 01:54:54 UTC (rev 940) @@ -62,7 +62,8 @@ WindowState getWindowState() throws Exception; /** - * Gets the internal (portal) window state for the current portlet window (fragment) + * Gets the internal (portal) window state for the current portlet window + * (fragment) * * @return The window state for the current window * @throws Exception @@ -78,7 +79,8 @@ PortletMode getPortletMode() throws Exception; /** - * Gets the internal (portal) portlet mode for a current portlet window (fragment) + * Gets the internal (portal) portlet mode for a current portlet window + * (fragment) * * @return The portlet mode of the current window * @throws Exception @@ -129,8 +131,8 @@ /** * * @param f - * Fragment whose <code>PortletEntity</code> we want to - * retreive. + * Fragment whose <code>PortletEntity</code> we want to + * retreive. * @return The PortletEntity represented by the current fragment. * @throws Exception */ @@ -141,9 +143,9 @@ * RenderReqeust. * * @param f - * Fragment + * Fragment * @return whether or not the Fragment in question should be considered - * visible during rendering. + * visible during rendering. */ boolean isHidden(ContentFragment f); @@ -154,15 +156,15 @@ * * * @param path - * Expected to the template. This may actually be changed by the - * TL service based the capability and localization information - * provided by the client. + * Expected to the template. This may actually be changed by the + * TL service based the capability and localization information + * provided by the client. * @param templateType - * Type off template we are interested in. + * Type off template we are interested in. * @return Template object containng the pertinent information required to - * inlcude the request template path in the current response + * inlcude the request template path in the current response * @throws TemplateLocatorException - * if the <code>path</code> does not exist. + * if the <code>path</code> does not exist. */ TemplateDescriptor getTemplate(String path, String templateType) throws TemplateLocatorException; @@ -182,7 +184,7 @@ * </p> * * @param f - * Fragment to include and decorate + * Fragment to include and decorate * @throws Exception * @return String path to the decorator. */ @@ -193,7 +195,7 @@ * page) has its own collection of actionAccess flags associated with it. * * @return A list of actions available to the current window, filtered by - * securty access and current state. + * securty access and current state. * @throws Exception */ List getDecoratorActions(); @@ -203,7 +205,7 @@ * page has its own collection of actionAccess flags associated with it. * * @return A list of actions available to the current window, filtered by - * securty access and current state. + * securty access and current state. * @throws Exception */ List getPageDecoratorActions() throws Exception; @@ -242,7 +244,7 @@ String getBasePath(); - String getPageBasePath(); - + String getPageBasePath(); + String renderPortletEntity(String entityId, String portletId); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/JetspeedPowerToolFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/JetspeedPowerToolFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/JetspeedPowerToolFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,12 +21,15 @@ import org.apache.jetspeed.request.RequestContext; /** - * Factory interface to retrieve the Jetspeed Power Tool from the current request context. - * + * Factory interface to retrieve the Jetspeed Power Tool from the current + * request context. + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ public interface JetspeedPowerToolFactory { - JetspeedPowerTool getJetspeedPowerTool(RequestContext requestContext) throws PortletException; + + JetspeedPowerTool getJetspeedPowerTool(RequestContext requestContext) + throws PortletException; } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/PortletActionSecurityBehavior.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/PortletActionSecurityBehavior.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/PortletActionSecurityBehavior.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,15 +19,19 @@ import org.apache.jetspeed.request.RequestContext; /** - * Abstracted behavior of security checks for portlet actions - * + * Abstracted behavior of security checks for portlet actions + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ -public interface PortletActionSecurityBehavior +public interface PortletActionSecurityBehavior { + public boolean checkAccess(RequestContext context, String action); + public boolean isCreateNewPageOnEditEnabled(); + public boolean isPageQualifiedForCreateNewPageOnEdit(RequestContext context); + public boolean createNewPageOnEdit(RequestContext context); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/PortletPlacementContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/PortletPlacementContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/PortletPlacementContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,141 +20,173 @@ import org.apache.jetspeed.om.page.Page; /** - * Handles portlet placement for client such as AJAX client side - * on a per request basis. The context is associated with a request context, - * thus it is only valid for the span of a request. - * + * Handles portlet placement for client such as AJAX client side on a per + * request basis. The context is associated with a request context, thus it is + * only valid for the span of a request. + * * @author <a>David Gurney</a> * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ -public interface PortletPlacementContext +public interface PortletPlacementContext { - /** - * Move a portlet fragment to a new absolute position as specified in the Coordinate parameter. + + /** + * Move a portlet fragment to a new absolute position as specified in the + * Coordinate parameter. * - * @param fragment The fragment to be moved. - * @param coordinate The specification of the new absolute coordinate - * @return new coordinate location of the portlet - * @throws PortletPlacementException - */ - public Coordinate moveAbsolute(Fragment fragment, Coordinate coordinate ) throws PortletPlacementException; + * @param fragment + * The fragment to be moved. + * @param coordinate + * The specification of the new absolute coordinate + * @return new coordinate location of the portlet + * @throws PortletPlacementException + */ + public Coordinate moveAbsolute(Fragment fragment, Coordinate coordinate) + throws PortletPlacementException; - /** - * Move a portlet fragment to a new absolute position as specified in the Coordinate parameter. + /** + * Move a portlet fragment to a new absolute position as specified in the + * Coordinate parameter. * - * @param fragment The fragment to be moved. - * @param coordinate The specification of the new absolute coordinate - * @param addFragment When true, the fragment is being added (i.e. it is not being moved within the column) - * @return new coordinate location of the portlet - * @throws PortletPlacementException - */ - public Coordinate moveAbsolute(Fragment fragment, Coordinate coordinate, boolean addFragment) throws PortletPlacementException; - - /** + * @param fragment + * The fragment to be moved. + * @param coordinate + * The specification of the new absolute coordinate + * @param addFragment + * When true, the fragment is being added (i.e. it is not being + * moved within the column) + * @return new coordinate location of the portlet + * @throws PortletPlacementException + */ + public Coordinate moveAbsolute(Fragment fragment, Coordinate coordinate, + boolean addFragment) throws PortletPlacementException; + + /** * Move a portlet relative to its current position UP one row. * - * @param fragment The fragment to be moved. + * @param fragment + * The fragment to be moved. * @return new coordinate location of the portlet - * @throws PortletPlacementException - */ - public Coordinate moveUp(Fragment fragment) throws PortletPlacementException; + * @throws PortletPlacementException + */ + public Coordinate moveUp(Fragment fragment) + throws PortletPlacementException; /** * Move a portlet relative to its current position DOWN one row. * - * @param fragment The fragment to be moved. + * @param fragment + * The fragment to be moved. * @return new coordinate location of the portlet * @throws PortletPlacementException - */ - public Coordinate moveDown(Fragment fragment) throws PortletPlacementException; - + */ + public Coordinate moveDown(Fragment fragment) + throws PortletPlacementException; + /** * Move a portlet relative to its current position LEFT one column. * - * @param fragment The fragment to be moved. + * @param fragment + * The fragment to be moved. * @return new coordinate location of the portlet * @throws PortletPlacementException - */ - public Coordinate moveLeft(Fragment fragment) throws PortletPlacementException; - + */ + public Coordinate moveLeft(Fragment fragment) + throws PortletPlacementException; + /** * Move a portlet relative to its current position RIGHT one column. * - * @param fragment The fragment to be moved. + * @param fragment + * The fragment to be moved. * @return new coordinate location of the portlet * @throws PortletPlacementException - */ - public Coordinate moveRight(Fragment fragment) throws PortletPlacementException; - - /** + */ + public Coordinate moveRight(Fragment fragment) + throws PortletPlacementException; + + /** * Add a portlet to its managed page. * - * @param fragment The Fragment to add - * @param coordinate The coordinate where to place the new portlet - * @return - * @throws PortletPlacementException - */ - public Coordinate add(Fragment fragment, Coordinate coordinate) throws PortletPlacementException; - - /** + * @param fragment + * The Fragment to add + * @param coordinate + * The coordinate where to place the new portlet + * @return + * @throws PortletPlacementException + */ + public Coordinate add(Fragment fragment, Coordinate coordinate) + throws PortletPlacementException; + + /** * Remove the specified fragment. - * @param fragment - * @return - * @throws PortletPlacementException - */ - public Coordinate remove(Fragment fragment) throws PortletPlacementException; - + * + * @param fragment + * @return + * @throws PortletPlacementException + */ + public Coordinate remove(Fragment fragment) + throws PortletPlacementException; + /** * retrieve the number of columns for the managed layout. * * @return the number of columns in the manged layout * @throws PortletPlacementException */ - public int getNumberColumns() throws PortletPlacementException; - + public int getNumberColumns() throws PortletPlacementException; + /** * retrieve the number of rows for the managed layout at the given column. * - * @param column the column to retrieve the number of rows for + * @param column + * the column to retrieve the number of rows for * @return the number of rows for the given column * @throws PortletPlacementException - */ - public int getNumberRows(int column) throws PortletPlacementException; - - /** + */ + public int getNumberRows(int column) throws PortletPlacementException; + + /** * Retrieve a portlet fragment for the given coordinate. - * - * @param coordinate the coordinate associated to a fragment. - * @return the fragment associated to the given coordinate - * @throws PortletPlacementException - */ - public Fragment getFragmentAtNewCoordinate(Coordinate coordinate) throws PortletPlacementException; - - /** - * Retrieve the old portlet fragment for the given coordinate (prior to placement). * - * @param coordinate the coordinate associated to a fragment. - * @return the fragment associated to the given coordinate - * @throws PortletPlacementException - */ - public Fragment getFragmentAtOldCoordinate(Coordinate coordinate) throws PortletPlacementException; - - /** + * @param coordinate + * the coordinate associated to a fragment. + * @return the fragment associated to the given coordinate + * @throws PortletPlacementException + */ + public Fragment getFragmentAtNewCoordinate(Coordinate coordinate) + throws PortletPlacementException; + + /** + * Retrieve the old portlet fragment for the given coordinate (prior to + * placement). + * + * @param coordinate + * the coordinate associated to a fragment. + * @return the fragment associated to the given coordinate + * @throws PortletPlacementException + */ + public Fragment getFragmentAtOldCoordinate(Coordinate coordinate) + throws PortletPlacementException; + + /** * Retrieve a fragment by fragment id. * - * @param fragmentId a string key for a fragment managed on this layout. - * @return The fragment associated with the given fragment id. - * @throws PortletPlacementException - */ - public Fragment getFragmentById(String fragmentId) throws PortletPlacementException; - + * @param fragmentId + * a string key for a fragment managed on this layout. + * @return The fragment associated with the given fragment id. + * @throws PortletPlacementException + */ + public Fragment getFragmentById(String fragmentId) + throws PortletPlacementException; + /** - * Takes the internal portlet placement state and writes it back - * out to the root fragment for the managed page layout. + * Takes the internal portlet placement state and writes it back out to the + * root fragment for the managed page layout. * * @return the managed page layout with updated fragment state. */ public Page syncPageFragments(); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/PortletPlacementException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/PortletPlacementException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/layout/PortletPlacementException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,16 +17,17 @@ package org.apache.jetspeed.layout; /** - * Handles portlet placement exceptions - * + * Handles portlet placement exceptions + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @author <a>David Gurney</a> * @version $Id: $ */ -public class PortletPlacementException extends Exception +public class PortletPlacementException extends Exception { - public PortletPlacementException(String message) + + public PortletPlacementException(String message) { - super(message); - } + super(message); + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/LocatorDescriptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/LocatorDescriptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/LocatorDescriptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,132 +18,131 @@ /** * LocatorDescriptor - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: LocatorDescriptor.java 516448 2007-03-09 16:25:47Z ate $ */ public interface LocatorDescriptor { - public final static String PARAM_TYPE = "type"; - public final static String PARAM_MEDIA_TYPE = "media-type"; - public final static String PARAM_NAME = "name"; - public final static String PARAM_LANGUAGE = "language"; - public final static String PARAM_COUNTRY = "country"; - public final static String TYPE_EMAIL = "emails"; - public final static String TYPE_PORTLET = "portlets"; - - + + public final static String PARAM_TYPE = "type"; + + public final static String PARAM_MEDIA_TYPE = "media-type"; + + public final static String PARAM_NAME = "name"; + + public final static String PARAM_LANGUAGE = "language"; + + public final static String PARAM_COUNTRY = "country"; + + public final static String TYPE_EMAIL = "emails"; + + public final static String TYPE_PORTLET = "portlets"; + /* - * Gets the unique template locator string, which is a combination of the params - * The string must follow the one the sequences below, where bracketed items are optional: - * - * template/<templateType>/[media-type/<mediaType>]/[language/<language>]/[country/<country>]]/name/<templateName - * + * Gets the unique template locator string, which is a combination of the + * params The string must follow the one the sequences below, where + * bracketed items are optional: + * + * template/<templateType>/[media-type/<mediaType>]/[language/<language>]/[country/<country>]]/name/<templateName + * * @return The template locator as a string */ String toString(); /* - * Gets the path locator string, which is a combination of the params without the name tags. - * The string must follow the one the sequences below, where bracketed items are optional: - * - * <templateType>/[<mediaType>]/[<language>]/[<country>]]/<templateName> - * + * Gets the path locator string, which is a combination of the params + * without the name tags. The string must follow the one the sequences + * below, where bracketed items are optional: + * + * <templateType>/[<mediaType>]/[<language>]/[<country>]]/<templateName> + * * @return The template locator path */ String toPath(); - + /* - * Gets the template type parameter for this template. - * Any value is valid if there the service supports it. - * Known values are email, portlet. - * + * Gets the template type parameter for this template. Any value is valid if + * there the service supports it. Known values are email, portlet. + * * @return The template type parameter for this template. */ String getType(); /* - * Sets the template type parameter for this template. - * Any value is valid if there the service supports it. - * Known values are email, portlet. - * + * Sets the template type parameter for this template. Any value is valid if + * there the service supports it. Known values are email, portlet. + * * @param The template type parameter for this template. */ void setType(String type); /* * Gets the resource name parameter for this template. - * + * * @return The resource name parameter for this template. */ String getName(); /* * Sets the resource name parameter for this template. - * + * * @param name The resource name parameter for this template. */ void setName(String name); /* - * Gets the media type parameter for this template. - * Media types are values such as html, wml, xml ... - * TODO: support for 2 or more media types + * Gets the media type parameter for this template. Media types are values + * such as html, wml, xml ... TODO: support for 2 or more media types * * @return The media type parameter for this template. */ - String getMediaType(); + String getMediaType(); /* - * Sets the media type parameter for this template. - * Media types are values such as html, wml, xml ... - * TODO: support for 2 or more media types - * + * Sets the media type parameter for this template. Media types are values + * such as html, wml, xml ... TODO: support for 2 or more media types + * * @param mediaType The media type parameter for this template. */ - void setMediaType(String mediaType); + void setMediaType(String mediaType); /* - * Gets the language parameter for this template. - * Language values are ISO-639 standard language abbreviations - * en, fr, de, ... - * + * Gets the language parameter for this template. Language values are + * ISO-639 standard language abbreviations en, fr, de, ... + * * @return The language parameter for this template. */ - String getLanguage(); + String getLanguage(); /* - * Sets the language parameter for this template. - * Language values are ISO-639 standard language abbreviations - * en, fr, de, ... - * + * Sets the language parameter for this template. Language values are + * ISO-639 standard language abbreviations en, fr, de, ... + * * @param language The language parameter for this template. */ - void setLanguage(String language); + void setLanguage(String language); /* - * Gets the country code parameter for this template. - * Country code values are ISO-3166 standard country code abbreviations. - * GB, US, FR, CA, DE, ... - * + * Gets the country code parameter for this template. Country code values + * are ISO-3166 standard country code abbreviations. GB, US, FR, CA, DE, ... + * * @return The country code parameter for this template. */ - String getCountry(); + String getCountry(); /* - * Sets the country code parameter for this template. - * Country code values are ISO-3166 standard country code abbreviations. - * GB, US, FR, CA, DE, ... - * + * Sets the country code parameter for this template. Country code values + * are ISO-3166 standard country code abbreviations. GB, US, FR, CA, DE, ... + * * @param country The country code parameter for this template. */ - void setCountry(String country); + void setCountry(String country); - /** * @see Object#clone * @return an instance copy of this object */ - Object clone() throws java.lang.CloneNotSupportedException; - + Object clone() throws java.lang.CloneNotSupportedException; + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/TemplateDescriptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/TemplateDescriptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/TemplateDescriptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,34 +18,40 @@ /** * TemplateDescriptor - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: TemplateDescriptor.java 516448 2007-03-09 16:25:47Z ate $ */ public interface TemplateDescriptor extends LocatorDescriptor { + /** * The absolute file system path to the template - * + * * @return absolute path - */ + */ String getAbsolutePath(); - + /** * The absolute file system path to the template - * - * @param absolute path - */ + * + * @param absolute + * path + */ void setAbsolutePath(String path); - - /** - * Returns the template path relative to the applications root - * @return Application-relative path - */ - public String getAppRelativePath(); - /** - * Sets the template path relative to the applications root - * @param string Application-relative path - */ - public void setAppRelativePath(String string); + + /** + * Returns the template path relative to the applications root + * + * @return Application-relative path + */ + public String getAppRelativePath(); + + /** + * Sets the template path relative to the applications root + * + * @param string + * Application-relative path + */ + public void setAppRelativePath(String string); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/TemplateLocator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/TemplateLocator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/TemplateLocator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,52 +20,58 @@ /** * TemplateLocator interface - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: TemplateLocator.java 516448 2007-03-09 16:25:47Z ate $ */ public interface TemplateLocator -{ +{ + /** * Locate an template using Jetspeed template location algorithm - * - * @param locator The template locator + * + * @param locator + * The template locator * @return The template found, or null if not found. * @throws TemplateLocatorException */ TemplateDescriptor locateTemplate(LocatorDescriptor locator) - throws TemplateLocatorException; + throws TemplateLocatorException; /** - * Factory to create template locators of the given type. - * Known supported locator types, but not limited to: - * <code>portlet</code> + * Factory to create template locators of the given type. Known supported + * locator types, but not limited to: <code>portlet</code> * <code>email</code> * - * @param The type of locator to create + * @param The + * type of locator to create * @return a general template locator of the given type - * @throws TemplateLocatorException if factory exception or if not valid locator type + * @throws TemplateLocatorException + * if factory exception or if not valid locator type */ LocatorDescriptor createLocatorDescriptor(String type) - throws TemplateLocatorException; + throws TemplateLocatorException; /** * Creates a locator from a string of format (where brackets are optional]: - * - * template/<templateType>/[media-type/<mediaType>]/[language/<language>]/[country/<country>]]/name/<templateName * - * @param string the string representation of a template locator + * template/<templateType>/[media-type/<mediaType>]/[language/<language>]/[country/<country>]]/name/<templateName + * + * @param string + * the string representation of a template locator * @throws TemplateLocatorException - */ + */ LocatorDescriptor createFromString(String string) - throws TemplateLocatorException; - - /** + throws TemplateLocatorException; + + /** * Query for a collection of templates given template locator criteria. - * - * @param locator The template locator criteria. - * @return The result list of {@link Template} objects matching the locator criteria. + * + * @param locator + * The template locator criteria. + * @return The result list of {@link Template} objects matching the locator + * criteria. */ public Iterator query(LocatorDescriptor locator); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/TemplateLocatorException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/TemplateLocatorException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/locator/TemplateLocatorException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,30 +18,31 @@ /** * TemplateLocatorException - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: TemplateLocatorException.java 516448 2007-03-09 16:25:47Z ate $ */ public class TemplateLocatorException extends Exception { - public TemplateLocatorException() + + public TemplateLocatorException() { super(); } - - public TemplateLocatorException(String message) + + public TemplateLocatorException(String message) { super(message); } - + public TemplateLocatorException(Throwable nested) { super(nested); } - + public TemplateLocatorException(String msg, Throwable nested) { super(msg, nested); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/login/LoginConstants.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/login/LoginConstants.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/login/LoginConstants.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,26 +16,36 @@ */ package org.apache.jetspeed.login; - /** * LoginConstants - * + * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id: LoginConstants.java 544402 2007-06-05 06:20:00Z taylor $ */ public final class LoginConstants { - public final static String USERNAME = "org.apache.jetspeed.login.username"; - public final static String PASSWORD = "org.apache.jetspeed.login.password"; + + public final static String USERNAME = "org.apache.jetspeed.login.username"; + + public final static String PASSWORD = "org.apache.jetspeed.login.password"; + public final static String DESTINATION = "org.apache.jetspeed.login.destination"; - public final static String RETRYCOUNT = "org.apache.jetspeed.login.retrycount"; - public final static String ERRORCODE = "org.apache.jetspeed.login.errorcode"; + + public final static String RETRYCOUNT = "org.apache.jetspeed.login.retrycount"; + + public final static String ERRORCODE = "org.apache.jetspeed.login.errorcode"; + public final static String LOGIN_CHECK = "org.apache.jetspeed.login.check"; - + public final static Integer ERROR_UNKNOWN_USER = new Integer(1); + public final static Integer ERROR_INVALID_PASSWORD = new Integer(2); + public final static Integer ERROR_USER_DISABLED = new Integer(3); + public final static Integer ERROR_FINAL_LOGIN_ATTEMPT = new Integer(4); + public final static Integer ERROR_CREDENTIAL_DISABLED = new Integer(5); + public final static Integer ERROR_CREDENTIAL_EXPIRED = new Integer(6); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/MockHttpServletRequest.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/MockHttpServletRequest.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/MockHttpServletRequest.java 2008-05-16 01:54:54 UTC (rev 940) @@ -15,6 +15,7 @@ * limitations under the License. */ package org.apache.jetspeed.mockobjects; + import java.io.BufferedReader; import java.io.IOException; import java.io.UnsupportedEncodingException; @@ -31,12 +32,14 @@ /** * @author <a href="mailto:sweaver ¡÷ einnovation.com">Scott T. Weaver</a> - * + * */ public class MockHttpServletRequest implements HttpServletRequest { - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getAuthType() */ public String getAuthType() @@ -45,7 +48,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getCookies() */ public Cookie[] getCookies() @@ -54,34 +59,42 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getDateHeader(java.lang.String) */ - public long getDateHeader( String arg0 ) + public long getDateHeader(String arg0) { // TODO Auto-generated method stub return 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getHeader(java.lang.String) */ - public String getHeader( String arg0 ) + public String getHeader(String arg0) { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getHeaders(java.lang.String) */ - public Enumeration getHeaders( String arg0 ) + public Enumeration getHeaders(String arg0) { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getHeaderNames() */ public Enumeration getHeaderNames() @@ -90,16 +103,20 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getIntHeader(java.lang.String) */ - public int getIntHeader( String arg0 ) + public int getIntHeader(String arg0) { // TODO Auto-generated method stub return 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getMethod() */ public String getMethod() @@ -108,7 +125,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getPathInfo() */ public String getPathInfo() @@ -117,7 +136,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getPathTranslated() */ public String getPathTranslated() @@ -126,7 +147,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getContextPath() */ public String getContextPath() @@ -135,7 +158,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getQueryString() */ public String getQueryString() @@ -144,7 +169,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getRemoteUser() */ public String getRemoteUser() @@ -153,16 +180,20 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#isUserInRole(java.lang.String) */ - public boolean isUserInRole( String arg0 ) + public boolean isUserInRole(String arg0) { // TODO Auto-generated method stub return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getUserPrincipal() */ public Principal getUserPrincipal() @@ -171,7 +202,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getRequestedSessionId() */ public String getRequestedSessionId() @@ -180,7 +213,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getRequestURI() */ public String getRequestURI() @@ -189,7 +224,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getRequestURL() */ public StringBuffer getRequestURL() @@ -198,7 +235,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getServletPath() */ public String getServletPath() @@ -207,16 +246,20 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getSession(boolean) */ - public HttpSession getSession( boolean arg0 ) + public HttpSession getSession(boolean arg0) { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#getSession() */ public HttpSession getSession() @@ -225,7 +268,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdValid() */ public boolean isRequestedSessionIdValid() @@ -234,7 +279,9 @@ return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromCookie() */ public boolean isRequestedSessionIdFromCookie() @@ -243,7 +290,9 @@ return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromURL() */ public boolean isRequestedSessionIdFromURL() @@ -252,7 +301,9 @@ return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromUrl() */ public boolean isRequestedSessionIdFromUrl() @@ -261,16 +312,20 @@ return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getAttribute(java.lang.String) */ - public Object getAttribute( String arg0 ) + public Object getAttribute(String arg0) { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getAttributeNames() */ public Enumeration getAttributeNames() @@ -279,7 +334,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getCharacterEncoding() */ public String getCharacterEncoding() @@ -288,17 +345,21 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#setCharacterEncoding(java.lang.String) */ - public void setCharacterEncoding( String arg0 ) + public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException { // TODO Auto-generated method stub } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getContentLength() */ public int getContentLength() @@ -307,7 +368,9 @@ return 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getContentType() */ public String getContentType() @@ -316,7 +379,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getInputStream() */ public ServletInputStream getInputStream() throws IOException @@ -325,16 +390,20 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getParameter(java.lang.String) */ - public String getParameter( String arg0 ) + public String getParameter(String arg0) { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getParameterNames() */ public Enumeration getParameterNames() @@ -343,16 +412,20 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getParameterValues(java.lang.String) */ - public String[] getParameterValues( String arg0 ) + public String[] getParameterValues(String arg0) { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getParameterMap() */ public Map getParameterMap() @@ -361,7 +434,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getProtocol() */ public String getProtocol() @@ -370,7 +445,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getScheme() */ public String getScheme() @@ -379,7 +456,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getServerName() */ public String getServerName() @@ -388,7 +467,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getServerPort() */ public int getServerPort() @@ -397,7 +478,9 @@ return 0; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getReader() */ public BufferedReader getReader() throws IOException @@ -406,7 +489,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getRemoteAddr() */ public String getRemoteAddr() @@ -415,7 +500,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getRemoteHost() */ public String getRemoteHost() @@ -424,25 +511,32 @@ return null; } - /* (non-Javadoc) - * @see javax.servlet.ServletRequest#setAttribute(java.lang.String, java.lang.Object) + /* + * (non-Javadoc) + * + * @see javax.servlet.ServletRequest#setAttribute(java.lang.String, + * java.lang.Object) */ - public void setAttribute( String arg0, Object arg1 ) + public void setAttribute(String arg0, Object arg1) { // TODO Auto-generated method stub } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#removeAttribute(java.lang.String) */ - public void removeAttribute( String arg0 ) + public void removeAttribute(String arg0) { // TODO Auto-generated method stub } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getLocale() */ public Locale getLocale() @@ -451,7 +545,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getLocales() */ public Enumeration getLocales() @@ -460,7 +556,9 @@ return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#isSecure() */ public boolean isSecure() @@ -469,19 +567,23 @@ return false; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getRequestDispatcher(java.lang.String) */ - public RequestDispatcher getRequestDispatcher( String arg0 ) + public RequestDispatcher getRequestDispatcher(String arg0) { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see javax.servlet.ServletRequest#getRealPath(java.lang.String) */ - public String getRealPath( String arg0 ) + public String getRealPath(String arg0) { // TODO Auto-generated method stub return null; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/portlet/MockPortletRequest.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/portlet/MockPortletRequest.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/portlet/MockPortletRequest.java 2008-05-16 01:54:54 UTC (rev 940) @@ -36,14 +36,17 @@ */ public class MockPortletRequest implements PortletRequest { + MockPortletSession session = null; - + public MockPortletRequest() { - session = new MockPortletSession(); + session = new MockPortletSession(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#isWindowStateAllowed(javax.portlet.WindowState) */ public boolean isWindowStateAllowed(WindowState state) @@ -51,7 +54,10 @@ // TODO Auto-generated method stub return false; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#isPortletModeAllowed(javax.portlet.PortletMode) */ public boolean isPortletModeAllowed(PortletMode mode) @@ -59,7 +65,10 @@ // TODO Auto-generated method stub return false; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getPortletMode() */ public PortletMode getPortletMode() @@ -67,7 +76,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getWindowState() */ public WindowState getWindowState() @@ -75,7 +87,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getPreferences() */ public PortletPreferences getPreferences() @@ -83,14 +98,20 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getPortletSession() */ public PortletSession getPortletSession() { return session; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getPortletSession(boolean) */ public PortletSession getPortletSession(boolean create) @@ -101,7 +122,10 @@ } return session; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getProperty(java.lang.String) */ public String getProperty(String name) @@ -109,7 +133,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getProperties(java.lang.String) */ public Enumeration getProperties(String name) @@ -117,7 +144,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getPropertyNames() */ public Enumeration getPropertyNames() @@ -125,7 +155,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getPortalContext() */ public PortalContext getPortalContext() @@ -133,7 +166,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getAuthType() */ public String getAuthType() @@ -141,7 +177,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getContextPath() */ public String getContextPath() @@ -149,7 +188,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getRemoteUser() */ public String getRemoteUser() @@ -157,7 +199,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getUserPrincipal() */ public Principal getUserPrincipal() @@ -165,7 +210,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#isUserInRole(java.lang.String) */ public boolean isUserInRole(String role) @@ -173,7 +221,10 @@ // TODO Auto-generated method stub return false; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getAttribute(java.lang.String) */ public Object getAttribute(String name) @@ -181,7 +232,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getAttributeNames() */ public Enumeration getAttributeNames() @@ -189,7 +243,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getParameter(java.lang.String) */ public String getParameter(String name) @@ -197,7 +254,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getParameterNames() */ public Enumeration getParameterNames() @@ -205,7 +265,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getParameterValues(java.lang.String) */ public String[] getParameterValues(String name) @@ -213,7 +276,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getParameterMap() */ public Map getParameterMap() @@ -221,7 +287,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#isSecure() */ public boolean isSecure() @@ -229,21 +298,31 @@ // TODO Auto-generated method stub return false; } - /* (non-Javadoc) - * @see javax.portlet.PortletRequest#setAttribute(java.lang.String, java.lang.Object) + + /* + * (non-Javadoc) + * + * @see javax.portlet.PortletRequest#setAttribute(java.lang.String, + * java.lang.Object) */ public void setAttribute(String name, Object o) { // TODO Auto-generated method stub } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#removeAttribute(java.lang.String) */ public void removeAttribute(String name) { // TODO Auto-generated method stub } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getRequestedSessionId() */ public String getRequestedSessionId() @@ -251,7 +330,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#isRequestedSessionIdValid() */ public boolean isRequestedSessionIdValid() @@ -259,7 +341,10 @@ // TODO Auto-generated method stub return false; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getResponseContentType() */ public String getResponseContentType() @@ -267,7 +352,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getResponseContentTypes() */ public Enumeration getResponseContentTypes() @@ -275,7 +363,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getLocale() */ public Locale getLocale() @@ -283,7 +374,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getScheme() */ public String getScheme() @@ -291,7 +385,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getServerName() */ public String getServerName() @@ -299,7 +396,10 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletRequest#getServerPort() */ public int getServerPort() @@ -307,10 +407,10 @@ // TODO Auto-generated method stub return 0; } - + public Enumeration getLocales() { return null; } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/portlet/MockPortletSession.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/portlet/MockPortletSession.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/portlet/MockPortletSession.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,51 +18,60 @@ import java.util.Enumeration; import java.util.Hashtable; + import javax.portlet.PortletContext; import javax.portlet.PortletSession; /** - * A mock portlet session, useful for unit testing and offline utilities - * Note: currently doesn't support scoping + * A mock portlet session, useful for unit testing and offline utilities Note: + * currently doesn't support scoping * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: MockPortletSession.java 516448 2007-03-09 16:25:47Z ate $ */ public class MockPortletSession implements PortletSession { + // Hashtable (not HashMap) makes enumerations easier to work with Hashtable attributes = new Hashtable(); public MockPortletSession() - { + { } - - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletSession#getAttribute(java.lang.String) */ public Object getAttribute(String name) { return attributes.get(name); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletSession#getAttribute(java.lang.String, int) */ public Object getAttribute(String name, int scope) { return attributes.get(name); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletSession#getAttributeNames(int) */ public Enumeration getAttributeNames(int scope) { return attributes.keys(); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletSession#getCreationTime() */ public long getCreationTime() @@ -70,8 +79,10 @@ // TODO Auto-generated method stub return 0; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletSession#getId() */ public String getId() @@ -79,8 +90,10 @@ // TODO Auto-generated method stub return null; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletSession#getLastAccessedTime() */ public long getLastAccessedTime() @@ -88,8 +101,10 @@ // TODO Auto-generated method stub return 0; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletSession#getMaxInactiveInterval() */ public int getMaxInactiveInterval() @@ -97,16 +112,20 @@ // TODO Auto-generated method stub return 0; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletSession#invalidate() */ public void invalidate() { // TODO Auto-generated method stub } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletSession#isNew() */ public boolean isNew() @@ -114,25 +133,32 @@ // TODO Auto-generated method stub return false; } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletSession#removeAttribute(java.lang.String) */ public void removeAttribute(String name) { attributes.remove(name); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletSession#removeAttribute(java.lang.String, int) */ public void removeAttribute(String name, int scope) { attributes.remove(name); } - - /* (non-Javadoc) - * @see javax.portlet.PortletSession#setAttribute(java.lang.String, java.lang.Object) + + /* + * (non-Javadoc) + * + * @see javax.portlet.PortletSession#setAttribute(java.lang.String, + * java.lang.Object) */ public void setAttribute(String name, Object value) { @@ -142,25 +168,32 @@ public Enumeration getAttributeNames() { return this.getAttributeNames(PortletSession.PORTLET_SCOPE); - } - - - /* (non-Javadoc) - * @see javax.portlet.PortletSession#setAttribute(java.lang.String, java.lang.Object, int) + } + + /* + * (non-Javadoc) + * + * @see javax.portlet.PortletSession#setAttribute(java.lang.String, + * java.lang.Object, int) */ public void setAttribute(String name, Object value, int scope) { attributes.put(name, value); } - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletSession#setMaxInactiveInterval(int) */ public void setMaxInactiveInterval(int interval) { // TODO Auto-generated method stub } - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see javax.portlet.PortletSession#getPortletContext() */ public PortletContext getPortletContext() Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/request/MockRequestContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/request/MockRequestContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/mockobjects/request/MockRequestContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -40,8 +40,6 @@ import org.apache.pluto.om.portlet.PortletDefinition; import org.apache.pluto.om.window.PortletWindow; - - /** * MockRequestContext * @@ -51,31 +49,50 @@ */ public class MockRequestContext implements RequestContext { + private Map requestParameters = new HashMap(); + private Map requestAttributes = new HashMap(); + private Map sessionAttributes = new HashMap(); + private String path; + private Map locators; + private Subject subject; + private Locale locale; + private String mediaType; + private String mimeType; + private ContentPage page; + private HttpServletRequest request; + private HttpServletResponse response; + private Object session; + private Pipeline pipeline; + private Map objects; - - /* (non-Javadoc) + + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.request.RequestContext#getUserInfoMap(org.apache.pluto.om.common.ObjectID) */ - public Map getUserInfoMap( ObjectID oid ) + public Map getUserInfoMap(ObjectID oid) { // TODO Auto-generated method stub return null; } - public MockRequestContext(HttpServletRequest request, HttpServletResponse response) + + public MockRequestContext(HttpServletRequest request, + HttpServletResponse response) { this.request = request; this.response = response; @@ -91,17 +108,16 @@ // TODO Auto-generated method stub return null; } - public MockRequestContext() { - // WebMockObjectFactory mockFactory = new WebMockObjectFactory(); + // WebMockObjectFactory mockFactory = new WebMockObjectFactory(); this.request = new MockHttpServletRequest(); - // this.response = mockFactory.getMockResponse(); + // this.response = mockFactory.getMockResponse(); // this.session = mockFactory.getSession(); } - public MockRequestContext( String path ) + public MockRequestContext(String path) { // super(null, null, null, null); this.path = path; @@ -216,9 +232,9 @@ } public void setPortalURL(PortalURL url) - { + { } - + /* * (non-Javadoc) * @@ -245,7 +261,7 @@ * * @see org.apache.jetspeed.request.RequestContext#getRequestForWindow(org.apache.pluto.om.window.PortletWindow) */ - public HttpServletRequest getRequestForWindow( PortletWindow window ) + public HttpServletRequest getRequestForWindow(PortletWindow window) { // TODO Auto-generated method stub return null; @@ -267,7 +283,7 @@ * * @see org.apache.jetspeed.request.RequestContext#getResponseForWindow(org.apache.pluto.om.window.PortletWindow) */ - public HttpServletResponse getResponseForWindow( PortletWindow window ) + public HttpServletResponse getResponseForWindow(PortletWindow window) { // TODO Auto-generated method stub return null; @@ -282,7 +298,7 @@ { return subject; } - + public Principal getUserPrincipal() { return request.getUserPrincipal(); @@ -293,7 +309,7 @@ * * @see org.apache.jetspeed.request.RequestContext#setActionWindow(org.apache.pluto.om.window.PortletWindow) */ - public void setActionWindow( PortletWindow window ) + public void setActionWindow(PortletWindow window) { // TODO Auto-generated method stub @@ -304,7 +320,7 @@ * * @see org.apache.jetspeed.request.RequestContext#setCapabilityMap(org.apache.jetspeed.capability.CapabilityMap) */ - public void setCapabilityMap( CapabilityMap map ) + public void setCapabilityMap(CapabilityMap map) { // TODO Auto-generated method stub @@ -315,7 +331,7 @@ * * @see org.apache.jetspeed.request.RequestContext#setCharacterEncoding(java.lang.String) */ - public void setCharacterEncoding( String enc ) + public void setCharacterEncoding(String enc) { // TODO Auto-generated method stub @@ -326,7 +342,7 @@ * * @see org.apache.jetspeed.request.RequestContext#setContentDispatcher(org.apache.jetspeed.aggregator.ContentDispatcher) */ - public void setContentDispatcher( ContentDispatcher dispatcher ) + public void setContentDispatcher(ContentDispatcher dispatcher) { // TODO Auto-generated method stub @@ -337,7 +353,7 @@ * * @see org.apache.jetspeed.request.RequestContext#setLocale(java.util.Locale) */ - public void setLocale( Locale locale ) + public void setLocale(Locale locale) { this.locale = locale; @@ -348,7 +364,7 @@ * * @see org.apache.jetspeed.request.RequestContext#setMediaType(java.lang.String) */ - public void setMediaType( String mediaType ) + public void setMediaType(String mediaType) { this.mediaType = mediaType; @@ -359,9 +375,9 @@ * * @see org.apache.jetspeed.request.RequestContext#setMimeType(java.lang.String) */ - public void setMimeType( String mimeType ) + public void setMimeType(String mimeType) { - this.mimeType = mimeType; + this.mimeType = mimeType; } @@ -370,7 +386,7 @@ * * @see org.apache.jetspeed.request.RequestContext#setPage(org.apache.jetspeed.om.page.Page) */ - public void setPage( ContentPage page ) + public void setPage(ContentPage page) { this.page = page; @@ -381,7 +397,7 @@ * * @see org.apache.jetspeed.request.RequestContext#setProfileLocators(java.util.Map) */ - public void setProfileLocators( Map locators ) + public void setProfileLocators(Map locators) { this.locators = locators; @@ -392,19 +408,18 @@ * * @see org.apache.jetspeed.request.RequestContext#setSubject(javax.security.auth.Subject) */ - public void setSubject( Subject subject ) + public void setSubject(Subject subject) { this.subject = subject; } - /* * (non-Javadoc) * * @see org.apache.jetspeed.request.RequestContext#getRequestParameter(java.lang.String) */ - public String getRequestParameter( String key ) + public String getRequestParameter(String key) { return (String) requestParameters.get(key); } @@ -425,7 +440,7 @@ * @see org.apache.jetspeed.request.RequestContext#setSessionAttribute(java.lang.String, * java.lang.Object) */ - public void setSessionAttribute( String key, Object value ) + public void setSessionAttribute(String key, Object value) { this.sessionAttributes.put(key, value); } @@ -435,7 +450,7 @@ * * @see org.apache.jetspeed.request.RequestContext#getSessionAttribute(java.lang.String) */ - public Object getSessionAttribute( String key ) + public Object getSessionAttribute(String key) { return this.sessionAttributes.get(key); } @@ -446,7 +461,7 @@ * @see org.apache.jetspeed.request.RequestContext#setAttribute(java.lang.String, * java.lang.Object) */ - public void setAttribute( String key, Object value ) + public void setAttribute(String key, Object value) { requestAttributes.put(key, value); } @@ -456,7 +471,7 @@ * * @see org.apache.jetspeed.request.RequestContext#getAttribute(java.lang.String) */ - public Object getAttribute( String key ) + public Object getAttribute(String key) { return requestAttributes.get(key); } @@ -475,31 +490,33 @@ * <p> * getPreferedLanguage * </p> - * + * * @see org.apache.jetspeed.request.RequestContext#getPreferedLanguage(org.apache.pluto.om.portlet.PortletDefinition) * @param portlet * @return */ - public Language getPreferedLanguage( PortletDefinition portlet ) + public Language getPreferedLanguage(PortletDefinition portlet) { // TODO Auto-generated method stub return null; } + /** * <p> * setPath * </p> - * + * * @see org.apache.jetspeed.request.RequestContext#setPath(java.lang.String) * @param path */ - public void setPath( String path ) + public void setPath(String path) { this.path = path; } - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.apache.jetspeed.request.RequestContext#popActionFailure(org.apache.pluto.om.window.PortletWindow) */ public Throwable popActionFailure(PortletWindow window) @@ -507,13 +524,17 @@ // TODO Auto-generated method stub return null; } - /* (non-Javadoc) - * @see org.apache.jetspeed.request.RequestContext#setActionFailure(org.apache.pluto.om.window.PortletWindow, java.lang.Throwable) + + /* + * (non-Javadoc) + * + * @see org.apache.jetspeed.request.RequestContext#setActionFailure(org.apache.pluto.om.window.PortletWindow, + * java.lang.Throwable) */ public void setActionFailure(PortletWindow window, Throwable actionFailure) { // TODO Auto-generated method stub - + } /** @@ -525,10 +546,10 @@ { return pipeline; } - - + /** * Set the current pipeline + * * @param pipeline */ public void setPipeline(Pipeline pipeline) @@ -537,15 +558,17 @@ } /** - * @param request The request to set. + * @param request + * The request to set. */ public void setRequest(HttpServletRequest request) { this.request = request; } - + /** - * @param response The request to set. + * @param response + * The request to set. */ public void setResponse(HttpServletResponse response) { @@ -556,12 +579,12 @@ { return null; } - + public Map getObjects() { return objects; } - + public void setObjects(Map objects) { this.objects = objects; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/BaseSecurityReference.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/BaseSecurityReference.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/BaseSecurityReference.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,51 +17,54 @@ package org.apache.jetspeed.om; // Jetspeed imports -import org.apache.jetspeed.om.SecurityReference; /** * BaseSecurityReference - * + * * @author <a href="paulsp ¡÷ apache.org">Paul Spencer</a> * @version $Id: BaseSecurityReference.java 516448 2007-03-09 16:25:47Z ate $ */ public class BaseSecurityReference implements SecurityReference { - + /** Holds value of property parent. */ private String parent; - + /** Creates new BaseSecurityReference */ public BaseSecurityReference() { } - - /** Getter for property parent. + + /** + * Getter for property parent. + * * @return Value of property parent. */ public String getParent() { return parent; } - - /** Setter for property parent. - * @param parent New value of property parent. + + /** + * Setter for property parent. + * + * @param parent + * New value of property parent. */ public void setParent(String parent) { this.parent = parent; } - + /** * Create a clone of this object */ - public Object clone() - throws java.lang.CloneNotSupportedException + public Object clone() throws java.lang.CloneNotSupportedException { BaseSecurityReference cloned = new BaseSecurityReference(); cloned.parent = this.parent; - + return cloned; - } // clone + } // clone } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/ControllerFactoryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/ControllerFactoryImpl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/ControllerFactoryImpl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,36 +16,37 @@ */ package org.apache.jetspeed.om; +import org.apache.pluto.om.Controller; import org.apache.pluto.om.ControllerFactory; import org.apache.pluto.om.Model; -import org.apache.pluto.om.Controller; - /** * ControllerFactoryImpl - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: ControllerFactoryImpl.java 516448 2007-03-09 16:25:47Z ate $ */ public class ControllerFactoryImpl implements ControllerFactory { - public void init(javax.servlet.ServletConfig config, - java.util.Map properties) throws Exception + public void init(javax.servlet.ServletConfig config, + java.util.Map properties) throws Exception { } + public void destroy() throws Exception { } public Controller get(Model model) { - // if (model instanceof org.apache.pluto.portalImpl.om.common.impl.UnmodifiableSet) - //{ - // model = (Model)((org.apache.pluto.portalImpl.om.common.impl.UnmodifiableSet)model).getModifiableSet(); - // } - return (Controller)model; + // if (model instanceof + // org.apache.pluto.portalImpl.om.common.impl.UnmodifiableSet) + // { + // model = + // (Model)((org.apache.pluto.portalImpl.om.common.impl.UnmodifiableSet)model).getModifiableSet(); + // } + return (Controller) model; } } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/SecurityReference.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/SecurityReference.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/SecurityReference.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,29 +18,33 @@ package org.apache.jetspeed.om; import java.io.Serializable; + /** * SecurityReference - * + * * @author <a href="paulsp ¡÷ apache.org">Paul Spencer</a> * @version $Id: SecurityReference.java 516448 2007-03-09 16:25:47Z ate $ */ public interface SecurityReference extends Serializable, Cloneable { - - /** Getter for property parent. + + /** + * Getter for property parent. + * * @return Value of property parent. */ public String getParent(); - - /** Setter for property parent. - * @param parent New value of property parent. + + /** + * Setter for property parent. + * + * @param parent + * New value of property parent. */ public void setParent(String parent); - + /** * Create a clone of this object */ - public Object clone() - throws java.lang.CloneNotSupportedException; + public Object clone() throws java.lang.CloneNotSupportedException; } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/DublinCore.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/DublinCore.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/DublinCore.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,75 +16,102 @@ */ package org.apache.jetspeed.om.common; -import java.util.Collection ; +import java.util.Collection; import java.util.Locale; /** - * DublinCore - * <br/> - * Interface that allows retrieving information according to the - * Dublin Core specification - * (<a href="http://www.dublincore.org">http://www.dublincore.org</a>) + * DublinCore <br/> Interface that allows retrieving information according to + * the Dublin Core specification (<a + * href="http://www.dublincore.org">http://www.dublincore.org</a>) * * @author <a href="mailto:jford ¡÷ apache.org">Jeremy Ford</a> * @version $Id: DublinCore.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface DublinCore extends java.io.Serializable { + public Collection getTitles(); + public void setTitles(Collection titles); + void addTitle(Locale locale, String title); - + public Collection getContributors(); + public void setContributors(Collection contributors); + void addContributor(Locale locale, String contributor); - + public Collection getCoverages(); + public void setCoverages(Collection coverages); + void addCoverage(Locale locale, String coverage); - + public Collection getCreators(); + public void setCreators(Collection creators); + void addCreator(Locale locale, String creator); - + public Collection getDescriptions(); + public void setDescriptions(Collection descriptions); + void addDescription(Locale locale, String description); - + public Collection getFormats(); + public void setFormats(Collection formats); + void addFormat(Locale locale, String format); - + public Collection getIdentifiers(); + public void setIdentifiers(Collection identifiers); + void addIdentifier(Locale locale, String identifier); - + public Collection getLanguages(); + public void setLanguages(Collection languages); + void addLanguage(Locale locale, String language); - + public Collection getPublishers(); + public void setPublishers(Collection publishers); + void addPublisher(Locale locale, String publisher); - + public Collection getRelations(); + public void setRelations(Collection relations); + void addRelation(Locale locale, String relation); - + public Collection getRights(); + public void setRights(Collection rights); + void addRight(Locale locale, String right); - + public Collection getSources(); + public void setSources(Collection sources); + void addSource(Locale locale, String source); - + public Collection getSubjects(); + public void setSubjects(Collection subjects); + void addSubject(Locale locale, String subject); - + public Collection getTypes(); + public void setTypes(Collection types); + void addType(Locale locale, String type); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/GenericMetadata.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/GenericMetadata.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/GenericMetadata.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,76 +27,77 @@ */ public interface GenericMetadata { + /** * * <p> * addField * </p> - * + * * @param locale * @param name * @param value */ - public void addField( Locale locale, String name, String value ); - + public void addField(Locale locale, String name, String value); + /** * * <p> * addField * </p> - * + * * @param field */ - public void addField( LocalizedField field ); - + public void addField(LocalizedField field); + /** * * <p> * getFields * </p> - * + * * @param name * @return */ - public Collection getFields( String name ); - + public Collection getFields(String name); + /** * * <p> * setFields * </p> - * + * * @param name * @param values */ - public void setFields( String name, Collection values ); - + public void setFields(String name, Collection values); + /** * * <p> * getFields * </p> - * + * * @return */ public Collection getFields(); - + /** * * <p> * setFields * </p> - * + * * @param fields */ - public void setFields( Collection fields ); - + public void setFields(Collection fields); + /** * * <p> * createLocalizedField * </p> - * + * * @return */ LocalizedField createLocalizedField(); @@ -106,8 +107,8 @@ * <p> * copyFields * </p> - * + * * @param fields */ - public void copyFields( Collection fields ); + public void copyFields(Collection fields); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/JetspeedServiceReference.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/JetspeedServiceReference.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/JetspeedServiceReference.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.om.common; import java.io.Serializable; @@ -25,18 +25,21 @@ */ public interface JetspeedServiceReference extends Serializable { + /** - * The name of the Jetspeed Component Service as defined in the component assembly. + * The name of the Jetspeed Component Service as defined in the component + * assembly. * * @return */ String getName(); /** - * The name of the Jetspeed Component Service as defined in the component assembly. + * The name of the Jetspeed Component Service as defined in the component + * assembly. * * @param name */ void setName(String name); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/LocalizedField.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/LocalizedField.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/LocalizedField.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,25 +21,28 @@ import org.apache.pluto.om.common.ObjectID; /** - * LocalizedField - * <br/> - * Interface that represents a string value and the locale of that string + * LocalizedField <br/> Interface that represents a string value and the locale + * of that string * * @author <a href="mailto:jford ¡÷ apache.org">Jeremy Ford</a> * @version $Id: LocalizedField.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface LocalizedField { + public String getName(); + public void setName(String name); - + public Locale getLocale(); + public void setLocale(Locale locale); - + public String getValue(); + public void setValue(String value); - + /** * */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDescription.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDescription.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDescription.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,25 +21,29 @@ import org.apache.pluto.om.common.Description; /** - * MutableDescription - * <br/> - * Extended version of <code>org.apache.pluto.om.common.Description</code> - * that allows for setting the description text and Locale for the description - * object. + * MutableDescription <br/> Extended version of + * <code>org.apache.pluto.om.common.Description</code> that allows for setting + * the description text and Locale for the description object. * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: MutableDescription.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface MutableDescription extends Description { String TYPE_PORTLET_APP = "org.apache.pluto.om.common.Description.portletApplication"; + String TYPE_WEB_APP = "org.apache.pluto.om.common.Description.webApplication"; + String TYPE_PORTLET = "org.apache.pluto.om.common.Description.portlet"; + String TYPE_PORTLET_ENTITY = "org.apache.pluto.om.common.Description.portletEntity"; + String TYPE_PARAMETER = "org.apache.pluto.om.common.Description.parameter"; + String TYPE_PREFERENCE = "org.apache.pluto.om.common.Description.preference"; + String TYPE_SEC_ROLE_REF = "org.apache.pluto.om.common.Description.securityRoleRef"; void setDescription(String description); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDescriptionSet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDescriptionSet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDescriptionSet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,8 +16,6 @@ */ package org.apache.jetspeed.om.common; - - import org.apache.pluto.om.common.Description; import org.apache.pluto.om.common.DescriptionSet; @@ -26,10 +24,11 @@ * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: MutableDescriptionSet.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface MutableDescriptionSet extends DescriptionSet { + void addDescription(Description description); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDisplayName.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDisplayName.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDisplayName.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,15 +25,17 @@ * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: MutableDisplayName.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface MutableDisplayName extends DisplayName { + String TYPE_WEB_APP = "org.apache.pluto.om.common.DisplayName.webapp"; + String TYPE_PORTLET = "org.apache.pluto.om.common.DisplayName.portlet"; void setDisplayName(String displayName); void setLocale(Locale locale); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDisplayNameSet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDisplayNameSet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableDisplayNameSet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,9 +24,10 @@ * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: MutableDisplayNameSet.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface MutableDisplayNameSet extends DisplayNameSet { + void addDisplayName(DisplayName name); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableLanguage.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableLanguage.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/MutableLanguage.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,17 +24,17 @@ /** * - * MutableLanguage - * <br/> - * Extension of <code>org.apache.pluto.om.common.Language</code> - * with mutator methods for easy maintenance. + * MutableLanguage <br/> Extension of + * <code>org.apache.pluto.om.common.Language</code> with mutator methods for + * easy maintenance. * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: MutableLanguage.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface MutableLanguage extends Language, Serializable { + void setKeywords(Collection keywords); /** Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/ParameterComposite.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/ParameterComposite.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/ParameterComposite.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,21 +29,18 @@ * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: ParameterComposite.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public interface ParameterComposite extends Parameter, ParameterCtrl, Serializable +public interface ParameterComposite extends Parameter, ParameterCtrl, + Serializable { - - String TYPE_PORTLET = "org.apache.pluto.om.common.Parameter.portlet"; + String TYPE_PORTLET = "org.apache.pluto.om.common.Parameter.portlet"; - String TYPE_WEB_APP = "org.apache.pluto.om.common.Parameter.webapp"; + String TYPE_WEB_APP = "org.apache.pluto.om.common.Parameter.webapp"; - - - void addDescription(Locale locale, String desc); - + DescriptionSet getDescriptionSet(); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecuredResource.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecuredResource.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecuredResource.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,7 +16,6 @@ */ package org.apache.jetspeed.om.common; - /** * <p> * SecuredResource @@ -24,39 +23,41 @@ * <p> * Implemented by those resources that have a security constraint defined for * security purposes. - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: SecuredResource.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface SecuredResource -{ +{ /** * <p> * getConstraintsEnabled * </p> - * + * * @return enabled indicator */ boolean getConstraintsEnabled(); - + /** * <p> * getSecurityConstraints * </p> - * + * * @return security constraints for resource */ SecurityConstraints getSecurityConstraints(); - + /** * <p> * newSecurityConstraints * </p> - * - * @return a newly created SecurityConstraints object for use in SecuredResource + * + * @return a newly created SecurityConstraints object for use in + * SecuredResource */ SecurityConstraints newSecurityConstraints(); @@ -64,8 +65,9 @@ * <p> * newSecurityConstraint * </p> - * - * @return a newly created SecurityConstraint object for use in SecuredResource + * + * @return a newly created SecurityConstraint object for use in + * SecuredResource */ SecurityConstraint newSecurityConstraint(); @@ -73,8 +75,9 @@ * <p> * setSecurityConstraints * </p> - * - * @param constraints security constraints for resource + * + * @param constraints + * security constraints for resource */ void setSecurityConstraints(SecurityConstraints constraints); @@ -82,8 +85,9 @@ * <p> * checkConstraints * </p> - * - * @param actions list to be checked against in CSV string form + * + * @param actions + * list to be checked against in CSV string form * @throws SecurityException */ void checkConstraints(String actions) throws SecurityException; @@ -92,17 +96,18 @@ * <p> * getPermissionsEnabled * </p> - * + * * @return enabled indicator */ boolean getPermissionsEnabled(); - + /** * <p> * checkPermissions * </p> - * - * @param mask Mask of actions to be checked + * + * @param mask + * Mask of actions to be checked * @throws SecurityException */ void checkPermissions(int mask) throws SecurityException; @@ -111,8 +116,9 @@ * <p> * checkAccess * </p> - * - * @param actions list to be checked against in CSV string form + * + * @param actions + * list to be checked against in CSV string form * @throws SecurityException */ void checkAccess(String actions) throws SecurityException; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecurityConstraint.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecurityConstraint.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecurityConstraint.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,87 +23,92 @@ * SecurityConstraint * </p> * <p> - * Used by SecureResource to specify access constraints for - * security purposes. - * + * Used by SecureResource to specify access constraints for security purposes. + * * </p> + * * @author <a href="mailto:rwatler ¡÷ finali.com">Randy Watler</a> * @version $Id: SecurityConstraint.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface SecurityConstraint -{ - String WILD_CHAR = "*"; +{ + String WILD_CHAR = "*"; + /** * <p> * getUsers * </p> - * + * * @return constraint users list as List of String */ List getUsers(); - + /** * <p> * setUsers * </p> - * - * @param users constraint users list as List of String + * + * @param users + * constraint users list as List of String */ void setUsers(List users); - + /** * <p> * getRoles * </p> - * + * * @return constraint roles list as List of String */ List getRoles(); - + /** * <p> * setRoles * </p> - * - * @param roles constraint roles list as List of String + * + * @param roles + * constraint roles list as List of String */ void setRoles(List roles); - + /** * <p> * getGroups * </p> - * + * * @return constraint groups list as List of String */ List getGroups(); - + /** * <p> * setGroups * </p> - * - * @param groups constraint groups list as List of String + * + * @param groups + * constraint groups list as List of String */ void setGroups(List groups); - + /** * <p> * getPermissions * </p> - * + * * @return constraint permissions list as List of String */ List getPermissions(); - + /** * <p> * setPermissions * </p> - * - * @param permissions constraint permissions list as List of String + * + * @param permissions + * constraint permissions list as List of String */ void setPermissions(List permissions); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecurityConstraints.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecurityConstraints.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecurityConstraints.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,29 +24,32 @@ * </p> * <p> * Used to specify security constraints for a resource. - * + * * </p> + * * @author <a href="mailto:rwatler ¡÷ finali.com">Randy Watler</a> * @version $Id: SecurityConstraints.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface SecurityConstraints -{ +{ + /** * <p> * getOwner * </p> - * - * @return owner constraint for resource + * + * @return owner constraint for resource */ String getOwner(); - + /** * <p> * setOwner * </p> - * - * @param owner constraint for resource + * + * @param owner + * constraint for resource */ void setOwner(String owner); @@ -54,17 +57,18 @@ * <p> * getSecurityConstraints * </p> - * + * * @return security constraints list for resource */ List getSecurityConstraints(); - + /** * <p> * setSecurityConstraint * </p> - * - * @param constraints security constraints for resource + * + * @param constraints + * security constraints for resource */ void setSecurityConstraints(List constraints); @@ -72,17 +76,18 @@ * <p> * getSecurityConstraintsRefs * </p> - * + * * @return security constraints references for resource */ List getSecurityConstraintsRefs(); - + /** * <p> * setSecurityConstraintsRefs * </p> - * - * @param constraintsRefs security constraints references for resource + * + * @param constraintsRefs + * security constraints references for resource */ void setSecurityConstraintsRefs(List constraintsRefs); @@ -90,7 +95,7 @@ * <p> * isEmpty * </p> - * + * * @return flag indicating whether there are constraints or owner set */ boolean isEmpty(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecurityRoleRefComposite.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecurityRoleRefComposite.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/SecurityRoleRefComposite.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,14 +30,16 @@ * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: SecurityRoleRefComposite.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public interface SecurityRoleRefComposite extends SecurityRoleRef, SecurityRoleRefCtrl, Serializable +public interface SecurityRoleRefComposite extends SecurityRoleRef, + SecurityRoleRefCtrl, Serializable { + void addDescription(Description description); - + void addDescription(Locale locale, String description); - + void setDescriptionSet(DescriptionSet descriptions); DescriptionSet getDescriptionSet(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/Support.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/Support.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/Support.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,17 +20,16 @@ package org.apache.jetspeed.om.common; -import java.lang.Exception; +public interface Support +{ -public interface Support { - - // public static final int POST_LOAD = 2; - // public static final int PRE_BUILD = 3; + // public static final int POST_LOAD = 2; + // public static final int PRE_BUILD = 3; // public static final int POST_BUILD = 4; - // public static final int PRE_STORE = 5; + // public static final int PRE_STORE = 5; // public static final int POST_STORE = 6; - // public void preLoad(Object parameter) throws Exception; + // public void preLoad(Object parameter) throws Exception; public void postLoad(Object parameter) throws Exception; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/UserAttribute.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/UserAttribute.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/UserAttribute.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,22 +19,26 @@ import java.io.Serializable; /** - * <p>Interface representing user attribute as defined in Portlet specs: - * PLT.17.2 Accessing User Attributes.</p> + * <p> + * Interface representing user attribute as defined in Portlet specs: PLT.17.2 + * Accessing User Attributes. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> - * + * */ public interface UserAttribute extends Serializable { + /** Getter for the user-attribute name. */ String getName(); - + /** Setter for the user-attribute name. */ void setName(String name); - + /** Getter for the user-attribute description. */ String getDescription(); - + /** Setter for the user-attribute description. */ void setDescription(String description); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/UserAttributeRef.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/UserAttributeRef.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/UserAttributeRef.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,31 +19,35 @@ import java.io.Serializable; /** - * <p>Interface allowing mapping of user attributes between the portal implementation - * and the portlet attribute definition according to the Portlet specs (PLT.17.2 Accessing - * User Attributes). This is a Jetspeed 2 specific extension that allows to map a user-attribute - * name used in the portlet to a user attribute name-link used in the portal implementation.</p> + * <p> + * Interface allowing mapping of user attributes between the portal + * implementation and the portlet attribute definition according to the Portlet + * specs (PLT.17.2 Accessing User Attributes). This is a Jetspeed 2 specific + * extension that allows to map a user-attribute name used in the portlet to a + * user attribute name-link used in the portal implementation. + * </p> * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> - * + * */ public interface UserAttributeRef extends Serializable { + /** Getter for the user-attribute-ref name. */ String getName(); - + /** Setter for the user-attribute-ref name. */ void setName(String name); - + /** Getter for the user-attribute-ref name-link. */ String getNameLink(); - + /** Setter for the user-attribute-ref name-link. */ void setNameLink(String nameLink); - + /** Getter for the user-attribute description. */ String getDescription(); - + /** Setter for the user-attribute description. */ void setDescription(String description); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/ContentTypeComposite.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/ContentTypeComposite.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/ContentTypeComposite.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,36 +22,42 @@ import javax.portlet.PortletMode; import org.apache.pluto.om.portlet.ContentType; + /** * * ContentTypeComposite * - * Combines the <code>org.apache.pluto.common.ContentType</code> - * and <code>org.apache.pluto.common.ContentTypeCtrl</code> interfaces - * into single interface for use in Jetspeed. + * Combines the <code>org.apache.pluto.common.ContentType</code> and + * <code>org.apache.pluto.common.ContentTypeCtrl</code> interfaces into single + * interface for use in Jetspeed. * * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: ContentTypeComposite.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface ContentTypeComposite extends ContentType, Serializable { + void setPortletModes(Collection modes); /** - * Adds a mode to be supported by this <code>ContentType</code>. If the mode - * already exists, the same mode is NOT added again. - * @param mode portlet mode to add. + * Adds a mode to be supported by this <code>ContentType</code>. If the + * mode already exists, the same mode is NOT added again. + * + * @param mode + * portlet mode to add. */ void addPortletMode(PortletMode mode); /** - * Checks whether or not the <code>mode</code> - * is supported by this <code>ContentType</code> - * @param mode portlet mode to check - * @return <code>true</code> if the <code>mode</code> is - * supported, otherwise <code>false</code>. + * Checks whether or not the <code>mode</code> is supported by this + * <code>ContentType</code> + * + * @param mode + * portlet mode to check + * @return <code>true</code> if the <code>mode</code> is supported, + * otherwise <code>false</code>. */ boolean supportsPortletMode(PortletMode mode); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/ContentTypeSetComposite.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/ContentTypeSetComposite.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/ContentTypeSetComposite.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,9 +27,10 @@ * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: ContentTypeSetComposite.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface ContentTypeSetComposite extends ContentTypeSet, Serializable { + void addContentType(ContentType contentType); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/CustomPortletMode.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/CustomPortletMode.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/CustomPortletMode.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,7 +22,10 @@ public interface CustomPortletMode extends Serializable { + PortletMode getCustomMode(); + PortletMode getMappedMode(); + String getDescription(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/CustomWindowState.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/CustomWindowState.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/CustomWindowState.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,7 +22,10 @@ public interface CustomWindowState extends Serializable { + WindowState getCustomState(); + WindowState getMappedState(); + String getDescription(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/MutablePortletApplication.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/MutablePortletApplication.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/MutablePortletApplication.java 2008-05-16 01:54:54 UTC (rev 940) @@ -29,29 +29,34 @@ /** * MutablePortletApplication - * - * Extends the <code>org.apache.pluto.om.portlet.PortletApplicationDefinition</code> + * + * Extends the + * <code>org.apache.pluto.om.portlet.PortletApplicationDefinition</code> * interface adding mutator methods for those attributes that do not have them * so as to make manipulating the portlet OM easier. - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: MutablePortletApplication.java 545987 2007-06-11 01:46:18Z taylor $ - * + * @version $Id: MutablePortletApplication.java 545987 2007-06-11 01:46:18Z + * taylor $ + * */ -public interface MutablePortletApplication extends PortletApplication, Serializable +public interface MutablePortletApplication extends PortletApplication, + Serializable { - public static final String PREFS_ROOT ="portlet_application"; - + + public static final String PREFS_ROOT = "portlet_application"; + /** * Sets the metadata from the extended jetspeed-portlet.xml * * @param metadata */ public void setMetadata(GenericMetadata metadata); - + /** - * Associates the web application definition with this portlet application defintion. + * Associates the web application definition with this portlet application + * defintion. * * @param wad */ @@ -73,35 +78,51 @@ void setPortletDefinitionList(PortletDefinitionList portlets); /** - * <p>Adds a user attribute to the user attribute set.</p> - * @param userAttribute The user attribute. + * <p> + * Adds a user attribute to the user attribute set. + * </p> + * + * @param userAttribute + * The user attribute. */ void addUserAttribute(UserAttribute userAttribute); - + /** - * <p>Adds a user attribute to the user attribute set.</p> - * @param userAttribute The user attribute. + * <p> + * Adds a user attribute to the user attribute set. + * </p> + * + * @param userAttribute + * The user attribute. */ void addUserAttribute(String name, String description); /** - * <p>Sets a user-attribute-ref to the collection of user attribute refs associated - * with this portlet application.</p> + * <p> + * Sets a user-attribute-ref to the collection of user attribute refs + * associated with this portlet application. + * </p> */ void setUserAttributeRefs(Collection userAttributeRefs); - + /** - * <p>Adds a user attribute ref to the user attribute ref set.</p> - * @param userAttributeRef The user attribute ref. + * <p> + * Adds a user attribute ref to the user attribute ref set. + * </p> + * + * @param userAttributeRef + * The user attribute ref. */ void addUserAttributeRef(UserAttributeRef userAttributeRef); /** - * <p>Sets a user-attribute to the collection of user attributes associated - * with this portlet application.</p> + * <p> + * Sets a user-attribute to the collection of user attributes associated + * with this portlet application. + * </p> */ void setUserAttributes(Collection userAttributes); - + void setApplicationIdentifier(String applicationIndentifier); /** @@ -110,78 +131,84 @@ void setDescription(String string); /** - * + * * @param version */ void setVersion(String version); /** - * Sets the Portlet Application type. - * Valid values are: + * Sets the Portlet Application type. Valid values are: * <p> - * {@link MutablePortletApplication#WEBAPP} - A standard web application, stored in the web application - * server's web application space. + * {@link MutablePortletApplication#WEBAPP} - A standard web application, + * stored in the web application server's web application space. * <p> - * {@link MutablePortletApplication#LOCAL} - A local portlet application stored within Jetspeed's web application. + * {@link MutablePortletApplication#LOCAL} - A local portlet application + * stored within Jetspeed's web application. * <p> - * @param type The type of portlet application. + * + * @param type + * The type of portlet application. */ void setApplicationType(int type); /** - * Marks this application as a standard web application, - * stored in the web application server's web application space. + * Marks this application as a standard web application, stored in the web + * application server's web application space. */ public static final int WEBAPP = 0; /** - * Marks this application as a LOCAL portlet application, - * stored in Jetspeed managed portlet application space. + * Marks this application as a LOCAL portlet application, stored in Jetspeed + * managed portlet application space. */ public static final int LOCAL = 1; /** - * Marks this application as a INTERNAL portlet application, - * stored in Jetspeed managed portlet application space. + * Marks this application as a INTERNAL portlet application, stored in + * Jetspeed managed portlet application space. */ public static final int INTERNAL = 2; - + /** - * Adds a Jetspeed component service to the collection of component services allowed for this application. + * Adds a Jetspeed component service to the collection of component services + * allowed for this application. * - * @param service The component service being added. + * @param service + * The component service being added. */ void addJetspeedService(JetspeedServiceReference service); - + /** * The checksum on the portlet XML from the last deployment - * + * * @param checksum */ void setChecksum(long checksum); - + /** * The checksum on the portlet XML from the last deployment * * @return */ long getChecksum(); - + /** * <p> - * Set the Jetspeed Security Constraint reference for this portlet application. - * This security constraint name references a Jetspeed-specific Security Constraint. - * Security Constraints are not Java Security Permissions, but a - * Jetspeed specific way of securing portlets, also known as PSML constraints. - * See the <i>page.security</i> file for examples of defining security constraint definitions. - * If the portlet application does not define a constraint, then no security constraints - * will be applied to this portlet. Security constraints for a portlet are normally - * checking during the render process of a portlet. + * Set the Jetspeed Security Constraint reference for this portlet + * application. This security constraint name references a Jetspeed-specific + * Security Constraint. Security Constraints are not Java Security + * Permissions, but a Jetspeed specific way of securing portlets, also known + * as PSML constraints. See the <i>page.security</i> file for examples of + * defining security constraint definitions. If the portlet application does + * not define a constraint, then no security constraints will be applied to + * this portlet. Security constraints for a portlet are normally checking + * during the render process of a portlet. * </p> * - * @param constraint The name of the Security Definition defined in - * the Jetspeed Security Constraints + * @param constraint + * The name of the Security Definition defined in the Jetspeed + * Security Constraints */ void setJetspeedSecurityConstraint(String constraint); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/MutablePortletEntity.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/MutablePortletEntity.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/MutablePortletEntity.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,22 +20,18 @@ import org.apache.pluto.om.entity.PortletEntity; import org.apache.pluto.om.entity.PortletEntityCtrl; - /** * MutablePortletEntity - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: MutablePortletEntity.java 516448 2007-03-09 16:25:47Z ate $ */ -public interface MutablePortletEntity - extends - PortletEntity, - PortletEntityCtrl +public interface MutablePortletEntity extends PortletEntity, PortletEntityCtrl { public static final String PORTLET_ENTITY_ROOT = "portlet_entity"; - + String getPortletUniqueName(); - + void setFragment(Fragment fragment); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/PortletApplication.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/PortletApplication.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/PortletApplication.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,19 +25,20 @@ import org.apache.pluto.om.portlet.PortletApplicationDefinition; import org.apache.pluto.om.portlet.PortletDefinition; - /** * PortletApplication - * - * Extends the <code>org.apache.pluto.om.portlet.PortletApplicationDefinition</code> - * interface adding methods for those attributes that do not have them - * so as to make manipulating the portlet OM easier. - * + * + * Extends the + * <code>org.apache.pluto.om.portlet.PortletApplicationDefinition</code> + * interface adding methods for those attributes that do not have them so as to + * make manipulating the portlet OM easier. + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: PortletApplication.java 516448 2007-03-09 16:25:47Z ate $ */ public interface PortletApplication extends PortletApplicationDefinition { + /** * Returns the metadata from the extended jetspeed-portlet.xml * @@ -51,29 +52,35 @@ * @return Name of the application */ String getName(); - + /** * @return */ Collection getPortletDefinitions(); /** - * Finds a portlet by portlet name, searching this portlet application's collection. + * Finds a portlet by portlet name, searching this portlet application's + * collection. * - * @param name The portlet name. + * @param name + * The portlet name. * @return A Portlet Definition */ PortletDefinition getPortletDefinitionByName(String name); - + /** - * <p>Gets the collection of user attribute refs associated - * with this portlet application.</p> + * <p> + * Gets the collection of user attribute refs associated with this portlet + * application. + * </p> */ Collection getUserAttributeRefs(); /** - * <p>Gets the collection of user attributes associated - * with this portlet application.</p> + * <p> + * Gets the collection of user attributes associated with this portlet + * application. + * </p> */ Collection getUserAttributes(); @@ -85,63 +92,71 @@ String getDescription(); /** - * Gets the Portlet Application type. - * Valid values are: + * Gets the Portlet Application type. Valid values are: * <p> - * {@link MutablePortletApplication#WEBAPP} - A standard web application, stored in the web application - * server's web application space. + * {@link MutablePortletApplication#WEBAPP} - A standard web application, + * stored in the web application server's web application space. * <p> - * {@link MutablePortletApplication#LOCAL} - A local portlet application stored within Jetspeed's web application. + * {@link MutablePortletApplication#LOCAL} - A local portlet application + * stored within Jetspeed's web application. * <p> + * * @return The type of portlet application. */ int getApplicationType(); - + /** * Gets a collection of all Jetspeed Services allowed for this application. * * @see org.apache.jetspeed.om.common.JetspeedServiceReference - * @return The collection of services of type <code>JetspeedServiceReference</code>. + * @return The collection of services of type + * <code>JetspeedServiceReference</code>. */ Collection getJetspeedServices(); - - Collection getCustomPortletModes(); + + Collection getCustomPortletModes(); + Collection getCustomWindowStates(); - + PortletMode getMappedPortletMode(PortletMode mode); + WindowState getMappedWindowState(WindowState state); + PortletMode getCustomPortletMode(PortletMode mode); + WindowState getCustomWindowState(WindowState state); - + Collection getSupportedPortletModes(); + Collection getSupportedWindowStates(); - + /** * <p> - * Get the Jetspeed Security Constraint reference for this portlet application. - * This security constraint name references a Jetspeed-specific Security Constraint. - * Security Constraints are not Java Security Permissions, but a - * Jetspeed specific way of securing portlets, also known as PSML constraints. - * See the <i>page.security</i> file for examples of defining security constraint definitions. - * If a Jetspeed Security Constraint is not defined for a portlet, the constraint - * applied will then fallback to the constraint defined for the portlet application. - * If the portlet application does not define a constraint, then no security constraints - * will be applied to this portlet. Security constraints for a portlet are normally - * checking during the render process of a portlet. + * Get the Jetspeed Security Constraint reference for this portlet + * application. This security constraint name references a Jetspeed-specific + * Security Constraint. Security Constraints are not Java Security + * Permissions, but a Jetspeed specific way of securing portlets, also known + * as PSML constraints. See the <i>page.security</i> file for examples of + * defining security constraint definitions. If a Jetspeed Security + * Constraint is not defined for a portlet, the constraint applied will then + * fallback to the constraint defined for the portlet application. If the + * portlet application does not define a constraint, then no security + * constraints will be applied to this portlet. Security constraints for a + * portlet are normally checking during the render process of a portlet. * </p> * - * @return The name of the Security Definition applied to this portlet, defined in - * the Jetspeed Security Constraints - */ - String getJetspeedSecurityConstraint(); - + * @return The name of the Security Definition applied to this portlet, + * defined in the Jetspeed Security Constraints + */ + String getJetspeedSecurityConstraint(); + /** - * Returns true if the portlet application is a layout application - * Layouts are not "general" portlets, but instead used to group together - * other layouts and portlet fragments + * Returns true if the portlet application is a layout application Layouts + * are not "general" portlets, but instead used to group together other + * layouts and portlet fragments * * @return true when this app is a Jetspeed layout application */ boolean isLayoutApplication(); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/PortletDefinitionComposite.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/PortletDefinitionComposite.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/PortletDefinitionComposite.java 2008-05-16 01:54:54 UTC (rev 940) @@ -45,33 +45,36 @@ * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: PortletDefinitionComposite.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public interface PortletDefinitionComposite extends PortletDefinition, PortletDefinitionCtrl, Serializable +public interface PortletDefinitionComposite extends PortletDefinition, + PortletDefinitionCtrl, Serializable { + public static final String PORTLETS_PREFS_ROOT = "portlets"; GenericMetadata getMetadata(); - + void setMetadata(GenericMetadata metadata); - + void addLanguage(Language lang); - - void addLanguage(String title, String shortTitle, String keywords, Locale locale); + void addLanguage(String title, String shortTitle, String keywords, + Locale locale); + void addContentType(ContentType cType); - + void addContentType(String contentType, Collection modes); void setLanguageSet(LanguageSet languages); - + String getResourceBundle(); - + Collection getSupportedLocales(); /** - * The PreferenceSet is a collection user-defineable preferences - * that this portlet can use to process its logic. + * The PreferenceSet is a collection user-defineable preferences that this + * portlet can use to process its logic. * * @param preferences */ @@ -82,14 +85,16 @@ void setContentTypeSet(ContentTypeSet contentTypes); void setInitSecurityRoleRefSet(SecurityRoleRefSet securityRefs); - + /** - * Convenience method for directly adding init parameters - * to this <code>PortletDefinition.</code>. This has the - * same affect as + * Convenience method for directly adding init parameters to this + * <code>PortletDefinition.</code>. This has the same affect as * <code>((ParameterSetCtrl)PortletDefinition.getInitParamaterSet()).add()</code> - * @param name Name of parameter to set - * @param value new value of said parameter + * + * @param name + * Name of parameter to set + * @param value + * new value of said parameter * @return ParameterComposite newly created parameter */ ParameterComposite addInitParameter(String name, String value); @@ -103,7 +108,8 @@ * @param DescriptionSet containing locale-specific descriptions of the parameter * @return ParameterComposite newly created parameter */ - ParameterComposite addInitParameter(String name, String value, DescriptionSet description); + ParameterComposite addInitParameter(String name, String value, + DescriptionSet description); /** * Same as <code>setInitParameter(name, title) plus allows you @@ -116,10 +122,11 @@ * @param locale The locale the description * @return ParameterComposite newly created parameter */ - ParameterComposite addInitParameter(String name, String value, String description, Locale locale); + ParameterComposite addInitParameter(String name, String value, + String description, Locale locale); /** - * Setter for setting expiration cache time for this portlet + * Setter for setting expiration cache time for this portlet */ void setExpirationCache(String cache); @@ -134,41 +141,43 @@ String getPortletIdentifier(); /** - * A portlet's unique name is a string formed by the combination of a portlet's - * unique within it's parent application plus the parent application's - * unique name within the portlet container using ":" as a delimiter. - * <br/> - * <strong>FORMAT: </strong> <i>application name</i>:<i>portlet name</i> - * <br/> - * <strong>EXAMPLE: </strong> com.myapp.portletApp1:weather-portlet + * A portlet's unique name is a string formed by the combination of a + * portlet's unique within it's parent application plus the parent + * application's unique name within the portlet container using ":" as a + * delimiter. <br/> <strong>FORMAT: </strong> <i>application name</i>:<i>portlet + * name</i> <br/> <strong>EXAMPLE: </strong> + * com.myapp.portletApp1:weather-portlet * - - * @return Name that uniquely indetifies this portlet within the container. If - * either the name of the portlet is <code>null</code> or this portlet has not - * yet been assigned to an portlet application, <code>null</code> is returned. + * + * @return Name that uniquely indetifies this portlet within the container. + * If either the name of the portlet is <code>null</code> or this + * portlet has not yet been assigned to an portlet application, + * <code>null</code> is returned. */ String getUniqueName(); /** * Returns localized text of this PortletDefinitions display name. * - * @param locale Locale to get the display name for + * @param locale + * Locale to get the display name for * @return Localized text string of the display name or <code>null</code> - * if no DisplayName exists for this locale + * if no DisplayName exists for this locale */ String getDisplayNameText(Locale locale); /** * Returns localized text of this PortletDefinitions description. * - * @param locale Locale to get the description for + * @param locale + * Locale to get the description for * @return Localized text string of the display name or <code>null</code> - * if no Description exists for this locale + * if no Description exists for this locale */ String getDescriptionText(Locale locale); void addDescription(Locale locale, String description); - + DescriptionSet getDescriptionSet(); void addDisplayName(Locale locale, String displayName); @@ -180,10 +189,10 @@ * </p> * * @param displayName - * + * */ void addDisplayName(DisplayName displayName); - + DisplayNameSet getDisplayNameSet(); String getPreferenceValidatorClassname(); @@ -196,49 +205,53 @@ * addSecurityRoleRef * </p> * - * Adds the <code>securityRef</code> to the existing - * set of SecurityRoleRefs of this PortletDefinition + * Adds the <code>securityRef</code> to the existing set of + * SecurityRoleRefs of this PortletDefinition * - * @param securityRef SecurityRoleRef to add. - * + * @param securityRef + * SecurityRoleRef to add. + * */ void addSecurityRoleRef(SecurityRoleRef securityRef); - + SecurityRoleRef addSecurityRoleRef(String roleName, String roleLink); /** * <p> - * Get the Jetspeed Security Constraint reference for this portlet. - * This security constraint name references a Jetspeed-specific Security Constraint. - * Security Constraints are not Java Security Permissions, but a - * Jetspeed specific way of securing portlets, also known as PSML constraints. - * See the <i>page.security</i> file for examples of defining security constraint definitions. - * If a Jetspeed Security Constraint is not defined for a portlet, the constraint - * applied will then fallback to the constraint defined for the portlet application. - * If the portlet application does not define a constraint, then no security constraints - * will be applied to this portlet. Security constraints for a portlet are normally - * checking during the render process of a portlet. + * Get the Jetspeed Security Constraint reference for this portlet. This + * security constraint name references a Jetspeed-specific Security + * Constraint. Security Constraints are not Java Security Permissions, but a + * Jetspeed specific way of securing portlets, also known as PSML + * constraints. See the <i>page.security</i> file for examples of defining + * security constraint definitions. If a Jetspeed Security Constraint is not + * defined for a portlet, the constraint applied will then fallback to the + * constraint defined for the portlet application. If the portlet + * application does not define a constraint, then no security constraints + * will be applied to this portlet. Security constraints for a portlet are + * normally checking during the render process of a portlet. * </p> * - * @return The name of the Security Definition applied to this portlet, defined in - * the Jetspeed Security Constraints - */ + * @return The name of the Security Definition applied to this portlet, + * defined in the Jetspeed Security Constraints + */ String getJetspeedSecurityConstraint(); - + /** * <p> - * Set the Jetspeed Security Constraint reference for this portlet. - * This security constraint name references a Jetspeed-specific Security Constraint. - * Security Constraints are not Java Security Permissions, but a - * Jetspeed specific way of securing portlets, also known as PSML constraints. - * See the <i>page.security</i> file for examples of defining security constraint definitions. - * If the portlet application does not define a constraint, then no security constraints - * will be applied to this portlet. Security constraints for a portlet are normally - * checking during the render process of a portlet. + * Set the Jetspeed Security Constraint reference for this portlet. This + * security constraint name references a Jetspeed-specific Security + * Constraint. Security Constraints are not Java Security Permissions, but a + * Jetspeed specific way of securing portlets, also known as PSML + * constraints. See the <i>page.security</i> file for examples of defining + * security constraint definitions. If the portlet application does not + * define a constraint, then no security constraints will be applied to this + * portlet. Security constraints for a portlet are normally checking during + * the render process of a portlet. * </p> * - * @param constraint The name of the Security Definition defined in - * the Jetspeed Security Constraints + * @param constraint + * The name of the Security Definition defined in the Jetspeed + * Security Constraints */ void setJetspeedSecurityConstraint(String constraint); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/PrincipalAware.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/PrincipalAware.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/portlet/PrincipalAware.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,12 +20,13 @@ /** * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Generation - Code and Comments + * + * TODO To change the template for this generated type comment go to Window - + * Preferences - Java - Code Generation - Code and Comments */ public interface PrincipalAware { - Principal getPrincipal(); + Principal getPrincipal(); + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferenceComposite.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferenceComposite.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferenceComposite.java 2008-05-16 01:54:54 UTC (rev 940) @@ -31,42 +31,48 @@ * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: PreferenceComposite.java,v 1.2 2004/06/18 20:46:21 weaver Exp $ - * + * */ -public interface PreferenceComposite extends PreferenceCtrl, Preference, Serializable +public interface PreferenceComposite extends PreferenceCtrl, Preference, + Serializable { - String DEFAULT_PREFERENCE = "org.apache.pluto.om.common.Preference.default"; - String USER_PREFERENCE = "org.apache.pluto.om.common.Preference.default.user"; - + + String DEFAULT_PREFERENCE = "org.apache.pluto.om.common.Preference.default"; + + String USER_PREFERENCE = "org.apache.pluto.om.common.Preference.default.user"; + void addDescription(Locale locale, String Description); - Description getDescription(Locale locale); + Description getDescription(Locale locale); /** - * @throws java.lang.ArrayIndexOutofBounds if index is outside the constraints + * @throws java.lang.ArrayIndexOutofBounds + * if index is outside the constraints * @param index - * @return The String value at the specified index or <code>null</code> - * if no values are present. + * @return The String value at the specified index or <code>null</code> if + * no values are present. */ String getValueAt(int index); - + /** * * @param index */ - void removeValueAt(int index); + void removeValueAt(int index); /** * * <p> * setValueAt * </p> - * Sets the current Preference's value at <code>index</code> - * to the specified <code>value</code> + * Sets the current Preference's value at <code>index</code> to the + * specified <code>value</code> * - * @param index Index hows value will be set. - * @param value Value to set - * + * @param index + * Index hows value will be set. + * @param value + * Value to set + * */ void setValueAt(int index, String value); @@ -76,8 +82,10 @@ * addValue * </p> * Adds a new value to this Preference. - * @param value Vale to add to the preference - * + * + * @param value + * Vale to add to the preference + * */ void addValue(String value); @@ -93,11 +101,10 @@ * setValues * </p> * - * Replaces the current set of values of this preference - * with this one. + * Replaces the current set of values of this preference with this one. * - * @param stringValues - * + * @param stringValues + * */ void setValues(String[] stringValues); @@ -105,13 +112,14 @@ * @return */ String getType(); + /** * @param string */ void setType(String string); - + String[] cloneValues(); - + Iterator getDescriptions(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferenceSetComposite.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferenceSetComposite.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferenceSetComposite.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,10 +28,12 @@ * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: PreferenceSetComposite.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public interface PreferenceSetComposite extends PreferenceSet, PreferenceSetCtrl +public interface PreferenceSetComposite extends PreferenceSet, + PreferenceSetCtrl { + Set getNames(); int size(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferenceValue.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferenceValue.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferenceValue.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,28 +17,29 @@ package org.apache.jetspeed.om.common.preference; /** - * PreferenceValue - * <br /> - * Represents an individual value for a preference which could - * either be the default preferences from a portlet's deployment descriptor - * or a preference value for a specific user. This class should only be - * accessed by Jetspeed internals as Preference values are really - * only String values. The use of preference value objects helps - * facilitate the use object relational tools in terms of persistence operations. + * PreferenceValue <br /> + * Represents an individual value for a preference which could either be the + * default preferences from a portlet's deployment descriptor or a preference + * value for a specific user. This class should only be accessed by Jetspeed + * internals as Preference values are really only String values. The use of + * preference value objects helps facilitate the use object relational tools in + * terms of persistence operations. * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: PreferenceValue.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface PreferenceValue { + /** * @return */ public abstract String getValue(); + /** * @param string */ - public abstract void setValue(String string); - + public abstract void setValue(String string); + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferencesValidatorFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferencesValidatorFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/preference/PreferencesValidatorFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.om.common.preference; import java.io.Serializable; @@ -22,5 +22,6 @@ public interface PreferencesValidatorFactory extends Serializable { + PreferencesValidator getPreferencesValidator(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/servlet/MutableSecurityRole.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/servlet/MutableSecurityRole.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/servlet/MutableSecurityRole.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,13 +20,14 @@ /** * MutableSecurityRole - * + * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id: MutableSecurityRole.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface MutableSecurityRole extends SecurityRole { + void setDescription(String description); void setRoleName(String roleName); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/servlet/MutableSecurityRoleSet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/servlet/MutableSecurityRoleSet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/servlet/MutableSecurityRoleSet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,18 +21,20 @@ /** * MutableSecurityRoleSet - * + * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id: MutableSecurityRoleSet.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface MutableSecurityRoleSet extends SecurityRoleSet { + /** * Adds a SecurityRole to the set - * - * @param securityRole the security-role to be added - * + * + * @param securityRole + * the security-role to be added + * * @return the new SecurityRole */ public SecurityRole add(SecurityRole securityRole); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/servlet/MutableWebApplication.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/servlet/MutableWebApplication.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/common/servlet/MutableWebApplication.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,19 +26,21 @@ /** * - * WebApplicationComposite - * This interface is a combination of the two interface classes - * used to identify a web application. It has additional methods - * to make it easier to use/test within Jetspeed. + * WebApplicationComposite This interface is a combination of the two interface + * classes used to identify a web application. It has additional methods to make + * it easier to use/test within Jetspeed. + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: MutableWebApplication.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ -public interface MutableWebApplication extends WebApplicationDefinition, Serializable +public interface MutableWebApplication extends WebApplicationDefinition, + Serializable { + void setContextRoot(String contextRoot); - + void setDescriptionSet(DescriptionSet descriptions); void setDisplayNameSet(DisplayNameSet names); @@ -46,7 +48,7 @@ void addDisplayName(Locale locale, String name); void addDescription(Locale locale, String description); - + void addSecurityRole(SecurityRole securityRole); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/Folder.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/Folder.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/Folder.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,97 +30,130 @@ /** * Folder - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @author <a href="mailto:jford ¡÷ apache.org">Jeremy Ford</a> * @version $Id: Folder.java 516448 2007-03-09 16:25:47Z ate $ */ public interface Folder extends Node { + String FOLDER_TYPE = "folder"; String FALLBACK_DEFAULT_PAGE = "default-page.psml"; + String PAGE_NOT_FOUND_PAGE = "page_not_found.psml"; - + String RESERVED_SUBSITE_FOLDER_PREFIX = "__"; + String RESERVED_FOLDER_PREFIX = "_"; + String RESERVED_USER_FOLDER_NAME = RESERVED_FOLDER_PREFIX + "user"; + String RESERVED_ROLE_FOLDER_NAME = RESERVED_FOLDER_PREFIX + "role"; + String RESERVED_GROUP_FOLDER_NAME = RESERVED_FOLDER_PREFIX + "group"; - String RESERVED_MEDIATYPE_FOLDER_NAME = RESERVED_FOLDER_PREFIX + "mediatype"; + + String RESERVED_MEDIATYPE_FOLDER_NAME = RESERVED_FOLDER_PREFIX + + "mediatype"; + String RESERVED_LANGUAGE_FOLDER_NAME = RESERVED_FOLDER_PREFIX + "language"; + String RESERVED_COUNTRY_FOLDER_NAME = RESERVED_FOLDER_PREFIX + "country"; - - String USER_FOLDER = PATH_SEPARATOR + RESERVED_USER_FOLDER_NAME + PATH_SEPARATOR; - String ROLE_FOLDER = PATH_SEPARATOR + RESERVED_ROLE_FOLDER_NAME + PATH_SEPARATOR; - String GROUP_FOLDER = PATH_SEPARATOR + RESERVED_GROUP_FOLDER_NAME + PATH_SEPARATOR; - String MEDIATYPE_FOLDER = PATH_SEPARATOR + RESERVED_MEDIATYPE_FOLDER_NAME + PATH_SEPARATOR; - String LANGUAGE_FOLDER = PATH_SEPARATOR + RESERVED_LANGUAGE_FOLDER_NAME + PATH_SEPARATOR; - String COUNTRY_FOLDER = PATH_SEPARATOR + RESERVED_COUNTRY_FOLDER_NAME + PATH_SEPARATOR; - int RESERVED_FOLDER_NONE = 0; + String USER_FOLDER = PATH_SEPARATOR + RESERVED_USER_FOLDER_NAME + + PATH_SEPARATOR; + + String ROLE_FOLDER = PATH_SEPARATOR + RESERVED_ROLE_FOLDER_NAME + + PATH_SEPARATOR; + + String GROUP_FOLDER = PATH_SEPARATOR + RESERVED_GROUP_FOLDER_NAME + + PATH_SEPARATOR; + + String MEDIATYPE_FOLDER = PATH_SEPARATOR + RESERVED_MEDIATYPE_FOLDER_NAME + + PATH_SEPARATOR; + + String LANGUAGE_FOLDER = PATH_SEPARATOR + RESERVED_LANGUAGE_FOLDER_NAME + + PATH_SEPARATOR; + + String COUNTRY_FOLDER = PATH_SEPARATOR + RESERVED_COUNTRY_FOLDER_NAME + + PATH_SEPARATOR; + + int RESERVED_FOLDER_NONE = 0; + int RESERVED_FOLDER_SUBSITES = 1; + int RESERVED_FOLDER_USERS = 2; + int RESERVED_FOLDER_ROLES = 3; + int RESERVED_FOLDER_GROUPS = 4; + int RESERVED_FOLDER_MEDIATYPE = 5; + int RESERVED_FOLDER_LANGUAGE = 6; + int RESERVED_FOLDER_COUNTRY = 7; + int RESERVED_FOLDER_OTHER = 9999; - + /** - * Returns the name of the skin that applies to this - * folder. - * + * Returns the name of the skin that applies to this folder. + * * @return the page default skin name */ String getSkin(); /** * Modifies the skin for this folder. - * - * @param skinName the name of the new skin for the folder + * + * @param skinName + * the name of the new skin for the folder */ void setSkin(String skinName); /** - * Returns the name of the default decorator as set here or - * in parent folders that applies to page fragments - * in this folder or subfolders. - * - * @param fragmentType the type of fragment considered + * Returns the name of the default decorator as set here or in parent + * folders that applies to page fragments in this folder or subfolders. + * + * @param fragmentType + * the type of fragment considered * @return the decorator name for the selected type */ String getEffectiveDefaultDecorator(String fragmentType); /** - * Returns the name of the default decorator that applies to page - * fragments in this folder or subfolders. - * - * @param fragmentType the type of fragment considered + * Returns the name of the default decorator that applies to page fragments + * in this folder or subfolders. + * + * @param fragmentType + * the type of fragment considered * @return the decorator name for the selected type */ String getDefaultDecorator(String fragmentType); /** * Modifies the default decorator for the specified fragment type. - * - * @param decoratorName the name of the new decorator for the type - * @param fragmentType the type of fragment considered + * + * @param decoratorName + * the name of the new decorator for the type + * @param fragmentType + * the type of fragment considered */ void setDefaultDecorator(String decoratorName, String fragmentType); /** * getDocumentOrder - * + * * @return list of ordered document names in folder */ List getDocumentOrder(); - + /** * setDocumentOrder - * - * @param docIndexes list of ordered document names in folder + * + * @param docIndexes + * list of ordered document names in folder */ void setDocumentOrder(List docIndexes); @@ -129,17 +162,17 @@ * <p> * getDefaultPage * </p> - * + * * @return A String representing the default psml page for this folder */ String getDefaultPage(); - + /** * * <p> * setDefaultPage * </p> - * + * * @param defaultPage */ void setDefaultPage(String defaultPage); @@ -149,171 +182,175 @@ * <p> * getFolders * </p> - * - * @return A <code>NodeSet</code> containing all sub-folders directly under - * this folder. + * + * @return A <code>NodeSet</code> containing all sub-folders directly + * under this folder. * @throws DocumentException */ NodeSet getFolders() throws DocumentException; - + /** * * <p> * getFolder * </p> - * + * * @param name * @return A Folder referenced by this folder. * @throws FolderNotFoundException * @throws DocumentException */ - Folder getFolder(String name) throws FolderNotFoundException, DocumentException; + Folder getFolder(String name) throws FolderNotFoundException, + DocumentException; /** * * <p> * getPages * </p> - * + * * @return NodeSet of all the Pages referenced by this Folder. * @throws NodeException - * @throws PageNotFoundException if any of the Pages referenced by this Folder - * could not be found. + * @throws PageNotFoundException + * if any of the Pages referenced by this Folder could not be + * found. */ NodeSet getPages() throws NodeException; - + /** * * <p> * getPage * </p> - * + * * @param name * @return A Page referenced by this folder. - * @throws PageNotFoundException if the Page requested could not be found. + * @throws PageNotFoundException + * if the Page requested could not be found. * @throws DocumentException * @throws NodeException */ Page getPage(String name) throws PageNotFoundException, NodeException; - + /** * * <p> * getLinks * </p> - * + * * @return NodeSet of all the Links referenced by this Folder. * @throws DocumentException * @throws NodeException - */ + */ NodeSet getLinks() throws NodeException; - + /** * * <p> * getLink * </p> - * + * * @param name * @return A Link referenced by this folder. - * @throws DocumentNotFoundException if the document requested could not be found. + * @throws DocumentNotFoundException + * if the document requested could not be found. * @throws NodeException - */ + */ Link getLink(String name) throws DocumentNotFoundException, NodeException; - + /** * * <p> * getPageSecurity * </p> - * + * * @param name * @return A PageSecurity referenced by this folder. - * @throws DocumentNotFoundException if the document requested could not be found. + * @throws DocumentNotFoundException + * if the document requested could not be found. * @throws NodeException - */ - PageSecurity getPageSecurity() throws DocumentNotFoundException, NodeException; + */ + PageSecurity getPageSecurity() throws DocumentNotFoundException, + NodeException; /** * * <p> * getAll * </p> - * - * @return A <code>NodeSet</code> containing all sub-folders and documents directly under - * this folder. + * + * @return A <code>NodeSet</code> containing all sub-folders and documents + * directly under this folder. * @throws DocumentException */ NodeSet getAll() throws DocumentException; /** * getMenuDefinitions - get list of menu definitions - * + * * @return definition list */ List getMenuDefinitions(); /** * newMenuDefinition - creates a new empty menu definition - * + * * @return a newly created MenuDefinition object for use in Folder */ MenuDefinition newMenuDefinition(); /** * newMenuExcludeDefinition - creates a new empty menu exclude definition - * + * * @return a newly created MenuExcludeDefinition object for use in Folder */ MenuExcludeDefinition newMenuExcludeDefinition(); /** * newMenuIncludeDefinition - creates a new empty menu include definition - * + * * @return a newly created MenuIncludeDefinition object for use in Folder */ MenuIncludeDefinition newMenuIncludeDefinition(); /** * newMenuOptionsDefinition - creates a new empty menu options definition - * + * * @return a newly created MenuOptionsDefinition object for use in Folder */ MenuOptionsDefinition newMenuOptionsDefinition(); /** - * newMenuSeparatorDefinition - creates a new empty menu separator definition - * + * newMenuSeparatorDefinition - creates a new empty menu separator + * definition + * * @return a newly created MenuSeparatorDefinition object for use in Folder */ MenuSeparatorDefinition newMenuSeparatorDefinition(); /** * setMenuDefinitions - set list of menu definitions - * - * @param definitions definition list + * + * @param definitions + * definition list */ void setMenuDefinitions(List definitions); - + /** - * Determines if a folder is a reserved folder. - * Reserved folders are special folders that can - * hold subsites, the root of user folders, and the - * root of role folders. + * Determines if a folder is a reserved folder. Reserved folders are special + * folders that can hold subsites, the root of user folders, and the root of + * role folders. + * * @return */ boolean isReserved(); - + /** - * Returns a valid reserved folder type: - * RESERVED_FOLDER_SUBSITES - * RESERVED_FOLDER_USERS - * RESERVED_FOLDER_ROLES - * RESERVED_FOLDER_GROUPS - * RESERVED_FOLDER_MEDIATYPE - * RESERVED_FOLDER_LANGUAGE - * RESERVED_FOLDER_COUNTRY - * + * Returns a valid reserved folder type: RESERVED_FOLDER_SUBSITES + * RESERVED_FOLDER_USERS RESERVED_FOLDER_ROLES RESERVED_FOLDER_GROUPS + * RESERVED_FOLDER_MEDIATYPE RESERVED_FOLDER_LANGUAGE + * RESERVED_FOLDER_COUNTRY + * * @return one of the valid reserved folder types */ int getReservedType(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/FolderNotFoundException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/FolderNotFoundException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/FolderNotFoundException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,11 +23,12 @@ * FolderNotFoundException * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: FolderNotFoundException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class FolderNotFoundException extends NodeNotFoundException { @@ -44,7 +45,7 @@ /** * @param message */ - public FolderNotFoundException( String message ) + public FolderNotFoundException(String message) { super(message); // TODO Auto-generated constructor stub @@ -53,7 +54,7 @@ /** * @param nested */ - public FolderNotFoundException( Throwable nested ) + public FolderNotFoundException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -63,7 +64,7 @@ * @param msg * @param nested */ - public FolderNotFoundException( String msg, Throwable nested ) + public FolderNotFoundException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/InvalidFolderException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/InvalidFolderException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/InvalidFolderException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,12 +23,13 @@ * InvalidFolderException * </p> * <p> - * Thrown when there is an attempt to represent a node as folder when - * it is actually not a folder. + * Thrown when there is an attempt to represent a node as folder when it is + * actually not a folder. * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: InvalidFolderException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class InvalidFolderException extends NodeException { @@ -45,7 +46,7 @@ /** * @param message */ - public InvalidFolderException( String message ) + public InvalidFolderException(String message) { super(message); // TODO Auto-generated constructor stub @@ -54,7 +55,7 @@ /** * @param nested */ - public InvalidFolderException( Throwable nested ) + public InvalidFolderException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -64,7 +65,7 @@ * @param msg * @param nested */ - public InvalidFolderException( String msg, Throwable nested ) + public InvalidFolderException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuDefinition.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuDefinition.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuDefinition.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,15 +22,15 @@ import org.apache.jetspeed.om.common.GenericMetadata; /** - * This interface describes the object used to define - * portal site menus comprised of nested menus, options, - * and separators. + * This interface describes the object used to define portal site menus + * comprised of nested menus, options, and separators. * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> * @version $Id: MenuDefinition.java 516448 2007-03-09 16:25:47Z ate $ */ public interface MenuDefinition { + /** * ANY_PROFILE_LOCATOR - wildcard value for profile locator names */ @@ -38,180 +38,194 @@ /** * getName - get menu name - * + * * @return menu name */ String getName(); /** * setName - set menu name - * - * @param name menu name + * + * @param name + * menu name */ void setName(String name); /** - * getOptions - get comma separated menu options if not specified as elements - * + * getOptions - get comma separated menu options if not specified as + * elements + * * @return option paths specification */ String getOptions(); /** - * setOptions - set comma separated menu options if not specified as elements - * - * @param option option paths specification + * setOptions - set comma separated menu options if not specified as + * elements + * + * @param option + * option paths specification */ void setOptions(String options); /** * getDepth - get depth of inclusion for folder menu options - * + * * @return inclusion depth */ int getDepth(); /** * setDepth - set depth of inclusion for folder menu options - * - * @param depth inclusion depth + * + * @param depth + * inclusion depth */ void setDepth(int depth); /** * isPaths - get generate ordered path options for specified options - * + * * @return paths options flag */ boolean isPaths(); - + /** * setPaths - set generate ordered path options for specified options - * - * @param paths paths options flag + * + * @param paths + * paths options flag */ void setPaths(boolean paths); - + /** * isRegexp - get regexp flag for interpreting specified options - * + * * @return regexp flag */ boolean isRegexp(); /** * setRegexp - set regexp flag for interpreting specified options - * - * @param regexp regexp flag + * + * @param regexp + * regexp flag */ void setRegexp(boolean regexp); /** * getProfile - get profile locator used to filter specified options - * + * * @return profile locator name */ String getProfile(); /** * setProfile - set profile locator used to filter specified options - * - * @param locatorName profile locator name + * + * @param locatorName + * profile locator name */ void setProfile(String locatorName); /** * getOrder - get comma separated regexp ordering patterns for options - * + * * @return ordering patterns list */ String getOrder(); /** * setOrder - set comma separated regexp ordering patterns for options - * - * @param order ordering patterns list + * + * @param order + * ordering patterns list */ void setOrder(String order); /** * getSkin - get skin name for menu - * + * * @return skin name */ String getSkin(); /** * setSkin - set skin name for menu - * - * @param name skin name + * + * @param name + * skin name */ void setSkin(String name); /** * getTitle - get default title for menu - * + * * @return title text */ String getTitle(); /** * setTitle - set default title for menu - * - * @param title title text + * + * @param title + * title text */ void setTitle(String title); /** * getShortTitle - get default short title for menu - * + * * @return short title text */ String getShortTitle(); /** * setShortTitle - set default short title for menu - * - * @param title short title text + * + * @param title + * short title text */ void setShortTitle(String title); /** * getTitle - get locale specific title for menu from metadata - * - * @param locale preferred locale + * + * @param locale + * preferred locale * @return title text */ String getTitle(Locale locale); /** * getShortTitle - get locale specific short title for menu from metadata - * - * @param locale preferred locale + * + * @param locale + * preferred locale * @return short title text */ String getShortTitle(Locale locale); /** * getMetadata - get generic metadata instance for menu - * + * * @return metadata instance */ GenericMetadata getMetadata(); /** - * getMenuElements - get ordered list of menu options, - * nested menus, separators, included - * menu, and excluded menu elements - * + * getMenuElements - get ordered list of menu options, nested menus, + * separators, included menu, and excluded menu elements + * * @return element list */ List getMenuElements(); /** * setMenuElements - set ordered list of menu options - * - * @param elements element list + * + * @param elements + * element list */ void setMenuElements(List elements); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuExcludeDefinition.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuExcludeDefinition.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuExcludeDefinition.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,25 +17,27 @@ package org.apache.jetspeed.om.folder; /** - * This interface describes the object used to define - * portal site menu excluded menu options. + * This interface describes the object used to define portal site menu excluded + * menu options. * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> * @version $Id: MenuExcludeDefinition.java 516448 2007-03-09 16:25:47Z ate $ */ public interface MenuExcludeDefinition { + /** * getName - get menu name with options to exclude - * + * * @return menu name */ String getName(); /** * setName - set menu name with options to exclude - * - * @param name menu name + * + * @param name + * menu name */ void setName(String name); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuIncludeDefinition.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuIncludeDefinition.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuIncludeDefinition.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,39 +17,42 @@ package org.apache.jetspeed.om.folder; /** - * This interface describes the object used to define - * portal site menu included menus. + * This interface describes the object used to define portal site menu included + * menus. * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> * @version $Id: MenuIncludeDefinition.java 516448 2007-03-09 16:25:47Z ate $ */ public interface MenuIncludeDefinition { + /** * getName - get menu name to nest or with options to include - * + * * @return menu name */ String getName(); /** * setName - set menu name to nest or with options to include - * - * @param name menu name + * + * @param name + * menu name */ void setName(String name); /** * isNest - get nesting for included menu - * + * * @return nest options flag */ boolean isNest(); - + /** * setNest - set nesting for included menu - * - * @param nest nest menu flag + * + * @param nest + * nest menu flag */ - void setNest(boolean nest); + void setNest(boolean nest); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuOptionsDefinition.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuOptionsDefinition.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuOptionsDefinition.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,14 +17,14 @@ package org.apache.jetspeed.om.folder; /** - * This interface describes the object used to define - * portal site menu options. + * This interface describes the object used to define portal site menu options. * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> * @version $Id: MenuOptionsDefinition.java 516448 2007-03-09 16:25:47Z ate $ */ public interface MenuOptionsDefinition { + /** * ANY_PROFILE_LOCATOR - wildcard value for profile locator names */ @@ -32,99 +32,106 @@ /** * getOptions - get comma separated menu options - * + * * @return option paths specification */ String getOptions(); /** * setOptions - set comma separated menu options - * - * @param options option paths specification + * + * @param options + * option paths specification */ void setOptions(String options); /** * getDepth - get depth of inclusion for folder options - * + * * @return inclusion depth */ int getDepth(); /** * setDepth - set depth of inclusion for folder options - * - * @param depth inclusion depth + * + * @param depth + * inclusion depth */ void setDepth(int depth); /** * isPaths - get generate ordered path options - * + * * @return paths options flag */ boolean isPaths(); - + /** * setPaths - set generate ordered path options - * - * @param paths paths options flag + * + * @param paths + * paths options flag */ void setPaths(boolean paths); - + /** * isRegexp - get regexp flag for interpreting options - * + * * @return regexp flag */ boolean isRegexp(); /** * setRegexp - set regexp flag for interpreting options - * - * @param regexp regexp flag + * + * @param regexp + * regexp flag */ void setRegexp(boolean regexp); /** * getProfile - get profile locator used to filter options - * + * * @return profile locator name */ String getProfile(); /** * setProfile - set profile locator used to filter options - * - * @param locatorName profile locator name + * + * @param locatorName + * profile locator name */ void setProfile(String locatorName); /** * getOrder - get comma separated regexp ordering patterns - * + * * @return ordering patterns list */ String getOrder(); /** * setOrder - set comma separated regexp ordering patterns - * - * @param order ordering patterns list + * + * @param order + * ordering patterns list */ void setOrder(String order); /** * getSkin - get skin name for options - * + * * @return skin name */ String getSkin(); /** * setSkin - set skin name for options - * - * @param name skin name + * + * @param name + * skin name */ void setSkin(String name); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuSeparatorDefinition.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuSeparatorDefinition.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/MenuSeparatorDefinition.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,75 +21,81 @@ import org.apache.jetspeed.om.common.GenericMetadata; /** - * This interface describes the object used to define - * portal site menu separators. + * This interface describes the object used to define portal site menu + * separators. * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> * @version $Id: MenuSeparatorDefinition.java 516448 2007-03-09 16:25:47Z ate $ */ public interface MenuSeparatorDefinition { + /** * getSkin - get skin name for separator - * + * * @return skin name */ String getSkin(); /** * setSkin - set skin name for separator - * - * @param name skin name + * + * @param name + * skin name */ void setSkin(String name); /** * getTitle - get default title for separator - * + * * @return title text */ String getTitle(); /** * setTitle - set default title for separator - * - * @param title title text + * + * @param title + * title text */ void setTitle(String title); /** * getText - get default text for separator - * + * * @return text */ String getText(); /** * setText - set default text for separator - * - * @param text text + * + * @param text + * text */ void setText(String text); /** * getTitle - get locale specific title for separator from metadata - * - * @param locale preferred locale + * + * @param locale + * preferred locale * @return title text */ String getTitle(Locale locale); /** * getText - get locale specific text for separator from metadata - * - * @param locale preferred locale + * + * @param locale + * preferred locale * @return text */ String getText(Locale locale); /** * getMetadata - get generic metadata instance for menu - * + * * @return metadata instance */ GenericMetadata getMetadata(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/Reset.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/Reset.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/folder/Reset.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,22 +1,23 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.om.folder; public interface Reset { - void reset(); + + void reset(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/BaseElement.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/BaseElement.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/BaseElement.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,46 +20,49 @@ /** * BaseElement - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: BaseElement.java 516448 2007-03-09 16:25:47Z ate $ */ public interface BaseElement extends SecuredResource { + /** * Returns the unique Id of this element. This id is guaranteed to be unique * from the complete portal and is suitable to be used as a unique key. - * + * * @return the unique id of this element. */ public String getId(); /** * Returns the title in the default Locale - * + * * @return the page title */ public String getTitle(); /** * Sets the title for the default Locale - * - * @param title the new title + * + * @param title + * the new title */ public void setTitle(String title); /** * Returns the short title in the default Locale - * + * * @return the page short title */ public String getShortTitle(); /** * Sets the short title for the default Locale - * - * @param title the new title + * + * @param title + * the new title */ public void setShortTitle(String title); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/ContentFragment.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/ContentFragment.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/ContentFragment.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.om.page; import java.util.List; @@ -21,32 +21,33 @@ import org.apache.jetspeed.aggregator.PortletContent; import org.apache.jetspeed.decoration.Decoration; - /** * - * ContentFragment provides a volatile wrapper interface for - * actual {@link org.apache.jetspeed.om.page.Fragment} metadata - * objects. Since Fragments are cached and are not request specific - * they cannot be used to store request-level content. This is where - * we use the <code>ContentFragment</code> to solve this problem. + * ContentFragment provides a volatile wrapper interface for actual + * {@link org.apache.jetspeed.om.page.Fragment} metadata objects. Since + * Fragments are cached and are not request specific they cannot be used to + * store request-level content. This is where we use the + * <code>ContentFragment</code> to solve this problem. * * @author weaver ¡÷ apache.org - * + * */ public interface ContentFragment extends Fragment { + /** - * Provides a list of of child ContentFragments that wrap - * the actual Fragment metadata objects. + * Provides a list of of child ContentFragments that wrap the actual + * Fragment metadata objects. + * * @return */ - List getContentFragments(); + List getContentFragments(); - /** - * Overridden to make it clear to the implemetor the {@link List} - * returned <strong>MUST</strong> ContentFragments and not - * just regular {@link org.apache.jetspeed.om.page.Fragment}s - * + /** + * Overridden to make it clear to the implemetor the {@link List} returned + * <strong>MUST</strong> ContentFragments and not just regular + * {@link org.apache.jetspeed.om.page.Fragment}s + * * @return a collection containing ContentFragment objects */ public List getFragments(); @@ -57,13 +58,14 @@ * getRenderedContent * </p> * <p> - * Returns the raw,undecorated content of this fragment. If - * overridenContent has been set and portlet content has not, - * overridden content should be returned. + * Returns the raw,undecorated content of this fragment. If overridenContent + * has been set and portlet content has not, overridden content should be + * returned. * </p> - * + * * @return The raw,undecorated content of this fragment. - * @throws java.lang.IllegalStateException if the content has not yet been set. + * @throws java.lang.IllegalStateException + * if the content has not yet been set. */ public String getRenderedContent() throws IllegalStateException; @@ -73,10 +75,10 @@ * overrideRenderedContent * </p> * <p> - * Can be used to store errors that may have occurred during the - * rendering process. + * Can be used to store errors that may have occurred during the rendering + * process. * </p> - * + * * @param contnent */ public void overrideRenderedContent(String contnent); @@ -85,39 +87,42 @@ * @return the overridden content set by overrideRenderedContent */ public String getOverriddenContent(); + /** * * <p> * setPortletContent * </p> - * + * * @param portletContent */ public void setPortletContent(PortletContent portletContent); - + /** * Retrieve the content for this fragment * * @return PortletContent */ public PortletContent getPortletContent(); - + /** - * Retrieves the actual <code>org.apache.jetspeed.decoration.decorator</code> - * object for this content fragment. + * Retrieves the actual + * <code>org.apache.jetspeed.decoration.decorator</code> object for this + * content fragment. * - * TODO: Re-evaluate the naming as this is somewhat confusing - * due to the existence of Fragment.getDecorator() + * TODO: Re-evaluate the naming as this is somewhat confusing due to the + * existence of Fragment.getDecorator() + * * @return */ Decoration getDecoration(); - + /** * * @param decoration */ void setDecoration(Decoration decoration); - + /** * Checks if the content is instantly rendered from JPT. */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/ContentPage.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/ContentPage.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/ContentPage.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,98 +1,96 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.om.page; import java.util.List; /** - * PageFragment is a volatile wrapper around a - * {@link org.apache.jetspeed.om.page.Page} metadata - * object for use in rendering. As with - * the {@link org.apache.jetspeed.om.page.Fragment} object, - * <code>Page</code> objects are persistent, single-instance - * metadata objects that should not be used to hold per-request - * content. ContentPage solves this by providing a thin, wrapper - * interface that can be used for rendering requested content associated - * with the wrapped page relative to the currect user-request. + * PageFragment is a volatile wrapper around a + * {@link org.apache.jetspeed.om.page.Page} metadata object for use in + * rendering. As with the {@link org.apache.jetspeed.om.page.Fragment} object, + * <code>Page</code> objects are persistent, single-instance metadata objects + * that should not be used to hold per-request content. ContentPage solves this + * by providing a thin, wrapper interface that can be used for rendering + * requested content associated with the wrapped page relative to the currect + * user-request. * * @author weaver ¡÷ apache.org - * + * */ public interface ContentPage extends Page { - /** - * Provides access to a per-request safe ContentFragment. - * ContentFragments add the additional ability to temporarily - * store rendered content of the current request along with - * original, persistent metadata of the Fragment itself. - * - * @return ContentFragment wrapping the actual root Fragment. - */ - ContentFragment getRootContentFragment(); - - void setRootContentFragment(ContentFragment frag); - /** - * Returns a ContentFragment that wraps the actual - * Fragment metadata represented by the id argument. - * @param id unique id of the Fragment we want to retrieve. - * @return - */ - ContentFragment getContentFragmentById(String id); + /** + * Provides access to a per-request safe ContentFragment. ContentFragments + * add the additional ability to temporarily store rendered content of the + * current request along with original, persistent metadata of the Fragment + * itself. + * + * @return ContentFragment wrapping the actual root Fragment. + */ + ContentFragment getRootContentFragment(); + void setRootContentFragment(ContentFragment frag); + /** + * Returns a ContentFragment that wraps the actual Fragment metadata + * represented by the id argument. + * + * @param id + * unique id of the Fragment we want to retrieve. + * @return + */ + ContentFragment getContentFragmentById(String id); - /** - * Returns a list of ContentFragment that wrap the actual - * Fragment metadata represented by the name argument. - * @param name name of the Fragments we want to retrieve. - * @return - */ - List getContentFragmentsByName(String name); + /** + * Returns a list of ContentFragment that wrap the actual Fragment metadata + * represented by the name argument. + * + * @param name + * name of the Fragments we want to retrieve. + * @return + */ + List getContentFragmentsByName(String name); + /** + * Overridden to to indicate that the {@link Fragment} returned must also be + * an instance of ContentFragment. + * + * @param id + * the fragment id to look for + * @return the found ContentFragment object or null if not found + */ + Fragment getFragmentById(String id); + /** + * Overridden to to indicate that the list of {@link Fragment} instances + * returned must also be instances of ContentFragment. + * + * @param name + * the fragments name to look for + * @return the list of found ContentFragment object or null if not found + */ + List getFragmentsByName(String name); -/** - * Overridden to to indicate that the {@link Fragment} returned - * must also be an instance of ContentFragment. - * - * @param id the fragment id to look for - * @return the found ContentFragment object or null if not found - */ - Fragment getFragmentById(String id); - - - -/** - * Overridden to to indicate that the list of {@link Fragment} - * instances returned must also be instances of ContentFragment. - * - * @param name the fragments name to look for - * @return the list of found ContentFragment object or null if not found - */ - List getFragmentsByName(String name); - - - -/** - * Overridden to to indicate that the {@link Fragment} returned - * must also be an instance of ContentFragment. - * - * @return the base Fragment object for this page. - */ - Fragment getRootFragment(); + /** + * Overridden to to indicate that the {@link Fragment} returned must also be + * an instance of ContentFragment. + * + * @return the base Fragment object for this page. + */ + Fragment getRootFragment(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Document.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Document.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Document.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,32 +28,39 @@ * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver </a> * @version $Id: Document.java 551606 2007-06-28 16:07:53Z taylor $ - * + * */ public interface Document extends Node { + /** * Gets the version number * - * @return version number is a string composed of optionally point separated digits + * @return version number is a string composed of optionally point separated + * digits */ String getVersion(); - + /** * Sets the version number * - * @param versionNumber version number is a string composed of optional point separated digits + * @param versionNumber + * version number is a string composed of optional point + * separated digits */ void setVersion(String versionNumber); - + /** * <p> * isDirty * </p> * <p> - * Whether this node is dirty, i.e. should be updated in the persistent store. + * Whether this node is dirty, i.e. should be updated in the persistent + * store. * </p> - * @param hidden flag + * + * @param hidden + * flag */ boolean isDirty(); @@ -62,11 +69,14 @@ * setDirty * </p> * <p> - * Flag the node as dirty / clean, i.e. should be resp. should not be updated in the persistent store + * Flag the node as dirty / clean, i.e. should be resp. should not be + * updated in the persistent store * </p> - * @param hidden flag + * + * @param hidden + * flag */ void setDirty(boolean dirty); - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Fragment.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Fragment.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Fragment.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,98 +21,104 @@ import java.util.Map; /** - * <p>A <code>Fragment</code> is the basic element handled by the aggregation - * engine to compose the final portal page. It represents a reserved screen - * area whose layout is managed by a specified component.</p> - * <p>The component that is responsible for the layout policy of the fragment - * is defined by two properties:<p> + * <p> + * A <code>Fragment</code> is the basic element handled by the aggregation + * engine to compose the final portal page. It represents a reserved screen area + * whose layout is managed by a specified component. + * </p> + * <p> + * The component that is responsible for the layout policy of the fragment is + * defined by two properties: + * <p> * <ul> - * <li><b>type</b>: defines the general class of layout component, enabling - * the engine to retrieve its exact defintion from its component - * repository. - * </li> - * <li><b>name</b>: this is the exact name of the component. This name must - * be unique within a portal instance for a specific component type. - * </li> + * <li><b>type</b>: defines the general class of layout component, enabling + * the engine to retrieve its exact defintion from its component repository. + * </li> + * <li><b>name</b>: this is the exact name of the component. This name must be + * unique within a portal instance for a specific component type. </li> * </ul> - * <p>In addition to specifying the component responsible for the layout, - * the fragment also stores contextual information used for rendering:</p> - * <p>Finally the fragment also holds layout and rendering properties that - * may be used by a parent fragment to layout all its inner fragments in - * an appropriate fashion.</p> - * + * <p> + * In addition to specifying the component responsible for the layout, the + * fragment also stores contextual information used for rendering: + * </p> + * <p> + * Finally the fragment also holds layout and rendering properties that may be + * used by a parent fragment to layout all its inner fragments in an appropriate + * fashion. + * </p> + * * @version $Id: Fragment.java 516448 2007-03-09 16:25:47Z ate $ */ public interface Fragment extends BaseElement, java.io.Serializable { + /** - * A fragment of type PORTLET is considered to be a compliant portlet - * in the sense of the JSR 168. + * A fragment of type PORTLET is considered to be a compliant portlet in the + * sense of the JSR 168. */ - public String PORTLET = "portlet"; + public String PORTLET = "portlet"; /** - * A fragment of type LAYOUT is a specific JSR 168 compliant portlet - * that knows how to layout a Page and depends on the Jetspeed - * layout service. + * A fragment of type LAYOUT is a specific JSR 168 compliant portlet that + * knows how to layout a Page and depends on the Jetspeed layout service. */ - public String LAYOUT = "layout"; + public String LAYOUT = "layout"; /** * row standard layout property name */ - public String ROW_PROPERTY_NAME = "row"; + public String ROW_PROPERTY_NAME = "row"; /** * column standard layout property name */ - public String COLUMN_PROPERTY_NAME = "column"; + public String COLUMN_PROPERTY_NAME = "column"; /** * sizes standard layout property name */ - public String SIZES_PROPERTY_NAME = "sizes"; + public String SIZES_PROPERTY_NAME = "sizes"; /** * x coordinate standard layout property name */ - public String X_PROPERTY_NAME = "x"; + public String X_PROPERTY_NAME = "x"; /** * y coordinate standard layout property name */ - public String Y_PROPERTY_NAME = "y"; + public String Y_PROPERTY_NAME = "y"; /** * z coordinate standard layout property name */ - public String Z_PROPERTY_NAME = "z"; + public String Z_PROPERTY_NAME = "z"; /** * width standard layout property name */ - public String WIDTH_PROPERTY_NAME = "width"; + public String WIDTH_PROPERTY_NAME = "width"; /** * height standard layout property name */ - public String HEIGHT_PROPERTY_NAME = "height"; + public String HEIGHT_PROPERTY_NAME = "height"; /** - * Returns the administrative name of this fragment. This name should map - * to a component name in the component repository defined by the type - * attribute. - * If the name is not mapped to any component, the fragment is discarded - * from the rendering process, as well as any inner fragment. - * + * Returns the administrative name of this fragment. This name should map to + * a component name in the component repository defined by the type + * attribute. If the name is not mapped to any component, the fragment is + * discarded from the rendering process, as well as any inner fragment. + * * @return the administrative name */ public String getName(); /** * Binds an administrative name to this fragment - * - * @param name the administrative name + * + * @param name + * the administrative name */ public void setName(String name); @@ -123,8 +129,9 @@ /** * Binds a type to this fragment - * - * @param type the type + * + * @param type + * the type */ public void setType(String type); @@ -134,10 +141,11 @@ public String getSkin(); /** - * Defines the skin for this fragment. This skin should be - * known by the portal. - * - * @param skinName the name of the new skin applied to this fragment + * Defines the skin for this fragment. This skin should be known by the + * portal. + * + * @param skinName + * the name of the new skin applied to this fragment */ public void setSkin(String skinName); @@ -147,10 +155,11 @@ public String getDecorator(); /** - * Defines the decorator for this fragment. This decorator should be - * known by the portal. - * - * @param decoratorName the name of the decorator applied to this fragment + * Defines the decorator for this fragment. This decorator should be known + * by the portal. + * + * @param decoratorName + * the name of the decorator applied to this fragment */ public void setDecorator(String decoratorName); @@ -161,10 +170,11 @@ public String getState(); /** - * Sets the display state of this fragment. - * Valid states are: "Normal","Minimized","Maximized","Hidden" - * - * @param state the new fragment state + * Sets the display state of this fragment. Valid states are: + * "Normal","Minimized","Maximized","Hidden" + * + * @param state + * the new fragment state */ public void setState(String state); @@ -175,79 +185,83 @@ public String getMode(); /** - * Sets the display mode of this fragment. - * Valid modes are: "View","Edit","Help","Config","Print","Custom" - * - * @param mode the new fragment mode + * Sets the display mode of this fragment. Valid modes are: + * "View","Edit","Help","Config","Print","Custom" + * + * @param mode + * the new fragment mode */ public void setMode(String mode); /** - * Returns all fragments used in this node. This may be - * a page fragment or even directly a portlet fragment - * + * Returns all fragments used in this node. This may be a page fragment or + * even directly a portlet fragment + * * @return a collection containing Fragment objects */ public List getFragments(); /** * getProperty - * + * * Get named property value. - * - * @param propName property name + * + * @param propName + * property name * @return value */ public String getProperty(String propName); - + /** * getIntProperty * * Get named property value as integer. - * - * @param propName property name + * + * @param propName + * property name * @return int value */ public int getIntProperty(String propName); - + /** * getFloatProperty * * Get named property value as float. - * - * @param propName property name + * + * @param propName + * property name * @return float value */ public float getFloatProperty(String propName); - + /** * getProperties * * Get writable Map of properties by name. - * + * * @return properties map */ public Map getProperties(); /** * get layout row property - * + * * @return row layout property - **/ + */ public int getLayoutRow(); /** * set the layout row property - * + * * @param row */ public void setLayoutRow(int row); /** * get layout column property - * + * * @return column layout property - **/ + */ public int getLayoutColumn(); /** @@ -256,110 +270,116 @@ * @param column */ public void setLayoutColumn(int column); - + /** * get layout sizes property, (i.e. "25%,75%") * * @return sizes layout property - **/ + */ public String getLayoutSizes(); - + /** * set the layout sizes * * @param sizes */ public void setLayoutSizes(String sizes); - + /** * get layout x coordinate property - * + * * @return the x coordinate value - **/ + */ public float getLayoutX(); /** * set the layout x coordinate property - * - * @param x the coordinate value + * + * @param x + * the coordinate value */ public void setLayoutX(float x); /** * get layout y coordinate property - * + * * @return the y coordinate value - **/ + */ public float getLayoutY(); /** * set the layout y coordinate property - * - * @param y the coordinate value + * + * @param y + * the coordinate value */ public void setLayoutY(float y); /** * get layout z coordinate property - * + * * @return the z coordinate value - **/ + */ public float getLayoutZ(); /** * set the layout z coordinate property - * - * @param z the coordinate value + * + * @param z + * the coordinate value */ public void setLayoutZ(float z); /** * get layout width property - * + * * @return the width value - **/ + */ public float getLayoutWidth(); /** * set the layout width property - * - * @param width the value + * + * @param width + * the value */ public void setLayoutWidth(float width); /** * get layout height property - * + * * @return the height value - **/ + */ public float getLayoutHeight(); /** * set the layout height property - * - * @param height the value + * + * @param height + * the value */ public void setLayoutHeight(float height); /** * Test if this fragment is actually a reference to an external fragment. - * + * * @return true is this element is a reference */ public boolean isReference(); /** - * Get collection of fragment preference objects used - * to initialize user preferences + * Get collection of fragment preference objects used to initialize user + * preferences * * @return list of FragmentPreference objects */ - public List getPreferences(); + public List getPreferences(); /** * Set collection of fragment preference objects * - * @param preferences list of FragmentPreference objects + * @param preferences + * list of FragmentPreference objects */ - public void setPreferences(List preferences); + public void setPreferences(List preferences); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Link.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Link.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Link.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,40 +16,41 @@ */ package org.apache.jetspeed.om.page; - - /** * <p> * Link * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: Link.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface Link extends Document { + String DOCUMENT_TYPE = ".link"; - + /** * Returns the name of the skin associated to this link */ String getSkin(); /** - * Defines the skin for this link. This skin should be - * known by the portal. - * - * @param skinName the name of the new skin applied to this link + * Defines the skin for this link. This skin should be known by the portal. + * + * @param skinName + * the name of the new skin applied to this link */ void setSkin(String skinName); /** - * @param url The url to set. + * @param url + * The url to set. */ - void setUrl( String url ); + void setUrl(String url); /** * @return Returns the target. @@ -57,7 +58,8 @@ String getTarget(); /** - * @param target The target to set. + * @param target + * The target to set. */ - void setTarget( String target ); + void setTarget(String target); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Page.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Page.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Page.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,147 +25,153 @@ import org.apache.jetspeed.om.folder.MenuSeparatorDefinition; /** - * This interface represents a complete page document used by Jetspeed - * to layout a user-customizable portal page. - * + * This interface represents a complete page document used by Jetspeed to layout + * a user-customizable portal page. + * * @version $Id: Page.java 516448 2007-03-09 16:25:47Z ate $ */ public interface Page extends Document, java.io.Serializable { + String DOCUMENT_TYPE = ".psml"; - + /** - * Returns the name of the default skin that applies to this - * page. - * + * Returns the name of the default skin that applies to this page. + * * @return the page default skin name */ String getSkin(); /** * Modifies the skin for this page. - * - * @param skinName the name of the new skin for the page + * + * @param skinName + * the name of the new skin for the page */ void setSkin(String skinName); /** - * Returns the name of the default decorator as set here or - * in parent folders that applies in this page to fragments - * of the specified type. - * - * @param fragmentType the type of fragment considered + * Returns the name of the default decorator as set here or in parent + * folders that applies in this page to fragments of the specified type. + * + * @param fragmentType + * the type of fragment considered * @return the decorator name for the selected type */ String getEffectiveDefaultDecorator(String fragmentType); /** - * Returns the name of the default decorator that applies in this page - * to fragments of the specified type - * - * @param fragmentType the type of fragment considered + * Returns the name of the default decorator that applies in this page to + * fragments of the specified type + * + * @param fragmentType + * the type of fragment considered * @return the decorator name for the selected type */ String getDefaultDecorator(String fragmentType); /** * Modifies the default decorator for the specified fragment type. - * - * @param decoratorName the name of the new decorator for the type - * @param fragmentType the type of fragment considered + * + * @param decoratorName + * the name of the new decorator for the type + * @param fragmentType + * the type of fragment considered */ void setDefaultDecorator(String decoratorName, String fragmentType); /** - * Retrieves the top level fragment of this page. This Fragment should - * never be null. - * + * Retrieves the top level fragment of this page. This Fragment should never + * be null. + * * @return the base Fragment object for this page. */ Fragment getRootFragment(); /** - * Sets the top level fragment of this page. This Fragment should - * never be null. - * + * Sets the top level fragment of this page. This Fragment should never be + * null. + * * @return the base Fragment object for this page. - */ + */ void setRootFragment(Fragment fragment); /** - * Retrieves the fragment contained within this page, with the - * specified Id. - * - * @param id the fragment id to look for + * Retrieves the fragment contained within this page, with the specified Id. + * + * @param id + * the fragment id to look for * @return the found Fragment object or null if not found */ Fragment getFragmentById(String id); /** - * Removes the fragment contained within this page, with the - * specified Id. - * - * @param id the fragment id to remove + * Removes the fragment contained within this page, with the specified Id. + * + * @param id + * the fragment id to remove * @return the removed Fragment object or null if not found */ Fragment removeFragmentById(String id); /** - * Retrieves the fragments contained within this page, with the - * specified name. - * - * @param name the fragment name to look for + * Retrieves the fragments contained within this page, with the specified + * name. + * + * @param name + * the fragment name to look for * @return the list of found Fragment objects or null if not found */ List getFragmentsByName(String name); /** * getMenuDefinitions - get list of menu definitions - * + * * @return definition list */ List getMenuDefinitions(); /** * newMenuDefinition - creates a new empty menu definition - * + * * @return a newly created MenuDefinition object for use in Page */ MenuDefinition newMenuDefinition(); /** * newMenuExcludeDefinition - creates a new empty menu exclude definition - * + * * @return a newly created MenuExcludeDefinition object for use in Page */ MenuExcludeDefinition newMenuExcludeDefinition(); /** * newMenuIncludeDefinition - creates a new empty menu include definition - * + * * @return a newly created MenuIncludeDefinition object for use in Page */ MenuIncludeDefinition newMenuIncludeDefinition(); /** * newMenuOptionsDefinition - creates a new empty menu options definition - * + * * @return a newly created MenuOptionsDefinition object for use in Page */ MenuOptionsDefinition newMenuOptionsDefinition(); /** - * newMenuSeparatorDefinition - creates a new empty menu separator definition - * + * newMenuSeparatorDefinition - creates a new empty menu separator + * definition + * * @return a newly created MenuSeparatorDefinition object for use in Page */ MenuSeparatorDefinition newMenuSeparatorDefinition(); /** * setMenuDefinitions - set list of menu definitions - * - * @param definitions definition list + * + * @param definitions + * definition list */ - void setMenuDefinitions(List definitions); + void setMenuDefinitions(List definitions); } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/PageSecurity.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/PageSecurity.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/PageSecurity.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,31 +24,34 @@ * </p> * <p> * Used to define named collections of SecurityConstraint objects. - * + * * </p> + * * @author <a href="mailto:rwatler ¡÷ finali.com">Randy Watler</a> * @version $Id: PageSecurity.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface PageSecurity extends Document -{ +{ + String DOCUMENT_TYPE = "page.security"; - + /** * <p> * getSecurityConstraintsDefs * </p> - * + * * @return security constraints definitions of type SecurityConstraintsDef */ List getSecurityConstraintsDefs(); - + /** * <p> * newSecurityConstraintsDef * </p> - * - * @return a newly created SecurityConstraintsDef object for use in PageSecurity + * + * @return a newly created SecurityConstraintsDef object for use in + * PageSecurity */ SecurityConstraintsDef newSecurityConstraintsDef(); @@ -56,8 +59,9 @@ * <p> * setSecurityConstraintsDefs * </p> - * - * @param defintions security constraints definitions + * + * @param defintions + * security constraints definitions */ void setSecurityConstraintsDefs(List definitions); @@ -65,8 +69,9 @@ * <p> * getSecurityConstraintsDef * </p> - * - * @param name of security constraints definition to return + * + * @param name + * of security constraints definition to return * @return security constraints definition */ SecurityConstraintsDef getSecurityConstraintsDef(String name); @@ -75,17 +80,18 @@ * <p> * getGlobalSecurityConstraintsRefs * </p> - * + * * @return global security constraints references of element type String */ List getGlobalSecurityConstraintsRefs(); - + /** * <p> * setGlobalSecurityConstraintsRefs * </p> - * - * @param constraintsRefs global security constraints references + * + * @param constraintsRefs + * global security constraints references */ void setGlobalSecurityConstraintsRefs(List constraintsRefs); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Reference.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Reference.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/Reference.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,7 +19,7 @@ /** * Interface for fragment reference objects - * + * * @version $Id: Reference.java 516448 2007-03-09 16:25:47Z ate $ */ public interface Reference Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/SecurityConstraintsDef.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/SecurityConstraintsDef.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/page/SecurityConstraintsDef.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,29 +24,32 @@ * </p> * <p> * Used to specify a named collection of SecurityConstraint objects. - * + * * </p> + * * @author <a href="mailto:rwatler ¡÷ finali.com">Randy Watler</a> * @version $Id: SecurityConstraintsDef.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface SecurityConstraintsDef -{ +{ + /** * <p> * getName * </p> - * + * * @return constraints name used by references */ String getName(); - + /** * <p> * setName * </p> - * - * @param name constraints name used by references + * + * @param name + * constraints name used by references */ void setName(String name); @@ -54,17 +57,18 @@ * <p> * getSecurityConstraints * </p> - * + * * @return security constraints list for resource */ List getSecurityConstraints(); - + /** * <p> * setSecurityConstraints * </p> - * - * @param constraints security constraints for resource + * + * @param constraints + * security constraints for resource */ void setSecurityConstraints(List constraints); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/preference/FragmentPreference.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/preference/FragmentPreference.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/om/preference/FragmentPreference.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,52 +19,56 @@ import java.util.List; /** - * This interface represents a fragment preference used to populate - * portlet user preferences on initial access. - * + * This interface represents a fragment preference used to populate portlet user + * preferences on initial access. + * * @version $Id$ */ public interface FragmentPreference { + /** * getName - * + * * @return preference name */ String getName(); - + /** * setName - * - * @param name preference name + * + * @param name + * preference name */ void setName(String name); - + /** * isReadOnly - * + * * @return read only preference flag */ boolean isReadOnly(); - + /** * setReadOnly - * - * @param readOnly read only preference flag + * + * @param readOnly + * read only preference flag */ void setReadOnly(boolean readOnly); - + /** * getValueList - * + * * @return list of String preference values */ List getValueList(); - + /** * setValueList - * - * @param values list of String preference values + * + * @param values + * list of String preference values */ void setValueList(List values); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/FolderNotRemovedException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/FolderNotRemovedException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/FolderNotRemovedException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,7 +25,7 @@ * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> * @version $Id: FolderNotRemovedException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class FolderNotRemovedException extends NodeException { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/FolderNotUpdatedException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/FolderNotUpdatedException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/FolderNotUpdatedException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,7 +25,7 @@ * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> * @version $Id: FolderNotUpdatedException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class FolderNotUpdatedException extends NodeException { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/LinkNotRemovedException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/LinkNotRemovedException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/LinkNotRemovedException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,7 +25,7 @@ * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> * @version $Id: LinkNotRemovedException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class LinkNotRemovedException extends NodeException { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/LinkNotUpdatedException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/LinkNotUpdatedException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/LinkNotUpdatedException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,7 +25,7 @@ * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> * @version $Id: LinkNotUpdatedException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class LinkNotUpdatedException extends NodeException { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -44,23 +44,23 @@ import org.apache.jetspeed.page.document.NodeSet; import org.apache.jetspeed.page.document.UnsupportedDocumentTypeException; - /** - * This service is responsible for loading and saving Pages into - * the selected persistent store. - * + * This service is responsible for loading and saving Pages into the selected + * persistent store. + * * @version $Id: PageManager.java 516448 2007-03-09 16:25:47Z ate $ */ -public interface PageManager +public interface PageManager { + /** The name of the service */ public String SERVICE_NAME = "PageManager"; - + /** * <p> * getConstraintsEnabled * </p> - * + * * @return enabled indicator */ public boolean getConstraintsEnabled(); @@ -69,175 +69,189 @@ * <p> * getPermissionsEnabled * </p> - * + * * @return enabled indicator */ public boolean getPermissionsEnabled(); /** * Creates a new empty Page instance - * + * * @return a newly created Page object */ public Page newPage(String path); /** * Create a new empty Folder instance - * + * * @return a newly created Folder object */ public Folder newFolder(String path); /** * Creates a new empty Link instance - * + * * @return a newly created Link object */ public Link newLink(String path); /** * Creates a new empty PageSecurity instance - * + * * @return a newly created PageSecurity object */ public PageSecurity newPageSecurity(); /** * Creates a new empty Layout Fragment instance - * + * * @return a newly created Fragment object */ public Fragment newFragment(); /** * Creates a new empty Portlet Fragment instance - * + * * @return a newly created Fragment object - */ + */ public Fragment newPortletFragment(); - + /** * newFolderMenuDefinition - creates a new empty menu definition - * + * * @return a newly created MenuDefinition object to be used in Folder */ public MenuDefinition newFolderMenuDefinition(); /** - * newFolderMenuExcludeDefinition - creates a new empty menu exclude definition - * + * newFolderMenuExcludeDefinition - creates a new empty menu exclude + * definition + * * @return a newly created MenuExcludeDefinition object to be used in Folder */ public MenuExcludeDefinition newFolderMenuExcludeDefinition(); /** - * newFolderMenuIncludeDefinition - creates a new empty menu include definition - * + * newFolderMenuIncludeDefinition - creates a new empty menu include + * definition + * * @return a newly created MenuIncludeDefinition object to be used in Folder */ public MenuIncludeDefinition newFolderMenuIncludeDefinition(); /** - * newFolderMenuOptionsDefinition - creates a new empty menu options definition - * + * newFolderMenuOptionsDefinition - creates a new empty menu options + * definition + * * @return a newly created MenuOptionsDefinition object to be used in Folder */ public MenuOptionsDefinition newFolderMenuOptionsDefinition(); /** - * newFolderMenuSeparatorDefinition - creates a new empty menu separator definition - * - * @return a newly created MenuSeparatorDefinition object to be used in Folder + * newFolderMenuSeparatorDefinition - creates a new empty menu separator + * definition + * + * @return a newly created MenuSeparatorDefinition object to be used in + * Folder */ public MenuSeparatorDefinition newFolderMenuSeparatorDefinition(); /** * newPageMenuDefinition - creates a new empty menu definition - * + * * @return a newly created MenuDefinition object to be used in Page */ public MenuDefinition newPageMenuDefinition(); /** - * newPageMenuExcludeDefinition - creates a new empty menu exclude definition - * + * newPageMenuExcludeDefinition - creates a new empty menu exclude + * definition + * * @return a newly created MenuExcludeDefinition object to be used in Page */ public MenuExcludeDefinition newPageMenuExcludeDefinition(); /** - * newPageMenuIncludeDefinition - creates a new empty menu include definition - * + * newPageMenuIncludeDefinition - creates a new empty menu include + * definition + * * @return a newly created MenuIncludeDefinition object to be used in Page */ public MenuIncludeDefinition newPageMenuIncludeDefinition(); /** - * newPageMenuOptionsDefinition - creates a new empty menu options definition - * + * newPageMenuOptionsDefinition - creates a new empty menu options + * definition + * * @return a newly created MenuOptionsDefinition object to be used in Page */ public MenuOptionsDefinition newPageMenuOptionsDefinition(); /** - * newPageMenuSeparatorDefinition - creates a new empty menu separator definition - * + * newPageMenuSeparatorDefinition - creates a new empty menu separator + * definition + * * @return a newly created MenuSeparatorDefinition object to be used in Page */ public MenuSeparatorDefinition newPageMenuSeparatorDefinition(); /** - * newSecurityConstraints - creates a new empty security constraints definition - * + * newSecurityConstraints - creates a new empty security constraints + * definition + * * @return a newly created SecurityConstraints object */ public SecurityConstraints newSecurityConstraints(); /** - * newFolderSecurityConstraint - creates a new security constraint definition - * + * newFolderSecurityConstraint - creates a new security constraint + * definition + * * @return a newly created SecurityConstraint object to be used in Folder */ public SecurityConstraint newFolderSecurityConstraint(); /** * newPageSecurityConstraint - creates a new security constraint definition - * + * * @return a newly created SecurityConstraint object to be used in Page */ public SecurityConstraint newPageSecurityConstraint(); /** - * newFragmentSecurityConstraint - creates a new security constraint definition - * + * newFragmentSecurityConstraint - creates a new security constraint + * definition + * * @return a newly created SecurityConstraint object to be used in Fragment */ public SecurityConstraint newFragmentSecurityConstraint(); /** * newLinkSecurityConstraint - creates a new security constraint definition - * + * * @return a newly created SecurityConstraint object to be used in Link */ public SecurityConstraint newLinkSecurityConstraint(); /** - * newPageSecuritySecurityConstraint - creates a new security constraint definition - * - * @return a newly created SecurityConstraint object to be used in PageSecurity + * newPageSecuritySecurityConstraint - creates a new security constraint + * definition + * + * @return a newly created SecurityConstraint object to be used in + * PageSecurity */ public SecurityConstraint newPageSecuritySecurityConstraint(); /** * newSecurityConstraintsDef - creates a new security constraints definition - * + * * @return a newly created SecurityConstraintsDef object */ public SecurityConstraintsDef newSecurityConstraintsDef(); /** * newFragmentPreference - creates a new fragment preference - * + * * @return a newly created FragmentPreference */ public FragmentPreference newFragmentPreference(); @@ -246,86 +260,98 @@ * <p> * getPage * </p> - * + * * Returns a Page based on its path - * + * * @param path - * @throws PageNotFoundException if the page cannot be found + * @throws PageNotFoundException + * if the page cannot be found * @throws NodeException */ - public Page getPage(String path) throws PageNotFoundException, NodeException; - + public Page getPage(String path) throws PageNotFoundException, + NodeException; + /** * <p> * ContentPage * </p> - * - * Returns a PSML document suitable for use in content - * rendering, for the given key - * + * + * Returns a PSML document suitable for use in content rendering, for the + * given key + * * @see ContentPage * @see Fragment - * @param locator The locator descriptor of the document to be retrieved. - * @throws PageNotFoundException if the page cannot be found + * @param locator + * The locator descriptor of the document to be retrieved. + * @throws PageNotFoundException + * if the page cannot be found * @throws NodeException */ - public ContentPage getContentPage(String path) throws PageNotFoundException, NodeException; - + public ContentPage getContentPage(String path) + throws PageNotFoundException, NodeException; + /** * <p> * getLink * </p> - * + * * Returns a Link document for the given path - * - * @param name The path of the document to be retrieved. - * @throws PageNotFoundException if the page cannot be found + * + * @param name + * The path of the document to be retrieved. + * @throws PageNotFoundException + * if the page cannot be found * @throws NodeException */ - public Link getLink(String name) throws DocumentNotFoundException, UnsupportedDocumentTypeException, NodeException; + public Link getLink(String name) throws DocumentNotFoundException, + UnsupportedDocumentTypeException, NodeException; /** * <p> * getPageSecurity * </p> - * + * * Returns the PageSecurity document - * - * @throws DocumentNotFoundException if the document cannot be found + * + * @throws DocumentNotFoundException + * if the document cannot be found * @throws UnsupportedDocumentTypeException * @throws NodeException */ - public PageSecurity getPageSecurity() throws DocumentNotFoundException, UnsupportedDocumentTypeException, NodeException; - + public PageSecurity getPageSecurity() throws DocumentNotFoundException, + UnsupportedDocumentTypeException, NodeException; + /** * <p> * getFolder * </p> - * + * * Locates a folder for the given path. - * + * * @param folderPath - * @return <code>Folder</code> object represented by the <code>folderPath</code> + * @return <code>Folder</code> object represented by the + * <code>folderPath</code> * @throws FolderNotFoundException * @throws NodeException * @throws InvalidFolderException */ - public Folder getFolder(String folderPath) throws FolderNotFoundException, InvalidFolderException, NodeException; + public Folder getFolder(String folderPath) throws FolderNotFoundException, + InvalidFolderException, NodeException; /** * <p> * getFolders * </p> - * - * Locates folders within a specified parent folder. - * Returned documents are filtered according to security - * constraints and/or permissions. - * + * + * Locates folders within a specified parent folder. Returned documents are + * filtered according to security constraints and/or permissions. + * * @see org.apache.jetspeed.om.folder.Folder#getFolders(org.apache.jetspeed.om.folder.Folder) - * - * @param folder The parent folder. - * @return A <code>NodeSet</code> containing all sub-folders - * directly under this folder. + * + * @param folder + * The parent folder. + * @return A <code>NodeSet</code> containing all sub-folders directly + * under this folder. * @throws DocumentException */ public NodeSet getFolders(Folder folder) throws DocumentException; @@ -334,272 +360,323 @@ * <p> * getFolder * </p> - * - * Locates folders within a specified parent folder. - * Returned documents are filtered according to security - * constraints and/or permissions. - * + * + * Locates folders within a specified parent folder. Returned documents are + * filtered according to security constraints and/or permissions. + * * @see org.apache.jetspeed.om.folder.Folder#getFolder(org.apache.jetspeed.om.folder.Folder,java.lang.String) - * - * @param folder The parent folder. - * @param name The name of folder to retrieve. + * + * @param folder + * The parent folder. + * @param name + * The name of folder to retrieve. * @return A Folder referenced by this folder. * @throws FolderNotFoundException * @throws DocumentException */ - public Folder getFolder(Folder folder, String name) throws FolderNotFoundException, DocumentException; + public Folder getFolder(Folder folder, String name) + throws FolderNotFoundException, DocumentException; /** * <p> * getPages * </p> - * - * Locates documents within a specified parent folder. - * Returned documents are filtered according to security - * constraints and/or permissions. - * + * + * Locates documents within a specified parent folder. Returned documents + * are filtered according to security constraints and/or permissions. + * * @see org.apache.jetspeed.om.folder.Folder#getPages(org.apache.jetspeed.om.folder.Folder) - * - * @param folder The parent folder. - * @return A <code>NodeSet</code> of all the Pages referenced - * by this Folder. + * + * @param folder + * The parent folder. + * @return A <code>NodeSet</code> of all the Pages referenced by this + * Folder. * @throws NodeException */ public NodeSet getPages(Folder folder) throws NodeException; - + /** * <p> * getPage * </p> - * - * Locates documents within a specified parent folder. - * Returned documents are filtered according to security - * constraints and/or permissions. - * + * + * Locates documents within a specified parent folder. Returned documents + * are filtered according to security constraints and/or permissions. + * * @see org.apache.jetspeed.om.folder.Folder#getPage(org.apache.jetspeed.om.folder.Folder,java.lang.String) - * - * @param folder The parent folder. - * @param name The name of page to retrieve. + * + * @param folder + * The parent folder. + * @param name + * The name of page to retrieve. * @return A Page referenced by this folder. - * @throws PageNotFoundException if the Page requested could not be found. + * @throws PageNotFoundException + * if the Page requested could not be found. * @throws NodeException */ - public Page getPage(Folder folder, String name) throws PageNotFoundException, NodeException; - + public Page getPage(Folder folder, String name) + throws PageNotFoundException, NodeException; + /** * <p> * getLinks * </p> - * + * * @see org.apache.jetspeed.om.folder.Folder#getLinks(org.apache.jetspeed.om.folder.Folder) - * - * Locates documents within a specified parent folder. - * Returned documents are filtered according to security - * constraints and/or permissions. - * - * @param folder The parent folder. + * + * Locates documents within a specified parent folder. Returned documents + * are filtered according to security constraints and/or permissions. + * + * @param folder + * The parent folder. * @return NodeSet of all the Links referenced by this Folder. * @throws NodeException - */ + */ public NodeSet getLinks(Folder folder) throws NodeException; - + /** * <p> * getLink * </p> - * - * Locates documents within a specified parent folder. - * Returned documents are filtered according to security - * constraints and/or permissions. - * + * + * Locates documents within a specified parent folder. Returned documents + * are filtered according to security constraints and/or permissions. + * * @see org.apache.jetspeed.om.folder.Folder#getLink(org.apache.jetspeed.om.folder.Folder,java.lang.String) - * - * @param folder The parent folder. - * @param name The name of page to retrieve. + * + * @param folder + * The parent folder. + * @param name + * The name of page to retrieve. * @return A Link referenced by this folder. - * @throws DocumentNotFoundException if the document requested could not be found. + * @throws DocumentNotFoundException + * if the document requested could not be found. * @throws NodeException - */ - public Link getLink(Folder folder, String name) throws DocumentNotFoundException, NodeException; - + */ + public Link getLink(Folder folder, String name) + throws DocumentNotFoundException, NodeException; + /** * <p> * getPageSecurity * </p> - * - * Locates documents within a specified parent folder. - * Returned documents are filtered according to security - * constraints and/or permissions. - * + * + * Locates documents within a specified parent folder. Returned documents + * are filtered according to security constraints and/or permissions. + * * @see org.apache.jetspeed.om.folder.Folder#getPageSecurity(org.apache.jetspeed.om.folder.Folder) - * - * @param folder The parent folder. + * + * @param folder + * The parent folder. * @return A PageSecurity referenced by this folder. - * @throws DocumentNotFoundException if the document requested could not be found. + * @throws DocumentNotFoundException + * if the document requested could not be found. * @throws NodeException - */ - public PageSecurity getPageSecurity(Folder folder) throws DocumentNotFoundException, NodeException; + */ + public PageSecurity getPageSecurity(Folder folder) + throws DocumentNotFoundException, NodeException; /** * <p> * getAll * </p> - * - * Locates folders and documents within a specified parent folder. - * Returned folders and documents are filtered according to - * security constraints and/or permissions. - * + * + * Locates folders and documents within a specified parent folder. Returned + * folders and documents are filtered according to security constraints + * and/or permissions. + * * @see org.apache.jetspeed.om.folder.Folder#getAll(org.apache.jetspeed.om.folder.Folder) - * - * @param folder The parent folder. - * @return A <code>NodeSet</code> containing all sub-folders - * and documents directly under this folder. + * + * @param folder + * The parent folder. + * @return A <code>NodeSet</code> containing all sub-folders and documents + * directly under this folder. * @throws DocumentException */ public NodeSet getAll(Folder folder) throws DocumentException; - /** Update a page in persistent storage - * - * @param page The page to be updated. + /** + * Update a page in persistent storage + * + * @param page + * The page to be updated. */ - public void updatePage(Page page) throws NodeException, PageNotUpdatedException; + public void updatePage(Page page) throws NodeException, + PageNotUpdatedException; - /** Remove a document. - * - * @param page The page to be removed. + /** + * Remove a document. + * + * @param page + * The page to be removed. */ - public void removePage(Page page) throws NodeException, PageNotRemovedException; + public void removePage(Page page) throws NodeException, + PageNotRemovedException; - /** Update a folder and all child folders - * and documents in persistent storage - * - * @param folder The folder to be updated. + /** + * Update a folder and all child folders and documents in persistent storage + * + * @param folder + * The folder to be updated. */ - public void updateFolder(Folder folder) throws NodeException, FolderNotUpdatedException; + public void updateFolder(Folder folder) throws NodeException, + FolderNotUpdatedException; - /** Update a folder in persistent storage - * - * @param folder The folder to be updated. - * @param deep Flag to control recursive deep updates. + /** + * Update a folder in persistent storage + * + * @param folder + * The folder to be updated. + * @param deep + * Flag to control recursive deep updates. */ - public void updateFolder(Folder folder, boolean deep) throws NodeException, FolderNotUpdatedException; + public void updateFolder(Folder folder, boolean deep) throws NodeException, + FolderNotUpdatedException; - /** Remove a folder. - * - * @param page The folder to be removed. + /** + * Remove a folder. + * + * @param page + * The folder to be removed. */ - public void removeFolder(Folder folder) throws NodeException, FolderNotRemovedException; + public void removeFolder(Folder folder) throws NodeException, + FolderNotRemovedException; - /** Update a link in persistent storage - * - * @param link The link to be updated. + /** + * Update a link in persistent storage + * + * @param link + * The link to be updated. */ - public void updateLink(Link link) throws NodeException, LinkNotUpdatedException; + public void updateLink(Link link) throws NodeException, + LinkNotUpdatedException; - /** Remove a link. - * - * @param link The link to be removed. + /** + * Remove a link. + * + * @param link + * The link to be removed. */ - public void removeLink(Link link) throws NodeException, LinkNotRemovedException; + public void removeLink(Link link) throws NodeException, + LinkNotRemovedException; - /** Update a page security document in persistent storage - * - * @param pageSecurity The document to be updated. + /** + * Update a page security document in persistent storage + * + * @param pageSecurity + * The document to be updated. */ - public void updatePageSecurity(PageSecurity pageSecurity) throws NodeException, FailedToUpdateDocumentException; + public void updatePageSecurity(PageSecurity pageSecurity) + throws NodeException, FailedToUpdateDocumentException; - /** Remove a page security document. - * - * @param pageSecurity The document to be removed. + /** + * Remove a page security document. + * + * @param pageSecurity + * The document to be removed. */ - public void removePageSecurity(PageSecurity pageSecurity) throws NodeException, FailedToDeleteDocumentException; + public void removePageSecurity(PageSecurity pageSecurity) + throws NodeException, FailedToDeleteDocumentException; /** * addListener - add page manager event listener - * - * @param listener page manager event listener + * + * @param listener + * page manager event listener */ public void addListener(PageManagerEventListener listener); /** * removeListener - remove page manager event listener - * - * @param listener page manager event listener + * + * @param listener + * page manager event listener */ public void removeListener(PageManagerEventListener listener); - + /** - * reset - force subsequent refresh from persistent store + * reset - force subsequent refresh from persistent store */ public void reset(); - /** - * Copy the source page creating and returning a new copy of the page - * with the same portlet and fragment collection as the source - * All fragments are created with new fragment ids + /** + * Copy the source page creating and returning a new copy of the page with + * the same portlet and fragment collection as the source All fragments are + * created with new fragment ids * - * @param source The source Page object to be copied - * @param path a PSML normalized path to the new page to be created + * @param source + * The source Page object to be copied + * @param path + * a PSML normalized path to the new page to be created * @return a new Page object copied from the source, with new fragment ids */ - public Page copyPage(Page source, String path) - throws NodeException; + public Page copyPage(Page source, String path) throws NodeException; - /** - * Copy the source link creating and returning a new copy of the link + /** + * Copy the source link creating and returning a new copy of the link * - * @param source The source Link object to be copied - * @param path a PSML normalized path to the new link to be created + * @param source + * The source Link object to be copied + * @param path + * a PSML normalized path to the new link to be created * @return a new Link object copied from the source */ - public Link copyLink(Link source, String path) - throws NodeException; + public Link copyLink(Link source, String path) throws NodeException; - /** - * Copy the source folder creating and returning a new copy of the folder - * with the same content as the source - * All subobjects are created with new ids + /** + * Copy the source folder creating and returning a new copy of the folder + * with the same content as the source All subobjects are created with new + * ids * - * @param source The source Folder object to be copied - * @param path a PSML normalized path to the new folder to be created - * @return a new Folder object copied from the source, with new subobject ids + * @param source + * The source Folder object to be copied + * @param path + * a PSML normalized path to the new folder to be created + * @return a new Folder object copied from the source, with new subobject + * ids */ - public Folder copyFolder(Folder source, String path) - throws NodeException; + public Folder copyFolder(Folder source, String path) throws NodeException; - /** - * Copy the source fragment creating and returning a new copy of the fragment - * with the parameter collection as the source - * The fragment is created with a new fragment id + /** + * Copy the source fragment creating and returning a new copy of the + * fragment with the parameter collection as the source The fragment is + * created with a new fragment id * - * @param source The source Fragment object to be copied - * @param the new fragment name, can be the same as source fragment name + * @param source + * The source Fragment object to be copied + * @param the + * new fragment name, can be the same as source fragment name * @return a new Fragment object copied from the source */ - public Fragment copyFragment(Fragment source, String name) - throws NodeException; + public Fragment copyFragment(Fragment source, String name) + throws NodeException; /** - * Copy the source page security (both global constraints and constraint references) - * creating and returning a new copy of the page security definition. - * - * @param source The source PageSecurity definitions + * Copy the source page security (both global constraints and constraint + * references) creating and returning a new copy of the page security + * definition. + * + * @param source + * The source PageSecurity definitions * @return the new page security object * @throws NodeException */ - public PageSecurity copyPageSecurity(PageSecurity source) - throws NodeException; - + public PageSecurity copyPageSecurity(PageSecurity source) + throws NodeException; + /** - * Deep copy a folder. Copies a folder and all subcontents including - * other folders, subpages, links, menus, security, fragments. - * - * @param source source folder - * @param dest destination folder - * @param owner set owner of the new folder(s), or null for no owner + * Deep copy a folder. Copies a folder and all subcontents including other + * folders, subpages, links, menus, security, fragments. + * + * @param source + * source folder + * @param dest + * destination folder + * @param owner + * set owner of the new folder(s), or null for no owner */ - public void deepCopyFolder(Folder srcFolder, String destinationPath, String owner) - throws NodeException; + public void deepCopyFolder(Folder srcFolder, String destinationPath, + String owner) throws NodeException; /** * Retrieve a page for the given user name and page name @@ -610,9 +687,9 @@ * @throws PageNotFoundException * @throws NodeException */ - public Page getUserPage(String userName, String pageName) - throws PageNotFoundException, NodeException; - + public Page getUserPage(String userName, String pageName) + throws PageNotFoundException, NodeException; + /** * Retrieve a user's folder * @@ -622,9 +699,10 @@ * @throws InvalidFolderException * @throws NodeException */ - public Folder getUserFolder(String userName) - throws FolderNotFoundException, InvalidFolderException, NodeException; - + public Folder getUserFolder(String userName) + throws FolderNotFoundException, InvalidFolderException, + NodeException; + /** * Check if a folder exists for the given folder name * @@ -632,7 +710,7 @@ * @return */ public boolean folderExists(String folderName); - + /** * Check if a page exists for the given page name * @@ -640,7 +718,7 @@ * @return */ public boolean pageExists(String pageName); - + /** * Check if a link exists for the given link name * @@ -648,7 +726,7 @@ * @return */ public boolean linkExists(String linkName); - + /** * Check if the root folder exists for a given user * @@ -656,7 +734,7 @@ * @return */ public boolean userFolderExists(String userName); - + /** * Check if a page exists for the given user * @@ -667,31 +745,34 @@ public boolean userPageExists(String userName, String pageName); /** - * Creates a user's home page from the roles of the current user. - * The use case: when a portal is setup to use shared pages, but then - * the user attempts to customize. At this point, we create the new page(s) for the user. + * Creates a user's home page from the roles of the current user. The use + * case: when a portal is setup to use shared pages, but then the user + * attempts to customize. At this point, we create the new page(s) for the + * user. * - * @param subject The full user Java Security subject. + * @param subject + * The full user Java Security subject. */ public void createUserHomePagesFromRoles(Subject subject) - throws NodeException; - + throws NodeException; + /** * * @param pages * @return * @throws NodeException */ - public int addPages(Page[] pages) - throws NodeException; - + public int addPages(Page[] pages) throws NodeException; + /** * For a given security constraint definition name, and the given action(s), * make a constraint check for the current user subject * - * @param securityConstraintName the name of the security constraint definition - * @param actions one or more portlet actions (view,edit,help,..) + * @param securityConstraintName + * the name of the security constraint definition + * @param actions + * one or more portlet actions (view,edit,help,..) * @return */ - public boolean checkConstraint(String securityConstraintName, String actions); + public boolean checkConstraint(String securityConstraintName, String actions); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageManagerEventListener.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageManagerEventListener.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageManagerEventListener.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,38 +19,39 @@ import org.apache.jetspeed.page.document.Node; /** - * This interface describes the page manager event listener - * that is notified when a managed node is updated or removed + * This interface describes the page manager event listener that is notified + * when a managed node is updated or removed * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> * @version $Id: PageManagerEventListener.java 516448 2007-03-09 16:25:47Z ate $ */ public interface PageManagerEventListener { + /** - * newNode - invoked when the definition of a node is - * created by the page manager or when the - * node creation is otherwise detected - * - * @param node new managed node if known + * newNode - invoked when the definition of a node is created by the page + * manager or when the node creation is otherwise detected + * + * @param node + * new managed node if known */ void newNode(Node node); /** - * updatedNode - invoked when the definition of a node is - * updated by the page manager or when the - * node modification is otherwise detected - * - * @param node updated managed node if known + * updatedNode - invoked when the definition of a node is updated by the + * page manager or when the node modification is otherwise detected + * + * @param node + * updated managed node if known */ void updatedNode(Node node); /** - * removedNode - invoked when the definition of a node is - * removed by the page manager or when the - * node removal is otherwise detected - * - * @param node removed managed node if known + * removedNode - invoked when the definition of a node is removed by the + * page manager or when the node removal is otherwise detected + * + * @param node + * removed managed node if known */ void removedNode(Node node); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageNotFoundException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageNotFoundException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageNotFoundException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,7 +18,6 @@ import org.apache.jetspeed.page.document.DocumentNotFoundException; - /** * <p> * PageNotFoundException @@ -26,9 +25,10 @@ * <p> * Thrown when a requested page cannot be found. * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: PageNotFoundException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class PageNotFoundException extends DocumentNotFoundException { @@ -39,27 +39,30 @@ public PageNotFoundException() { super(); - + } + /** * @param message */ - public PageNotFoundException( String message ) + public PageNotFoundException(String message) { super(message); } + /** * @param msg * @param nested */ - public PageNotFoundException( String msg, Throwable nested ) + public PageNotFoundException(String msg, Throwable nested) { super(msg, nested); } + /** * @param nested */ - public PageNotFoundException( Throwable nested ) + public PageNotFoundException(Throwable nested) { super(nested); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageNotRemovedException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageNotRemovedException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageNotRemovedException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,7 +25,7 @@ * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: PageNotRemovedException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class PageNotRemovedException extends NodeException { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageNotUpdatedException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageNotUpdatedException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/PageNotUpdatedException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,7 +25,7 @@ * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: PageNotUpdatedException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class PageNotUpdatedException extends NodeException { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,17 +16,17 @@ */ package org.apache.jetspeed.page.document; - /** * <p> * DocumentException * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: DocumentException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class DocumentException extends NodeException { @@ -43,7 +43,7 @@ /** * @param message */ - public DocumentException( String message ) + public DocumentException(String message) { super(message); // TODO Auto-generated constructor stub @@ -52,7 +52,7 @@ /** * @param nested */ - public DocumentException( Throwable nested ) + public DocumentException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -62,7 +62,7 @@ * @param msg * @param nested */ - public DocumentException( String msg, Throwable nested ) + public DocumentException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,22 +23,28 @@ * DocumentHandler * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: DocumentHandler.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface DocumentHandler { - Document getDocument(String name) throws DocumentNotFoundException, NodeException; - - Document getDocument(String name, boolean fromCahe) throws DocumentNotFoundException, NodeException; - - void updateDocument(Document document) throws FailedToUpdateDocumentException; - - void removeDocument(Document document) throws DocumentNotFoundException, FailedToDeleteDocumentException; - + + Document getDocument(String name) throws DocumentNotFoundException, + NodeException; + + Document getDocument(String name, boolean fromCahe) + throws DocumentNotFoundException, NodeException; + + void updateDocument(Document document) + throws FailedToUpdateDocumentException; + + void removeDocument(Document document) throws DocumentNotFoundException, + FailedToDeleteDocumentException; + String getType(); DocumentHandlerFactory getHandlerFactory(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentHandlerFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentHandlerFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentHandlerFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,54 +21,64 @@ * DocumentHandlerFactory * </p> * <p> - * Factory for generating <code>DocumentHandlers</code> for specific document types + * Factory for generating <code>DocumentHandlers</code> for specific document + * types * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: DocumentHandlerFactory.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface DocumentHandlerFactory { + /** * * <p> * getDocumentHandler - * </p> - * - * @param documentType document type to retreive a handler for. Examples: .psml, .link - * @return DocumentHanlder for the <code>documentType</code> indicated. Never returns <code>null.</code> - * @throws UnsupportedDocumentTypeException If no handler has been registered for the - * <code>documentType</code> argument. + * </p> + * + * @param documentType + * document type to retreive a handler for. Examples: .psml, + * .link + * @return DocumentHanlder for the <code>documentType</code> indicated. + * Never returns <code>null.</code> + * @throws UnsupportedDocumentTypeException + * If no handler has been registered for the + * <code>documentType</code> argument. */ - DocumentHandler getDocumentHandler(String documentType) throws UnsupportedDocumentTypeException; - + DocumentHandler getDocumentHandler(String documentType) + throws UnsupportedDocumentTypeException; + /** * * <p> * getDocumentHandlerForPath * </p> - * + * * @param documentPath * @return * @throws UnsupportedDocumentTypeException */ - DocumentHandler getDocumentHandlerForPath( String documentPath) throws UnsupportedDocumentTypeException; - + DocumentHandler getDocumentHandlerForPath(String documentPath) + throws UnsupportedDocumentTypeException; + /** * * <p> * addDocumentHandler * </p> - * + * * @param documentHandler */ - void registerDocumentHandler(DocumentHandler documentHandler) throws DocumentTypeAlreadyRegisteredException; - + void registerDocumentHandler(DocumentHandler documentHandler) + throws DocumentTypeAlreadyRegisteredException; + /** * <p> * getConstraintsEnabled * </p> - * + * * @return enabled indicator */ boolean getConstraintsEnabled(); @@ -77,8 +87,9 @@ * <p> * setConstraintsEnabled * </p> - * - * @param enabled indicator + * + * @param enabled + * indicator */ void setConstraintsEnabled(boolean enabled); @@ -86,7 +97,7 @@ * <p> * getPermissionsEnabled * </p> - * + * * @return enabled indicator */ boolean getPermissionsEnabled(); @@ -95,8 +106,9 @@ * <p> * setPermissionsEnabled * </p> - * - * @param enabled indicator + * + * @param enabled + * indicator */ void setPermissionsEnabled(boolean enabled); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentNotFoundException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentNotFoundException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentNotFoundException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,17 +16,17 @@ */ package org.apache.jetspeed.page.document; - /** * <p> * DocumentNotFound * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: DocumentNotFoundException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class DocumentNotFoundException extends NodeNotFoundException { @@ -43,7 +43,7 @@ /** * @param message */ - public DocumentNotFoundException( String message ) + public DocumentNotFoundException(String message) { super(message); // TODO Auto-generated constructor stub @@ -52,7 +52,7 @@ /** * @param nested */ - public DocumentNotFoundException( Throwable nested ) + public DocumentNotFoundException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -62,7 +62,7 @@ * @param msg * @param nested */ - public DocumentNotFoundException( String msg, Throwable nested ) + public DocumentNotFoundException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentTypeAlreadyRegisteredException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentTypeAlreadyRegisteredException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/DocumentTypeAlreadyRegisteredException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,11 +21,13 @@ * DocumentTypeAlreadyRegisteredException * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: DocumentTypeAlreadyRegisteredException.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: DocumentTypeAlreadyRegisteredException.java 516448 2007-03-09 + * 16:25:47Z ate $ + * */ public class DocumentTypeAlreadyRegisteredException extends DocumentException { @@ -42,7 +44,7 @@ /** * @param message */ - public DocumentTypeAlreadyRegisteredException( String message ) + public DocumentTypeAlreadyRegisteredException(String message) { super(message); // TODO Auto-generated constructor stub @@ -51,7 +53,7 @@ /** * @param nested */ - public DocumentTypeAlreadyRegisteredException( Throwable nested ) + public DocumentTypeAlreadyRegisteredException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -61,7 +63,7 @@ * @param msg * @param nested */ - public DocumentTypeAlreadyRegisteredException( String msg, Throwable nested ) + public DocumentTypeAlreadyRegisteredException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToDeleteDocumentException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToDeleteDocumentException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToDeleteDocumentException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,17 +16,18 @@ */ package org.apache.jetspeed.page.document; - /** * <p> * FailedToDeleteDocument * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: FailedToDeleteDocumentException.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: FailedToDeleteDocumentException.java 516448 2007-03-09 + * 16:25:47Z ate $ + * */ public class FailedToDeleteDocumentException extends DocumentException { @@ -43,7 +44,7 @@ /** * @param message */ - public FailedToDeleteDocumentException( String message ) + public FailedToDeleteDocumentException(String message) { super(message); // TODO Auto-generated constructor stub @@ -52,7 +53,7 @@ /** * @param nested */ - public FailedToDeleteDocumentException( Throwable nested ) + public FailedToDeleteDocumentException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -62,7 +63,7 @@ * @param msg * @param nested */ - public FailedToDeleteDocumentException( String msg, Throwable nested ) + public FailedToDeleteDocumentException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToDeleteFolderException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToDeleteFolderException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToDeleteFolderException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,17 +16,18 @@ */ package org.apache.jetspeed.page.document; - /** * <p> * FailedToDeleteFolderException * </p> * <p> - * + * * </p> + * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> - * @version $Id: FailedToDeleteFolderException.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: FailedToDeleteFolderException.java 516448 2007-03-09 16:25:47Z + * ate $ + * */ public class FailedToDeleteFolderException extends NodeException { @@ -42,7 +43,7 @@ /** * @param message */ - public FailedToDeleteFolderException( String message ) + public FailedToDeleteFolderException(String message) { super(message); } @@ -50,7 +51,7 @@ /** * @param nested */ - public FailedToDeleteFolderException( Throwable nested ) + public FailedToDeleteFolderException(Throwable nested) { super(nested); } @@ -59,7 +60,7 @@ * @param msg * @param nested */ - public FailedToDeleteFolderException( String msg, Throwable nested ) + public FailedToDeleteFolderException(String msg, Throwable nested) { super(msg, nested); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToUpdateDocumentException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToUpdateDocumentException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToUpdateDocumentException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,17 +16,18 @@ */ package org.apache.jetspeed.page.document; - /** * <p> * FailedToUpdateDocumentException * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: FailedToUpdateDocumentException.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: FailedToUpdateDocumentException.java 516448 2007-03-09 + * 16:25:47Z ate $ + * */ public class FailedToUpdateDocumentException extends DocumentException { @@ -43,7 +44,7 @@ /** * @param message */ - public FailedToUpdateDocumentException( String message ) + public FailedToUpdateDocumentException(String message) { super(message); // TODO Auto-generated constructor stub @@ -52,7 +53,7 @@ /** * @param nested */ - public FailedToUpdateDocumentException( Throwable nested ) + public FailedToUpdateDocumentException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -62,7 +63,7 @@ * @param msg * @param nested */ - public FailedToUpdateDocumentException( String msg, Throwable nested ) + public FailedToUpdateDocumentException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToUpdateFolderException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToUpdateFolderException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FailedToUpdateFolderException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,17 +16,18 @@ */ package org.apache.jetspeed.page.document; - /** * <p> * FailedToUpdateFolderException * </p> * <p> - * + * * </p> + * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> - * @version $Id: FailedToUpdateFolderException.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: FailedToUpdateFolderException.java 516448 2007-03-09 16:25:47Z + * ate $ + * */ public class FailedToUpdateFolderException extends NodeException { @@ -42,7 +43,7 @@ /** * @param message */ - public FailedToUpdateFolderException( String message ) + public FailedToUpdateFolderException(String message) { super(message); } @@ -50,7 +51,7 @@ /** * @param nested */ - public FailedToUpdateFolderException( Throwable nested ) + public FailedToUpdateFolderException(Throwable nested) { super(nested); } @@ -59,7 +60,7 @@ * @param msg * @param nested */ - public FailedToUpdateFolderException( String msg, Throwable nested ) + public FailedToUpdateFolderException(String msg, Throwable nested) { super(msg, nested); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FolderHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FolderHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/FolderHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,112 +25,140 @@ * FolderHandler * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: FolderHandler.java 553584 2007-07-05 18:09:45Z taylor $ - * + * */ public interface FolderHandler { + /** * * <p> * getFolder * </p> * <p> - * Locates a folder given using the <code>path</code> argument. This should behave - * as <code>getFolder("folder/subfolder, true);</code> + * Locates a folder given using the <code>path</code> argument. This + * should behave as <code>getFolder("folder/subfolder, true);</code> * </p> - * - * @param path fully-quallified path to a folder - * @return Folder represented by the <code>path</code> argument. Never returns <code>null</code> - * @throws DocumentException if there was an error processing the request. + * + * @param path + * fully-quallified path to a folder + * @return Folder represented by the <code>path</code> argument. Never + * returns <code>null</code> + * @throws DocumentException + * if there was an error processing the request. * @throws InvalidFolderException * @throws NodeException - * @throws DocumentNotFoundException If there is no folder at the <code>path</code> specified. + * @throws DocumentNotFoundException + * If there is no folder at the <code>path</code> specified. */ - Folder getFolder(String path) throws FolderNotFoundException, InvalidFolderException, NodeException; - + Folder getFolder(String path) throws FolderNotFoundException, + InvalidFolderException, NodeException; + /** * * <p> * updateFolder * </p> * <p> - * Updates the folder specified with the <code>folder</code> argument. + * Updates the folder specified with the <code>folder</code> argument. * </p> - * - * @param folder folder to update + * + * @param folder + * folder to update */ void updateFolder(Folder folder) throws FailedToUpdateFolderException; - + /** * * <p> * removeFolder * </p> * <p> - * Removes the folder specified with the <code>folder</code> argument. + * Removes the folder specified with the <code>folder</code> argument. * </p> - * - * @param folder folder to update + * + * @param folder + * folder to update */ void removeFolder(Folder folder) throws FailedToDeleteFolderException; - + /** * * <p> * getFolder * </p> * <p> - * Locates a folder given using the <code>path</code> argument. + * Locates a folder given using the <code>path</code> argument. * </p> - * - * @param path fully-quallified path to a folder - * @param fromCache whether or not to check the cache first before checking the underlying folder - * repository. - * @return Folder represented by the <code>path</code> argument. Never returns <code>null</code> - * @throws DocumentException if there was an error processing the request. + * + * @param path + * fully-quallified path to a folder + * @param fromCache + * whether or not to check the cache first before checking the + * underlying folder repository. + * @return Folder represented by the <code>path</code> argument. Never + * returns <code>null</code> + * @throws DocumentException + * if there was an error processing the request. * @throws InvalidFolderException * @throws NodeException - * @throws DocumentNotFoundException If there is no folder at the <code>path</code> specified. + * @throws DocumentNotFoundException + * If there is no folder at the <code>path</code> specified. */ - Folder getFolder(String path, boolean fromCache) throws FolderNotFoundException, InvalidFolderException, NodeException; - + Folder getFolder(String path, boolean fromCache) + throws FolderNotFoundException, InvalidFolderException, + NodeException; + /** * * <p> * getFolders * </p> - * - * @param path Path from which to locate child folders - * @return NodeSet of sub-folders located under the <code>path</code> argument. - * @throws FolderNotFoundException if folder under the <code>path</code> does not actually - * exist - * @throws DocumentException if an error is encountered reading the folders. + * + * @param path + * Path from which to locate child folders + * @return NodeSet of sub-folders located under the <code>path</code> + * argument. + * @throws FolderNotFoundException + * if folder under the <code>path</code> does not actually + * exist + * @throws DocumentException + * if an error is encountered reading the folders. * @throws InvalidFolderException * @throws NodeException */ - NodeSet getFolders( String path ) throws FolderNotFoundException, InvalidFolderException, NodeException; - + NodeSet getFolders(String path) throws FolderNotFoundException, + InvalidFolderException, NodeException; + /** * * <p> * list * </p> * <p> - * generates a list of document names, relative to the <code>folderPath</code> argument - * of the type indicated by the <code>documentType</code> argument. + * generates a list of document names, relative to the + * <code>folderPath</code> argument of the type indicated by the + * <code>documentType</code> argument. * </p> - * @param folderPath folder path to search under - * @param documentType document type to filter on. - * @return a <code>String[]</code> of child document names relative to the <code>folderPath</code> - * argument and matching the <code>documentType</code> argument. - * @throws FolderNotFoundException if the <code>folderPath</code> does not exsit. + * + * @param folderPath + * folder path to search under + * @param documentType + * document type to filter on. + * @return a <code>String[]</code> of child document names relative to the + * <code>folderPath</code> argument and matching the + * <code>documentType</code> argument. + * @throws FolderNotFoundException + * if the <code>folderPath</code> does not exsit. */ - String[] list(String folderPath, String documentType) throws FolderNotFoundException; - + String[] list(String folderPath, String documentType) + throws FolderNotFoundException; + String[] listAll(String folderPath) throws FolderNotFoundException; /** @@ -138,23 +166,33 @@ * getNodes * </p> * <p> - * Returns a set of nodes relative to the <code>folder</code> argument of the type - * indicated by the <code>documentType</code> argument. The <code>folder</code> argument - * may include regular expressions if indicated by the <code>regex</code> argument. The - * returned set is unordered. + * Returns a set of nodes relative to the <code>folder</code> argument of + * the type indicated by the <code>documentType</code> argument. The + * <code>folder</code> argument may include regular expressions if + * indicated by the <code>regex</code> argument. The returned set is + * unordered. * </p> - * - * @param path Path from which to locate documents - * @param regexp Flag indicating whether regexp should be expanded in path - * @param documentType document type to filter on. - * @return NodeSet of documents and folders located under the <code>path</code> argument. - * @throws FolderNotFoundException if folder under the <code>path</code> does not actually exist. - * @throws DocumentException if an error is encountered reading the folders. + * + * @param path + * Path from which to locate documents + * @param regexp + * Flag indicating whether regexp should be expanded in path + * @param documentType + * document type to filter on. + * @return NodeSet of documents and folders located under the + * <code>path</code> argument. + * @throws FolderNotFoundException + * if folder under the <code>path</code> does not actually + * exist. + * @throws DocumentException + * if an error is encountered reading the folders. * @throws InvalidFolderException * @throws NodeException */ - NodeSet getNodes(String path, boolean regexp, String documentType) throws FolderNotFoundException, InvalidFolderException, NodeException; - + NodeSet getNodes(String path, boolean regexp, String documentType) + throws FolderNotFoundException, InvalidFolderException, + NodeException; + /** * Returns true if the path is a folder * @@ -162,5 +200,5 @@ * @return */ boolean isFolder(String path); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/Node.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/Node.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/Node.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,15 +26,18 @@ * Node * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: Node.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface Node extends BaseElement { + String PATH_SEPARATOR = "/"; + char PATH_SEPARATOR_CHAR = '/'; /** @@ -42,27 +45,27 @@ * <p> * getParent * </p> - * + * * @return */ Node getParent(); - + /** * * <p> * setParent * </p> - * + * * @param parent */ void setParent(Node parent); - + /** * * <p> * getPath * </p> - * + * * @return */ String getPath(); @@ -73,31 +76,30 @@ * getName * </p> * - * Returns the name of this node relative to + * Returns the name of this node relative to * <code>Node.getParent().getPath()</code> - * + * * @return Name, relative to the parent node. */ String getName(); - + /** * * <p> * setPath * </p> * Sets the full-qualified path of this node. - * + * * @param path */ void setPath(String path); - - + /** * * <p> * getMetadata * </p> - * + * * @return */ GenericMetadata getMetadata(); @@ -108,7 +110,7 @@ * getTitle * </p> * Returns the title for the specified locale. - * + * * @param locale * @return localized title of this Node. */ @@ -120,7 +122,7 @@ * getShortTitle * </p> * Returns the short title for the specified locale. - * + * * @param locale * @return localized title of this Node. */ @@ -135,7 +137,7 @@ * @return */ String getType(); - + /** * * <p> @@ -145,17 +147,18 @@ * @return */ String getUrl(); - + /** * * <p> * isHidden * </p> * <p> - * Whether or not this Node should be hidden in terms of the view. This MUST NOT restrict - * the presence of this node in terms of being returned in - * {@link NodeSets org.apache.jetspeed.page.document.NodeSet}. + * Whether or not this Node should be hidden in terms of the view. This MUST + * NOT restrict the presence of this node in terms of being returned in + * {@link NodeSets org.apache.jetspeed.page.document.NodeSet}. * </p> + * * @return hidden flag */ boolean isHidden(); @@ -166,9 +169,11 @@ * setHidden * </p> * <p> - * Whether or not this Node should be hidden in terms of the view. + * Whether or not this Node should be hidden in terms of the view. * </p> - * @param hidden flag + * + * @param hidden + * flag */ void setHidden(boolean hidden); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/NodeException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/NodeException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/NodeException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,19 +1,19 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /* * Created on Sep 2, 2004 * @@ -29,13 +29,14 @@ * NodeException * </p> * <p> - * Note that these exceptions are assumed to be "unexpected" and/or - * fatal; use NodeNotFoundException or other exceptions derived from - * the base JetspeedException for "informational" exceptions. + * Note that these exceptions are assumed to be "unexpected" and/or fatal; use + * NodeNotFoundException or other exceptions derived from the base + * JetspeedException for "informational" exceptions. * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: NodeException.java 516881 2007-03-11 10:34:21Z ate $ - * + * */ public class NodeException extends JetspeedException { @@ -52,7 +53,7 @@ /** * @param message */ - public NodeException( String message ) + public NodeException(String message) { super(message); // TODO Auto-generated constructor stub @@ -61,7 +62,7 @@ /** * @param nested */ - public NodeException( Throwable nested ) + public NodeException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -71,7 +72,7 @@ * @param msg * @param nested */ - public NodeException( String msg, Throwable nested ) + public NodeException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/NodeNotFoundException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/NodeNotFoundException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/NodeNotFoundException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,12 +23,13 @@ * NodeNotFoundException * </p> * <p> - * Note that these "informational" exceptions must not derive from - * NodeException and instead derive from only the base JetspeedException. + * Note that these "informational" exceptions must not derive from NodeException + * and instead derive from only the base JetspeedException. * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: NodeNotFoundException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class NodeNotFoundException extends JetspeedException { @@ -45,7 +46,7 @@ /** * @param message */ - public NodeNotFoundException( String message ) + public NodeNotFoundException(String message) { super(message); // TODO Auto-generated constructor stub @@ -54,7 +55,7 @@ /** * @param nested */ - public NodeNotFoundException( Throwable nested ) + public NodeNotFoundException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -64,7 +65,7 @@ * @param msg * @param nested */ - public NodeNotFoundException( String msg, Throwable nested ) + public NodeNotFoundException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/NodeSet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/NodeSet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/NodeSet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,11 +23,12 @@ * NodeSet * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: NodeSet.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface NodeSet { @@ -37,10 +38,11 @@ /** * <p> * get - * </p> - * Returns a Node based on <code>name</code>. <code>name</code> - * can either be the fully quallified path, <code>folder1/folder2/myPage.psml</code> - * as returned by Node.getPath(), or the page name relative the <code>Node.getParent().getPath()</code> + * </p> + * Returns a Node based on <code>name</code>. <code>name</code> can + * either be the fully quallified path, + * <code>folder1/folder2/myPage.psml</code> as returned by Node.getPath(), + * or the page name relative the <code>Node.getParent().getPath()</code> * as return by Node.getName()that this DocumentSet was generated for. * * @param name @@ -49,11 +51,11 @@ Node get(String name); Iterator iterator(); - + NodeSet subset(String type); NodeSet inclusiveSubset(String regex); - + NodeSet exclusiveSubset(String regex); int size(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/UnsupportedDocumentTypeException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/UnsupportedDocumentTypeException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/page/document/UnsupportedDocumentTypeException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,17 +16,18 @@ */ package org.apache.jetspeed.page.document; - /** * <p> * UnsupportedDocumentTypeException * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: UnsupportedDocumentTypeException.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: UnsupportedDocumentTypeException.java 516448 2007-03-09 + * 16:25:47Z ate $ + * */ public class UnsupportedDocumentTypeException extends DocumentException { @@ -43,7 +44,7 @@ /** * @param message */ - public UnsupportedDocumentTypeException( String message ) + public UnsupportedDocumentTypeException(String message) { super(message); // TODO Auto-generated constructor stub @@ -52,7 +53,7 @@ /** * @param nested */ - public UnsupportedDocumentTypeException( Throwable nested ) + public UnsupportedDocumentTypeException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -62,7 +63,7 @@ * @param msg * @param nested */ - public UnsupportedDocumentTypeException( String msg, Throwable nested ) + public UnsupportedDocumentTypeException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/Pipeline.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/Pipeline.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/Pipeline.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,58 +23,71 @@ /** * Jetspeed Pipeline - * + * * @author <a href="mailto:david ¡÷ bluesunrise.com">David Sean Taylor</a> * @version $Id: Pipeline.java 516448 2007-03-09 16:25:47Z ate $ */ public interface Pipeline { - void initialize() - throws PipelineException; + + void initialize() throws PipelineException; + /** - * <p>Add a new Valve to the end of the pipeline.</p> - * - * @param valve Valve to be added. - * - * @exception IllegalStateException If the pipeline has not been - * initialized. + * <p> + * Add a new Valve to the end of the pipeline. + * </p> + * + * @param valve + * Valve to be added. + * + * @exception IllegalStateException + * If the pipeline has not been initialized. */ void addValve(Valve valve); /** - * <p>Return the set of all Valves in the pipeline. If there are no - * such Valves, a zero-length array is returned.</p> - * + * <p> + * Return the set of all Valves in the pipeline. If there are no such + * Valves, a zero-length array is returned. + * </p> + * * @return An array of valves. */ Valve[] getValves(); /** - * <p>Cause the specified request and response to be processed by - * the sequence of Valves associated with this pipeline, until one - * of these Valves decides to end the processing.</p> - * - * <p>The implementation must ensure that multiple simultaneous - * requests (on different threads) can be processed through the - * same Pipeline without interfering with each other's control - * flow.</p> - * - * @param data The run-time information, including the servlet - * request and response we are processing. - * - * @exception IOException an input/output error occurred. + * <p> + * Cause the specified request and response to be processed by the sequence + * of Valves associated with this pipeline, until one of these Valves + * decides to end the processing. + * </p> + * + * <p> + * The implementation must ensure that multiple simultaneous requests (on + * different threads) can be processed through the same Pipeline without + * interfering with each other's control flow. + * </p> + * + * @param data + * The run-time information, including the servlet request and + * response we are processing. + * + * @exception IOException + * an input/output error occurred. */ - void invoke(RequestContext context) - throws PipelineException; + void invoke(RequestContext context) throws PipelineException; /** - * <p>Remove the specified Valve from the pipeline, if it is found; - * otherwise, do nothing.</p> - * - * @param valve Valve to be removed. + * <p> + * Remove the specified Valve from the pipeline, if it is found; otherwise, + * do nothing. + * </p> + * + * @param valve + * Valve to be removed. */ void removeValve(Valve valve); - + /** * Get the name of the pipeine * Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/PipelineException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/PipelineException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/PipelineException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -15,33 +15,34 @@ * limitations under the License. */ package org.apache.jetspeed.pipeline; + import org.apache.jetspeed.exception.JetspeedException; /** - * Occurs when anything unexpected happens within Jetspeed and the Pipeline. - * - * @author <a href="mailto:david ¡÷ bluesunrise.com">David Sean Taylor</a> - * @version $Id: PipelineException.java 516448 2007-03-09 16:25:47Z ate $ - */ + * Occurs when anything unexpected happens within Jetspeed and the Pipeline. + * + * @author <a href="mailto:david ¡÷ bluesunrise.com">David Sean Taylor</a> + * @version $Id: PipelineException.java 516448 2007-03-09 16:25:47Z ate $ + */ public class PipelineException extends JetspeedException - { +{ - public PipelineException() + public PipelineException() { super(); } - public PipelineException( String message ) + public PipelineException(String message) { - super( message ); + super(message); } public PipelineException(Throwable nested) { super(nested); } - + public PipelineException(String msg, Throwable nested) { super(msg, nested); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/descriptor/PipelineDescriptorApi.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/descriptor/PipelineDescriptorApi.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/descriptor/PipelineDescriptorApi.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,51 +19,51 @@ import java.util.List; -import org.apache.jetspeed.pipeline.descriptor.ValveDescriptorApi; - - public interface PipelineDescriptorApi { + /** - * Add a ValveDescriptor to the Pipeline - * descriptor - * + * Add a ValveDescriptor to the Pipeline descriptor + * * @param ValveDescriptor - */ + */ public void addValveDescriptor(ValveDescriptorApi valveDescriptor); /** * Return a list of ValveDesccriptors - * + * * @return List of ValveDesccriptors */ public List getValveDescriptors(); /** * Sets the name attribute - * - * @param name the new name value + * + * @param name + * the new name value */ public void setName(String name); + /** * Gets the name attribute - * - * @return the name attribute + * + * @return the name attribute */ public String getName(); - + /** * Sets the id attribute of the BaseDescriptor object - * - * @param id the new id value + * + * @param id + * the new id value */ public void setId(String id); - + /** * Gets the id attribute - * + * * @return the id attribute */ public String getId(); - -} \ No newline at end of file + +} \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/descriptor/ValveDescriptorApi.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/descriptor/ValveDescriptorApi.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/descriptor/ValveDescriptorApi.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,17 +18,18 @@ public interface ValveDescriptorApi { + /** - * This is the full package/class name of the - * class used for the valve. - * - * @param s the full package/class name used for the valve + * This is the full package/class name of the class used for the valve. + * + * @param s + * the full package/class name used for the valve */ public void setClassName(String className); - + /** * @return the full package/class name used for the valve */ public String getClassName(); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/valve/Valve.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/valve/Valve.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/valve/Valve.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,30 +16,30 @@ */ package org.apache.jetspeed.pipeline.valve; +import org.apache.jetspeed.pipeline.PipelineException; import org.apache.jetspeed.request.RequestContext; -import org.apache.jetspeed.pipeline.PipelineException; /** * NOTE: This class will be deprecated once we merge with Summit - * - * General valve interface. The actual valve interface(s) should be - * extended by the implementing class. - * + * + * General valve interface. The actual valve interface(s) should be extended by + * the implementing class. + * * @author <a href="mailto:david ¡÷ bluesunrise.com">David Sean Taylor</a> * @version $Id: Valve.java 186726 2004-06-05 05:13:09Z taylor $ - * + * * @see org.apache.jetspeed.pipeline.JetspeedPipeline * @see org.apache.jetspeed.pipeline.Pipeline */ public interface Valve { + public void invoke(RequestContext request, ValveContext context) - throws PipelineException; + throws PipelineException; /** * Initialize the valve before using in a pipeline. */ - public void initialize() - throws PipelineException; + public void initialize() throws PipelineException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/valve/ValveContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/valve/ValveContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/pipeline/valve/ValveContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,37 +17,46 @@ package org.apache.jetspeed.pipeline.valve; +import java.io.IOException; + +import org.apache.jetspeed.pipeline.PipelineException; import org.apache.jetspeed.request.RequestContext; -import org.apache.jetspeed.pipeline.PipelineException; /** * NOTE: This class will be deprecated once we merge with Summit - * - * + * + * * @author <a href="mailto:david ¡÷ bluesunrise.com">David Sean Taylor</a> * @version $Id: ValveContext.java 186726 2004-06-05 05:13:09Z taylor $ */ public interface ValveContext { + /** - * <p>Cause the <code>invoke()</code> method of the next Valve - * that is part of the Pipeline currently being processed (if any) - * to be executed, passing on the specified request and response - * objects plus this <code>ValveContext</code> instance. - * Exceptions thrown by a subsequently executed Valve will be - * passed on to our caller.</p> - * - * <p>If there are no more Valves to be executed, execution of - * this method will result in a no op.</p> - * - * @param data The run-time information, including the servlet - * request and response we are processing. - * - * @exception IOException Thrown by a subsequent Valve. - * @exception SummitException Thrown by a subsequent Valve. - * @exception SummitException No further Valves configured in the - * Pipeline currently being processed. + * <p> + * Cause the <code>invoke()</code> method of the next Valve that is part + * of the Pipeline currently being processed (if any) to be executed, + * passing on the specified request and response objects plus this + * <code>ValveContext</code> instance. Exceptions thrown by a subsequently + * executed Valve will be passed on to our caller. + * </p> + * + * <p> + * If there are no more Valves to be executed, execution of this method will + * result in a no op. + * </p> + * + * @param data + * The run-time information, including the servlet request and + * response we are processing. + * + * @exception IOException + * Thrown by a subsequent Valve. + * @exception SummitException + * Thrown by a subsequent Valve. + * @exception SummitException + * No further Valves configured in the Pipeline currently + * being processed. */ - public void invokeNext(RequestContext request) - throws PipelineException; + public void invokeNext(RequestContext request) throws PipelineException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/Menu.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/Menu.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/Menu.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,72 +19,69 @@ import java.util.List; /** - * This interface describes the portal-site menu elements - * constructed and returned to decorators. + * This interface describes the portal-site menu elements constructed and + * returned to decorators. * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> * @version $Id: Menu.java 516448 2007-03-09 16:25:47Z ate $ */ public interface Menu extends MenuElement { + /** * getName - get name of menu - * + * * @return menu name */ String getName(); /** - * getUrl - get url of top level folder that defined - * menu options; only available for menus - * defined without multiple options, nested - * menus, or separators - * + * getUrl - get url of top level folder that defined menu options; only + * available for menus defined without multiple options, nested menus, or + * separators + * * @return folder url */ String getUrl(); /** - * isHidden - get hidden state of folder that defined - * menu options; only available for menus - * defined without multiple options, nested - * menus, or separators - * + * isHidden - get hidden state of folder that defined menu options; only + * available for menus defined without multiple options, nested menus, or + * separators + * * @return hidden state */ boolean isHidden(); /** - * isSelected - return true if an option or nested - * menu within this menu are selected by - * the specified request context - * - * @param context request context + * isSelected - return true if an option or nested menu within this menu are + * selected by the specified request context + * + * @param context + * request context * @return selected state */ boolean isSelected(PortalSiteRequestContext context); /** - * getElements - get ordered list of menu elements that - * are members of this menu; possibly contains - * options, nested menus, or separators - * + * getElements - get ordered list of menu elements that are members of this + * menu; possibly contains options, nested menus, or separators + * * @return menu elements list */ List getElements(); /** * isEmpty - get empty state of list of menu elements - * + * * @return menu elements list empty state */ boolean isEmpty(); /** - * getSelectedElement - return selected option or nested - * menu within this menu selected by - * the specified request context - * + * getSelectedElement - return selected option or nested menu within this + * menu selected by the specified request context + * * @return selected menu element */ MenuElement getSelectedElement(PortalSiteRequestContext context); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/MenuElement.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/MenuElement.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/MenuElement.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,14 +21,15 @@ import org.apache.jetspeed.om.common.GenericMetadata; /** - * This interface describes common features of portal-site - * menu elements constructed and returned to decorators. + * This interface describes common features of portal-site menu elements + * constructed and returned to decorators. * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> * @version $Id: MenuElement.java 516448 2007-03-09 16:25:47Z ate $ */ public interface MenuElement { + /** * MENU_ELEMENT_TYPE - element type of menu elements */ @@ -46,61 +47,61 @@ /** * getElementType - get type of menu element - * - * @return MENU_ELEMENT_TYPE, OPTION_ELEMENT_TYPE, or - * SEPARATOR_ELEMENT_TYPE + * + * @return MENU_ELEMENT_TYPE, OPTION_ELEMENT_TYPE, or SEPARATOR_ELEMENT_TYPE */ String getElementType(); /** - * getParentMenu - get menu that contains menu element - * + * getParentMenu - get menu that contains menu element + * * @return parent menu - */ + */ Menu getParentMenu(); /** * getTitle - get default title for menu element - * + * * @return title text */ String getTitle(); /** * getShortTitle - get default short title for menu element - * + * * @return short title text */ String getShortTitle(); /** - * getTitle - get locale specific title for menu element - * from metadata - * - * @param locale preferred locale + * getTitle - get locale specific title for menu element from metadata + * + * @param locale + * preferred locale * @return title text */ String getTitle(Locale locale); /** - * getShortTitle - get locale specific short title for menu - * element from metadata - * - * @param locale preferred locale + * getShortTitle - get locale specific short title for menu element from + * metadata + * + * @param locale + * preferred locale * @return short title text */ String getShortTitle(Locale locale); /** * getMetadata - get generic metadata for menu element - * + * * @return metadata - */ + */ GenericMetadata getMetadata(); /** * getSkin - get skin name for menu element - * + * * @return skin name */ String getSkin(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/MenuOption.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/MenuOption.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/MenuOption.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,14 +17,15 @@ package org.apache.jetspeed.portalsite; /** - * This interface describes the portal-site menu option - * elements constructed and returned to decorators. + * This interface describes the portal-site menu option elements constructed and + * returned to decorators. * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> * @version $Id: MenuOption.java 537314 2007-05-11 23:08:36Z taylor $ */ public interface MenuOption extends MenuElement { + /** * FOLDER_OPTION_TYPE - type of folder menu option */ @@ -42,45 +43,45 @@ /** * getType - get type of menu option - * - * @return FOLDER_OPTION_TYPE, PAGE_OPTION_TYPE, or - * LINK_OPTION_TYPE + * + * @return FOLDER_OPTION_TYPE, PAGE_OPTION_TYPE, or LINK_OPTION_TYPE */ String getType(); /** * getUrl - get url of menu option - * + * * @return folder, page, or link url */ String getUrl(); /** * getTarget - get target for url of menu option - * + * * @return url target */ String getTarget(); /** * getDefaultPage - get target for url of menu option - * + * * @return url target */ String getDefaultPage(); - + /** * isHidden - get hidden state of menu option - * + * * @return hidden state */ boolean isHidden(); /** - * isSelected - return true if menu option is selected in - * the specified request context - * - * @param context request context + * isSelected - return true if menu option is selected in the specified + * request context + * + * @param context + * request context * @return selected state */ boolean isSelected(PortalSiteRequestContext context); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/MenuSeparator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/MenuSeparator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/MenuSeparator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,26 +19,27 @@ import java.util.Locale; /** - * This interface describes the portal-site menu separator - * elements constructed and returned to decorators. + * This interface describes the portal-site menu separator elements constructed + * and returned to decorators. * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> * @version $Id: MenuSeparator.java 516448 2007-03-09 16:25:47Z ate $ */ public interface MenuSeparator extends MenuElement { + /** * getText - get default text for menu separator - * + * * @return text */ String getText(); /** - * getText - get locale specific text for menu separator - * from metadata - * - * @param locale preferred locale + * getText - get locale specific text for menu separator from metadata + * + * @param locale + * preferred locale * @return text */ String getText(Locale locale); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/PortalSite.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/PortalSite.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/PortalSite.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,16 +26,17 @@ */ public interface PortalSite { + /** * newSessionContext - create a new session context instance - * + * * @return new session context instance */ PortalSiteSessionContext newSessionContext(); /** * getPageManager - return PageManager component instance - * + * * @return PageManager instance */ PageManager getPageManager(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/PortalSiteRequestContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/PortalSiteRequestContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/PortalSiteRequestContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,124 +32,144 @@ */ public interface PortalSiteRequestContext { + /** * getSessionContext - get component session context - * + * * @return component session context */ PortalSiteSessionContext getSessionContext(); /** * getLocators - get profile locators by locator names - * + * * @return request profile locators */ Map getLocators(); /** - * getManagedPage - get request profiled concrete page instance - * as managed by the page manager - * + * getManagedPage - get request profiled concrete page instance as managed + * by the page manager + * * @return page - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ Page getManagedPage() throws NodeNotFoundException; /** * getPage - get request profiled page proxy - * + * * @return page proxy - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ Page getPage() throws NodeNotFoundException; /** * getFolder - get folder proxy relative to request profiled page - * + * * @return page folder proxy - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ Folder getFolder() throws NodeNotFoundException; /** - * getSiblingPages - get node set of sibling page proxies relative - * to request profiled page, (includes profiled - * page proxy) - * + * getSiblingPages - get node set of sibling page proxies relative to + * request profiled page, (includes profiled page proxy) + * * @return sibling page proxies - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ NodeSet getSiblingPages() throws NodeNotFoundException; /** - * getParentFolder - get parent folder proxy relative to request - * profiled page - * + * getParentFolder - get parent folder proxy relative to request profiled + * page + * * @return parent folder proxy or null - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ Folder getParentFolder() throws NodeNotFoundException; /** - * getSiblingFolders - get node set of sibling folder proxies relative - * to request profiled page, (includes profiled - * page folder proxy) - * + * getSiblingFolders - get node set of sibling folder proxies relative to + * request profiled page, (includes profiled page folder proxy) + * * @return sibling folder proxies - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ NodeSet getSiblingFolders() throws NodeNotFoundException; /** * getRootFolder - get root profiled folder proxy - * + * * @return parent folder proxy - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ Folder getRootFolder() throws NodeNotFoundException; /** - * getRootLinks - get node set of link proxies relative to - * profiled root folder - * + * getRootLinks - get node set of link proxies relative to profiled root + * folder + * * @return root link proxies - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ NodeSet getRootLinks() throws NodeNotFoundException; /** * getStandardMenuNames - get set of available standard menu names - * + * * @return menu names set */ Set getStandardMenuNames(); /** - * getCustomMenuNames - get set of custom menu names available as - * defined for the request profiled page and folder - * + * getCustomMenuNames - get set of custom menu names available as defined + * for the request profiled page and folder + * * @return menu names set - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ Set getCustomMenuNames() throws NodeNotFoundException; /** - * getMenu - get instantiated menu available for the request - * profiled page and folder - * - * @param name menu definition name + * getMenu - get instantiated menu available for the request profiled page + * and folder + * + * @param name + * menu definition name * @return menu instance - * @throws NodeNotFoundException if page not found - * @throws SecurityException if page view access not granted + * @throws NodeNotFoundException + * if page not found + * @throws SecurityException + * if page view access not granted */ Menu getMenu(String name) throws NodeNotFoundException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/PortalSiteSessionContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/PortalSiteSessionContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portalsite/PortalSiteSessionContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,66 +25,75 @@ * This describes the session context for the portal-site component. * * @author <a href="mailto:rwatler ¡÷ apache.org">Randy Watler</a> - * @version $Id: PortalSiteSessionContext.java 553375 2007-07-05 05:37:00Z taylor $ + * @version $Id: PortalSiteSessionContext.java 553375 2007-07-05 05:37:00Z + * taylor $ */ public interface PortalSiteSessionContext extends Serializable { + /** - * newRequestContext - create a new request context instance with fallback and history - * - * @param requestProfileLocators request profile locators + * newRequestContext - create a new request context instance with fallback + * and history + * + * @param requestProfileLocators + * request profile locators * @return new request context instance */ PortalSiteRequestContext newRequestContext(Map requestProfileLocators); /** * newRequestContext - create a new request context instance with history - * - * @param requestProfileLocators request profile locators - * @param requestFallback flag specifying whether to fallback to root folder - * if locators do not select a page or access is forbidden + * + * @param requestProfileLocators + * request profile locators + * @param requestFallback + * flag specifying whether to fallback to root folder if locators + * do not select a page or access is forbidden * @return new request context instance */ - PortalSiteRequestContext newRequestContext(Map requestProfileLocators, boolean requestFallback); + PortalSiteRequestContext newRequestContext(Map requestProfileLocators, + boolean requestFallback); /** * newRequestContext - create a new request context instance - * - * @param requestProfileLocators request profile locators - * @param requestFallback flag specifying whether to fallback to root folder - * if locators do not select a page or access is forbidden - * @param useHistory flag indicating whether to use visited page - * history to select default page per site folder + * + * @param requestProfileLocators + * request profile locators + * @param requestFallback + * flag specifying whether to fallback to root folder if locators + * do not select a page or access is forbidden + * @param useHistory + * flag indicating whether to use visited page history to select + * default page per site folder * @return new request context instance */ - PortalSiteRequestContext newRequestContext(Map requestProfileLocators, boolean requestFallback, boolean useHistory); + PortalSiteRequestContext newRequestContext(Map requestProfileLocators, + boolean requestFallback, boolean useHistory); /** * getPageManager - return PageManager component instance - * + * * @return PageManager instance */ PageManager getPageManager(); /** - * isValid - return flag indicating whether this context instance - * is valid or if it is stale after being persisted and - * reloaded as session state - * + * isValid - return flag indicating whether this context instance is valid + * or if it is stale after being persisted and reloaded as session state + * * @return valid context status */ boolean isValid(); - + /** - * set which pipeline this context is stored for + * set which pipeline this context is stored for * * @param pipeline */ void setPipeline(String pipeline); - + /** * get which pipeline this context is stored for */ String getPipeline(); } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portlet/PortletHeaderRequest.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portlet/PortletHeaderRequest.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portlet/PortletHeaderRequest.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,27 +19,29 @@ import javax.portlet.PortletPreferences; public interface PortletHeaderRequest -{ +{ + /** - * Returns the web context path for the portal + * Returns the web context path for the portal + * * @return the portal context path, for example "/jetspeed" */ String getPortalContextPath(); - + /** - * Returns the portlet applicatoin context path + * Returns the portlet applicatoin context path * * @return */ String getPortletApplicationContextPath(); - + /** * Get the portlet preferences */ PortletPreferences getPreferences(); - + /** * Get the init parameter by name */ - String getInitParameter( String name ); + String getInitParameter(String name); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portlet/PortletHeaderResponse.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portlet/PortletHeaderResponse.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portlet/PortletHeaderResponse.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,48 +22,47 @@ import org.apache.jetspeed.headerresource.HeaderResource; - public interface PortletHeaderResponse -{ +{ + /** * Retrieves the header resource for this request * * @return a per request HeaderResource */ HeaderResource getHeaderResource(); - + /** * Is request for /desktop rather than /portal * * @return true if request is for /desktop, false if request is for /portal */ boolean isDesktop(); - - + /** * Configuration data for use by HeaderResource * * @return an immutable Map */ Map getHeaderConfiguration(); - + /** * Map containing overrides of content for header statements * * @return an immutable Map */ Map getHeaderResourceRegistry(); - + /** - * Temporary solution: get the content after calling include - * this will be deprecated + * Temporary solution: get the content after calling include this will be + * deprecated * */ String getContent(); - /** - * Dispatch to a servlet or resource to generate and include the header content + * Dispatch to a servlet or resource to generate and include the header + * content * * @param request * @param response @@ -71,6 +70,6 @@ * @return * @throws PortletException */ - void include(PortletHeaderRequest request, PortletHeaderResponse response, String headerResource) - throws PortletException; + void include(PortletHeaderRequest request, PortletHeaderResponse response, + String headerResource) throws PortletException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portlet/SupportsHeaderPhase.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portlet/SupportsHeaderPhase.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/portlet/SupportsHeaderPhase.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,11 +19,13 @@ import javax.portlet.PortletException; /** - * Indicates that a portlet supports the pre-286 header phase - * + * Indicates that a portlet supports the pre-286 header phase + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> */ public interface SupportsHeaderPhase { - void doHeader(PortletHeaderRequest request, PortletHeaderResponse response) throws PortletException; + + void doHeader(PortletHeaderRequest request, PortletHeaderResponse response) + throws PortletException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/FailedToCreateNodeException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/FailedToCreateNodeException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/FailedToCreateNodeException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,11 +21,13 @@ * FailedToCreateNodeException * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * @version $Id: FailedToCreateNodeException.java 516448 2007-03-09 16:25:47Z ate $ - * + * @version $Id: FailedToCreateNodeException.java 516448 2007-03-09 16:25:47Z + * ate $ + * */ public class FailedToCreateNodeException extends PreferencesException { @@ -42,7 +44,7 @@ /** * @param message */ - public FailedToCreateNodeException( String message ) + public FailedToCreateNodeException(String message) { super(message); // TODO Auto-generated constructor stub @@ -51,7 +53,7 @@ /** * @param nested */ - public FailedToCreateNodeException( Throwable nested ) + public FailedToCreateNodeException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -61,7 +63,7 @@ * @param msg * @param nested */ - public FailedToCreateNodeException( String msg, Throwable nested ) + public FailedToCreateNodeException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/NodeAlreadyExistsException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/NodeAlreadyExistsException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/NodeAlreadyExistsException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,11 +21,12 @@ * NodeAlreadyExistsException * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: NodeAlreadyExistsException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class NodeAlreadyExistsException extends PreferencesException { @@ -41,7 +42,7 @@ /** * @param message */ - public NodeAlreadyExistsException( String message ) + public NodeAlreadyExistsException(String message) { super(message); } @@ -49,7 +50,7 @@ /** * @param nested */ - public NodeAlreadyExistsException( Throwable nested ) + public NodeAlreadyExistsException(Throwable nested) { super(nested); } @@ -58,7 +59,7 @@ * @param msg * @param nested */ - public NodeAlreadyExistsException( String msg, Throwable nested ) + public NodeAlreadyExistsException(String msg, Throwable nested) { super(msg, nested); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/NodeDoesNotExistException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/NodeDoesNotExistException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/NodeDoesNotExistException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,11 +21,12 @@ * NodeDoesNotExistException * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: NodeDoesNotExistException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class NodeDoesNotExistException extends PreferencesException { @@ -42,7 +43,7 @@ /** * @param message */ - public NodeDoesNotExistException( String message ) + public NodeDoesNotExistException(String message) { super(message); // TODO Auto-generated constructor stub @@ -51,7 +52,7 @@ /** * @param nested */ - public NodeDoesNotExistException( Throwable nested ) + public NodeDoesNotExistException(Throwable nested) { super(nested); // TODO Auto-generated constructor stub @@ -61,7 +62,7 @@ * @param msg * @param nested */ - public NodeDoesNotExistException( String msg, Throwable nested ) + public NodeDoesNotExistException(String msg, Throwable nested) { super(msg, nested); // TODO Auto-generated constructor stub Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/PreferencesException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/PreferencesException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/PreferencesException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,11 +23,12 @@ * PreferencesException * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: PreferencesException.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public class PreferencesException extends JetspeedException { @@ -38,13 +39,13 @@ public PreferencesException() { super(); - + } /** * @param message */ - public PreferencesException( String message ) + public PreferencesException(String message) { super(message); @@ -53,7 +54,7 @@ /** * @param nested */ - public PreferencesException( Throwable nested ) + public PreferencesException(Throwable nested) { super(nested); } @@ -62,7 +63,7 @@ * @param msg * @param nested */ - public PreferencesException( String msg, Throwable nested ) + public PreferencesException(String msg, Throwable nested) { super(msg, nested); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/PreferencesProvider.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/PreferencesProvider.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/PreferencesProvider.java 2008-05-16 01:54:54 UTC (rev 940) @@ -32,72 +32,104 @@ */ public interface PreferencesProvider { + /** - * Given the fullpath to a node, retrieve the node associated with the node path + * Given the fullpath to a node, retrieve the node associated with the node + * path * - * @param fullPath the full path to the node such as "/portlet_entity/dp-1/guest/preferences/mypref" - * @param nodeType either System or User node type. A value of 0 is User, a value of 1 is System + * @param fullPath + * the full path to the node such as + * "/portlet_entity/dp-1/guest/preferences/mypref" + * @param nodeType + * either System or User node type. A value of 0 is User, a value + * of 1 is System * @return The Preference Node found when found - * @throws NodeDoesNotExistException when a node is not found, an exception is thrown + * @throws NodeDoesNotExistException + * when a node is not found, an exception is thrown */ - Node getNode(String fullPath, int nodeType) throws NodeDoesNotExistException; + Node getNode(String fullPath, int nodeType) + throws NodeDoesNotExistException; /** * Check for the existence of a node given the full path to the node * - * @param fullPath the full path to the node such as "/portlet_entity/dp-1/guest/preferences/mypref" - * @param nodeType either System or User node type. A value of 0 is User, a value of 1 is System + * @param fullPath + * the full path to the node such as + * "/portlet_entity/dp-1/guest/preferences/mypref" + * @param nodeType + * either System or User node type. A value of 0 is User, a value + * of 1 is System * @return true if the node exists, false if it does not exist */ boolean nodeExists(String fullPath, int nodeType); /** - * Create a preferences node given the following parameters. Will throw an exception if the node already exists. + * Create a preferences node given the following parameters. Will throw an + * exception if the node already exists. * - * @param parent the existing parent node of this node to be created - * @param nodeName the name of the node, which should be the same value as the last value of the full path - * for example when the full path is "/portlet_entity/dp-1", the nodeName will be "dp-1" - * @param nodeType either System or User node type. A value of 0 is User, a value of 1 is System - * @param fullPath the full path to the node such as "/portlet_entity/dp-1/guest/preferences/mypref" + * @param parent + * the existing parent node of this node to be created + * @param nodeName + * the name of the node, which should be the same value as the + * last value of the full path for example when the full path is + * "/portlet_entity/dp-1", the nodeName will be "dp-1" + * @param nodeType + * either System or User node type. A value of 0 is User, a value + * of 1 is System + * @param fullPath + * the full path to the node such as + * "/portlet_entity/dp-1/guest/preferences/mypref" * @return the newly created node on success - * @throws FailedToCreateNodeException thrown when the node fails to create - * @throws NodeAlreadyExistsException thrown when a node already exists at the given full path + * @throws FailedToCreateNodeException + * thrown when the node fails to create + * @throws NodeAlreadyExistsException + * thrown when a node already exists at the given full path */ - Node createNode(Node parent, String nodeName, int nodeType, String fullPath) throws FailedToCreateNodeException, - NodeAlreadyExistsException; + Node createNode(Node parent, String nodeName, int nodeType, String fullPath) + throws FailedToCreateNodeException, NodeAlreadyExistsException; /** - * Create a property on the given node. - * @param node the node to have a property added to it - * @param name the name of the property to add to the node - * @param value the value of the property to add to the node + * Create a property on the given node. + * + * @param node + * the node to have a property added to it + * @param name + * the name of the property to add to the node + * @param value + * the value of the property to add to the node * @return the newly created property * @since 2.1.2 */ Property createProperty(Node node, String name, Object value); - + /** - * Given a parent node, return a flat collection of immediate children of this node + * Given a parent node, return a flat collection of immediate children of + * this node * - * @param parentNode the parent node to be searched for children + * @param parentNode + * the parent node to be searched for children * @return a Java collection of immediate children of this node */ Collection getChildren(Node parentNode); /** * Stores a preference node to the backing preferences persistent storage. - * If the node does not exist, it is created. If it does exist, the node - * is updated. + * If the node does not exist, it is created. If it does exist, the node is + * updated. * - * @param node the node to be stored. + * @param node + * the node to be stored. */ void storeNode(Node node); /** - * Removes a node from a given parent node, also removing the node from the preferences persistence store. + * Removes a node from a given parent node, also removing the node from the + * preferences persistence store. * - * @param parentNode the parent of the node to be deleted - * @param node the node to be deleted + * @param parentNode + * the parent of the node to be deleted + * @param node + * the node to be deleted */ void removeNode(Node parentNode, Node node); @@ -106,13 +138,16 @@ * value. Options can be set to null if you dont want them included in the * query. * - * @param nodeName the name of the node to lookup, such as 'userinfo' - * @param propertyName the name of the property, such as 'user.email' - * @param propertyValue the value of the property, such as - * 'taylor ¡÷ apache.org' + * @param nodeName + * the name of the node to lookup, such as 'userinfo' + * @param propertyName + * the name of the property, such as 'user.email' + * @param propertyValue + * the value of the property, such as 'taylor ¡÷ apache.org' * @return a collection of found matching elements of type <code>Node</code> */ - Collection lookupPreference(String nodeName, String propertyName, String propertyValue); + Collection lookupPreference(String nodeName, String propertyName, + String propertyValue); /** * Initializes the preferences node Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/om/Node.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/om/Node.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/om/Node.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,133 +17,199 @@ package org.apache.jetspeed.prefs.om; import java.io.Serializable; +import java.sql.Timestamp; import java.util.Collection; -import java.sql.Timestamp; /** - * <p>Interface representing a {@link java.util.prefs.Preferences} - * node.</p> - * + * <p> + * Interface representing a {@link java.util.prefs.Preferences} node. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public interface Node extends Serializable, Cloneable { /** - * <p>Getter for the node id.</p> + * <p> + * Getter for the node id. + * </p> + * * @return The node id. */ long getNodeId(); /** - * <p>Setter for the node id.</p> - * @param nodeId The node id. + * <p> + * Setter for the node id. + * </p> + * + * @param nodeId + * The node id. */ void setNodeId(long nodeId); /** - * <p>Getter for the parent node id.</p> - * <p>Passed as an Integer to be able to pass null if no parent - * is associated to a node.</p> + * <p> + * Getter for the parent node id. + * </p> + * <p> + * Passed as an Integer to be able to pass null if no parent is associated + * to a node. + * </p> + * * @return The parent node id. */ Long getParentNodeId(); /** - * <p>Setter for the parent node id.</p> - * @param parentNodeId The parent node id. + * <p> + * Setter for the parent node id. + * </p> + * + * @param parentNodeId + * The parent node id. */ void setParentNodeId(Long parentNodeId); /** - * <p>Getter for the node properties.</p> + * <p> + * Getter for the node properties. + * </p> + * * @return The node properties. */ Collection getNodeProperties(); /** - * <p>Setter for the node properties.</p> - * @param properties The node properties. + * <p> + * Setter for the node properties. + * </p> + * + * @param properties + * The node properties. */ void setNodeProperties(Collection nodeProperties); /** - * <p>Getter for the keys associated to a specific nodes.</p> + * <p> + * Getter for the keys associated to a specific nodes. + * </p> + * * @return The node keys. */ Collection getNodeKeys(); /** - * <p>Setter for the keys associated to a specific nodes.</p> - * @param nodeKeys The node keys. + * <p> + * Setter for the keys associated to a specific nodes. + * </p> + * + * @param nodeKeys + * The node keys. */ void setNodeKeys(Collection nodeKeys); /** - * <p>Getter for the node name.</p> + * <p> + * Getter for the node name. + * </p> + * * @return The node name. */ - String getNodeName(); + String getNodeName(); /** - * <p>Setter for the node name.</p> - * @param nodeName The node name. + * <p> + * Setter for the node name. + * </p> + * + * @param nodeName + * The node name. */ - void setNodeName(String nodeName); + void setNodeName(String nodeName); /** - * <p>Getter for the node type.</p> + * <p> + * Getter for the node type. + * </p> * <ul> - * <li>0=user,</li> - * <li>1=system,</li> + * <li>0=user,</li> + * <li>1=system,</li> * </ul> + * * @return The node type. */ int getNodeType(); /** - * <p>Setter for the node type.</p> + * <p> + * Setter for the node type. + * </p> * <ul> - * <li>0=user,</li> - * <li>1=system,</li> + * <li>0=user,</li> + * <li>1=system,</li> * </ul> - * @param nodeType The node type. + * + * @param nodeType + * The node type. */ void setNodeType(int nodeType); /** - * <p>Getter for the full path.</p> + * <p> + * Getter for the full path. + * </p> + * * @return The full path. */ String getFullPath(); /** - * <p>Setter for the full path.</p> - * @param fullPath The full path. + * <p> + * Setter for the full path. + * </p> + * + * @param fullPath + * The full path. */ void setFullPath(String fullPath); /** - * <p>Getter for creation date.</p> + * <p> + * Getter for creation date. + * </p> + * * @return The creation date. */ Timestamp getCreationDate(); /** - * <p>Setter for the creation date.</p> - * @param creationDate The creation date. + * <p> + * Setter for the creation date. + * </p> + * + * @param creationDate + * The creation date. */ void setCreationDate(Timestamp creationDate); /** - * <p>Getter for the modified date.</p> + * <p> + * Getter for the modified date. + * </p> + * * @return The modified date. */ Timestamp getModifiedDate(); /** - * <p>Setter for the modified date.</p> - * @param modifiedDate The modified date. + * <p> + * Setter for the modified date. + * </p> + * + * @param modifiedDate + * The modified date. */ void setModifiedDate(Timestamp modifiedDate); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/om/Property.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/om/Property.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/prefs/om/Property.java 2008-05-16 01:54:54 UTC (rev 940) @@ -43,7 +43,8 @@ * Setter for the property value id. * </p> * - * @param propertyValueId The property value id. + * @param propertyValueId + * The property value id. */ void setPropertyValueId(long propertyValueId); @@ -61,7 +62,8 @@ * Setter for the node id. * </p> * - * @param nodeId The node id. + * @param nodeId + * The node id. */ void setNodeId(long nodeId); @@ -79,7 +81,8 @@ * Setter for the property name. * </p> * - * @param propertyName The property name. + * @param propertyName + * The property name. */ void setPropertyName(String propertyName); @@ -98,7 +101,8 @@ * value object type. * </p> * - * @param valueObject The value object. + * @param valueObject + * The value object. */ void setPropertyValue(String valueObject); @@ -116,7 +120,8 @@ * Setter for the creation date. * </p> * - * @param creationDate The creation date. + * @param creationDate + * The creation date. */ void setCreationDate(Timestamp creationDate); @@ -134,7 +139,8 @@ * Setter for the modified date. * </p> * - * @param modifiedDate The modified date. + * @param modifiedDate + * The modified date. */ void setModifiedDate(Timestamp modifiedDate); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/ProfileLocator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/ProfileLocator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/ProfileLocator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,148 +18,196 @@ import java.util.Iterator; -import org.apache.jetspeed.profiler.ProfileLocatorProperty; import org.apache.jetspeed.profiler.rules.RuleCriterion; /** - * <p>Profile Locators are used to locate profiled portal resources such as - * pages, documents, and fragments. A locator contains properties describing - * the actually resource to be located. Since the locator is based on properties + * <p> + * Profile Locators are used to locate profiled portal resources such as pages, + * documents, and fragments. A locator contains properties describing the + * actually resource to be located. Since the locator is based on properties * that are usually related to a user or other subject's profile, it is referred - * to as a profile locator.</p> + * to as a profile locator. + * </p> * - * <p>Profiles can be created from a normalized <i>Profile Locator Path</i> - * The format of the path is name/value pairs of all property, separated by a <i>path separator</i>. - * An example locator path:</p> + * <p> + * Profiles can be created from a normalized <i>Profile Locator Path</i> The + * format of the path is name/value pairs of all property, separated by a + * <i>path separator</i>. An example locator path: + * </p> * - * <pre>page:default.psml:artist:al-stewart:song:on-the-border</pre> - * <pre>path:/sports/football/nfl/chiefs:language:en</pre> + * <pre> + * page:default.psml:artist:al-stewart:song:on-the-border + * </pre> + * <pre> + * path:/sports/football/nfl/chiefs:language:en + * </pre> * - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: ProfileLocator.java 516448 2007-03-09 16:25:47Z ate $ */ -public interface ProfileLocator +public interface ProfileLocator { + public final static String PAGE_LOCATOR = "page"; + public final static String SECURITY_LOCATOR = "security"; public final static String PATH_SEPARATOR = ":"; - + /** * Initialize this page context. - * - * @param profiler The profiler initializing this locator. - * @param requestPath The request path used to create this locator. + * + * @param profiler + * The profiler initializing this locator. + * @param requestPath + * The request path used to create this locator. */ void init(Profiler profiler, String requestPath); /** - * Get an iterator over the locator's properties. - * Elements are returned as @link ProfileLocatorProperty array. - * + * Get an iterator over the locator's properties. Elements are returned as + * + * @link ProfileLocatorProperty array. + * * @return an iterator over the profile locator properties */ - Iterator iterator(); - + Iterator iterator(); + /** - * Add a property based on a @link org.apache.jetspeed.profiler.rules.RuleCriterion - * and a value. Rule criteria are templates for locating profile properties. - * The value is combined with the rule to create a property. + * Add a property based on a * - * @param criterion The rule criterion on which this property is based. - * @param isControl The control classification for property. - * @param isNavigation The navigation classification for property. - * @param value The value to set on the property. - */ - void add(RuleCriterion criterion, boolean isControl, boolean isNavigation, String value); + * @link org.apache.jetspeed.profiler.rules.RuleCriterion and a value. Rule + * criteria are templates for locating profile properties. The value + * is combined with the rule to create a property. + * + * @param criterion + * The rule criterion on which this property is based. + * @param isControl + * The control classification for property. + * @param isNavigation + * The navigation classification for property. + * @param value + * The value to set on the property. + */ + void add(RuleCriterion criterion, boolean isControl, boolean isNavigation, + String value); /** * Add a property based on a Simple name and value. * - * @param name The name of the property. - * @param isControl The control classification for property. - * @param isNavigation The control classification for property. - * @param value The value to set on the property. - */ + * @param name + * The name of the property. + * @param isControl + * The control classification for property. + * @param isNavigation + * The control classification for property. + * @param value + * The value to set on the property. + */ void add(String name, boolean isControl, boolean isNavigation, String value); - + /** - * Add a property based on a Simple name and value assumed - * to be control property. + * Add a property based on a Simple name and value assumed to be control + * property. * - * @param name The name of the property. - * @param value The value to set on the property. - */ + * @param name + * The name of the property. + * @param value + * The value to set on the property. + */ void add(String name, String value); - + /** - * For a given property name, get a property of type @link ProfileLocatorProperty - * - * @param name The name of the property - * @return a property of type @link ProfileLocatorProperty + * For a given property name, get a property of type + * + * @link ProfileLocatorProperty + * + * @param name + * The name of the property + * @return a property of type + * @link ProfileLocatorProperty */ String getValue(String name); - + /** * For a given property name, return control status of property. - * - * @param name The name of the property + * + * @param name + * The name of the property * @return control classification flag */ boolean isControl(String name); /** * For a given property name, return navigation status of property. - * - * @param name The name of the property + * + * @param name + * The name of the property * @return navigation classification flag */ boolean isNavigation(String name); - + /** - * <p>Profiles can be created from a normalized <i>Profile Locator Path</i> - * The format of the path is name:value pairs of all property, separated by a <i>path separator</i>. - * Note: all locator property elements are assumed to be control properties. - * An example locator path:</p> + * <p> + * Profiles can be created from a normalized <i>Profile Locator Path</i> + * The format of the path is name:value pairs of all property, separated by + * a <i>path separator</i>. Note: all locator property elements are assumed + * to be control properties. An example locator path: + * </p> * - * <pre>:page:default.psml:artist:air:song:all-i-need</pre> + * <pre> + * :page:default.psml:artist:air:song:all-i-need + * </pre> * - * @param path The normalized path as shown above from which the locator is created. + * @param path + * The normalized path as shown above from which the locator is + * created. */ void createFromLocatorPath(String path); - + /** - * <p>Profiles can be converted to a normalized <i>Profile Locator Path</i> - * The format of the path is name/value pairs of all property, separated by a <i>path separator</i>. - * An example locator path:</p> + * <p> + * Profiles can be converted to a normalized <i>Profile Locator Path</i> + * The format of the path is name/value pairs of all property, separated by + * a <i>path separator</i>. An example locator path: + * </p> * - * <pre>:page:default.psml:artist:joni-mitchell:song:cary</pre> + * <pre> + * :page:default.psml:artist:joni-mitchell:song:cary + * </pre> * * @return The normalized path as shown above. */ String getLocatorPath(); - + /** - * <p>Normalize profile properties obtained from profile locator iterators - * into a <i>Profile Locator Path</i>.</p> + * <p> + * Normalize profile properties obtained from profile locator iterators into + * a <i>Profile Locator Path</i>. + * </p> * - * @param properties The array of profile properties. + * @param properties + * The array of profile properties. * @return The normalized path for properties. */ - String getLocatorPath(ProfileLocatorProperty [] properties); - + String getLocatorPath(ProfileLocatorProperty[] properties); + /** - * Returns a normalized path. @see #getLocatorPath() + * Returns a normalized path. * + * @see #getLocatorPath() + * * @return The normalized path representation of this locator. */ String toString(); - + /** - * <p>Locators are intended to be sufficient to locate managed pages, so the request - * path must be generally available in the event it is not otherwise captured in a - * rule criterion.</p> + * <p> + * Locators are intended to be sufficient to locate managed pages, so the + * request path must be generally available in the event it is not otherwise + * captured in a rule criterion. + * </p> * * @return The request path. */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/ProfileLocatorProperty.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/ProfileLocatorProperty.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/ProfileLocatorProperty.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,29 +18,30 @@ /** * ProfileLocatorElement - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: ProfileLocatorProperty.java 516448 2007-03-09 16:25:47Z ate $ */ public interface ProfileLocatorProperty -{ +{ + /** * Gets the value of the locator property. * * @return The value of the property. */ String getValue(); - + /** * Sets the value of the locator property. - * @param value The value of the property. + * + * @param value + * The value of the property. */ void setValue(String value); - /** - * Returns the fallback type of the property. - * see + * Returns the fallback type of the property. see * * @return */ @@ -65,17 +66,17 @@ * @param string */ void setName(String string); - + /** * @param string */ - void setType(String type); + void setType(String type); /** * @return control classification flag */ boolean isControl(); - + /** * @return true if a property is a navigation */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/Profiler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/Profiler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/Profiler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,71 +26,85 @@ import org.apache.jetspeed.request.RequestContext; /** - * ProfilerService - * Jetspeed-2 Profiler service. - * Locates portal resources given a set of request parameters, properties, and attributes - * The Profiler is invoked during the request processing pipeline. - * It requires that the request context is already populated with the portal request and response, - * and capability and user information. The request context parameters, properties and attributes - * make up the profile criterion which the profiler uses to locate portal resources: - * 1. page - * 2. navigations - * 3. document lists + * ProfilerService Jetspeed-2 Profiler service. Locates portal resources given a + * set of request parameters, properties, and attributes The Profiler is invoked + * during the request processing pipeline. It requires that the request context + * is already populated with the portal request and response, and capability and + * user information. The request context parameters, properties and attributes + * make up the profile criterion which the profiler uses to locate portal + * resources: 1. page 2. navigations 3. document lists * - * In all cases, a fallback algorithm should be applied to fallback - * to default portal resources. - * + * In all cases, a fallback algorithm should be applied to fallback to default + * portal resources. + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: Profiler.java 516881 2007-03-11 10:34:21Z ate $ */ public interface Profiler { - - + /** - * Get the Profile object using the request parameters. - * - * @param context The request context - * @param locatorName The name of the profile locator to find i.e. "page", "docset", ... - * @return a new Profile Locator object or null if failed to find a appropriate locator. + * Get the Profile object using the request parameters. + * + * @param context + * The request context + * @param locatorName + * The name of the profile locator to find i.e. "page", "docset", + * ... + * @return a new Profile Locator object or null if failed to find a + * appropriate locator. */ - ProfileLocator getProfile(RequestContext context, String locatorName) throws ProfilerException; - + ProfileLocator getProfile(RequestContext context, String locatorName) + throws ProfilerException; + /** * * <p> * getDefaultProfile * </p> - * Intstead of using the princpal found within the request, the DEFAULT_RULE_PRINCIPAL is used. - * - * @param context The request context - * @param locatorName The name of the profile locator to find i.e. "page", "docset", ... - * @return a new Profile Locator object or null if failed to find a appropriate locator. + * Intstead of using the princpal found within the request, the + * DEFAULT_RULE_PRINCIPAL is used. + * + * @param context + * The request context + * @param locatorName + * The name of the profile locator to find i.e. "page", "docset", + * ... + * @return a new Profile Locator object or null if failed to find a + * appropriate locator. */ - ProfileLocator getDefaultProfile(RequestContext context, String locatorName) throws ProfilerException; + ProfileLocator getDefaultProfile(RequestContext context, String locatorName) + throws ProfilerException; /** - * Get the Profile object using the request parameters and the rule. - * - * @param context The request context - * @return a new Profile Locator object or null if failed to find a appropriate locator. - */ - ProfileLocator getProfile(RequestContext context, ProfilingRule rule) throws ProfilerException; - + * Get the Profile object using the request parameters and the rule. + * + * @param context + * The request context + * @return a new Profile Locator object or null if failed to find a + * appropriate locator. + */ + ProfileLocator getProfile(RequestContext context, ProfilingRule rule) + throws ProfilerException; + /** - * Creates a new ProfileLocator object that can be managed by - * the current Profiler implementation - * - * @param context The request context - * @return A new ProfileLocator object - */ + * Creates a new ProfileLocator object that can be managed by the current + * Profiler implementation + * + * @param context + * The request context + * @return A new ProfileLocator object + */ ProfileLocator createLocator(RequestContext context); - + /** - * For a given principal, lookup the associated profiling rule to that principal name. + * For a given principal, lookup the associated profiling rule to that + * principal name. * - * @param principal Lookup the profiling rule based on this principal. - * @param locatorName the unique name of a locator for this principal/rule/locator + * @param principal + * Lookup the profiling rule based on this principal. + * @param locatorName + * the unique name of a locator for this principal/rule/locator * @return The rule found or null if not found */ ProfilingRule getRuleForPrincipal(Principal principal, String locatorName); @@ -234,10 +248,9 @@ */ public RuleCriterion createRuleCriterion() throws ClassNotFoundException; - - /** * Resets the default rule for this portal + * * @param defaultRule * The default rule to set. */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/ProfilerException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/ProfilerException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/ProfilerException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,30 +20,31 @@ /** * ProfilerException - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: ProfilerException.java 516448 2007-03-09 16:25:47Z ate $ */ public class ProfilerException extends JetspeedException { - public ProfilerException() + + public ProfilerException() { super(); } - public ProfilerException( String message ) + public ProfilerException(String message) { - super( message ); + super(message); } public ProfilerException(Throwable nested) { super(nested); } - + public ProfilerException(String msg, Throwable nested) { super(msg, nested); } - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/PrincipalRule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/PrincipalRule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/PrincipalRule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,67 +19,73 @@ import java.io.Serializable; /** - * PrincipalRule is a paired association from principal to rule. - * This pair is unique in that there can only be a one entry for a principal which maps to a rule. - * This association is used by the profiler to determine which profiling rule to apply for a principal. - * If a rule is not found, there should be a default system wide rule. - * + * PrincipalRule is a paired association from principal to rule. This pair is + * unique in that there can only be a one entry for a principal which maps to a + * rule. This association is used by the profiler to determine which profiling + * rule to apply for a principal. If a rule is not found, there should be a + * default system wide rule. + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: PrincipalRule.java 516448 2007-03-09 16:25:47Z ate $ */ public interface PrincipalRule extends Serializable { + /** - * Gets the name of the principal in this principal/rule/locator pair association. - * The principal name identifies the uniqueness of the relationship. - * It is used for keyed lookups to find the rule associated with this principal. - * + * Gets the name of the principal in this principal/rule/locator pair + * association. The principal name identifies the uniqueness of the + * relationship. It is used for keyed lookups to find the rule associated + * with this principal. + * * @return The name of the principal in this association. - */ + */ String getPrincipalName(); /** - * Sets the name of the principal in this principal/rule/locator pair association. - * The principal name identifies the uniqueness of the relationship. - * It is used for keyed lookups to find the rule associated with this principal. - * - * @param name The name of the principal in this association. - */ + * Sets the name of the principal in this principal/rule/locator pair + * association. The principal name identifies the uniqueness of the + * relationship. It is used for keyed lookups to find the rule associated + * with this principal. + * + * @param name + * The name of the principal in this association. + */ void setPrincipalName(String name); /** - * Gets the name of the locator in this principal/rule/locator pair association. - * The principal + locator name identifies the uniqueness of the relationship. - * It is used for keyed lookups to find the rule associated with this principal - * for a given locator - * + * Gets the name of the locator in this principal/rule/locator pair + * association. The principal + locator name identifies the uniqueness of + * the relationship. It is used for keyed lookups to find the rule + * associated with this principal for a given locator + * * @return The name of the locator in this association. - */ + */ String getLocatorName(); /** - * Sets the name of the locator in this principal/locator/rule pair association. - * The principal name + locator name identifies the uniqueness of the relationship. - * It is used for keyed lookups to find the rule associated with this principal - * for a given locator - * - * @param name The name of the locator in this association. - */ + * Sets the name of the locator in this principal/locator/rule pair + * association. The principal name + locator name identifies the uniqueness + * of the relationship. It is used for keyed lookups to find the rule + * associated with this principal for a given locator + * + * @param name + * The name of the locator in this association. + */ void setLocatorName(String name); - - + /** - * Gets the profiling rule associated with the principal name + * Gets the profiling rule associated with the principal name * * @return The profiling rule associated with the principal name */ ProfilingRule getProfilingRule(); /** - * Sets the profiling rule associated with the principal name + * Sets the profiling rule associated with the principal name * - * @param rule The profiling rule associated with the principal name + * @param rule + * The profiling rule associated with the principal name */ void setProfilingRule(ProfilingRule rule); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/ProfileResolvers.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/ProfileResolvers.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/ProfileResolvers.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,13 +20,15 @@ /** * Spring component to hold criterion resolvers for building profiling rules. - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: PrincipalRule.java 188415 2005-03-23 22:15:25Z ate $ */ -public interface ProfileResolvers +public interface ProfileResolvers { + RuleCriterionResolver get(String resolverName); + /** * return the map of resolver */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/ProfilingRule.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/ProfilingRule.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/ProfilingRule.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,87 +18,108 @@ import java.io.Serializable; import java.util.Collection; + import org.apache.jetspeed.profiler.ProfileLocator; import org.apache.jetspeed.profiler.Profiler; import org.apache.jetspeed.request.RequestContext; /** - * A ProfilingRule defines a list of criteria used when evaluating a request - * to determine the location of a specific resource. Profiling rules are - * used by the Profiler Service to generically locate portal resources - * based on the decoupled criteria for known portlet request data. - * A rule consists of an ordered list of criteria which should be applied - * in the given order of the SortedMap provided by this rule. - * Following this order, fallback searches may be applied to find resources - * using a less-specific algorithm until the least specific resource criterion - * is considered. When all criteria are exhausted, the rule will fail. - * + * A ProfilingRule defines a list of criteria used when evaluating a request to + * determine the location of a specific resource. Profiling rules are used by + * the Profiler Service to generically locate portal resources based on the + * decoupled criteria for known portlet request data. A rule consists of an + * ordered list of criteria which should be applied in the given order of the + * SortedMap provided by this rule. Following this order, fallback searches may + * be applied to find resources using a less-specific algorithm until the least + * specific resource criterion is considered. When all criteria are exhausted, + * the rule will fail. + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: ProfilingRule.java 516448 2007-03-09 16:25:47Z ate $ */ public interface ProfilingRule extends Serializable { - + /** - * Define the basic supported rule types in the default Jetspeed implementation. - * Other rule types can be added. - * Rule types define a grouping of rule parameters. - * For example, request parameters refer to parameters on the request - */ - - /** Standard rule criteria used by Jetspeed traditionally such as media type, language, username, role */ + * Define the basic supported rule types in the default Jetspeed + * implementation. Other rule types can be added. Rule types define a + * grouping of rule parameters. For example, request parameters refer to + * parameters on the request + */ + + /** + * Standard rule criteria used by Jetspeed traditionally such as media type, + * language, username, role + */ public final static String STANDARD = "standard"; - /** Request parameters as defined in the Portlet spec 1.0 PLT.11.1.1 */ + + /** Request parameters as defined in the Portlet spec 1.0 PLT.11.1.1 */ public final static String REQUEST_PARAMETER = "request"; + /** Request attributes as defined in the Portlet spec 1.0 PLT.11.1.3 */ public final static String REQUEST_ATTRIBUTE = "attribute"; - /** Session Attribute */ + + /** Session Attribute */ public final static String SESSION_ATTRIBUTE = "session"; + /** User attributes as defined in the Portlet spec 1.0 PLT.17 */ public final static String USER_ATTRIBUTE = "user"; - /** Composite Capabilities and Preference Profile as defined http://www.w3.org/TR/NOTE-CCPP/ */ + + /** + * Composite Capabilities and Preference Profile as defined + * http://www.w3.org/TR/NOTE-CCPP/ + */ public final static String CCPP_PROPERTY = "ccpp"; - + /** * Standard properties used traditionally in Jetspeed */ public final static String STANDARD_PAGE = "page"; - public final static String STANDARD_GROUP_ROLE_USER = "group.role.user"; + + public final static String STANDARD_GROUP_ROLE_USER = "group.role.user"; + public final static String STANDARD_USER = "user"; + public final static String STANDARD_GROUP = "group"; + public final static String STANDARD_ROLE = "role"; + public final static String STANDARD_MEDIATYPE = "mediatype"; + public final static String STANDARD_COUNTRY = "country"; + public final static String STANDARD_LANGUAGE = "language"; + public final static String STANDARD_ROLE_FALLBACK = "roles"; /** * Given a criterion name, look up a value resolver * - * @param name The name of the criterion + * @param name + * The name of the criterion * @return */ - RuleCriterionResolver getResolver(String name); - + RuleCriterionResolver getResolver(String name); + /** - * Applying the profiling rule generates a generic profile locator. - * With this locator we can then locate a profiling resource. + * Applying the profiling rule generates a generic profile locator. With + * this locator we can then locate a profiling resource. * * @param context * @param service * @return */ ProfileLocator apply(RequestContext context, Profiler service); - + /** - * Returns a sorted map (ordered) of rule criteria. - * Each criteria consists of a normalized property/attribute/parameter - * associated with a request type. + * Returns a sorted map (ordered) of rule criteria. Each criteria consists + * of a normalized property/attribute/parameter associated with a request + * type. * * @return a sorted map of rule criteria. - */ + */ Collection getRuleCriteria(); - + /** * Gets the unique identifier for this rule * @@ -109,41 +130,47 @@ /** * Sets the unique identifier for this rule * - * @param id The unique identifier - */ + * @param id + * The unique identifier + */ void setId(String id); - + /** * Gets the title used for with the rule for displaying descriptive text. * * @return The title of this rule. */ String getTitle(); - + /** * Set the title used for with the rule for displaying descriptive text. * - * @param title The title of this rule. + * @param title + * The title of this rule. */ void setTitle(String title); - + /** - * Get the implementing classname of this rule from the database. - * The class must exist in the hiearchy and in fact refers to itself when instantiated. + * Get the implementing classname of this rule from the database. The class + * must exist in the hiearchy and in fact refers to itself when + * instantiated. * * @return The classname of this instance. */ String getClassname(); - + /** - * Sets the implementing classname of this rule from the database. - * The class must exist in the hiearchy and in fact refers to itself when instantiated. + * Sets the implementing classname of this rule from the database. The class + * must exist in the hiearchy and in fact refers to itself when + * instantiated. * - * @param classname The classname of this instance. + * @param classname + * The classname of this instance. */ void setClassname(String classname); - + ProfileResolvers getResolvers(); + void setResolvers(ProfileResolvers resolvers); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/RuleCriterion.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/RuleCriterion.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/RuleCriterion.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,130 +20,143 @@ /** * A RuleCriterion specifies one criterion in a list of profiling rule criteria. - * This list is used to build normalized profiling locator and then - * locate a portal resource based on the request. - * + * This list is used to build normalized profiling locator and then locate a + * portal resource based on the request. + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: RuleCriterion.java 516448 2007-03-09 16:25:47Z ate $ */ public interface RuleCriterion extends Serializable { + public static final int FALLBACK_CONTINUE = 1; + public static final int FALLBACK_STOP = 0; + public static final int FALLBACK_LOOP = 2; - + /** - * Gets the rule request type for this specific criterion. - * Rule types determine which type of request property, parameter or attribute - * to look at when building a profiling locator. - * + * Gets the rule request type for this specific criterion. Rule types + * determine which type of request property, parameter or attribute to look + * at when building a profiling locator. + * * @return The request type associated with this criterion. */ String getType(); /** - * Sets the rule request type for this specific criterion. - * Rule types determine which type of request property, parameter or attribute - * to look at when building a profiling locator. - * - * @param The request type associated with this criterion. - */ + * Sets the rule request type for this specific criterion. Rule types + * determine which type of request property, parameter or attribute to look + * at when building a profiling locator. + * + * @param The + * request type associated with this criterion. + */ void setType(String type); /** - * Sets the fallback order for this criterion. - * Lower numbers are returned first during iteration. - * Higher numbers should be put on the locator stack first. + * Sets the fallback order for this criterion. Lower numbers are returned + * first during iteration. Higher numbers should be put on the locator stack + * first. * * @return The fallback order for this criterion. */ int getFallbackOrder(); - - + /** - * Gets the fallback order for this criterion. - * Lower numbers are returned first during iteration. - * Higher numbers should be put on the locator stack first. + * Gets the fallback order for this criterion. Lower numbers are returned + * first during iteration. Higher numbers should be put on the locator stack + * first. * - * @param order The fallback order for this criterion. + * @param order + * The fallback order for this criterion. */ void setFallbackOrder(int order); /** - * Gets the fallback type for this criterion. - * Fallback types are used when locating a profiled resource. - * The type tells the Profiling rule what to do next on failed criterion matching. + * Gets the fallback type for this criterion. Fallback types are used when + * locating a profiled resource. The type tells the Profiling rule what to + * do next on failed criterion matching. * * Known values: * - * FALLBACK_CONTINUE - evaluate this criterion and if it fails continue to the next criterion - * FALLBACK_STOP - evaluate this criterion and if it fails stop evaluation criteria for this rule - * FALLBACK_LOOP - evaluate this criterion and if it fails continue evaluating + * FALLBACK_CONTINUE - evaluate this criterion and if it fails continue to + * the next criterion FALLBACK_STOP - evaluate this criterion and if it + * fails stop evaluation criteria for this rule FALLBACK_LOOP - evaluate + * this criterion and if it fails continue evaluating * - * @return The fallback type for this criterion, should be a valid value as shown above. + * @return The fallback type for this criterion, should be a valid value as + * shown above. */ int getFallbackType(); /** - * Sets the fallback type for this criterion. - * Fallback types are used when locating a profiled resource. - * The type tells the Profiling rule what to do next on failed criterion matching. + * Sets the fallback type for this criterion. Fallback types are used when + * locating a profiled resource. The type tells the Profiling rule what to + * do next on failed criterion matching. * * Known values: * - * FALLBACK_CONTINUE - evaluate this criterion and if it fails continue to the next criterion - * FALLBACK_STOP - evaluate this criterion and if it fails stop evaluation criteria for this rule - * FALLBACK_LOOP - evaluate this criterion and if it fails continue evaluating + * FALLBACK_CONTINUE - evaluate this criterion and if it fails continue to + * the next criterion FALLBACK_STOP - evaluate this criterion and if it + * fails stop evaluation criteria for this rule FALLBACK_LOOP - evaluate + * this criterion and if it fails continue evaluating * - * @param The fallback type for this criterion, should be a valid value as shown above. - */ + * @param The + * fallback type for this criterion, should be a valid value as + * shown above. + */ void setFallbackType(int order); - + /** - * Gets the name of the parameter, attribute or property in the portal request. - * This name is used to lookup the value of the request parameter, attribute, or - * property when building a profile locator. - * + * Gets the name of the parameter, attribute or property in the portal + * request. This name is used to lookup the value of the request parameter, + * attribute, or property when building a profile locator. + * * @return The name of the request parameter, attribute or property. - */ + */ String getName(); /** - * Sets the name of the parameter, attribute or property in the portal request. - * This name is used to lookup the value of the request parameter, attribute, or - * property when building a profile locator. - * - * @param The name of the request parameter, attribute or property. - */ + * Sets the name of the parameter, attribute or property in the portal + * request. This name is used to lookup the value of the request parameter, + * attribute, or property when building a profile locator. + * + * @param The + * name of the request parameter, attribute or property. + */ void setName(String name); - /** - * Gets the value of the parameter, attribute or property in the portal request. - * + * Gets the value of the parameter, attribute or property in the portal + * request. + * * @return The value of the request parameter, attribute or property. - */ + */ String getValue(); /** - * Sets the value of the parameter, attribute or property in the portal request. - * - * @param The value of the request parameter, attribute or property. - */ + * Sets the value of the parameter, attribute or property in the portal + * request. + * + * @param The + * value of the request parameter, attribute or property. + */ void setValue(String value); /** - * Gets the unique rule identifier for the associated owner rule + * Gets the unique rule identifier for the associated owner rule * * @return The rule's unique identifier */ String getRuleId(); /** - * Sets the unique rule identifier for the associated owner rule + * Sets the unique rule identifier for the associated owner rule * - * @param id The rule's unique identifier - */ + * @param id + * The rule's unique identifier + */ void setRuleId(String ruleId); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/RuleCriterionResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/RuleCriterionResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/profiler/rules/RuleCriterionResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,90 +21,99 @@ import org.apache.jetspeed.request.RequestContext; /** - * Resolves rule criterion based on a single criterion and - * runtime request context state. Note all resolvers should - * look at the criterion's value if they fail to find it + * Resolves rule criterion based on a single criterion and runtime request + * context state. Note all resolvers should look at the criterion's value if + * they fail to find it * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: RuleCriterionResolver.java 516448 2007-03-09 16:25:47Z ate $ */ public interface RuleCriterionResolver extends Serializable -{ - /** resolve the parameter via the request parameter, then value */ +{ + + /** resolve the parameter via the request parameter, then value */ public static final String REQUEST = "request"; /** resolve the parameter via a session attribute */ public static final String SESSION = "session"; - + /** look in the request first, then session */ public static final String REQUEST_SESSION = "request.session"; - + /** look at hard-coded criterion value only */ - public final static String HARD_CODED = "hard.coded"; - + public final static String HARD_CODED = "hard.coded"; + /** look for group, then role, then user */ public final static String GROUP_ROLE_USER = "group.role.user"; - /** first check request parameter, then check user in the request context */ + /** first check request parameter, then check user in the request context */ public final static String USER = "user"; - - /** first check request parameter, then check group in the request context */ + + /** first check request parameter, then check group in the request context */ public final static String GROUP = "group"; - - /** first check request parameter, then check role in the request context */ + + /** first check request parameter, then check role in the request context */ public final static String ROLE = "role"; - - /** first check request parameter, then check media type in the request context */ + + /** + * first check request parameter, then check media type in the request + * context + */ public final static String MEDIATYPE = "mediatype"; - - /** first check request parameter, then check country code in the request context */ + + /** + * first check request parameter, then check country code in the request + * context + */ public final static String COUNTRY = "country"; - /** first check request parameter, then user agent in the request context */ + /** first check request parameter, then user agent in the request context */ public final static String USER_AGENT = "user.agent"; - - /** first check request parameter, then check language in the request context */ + + /** first check request parameter, then check language in the request context */ public final static String LANGUAGE = "language"; - + public final static String ROLE_FALLBACK = "roles"; - /** resolve the parameter via the request path, then value */ + /** resolve the parameter via the request path, then value */ public static final String PATH = "path"; - /** resolve the parameter via the request path, then value */ + /** resolve the parameter via the request path, then value */ public static final String PAGE = "page"; - + /** look in the request path first, then session */ public static final String PATH_SESSION = "path.session"; - + /** look in user attributes */ public static final String USER_ATTRIBUTE = "user.attribute"; - + /** change the current navigation path */ public static final String NAVIGATION = "navigation"; - + /** * Resolver the value for a criterion. * - * @param context The request context. - * @param criterion The criterion being evaluated. - * @return The value of the criterion or null if not found. - * Returns null to indicate to subclasses to continue processing. - */ + * @param context + * The request context. + * @param criterion + * The criterion being evaluated. + * @return The value of the criterion or null if not found. Returns null to + * indicate to subclasses to continue processing. + */ String resolve(RequestContext context, RuleCriterion criterion); - + /** * Gets the control classification of the resolver. * * @return The control class flag - */ + */ boolean isControl(RuleCriterion criterion); /** * Gets the navigation classification of the resolver. * * @return The control class flag - */ + */ boolean isNavigation(RuleCriterion criterion); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/request/RequestContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/request/RequestContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/request/RequestContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -39,352 +39,372 @@ /** * Portal Request Context is associated with each request - * + * * @author <a href="mailto:david ¡÷ bluesunrise.com">David Sean Taylor</a> * @version $Id: RequestContext.java,v 1.14 2005/04/29 14:00:48 weaver Exp $ */ public interface RequestContext { + public final static String REQUEST_PORTALENV = PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE; /** - * Gets the HTTP Servlet Request. This is the Servlet - * containers raw request object. This request should - * be wrapped using <code>getPortletRequestForWindow()</code> before - * being processed by the portlet container. - * + * Gets the HTTP Servlet Request. This is the Servlet containers raw request + * object. This request should be wrapped using + * <code>getPortletRequestForWindow()</code> before being processed by the + * portlet container. + * * @return HttpServletRequest */ public HttpServletRequest getRequest(); /** - * Sets the HTTP Servlet Request. This is the Servlet - * containers raw request object. This request should - * be wrapped using <code>getPortletRequestForWindow()</code> before - * being processed by the portlet container. - * + * Sets the HTTP Servlet Request. This is the Servlet containers raw request + * object. This request should be wrapped using + * <code>getPortletRequestForWindow()</code> before being processed by the + * portlet container. + * * @return HttpServletRequest - */ + */ public void setRequest(HttpServletRequest request); - + /** - * Gets the HTTP Servlet Response. This is the Servlet - * containers raw response object. This response should - * be wrapped using <code>getPortletResponseForWindow()</code> before - * being processed by the portlet container. + * Gets the HTTP Servlet Response. This is the Servlet containers raw + * response object. This response should be wrapped using + * <code>getPortletResponseForWindow()</code> before being processed by + * the portlet container. + * * @return HttpServletResponse */ public HttpServletResponse getResponse(); /** - * Sets the HTTP Servlet Response. This is the Servlet - * containers raw response object. This response should - * be wrapped using <code>getPortletResponseForWindow()</code> before - * being processed by the portlet container. + * Sets the HTTP Servlet Response. This is the Servlet containers raw + * response object. This response should be wrapped using + * <code>getPortletResponseForWindow()</code> before being processed by + * the portlet container. + * * @return HttpServletResponse - */ + */ public void setResponse(HttpServletResponse response); - + /** * Gets the HTTP Servlet Config - * + * * @return ServletConfig */ public ServletConfig getConfig(); /** * Gets the profile locators for this request - * + * * @return Profile locators by locator name */ public Map getProfileLocators(); /** * Sets the target page profile locators for this request - * - * @param locators The target profile locators by locator name + * + * @param locators + * The target profile locators by locator name */ public void setProfileLocators(Map locators); /** * Gets the target page for this request - * + * * @return Page */ public ContentPage getPage(); /** - * Sets the target page for this request - * - * @param page The target page + * Sets the target page for this request + * + * @param page + * The target page */ public void setPage(ContentPage page); /** * Gets the content dispatcher for this request - * + * * @return ContentDispatcher */ public ContentDispatcher getContentDispatcher(); /** * Sets the content dispatcher for this request - * - * @param dispatcher The ContentDispatcher to use for this request + * + * @param dispatcher + * The ContentDispatcher to use for this request */ public void setContentDispatcher(ContentDispatcher dispatcher); /** * Set the capabilityMap. Used by the CapabilityValve - * + * * @param capabilityMap */ public void setCapabilityMap(CapabilityMap map); /** * Get the Capability Map - * + * */ public CapabilityMap getCapabilityMap(); /** * Set the Mimetype. Set by the CapabilityValve - * + * * @param mimeType */ public void setMimeType(String mimeType); /** * Get the mimeType for the request - * + * */ public String getMimeType(); /** * Set the mediaType. Set by the CapabilityValve - * + * * @param mediaType */ public void setMediaType(String mediaType); /** * get the Media Type - * + * */ public String getMediaType(); - + /** * Gets the Portal URL for the current request. * - * @return The Portal URL object for the current request. This method will never - * return a <code>null</code> value. - * @throws IllegalStateException if <code>portalUrl</code> - * if has not been set. + * @return The Portal URL object for the current request. This method will + * never return a <code>null</code> value. + * @throws IllegalStateException + * if <code>portalUrl</code> if has not been set. */ public PortalURL getPortalURL(); - + /** * Sets the Portal URL for the current request. * - * @throws IllegalStateException if <code>portalUrl</code> - * has been set already. - * @throws IllegalArgumentException if a null value is passed in. + * @throws IllegalStateException + * if <code>portalUrl</code> has been set already. + * @throws IllegalArgumentException + * if a null value is passed in. */ public void setPortalURL(PortalURL portalUrl); - + /** * Get the target Action Window - * + * * @return PortletWindow The target portlet action window */ public PortletWindow getActionWindow(); /** * Sets the target Portlet Window - * + * * @param window */ public void setActionWindow(PortletWindow window); /** * get the character encoding - * - * + * + * */ public String getCharacterEncoding(); /** * set character encoding - * + * * @param enc */ public void setCharacterEncoding(String enc); /** - * + * * <p> * getRequestForWindow * </p> - * - * Takes a PortletWindow and generates a HttpServletRequest that - * accurately represents that PortletWindow's request parameters - * - * - * @param window PortletWindow that we are build a request for - * @return HttpServletRequest that wraps the existing servlet - * container's request that can interpret encoded portlet information - * for this PortletWindow - * + * + * Takes a PortletWindow and generates a HttpServletRequest that accurately + * represents that PortletWindow's request parameters + * + * + * @param window + * PortletWindow that we are build a request for + * @return HttpServletRequest that wraps the existing servlet container's + * request that can interpret encoded portlet information for this + * PortletWindow + * */ HttpServletRequest getRequestForWindow(PortletWindow window); /** - * + * * <p> * getResponseForWindow * </p> - * - * Takes a PortletWindow and generates a HttpServletResponse that - * accurately represents that PortletWindow's request parameters. - * - * - * @param window PortletWindow that we are build a response for - * @return HttpServletRequest that wraps the existing servlet - * container's request that can interpret encoded portlet information - * for this PortletWindow - * - * + * + * Takes a PortletWindow and generates a HttpServletResponse that accurately + * represents that PortletWindow's request parameters. + * + * + * @param window + * PortletWindow that we are build a response for + * @return HttpServletRequest that wraps the existing servlet container's + * request that can interpret encoded portlet information for this + * PortletWindow + * + * */ HttpServletResponse getResponseForWindow(PortletWindow window); /** - * Gets the subject associated with the authorized entity. - * This subject can be used to provide credentials and principals. - * + * Gets the subject associated with the authorized entity. This subject can + * be used to provide credentials and principals. + * * @return The JAAS subject on this request. */ Subject getSubject(); /** - * Sets the subject associated with the authorized entity. - * This subject can be used to provide credentials and principals. - * - * @param subject The JAAS subject on this request. + * Sets the subject associated with the authorized entity. This subject can + * be used to provide credentials and principals. + * + * @param subject + * The JAAS subject on this request. */ void setSubject(Subject subject); /** * Gets the locale associated with this request. - * + * * @return The locale associated with this request. */ Locale getLocale(); /** * Sets the locale associated with this request. - * - * @param The locale associated with this request. + * + * @param The + * locale associated with this request. */ void setLocale(Locale locale); /** * Use this method to get a request parameter on the generalized request, - * decoupling request parameter manipulation from servlet API. - * This parameter could be on the Http Servlet request, - * in that case it simply passes through to the servlet request. - * - * @param key The parameter unique key + * decoupling request parameter manipulation from servlet API. This + * parameter could be on the Http Servlet request, in that case it simply + * passes through to the servlet request. + * + * @param key + * The parameter unique key * @return The object associated with the uniqu */ String getRequestParameter(String key); /** - * Use this method to get a map of request parameters on the generalized request, - * decoupling request parameter manipulation from servlet API. - * The parameters returned could be on the Http Servlet request, - * in that case it simply passes through to the servlet request. - * + * Use this method to get a map of request parameters on the generalized + * request, decoupling request parameter manipulation from servlet API. The + * parameters returned could be on the Http Servlet request, in that case it + * simply passes through to the servlet request. + * * @return */ Map getParameterMap(); - /** - * Gets an attribute from the session. - * This method is decoupled from the servlet api request to - * facilitate abstractions for testing and other programs not - * connected to a servlet application. - * - * @param key The key of the attribute + * Gets an attribute from the session. This method is decoupled from the + * servlet api request to facilitate abstractions for testing and other + * programs not connected to a servlet application. + * + * @param key + * The key of the attribute * @return The value of the attribute */ Object getSessionAttribute(String key); /** - * Sets an attribute into the session. - * This method is decoupled from the servlet api request to - * facilitate abstractions for testing and other programs not - * connected to a servlet application. - * - * @param key The key of the session attribute - * @param value The value of the session attribute + * Sets an attribute into the session. This method is decoupled from the + * servlet api request to facilitate abstractions for testing and other + * programs not connected to a servlet application. + * + * @param key + * The key of the session attribute + * @param value + * The value of the session attribute */ void setSessionAttribute(String key, Object value); /** * Get a request attribute associated with this single request. - * - * @param key The key of the request attribute + * + * @param key + * The key of the request attribute * @return The value of the request attribute */ Object getAttribute(String key); /** - * Sets an attribute into the request. - * This method is decoupled from the servlet api request to - * facilitate abstractions for testing and other programs not - * connected to a servlet application. - * - * @param key The key of the request attribute - * @param value The value of the request attribute + * Sets an attribute into the request. This method is decoupled from the + * servlet api request to facilitate abstractions for testing and other + * programs not connected to a servlet application. + * + * @param key + * The key of the request attribute + * @param value + * The value of the request attribute */ void setAttribute(String key, Object value); /** * <p> - * Returns any extra path information associated with the URL the - * client sent when it made this request. The extra path information - * follows the servlet path but precedes the query string. - * This method returns null if there was no extra path information. + * Returns any extra path information associated with the URL the client + * sent when it made this request. The extra path information follows the + * servlet path but precedes the query string. This method returns null if + * there was no extra path information. * </p> * <p> - * This method should function identically to <code>HttpServletRequest.getPathInfo()</code> - * except for that it removes ALL portal/portlet navigational state information from the - * path info string. + * This method should function identically to + * <code>HttpServletRequest.getPathInfo()</code> except for that it + * removes ALL portal/portlet navigational state information from the path + * info string. * </p> - * + * * @return the path */ String getPath(); - + /** * * <p> * setPath * </p> - * Allows the manual overriding of path Jetspeed 2 will look to resolves pages and folders. - * + * Allows the manual overriding of path Jetspeed 2 will look to resolves + * pages and folders. + * * @param path */ void setPath(String path); - + /** - * Returns the user info map of user attributes for a given portlet application.</p> - * @param oid The portlet application object id. + * Returns the user info map of user attributes for a given portlet + * application. + * </p> + * + * @param oid + * The portlet application object id. * @return The PortletRequest.USER_INFO map. */ Map getUserInfoMap(ObjectID oid); - + /** * * <p> @@ -394,58 +414,62 @@ * closely matches the prefences of the currently requesting client. * * @param portlet - * @return <code>Language</code> that matches, as closely as possible, that of - * the requesting client. + * @return <code>Language</code> that matches, as closely as possible, + * that of the requesting client. */ - Language getPreferedLanguage( PortletDefinition portlet ); - + Language getPreferedLanguage(PortletDefinition portlet); + /** * * @return */ - Throwable popActionFailure(PortletWindow window); + Throwable popActionFailure(PortletWindow window); - /** - * @param actionFailed The actionFailed to set. + * @param actionFailed + * The actionFailed to set. */ void setActionFailure(PortletWindow window, Throwable actionFailure); - + /** * Get the current executing pipeline * * @return Pipeline */ Pipeline getPipeline(); - + /** * Set the current pipeline + * * @param pipeline */ void setPipeline(Pipeline pipeline); /** - * Gets the Jetspeed primary user principal associated with the authorized entity. - * + * Gets the Jetspeed primary user principal associated with the authorized + * entity. + * * @return The primary principal on this request. */ Principal getUserPrincipal(); - + /** - * Locates a specific page using the profiler and site manager location algorithms - * from a generalized non-profiled path to the first page matching the path + * Locates a specific page using the profiler and site manager location + * algorithms from a generalized non-profiled path to the first page + * matching the path * - * @param profiler The profiler component to use in the search - * @return A Content Page located by the profiler, or null if not found + * @param profiler + * The profiler component to use in the search + * @return A Content Page located by the profiler, or null if not found */ ContentPage locatePage(Profiler profiler, String nonProfiledPath); - + /** - * Return a map of Jetspeed Request Context objects configured via Spring Map + * Return a map of Jetspeed Request Context objects configured via Spring + * Map * * @return a Map of request context objects * @since 2.1.2 */ Map getObjects(); } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/request/RequestContextComponent.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/request/RequestContextComponent.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/request/RequestContextComponent.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,15 +20,15 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - /** * RequestContextComponent - * + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: RequestContextComponent.java 516448 2007-03-09 16:25:47Z ate $ */ -public interface RequestContextComponent +public interface RequestContextComponent { + /** * Creates a request context for the given servlet request. * @@ -37,7 +37,8 @@ * @param config * @return */ - RequestContext create(HttpServletRequest req, HttpServletResponse resp, ServletConfig config); + RequestContext create(HttpServletRequest req, HttpServletResponse resp, + ServletConfig config); /** * Release a request context back to the context pool. @@ -45,15 +46,16 @@ * @param context */ void release(RequestContext context); - + /** - * The servlet request can always get you back to the Request Context if you need it - * This static accessor provides this capability - * + * The servlet request can always get you back to the Request Context if you + * need it This static accessor provides this capability + * * @param request * @return RequestContext */ - RequestContext getRequestContext(HttpServletRequest request); - RequestContext getRequestContext(); - + RequestContext getRequestContext(HttpServletRequest request); + + RequestContext getRequestContext(); + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/HandlerFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/HandlerFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/HandlerFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,13 +18,16 @@ /** * @author jford - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Style - Code Templates + * + * TODO To change the template for this generated type comment go to Window - + * Preferences - Java - Code Style - Code Templates */ public interface HandlerFactory { + void addClassNameMapping(String className, String handlerClassName); + ObjectHandler getHandler(Object obj) throws Exception; + ObjectHandler getHandler(String className) throws Exception; } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/ObjectHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/ObjectHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/ObjectHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,33 +19,34 @@ import java.util.Set; /** - * Contract for implementing a specific object handler. Implementation - * should convert the object into a document suitable for placement into - * search index. + * Contract for implementing a specific object handler. Implementation should + * convert the object into a document suitable for placement into search index. * * @author <a href="mailto:morciuch ¡÷ apache.org">Mark Orciuch</a> * @version $Id: ObjectHandler.java 516448 2007-03-09 16:25:47Z ate $ */ public interface ObjectHandler { + /** * Parses a specific object into a document suitable for index placement * * @param o - * @return + * @return */ public ParsedObject parseObject(Object o); - + /** * Returns the set of fields used to create the parsed object. + * * @return */ public Set getFields(); - + /** * Returns the set of keywords used to create the parsed object. + * * @return */ public Set getKeywords(); } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/ParsedObject.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/ParsedObject.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/ParsedObject.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,12 +16,12 @@ */ package org.apache.jetspeed.search; +import java.net.URL; import java.util.Map; -import java.net.URL; /** * Contract for implementing a specific parsed object. - * + * * @author <a href="mailto:morciuch ¡÷ apache.org">Mark Orciuch</a> * @version $Id: ParsedObject.java 516448 2007-03-09 16:25:47Z ate $ */ @@ -29,38 +29,62 @@ { public static final String FIELDNAME_KEY = "fieldname.key"; + public static final String FIELDNAME_KEY_DEFAULT = "Key"; + public static final String FIELDNAME_TYPE = "fieldname.type"; + public static final String FIELDNAME_TYPE_DEFAULT = "Type"; + public static final String FIELDNAME_CONTENT = "fieldname.content"; + public static final String FIELDNAME_CONTENT_DEFAULT = "Content"; + public static final String FIELDNAME_DESCRIPTION = "fieldname.description"; + public static final String FIELDNAME_DESCRIPTION_DEFAULT = "Description"; + public static final String FIELDNAME_TITLE = "fieldname.title"; + public static final String FIELDNAME_TITLE_DEFAULT = "Title"; + public static final String FIELDNAME_LANGUAGE = "fieldname.language"; + public static final String FIELDNAME_LANGUAGE_DEFAULT = "Language"; + public static final String FIELDNAME_FIELDS = "fieldname.fields"; + public static final String FIELDNAME_FIELDS_DEFAULT = "Fields"; + public static final String FIELDNAME_KEYWORDS = "fieldname.keywords"; + public static final String FIELDNAME_KEYWORDS_DEFAULT = "Keywords"; + public static final String FIELDNAME_URL = "fieldname.url"; + public static final String FIELDNAME_URL_DEFAULT = "URL"; + public static final String FIELDNAME_SCORE = "fieldname.score"; + public static final String FIELDNAME_SCORE_DEFAULT = "Score"; + public static final String FIELDNAME_CLASSNAME = "fieldname.className"; + public static final String FIELDNAME_CLASSNAME_DEFAULT = "ClassName"; // Known object types public static final String OBJECT_TYPE_URL = "url"; + public static final String OBJECT_TYPE_PORTLET = "portlet"; + public static final String OBJECT_TYPE_PORTLET_APPLICATION = "portlet_application"; + public static final String OBJECT_TYPE_PDF = "pdf"; /** * Returns parsed object key (cannot be null) * - * @return + * @return */ public String getKey(); @@ -74,7 +98,7 @@ /** * Returns parsed object type (cannot be null) * - * @return + * @return */ public String getType(); @@ -88,7 +112,7 @@ /** * Returns parsed object content (cannot be null) * - * @return + * @return */ public String getContent(); @@ -102,7 +126,7 @@ /** * Returns parsed object description (cannot be null) * - * @return + * @return */ public String getDescription(); @@ -117,7 +141,7 @@ * * Returns parsed object keywords * - * @return + * @return */ public String[] getKeywords(); @@ -132,7 +156,7 @@ /** * Returns parsed object title (cannot be null) * - * @return + * @return */ public String getTitle(); @@ -144,9 +168,9 @@ public void setTitle(String title); /** - * Returns parsed object language (cannot be null) + * Returns parsed object language (cannot be null) * - * @return + * @return */ public String getLanguage(); @@ -161,7 +185,7 @@ * * Returns parsed object searchable fields * - * @return + * @return */ public Map getFields(); @@ -172,12 +196,12 @@ * @param fields */ public void setFields(Map fields); - + /** * @return */ public Map getKeywordsMap(); - + /** * @param multiKeywords */ @@ -186,7 +210,7 @@ /** * Returns parsed object URL * - * @return + * @return */ public URL getURL(); @@ -203,27 +227,28 @@ * @return Value of property score. */ public float getScore(); - + /** * Setter for property score. * - * @param score New value of property score. + * @param score + * New value of property score. */ public void setScore(float score); - + /** * Getter for property className. * * @return Value of property className. */ public String getClassName(); - + /** * Setter for property className. * - * @param className New value of property className. + * @param className + * New value of property className. */ public void setClassName(String className); } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/SearchEngine.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/SearchEngine.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/SearchEngine.java 2008-05-16 01:54:54 UTC (rev 940) @@ -23,19 +23,20 @@ */ public interface SearchEngine { + boolean add(Object o); - + boolean add(Collection objects); - + boolean remove(Object o); - + boolean remove(Collection objects); - + boolean update(Object o); - + boolean update(Collection objects); - + boolean optimize(); - + SearchResults search(String query); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/SearchResults.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/SearchResults.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/search/SearchResults.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,17 +21,18 @@ /** * @author <a href="mailto: jford ¡÷ apache.org">Jeremy Ford</a> - * + * */ public interface SearchResults { + public int size(); - + public Iterator iterator(); - + public ParsedObject get(int index); - + public List getResults(); - + public List getResults(int fromIndex, int toIndex); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AlgorithmUpgradePasswordEncodingService.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AlgorithmUpgradePasswordEncodingService.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AlgorithmUpgradePasswordEncodingService.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,28 +5,33 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security; /** * <p> - * AlgorithmUpgradePasswordEncodingService allows checking a specific PasswordCredential if it uses the provided Encoding Algorithm. + * AlgorithmUpgradePasswordEncodingService allows checking a specific + * PasswordCredential if it uses the provided Encoding Algorithm. * </p> * <p> - * This service can be used for gradually migrating from a one-way encoding to a two-way encoding algoritmn. + * This service can be used for gradually migrating from a one-way encoding to a + * two-way encoding algoritmn. * </p> + * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id$ */ -public interface AlgorithmUpgradePasswordEncodingService extends PasswordEncodingService +public interface AlgorithmUpgradePasswordEncodingService extends + PasswordEncodingService { + boolean usesOldEncodingAlgorithm(PasswordCredential passwordCredential); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AuthenticationProvider.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AuthenticationProvider.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AuthenticationProvider.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,7 +28,7 @@ */ public interface AuthenticationProvider { - + /** * <p> * Gets the authentication provider name. @@ -37,7 +37,7 @@ * @return The authentication provider name. */ String getProviderName(); - + /** * <p> * Gets the authentication provider description. @@ -46,7 +46,7 @@ * @return The authentication provider description. */ String getProviderDescription(); - + /** * <p> * Gets the {@link UserSecurityHandler}. @@ -55,17 +55,17 @@ * @return The {@link UserSecurityHandler}. */ UserSecurityHandler getUserSecurityHandler(); - - + /** * <p> * Sets the {@link UserSecurityHandler}. * </p> * - * @param userSecurityHandler The {@link UserSecurityHandler}. + * @param userSecurityHandler + * The {@link UserSecurityHandler}. */ void setUserSecurityHandler(UserSecurityHandler userSecurityHandler); - + /** * <p> * Gets the {@link CredentialHandler}. @@ -74,13 +74,14 @@ * @return The {@link CredentialHandler}. */ CredentialHandler getCredentialHandler(); - + /** * <p> * Sets the {@link CredentialHandler}. * </p> * - * @param credHandler The {@link CredentialHandler}. + * @param credHandler + * The {@link CredentialHandler}. */ void setCredentialHandler(CredentialHandler credHandler); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AuthenticationProviderProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AuthenticationProviderProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AuthenticationProviderProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,8 +16,8 @@ */ package org.apache.jetspeed.security; +import java.sql.Date; import java.util.List; -import java.sql.Date; import org.apache.jetspeed.security.spi.CredentialHandler; import org.apache.jetspeed.security.spi.UserSecurityHandler; @@ -29,8 +29,10 @@ * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat </a> */ -public interface AuthenticationProviderProxy extends UserSecurityHandler, CredentialHandler +public interface AuthenticationProviderProxy extends UserSecurityHandler, + CredentialHandler { + /** * <p> * Returns the default authentication provider. @@ -39,10 +41,11 @@ * @return The default authentication provider. */ String getDefaultAuthenticationProvider(); - + /** * <p> * Returns the authentication provider of a user principal. + * * @param userName * @return The authentication provider or null if user is unknown. */ @@ -53,140 +56,192 @@ * Gets the iterator of user principals for a given filter. * </p> * - * @param filter The filter. - * @param authenticationProvider The authentication provider name. + * @param filter + * The filter. + * @param authenticationProvider + * The authentication provider name. * @return The list of <code>Principal</code> */ - List getUserPrincipals(String filter, String authenticationProvider) throws SecurityException; + List getUserPrincipals(String filter, String authenticationProvider) + throws SecurityException; /** * <p> * Gets the number of user principals for a given filter. * </p> * - * @param filter The filter. - * @param authenticationProvider The authentication provider name. + * @param filter + * The filter. + * @param authenticationProvider + * The authentication provider name. * @return The number of <code>Principal</code> */ - int getUserCount(String filter, String authenticationProvider) throws SecurityException; + int getUserCount(String filter, String authenticationProvider) + throws SecurityException; - /** * <p> * Adds a new user principal in a given authentication provider. * </p> * - * @param userPrincipal The new user principal. - * @param authenticationProvider The authentication provider name. - * @throws SecurityException Throws a security exception. + * @param userPrincipal + * The new user principal. + * @param authenticationProvider + * The authentication provider name. + * @throws SecurityException + * Throws a security exception. */ - void addUserPrincipal(UserPrincipal userPrincipal, String authenticationProvider) throws SecurityException; + void addUserPrincipal(UserPrincipal userPrincipal, + String authenticationProvider) throws SecurityException; /** * <p> * Updates user principal in a given authentication provider. * </p> * - * @param userPrincipal The user principal. - * @param authenticationProvider The authentication provider name. - * @throws SecurityException Throws a security exception. + * @param userPrincipal + * The user principal. + * @param authenticationProvider + * The authentication provider name. + * @throws SecurityException + * Throws a security exception. */ - void updateUserPrincipal(UserPrincipal userPrincipal, String authenticationProvider) throws SecurityException; + void updateUserPrincipal(UserPrincipal userPrincipal, + String authenticationProvider) throws SecurityException; /** * <p> * Remove user principal in a given authentication provider. * </p> * - * @param userPrincipal The user principal. - * @param authenticationProvider The authentication provider name. - * @throws SecurityException Throws a security exception. + * @param userPrincipal + * The user principal. + * @param authenticationProvider + * The authentication provider name. + * @throws SecurityException + * Throws a security exception. */ - void removeUserPrincipal(UserPrincipal userPrincipal, String authenticationProvider) throws SecurityException; + void removeUserPrincipal(UserPrincipal userPrincipal, + String authenticationProvider) throws SecurityException; /** * <p> - * Adds or updates a private password credentialin a given authentication provider.<br> - * Note that there is no checking of the <code>oldPassword</code> and the provided password is - * assumed to be encoded. Hence no encoding will take place. + * Adds or updates a private password credentialin a given authentication + * provider.<br> + * Note that there is no checking of the <code>oldPassword</code> and the + * provided password is assumed to be encoded. Hence no encoding will take + * place. * </p> * - * @param username The user to be updated. - * @param newPassword The new password. - * @throws SecurityException Throws a {@link SecurityException}. + * @param username + * The user to be updated. + * @param newPassword + * The new password. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - void importPassword(String userName, String newPassword) throws SecurityException; + void importPassword(String userName, String newPassword) + throws SecurityException; - - /** * <p> - * Adds or updates a private password credentialin a given authentication provider.<br> - * Note that there is no checking of the <code>oldPassword</code> and the provided password is - * assumed to be encoded. Hence no encoding will take place. + * Adds or updates a private password credentialin a given authentication + * provider.<br> + * Note that there is no checking of the <code>oldPassword</code> and the + * provided password is assumed to be encoded. Hence no encoding will take + * place. * </p> * - * @param username The user to be updated. - * @param newPassword The new password. - * @param authenticationProvider The authentication provider name. - * @throws SecurityException Throws a {@link SecurityException}. + * @param username + * The user to be updated. + * @param newPassword + * The new password. + * @param authenticationProvider + * The authentication provider name. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - void importPassword(String userName, String newPassword,String authenticationProvider) throws SecurityException; + void importPassword(String userName, String newPassword, + String authenticationProvider) throws SecurityException; /** * <p> - * Adds or updates a private password credential in a given authentication provider.<br> - * If <code>oldPassword</code> is not null, the oldPassword will first be checked (authenticated).<br> + * Adds or updates a private password credential in a given authentication + * provider.<br> + * If <code>oldPassword</code> is not null, the oldPassword will first be + * checked (authenticated).<br> * </p> * - * @param userName The name of the user to be updated. - * @param oldPassword The old password value. - * @param newPassword The new password value. - * @param authenticationProvider The authentication provider name. - * @throws SecurityException Throws a {@link SecurityException}. + * @param userName + * The name of the user to be updated. + * @param oldPassword + * The old password value. + * @param newPassword + * The new password value. + * @param authenticationProvider + * The authentication provider name. + * @throws SecurityException + * Throws a {@link SecurityException}. */ void setPassword(String userName, String oldPassword, String newPassword, String authenticationProvider) throws SecurityException; /** * <p> - * Set the update required state of the user password credential in a given authentication provider. + * Set the update required state of the user password credential in a given + * authentication provider. * </p> * - * @param userName The user name. - * @param updateRequired The update required state. - * @param authenticationProvider The authentication provider name. - * @throws Throws a security exception. + * @param userName + * The user name. + * @param updateRequired + * The update required state. + * @param authenticationProvider + * The authentication provider name. + * @throws Throws + * a security exception. */ - void setPasswordUpdateRequired(String userName, boolean updateRequired, + void setPasswordUpdateRequired(String userName, boolean updateRequired, String authenticationProvider) throws SecurityException; /** * <p> - * Set the enabled state of the user password credential in a given authentication provider. + * Set the enabled state of the user password credential in a given + * authentication provider. * </p> * - * @param userName The user name. - * @param enabled The enabled state. - * @param authenticationProvider The authentication provider name. - * @throws Throws a security exception. + * @param userName + * The user name. + * @param enabled + * The enabled state. + * @param authenticationProvider + * The authentication provider name. + * @throws Throws + * a security exception. */ - void setPasswordEnabled(String userName, boolean enabled, + void setPasswordEnabled(String userName, boolean enabled, String authenticationProvider) throws SecurityException; /** * <p> - * Set the expiration date and the expired flag of the password credential in a given authentication provider</p> + * Set the expiration date and the expired flag of the password credential + * in a given authentication provider + * </p> * <p> - * If a date equal or before the current date is provided, the expired flag will be set to true, - * otherwise to false.</p> + * If a date equal or before the current date is provided, the expired flag + * will be set to true, otherwise to false. + * </p> * - * @param userName The user name. - * @param expirationDate The expiration date to set. - * @param authenticationProvider The authentication provider name. - * @throws Throws a security exception. + * @param userName + * The user name. + * @param expirationDate + * The expiration date to set. + * @param authenticationProvider + * The authentication provider name. + * @throws Throws + * a security exception. */ - void setPasswordExpiration(String userName, Date expirationDate, + void setPasswordExpiration(String userName, Date expirationDate, String authenticationProvider) throws SecurityException; /** @@ -194,10 +249,14 @@ * Authenticate a user in a given authentication provider * </p> * - * @param userName The user name. - * @param password The user password. - * @param authenticationProvider The authentication provider name. + * @param userName + * The user name. + * @param password + * The user password. + * @param authenticationProvider + * The authentication provider name. * @return Whether or not a user is authenticated. */ - boolean authenticate(String userName, String password, String authenticationProvider) throws SecurityException; + boolean authenticate(String userName, String password, + String authenticationProvider) throws SecurityException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AuthorizationProvider.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AuthorizationProvider.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/AuthorizationProvider.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,30 +5,32 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security; import java.util.List; /** * <p> - * Configures the policies. Instantiates the <code>SecurityPolicies</code> with the security policies - * that need to be enforced. It will add the default policy already configured as well as the engine policies - * used to enforce permission checks. + * Configures the policies. Instantiates the <code>SecurityPolicies</code> + * with the security policies that need to be enforced. It will add the default + * policy already configured as well as the engine policies used to enforce + * permission checks. * </p> * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat </a> */ public interface AuthorizationProvider { + /** * <p> * The list of configured policies. @@ -37,14 +39,15 @@ * @return The list of policies. */ List getPolicies(); - - + /** * <p> - * Whether to use the default policy or not in addition to the Policies configured for the AuthorizationProvider. + * Whether to use the default policy or not in addition to the Policies + * configured for the AuthorizationProvider. * </p> * - * @param whetherToUseDefaultPolicy Boolean false: does not use the default policy, true: does. + * @param whetherToUseDefaultPolicy + * Boolean false: does not use the default policy, true: does. */ void useDefaultPolicy(boolean whetherToUseDefaultPolicy); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/BasePrincipal.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/BasePrincipal.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/BasePrincipal.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,46 +17,75 @@ package org.apache.jetspeed.security; import java.io.Serializable; - import java.security.Principal; /** -* <p>The base principal.</p> -* @author <a href="mailto:taylor ¡÷ apache.org">David Taylor</a>, <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> -*/ + * <p> + * The base principal. + * </p> + * + * @author <a href="mailto:taylor ¡÷ apache.org">David Taylor</a>, <a + * href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> + */ public interface BasePrincipal extends Principal, Serializable { - /** <p>The Preferences user root node</p> */ - final static String PREFS_USER_ROOT = "/user/"; - - /** <p>The Preferences group root node</p> */ + + /** + * <p> + * The Preferences user root node + * </p> + */ + final static String PREFS_USER_ROOT = "/user/"; + + /** + * <p> + * The Preferences group root node + * </p> + */ final static String PREFS_GROUP_ROOT = "/group/"; - - /** <p>The Preferences role root node</p> */ - final static String PREFS_ROLE_ROOT = "/role/"; - + /** - * <p>Provides the principal full path prepending PREFS_{PRINCPAL}_ROOT if not prepended.</p> + * <p> + * The Preferences role root node + * </p> + */ + final static String PREFS_ROLE_ROOT = "/role/"; + + /** + * <p> + * Provides the principal full path prepending PREFS_{PRINCPAL}_ROOT if not + * prepended. + * </p> + * * @return The principal full path. */ String getFullPath(); /** - * <p>Getter for the enabled state</p> + * <p> + * Getter for the enabled state + * </p> + * * @return true if enabled */ boolean isEnabled(); - + /** - * Setter for the enabled state</p> - * @param enabled The enabled state + * Setter for the enabled state + * </p> + * + * @param enabled + * The enabled state */ void setEnabled(boolean enabled); - + /** - * <p>is this principal a security principal mapping or a real principal</p> + * <p> + * is this principal a security principal mapping or a real principal + * </p> + * * @return true if is a mapping */ boolean isMapping(); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/Group.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/Group.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/Group.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,34 +20,52 @@ import java.util.prefs.Preferences; /** - * <p>A group made of a {@link GroupPrincipal} and the group {@link Preferences}.</p> + * <p> + * A group made of a {@link GroupPrincipal} and the group {@link Preferences}. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public interface Group { + /** - * <p>Getter for the group {@link Principal}.</p> + * <p> + * Getter for the group {@link Principal}. + * </p> + * * @return The {@link GroupPrincipal}. */ Principal getPrincipal(); /** - * <p>Setter for the group {@link Principal}.</p> - * @param groupPrincipal The {@link Principal}. + * <p> + * Setter for the group {@link Principal}. + * </p> + * + * @param groupPrincipal + * The {@link Principal}. */ void setPrincipal(Principal groupPrincipal); /** - * <p>Getter for the group {@link Preferences} node, providing access to the - * group preferences properties.</p> + * <p> + * Getter for the group {@link Preferences} node, providing access to the + * group preferences properties. + * </p> + * * @return The {@link Preferences}. */ Preferences getPreferences(); /** - * <p>Setter for the group {@link Preferences} node, providing access to the - * group preferences properties.</p> - * @param preferences The {@link Preferences}. + * <p> + * Setter for the group {@link Preferences} node, providing access to the + * group preferences properties. + * </p> + * + * @param preferences + * The {@link Preferences}. */ void setPreferences(Preferences preferences); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/GroupManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/GroupManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/GroupManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -52,9 +52,11 @@ * api. Groups will be stored under /group/theGroupName/theGroupNameChild * when given the full path name theGroupName.theGroupNameChild. * - * @param groupFullPathName The group name full path (e.g. + * @param groupFullPathName + * The group name full path (e.g. * theGroupName.theGroupNameChild). - * @throws Throws a security exception. + * @throws Throws + * a security exception. */ void addGroup(String groupFullPathName) throws SecurityException; @@ -71,9 +73,10 @@ * api. Groups will be stored under /group/theGroupName/theGroupNameChild * when given the full path name theGroupName.theGroupNameChild. * - * @param groupFullPathName The group name full path (e.g. - * theGroupName.theGroupNameChild) - * @throws Throws a security exception. + * @param groupFullPathName + * The group name full path (e.g. theGroupName.theGroupNameChild) + * @throws Throws + * a security exception. */ void removeGroup(String groupFullPathName) throws SecurityException; @@ -82,8 +85,8 @@ * Whether or not a group exists. * </p> * - * @param groupFullPathName The group name full path (e.g. - * theGroupName.theGroupNameChild) + * @param groupFullPathName + * The group name full path (e.g. theGroupName.theGroupNameChild) * @return Whether or not a group exists. */ boolean groupExists(String groupFullPathName); @@ -92,10 +95,12 @@ * <p> * Get a group {@link Group}for a given group full path name. * - * @param groupFullPathName The group name full path (e.g. + * @param groupFullPathName + * The group name full path (e.g. * theGroupName.theGroupChildName). * @return The {@link Preferences}node. - * @throws Throws security exception if the group does not exist. + * @throws Throws + * security exception if the group does not exist. */ Group getGroup(String groupFullPathName) throws SecurityException; @@ -104,9 +109,11 @@ * A collection of {@link Group}for all the groups associated to a specific * user. * - * @param username The user name. + * @param username + * The user name. * @return A collection of {@link Group}. - * @throws Throws security exception if the user does not exist. + * @throws Throws + * security exception if the user does not exist. */ Collection getGroupsForUser(String username) throws SecurityException; @@ -115,63 +122,81 @@ * A collection of {@link Group}for all the groups in a specific role. * </p> * - * @param roleFullPathName The role full path (e.g. - * theRoleName.theRoleChildName).. + * @param roleFullPathName + * The role full path (e.g. theRoleName.theRoleChildName).. * @return A Collection of {@link Group}. - * @throws Throws a security exception if the role does not exist. + * @throws Throws + * a security exception if the role does not exist. */ - Collection getGroupsInRole(String roleFullPathName) throws SecurityException; + Collection getGroupsInRole(String roleFullPathName) + throws SecurityException; /** * <p> * Add a user to a group. * </p> * - * @param username The user name. - * @param groupFullPathName The group name full path (e.g. + * @param username + * The user name. + * @param groupFullPathName + * The group name full path (e.g. * theGroupName.theGroupChildName). - * @throws Throws a security exception. + * @throws Throws + * a security exception. */ - void addUserToGroup(String username, String groupFullPathName) throws SecurityException; + void addUserToGroup(String username, String groupFullPathName) + throws SecurityException; /** * <p> * Remove a user from a group. * </p> * - * @param username The user name. - * @param groupFullPathName The group name full path (e.g. + * @param username + * The user name. + * @param groupFullPathName + * The group name full path (e.g. * theGroupName.theGroupChildName). - * @throws Throws a security exception. + * @throws Throws + * a security exception. */ - void removeUserFromGroup(String username, String groupFullPathName) throws SecurityException; + void removeUserFromGroup(String username, String groupFullPathName) + throws SecurityException; /** * <p> * Whether or not a user is in a group. * </p> * - * @param username The user name. - * @param groupFullPathName The group name full path (e.g. + * @param username + * The user name. + * @param groupFullPathName + * The group name full path (e.g. * theGroupName.theGroupChildName). * @return Whether or not a user is in a group. - * @throws Throws security exception if the user or group does not exist. + * @throws Throws + * security exception if the user or group does not exist. */ - boolean isUserInGroup(String username, String groupFullPathName) throws SecurityException; + boolean isUserInGroup(String username, String groupFullPathName) + throws SecurityException; /** * Get all groups available from all group handlers * - * @param filter The filter used to retrieve matching groups. - * @return all groups available as {@link Principal} + * @param filter + * The filter used to retrieve matching groups. + * @return all groups available as {@link Principal} */ - Iterator getGroups(String filter) throws SecurityException; - - /** - * Enable or disable a group. - * @param groupFullPathName The group name full path - * theGroupName.theGroupChildName). - * @param enabled enabled flag for the group - */ - void setGroupEnabled(String groupFullPathName, boolean enabled) throws SecurityException; + Iterator getGroups(String filter) throws SecurityException; + + /** + * Enable or disable a group. + * + * @param groupFullPathName + * The group name full path theGroupName.theGroupChildName). + * @param enabled + * enabled flag for the group + */ + void setGroupEnabled(String groupFullPathName, boolean enabled) + throws SecurityException; } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/GroupPrincipal.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/GroupPrincipal.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/GroupPrincipal.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,7 +17,10 @@ package org.apache.jetspeed.security; /** - * <p>The group principal.</p> + * <p> + * The group principal. + * </p> + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: GroupPrincipal.java 516448 2007-03-09 16:25:47Z ate $ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/HierarchyResolver.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/HierarchyResolver.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/HierarchyResolver.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,28 +26,30 @@ * @author <a href="mailto:Artem.Grinshtein ¡÷ t-systems.com">Artem Grinshtein </a> * @version $Id: HierarchyResolver.java 187640 2004-09-30 04:01:42Z dlestrat $ */ -public interface HierarchyResolver +public interface HierarchyResolver { - + /** * <p> * Returns absolute path names of the hierarchy roles/groups. * </p> * - * @param prefs Preferences for the role/group + * @param prefs + * Preferences for the role/group * @return Returns absolute path names of the dependcy roles/groups. */ public String[] resolve(Preferences prefs); - + /** * <p> * Returns the absolute path names of the children of the given hierarchy * roles/groups node. * </p> * - * @param prefs Preferences for the role/group + * @param prefs + * Preferences for the role/group * @return Returns absolute path names of the children roles/groups. */ public String[] resolveChildren(Preferences prefs); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidDnException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidDnException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidDnException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -13,16 +13,17 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ package org.apache.jetspeed.security; /** * Exception thrown when the distinguished name is invalid. - * + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public class InvalidDnException extends SecurityException { + /** The serial version uid. */ private static final long serialVersionUID = -2643327886955569635L; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidNewPasswordException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidNewPasswordException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidNewPasswordException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -13,17 +13,19 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ package org.apache.jetspeed.security; /** * Exception thrown when supplied new password is invalid. - * + * * @author <a href="mailto:ate ¡÷ apache.org">Ate Douma</a> - * @version $Id: InvalidNewPasswordException.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: InvalidNewPasswordException.java 516448 2007-03-09 16:25:47Z + * ate $ */ public class InvalidNewPasswordException extends SecurityException { + /** The serial version uid. */ private static final long serialVersionUID = -801235816327102698L; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidPasswordException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidPasswordException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidPasswordException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -13,17 +13,18 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ package org.apache.jetspeed.security; /** * Exception thrown when supplied password is invalid. - * + * * @author <a href="mailto:ate ¡÷ apache.org">Ate Douma</a> * @version $Id: InvalidPasswordException.java 516448 2007-03-09 16:25:47Z ate $ */ public class InvalidPasswordException extends SecurityException { + /** The serial uid. */ private static final long serialVersionUID = 3213606705251501558L; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidUidException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidUidException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/InvalidUidException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -13,16 +13,17 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ package org.apache.jetspeed.security; /** * Exception thrown when the uid is invalid. - * + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public class InvalidUidException extends SecurityException { + /** The serial version uid. */ private static final long serialVersionUID = 8603304762095029084L; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/LoginModuleProxy.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/LoginModuleProxy.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/LoginModuleProxy.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,40 +5,53 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security; /** - * <p>Utility component used as a bridge between the login module and the security component.</p> + * <p> + * Utility component used as a bridge between the login module and the security + * component. + * </p> * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public interface LoginModuleProxy { + /** - * <p>Default .portal user role name</p> + * <p> + * Default .portal user role name + * </p> */ String DEFAULT_PORTAL_USER_ROLE_NAME = "portal-user"; /** - * <p>Getter for the {@link UserManager}.</p> + * <p> + * Getter for the {@link UserManager}. + * </p> + * * @return The UserManager. */ UserManager getUserManager(); /** - * <p>Getter for the required portal user role name.</p> - * - * <p>Used in web.xml authorization to detect authenticated portal users.</p> - * + * <p> + * Getter for the required portal user role name. + * </p> + * + * <p> + * Used in web.xml authorization to detect authenticated portal users. + * </p> + * * @return The portal user role name. */ String getPortalUserRole(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PasswordAlreadyUsedException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PasswordAlreadyUsedException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PasswordAlreadyUsedException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -13,17 +13,19 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ + */ package org.apache.jetspeed.security; /** * Exception thrown when supplied password has been used before. - * + * * @author <a href="mailto:ate ¡÷ apache.org">Ate Douma</a> - * @version $Id: PasswordAlreadyUsedException.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: PasswordAlreadyUsedException.java 516448 2007-03-09 16:25:47Z + * ate $ */ public class PasswordAlreadyUsedException extends SecurityException { + /** The serial version uid. */ private static final long serialVersionUID = 302007677387600743L; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PasswordCredential.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PasswordCredential.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PasswordCredential.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security; import java.sql.Date; @@ -29,8 +29,11 @@ */ public interface PasswordCredential { - String PASSWORD_CREDENTIAL_DAYS_VALID_REQUEST_ATTR_KEY = PasswordCredential.class.getName() + ".check"; + String PASSWORD_CREDENTIAL_DAYS_VALID_REQUEST_ATTR_KEY = PasswordCredential.class + .getName() + + ".check"; + /** * @return The username. */ @@ -45,39 +48,42 @@ * @return true if update required. */ boolean isUpdateRequired(); - + /** * @return true if enabled. */ boolean isEnabled(); - + /** * @return true if expired. */ boolean isExpired(); - + /** * @return when the password is (going to be) expired. */ Date getExpirationDate(); - + /** - * @return the previous time the user logged in + * @return the previous time the user logged in */ Timestamp getPreviousAuthenticationDate(); /** - * @return the last time the user logged in + * @return the last time the user logged in */ Timestamp getLastAuthenticationDate(); /** - * <p>Getter for the current number of authentication failures in a row.</p> + * <p> + * Getter for the current number of authentication failures in a row. + * </p> * <ul> - * <li>-1: never tried yet</li> - * <li> 0: none, or last attempt was successful</li> - * <li>>0: number of failures</li> + * <li>-1: never tried yet</li> + * <li> 0: none, or last attempt was successful</li> + * <li>>0: number of failures</li> * </ul> + * * @return The number of authentication failures */ int getAuthenticationFailures(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PasswordEncodingService.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PasswordEncodingService.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PasswordEncodingService.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,7 +18,8 @@ /** * <p> - * PasswordEncodingService allows decoding of user passwords provided that a two-way encryption algoritmn is used. + * PasswordEncodingService allows decoding of user passwords provided that a + * two-way encryption algoritmn is used. * </p> * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> @@ -26,6 +27,10 @@ */ public interface PasswordEncodingService { - String encode(String userName, String clearTextPassword) throws SecurityException; - String decode(String userName, String encodedPassword) throws SecurityException; + + String encode(String userName, String clearTextPassword) + throws SecurityException; + + String decode(String userName, String encodedPassword) + throws SecurityException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PermissionManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PermissionManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/PermissionManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,6 +20,7 @@ import java.security.Permissions; import java.security.Principal; import java.util.Collection; + import javax.security.auth.Subject; /** @@ -29,8 +30,9 @@ * access entitlement on specified resources. * </p> * <p> - * The permission manager does not enforce any hierarchy resolution, all relevant - * principals must be passed to the permission manager to assess the proper permissions. + * The permission manager does not enforce any hierarchy resolution, all + * relevant principals must be passed to the permission manager to assess the + * proper permissions. * </p> * <p> * For instance: @@ -45,7 +47,7 @@ * * </code> * <pre> - * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> + * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> * */ public interface PermissionManager @@ -55,7 +57,8 @@ * <p> * Gets the {@link Permissions}given a {@link Principal}. * - * @param principal The principal. + * @param principal + * The principal. * @return The permissions. */ Permissions getPermissions(Principal principal); @@ -64,7 +67,8 @@ * <p> * Gets the {@link Permissions}given a collection of {@link Principal}. * - * @param principals A collection of principal. + * @param principals + * A collection of principal. * @return The permissions. */ Permissions getPermissions(Collection principals); @@ -74,8 +78,10 @@ * Adds a permission definition. * </p> * - * @param permission The permission to add. - * @throws Throws a security exception. + * @param permission + * The permission to add. + * @throws Throws + * a security exception. */ void addPermission(Permission permission) throws SecurityException; @@ -84,8 +90,10 @@ * Remove all instances of a given permission. * </p> * - * @param permission The permission to remove. - * @throws Throws a security exception. + * @param permission + * The permission to remove. + * @throws Throws + * a security exception. */ void removePermission(Permission permission) throws SecurityException; @@ -94,7 +102,8 @@ * Whether the given permission exists. * </p> * - * @param permission The permission to look for. + * @param permission + * The permission to look for. * @return Whether the permission exists. */ boolean permissionExists(Permission permission); @@ -104,8 +113,10 @@ * Remove all permissions for a given principal. * </p> * - * @param principal The principal. - * @throws Throws a security exception. + * @param principal + * The principal. + * @throws Throws + * a security exception. */ void removePermissions(Principal principal) throws SecurityException; @@ -113,46 +124,59 @@ * <p> * Grant a {@link Permission}to a given {@link Principal}. * - * @param principal The principal. - * @param permission The permission. - * @throws Throws a security exception if the principal does not exist. + * @param principal + * The principal. + * @param permission + * The permission. + * @throws Throws + * a security exception if the principal does not exist. */ - void grantPermission(Principal principal, Permission permission) throws SecurityException; + void grantPermission(Principal principal, Permission permission) + throws SecurityException; /** * <p> * Revoke a {@link Permission}from a given {@link Principal}. * - * @param principal The principal. - * @param permission The permission. - * @throws Throws a security exception. + * @param principal + * The principal. + * @param permission + * The permission. + * @throws Throws + * a security exception. */ - void revokePermission(Principal principal, Permission permission) throws SecurityException; + void revokePermission(Principal principal, Permission permission) + throws SecurityException; /** * <p> - * Check permission for the given subject's access to the resource protected by the permission - * This is an abstraction introduced in M4 for Permission Manager implementations NOT - * founded upon the a Java security policy.</p> + * Check permission for the given subject's access to the resource protected + * by the permission This is an abstraction introduced in M4 for Permission + * Manager implementations NOT founded upon the a Java security policy. + * </p> * - * @param subject The Java subject. - * @param permission The permission, usually a portlet, page or folder type permission. - * @return true if the subject has access to the permission protected resource, false - * if the subject does not have access. + * @param subject + * The Java subject. + * @param permission + * The permission, usually a portlet, page or folder type + * permission. + * @return true if the subject has access to the permission protected + * resource, false if the subject does not have access. */ boolean checkPermission(Subject subject, Permission permission); - + /** - * Retrieve a collection of all Permissions in the system ordered by Permission Type, resource - * Note that we return a collection of <code>InternalPrincipal</code> + * Retrieve a collection of all Permissions in the system ordered by + * Permission Type, resource Note that we return a collection of + * <code>InternalPrincipal</code> * * @return A Java Security collection of <code>InternalPrincipal</code> */ - Collection getPermissions(); - + Collection getPermissions(); + /** - * Retrieve a list of all Permissions in the system for a given resource - * The resource can be a prefix, for example "j2-admin" will retrieve all + * Retrieve a list of all Permissions in the system for a given resource The + * resource can be a prefix, for example "j2-admin" will retrieve all * portlet permissions starting with j2-admin * * @return A Java Security collection of Permissions @@ -160,22 +184,24 @@ Permissions getPermissions(String classname, String resource); /** - * Update the collection of principals on the given principal, - * appropriately granting or revoking principals to the given permission. + * Update the collection of principals on the given principal, appropriately + * granting or revoking principals to the given permission. * - * @param permission Permission to be updated - * @param principals The new collection of principals based on BasePrincipal - * to be associated with this permission + * @param permission + * Permission to be updated + * @param principals + * The new collection of principals based on BasePrincipal to be + * associated with this permission * @return * @throws SecurityException */ int updatePermission(Permission permission, Collection principals) - throws SecurityException; - + throws SecurityException; + /** * Given a permission, return all principals granted to that permission * - * @param permission + * @param permission * @return A collection of Java Security Permission objects */ public Collection getPrincipals(Permission permission); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/Role.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/Role.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/Role.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,34 +20,52 @@ import java.util.prefs.Preferences; /** - * <p>A role made of a {@link RolePrincipal} and the role {@link Preferences}.</p> + * <p> + * A role made of a {@link RolePrincipal} and the role {@link Preferences}. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public interface Role { + /** - * <p>Getter for the role {@link Principal}.</p> + * <p> + * Getter for the role {@link Principal}. + * </p> + * * @return The {@link Principal}. */ Principal getPrincipal(); /** - * <p>Setter for the role {@link RolePrincipal}.</p> - * @param rolePrincipal The {@link Principal}. + * <p> + * Setter for the role {@link RolePrincipal}. + * </p> + * + * @param rolePrincipal + * The {@link Principal}. */ void setPrincipal(Principal rolePrincipal); /** - * <p>Getter for the role {@link Preferences} node, providing access to the - * role preferences properties.</p> + * <p> + * Getter for the role {@link Preferences} node, providing access to the + * role preferences properties. + * </p> + * * @return The {@link Preferences}. */ Preferences getPreferences(); /** - * <p>Setter for the role {@link Preferences} node, providing access to the - * role preferences properties.</p> - * @param preferences The {@link Preferences}. + * <p> + * Setter for the role {@link Preferences} node, providing access to the + * role preferences properties. + * </p> + * + * @param preferences + * The {@link Preferences}. */ void setPreferences(Preferences preferences); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/RoleManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/RoleManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/RoleManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,152 +20,230 @@ import java.util.Collection; /** - * <p>Describes the service interface for managing roles.</p> - * <p>Role hierarchy elements are being returned as a {@link Role} - * collection. The backing implementation must appropriately map - * the role hierarchy to a preferences sub-tree.</p> - * <p>The convention {principal}.{subprincipal} has been chosen to name - * roles hierachies in order to support declarative security. Implementation - * follow the conventions enforced by the preferences API.</p> + * <p> + * Describes the service interface for managing roles. + * </p> + * <p> + * Role hierarchy elements are being returned as a {@link Role} collection. The + * backing implementation must appropriately map the role hierarchy to a + * preferences sub-tree. + * </p> + * <p> + * The convention {principal}.{subprincipal} has been chosen to name roles + * hierachies in order to support declarative security. Implementation follow + * the conventions enforced by the preferences API. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public interface RoleManager { /** - * <p>Add a new role.</p> - * <p>Role principal names are expressed as {principal}.{subprincipal} where - * "." is the separator expressing the hierarchical nature of a role.</p> - * <p>Role principal path names are stored leveraging the {@link Preferences} - * api. Roles will be stored under /role/theGroupName/theGroupNameChild - * when given the full path name theRoleName.theRoleNameChild. - * @param roleFullPathName The role name full path - * (e.g. theRoleName.theRoleNameChild). - * @throws Throws a security exception if the role already exists. + * <p> + * Add a new role. + * </p> + * <p> + * Role principal names are expressed as {principal}.{subprincipal} where + * "." is the separator expressing the hierarchical nature of a role. + * </p> + * <p> + * Role principal path names are stored leveraging the {@link Preferences} + * api. Roles will be stored under /role/theGroupName/theGroupNameChild when + * given the full path name theRoleName.theRoleNameChild. + * + * @param roleFullPathName + * The role name full path (e.g. theRoleName.theRoleNameChild). + * @throws Throws + * a security exception if the role already exists. */ void addRole(String roleFullPathName) throws SecurityException; /** - * <p>Remove a given role and all the children of that role.</p> - * <p>Role principal names are expressed as {principal}.{subprincipal} where - * "." is the separator expressing the hierarchical nature of a role.</p> - * <p>Role principal path names are stored leveraging the {@link Preferences} - * api. Roles will be stored under /role/theGroupName/theGroupNameChild - * when given the full path name theRoleName.theRoleNameChild. - * @param roleFullPathName The role name full path - * (e.g. theRoleName.theRoleNameChild). - * @throws Throws a security exception. + * <p> + * Remove a given role and all the children of that role. + * </p> + * <p> + * Role principal names are expressed as {principal}.{subprincipal} where + * "." is the separator expressing the hierarchical nature of a role. + * </p> + * <p> + * Role principal path names are stored leveraging the {@link Preferences} + * api. Roles will be stored under /role/theGroupName/theGroupNameChild when + * given the full path name theRoleName.theRoleNameChild. + * + * @param roleFullPathName + * The role name full path (e.g. theRoleName.theRoleNameChild). + * @throws Throws + * a security exception. */ void removeRole(String roleFullPathName) throws SecurityException; /** - * <p>Whether or not a role exists.</p> - * @param roleFullPathName The role name full path - * (e.g. theRoleName.theRoleNameChild). + * <p> + * Whether or not a role exists. + * </p> + * + * @param roleFullPathName + * The role name full path (e.g. theRoleName.theRoleNameChild). * @return Whether or not a role exists. */ boolean roleExists(String roleFullPathName); /** - * <p>Get a role {@link Role} for a given role full path name. - * @param roleFullPathName The role name full path - * (e.g. theRoleName.theRoleNameChild). + * <p> + * Get a role {@link Role} for a given role full path name. + * + * @param roleFullPathName + * The role name full path (e.g. theRoleName.theRoleNameChild). * @return The {@link Preferences} node. - * @throws Throws a security exception if the role does not exist. + * @throws Throws + * a security exception if the role does not exist. */ Role getRole(String roleFullPathName) throws SecurityException; /** - * <p>A collection of {@link Role} for all the roles - * associated to a specific user.</p> - * @param username The user name. + * <p> + * A collection of {@link Role} for all the roles associated to a specific + * user. + * </p> + * + * @param username + * The user name. * @return A Collection of {@link Role}. - * @throws Throws a security exception if the user does not exist. + * @throws Throws + * a security exception if the user does not exist. */ Collection getRolesForUser(String username) throws SecurityException; /** - * <p>A collection of {@link Role} for all the roles - * associated to a specific group.</p> - * @param groupFullPathName The group full path - * (e.g. theGroupName.theGroupChildName). + * <p> + * A collection of {@link Role} for all the roles associated to a specific + * group. + * </p> + * + * @param groupFullPathName + * The group full path (e.g. theGroupName.theGroupChildName). * @return A Collection of {@link Role}. - * @throws Throws a security exception if the group does not exist. + * @throws Throws + * a security exception if the group does not exist. */ - Collection getRolesInGroup(String groupFullPathName) throws SecurityException; - + Collection getRolesInGroup(String groupFullPathName) + throws SecurityException; + /** - * <p>Add a role to a user.</p> - * @param username The user name. - * @param roleFullPathName The role name full path - * (e.g. theRoleName.theRoleChildName). - * @throws Throws a security exception if the role or the user do not exist. + * <p> + * Add a role to a user. + * </p> + * + * @param username + * The user name. + * @param roleFullPathName + * The role name full path (e.g. theRoleName.theRoleChildName). + * @throws Throws + * a security exception if the role or the user do not exist. */ - void addRoleToUser(String username, String roleFullPathName) throws SecurityException; + void addRoleToUser(String username, String roleFullPathName) + throws SecurityException; /** - * <p>Remove a user from a role.</p> - * @param username The user name. - * @param roleFullPathName The role name full path relative to the - * /role node (e.g. /theRoleName/theRoleChildName). - * @throws Throws a security exception. + * <p> + * Remove a user from a role. + * </p> + * + * @param username + * The user name. + * @param roleFullPathName + * The role name full path relative to the /role node (e.g. + * /theRoleName/theRoleChildName). + * @throws Throws + * a security exception. */ - void removeRoleFromUser(String username, String roleFullPathName) throws SecurityException; + void removeRoleFromUser(String username, String roleFullPathName) + throws SecurityException; /** - * <p>Whether or not a user is in a role.</p> - * @param username The user name. - * @param roleFullPathName The role name full path - * (e.g. theRoleName.theRoleChildName). + * <p> + * Whether or not a user is in a role. + * </p> + * + * @param username + * The user name. + * @param roleFullPathName + * The role name full path (e.g. theRoleName.theRoleChildName). * @return Whether or not a user is in a role. - * @throws Throws a security exception if the role or the user does not exist. + * @throws Throws + * a security exception if the role or the user does not exist. */ - boolean isUserInRole(String username, String roleFullPathName) throws SecurityException; + boolean isUserInRole(String username, String roleFullPathName) + throws SecurityException; /** - * <p>Add a role to a group.</p> - * @param roleFullPathName The role name full path - * (e.g. theRoleName.theRoleChildName). - * @param groupFullPathName The group name full path - * (e.g. theGroupName.theGroupChildName). - * @throws Throws a security exception. + * <p> + * Add a role to a group. + * </p> + * + * @param roleFullPathName + * The role name full path (e.g. theRoleName.theRoleChildName). + * @param groupFullPathName + * The group name full path (e.g. + * theGroupName.theGroupChildName). + * @throws Throws + * a security exception. */ - void addRoleToGroup(String roleFullPathName, String groupFullPathName) throws SecurityException; + void addRoleToGroup(String roleFullPathName, String groupFullPathName) + throws SecurityException; /** - * <p>Remove a role from a group.</p> - * @param roleFullPathName The role name full path - * (e.g. theRoleName.theRoleChildName). - * @param groupFullPathName The group name full path - * (e.g. theGroupName.theGroupChildName). - * @throws Throws a security exception. + * <p> + * Remove a role from a group. + * </p> + * + * @param roleFullPathName + * The role name full path (e.g. theRoleName.theRoleChildName). + * @param groupFullPathName + * The group name full path (e.g. + * theGroupName.theGroupChildName). + * @throws Throws + * a security exception. */ - void removeRoleFromGroup(String roleFullPathName, String groupFullPathName) throws SecurityException; + void removeRoleFromGroup(String roleFullPathName, String groupFullPathName) + throws SecurityException; /** - * <p>Whether or not a role is in a group.</p> - * @param groupFullPathName The group name full path - * (e.g. theGroupName.theGroupChildName). - * @param roleFullPathName The role name full path - * (e.g. theRoleName.theRoleChildName). + * <p> + * Whether or not a role is in a group. + * </p> + * + * @param groupFullPathName + * The group name full path (e.g. + * theGroupName.theGroupChildName). + * @param roleFullPathName + * The role name full path (e.g. theRoleName.theRoleChildName). * @return Whether or not a role is in a group. - * @throws Throws a security exception if the role or the group does not exist. + * @throws Throws + * a security exception if the role or the group does not exist. */ - boolean isGroupInRole(String groupFullPathName, String roleFullPathName) throws SecurityException; + boolean isGroupInRole(String groupFullPathName, String roleFullPathName) + throws SecurityException; /** * Get all roles available from all role handlers * - * @param filter The filter used to retrieve matching roles. - * @return all roles available as {@link Principal} + * @param filter + * The filter used to retrieve matching roles. + * @return all roles available as {@link Principal} */ Iterator getRoles(String filter) throws SecurityException; - + /** * Enable or disable a role. - * @param roleFullPathName The role name full path - * (e.g. theRoleName.theRoleChildName). - * @param enabled enabled flag for the role + * + * @param roleFullPathName + * The role name full path (e.g. theRoleName.theRoleChildName). + * @param enabled + * enabled flag for the role */ - void setRoleEnabled(String roleFullPathName, boolean enabled) throws SecurityException; + void setRoleEnabled(String roleFullPathName, boolean enabled) + throws SecurityException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/RolePrincipal.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/RolePrincipal.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/RolePrincipal.java 2008-05-16 01:54:54 UTC (rev 940) @@ -14,10 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.apache.jetspeed.security; +package org.apache.jetspeed.security; /** - * <p>The role principal.</p> + * <p> + * The role principal. + * </p> + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: RolePrincipal.java 516448 2007-03-09 16:25:47Z ate $ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/SecurityAccessController.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/SecurityAccessController.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/SecurityAccessController.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,49 +20,58 @@ /** * <p> - * This component abstracts access to security checks. - * Jetspeed supports two kinds of secured access: + * This component abstracts access to security checks. Jetspeed supports two + * kinds of secured access: * <ul> * <li>Permissions</li> * <li>Constraints</li> * </ul> - * Permissions are checked via Java Security. Jetspeed implements its own security policy. - * Constrainted are checked via the Page Manager's constraints. - * Either way, the implicit Jetspeed Security Subject is applied to the security access check. + * Permissions are checked via Java Security. Jetspeed implements its own + * security policy. Constrainted are checked via the Page Manager's constraints. + * Either way, the implicit Jetspeed Security Subject is applied to the security + * access check. * </p> * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ public interface SecurityAccessController -{ +{ + /** * Use the Java Security Policy (Permissions) to make secure access checks */ final int PERMISSIONS = 1; + /** * Use the Jetspeed Security Constraints to make secure access checks */ final int CONSTRAINTS = 2; - + /** * <p> - * Checks access for the implicit active subject's access to the resource protected by the portlet permission - * This is an abstraction introduced in 2.1 for Permission Manager implementations NOT - * founded upon the a Java security policy. If the Permission Manager is configured to - * run with Security Constraints, then a security constraint check is made. Otherwise, - * a standard Java Security permission check is made.</p> + * Checks access for the implicit active subject's access to the resource + * protected by the portlet permission This is an abstraction introduced in + * 2.1 for Permission Manager implementations NOT founded upon the a Java + * security policy. If the Permission Manager is configured to run with + * Security Constraints, then a security constraint check is made. + * Otherwise, a standard Java Security permission check is made. + * </p> * - * @param portlet The portlet to be checked - * @param mask A mask <code>JetspeedActions</code> such as view, edit - * @return true if access is granted, false if access denied based on policy or constraints + * @param portlet + * The portlet to be checked + * @param mask + * A mask <code>JetspeedActions</code> such as view, edit + * @return true if access is granted, false if access denied based on policy + * or constraints */ boolean checkPortletAccess(PortletDefinitionComposite portlet, int mask); - + /** - * Returns the configured security mode for this accessor - * This component can be configured to make Java Security Policy permission checks - * or Jetspeed Security Constraint checks + * Returns the configured security mode for this accessor This component can + * be configured to make Java Security Policy permission checks or Jetspeed + * Security Constraint checks + * * @return either PERMISSIONS or CONSTRAINTS */ int getSecurityMode(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/SecurityException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/SecurityException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/SecurityException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,75 +20,175 @@ import org.apache.jetspeed.i18n.KeyedMessage; /** - * <p>Exception throwns by members of the security service.</p> - * + * <p> + * Exception throwns by members of the security service. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public class SecurityException extends JetspeedException { + /** The serial version uid. */ private static final long serialVersionUID = -8823877029853488430L; - /** <p>Principal does not exist exception message.</p> */ - public static final KeyedMessage PRINCIPAL_DOES_NOT_EXIST = new KeyedMessage("The principal {0} does not exist."); + /** + * <p> + * Principal does not exist exception message. + * </p> + */ + public static final KeyedMessage PRINCIPAL_DOES_NOT_EXIST = new KeyedMessage( + "The principal {0} does not exist."); - /** <p>Permission does not exist exception message.</p> */ - public static final KeyedMessage PERMISSION_DOES_NOT_EXIST = new KeyedMessage("The permission {0} does not exist."); - - /** <p>User principal already exists exception message.</p> */ - public static final KeyedMessage USER_ALREADY_EXISTS = new KeyedMessage("The user {0} already exists."); + /** + * <p> + * Permission does not exist exception message. + * </p> + */ + public static final KeyedMessage PERMISSION_DOES_NOT_EXIST = new KeyedMessage( + "The permission {0} does not exist."); - /** <p>User principal does not exist exception message.</p> */ - public static final KeyedMessage USER_DOES_NOT_EXIST = new KeyedMessage("The user {0} does not exist."); + /** + * <p> + * User principal already exists exception message. + * </p> + */ + public static final KeyedMessage USER_ALREADY_EXISTS = new KeyedMessage( + "The user {0} already exists."); - /** <p>Role principal already exists exception message.</p> */ - public static final KeyedMessage ROLE_ALREADY_EXISTS = new KeyedMessage("The role {0} already exists."); + /** + * <p> + * User principal does not exist exception message. + * </p> + */ + public static final KeyedMessage USER_DOES_NOT_EXIST = new KeyedMessage( + "The user {0} does not exist."); - /** <p>Role principal does not exist exception message.</p> */ - public static final KeyedMessage ROLE_DOES_NOT_EXIST = new KeyedMessage("The role {0} does not exist."); + /** + * <p> + * Role principal already exists exception message. + * </p> + */ + public static final KeyedMessage ROLE_ALREADY_EXISTS = new KeyedMessage( + "The role {0} already exists."); - /** <p>Group principal already exists exception message.</p> */ - public static final KeyedMessage GROUP_ALREADY_EXISTS = new KeyedMessage("The group {0} already exists."); + /** + * <p> + * Role principal does not exist exception message. + * </p> + */ + public static final KeyedMessage ROLE_DOES_NOT_EXIST = new KeyedMessage( + "The role {0} does not exist."); - /** <p>Group principal does not exist exception message.</p> */ - public static final KeyedMessage GROUP_DOES_NOT_EXIST = new KeyedMessage("The group {0} does not exist."); + /** + * <p> + * Group principal already exists exception message. + * </p> + */ + public static final KeyedMessage GROUP_ALREADY_EXISTS = new KeyedMessage( + "The group {0} already exists."); - /** <p>Invalid password exception message.</p> */ - public static final KeyedMessage EMPTY_PARAMETER = new KeyedMessage("Invalid null or empty parameter {0}."); + /** + * <p> + * Group principal does not exist exception message. + * </p> + */ + public static final KeyedMessage GROUP_DOES_NOT_EXIST = new KeyedMessage( + "The group {0} does not exist."); - /** <p>Invalid password exception message.</p> */ - public static final KeyedMessage INVALID_PASSWORD = new KeyedMessage("Invalid password."); + /** + * <p> + * Invalid password exception message. + * </p> + */ + public static final KeyedMessage EMPTY_PARAMETER = new KeyedMessage( + "Invalid null or empty parameter {0}."); - /** <p>Invalid new password exception message.</p> */ - public static final KeyedMessage INVALID_NEW_PASSWORD = new KeyedMessage("Invalid new password."); + /** + * <p> + * Invalid password exception message. + * </p> + */ + public static final KeyedMessage INVALID_PASSWORD = new KeyedMessage( + "Invalid password."); - /** <p>Incorrect password exception message.</p> */ - public static final KeyedMessage INCORRECT_PASSWORD = new KeyedMessage("Incorrect password."); + /** + * <p> + * Invalid new password exception message. + * </p> + */ + public static final KeyedMessage INVALID_NEW_PASSWORD = new KeyedMessage( + "Invalid new password."); - /** <p>Password required exception message.</p> */ - public static final KeyedMessage PASSWORD_REQUIRED = new KeyedMessage("Password required."); - - /** <p>Invalid authentication provider exception message.</p> */ - public static final KeyedMessage INVALID_AUTHENTICATION_PROVIDER = new KeyedMessage("Invalid authentication provider {0}."); + /** + * <p> + * Incorrect password exception message. + * </p> + */ + public static final KeyedMessage INCORRECT_PASSWORD = new KeyedMessage( + "Incorrect password."); - /** <p>Password already used exception message.</p> */ - public static final KeyedMessage PASSWORD_ALREADY_USED = new KeyedMessage("Password already used."); + /** + * <p> + * Password required exception message. + * </p> + */ + public static final KeyedMessage PASSWORD_REQUIRED = new KeyedMessage( + "Password required."); - /** <p>The anonymous user is protected exception message.</p> */ - public static final KeyedMessage ANONYMOUS_USER_PROTECTED = new KeyedMessage("The user {0} is protected."); + /** + * <p> + * Invalid authentication provider exception message. + * </p> + */ + public static final KeyedMessage INVALID_AUTHENTICATION_PROVIDER = new KeyedMessage( + "Invalid authentication provider {0}."); - /** <p>The anonymous user is protected exception message.</p> */ - public static final KeyedMessage UNEXPECTED = new KeyedMessage("Unexpected security error at {0} from {1}: {2}"); - - /** <p>The uid is invalid.</p> */ - public static final KeyedMessage INVALID_UID = new KeyedMessage("The uid cannot contain any regular expression meta-characters or be null or be empty."); + /** + * <p> + * Password already used exception message. + * </p> + */ + public static final KeyedMessage PASSWORD_ALREADY_USED = new KeyedMessage( + "Password already used."); - /** <p>The dn is invalid.</p> */ - public static final KeyedMessage INVALID_DN = new KeyedMessage("The dn cannot be null or empty."); - /** - * <p>Default Constructor.</p> + * <p> + * The anonymous user is protected exception message. + * </p> */ + public static final KeyedMessage ANONYMOUS_USER_PROTECTED = new KeyedMessage( + "The user {0} is protected."); + + /** + * <p> + * The anonymous user is protected exception message. + * </p> + */ + public static final KeyedMessage UNEXPECTED = new KeyedMessage( + "Unexpected security error at {0} from {1}: {2}"); + + /** + * <p> + * The uid is invalid. + * </p> + */ + public static final KeyedMessage INVALID_UID = new KeyedMessage( + "The uid cannot contain any regular expression meta-characters or be null or be empty."); + + /** + * <p> + * The dn is invalid. + * </p> + */ + public static final KeyedMessage INVALID_DN = new KeyedMessage( + "The dn cannot be null or empty."); + + /** + * <p> + * Default Constructor. + * </p> + */ public SecurityException() { super(); @@ -98,10 +198,14 @@ { super(t); } - + /** - * <p>Constructor with exception message.</p> - * @param message The exception message. + * <p> + * Constructor with exception message. + * </p> + * + * @param message + * The exception message. */ public SecurityException(KeyedMessage typedMessage) { @@ -109,9 +213,14 @@ } /** - * <p>Constructor with exception message and nested exception.</p> - * @param msg The exception message. - * @param nested Nested exception. + * <p> + * Constructor with exception message and nested exception. + * </p> + * + * @param msg + * The exception message. + * @param nested + * Nested exception. */ public SecurityException(KeyedMessage msg, Throwable nested) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/SecurityProvider.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/SecurityProvider.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/SecurityProvider.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,6 +30,7 @@ */ public interface SecurityProvider { + /** * <p> * Getter for the {@link AuthenticationProviderProxy} Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/User.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/User.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/User.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,56 +21,74 @@ import javax.security.auth.Subject; /** - * <p>A user made of a {@link Subject} and the user {@link Preferences}.</p> + * <p> + * A user made of a {@link Subject} and the user {@link Preferences}. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public interface User { + /** * <p> * The default user attributes property set. * </p> */ final static String USER_INFO_PROPERTY_SET = "userinfo"; - + /** * the subsite path for a given user stored as a user attribute */ final static String USER_INFO_SUBSITE = "subsite"; - + /** - * <p>Getter for the user {@link Subject} populated with the - * application principals.</p> + * <p> + * Getter for the user {@link Subject} populated with the application + * principals. + * </p> + * * @return The {@link Subject}. */ Subject getSubject(); /** - * <p>Setter for the user {@link Subject} populated with the - * application principals.</p> - * @param subject The {@link Subject}. + * <p> + * Setter for the user {@link Subject} populated with the application + * principals. + * </p> + * + * @param subject + * The {@link Subject}. */ void setSubject(Subject subject); /** - * <p>Getter for the user {@link Preferences} node, providing access to the - * user preferences properties.</p> + * <p> + * Getter for the user {@link Preferences} node, providing access to the + * user preferences properties. + * </p> + * * @return The {@link Preferences}. */ Preferences getPreferences(); /** - * <p>Setter for the user {@link Preferences} node, providing access to the - * user preferences properties.</p> - * - * @param preferences The {@link Preferences}. + * <p> + * Setter for the user {@link Preferences} node, providing access to the + * user preferences properties. + * </p> + * + * @param preferences + * The {@link Preferences}. */ void setPreferences(Preferences preferences); - + /** * Get the user attributes for a given user + * * @return a preference set of user attributes for a given user */ Preferences getUserAttributes(); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/UserManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/UserManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/UserManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,18 +30,21 @@ */ public interface UserManager { + /** * @return the name of the anonymous user */ String getAnonymousUser(); - + /** * <p> * Authenticate a user. * </p> * - * @param username The user name. - * @param password The user password. + * @param username + * The user name. + * @param password + * The user password. * @return Whether or not a user is authenticated. */ boolean authenticate(String username, String password); @@ -51,53 +54,71 @@ * Add a new user provided a username and password. * </p> * - * @param username The user name. - * @param password The password. - * @throws Throws a security exception. + * @param username + * The user name. + * @param password + * The password. + * @throws Throws + * a security exception. */ void addUser(String username, String password) throws SecurityException; /** * <p> - * Add a new user provided a username and password in the specified authentication - * provider store. + * Add a new user provided a username and password in the specified + * authentication provider store. * </p> * - * @param username The user name. - * @param password The password. - * @param atnProviderName The authentication provider name. - * @throws Throws a security exception. + * @param username + * The user name. + * @param password + * The password. + * @param atnProviderName + * The authentication provider name. + * @throws Throws + * a security exception. */ - void addUser(String username, String password, String atnProviderName) throws SecurityException; + void addUser(String username, String password, String atnProviderName) + throws SecurityException; - /** * <p> - * Import a new user with username and password and allow to bypass the enconding algorithm + * Import a new user with username and password and allow to bypass the + * enconding algorithm * </p> * - * @param username The user name. - * @param password The password. - * @param passThrough If true the provided password will not be validated/encoded - * @throws Throws a security exception. + * @param username + * The user name. + * @param password + * The password. + * @param passThrough + * If true the provided password will not be validated/encoded + * @throws Throws + * a security exception. */ - void importUser(String username, String password, boolean passThrough) throws SecurityException; + void importUser(String username, String password, boolean passThrough) + throws SecurityException; /** * <p> - * Import a new user with username and password in the specified authentication - * provider store and allow to bypass the enconding algorithm + * Import a new user with username and password in the specified + * authentication provider store and allow to bypass the enconding algorithm * </p> * - * @param username The user name. - * @param password The password. - * @param atnProviderName The authentication provider name. - * @param passThrough If true the provided password will not be validated/encoded - * @throws Throws a security exception. + * @param username + * The user name. + * @param password + * The password. + * @param atnProviderName + * The authentication provider name. + * @param passThrough + * If true the provided password will not be validated/encoded + * @throws Throws + * a security exception. */ - void importUser(String username, String password, String atnProviderName, boolean passThrough) throws SecurityException; + void importUser(String username, String password, String atnProviderName, + boolean passThrough) throws SecurityException; - /** * <p> * Remove a user. If there is a {@link java.util.prefs.Preferences}node for @@ -107,8 +128,10 @@ * {@link java.security.Permission}for this user will be removed as well. * </p> * - * @param username The user name. - * @throws Throws a security exception. + * @param username + * The user name. + * @throws Throws + * a security exception. */ void removeUser(String username) throws SecurityException; @@ -117,7 +140,8 @@ * Whether or not a user exists. * </p> * - * @param username The user name. + * @param username + * The user name. * @return Whether or not a user exists. */ boolean userExists(String username); @@ -127,9 +151,11 @@ * Get a {@link User}for a given username. * </p> * - * @param username The username. + * @param username + * The username. * @return The {@link User}. - * @throws Throws a security exception if the user cannot be found. + * @throws Throws + * a security exception if the user cannot be found. */ User getUser(String username) throws SecurityException; @@ -140,7 +166,8 @@ * </p> * TODO Complete filter implementation. * - * @param filter The filter used to retrieve matching users. + * @param filter + * The filter used to retrieve matching users. * @return The Iterator of {@link User}. */ Iterator getUsers(String filter) throws SecurityException; @@ -152,7 +179,8 @@ * </p> * TODO Complete filter implementation. * - * @param filter The filter used to retrieve matching users. + * @param filter + * The filter used to retrieve matching users. * @return The Iterator of {@link User}. */ Iterator getUserNames(String filter) throws SecurityException; @@ -162,73 +190,103 @@ * A collection of {@link User}for all the users in a specific role. * </p> * - * @param roleFullPathName The role name full path (e.g. - * theRoleName.theRoleNameChild). + * @param roleFullPathName + * The role name full path (e.g. theRoleName.theRoleNameChild). * @return A Collection of {@link User}. - * @throws Throws a security exception if the role does not exist. + * @throws Throws + * a security exception if the role does not exist. */ Collection getUsersInRole(String roleFullPathName) throws SecurityException; - + /** - * <p>A collection of {@link User} for a specific group.</p> - * @param groupFullPathName The group name full path - * (e.g. theGroupName.theGroupChildName). + * <p> + * A collection of {@link User} for a specific group. + * </p> + * + * @param groupFullPathName + * The group name full path (e.g. + * theGroupName.theGroupChildName). * @return A collection of {@link User}. - * @throws Throws security exception if the group does not exist. + * @throws Throws + * security exception if the group does not exist. */ - Collection getUsersInGroup(String groupFullPathName) throws SecurityException; - + Collection getUsersInGroup(String groupFullPathName) + throws SecurityException; + /** * <p> * Set the user password. * </p> * - * @param username The user name. - * @param oldPassword The old password. - * @param newPassword The new password. - * @throws Throws a security exception. + * @param username + * The user name. + * @param oldPassword + * The old password. + * @param newPassword + * The new password. + * @throws Throws + * a security exception. */ - void setPassword(String username, String oldPassword, String newPassword) throws SecurityException; + void setPassword(String username, String oldPassword, String newPassword) + throws SecurityException; /** * <p> * Set the update required state of the user password credential. * </p> * - * @param userName The user name. - * @param updateRequired The update required state. - * @throws Throws a security exception. + * @param userName + * The user name. + * @param updateRequired + * The update required state. + * @throws Throws + * a security exception. */ - void setPasswordUpdateRequired(String userName, boolean updateRequired) throws SecurityException; + void setPasswordUpdateRequired(String userName, boolean updateRequired) + throws SecurityException; /** * <p> * Set the enabled state of the user password credential. * </p> * - * @param userName The user name. - * @param enabled The enabled state. - * @throws Throws a security exception. + * @param userName + * The user name. + * @param enabled + * The enabled state. + * @throws Throws + * a security exception. */ - void setPasswordEnabled(String userName, boolean enabled) throws SecurityException; + void setPasswordEnabled(String userName, boolean enabled) + throws SecurityException; /** * Enable or disable a user. - * @param userName The user name - * @param enabled enabled flag for the user + * + * @param userName + * The user name + * @param enabled + * enabled flag for the user */ - void setUserEnabled(String userName, boolean enabled) throws SecurityException; + void setUserEnabled(String userName, boolean enabled) + throws SecurityException; /** * <p> - * Set the expiration date and the expired flag of the password credential.</p> + * Set the expiration date and the expired flag of the password credential. + * </p> * <p> - * If a date equal or before the current date is provided, the expired flag will be set to true, - * otherwise to false.</p> + * If a date equal or before the current date is provided, the expired flag + * will be set to true, otherwise to false. + * </p> * - * @param userName The user name. - * @param expirationDate The expiration date to set. - * @throws Throws a security exception. + * @param userName + * The user name. + * @param expirationDate + * The expiration date to set. + * @throws Throws + * a security exception. */ - void setPasswordExpiration(String userName, Date expirationDate) throws SecurityException; + void setPasswordExpiration(String userName, Date expirationDate) + throws SecurityException; } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/UserPrincipal.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/UserPrincipal.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/UserPrincipal.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,7 +17,10 @@ package org.apache.jetspeed.security; /** - * <p>The user principal.</p> + * <p> + * The user principal. + * </p> + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: UserPrincipal.java 516448 2007-03-09 16:25:47Z ate $ */ Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/UserSubjectPrincipal.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/UserSubjectPrincipal.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/UserSubjectPrincipal.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,11 +19,15 @@ import javax.security.auth.Subject; /** - * <p>The user principal.</p> + * <p> + * The user principal. + * </p> + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: UserPrincipal.java 187022 2004-07-16 19:31:24Z weaver $ */ public interface UserSubjectPrincipal extends UserPrincipal { + Subject getSubject(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/activeauthentication/ActiveAuthenticationIdentityProvider.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/activeauthentication/ActiveAuthenticationIdentityProvider.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/activeauthentication/ActiveAuthenticationIdentityProvider.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,65 +1,73 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.activeauthentication; import java.util.List; - /** * <p> * ActiveAuthenticationIdentityProvider * </p> * <p> - * Provides identity tokens used during active authentication to bridge the deficiencies - * in Java Login Modules and general Active Authentication patterns - * based on Java login modules. Creates a unique, short lived identity token, caching basic Authentication information across redirects, - * requests, and threads during the active authentication process. The life-time - * of this cached authentication information is meant to be very short lived. + * Provides identity tokens used during active authentication to bridge the + * deficiencies in Java Login Modules and general Active Authentication patterns + * based on Java login modules. Creates a unique, short lived identity token, + * caching basic Authentication information across redirects, requests, and + * threads during the active authentication process. The life-time of this + * cached authentication information is meant to be very short lived. * </p> + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ - * + * */ public interface ActiveAuthenticationIdentityProvider { + /** - * Start an authentication event with the server, creating a new and unique identity token + * Start an authentication event with the server, creating a new and unique + * identity token * - * @return the newly created identity token + * @return the newly created identity token */ IdentityToken createIdentityToken(); /** - * Start an authentication event with the server, creating a new and unique identity token - * - * @param seed seed information to add to token - * @return the newly created identity token + * Start an authentication event with the server, creating a new and unique + * identity token + * + * @param seed + * seed information to add to token + * @return the newly created identity token */ IdentityToken createIdentityToken(String seed); /** * Completes an authentication event for a given authentication token * - * @param token The token identifying the authentication event to be completed + * @param token + * The token identifying the authentication event to be completed */ void completeAuthenticationEvent(String token); - + /** - * Get a list of session attribute names that should be saved and restored upon authentication events + * Get a list of session attribute names that should be saved and restored + * upon authentication events + * * @return list of session attribute names */ List getSessionAttributeNames(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/activeauthentication/IdentityToken.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/activeauthentication/IdentityToken.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/activeauthentication/IdentityToken.java 2008-05-16 01:54:54 UTC (rev 940) @@ -1,60 +1,65 @@ /* -* Licensed to the Apache Software Foundation (ASF) under one or more -* contributor license agreements. See the NOTICE file distributed with -* this work for additional information regarding copyright ownership. -* The ASF licenses this file to You under the Apache License, Version 2.0 -* (the "License"); you may not use this file except in compliance with -* the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.activeauthentication; import java.util.Iterator; - /** * <p> * Identity Token * </p> * <p> - * Holds a unique token identifying the current authentication process. - * This token can hold one or more unique name / value (object) attributes + * Holds a unique token identifying the current authentication process. This + * token can hold one or more unique name / value (object) attributes * </p> + * * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ - * + * */ public interface IdentityToken { + /** - * Get the value of the identity token + * Get the value of the identity token + * * @return the identity token string */ String getToken(); - + /** * set a name/value attribute on this token + * * @param name * @param value */ void setAttribute(String name, Object value); - - /** + + /** * Get an attribute value given the attribute name + * * @param name * @return */ Object getAttribute(String name); - + /** * Get an iterator over all attribute names + * * @return */ Iterator getAttributeNames(); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalCredential.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalCredential.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalCredential.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,228 +21,341 @@ import java.sql.Timestamp; /** - * <p>Interface representing a security credential.</p> - * <p>The credential value represents the value of the credential - * such as a password.</p> - * <p>For now, we do not have custom credentials classes and - * credentials support only 1 credential (i.e. 1 password).<p> - * <p>The credential type represents whether a credential is private or - * public:</p> + * <p> + * Interface representing a security credential. + * </p> + * <p> + * The credential value represents the value of the credential such as a + * password. + * </p> + * <p> + * For now, we do not have custom credentials classes and credentials support + * only 1 credential (i.e. 1 password). + * <p> + * <p> + * The credential type represents whether a credential is private or public: + * </p> * <ul> - * <li>Private credential: type == 0</li> - * <li>Public credential: type == 1</li> + * <li>Private credential: type == 0</li> + * <li>Public credential: type == 1</li> * </ul> - * <p>The credential classname represent the class of credential. + * <p> + * The credential classname represent the class of credential. * </p> * TODO Add multiple credentials support. + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> * @version $Id: InternalCredential.java 516448 2007-03-09 16:25:47Z ate $ */ public interface InternalCredential extends Serializable, Cloneable { + /** Private credentials type. */ public static final int PRIVATE = 0; + /** Public credentials type. */ public static final int PUBLIC = 1; - + /** * Maximum allowed java.sql.Date value (according to the specs). * <em>Note:</em><br> - * The concrete value is default time zone dependent and should <em>only</em> - * be used for setting Date fields, not to <em>compare<em> against. + * The concrete value is default time zone dependent and should + * <em>only</em> be used for setting Date fields, not to + * <em>compare<em> against. */ public static final Date MAX_DATE = Date.valueOf("8099-01-01"); /** - * <p>Getter for the credential id.</p> + * <p> + * Getter for the credential id. + * </p> + * * @return The credential id. */ long getCredentialId(); /** - * <p>Setter for the credential id.</p> - * @param credentialId The credential id. + * <p> + * Setter for the credential id. + * </p> + * + * @param credentialId + * The credential id. */ void setCredentialId(long credentialId); /** - * <p>Getter for the principal id.</p> + * <p> + * Getter for the principal id. + * </p> + * * @return The principal id. */ long getPrincipalId(); /** - * <p>Setter for the principal id.</p> - * @param principalId The principal id. + * <p> + * Setter for the principal id. + * </p> + * + * @param principalId + * The principal id. */ void setPrincipalId(long principalId); /** - * <p>Getter for the credential value.</p> + * <p> + * Getter for the credential value. + * </p> + * * @return The credential value. */ String getValue(); /** - * <p>Setter for the credential value.</p> - * @param value The credential value. + * <p> + * Setter for the credential value. + * </p> + * + * @param value + * The credential value. */ void setValue(String value); - + /** - * <p>Getter for the update required state</p> + * <p> + * Getter for the update required state + * </p> + * * @return true if required */ boolean isUpdateRequired(); - + /** - * <p>Setter for the update required state</p> - * @param updateRequired the update required state + * <p> + * Setter for the update required state + * </p> + * + * @param updateRequired + * the update required state */ void setUpdateRequired(boolean updateRequired); - + /** - * <p>Getter for the encoded state</p> + * <p> + * Getter for the encoded state + * </p> + * * @return true if encoded */ boolean isEncoded(); - + /** - * Setter for the encoded state</p> - * @param encoded The encoded state + * Setter for the encoded state + * </p> + * + * @param encoded + * The encoded state */ void setEncoded(boolean encoded); - + /** - * <p>Getter for the enabled state</p> + * <p> + * Getter for the enabled state + * </p> + * * @return true if enabled */ boolean isEnabled(); - + /** - * Setter for the enabled state</p> - * @param enabled The enabled state + * Setter for the enabled state + * </p> + * + * @param enabled + * The enabled state */ void setEnabled(boolean enabled); - + /** - * <p>Getter for the current number of authentication failures in a row.</p> + * <p> + * Getter for the current number of authentication failures in a row. + * </p> * <ul> - * <li>-1: never tried yet</li> - * <li> 0: none, or last attempt was successful</li> - * <li>>0: number of failures</li> + * <li>-1: never tried yet</li> + * <li> 0: none, or last attempt was successful</li> + * <li>>0: number of failures</li> * </ul> + * * @return The number of authentication failures */ int getAuthenticationFailures(); - + /** - * <p>Setter for the number of authentication failures</p> - * @param authenticationFailures The number of authentication failures + * <p> + * Setter for the number of authentication failures + * </p> + * + * @param authenticationFailures + * The number of authentication failures */ void setAuthenticationFailures(int authenticationFailures); /** - * Getter for the expired state.</p> + * Getter for the expired state. + * </p> + * * @return true if expired */ boolean isExpired(); - + /** - * Setter for the expired state.</p> - * @param expired The expired state + * Setter for the expired state. + * </p> + * + * @param expired + * The expired state */ void setExpired(boolean expired); - + /** - * <p>Getter for the expiration date.</p> + * <p> + * Getter for the expiration date. + * </p> + * * @return The expiration date. */ Date getExpirationDate(); - + /** - * <p>Setter for the expiration date.</p> - * @param expirationDate The expiration date. + * <p> + * Setter for the expiration date. + * </p> + * + * @param expirationDate + * The expiration date. */ void setExpirationDate(Date expirationDate); - + /** - * <p>Getter for the credential type.</p> + * <p> + * Getter for the credential type. + * </p> * <ul> - * <li>Private credential: type == 0</li> - * <li>Public credential: type == 1</li> + * <li>Private credential: type == 0</li> + * <li>Public credential: type == 1</li> * </ul> + * * @return The credential type. */ int getType(); /** - * <p>Setter for the credential type.</p> + * <p> + * Setter for the credential type. + * </p> * <ul> - * <li>Private credential: type == 0</li> - * <li>Public credential: type == 1</li> + * <li>Private credential: type == 0</li> + * <li>Public credential: type == 1</li> * </ul> - * @param type The credential type. + * + * @param type + * The credential type. */ void setType(int type); /** - * <p>Getter for the principal classname.</p> + * <p> + * Getter for the principal classname. + * </p> + * * @return The principal classname. */ String getClassname(); /** - * <p>Setter for the principal classname.</p> - * @param classname The principal classname. + * <p> + * Setter for the principal classname. + * </p> + * + * @param classname + * The principal classname. */ void setClassname(String classname); /** - * <p>Getter for creation date.</p> + * <p> + * Getter for creation date. + * </p> + * * @return The creation date. */ Timestamp getCreationDate(); /** - * <p>Setter for the creation date.</p> - * @param creationDate The creation date. + * <p> + * Setter for the creation date. + * </p> + * + * @param creationDate + * The creation date. */ void setCreationDate(Timestamp creationDate); /** - * <p>Getter for the modified date.</p> + * <p> + * Getter for the modified date. + * </p> + * * @return The modified date. */ Timestamp getModifiedDate(); /** - * <p>Setter for the modified date.</p> - * @param modifiedDate The modified date. + * <p> + * Setter for the modified date. + * </p> + * + * @param modifiedDate + * The modified date. */ void setModifiedDate(Timestamp modifiedDate); /** - * <p>Getter for the previous authentication date</p> + * <p> + * Getter for the previous authentication date + * </p> + * * @return The previous authentication date. */ Timestamp getPreviousAuthenticationDate(); - + /** - * <p>Setter for the previous authentication date</p> - * @param previousAuthenticationDate The previous authentication date. + * <p> + * Setter for the previous authentication date + * </p> + * + * @param previousAuthenticationDate + * The previous authentication date. */ void setPreviousAuthenticationDate(Timestamp previousAuthenticationDate); /** - * <p>Getter for the last authentication date</p> + * <p> + * Getter for the last authentication date + * </p> + * * @return The last authentication date. */ Timestamp getLastAuthenticationDate(); - + /** - * <p>Setter for the last authentication date</p> - * @param lastAuthenticationDate The last authentication date. + * <p> + * Setter for the last authentication date + * </p> + * + * @param lastAuthenticationDate + * The last authentication date. */ void setLastAuthenticationDate(Timestamp lastAuthenticationDate); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalGroupPrincipal.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalGroupPrincipal.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalGroupPrincipal.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,32 +19,50 @@ import java.util.Collection; /** - * <p>Interface representing a Jetspeed security group principal object model.</p> + * <p> + * Interface representing a Jetspeed security group principal object model. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public interface InternalGroupPrincipal extends InternalPrincipal { + /** - * <p>Getter for the user principals.</p> + * <p> + * Getter for the user principals. + * </p> + * * @return The user principals. */ Collection getUserPrincipals(); /** - * <p>Setter for the user principals.</p> - * @param userPrincipals The user principals. + * <p> + * Setter for the user principals. + * </p> + * + * @param userPrincipals + * The user principals. */ void setUserPrincipals(Collection userPrincipals); /** - * <p>Getter for the role principals.</p> + * <p> + * Getter for the role principals. + * </p> + * * @return The role principals. */ Collection getRolePrincipals(); /** - * <p>Setter for the role principals.</p> - * @param rolePrincipals The role principals. + * <p> + * Setter for the role principals. + * </p> + * + * @param rolePrincipals + * The role principals. */ void setRolePrincipals(Collection rolePrincipals); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalPermission.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalPermission.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalPermission.java 2008-05-16 01:54:54 UTC (rev 940) @@ -21,112 +21,171 @@ import java.util.Collection; /** - * <p>Interface representing a policy permission. This will be used by the - * {@link org.apache.jetspeed.security.impl.RdbmsPolicy} to retrieve a permission - * policy according to JAAS where permission are used in JAAS:</p> + * <p> + * Interface representing a policy permission. This will be used by the + * {@link org.apache.jetspeed.security.impl.RdbmsPolicy} to retrieve a + * permission policy according to JAAS where permission are used in JAAS: + * </p> + * * <pre> - * <code>grant [SignedBy "signer_names"] [, CodeBase "URL"] - * [, InternalPrincipal [principal_class_name] "principal_name"] - * [, InternalPrincipal [principal_class_name] "principal_name"] ... + * <code> + * grant [SignedBy "signer_names"] [, CodeBase "URL"] + * [, InternalPrincipal [principal_class_name] "principal_name"] + * [, InternalPrincipal [principal_class_name] "principal_name"] ... * { - * permission permission_class_name [ "target_name" ] - * [, "action"] [, SignedBy "signer_names"]; + * permission permission_class_name [ "target_name" ] + * [, "action"] [, SignedBy "signer_names"]; * permission ... * }; * </code> * </pre> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public interface InternalPermission extends Serializable, Cloneable { /** - * <p>Getter for the permission id.</p> + * <p> + * Getter for the permission id. + * </p> + * * @return The permission id. */ long getPermissionId(); /** - * <p>Setter for the permission id.</p> - * @param permissionId The permission id. + * <p> + * Setter for the permission id. + * </p> + * + * @param permissionId + * The permission id. */ void setPermissionId(long permissionId); /** - * <p>Getter for the permission classname.</p> + * <p> + * Getter for the permission classname. + * </p> + * * @return The permission classname. */ String getClassname(); /** - * <p>Setter for the permission classname.</p> - * @param classname The permission classname. + * <p> + * Setter for the permission classname. + * </p> + * + * @param classname + * The permission classname. */ void setClassname(String classname); /** - * <p>Getter for the permission resource name.</p> + * <p> + * Getter for the permission resource name. + * </p> + * * @return The permission resource name. */ String getName(); /** - * <p>Setter for the permission resource name.</p> - * @param name The permission resource name. + * <p> + * Setter for the permission resource name. + * </p> + * + * @param name + * The permission resource name. */ void setName(String name); - + /** - * <p>Getter for the permission actions.</p> + * <p> + * Getter for the permission actions. + * </p> + * * @return The permission actions. */ String getActions(); /** - * <p>Setter for the permission actions.</p> - * @param actions The permission actions. + * <p> + * Setter for the permission actions. + * </p> + * + * @param actions + * The permission actions. */ void setActions(String actions); /** - * <p>Getter for the permission principals.</p> + * <p> + * Getter for the permission principals. + * </p> + * * @return The permission principals. */ Collection getPrincipals(); /** - * <p>Setter for the permission principals.</p> - * @param principals The permission principals. + * <p> + * Setter for the permission principals. + * </p> + * + * @param principals + * The permission principals. */ void setPrincipals(Collection principals); /** - * <p>Getter for creation date.</p> + * <p> + * Getter for creation date. + * </p> + * * @return The creation date. */ Timestamp getCreationDate(); /** - * <p>Setter for the creation date.</p> - * @param creationDate The creation date. + * <p> + * Setter for the creation date. + * </p> + * + * @param creationDate + * The creation date. */ void setCreationDate(Timestamp creationDate); /** - * <p>Getter for the modified date.</p> + * <p> + * Getter for the modified date. + * </p> + * * @return The modified date. */ Timestamp getModifiedDate(); /** - * <p>Setter for the modified date.</p> - * @param modifiedDate The modified date. + * <p> + * Setter for the modified date. + * </p> + * + * @param modifiedDate + * The modified date. */ void setModifiedDate(Timestamp modifiedDate); /** - * <p>Equals method used to appropriately compare 2 {@link InternalPermission} objects.</p> - * @param object The object to compare with. + * <p> + * Equals method used to appropriately compare 2 {@link InternalPermission} + * objects. + * </p> + * + * @param object + * The object to compare with. * @return The comparison result. */ boolean equals(Object object); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalPrincipal.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalPrincipal.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalPrincipal.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,8 +17,8 @@ package org.apache.jetspeed.security.om; import java.io.Serializable; +import java.sql.Timestamp; import java.util.Collection; -import java.sql.Timestamp; /** * <p> @@ -61,7 +61,8 @@ * Setter for the principal id. * </p> * - * @param principalId The principal id. + * @param principalId + * The principal id. */ void setPrincipalId(long principalId); @@ -79,7 +80,8 @@ * Setter for the principal classname. * </p> * - * @param classname The principal classname. + * @param classname + * The principal classname. */ void setClassname(String classname); @@ -97,7 +99,8 @@ * Setter for isMappingOnly. * </p> * - * @param isMappingOnly The isMappingOnly. + * @param isMappingOnly + * The isMappingOnly. */ void setMappingOnly(boolean isMappingOnly); @@ -123,7 +126,8 @@ * preferences services. * </p> * - * @param fullPath The principal full path. + * @param fullPath + * The principal full path. */ void setFullPath(String fullPath); @@ -141,7 +145,8 @@ * Setter for the principal permissions. * </p> * - * @param permissions The principal permissions. + * @param permissions + * The principal permissions. */ void setPermissions(Collection permissions); @@ -159,7 +164,8 @@ * Setter for the creation date. * </p> * - * @param creationDate The creation date. + * @param creationDate + * The creation date. */ void setCreationDate(Timestamp creationDate); @@ -177,19 +183,26 @@ * Setter for the modified date. * </p> * - * @param modifiedDate The modified date. + * @param modifiedDate + * The modified date. */ void setModifiedDate(Timestamp modifiedDate); /** - * <p>Getter for the enabled state</p> + * <p> + * Getter for the enabled state + * </p> + * * @return true if enabled */ boolean isEnabled(); - + /** - * Setter for the enabled state</p> - * @param enabled The enabled state + * Setter for the enabled state + * </p> + * + * @param enabled + * The enabled state */ - void setEnabled(boolean enabled); + void setEnabled(boolean enabled); } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalRolePrincipal.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalRolePrincipal.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalRolePrincipal.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,32 +19,50 @@ import java.util.Collection; /** - * <p>Interface representing Jetspeed security role principal object model.</p> + * <p> + * Interface representing Jetspeed security role principal object model. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public interface InternalRolePrincipal extends InternalPrincipal { + /** - * <p>Getter for the user principals.</p> + * <p> + * Getter for the user principals. + * </p> + * * @return The user principals. */ Collection getUserPrincipals(); /** - * <p>Setter for the user principals.</p> - * @param userPrincipals The user principals. + * <p> + * Setter for the user principals. + * </p> + * + * @param userPrincipals + * The user principals. */ void setUserPrincipals(Collection userPrincipals); /** - * <p>Getter for the group principals.</p> + * <p> + * Getter for the group principals. + * </p> + * * @return The group principals. */ Collection getGroupPrincipals(); /** - * <p>Setter for the group principals.</p> - * @param groupPrincipals The group principals. + * <p> + * Setter for the group principals. + * </p> + * + * @param groupPrincipals + * The group principals. */ void setGroupPrincipals(Collection groupPrincipals); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalUserPrincipal.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalUserPrincipal.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/om/InternalUserPrincipal.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,44 +19,69 @@ import java.util.Collection; /** - * <p>Interface representing Jetspeed security user principal object model.</p> + * <p> + * Interface representing Jetspeed security user principal object model. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public interface InternalUserPrincipal extends InternalPrincipal { + /** - * <p>Getter for the security credentials.</p> + * <p> + * Getter for the security credentials. + * </p> + * * @return The credentials. */ Collection getCredentials(); /** - * <p>Setter for the security credentials.</p> - * @param credentials The credentials. + * <p> + * Setter for the security credentials. + * </p> + * + * @param credentials + * The credentials. */ void setCredentials(Collection credentials); /** - * <p>Getter for the role principals.</p> + * <p> + * Getter for the role principals. + * </p> + * * @return The role principals. */ Collection getRolePrincipals(); /** - * <p>Setter for the role principals.</p> - * @param rolePrincipals The role principals. + * <p> + * Setter for the role principals. + * </p> + * + * @param rolePrincipals + * The role principals. */ void setRolePrincipals(Collection rolePrincipals); /** - * <p>Getter for the group principals.</p> + * <p> + * Getter for the group principals. + * </p> + * * @return The group principals. */ Collection getGroupPrincipals(); /** - * <p>Setter for the group principals.</p> - * @param groupPrincipals The group principals. + * <p> + * Setter for the group principals. + * </p> + * + * @param groupPrincipals + * The group principals. */ void setGroupPrincipals(Collection groupPrincipals); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/AlgorithmUpgradeCredentialPasswordEncoder.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/AlgorithmUpgradeCredentialPasswordEncoder.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/AlgorithmUpgradeCredentialPasswordEncoder.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi; import org.apache.jetspeed.security.PasswordCredential; @@ -22,23 +22,32 @@ /** * <p> - * AlgorithmUpgradeCredentialPasswordEncoder which is provided with the InternalCredential as well - * to allow for migrating between two different encoding schemes. + * AlgorithmUpgradeCredentialPasswordEncoder which is provided with the + * InternalCredential as well to allow for migrating between two different + * encoding schemes. * </p> * <p> - * The extended encode method is *only* called in the context of validating an existing (old) password, - * and not used for creating or updating to a new password directl! + * The extended encode method is *only* called in the context of validating an + * existing (old) password, and not used for creating or updating to a new + * password directl! * </p> * <p> - * After successfull authentication, the recodeIfNeeded method will be called allowing to migrate to the new encryption scheme. + * After successfull authentication, the recodeIfNeeded method will be called + * allowing to migrate to the new encryption scheme. * </p> * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> * @version $Id$ */ -public interface AlgorithmUpgradeCredentialPasswordEncoder extends CredentialPasswordEncoder +public interface AlgorithmUpgradeCredentialPasswordEncoder extends + CredentialPasswordEncoder { - String encode(String userName, String clearTextPassword, InternalCredential credential) throws SecurityException; - void recodeIfNeeded(String userName, String clearTextPassword, InternalCredential credential) throws SecurityException; + + String encode(String userName, String clearTextPassword, + InternalCredential credential) throws SecurityException; + + void recodeIfNeeded(String userName, String clearTextPassword, + InternalCredential credential) throws SecurityException; + boolean usesOldEncodingAlgorithm(PasswordCredential credential); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/CredentialHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/CredentialHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/CredentialHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -27,7 +27,8 @@ * </p> * <p> * This provides a central placeholder for changing the mapping of user - * credentials. The default implementation only supports <code>PasswordCredential</code> + * credentials. The default implementation only supports + * <code>PasswordCredential</code> * </p> * <p> * A security implementation wanting to map additional credentials should do so @@ -38,99 +39,127 @@ */ public interface CredentialHandler { + /** * <p> * Gets the public credentials for the user. * </p> * - * @param username The username. + * @param username + * The username. * @return The set of public credentials. */ Set getPublicCredentials(String username); - + /** * <p> * Gets the private credentials for the user. * </p> * - * @param username The username. + * @param username + * The username. * @return The set of private credentials. */ Set getPrivateCredentials(String username); - + /** * <p> * Adds or updates a private password credential.<br> - * Note that there is no checking of the <code>oldPassword</code> and the provided password is - * assumed to be encoded. Hence no encoding will take place. + * Note that there is no checking of the <code>oldPassword</code> and the + * provided password is assumed to be encoded. Hence no encoding will take + * place. * * </p> * - * @param username The user to be updated. - * @param newPassword The new password. - * @throws SecurityException Throws a {@link SecurityException}. + * @param username + * The user to be updated. + * @param newPassword + * The new password. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - void importPassword(String userName, String newPassword) throws SecurityException; + void importPassword(String userName, String newPassword) + throws SecurityException; - /** * <p> * Adds or updates a private password credential.<br> - * If <code>oldPassword</code> is not null, the oldPassword will first be checked (authenticated).<br> + * If <code>oldPassword</code> is not null, the oldPassword will first be + * checked (authenticated).<br> * </p> * - * @param username The user to be updated. - * @param oldPassword The old password. - * @param newPassword The new password. - * @throws SecurityException Throws a {@link SecurityException}. + * @param username + * The user to be updated. + * @param oldPassword + * The old password. + * @param newPassword + * The new password. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - void setPassword(String userName, String oldPassword, String newPassword) throws SecurityException; + void setPassword(String userName, String oldPassword, String newPassword) + throws SecurityException; - - /** * <p> * Set the update required state of the user password credential. * </p> * - * @param userName The user name. - * @param updateRequired The update required state. - * @throws Throws a security exception. + * @param userName + * The user name. + * @param updateRequired + * The update required state. + * @throws Throws + * a security exception. */ - void setPasswordUpdateRequired(String userName, boolean updateRequired) throws SecurityException; + void setPasswordUpdateRequired(String userName, boolean updateRequired) + throws SecurityException; /** * <p> * Set the enabled state of the user password credential. * </p> * - * @param userName The user name. - * @param enabled The enabled state. - * @throws Throws a security exception. + * @param userName + * The user name. + * @param enabled + * The enabled state. + * @throws Throws + * a security exception. */ - void setPasswordEnabled(String userName, boolean enabled) throws SecurityException; + void setPasswordEnabled(String userName, boolean enabled) + throws SecurityException; /** * <p> - * Set the expiration date and the expired flag of the password credential.</p> + * Set the expiration date and the expired flag of the password credential. + * </p> * <p> - * If a date equal or before the current date is provided, the expired flag will be set to true, - * otherwise to false.</p> + * If a date equal or before the current date is provided, the expired flag + * will be set to true, otherwise to false. + * </p> * - * @param userName The user name. - * @param expirationDate The expiration date to set. - * @throws Throws a security exception. + * @param userName + * The user name. + * @param expirationDate + * The expiration date to set. + * @throws Throws + * a security exception. */ - void setPasswordExpiration(String userName, Date expirationDate) throws SecurityException; + void setPasswordExpiration(String userName, Date expirationDate) + throws SecurityException; /** * <p> * Authenticate a user. * </p> * - * @param userName The user name. - * @param password The user password. + * @param userName + * The user name. + * @param password + * The user password. * @return Whether or not a user is authenticated. */ - boolean authenticate(String userName, String password) throws SecurityException; + boolean authenticate(String userName, String password) + throws SecurityException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/CredentialPasswordEncoder.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/CredentialPasswordEncoder.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/CredentialPasswordEncoder.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi; import org.apache.jetspeed.security.SecurityException; @@ -28,5 +28,7 @@ */ public interface CredentialPasswordEncoder { - String encode(String userName, String clearTextPassword) throws SecurityException; + + String encode(String userName, String clearTextPassword) + throws SecurityException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/CredentialPasswordValidator.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/CredentialPasswordValidator.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/CredentialPasswordValidator.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi; import org.apache.jetspeed.security.SecurityException; @@ -24,9 +24,11 @@ * </p> * * @author <a href="mailto:ate ¡÷ apache.org">Ate Douma</a> - * @version $Id: CredentialPasswordValidator.java 187914 2004-11-08 22:36:04Z ate $ + * @version $Id: CredentialPasswordValidator.java 187914 2004-11-08 22:36:04Z + * ate $ */ public interface CredentialPasswordValidator { + void validate(String clearTextPassword) throws SecurityException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/GroupSecurityHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/GroupSecurityHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/GroupSecurityHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -39,44 +39,54 @@ */ public interface GroupSecurityHandler { + /** * <p> - * Gets the group principal for the group full path name {principal}.{subprincipal}. + * Gets the group principal for the group full path name + * {principal}.{subprincipal}. * </p> * - * @param groupFullPathName The group full path name. + * @param groupFullPathName + * The group full path name. * @return The <code>Principal</p> */ GroupPrincipal getGroupPrincipal(String groupFullPathName); - + /** * <p> * Sets the group principal in the backing store. * </p> * - * @param groupPrincipal The <code>GroupPrincipal</code>. - * @throws SecurityException Throws a {@link SecurityException}. + * @param groupPrincipal + * The <code>GroupPrincipal</code>. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - void setGroupPrincipal(GroupPrincipal groupPrincipal) throws SecurityException; - + void setGroupPrincipal(GroupPrincipal groupPrincipal) + throws SecurityException; + /** * <p> * Removes the group principal. * </p> * - * @param groupPrincipal The <code>GroupPrincipal</code>. - * @throws SecurityException Throws a {@link SecurityException}. + * @param groupPrincipal + * The <code>GroupPrincipal</code>. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - void removeGroupPrincipal(GroupPrincipal groupPrincipal) throws SecurityException; + void removeGroupPrincipal(GroupPrincipal groupPrincipal) + throws SecurityException; /** * <p> * Gets the an iterator of group principals for a given filter. * </p> * - * @param filter The filter. + * @param filter + * The filter. * @return The list of <code>Principal</code> */ List getGroupPrincipals(String filter); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/InternalPasswordCredentialInterceptor.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/InternalPasswordCredentialInterceptor.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/InternalPasswordCredentialInterceptor.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi; import java.util.Collection; @@ -24,98 +24,164 @@ /** * <p> - * Callback component interface used by {@link org.apache.jetspeed.security.spi.impl.DefaultCredentialHandler DefaultCredentialHandler} - * allowing injecting custom logic on certain events of the {@link InternalCredential}. + * Callback component interface used by + * {@link org.apache.jetspeed.security.spi.impl.DefaultCredentialHandler DefaultCredentialHandler} + * allowing injecting custom logic on certain events of the + * {@link InternalCredential}. * </p> * * @author <a href="mailto:ate ¡÷ apache.org">Ate Douma</a> - * @version $Id: InternalPasswordCredentialInterceptor.java 291016 2005-09-22 21:19:36Z ate $ + * @version $Id: InternalPasswordCredentialInterceptor.java 291016 2005-09-22 + * 21:19:36Z ate $ */ public interface InternalPasswordCredentialInterceptor { + /** * <p> - * Invoked after a password credential is loaded from the persistent store.</p> + * Invoked after a password credential is loaded from the persistent store. + * </p> * <p> - * If true is returned the credential is expected to be updated and its changes will be stored again.</p> + * If true is returned the credential is expected to be updated and its + * changes will be stored again. + * </p> * <p> - * A thrown SecurityException will be logged as an error and result in the credential to be ignored - * as if not existing (like for authentication).</p> + * A thrown SecurityException will be logged as an error and result in the + * credential to be ignored as if not existing (like for authentication). + * </p> * - * @param pcProvider provides callback access to for instance the configured {@link CredentialPasswordEncoder} and - * {@link CredentialPasswordValidator} - * @param userName the name of the principal to which the credential belongs - * @param credential the credential just loaded from the persistent store + * @param pcProvider + * provides callback access to for instance the configured + * {@link CredentialPasswordEncoder} and + * {@link CredentialPasswordValidator} + * @param userName + * the name of the principal to which the credential belongs + * @param credential + * the credential just loaded from the persistent store * @return true if the credential is updated * @throws SecurityException - * @see org.apache.jetspeed.security.spi.impl.DefaultCredentialHandler#getPasswordCredential(InternalUserPrincipal, String) - * @see org.apache.jetspeed.security.spi.impl.DefaultCredentialHandler#setPasswordExpiration(String, java.sql.Date) + * @see org.apache.jetspeed.security.spi.impl.DefaultCredentialHandler#getPasswordCredential(InternalUserPrincipal, + * String) + * @see org.apache.jetspeed.security.spi.impl.DefaultCredentialHandler#setPasswordExpiration(String, + * java.sql.Date) */ - boolean afterLoad(PasswordCredentialProvider pcProvider, String userName, InternalCredential credential) throws SecurityException; + boolean afterLoad(PasswordCredentialProvider pcProvider, String userName, + InternalCredential credential) throws SecurityException; /** * <p> - * Invoked during authentication after the provided password is compared against the one retrieved from - * the InternalCredential.</p> + * Invoked during authentication after the provided password is compared + * against the one retrieved from the InternalCredential. + * </p> * <p> - * If true is returned, the credential is expected to be updated and its {@link InternalCredential#isEnabled() enabled} - * and {@link InternalCredential#isExpired() expired} flags will checked if the credential is (still) valid.</p> + * If true is returned, the credential is expected to be updated and its + * {@link InternalCredential#isEnabled() enabled} and + * {@link InternalCredential#isExpired() expired} flags will checked if the + * credential is (still) valid. + * </p> * <p> - * Note: the enabled and expired flags are <em>only</em> checked if this method returns true.</p> + * Note: the enabled and expired flags are <em>only</em> checked if this + * method returns true. + * </p> * <p> - * A thrown SecurityException will be passed on to the authentication requestor.</p> - * - * @param internalUser the user to which the credential belongs - * @param userName the name of the principal to which the credential belongs - * @param credential the credential of the user - * @param authenticated true if the provided password matches the value of the credential + * A thrown SecurityException will be passed on to the authentication + * requestor. + * </p> + * + * @param internalUser + * the user to which the credential belongs + * @param userName + * the name of the principal to which the credential belongs + * @param credential + * the credential of the user + * @param authenticated + * true if the provided password matches the value of the + * credential * @return true if the credential is updated * @throws SecurityException - * @see org.apache.jetspeed.security.spi.impl.DefaultCredentialHandler#authenticate(String, String) + * @see org.apache.jetspeed.security.spi.impl.DefaultCredentialHandler#authenticate(String, + * String) */ - boolean afterAuthenticated(InternalUserPrincipal internalUser, String userName, InternalCredential credential, boolean authenticated) throws SecurityException; + boolean afterAuthenticated(InternalUserPrincipal internalUser, + String userName, InternalCredential credential, + boolean authenticated) throws SecurityException; /** * <p> - * Invoked when the first password credential is to be saved for a user.</p> + * Invoked when the first password credential is to be saved for a user. + * </p> * <p> - * This callback method can be used to set default values like the {@link InternalCredential#getExpirationDate() expiration date}.</p> + * This callback method can be used to set default values like the + * {@link InternalCredential#getExpirationDate() expiration date}. + * </p> * <p> - * A thrown SecurityException is passed on to the new password requestor.</p> + * A thrown SecurityException is passed on to the new password requestor. + * </p> * - * @param internalUser the user to which the credential belongs - * @param credentials the collection of credentials which will set on the user after (already contains the new credential) - * @param userName the name of the principal to which the credential belongs - * @param credential the credential of the user - * @param password the new password value (already set on the new credential) + * @param internalUser + * the user to which the credential belongs + * @param credentials + * the collection of credentials which will set on the user after + * (already contains the new credential) + * @param userName + * the name of the principal to which the credential belongs + * @param credential + * the credential of the user + * @param password + * the new password value (already set on the new credential) * @throws SecurityException - * @see org.apache.jetspeed.security.spi.impl.DefaultCredentialHandler#setPassword(String, String, String) + * @see org.apache.jetspeed.security.spi.impl.DefaultCredentialHandler#setPassword(String, + * String, String) */ - void beforeCreate(InternalUserPrincipal internalUser, Collection credentials, String userName, InternalCredential credential, String password) throws SecurityException; + void beforeCreate(InternalUserPrincipal internalUser, + Collection credentials, String userName, + InternalCredential credential, String password) + throws SecurityException; /** * <p> - * Invoked when a new password value is to be saved for a user.</p> + * Invoked when a new password value is to be saved for a user. + * </p> * <p> - * The new password value is <em>not</em> yet set on the provided credential when this callback is invoked. This allows - * custom history maintenance and/or auditing to be performed.</p> + * The new password value is <em>not</em> yet set on the provided + * credential when this callback is invoked. This allows custom history + * maintenance and/or auditing to be performed. + * </p> * <p> - * The provided authenticated flag can be used to differentiate between a new password value set directly by a user - * itself or through an administrative interface.</p> + * The provided authenticated flag can be used to differentiate between a + * new password value set directly by a user itself or through an + * administrative interface. + * </p> * <p> - * After this callback is invoked, the specified password value will be set, as well as a reset of the - * {@link InternalCredential#isUpdateRequired() updateRequired} flag, before the credential is saved.</p> + * After this callback is invoked, the specified password value will be set, + * as well as a reset of the + * {@link InternalCredential#isUpdateRequired() updateRequired} flag, before + * the credential is saved. + * </p> * <p> - * A thrown SecurityException is passed on to the set password requestor.</p> + * A thrown SecurityException is passed on to the set password requestor. + * </p> * - * @param internalUser the user to which the credential belongs - * @param credentials the collection of credentials which will set on the user after (already contains the new credential) - * @param userName the name of the principal to which the credential belongs - * @param credential the credential of the user - * @param password the new password value (already set on the new credential) - * @param authenticated true if the new password value is provided by the user directly + * @param internalUser + * the user to which the credential belongs + * @param credentials + * the collection of credentials which will set on the user after + * (already contains the new credential) + * @param userName + * the name of the principal to which the credential belongs + * @param credential + * the credential of the user + * @param password + * the new password value (already set on the new credential) + * @param authenticated + * true if the new password value is provided by the user + * directly * @throws SecurityException - * @see org.apache.jetspeed.security.spi.impl.DefaultCredentialHandler#setPassword(String, String, String) + * @see org.apache.jetspeed.security.spi.impl.DefaultCredentialHandler#setPassword(String, + * String, String) */ - void beforeSetPassword(InternalUserPrincipal internalUser, Collection credentials, String userName, InternalCredential credential, String password, boolean authenticated) throws SecurityException; + void beforeSetPassword(InternalUserPrincipal internalUser, + Collection credentials, String userName, + InternalCredential credential, String password, + boolean authenticated) throws SecurityException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/PasswordCredentialProvider.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/PasswordCredentialProvider.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/PasswordCredentialProvider.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi; import org.apache.jetspeed.security.PasswordCredential; @@ -30,9 +30,16 @@ */ public interface PasswordCredentialProvider { + Class getPasswordCredentialClass(); + CredentialPasswordValidator getValidator(); + CredentialPasswordEncoder getEncoder(); - PasswordCredential create(String userName, String password) throws SecurityException; - PasswordCredential create(String userName, InternalCredential credential) throws SecurityException; + + PasswordCredential create(String userName, String password) + throws SecurityException; + + PasswordCredential create(String userName, InternalCredential credential) + throws SecurityException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/RoleSecurityHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/RoleSecurityHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/RoleSecurityHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -39,45 +39,53 @@ */ public interface RoleSecurityHandler { - + /** * <p> - * Gets the role principal for the role full path name {principal}.{subprincipal}. + * Gets the role principal for the role full path name + * {principal}.{subprincipal}. * </p> * - * @param roleFullPathName The role full path name. + * @param roleFullPathName + * The role full path name. * @return The <code>Principal</p> */ RolePrincipal getRolePrincipal(String roleFullPathName); - + /** * <p> * Sets the role principal in the backing store. * </p> * - * @param rolePrincipal The <code>RolePrincipal</code>. - * @throws SecurityException Throws a {@link SecurityException}. + * @param rolePrincipal + * The <code>RolePrincipal</code>. + * @throws SecurityException + * Throws a {@link SecurityException}. */ void setRolePrincipal(RolePrincipal rolePrincipal) throws SecurityException; - + /** * <p> * Removes the role principal. * </p> * - * @param rolePrincipal The <code>RolePrincipal</code>. - * @throws SecurityException Throws a {@link SecurityException}. + * @param rolePrincipal + * The <code>RolePrincipal</code>. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - void removeRolePrincipal(RolePrincipal rolePrincipal) throws SecurityException; + void removeRolePrincipal(RolePrincipal rolePrincipal) + throws SecurityException; /** * <p> * Gets the an iterator of role principals for a given filter. * </p> * - * @param filter The filter. + * @param filter + * The filter. * @return The list of <code>Principal</code> */ List getRolePrincipals(String filter); - -} + +} Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/SecurityAccess.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/SecurityAccess.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/SecurityAccess.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,20 +28,23 @@ * SecurityAccess * </p> * <p> - * + * * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: SecurityAccess.java 290457 2005-09-20 14:14:31Z ate $ - * + * */ public interface SecurityAccess { + /** * <p> * Returns if a Internal UserPrincipal is defined for the user name. * </p> * - * @param username The user name. + * @param username + * The user name. * @return true if the user is known */ public boolean isKnownUser(String username); @@ -51,144 +54,175 @@ * Returns the {@link InternalUserPrincipal} from the user name. * </p> * - * @param username The user name. + * @param username + * The user name. * @return The {@link InternalUserPrincipal}. */ - InternalUserPrincipal getInternalUserPrincipal( String username ); + InternalUserPrincipal getInternalUserPrincipal(String username); /** * <p> * Returns the {@link InternalUserPrincipal} from the user name. * </p> * - * @param username The user name. - * @param isMappingOnly Whether a principal's purpose is for security mappping only. + * @param username + * The user name. + * @param isMappingOnly + * Whether a principal's purpose is for security mappping only. * @return The {@link InternalUserPrincipal}. */ - InternalUserPrincipal getInternalUserPrincipal( String username, boolean isMappingOnly ); + InternalUserPrincipal getInternalUserPrincipal(String username, + boolean isMappingOnly); /** * <p> * Returns a {@link InternalUserPrincipal} collection given the filter. * </p> * - * @param filter The filter. + * @param filter + * The filter. * @return Collection of {@link InternalUserPrincipal}. */ - Iterator getInternalUserPrincipals( String filter ); + Iterator getInternalUserPrincipals(String filter); /** * <p> * Returns a {@link InternalUserPrincipal} collection given the filter. * </p> * - * @param filter The filter. + * @param filter + * The filter. * @return The number of {@link InternalUserPrincipal}. */ - int getInternalUserCount( String filter ); + int getInternalUserCount(String filter); /** * <p> * Sets the given {@link InternalUserPrincipal}. * </p> * - * @param internalUser The {@link InternalUserPrincipal}. - * @param isMappingOnly Whether a principal's purpose is for security mappping only. - * @throws SecurityException Throws a {@link SecurityException}. + * @param internalUser + * The {@link InternalUserPrincipal}. + * @param isMappingOnly + * Whether a principal's purpose is for security mappping only. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - void setInternalUserPrincipal( InternalUserPrincipal internalUser, boolean isMappingOnly ) throws SecurityException; + void setInternalUserPrincipal(InternalUserPrincipal internalUser, + boolean isMappingOnly) throws SecurityException; /** * <p> * Remove the given {@link InternalUserPrincipal}. * </p> * - * @param internalUser The {@link InternalUserPrincipal}. - * @throws SecurityException Throws a {@link SecurityException}. + * @param internalUser + * The {@link InternalUserPrincipal}. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - void removeInternalUserPrincipal( InternalUserPrincipal internalUser ) throws SecurityException; + void removeInternalUserPrincipal(InternalUserPrincipal internalUser) + throws SecurityException; /** * <p> * Returns the {@link InternalRolePrincipal}from the role full path name. * </p> * - * @param roleFullPathName The role full path name. + * @param roleFullPathName + * The role full path name. * @return The {@link InternalRolePrincipal}. */ - InternalRolePrincipal getInternalRolePrincipal( String roleFullPathName ); + InternalRolePrincipal getInternalRolePrincipal(String roleFullPathName); /** * <p> * Sets the given {@link InternalRolePrincipal}. * </p> * - * @param internalRole The {@link InternalRolePrincipal}. - * @param isMappingOnly Whether a principal's purpose is for security mappping only. - * @throws SecurityException Throws a {@link SecurityException}. + * @param internalRole + * The {@link InternalRolePrincipal}. + * @param isMappingOnly + * Whether a principal's purpose is for security mappping only. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - void setInternalRolePrincipal( InternalRolePrincipal internalRole, boolean isMappingOnly ) throws SecurityException; + void setInternalRolePrincipal(InternalRolePrincipal internalRole, + boolean isMappingOnly) throws SecurityException; /** * <p> * Remove the given {@link InternalRolePrincipal}. * </p> * - * @param internalRole The {@link InternalRolePrincipal}. - * @throws SecurityException Throws a {@link SecurityException}. + * @param internalRole + * The {@link InternalRolePrincipal}. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - void removeInternalRolePrincipal( InternalRolePrincipal internalRole ) throws SecurityException; + void removeInternalRolePrincipal(InternalRolePrincipal internalRole) + throws SecurityException; /** * <p> * Returns the {@link InternalGroupPrincipal}from the group full path name. * </p> * - * @param groupFullPathName The group full path name. + * @param groupFullPathName + * The group full path name. * @return The {@link InternalGroupPrincipal}. */ - InternalGroupPrincipal getInternalGroupPrincipal( String groupFullPathName ); + InternalGroupPrincipal getInternalGroupPrincipal(String groupFullPathName); /** * <p> * Sets the given {@link InternalGroupPrincipal}. * </p> * - * @param internalGroup The {@link InternalGroupPrincipal}. - * @param isMappingOnly Whether a principal's purpose is for security mappping only. - * @throws SecurityException Throws a {@link SecurityException}. + * @param internalGroup + * The {@link InternalGroupPrincipal}. + * @param isMappingOnly + * Whether a principal's purpose is for security mappping only. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - void setInternalGroupPrincipal( InternalGroupPrincipal internalGroup, boolean isMappingOnly ) - throws SecurityException; + void setInternalGroupPrincipal(InternalGroupPrincipal internalGroup, + boolean isMappingOnly) throws SecurityException; /** * <p> * Remove the given {@link InternalGroupPrincipal}. * </p> * - * @param internalGroup The {@link InternalGroupPrincipal}. - * @throws SecurityException Throws a {@link SecurityException}. + * @param internalGroup + * The {@link InternalGroupPrincipal}. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - void removeInternalGroupPrincipal( InternalGroupPrincipal internalGroup ) throws SecurityException; + void removeInternalGroupPrincipal(InternalGroupPrincipal internalGroup) + throws SecurityException; /** * <p> * Returns a {@link InternalRolePrincipal} collection given the filter. * </p> * - * @param filter The filter. + * @param filter + * The filter. * @return Collection of {@link InternalRolePrincipal}. - */ + */ Iterator getInternalRolePrincipals(String filter); - + /** * <p> - * Returns a {@link InternalGroupPrincipal} collection of Group given the filter. + * Returns a {@link InternalGroupPrincipal} collection of Group given the + * filter. * </p> * - * @param filter The filter. + * @param filter + * The filter. * @return Collection of {@link InternalGroupPrincipal}. - */ + */ Iterator getInternalGroupPrincipals(String filter); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/SecurityMappingHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/SecurityMappingHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/SecurityMappingHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.security.spi; import java.util.Set; @@ -26,77 +26,87 @@ * This interface encapsulates the mapping between principals. * </p> * <p> - * This provides a central placeholder for changing the implementation - * of the mapping association between principals. + * This provides a central placeholder for changing the implementation of the + * mapping association between principals. * </p> * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat </a> */ public interface SecurityMappingHandler { - + /** * <p> - * Gets the {@link HierarchyResolver} to be used for resolving role hierarchy. + * Gets the {@link HierarchyResolver} to be used for resolving role + * hierarchy. * </p> * * @return The role {@link HierarchyResolver}. */ HierarchyResolver getRoleHierarchyResolver(); - + /** * <p> - * Sets the {@link HierarchyResolver} to be used for resolving role hierachy. + * Sets the {@link HierarchyResolver} to be used for resolving role + * hierachy. * </p> * - * @param roleHierarchyResolver The role {@link HierarchyResolver}. + * @param roleHierarchyResolver + * The role {@link HierarchyResolver}. */ void setRoleHierarchyResolver(HierarchyResolver roleHierarchyResolver); - + /** * <p> - * Gets the {@link HierarchyResolver} to be used for resolving group hierarchy. + * Gets the {@link HierarchyResolver} to be used for resolving group + * hierarchy. * </p> * * @return The role {@link HierarchyResolver}. */ HierarchyResolver getGroupHierarchyResolver(); - + /** * <p> * Sets the {@link HierarchyResolver} used for resolving group hierarchy. * </p> * - * @param groupHierarchyResolver The group {@link HierarchyResolver}. + * @param groupHierarchyResolver + * The group {@link HierarchyResolver}. */ void setGroupHierarchyResolver(HierarchyResolver groupHierarchyResolver); - + /** * <p> - * Gets the role principals for the given user according to the relevant hierarchy - * resolution rules. + * Gets the role principals for the given user according to the relevant + * hierarchy resolution rules. * </p> * - * @param username The user name. + * @param username + * The user name. * @return A set of <code>Principal</p> */ Set getRolePrincipals(String username); - + /** * <p> - * Sets the role principal on a given user. - * Existence of the role or the user must be checked prior to invoking this method. - * If a principal does not exist in the security mapping store, it will be created for the purpose of - * security mapping only. + * Sets the role principal on a given user. Existence of the role or the + * user must be checked prior to invoking this method. If a principal does + * not exist in the security mapping store, it will be created for the + * purpose of security mapping only. * </p> * - * @param username The user to add the role principal to. - * @param roleFullPathName The full path of the role principal to add. - * @throws SecurityException Throws a {@link SecurityException}. An exeption needs to be - * thrown if the user does not exist. + * @param username + * The user to add the role principal to. + * @param roleFullPathName + * The full path of the role principal to add. + * @throws SecurityException + * Throws a {@link SecurityException}. An exeption needs to be + * thrown if the user does not exist. */ - void setUserPrincipalInRole(String username, String roleFullPathName) throws SecurityException; - + void setUserPrincipalInRole(String username, String roleFullPathName) + throws SecurityException; + /** * <p> * Removes the role principal on a given user. @@ -106,119 +116,144 @@ * remove the record as well. * </p> * - * @param username The user to remove the role principal from. - * @param roleFullPathName The full path of the role principal to remove. - * @throws SecurityException Throws a {@link SecurityException}. An exeption needs to be - * thrown if the user does not exist. + * @param username + * The user to remove the role principal from. + * @param roleFullPathName + * The full path of the role principal to remove. + * @throws SecurityException + * Throws a {@link SecurityException}. An exeption needs to be + * thrown if the user does not exist. */ - void removeUserPrincipalInRole(String username, String roleFullPathName) throws SecurityException; + void removeUserPrincipalInRole(String username, String roleFullPathName) + throws SecurityException; /** * <p> - * Gets the role principals for the given group according to the relevant hierarchy - * resolution rules. + * Gets the role principals for the given group according to the relevant + * hierarchy resolution rules. * </p> * - * @param groupFullPathName The group full path name. + * @param groupFullPathName + * The group full path name. * @return A set of <code>Principal</p> */ Set getRolePrincipalsInGroup(String groupFullPathName); - + /** * <p> * Sets the role principal on a given user. * </p> * - * @param groupFullPathName The group to add the role principal to. - * @param roleFullPathName The full path of the role principal to add. - * @throws SecurityException Throws a {@link SecurityException}. An exeption needs to be - * thrown if the group does not exist. + * @param groupFullPathName + * The group to add the role principal to. + * @param roleFullPathName + * The full path of the role principal to add. + * @throws SecurityException + * Throws a {@link SecurityException}. An exeption needs to be + * thrown if the group does not exist. */ - void setRolePrincipalInGroup(String groupFullPathName, String roleFullPathName) throws SecurityException; - + void setRolePrincipalInGroup(String groupFullPathName, + String roleFullPathName) throws SecurityException; + /** * <p> * Removes the role principal on a given user. * </p> * - * @param groupFullPathName The group to remove the role principal from. - * @param roleFullPathName The full path of the role principal to remove. - * @throws SecurityException Throws a {@link SecurityException}. An exeption needs to be - * thrown if the group does not exist. + * @param groupFullPathName + * The group to remove the role principal from. + * @param roleFullPathName + * The full path of the role principal to remove. + * @throws SecurityException + * Throws a {@link SecurityException}. An exeption needs to be + * thrown if the group does not exist. */ - void removeRolePrincipalInGroup(String groupFullPathName, String roleFullPathName) throws SecurityException; - + void removeRolePrincipalInGroup(String groupFullPathName, + String roleFullPathName) throws SecurityException; + /** * <p> - * Gets the group principals for the given user according to the relevant hierarchy - * resolution rules. + * Gets the group principals for the given user according to the relevant + * hierarchy resolution rules. * </p> * - * @param username The user name. + * @param username + * The user name. * @return A set of <code>GroupPrincipal</p> */ Set getGroupPrincipals(String username); - + /** * <p> - * Gets the group principals for the given role according to the relevant hierarchy - * resolution rules. + * Gets the group principals for the given role according to the relevant + * hierarchy resolution rules. * </p> * - * @param roleFullPathName The role full path name. + * @param roleFullPathName + * The role full path name. * @return A set of <code>Principal</p> */ Set getGroupPrincipalsInRole(String roleFullPathName); - + /** * <p> - * Gets the user principals for the given role according to the relevant hierarchy - * resolution rules. + * Gets the user principals for the given role according to the relevant + * hierarchy resolution rules. * </p> * - * @param roleFullPathName The role full path name. + * @param roleFullPathName + * The role full path name. * @return A set of <code>Principal</p> - */ + */ Set getUserPrincipalsInRole(String roleFullPathName); - + /** * <p> - * Gets the user principals for the given group according to the relevant hierarchy - * resolution rules. + * Gets the user principals for the given group according to the relevant + * hierarchy resolution rules. * </p> * - * @param groupFullPathName The group full path name. + * @param groupFullPathName + * The group full path name. * @return A set of <code>Principal</p> - */ + */ Set getUserPrincipalsInGroup(String groupFullPathName); - + /** * <p> * Sets the user principal in the given group. * </p> * <p> - * Existence of the group or the user must be checked prior to invoking this method. - * If a principal does not exist in the security mapping store, it will be created for the purpose of - * security mapping only. + * Existence of the group or the user must be checked prior to invoking this + * method. If a principal does not exist in the security mapping store, it + * will be created for the purpose of security mapping only. * </p> * - * @param username The user to add to the group principal. - * @param groupFullPathName The full path of the group principal. - * @throws SecurityException Throws a {@link SecurityException}. An exeption needs to be - * thrown if the user does not exist. + * @param username + * The user to add to the group principal. + * @param groupFullPathName + * The full path of the group principal. + * @throws SecurityException + * Throws a {@link SecurityException}. An exeption needs to be + * thrown if the user does not exist. */ - void setUserPrincipalInGroup(String username, String groupFullPathName) throws SecurityException; - + void setUserPrincipalInGroup(String username, String groupFullPathName) + throws SecurityException; + /** * <p> * Removes the user principal from the given group. * </p> * - * @param username The user to remove from the group principal. - * @param groupFullPathName The full path of the group principal. - * @throws SecurityException Throws a {@link SecurityException}. An exeption needs to be - * thrown if the user does not exist. + * @param username + * The user to remove from the group principal. + * @param groupFullPathName + * The full path of the group principal. + * @throws SecurityException + * Throws a {@link SecurityException}. An exeption needs to be + * thrown if the user does not exist. */ - void removeUserPrincipalInGroup(String username, String groupFullPathName) throws SecurityException; + void removeUserPrincipalInGroup(String username, String groupFullPathName) + throws SecurityException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/UserSecurityHandler.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/UserSecurityHandler.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/security/spi/UserSecurityHandler.java 2008-05-16 01:54:54 UTC (rev 940) @@ -40,71 +40,84 @@ */ public interface UserSecurityHandler { + /** * <p> - * Checks if a UserPrincipal exists + * Checks if a UserPrincipal exists + * * @param userName * @return true if a UserPrincipal exists */ boolean isUserPrincipal(String userName); - + /** * <p> * Gets the user principal for the given user name. * </p> * - * @param username The user name. + * @param username + * The user name. * @return The <code>Principal</p> */ Principal getUserPrincipal(String username); - + /** * <p> * Gets the an iterator of user principals for a given filter. * </p> * - * @param filter The filter. + * @param filter + * The filter. * @return The list of <code>Principal</code> */ List getUserPrincipals(String filter); - + /** * <p> * Gets the number of user principals for a given filter. * </p> * - * @param filter The filter. + * @param filter + * The filter. * @return The number of <code>Principal</code> */ int getUserCount(String filter); - + /** * <p> * Adds a new user principal in the backing store. * </p> * - * @param userPrincipal The new <code>UserPrincipal</code>. - * @throws SecurityException Throws a {@link SecurityException}. + * @param userPrincipal + * The new <code>UserPrincipal</code>. + * @throws SecurityException + * Throws a {@link SecurityException}. */ void addUserPrincipal(UserPrincipal userPrincipal) throws SecurityException; - + /** * <p> * Updates the user principal in the backing store. * </p> * - * @param userPrincipal The <code>UserPrincipal</code>. - * @throws SecurityException Throws a {@link SecurityException}. + * @param userPrincipal + * The <code>UserPrincipal</code>. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - void updateUserPrincipal(UserPrincipal userPrincipal) throws SecurityException; - + void updateUserPrincipal(UserPrincipal userPrincipal) + throws SecurityException; + /** * <p> * Removes the user principal. * </p> * - * @param userPrincipal The <code>UserPrincipal</code>. - * @throws SecurityException Throws a {@link SecurityException}. + * @param userPrincipal + * The <code>UserPrincipal</code>. + * @throws SecurityException + * Throws a {@link SecurityException}. */ - void removeUserPrincipal(UserPrincipal userPrincipal) throws SecurityException; + void removeUserPrincipal(UserPrincipal userPrincipal) + throws SecurityException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/serializer/JetspeedSerializer.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/serializer/JetspeedSerializer.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/serializer/JetspeedSerializer.java 2008-05-16 01:54:54 UTC (rev 940) @@ -28,8 +28,8 @@ * standalone java application for seeding a new database or from a running * portal as an administrative backup/restore function. * <p> - * The XML file needs to indicate whether passwords used in credentials - * are plain text or whether they are encoded. The import algoritm can determine - + * The XML file needs to indicate whether passwords used in credentials are + * plain text or whether they are encoded. The import algoritm can determine - * prior to reading users - which encode/decode scheme was used and if <none> or * <implements PasswordEncodingService> then we store plain passwords (Note that * that alone requires the resulting XML to be encoded!!!!!) @@ -74,12 +74,13 @@ .intern(); public final static String KEY_PROCESS_PERMISSIONS = "process_permissions" - .intern(); - + .intern(); + public final static String KEY_PROCESS_USER_PREFERENCES = "process_user_preferences" .intern(); + public final static String KEY_PROCESS_PORTAL_PREFERENCES = "process_portal_preferences" - .intern(); + .intern(); public final static String KEY_OVERWRITE_EXISTING = "overwrite_existing" .intern(); @@ -87,17 +88,22 @@ public final static String KEY_BACKUP_BEFORE_PROCESS = "backup_before_process" .intern(); - /** export/import instructions secondary*/ - public final static String KEY_PROCESS_ENTITIES = "process_entities".intern(); - public final static String KEY_PROCESS_PREFERENCES = "process_preferences".intern(); - - - - /**<p> the main tag in the XML file */ - public final static String TAG_SNAPSHOT = "Snapshot"; - public final static String TAG_SECONDARYSNAPSHOT = "SecondaryData"; - + /** export/import instructions secondary */ + public final static String KEY_PROCESS_ENTITIES = "process_entities" + .intern(); + + public final static String KEY_PROCESS_PREFERENCES = "process_preferences" + .intern(); + /** + * <p> + * the main tag in the XML file + */ + public final static String TAG_SNAPSHOT = "Snapshot"; + + public final static String TAG_SECONDARYSNAPSHOT = "SecondaryData"; + + /** * hand the serializer an existing component manager to access the * environment * Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/serializer/JetspeedSerializerFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/serializer/JetspeedSerializerFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/serializer/JetspeedSerializerFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -16,29 +16,34 @@ */ package org.apache.jetspeed.serializer; - /** * Jetspeed Serializer Factory * - * <p>Interface for creating serializers. Serializer keep some state so they should be recreated as needed - * We will revisit this class in the refactoring in 2.2 as Im not really sure why we need a primary and secondary class - * but I think its related to the dependencies fixed in these issues, see: - * http://issues.apache.org/jira/browse/JS2-771 and http://issues.apache.org/jira/browse/JS2-770 - * </p> + * <p> + * Interface for creating serializers. Serializer keep some state so they should + * be recreated as needed We will revisit this class in the refactoring in 2.2 + * as Im not really sure why we need a primary and secondary class but I think + * its related to the dependencies fixed in these issues, see: + * http://issues.apache.org/jira/browse/JS2-771 and + * http://issues.apache.org/jira/browse/JS2-770 + * </p> */ public interface JetspeedSerializerFactory { /** Create basic Jetspeed Serializer */ public final static String PRIMARY = "primary"; + /** Create a secondary Jetspeed Serializer (registry data) */ public final static String SECONDARY = "secondary"; - + /** * Create a Jetspeed Serializer of one of the two supported types - * @param serializerType eithe PRIMARY OR SECONDARY + * + * @param serializerType + * eithe PRIMARY OR SECONDARY * @return */ public JetspeedSerializer create(String serializerType); - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/serializer/SerializerException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/serializer/SerializerException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/serializer/SerializerException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -20,51 +20,112 @@ import org.apache.jetspeed.i18n.KeyedMessage; /** - * <p>Exception throwns by members of the security service.</p> - * + * <p> + * Exception throwns by members of the security service. + * </p> + * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public class SerializerException extends JetspeedException { + /** The serial version uid. */ private static final long serialVersionUID = -8823877029853488431L; - /** <p>Component Manager does not exist exception message.</p> */ - public static final KeyedMessage COMPONENTMANAGER_DOES_NOT_EXIST = new KeyedMessage("The component manager {0} does not exist."); + /** + * <p> + * Component Manager does not exist exception message. + * </p> + */ + public static final KeyedMessage COMPONENTMANAGER_DOES_NOT_EXIST = new KeyedMessage( + "The component manager {0} does not exist."); - /** <p>Creating the serilized Object failed </p> */ - public static final KeyedMessage GET_EXISTING_OBJECTS = new KeyedMessage("Get existing objects for {0} failed with message {1}"); + /** + * <p> + * Creating the serilized Object failed + * </p> + */ + public static final KeyedMessage GET_EXISTING_OBJECTS = new KeyedMessage( + "Get existing objects for {0} failed with message {1}"); - /** <p>Creating the serilized Object failed </p> */ - public static final KeyedMessage CREATE_SERIALIZED_OBJECT_FAILED = new KeyedMessage("Creating a serialized representation of {0} failed with message {1}"); + /** + * <p> + * Creating the serilized Object failed + * </p> + */ + public static final KeyedMessage CREATE_SERIALIZED_OBJECT_FAILED = new KeyedMessage( + "Creating a serialized representation of {0} failed with message {1}"); - /** <p>Creating the serilized Object failed </p> */ - public static final KeyedMessage CREATE_OBJECT_FAILED = new KeyedMessage("Creating an instance from a serialized representation of {0} failed with message {1}"); + /** + * <p> + * Creating the serilized Object failed + * </p> + */ + public static final KeyedMessage CREATE_OBJECT_FAILED = new KeyedMessage( + "Creating an instance from a serialized representation of {0} failed with message {1}"); - /** <p>Component Manager already initialized</p> */ - public static final KeyedMessage COMPONENT_MANAGER_EXISTS = new KeyedMessage("Component Manager already established"); + /** + * <p> + * Component Manager already initialized + * </p> + */ + public static final KeyedMessage COMPONENT_MANAGER_EXISTS = new KeyedMessage( + "Component Manager already established"); + /** + * <p> + * Filename already exists + * </p> + */ + public static final KeyedMessage FILE_ALREADY_EXISTS = new KeyedMessage( + "File {0} already exists"); - /** <p>Filename already exists</p> */ - public static final KeyedMessage FILE_ALREADY_EXISTS = new KeyedMessage("File {0} already exists"); + /** + * <p> + * Filename already exists + * </p> + */ + public static final KeyedMessage FILE_BACKUP_FAILED = new KeyedMessage( + "File {0} backup failed. Could create new name."); - /** <p>Filename already exists</p> */ - public static final KeyedMessage FILE_BACKUP_FAILED = new KeyedMessage("File {0} backup failed. Could create new name."); + /** + * <p> + * io error + * </p> + */ + public static final KeyedMessage FILE_PROCESSING_ERROR = new KeyedMessage( + "Error processing File {0} : {1}"); - /** <p>io error</p> */ - public static final KeyedMessage FILE_PROCESSING_ERROR = new KeyedMessage("Error processing File {0} : {1}"); - /** <p>writer error</p> */ - public static final KeyedMessage FILE_WRITER_ERROR = new KeyedMessage("Error creating Writer for {0} : {1}"); - /** <p>reader error</p> */ - public static final KeyedMessage FILE_READER_ERROR = new KeyedMessage("Error creating Reader for {0} : {1}"); - - /** <p>version problem - version in XML file is not compatible with current environment </p> */ - public static final KeyedMessage INCOMPETIBLE_VERSION = new KeyedMessage("Incompetible version in {0} : CurrentVersion = {1}, RequestedVersion = {2}"); - - /** - * <p>Default Constructor.</p> + * <p> + * writer error + * </p> */ + public static final KeyedMessage FILE_WRITER_ERROR = new KeyedMessage( + "Error creating Writer for {0} : {1}"); + + /** + * <p> + * reader error + * </p> + */ + public static final KeyedMessage FILE_READER_ERROR = new KeyedMessage( + "Error creating Reader for {0} : {1}"); + + /** + * <p> + * version problem - version in XML file is not compatible with current + * environment + * </p> + */ + public static final KeyedMessage INCOMPETIBLE_VERSION = new KeyedMessage( + "Incompetible version in {0} : CurrentVersion = {1}, RequestedVersion = {2}"); + + /** + * <p> + * Default Constructor. + * </p> + */ public SerializerException() { super(); @@ -74,10 +135,14 @@ { super(t); } - + /** - * <p>Constructor with exception message.</p> - * @param message The exception message. + * <p> + * Constructor with exception message. + * </p> + * + * @param message + * The exception message. */ public SerializerException(KeyedMessage typedMessage) { @@ -85,9 +150,14 @@ } /** - * <p>Constructor with exception message and nested exception.</p> - * @param msg The exception message. - * @param nested Nested exception. + * <p> + * Constructor with exception message and nested exception. + * </p> + * + * @param msg + * The exception message. + * @param nested + * Nested exception. */ public SerializerException(KeyedMessage msg, Throwable nested) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOContext.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOContext.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOContext.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,30 +5,35 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.sso; /** -* <p>Represents SSO Remote and Portal principal and credentials</p> -* -* @author <a href="mailto:rogerrut ¡÷ apache.org">Roger Ruttimann</a> -*/ + * <p> + * Represents SSO Remote and Portal principal and credentials + * </p> + * + * @author <a href="mailto:rogerrut ¡÷ apache.org">Roger Ruttimann</a> + */ -public interface SSOContext +public interface SSOContext { - // Getters only. The interface shouldn't allow any changes - public long getRemotePrincipalId(); - public String getPortalPrincipalName(); - public String getRemotePrincipalName(); - public String getRemoteCredential(); + // Getters only. The interface shouldn't allow any changes + public long getRemotePrincipalId(); + + public String getPortalPrincipalName(); + + public String getRemotePrincipalName(); + + public String getRemoteCredential(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOCookie.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOCookie.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOCookie.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /*Created on: Nov 23, 2005 */ @@ -27,56 +27,59 @@ * * @author Roger Ruttimann <rogerrut ¡÷ apache.org> * - * Class sthat handles the cookies created for SSO - * principals - * + * Class sthat handles the cookies created for SSO principals + * */ -public interface SSOCookie { +public interface SSOCookie +{ - /** Setters and getters for cookie properties */ - - /** - * - * @param cookieId - */ - void setCookieId(int cookieId); - /** - * - * @return - */ - int getCookieId(); - - /** - * - * @param cookieValue - */ - void setCookie(String cookieValue); - /** - * - * @return - */ - String getCookie(); - - /** - * - * @param createDate - */ - void setCreateDate(Timestamp createDate); - /** - * - * @return - */ - Timestamp getCreateDate(); - - /** - * - * @return - */ - Collection getRemotePrincipals(); - - /** - * - * @param remotePrincipals - */ - void setRemotePrincipals(Collection remotePrincipals); + /** Setters and getters for cookie properties */ + + /** + * + * @param cookieId + */ + void setCookieId(int cookieId); + + /** + * + * @return + */ + int getCookieId(); + + /** + * + * @param cookieValue + */ + void setCookie(String cookieValue); + + /** + * + * @return + */ + String getCookie(); + + /** + * + * @param createDate + */ + void setCreateDate(Timestamp createDate); + + /** + * + * @return + */ + Timestamp getCreateDate(); + + /** + * + * @return + */ + Collection getRemotePrincipals(); + + /** + * + * @param remotePrincipals + */ + void setRemotePrincipals(Collection remotePrincipals); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,90 +5,144 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.sso; import org.apache.jetspeed.exception.JetspeedException; /** -* <p>Exception throwns by members of the sso service.</p> -* -* @author <a href="mailto:rogerrut @apache.org">Roger Ruttimann</a> -*/ + * <p> + * Exception throwns by members of the sso service. + * </p> + * + * @author <a href="mailto:rogerrut + * @apache.org">Roger Ruttimann</a> + */ -public class SSOException extends JetspeedException { +public class SSOException extends JetspeedException +{ - /** <p>Adding the credentials to the request failed.</p> */ - public static final String BASIC_AUTHENTICATION_ADD_FAILED = "Adding the credentials to the request failed."; - - /** <p>The site has no Single Sign On credentails attached.</p> */ - public static final String NO_CREDENTIALS_FOR_SITE = "The site has no Single Sign On credentails attached."; + /** + * <p> + * Adding the credentials to the request failed. + * </p> + */ + public static final String BASIC_AUTHENTICATION_ADD_FAILED = "Adding the credentials to the request failed."; - /** <p>Adding the credentials for site failed.</p> */ - public static final String FAILED_ADDING_CREDENTIALS_FOR_SITE = "Adding the credential for site failed."; - - /** <p>Removing the credential for site failed.</p> */ - public static final String FAILED_REMOVING_CREDENTIALS_FOR_SITE = "Removing the credential for site failed."; - - /** <p>Failed to store site info in database.</p> */ - public static final String FAILED_STORING_SITE_INFO_IN_DB = "Failed to store site info in database."; - - /** <p>Requested principal doesn't exist in Principal store.</p> */ - public static final String REQUESTED_PRINCIPAL_DOES_NOT_EXIST = "Requested principal doesn't exist in Principal store."; - - /** <p>Could not remove Principla from SITE mapping table.</p> */ - public static final String FAILED_REMOVING_PRINCIPAL_FROM_MAPPING_TABLE_FOR_SITE = "Could not remove Principal from SITE mapping table."; - - /** <p>Could not add Principal from SITE mapping table.</p> */ - public static final String FAILED_ADDING_PRINCIPAL_TO_MAPPING_TABLE_FOR_SITE = "Could not add Principal from SITE mapping table."; - - /** <p>Site/principal has remote principal. Calll update.</p> */ - public static final String REMOTE_PRINCIPAL_EXISTS_CALL_UPDATE = "Remote principal for site/principal already exists. Call update instead"; - - /** - * <p>Default Constructor.</p> - */ - public SSOException() - { - super(); - } + /** + * <p> + * The site has no Single Sign On credentails attached. + * </p> + */ + public static final String NO_CREDENTIALS_FOR_SITE = "The site has no Single Sign On credentails attached."; - /** - * <p>Constructor with exception message.</p> - * @param message The exception message. - */ - public SSOException(String message) - { - super(message); - } + /** + * <p> + * Adding the credentials for site failed. + * </p> + */ + public static final String FAILED_ADDING_CREDENTIALS_FOR_SITE = "Adding the credential for site failed."; - /** - * <p>Constructor with nested exception.</p> - * @param nested Nested exception. - */ - public SSOException(Throwable nested) - { - super(nested); - } + /** + * <p> + * Removing the credential for site failed. + * </p> + */ + public static final String FAILED_REMOVING_CREDENTIALS_FOR_SITE = "Removing the credential for site failed."; - /** - * <p>Constructor with exception message and nested exception.</p> - * @param msg The exception message. - * @param nested Nested exception. - */ - public SSOException(String msg, Throwable nested) - { - super(msg, nested); - } + /** + * <p> + * Failed to store site info in database. + * </p> + */ + public static final String FAILED_STORING_SITE_INFO_IN_DB = "Failed to store site info in database."; + /** + * <p> + * Requested principal doesn't exist in Principal store. + * </p> + */ + public static final String REQUESTED_PRINCIPAL_DOES_NOT_EXIST = "Requested principal doesn't exist in Principal store."; + + /** + * <p> + * Could not remove Principla from SITE mapping table. + * </p> + */ + public static final String FAILED_REMOVING_PRINCIPAL_FROM_MAPPING_TABLE_FOR_SITE = "Could not remove Principal from SITE mapping table."; + + /** + * <p> + * Could not add Principal from SITE mapping table. + * </p> + */ + public static final String FAILED_ADDING_PRINCIPAL_TO_MAPPING_TABLE_FOR_SITE = "Could not add Principal from SITE mapping table."; + + /** + * <p> + * Site/principal has remote principal. Calll update. + * </p> + */ + public static final String REMOTE_PRINCIPAL_EXISTS_CALL_UPDATE = "Remote principal for site/principal already exists. Call update instead"; + + /** + * <p> + * Default Constructor. + * </p> + */ + public SSOException() + { + super(); + } + + /** + * <p> + * Constructor with exception message. + * </p> + * + * @param message + * The exception message. + */ + public SSOException(String message) + { + super(message); + } + + /** + * <p> + * Constructor with nested exception. + * </p> + * + * @param nested + * Nested exception. + */ + public SSOException(Throwable nested) + { + super(nested); + } + + /** + * <p> + * Constructor with exception message and nested exception. + * </p> + * + * @param msg + * The exception message. + * @param nested + * Nested exception. + */ + public SSOException(String msg, Throwable nested) + { + super(msg, nested); + } + } - Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOPrincipal.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOPrincipal.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOPrincipal.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,195 +5,212 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.sso; +import java.sql.Timestamp; import java.util.Collection; -import java.sql.Timestamp; import org.apache.jetspeed.security.om.InternalUserPrincipal; /** */ -public interface SSOPrincipal { +public interface SSOPrincipal +{ - /** - * addRemotePrincipal() - * @param principal - * Adds remote principal to the main (logged in) principal - */ - public void addRemotePrincipal(InternalUserPrincipal principal); - /** - * <p> - * Getter for the principal id. - * </p> - * - * @return The principal id. - */ - long getPrincipalId(); + /** + * addRemotePrincipal() + * + * @param principal + * Adds remote principal to the main (logged in) principal + */ + public void addRemotePrincipal(InternalUserPrincipal principal); - /** - * <p> - * Setter for the principal id. - * </p> - * - * @param principalId The principal id. - */ - void setPrincipalId(long principalId); + /** + * <p> + * Getter for the principal id. + * </p> + * + * @return The principal id. + */ + long getPrincipalId(); - /** - * <p> - * Getter for the principal classname. - * </p> - * - * @return The principal classname. - */ - String getClassname(); + /** + * <p> + * Setter for the principal id. + * </p> + * + * @param principalId + * The principal id. + */ + void setPrincipalId(long principalId); - /** - * <p> - * Setter for the principal classname. - * </p> - * - * @param classname The principal classname. - */ - void setClassname(String classname); + /** + * <p> + * Getter for the principal classname. + * </p> + * + * @return The principal classname. + */ + String getClassname(); - /** - * <p> - * Getter for isMappingOnly. - * </p> - * - * @return The isMappingOnly. - */ - boolean isMappingOnly(); + /** + * <p> + * Setter for the principal classname. + * </p> + * + * @param classname + * The principal classname. + */ + void setClassname(String classname); - /** - * <p> - * Setter for isMappingOnly. - * </p> - * - * @param isMappingOnly The isMappingOnly. - */ - void setMappingOnly(boolean isMappingOnly); + /** + * <p> + * Getter for isMappingOnly. + * </p> + * + * @return The isMappingOnly. + */ + boolean isMappingOnly(); - /** - * <p> - * Getter for the principal full path. - * </p> - * <p> - * The full path allows to retrieve the principal preferences from the - * preferences services. - * </p> - * - * @return The principal full path. - */ - String getFullPath(); + /** + * <p> + * Setter for isMappingOnly. + * </p> + * + * @param isMappingOnly + * The isMappingOnly. + */ + void setMappingOnly(boolean isMappingOnly); - /** - * <p> - * Setter for the principal name. - * </p> - * <p> - * The full path allows to retrieve the principal preferences from the - * preferences services. - * </p> - * - * @param fullPath The principal full path. - */ - void setFullPath(String fullPath); + /** + * <p> + * Getter for the principal full path. + * </p> + * <p> + * The full path allows to retrieve the principal preferences from the + * preferences services. + * </p> + * + * @return The principal full path. + */ + String getFullPath(); - /** - * <p> - * Getter for the principal permissions. - * </p> - * - * @return The principal permissions. - */ - Collection getPermissions(); + /** + * <p> + * Setter for the principal name. + * </p> + * <p> + * The full path allows to retrieve the principal preferences from the + * preferences services. + * </p> + * + * @param fullPath + * The principal full path. + */ + void setFullPath(String fullPath); - /** - * <p> - * Setter for the principal permissions. - * </p> - * - * @param permissions The principal permissions. - */ - void setPermissions(Collection permissions); + /** + * <p> + * Getter for the principal permissions. + * </p> + * + * @return The principal permissions. + */ + Collection getPermissions(); - /** - * <p> - * Getter for creation date. - * </p> - * - * @return The creation date. - */ - Timestamp getCreationDate(); + /** + * <p> + * Setter for the principal permissions. + * </p> + * + * @param permissions + * The principal permissions. + */ + void setPermissions(Collection permissions); - /** - * <p> - * Setter for the creation date. - * </p> - * - * @param creationDate The creation date. - */ - void setCreationDate(Timestamp creationDate); + /** + * <p> + * Getter for creation date. + * </p> + * + * @return The creation date. + */ + Timestamp getCreationDate(); - /** - * <p> - * Getter for the modified date. - * </p> - * - * @return The modified date. - */ - Timestamp getModifiedDate(); + /** + * <p> + * Setter for the creation date. + * </p> + * + * @param creationDate + * The creation date. + */ + void setCreationDate(Timestamp creationDate); - /** - * <p> - * Setter for the modified date. - * </p> - * - * @param modifiedDate The modified date. - */ - void setModifiedDate(Timestamp modifiedDate); + /** + * <p> + * Getter for the modified date. + * </p> + * + * @return The modified date. + */ + Timestamp getModifiedDate(); - /** - * <p>Getter for the enabled state</p> - * @return true if enabled - */ - boolean isEnabled(); - - /** - * Setter for the enabled state</p> - * @param enabled The enabled state - */ - void setEnabled(boolean enabled); - - /** - * Getter for the remotePrincipals. - */ - public Collection getRemotePrincipals(); - - /** - * Setter for the remotePrincipals - */ - public void setRemotePrincipals(Collection remotePrincipals) ; + /** + * <p> + * Setter for the modified date. + * </p> + * + * @param modifiedDate + * The modified date. + */ + void setModifiedDate(Timestamp modifiedDate); - /** - * Getter for the siteID. - */ - public int getSiteID(); - /** - * Setter for thesiteID - */ - public void setSiteID(int siteID); + /** + * <p> + * Getter for the enabled state + * </p> + * + * @return true if enabled + */ + boolean isEnabled(); + + /** + * Setter for the enabled state + * </p> + * + * @param enabled + * The enabled state + */ + void setEnabled(boolean enabled); + + /** + * Getter for the remotePrincipals. + */ + public Collection getRemotePrincipals(); + + /** + * Setter for the remotePrincipals + */ + public void setRemotePrincipals(Collection remotePrincipals); + + /** + * Getter for the siteID. + */ + public int getSiteID(); + + /** + * Setter for thesiteID + */ + public void setSiteID(int siteID); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOProvider.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOProvider.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOProvider.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.sso; import java.util.Collection; @@ -22,111 +22,123 @@ import javax.security.auth.Subject; - /** -* <p>Utility component to handle SSO requests</p> -* -* @author <a href="mailto:rogerrut ¡÷ apache.org">Roger Ruttimann</a> -*/ + * <p> + * Utility component to handle SSO requests + * </p> + * + * @author <a href="mailto:rogerrut ¡÷ apache.org">Roger Ruttimann</a> + */ public interface SSOProvider -{ - /** - * Init - * Called from the Spring Framework to initialize SSO Provider component - * @throws Exception - */ - void init() throws Exception; - - /** - * This method first authenticates the the SSOSite and then forwards the request - * to the destination URL. The content will be returned as a string. - * If the SSOSite and the url match only one call will be executed since the - * authentication will be done while getting the result page. - * - * @param userID - * @param url - * @param SSOSite - * @param bRefresh if true it refreshes the proxy connection if false a cached proxy will be used - * @return - * @throws SSOException - */ - public String useSSO(Subject subject, String url, String SSOSite, boolean bRefresh) throws SSOException; - - /** - * Same as the method above except that the user will be authenticated against all - * SSOSites defined for the user before going to the destination site. - * - * @param userID - * @param url - * @param bRefresh if true it refreshes the proxy connection if false a cached proxy will be used - * @return - * @throws SSOException - */ - public String useSSO(Subject subject, String url, boolean bRefresh) throws SSOException; - - - /** - * Retrive cookies for an user by User full path - * @param fullPath - * @return - */ - Collection getCookiesForUser(String fullPath); - - /** - * Retrive Cookies by Subject - * @param user - * @return - */ - Collection getCookiesForUser(Subject user); - - - /** - * Public API's for SSO functinality - * @return - */ - boolean hasSSOCredentials(Subject subject, String site); - - SSOContext getCredentials(Subject subject, String site) - throws SSOException; - - void addCredentialsForSite(Subject subject, String remoteUser, String site, String pwd) - throws SSOException; - - void updateCredentialsForSite(Subject subject, String remoteUser, String site, String pwd) - throws SSOException; - - void removeCredentialsForSite(Subject subject, String site) - throws SSOException; - +{ + /** - * return a list of SSOContext objects containing - * both the portal principal, remote principal, and credentials + * Init Called from the Spring Framework to initialize SSO Provider + * component * + * @throws Exception + */ + void init() throws Exception; + + /** + * This method first authenticates the the SSOSite and then forwards the + * request to the destination URL. The content will be returned as a string. + * If the SSOSite and the url match only one call will be executed since the + * authentication will be done while getting the result page. + * + * @param userID + * @param url + * @param SSOSite + * @param bRefresh + * if true it refreshes the proxy connection if false a cached + * proxy will be used + * @return + * @throws SSOException + */ + public String useSSO(Subject subject, String url, String SSOSite, + boolean bRefresh) throws SSOException; + + /** + * Same as the method above except that the user will be authenticated + * against all SSOSites defined for the user before going to the destination + * site. + * + * @param userID + * @param url + * @param bRefresh + * if true it refreshes the proxy connection if false a cached + * proxy will be used + * @return + * @throws SSOException + */ + public String useSSO(Subject subject, String url, boolean bRefresh) + throws SSOException; + + /** + * Retrive cookies for an user by User full path + * + * @param fullPath + * @return + */ + Collection getCookiesForUser(String fullPath); + + /** + * Retrive Cookies by Subject + * + * @param user + * @return + */ + Collection getCookiesForUser(Subject user); + + /** + * Public API's for SSO functinality + * + * @return + */ + boolean hasSSOCredentials(Subject subject, String site); + + SSOContext getCredentials(Subject subject, String site) throws SSOException; + + void addCredentialsForSite(Subject subject, String remoteUser, String site, + String pwd) throws SSOException; + + void updateCredentialsForSite(Subject subject, String remoteUser, + String site, String pwd) throws SSOException; + + void removeCredentialsForSite(Subject subject, String site) + throws SSOException; + + /** + * return a list of SSOContext objects containing both the portal principal, + * remote principal, and credentials + * * @param site - * @return list SSOContext objects + * @return list SSOContext objects */ List getPrincipalsForSite(SSOSite site); - + Iterator getSites(String filter); - + SSOSite getSite(String siteUrl); - + void updateSite(SSOSite site) throws SSOException; - - void addSite(String siteName, String siteUrl) throws SSOException; - + + void addSite(String siteName, String siteUrl) throws SSOException; + void removeSite(SSOSite site) throws SSOException; - + /** * addCredentialsForSite() + * * @param fullPath * @param remoteUser * @param site * @param pwd * @throws SSOException */ - void addCredentialsForSite(String fullPath, String remoteUser, String site, String pwd) throws SSOException; - + void addCredentialsForSite(String fullPath, String remoteUser, String site, + String pwd) throws SSOException; + /** * Add credentials inside a transaction using existing ssoSite * @@ -136,42 +148,50 @@ * @param pwd * @throws SSOException */ - public void addCredentialsForSite(SSOSite ssoSite, Subject subject, String remoteUser, String pwd) - throws SSOException; - + public void addCredentialsForSite(SSOSite ssoSite, Subject subject, + String remoteUser, String pwd) throws SSOException; + /** * removeCredentialsForSite() + * * @param fullPath * @param site * @throws SSOException */ - void removeCredentialsForSite(String fullPath, String site) throws SSOException; + void removeCredentialsForSite(String fullPath, String site) + throws SSOException; /* Retrive site information */ String getSiteURL(String site); - String getSiteName(String site); - - void setRealmForSite(String site, String realm) throws SSOException; - String getRealmForSite(String site) throws SSOException; - + + String getSiteName(String site); + + void setRealmForSite(String site, String realm) throws SSOException; + + String getRealmForSite(String site) throws SSOException; + /** * Get all SSOSites that the principal has access to + * * @param userId * @return */ public Collection getSitesForPrincipal(String userId); - + /** * Add a new site that uses Challenge / Response Authentication + * * @param siteName * @param siteUrl * @param realm * @throws SSOException */ - public void addSiteChallengeResponse(String siteName, String siteUrl, String realm) throws SSOException; - + public void addSiteChallengeResponse(String siteName, String siteUrl, + String realm) throws SSOException; + /** * Add a new site that uses Form Authentication + * * @param siteName * @param siteUrl * @param realm @@ -179,6 +199,8 @@ * @param pwdField * @throws SSOException */ - public void addSiteFormAuthenticated(String siteName, String siteUrl, String realm, String userField, String pwdField) throws SSOException; - + public void addSiteFormAuthenticated(String siteName, String siteUrl, + String realm, String userField, String pwdField) + throws SSOException; + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOSite.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOSite.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/sso/SSOSite.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,140 +5,150 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.sso; import java.util.Collection; -import org.apache.jetspeed.sso.SSOPrincipal; /** * Interface SSOSite * * @author rruttimann - * + * */ -public interface SSOSite { - /** - * @return Returns the isAllowUserSet. - */ - public boolean isAllowUserSet() ; - - /** - * @param isAllowUserSet The isAllowUserSet to set. - */ - public void setAllowUserSet(boolean isAllowUserSet); - - /** - * @return Returns the isCertificateRequired. - */ - public boolean isCertificateRequired(); - - /** - * @param isCertificateRequired The isCertificateRequired to set. - */ - public void setCertificateRequired(boolean isCertificateRequired); - - /** - * @return Returns the name. - */ - public String getName() ; - - /** - * @param name The name to set. - */ - public void setName(String name) ; - - /** - * @return Returns the principals. - */ - public Collection getPrincipals() ; - - /** - * @param principals The principals to set. - */ - public void setPrincipals(Collection principals); - - /** - * @return Returns the siteId. - */ - public int getSiteId() ; - - /** - * @param siteId The siteId to set. - */ - public void setSiteId(int siteId) ; - - /** - * @return Returns the siteURL. - */ - public String getSiteURL() ; - - /** - * @param siteURL The siteURL to set. - */ - public void setSiteURL(String siteURL) ; - - - - /** - * Adds the SSOPrincipal to the principals collection - * - */ - public void addPrincipal(SSOPrincipal principal) throws SSOException; - - /** - * removePrincipal() - * removes a principal from the principals collection - * - */ - public void removePrincipal(long principalId) throws SSOException; - - /** - * getRemotePrincipals +public interface SSOSite +{ + + /** + * @return Returns the isAllowUserSet. */ - public Collection getRemotePrincipals(); - + public boolean isAllowUserSet(); + /** - * setRemotePrincipals + * @param isAllowUserSet + * The isAllowUserSet to set. */ + public void setAllowUserSet(boolean isAllowUserSet); + + /** + * @return Returns the isCertificateRequired. + */ + public boolean isCertificateRequired(); + + /** + * @param isCertificateRequired + * The isCertificateRequired to set. + */ + public void setCertificateRequired(boolean isCertificateRequired); + + /** + * @return Returns the name. + */ + public String getName(); + + /** + * @param name + * The name to set. + */ + public void setName(String name); + + /** + * @return Returns the principals. + */ + public Collection getPrincipals(); + + /** + * @param principals + * The principals to set. + */ + public void setPrincipals(Collection principals); + + /** + * @return Returns the siteId. + */ + public int getSiteId(); + + /** + * @param siteId + * The siteId to set. + */ + public void setSiteId(int siteId); + + /** + * @return Returns the siteURL. + */ + public String getSiteURL(); + + /** + * @param siteURL + * The siteURL to set. + */ + public void setSiteURL(String siteURL); + + /** + * Adds the SSOPrincipal to the principals collection + * + */ + public void addPrincipal(SSOPrincipal principal) throws SSOException; + + /** + * removePrincipal() removes a principal from the principals collection + * + */ + public void removePrincipal(long principalId) throws SSOException; + + /** + * getRemotePrincipals + */ + public Collection getRemotePrincipals(); + + /** + * setRemotePrincipals + */ public void setRemotePrincipals(Collection remotePrincipals); - + /** - * Define the Authentication methods. - * Supported are: Challenge Response and From based + * Define the Authentication methods. Supported are: Challenge Response and + * From based */ public void setFormAuthentication(boolean isFormAuthentication); - + /** - * Form authentication requires two fields that hold the credential + * Form authentication requires two fields that hold the credential * information for the request. */ - - public void configFormAuthentication(String formUserField, String formPwdField); - + + public void configFormAuthentication(String formUserField, + String formPwdField); + /* * Uses Challenge Response mechanism for authentication */ - public void setChallengeResponseAuthentication(boolean isChallengeResponseAuthentication); - + public void setChallengeResponseAuthentication( + boolean isChallengeResponseAuthentication); + public boolean isChallangeResponseAuthentication(); - public boolean isFormAuthentication(); - public String getFormPwdField(); - public void setFormPwdField(String formPwdField); + public boolean isFormAuthentication(); - public String getFormUserField(); - public void setFormUserField(String formUserField); - - public void setRealm(String realm); - public String getRealm(); + public String getFormPwdField(); + + public void setFormPwdField(String formPwdField); + + public String getFormUserField(); + + public void setFormUserField(String formUserField); + + public void setRealm(String realm); + + public String getRealm(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/statistics/PortalStatistics.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/statistics/PortalStatistics.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/statistics/PortalStatistics.java 2008-05-16 01:54:54 UTC (rev 940) @@ -46,8 +46,8 @@ * * <PRE> * - * 192.168.2.3 - johndoe [25/Oct/2005:11:44:40 PDT] "GET - * /jetspeed/DatabaseBrowserTest HTTP/1.1" 200 - + * 192.168.2.3 - johndoe [25/Oct/2005:11:44:40 PDT] "GET + * /jetspeed/DatabaseBrowserTest HTTP/1.1" 200 - * * </PRE> * @@ -59,8 +59,8 @@ * <PRE> * * LOG TYPE FORMAT OF %r FIELD -------------- ---------------------------- - * Portlet access "PORTLET <page-path><portlet-name>" Page access "PAGE - * <page-path>" User logout "LOGOUT" + * Portlet access "PORTLET <page-path><portlet-name>" Page access "PAGE + * <page-path>" User logout "LOGOUT" * * </PRE> * @@ -71,10 +71,13 @@ */ public interface PortalStatistics { + public static final String QUERY_TYPE_PORTLET = "portlet"; + public static final String QUERY_TYPE_USER = "user"; + public static final String QUERY_TYPE_PAGE = "page"; - + public static final String HTTP_OK = "200"; public static final String HTTP_UNAUTHORIZED = "401"; @@ -155,18 +158,18 @@ public int getNumberOfLoggedInUsers(); public List getListOfLoggedInUsers(); - + /** * Factory to create new statistics query criteria * * @return a newly create statistics empty criteria */ public StatisticsQueryCriteria createStatisticsQueryCriteria(); - + /** * Factory to create new, empty, aggregate statistics object. * - * @return unpopulated AggregateStatistics object + * @return unpopulated AggregateStatistics object */ public AggregateStatistics getDefaultEmptyAggregateStatistics(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/statistics/UserStats.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/statistics/UserStats.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/statistics/UserStats.java 2008-05-16 01:54:54 UTC (rev 940) @@ -37,10 +37,10 @@ public void setNumberOfSession(int number); public void setUsername(String username); - - public void setInetAddress(InetAddress inetAddress); + public void setInetAddress(InetAddress inetAddress); + public InetAddress getInetAddress(); - + public void setInetAddressFromIp(String ip) throws UnknownHostException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/deploy/DeployFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/deploy/DeployFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/deploy/DeployFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -24,13 +24,15 @@ */ public interface DeployFactory { + /** * getInstance - * + * * @param inputWarPath * @param outputWarPath * @param stripLoggers * @return Deploy instance */ - public Deploy getInstance(String inputWarPath, String outputWarPath, boolean stripLoggers) throws Exception; + public Deploy getInstance(String inputWarPath, String outputWarPath, + boolean stripLoggers) throws Exception; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/pamanager/PortletApplicationManagement.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/pamanager/PortletApplicationManagement.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/pamanager/PortletApplicationManagement.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,33 +19,49 @@ import org.apache.jetspeed.components.portletregistry.RegistryException; import org.apache.jetspeed.util.FileSystemHelper; - /** * PortletApplicationManagement - * + * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> - * @version $Id: PortletApplicationManagement.java 593180 2007-11-08 15:00:35Z weaver $ + * @version $Id: PortletApplicationManagement.java 593180 2007-11-08 15:00:35Z + * weaver $ */ public interface PortletApplicationManagement { - public static final String LOCAL_PA_PREFIX = "jetspeed-"; - - public boolean isStarted(); - /** - * Allows deployment to override the default of using the <code>contextName</code> as the - * context path. - * - * @param contextName - * @param contextPath - * @param warStruct - * @param paClassLoader - * @throws RegistryException - */ - void startPortletApplication(String contextName, String contextPath, FileSystemHelper warStruct, ClassLoader paClassLoader) throws RegistryException; - void startPortletApplication(String contextName, FileSystemHelper warStruct, ClassLoader paClassLoader) throws RegistryException; - void stopPortletApplication(String contextName) throws RegistryException; - void startLocalPortletApplication(String contextName, FileSystemHelper warStruct, ClassLoader paClassLoader) throws RegistryException; - void startInternalApplication(String contextName) throws RegistryException; - void stopLocalPortletApplication(String contextName) throws RegistryException; - public void unregisterPortletApplication(String paName) throws RegistryException; + + public static final String LOCAL_PA_PREFIX = "jetspeed-"; + + public boolean isStarted(); + + /** + * Allows deployment to override the default of using the + * <code>contextName</code> as the context path. + * + * @param contextName + * @param contextPath + * @param warStruct + * @param paClassLoader + * @throws RegistryException + */ + void startPortletApplication(String contextName, String contextPath, + FileSystemHelper warStruct, ClassLoader paClassLoader) + throws RegistryException; + + void startPortletApplication(String contextName, + FileSystemHelper warStruct, ClassLoader paClassLoader) + throws RegistryException; + + void stopPortletApplication(String contextName) throws RegistryException; + + void startLocalPortletApplication(String contextName, + FileSystemHelper warStruct, ClassLoader paClassLoader) + throws RegistryException; + + void startInternalApplication(String contextName) throws RegistryException; + + void stopLocalPortletApplication(String contextName) + throws RegistryException; + + public void unregisterPortletApplication(String paName) + throws RegistryException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/ApplicationServerManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/ApplicationServerManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/ApplicationServerManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -26,96 +26,101 @@ * </p> * <p> * Implementations of this interface are used primarily by the - * {@link org.apache.jetspeed.tools.pamanager.ApplicationServerPAM} - * to interact with the servlet container that is supporting the web - * appliaction portion of deployed the portlet applications. + * {@link org.apache.jetspeed.tools.pamanager.ApplicationServerPAM} to interact + * with the servlet container that is supporting the web appliaction portion of + * deployed the portlet applications. * </p> + * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> * @version $Id: ApplicationServerManager.java 516448 2007-03-09 16:25:47Z ate $ - * + * */ public interface ApplicationServerManager { + /** * * <p> * start * </p> - * Starts the application represented by the context path, <code>appPath</code> - * - * @param appPath path to restart + * Starts the application represented by the context path, + * <code>appPath</code> + * + * @param appPath + * path to restart * @return container-specific status message - * @throws HttpException * @throws IOException */ - ApplicationServerManagerResult start( String appPath ) throws IOException; - + ApplicationServerManagerResult start(String appPath) throws IOException; + /** * * <p> * stop * </p> - * Stops the application represented by the context path, <code>appPath</code> + * Stops the application represented by the context path, + * <code>appPath</code> * * @param appPath * @return container-specific status message - * @throws HttpException * @throws IOException */ - ApplicationServerManagerResult stop( String appPath ) throws IOException; - + ApplicationServerManagerResult stop(String appPath) throws IOException; + /** * * <p> * reload * </p> - * Reloads the application represented by the context path, <code>appPath</code>. This - * must included re-reading the web.xml and reloading all classpath resources. - * + * Reloads the application represented by the context path, + * <code>appPath</code>. This must included re-reading the web.xml and + * reloading all classpath resources. + * * @param appPath * @return container-specific status message - * @throws HttpException * @throws IOException */ - ApplicationServerManagerResult reload( String appPath ) throws IOException; - + ApplicationServerManagerResult reload(String appPath) throws IOException; + /** * * <p> * undeploy * </p> - * Undeploys the application represented by the context path, <code>appPath</cod + * Undeploys the application represented by the context path, + * <code>appPath</cod * @param appPath * @return container-specific status message - * @throws HttpException * @throws IOException */ - ApplicationServerManagerResult undeploy( String appPath ) throws IOException; - + ApplicationServerManagerResult undeploy(String appPath) throws IOException; + /** * * <p> * deploy * </p> - * - * Deploys the contents of the InputStream, <code>is</code>, into the parent servlet - * container using the specified <code>appPath</code> as the context path. * + * Deploys the contents of the InputStream, <code>is</code>, into the + * parent servlet container using the specified <code>appPath</code> as + * the context path. + * * @param appPath * @param is - * @param size size (in bytes) of InputStream <code>is</code> + * @param size + * size (in bytes) of InputStream <code>is</code> * @return - * @throws HttpException * @throws IOException */ - ApplicationServerManagerResult deploy( String appPath, InputStream is, int size ) throws IOException; + ApplicationServerManagerResult deploy(String appPath, InputStream is, + int size) throws IOException; /** * * <p> * getHostPort * </p> - * + * * @return */ int getHostPort(); @@ -125,26 +130,27 @@ * <p> * getHostUrl * </p> - * + * * @return */ String getHostUrl(); - + /** * * <p> * isConnected * </p> - * + * * @return */ boolean isConnected(); - + /** - * <p> Returns the name of the target directory or archive where the portlet app will be - * deployed as known to the application server + * <p> + * Returns the name of the target directory or archive where the portlet app + * will be deployed as known to the application server * </p> */ String getAppServerTarget(String appName); - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/ApplicationServerManagerResult.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/ApplicationServerManagerResult.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/tools/pamanager/servletcontainer/ApplicationServerManagerResult.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,33 +18,38 @@ /** * ApplicationServerManagerResult - * + * * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> - * @version $Id: ApplicationServerManagerResult.java 516448 2007-03-09 16:25:47Z ate $ + * @version $Id: ApplicationServerManagerResult.java 516448 2007-03-09 16:25:47Z + * ate $ */ public class ApplicationServerManagerResult { + private boolean ok; - private String message; - private String response; - - public ApplicationServerManagerResult(boolean ok, String message, String response) + + private String message; + + private String response; + + public ApplicationServerManagerResult(boolean ok, String message, + String response) { this.ok = ok; this.message = message; this.response = response; } - + public boolean isOk() { return ok; } - + public String getMessage() { return message; } - + public String getResponse() { return response; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/userinfo/UserAttributeRetrievalException.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/userinfo/UserAttributeRetrievalException.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/userinfo/UserAttributeRetrievalException.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,15 +5,15 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.userinfo; /** @@ -23,11 +23,12 @@ * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ -public class UserAttributeRetrievalException extends Exception +public class UserAttributeRetrievalException extends Exception { - public UserAttributeRetrievalException(Exception e) - { - super(e); - } + public UserAttributeRetrievalException(Exception e) + { + super(e); + } + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/userinfo/UserAttributeSource.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/userinfo/UserAttributeSource.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/userinfo/UserAttributeSource.java 2008-05-16 01:54:54 UTC (rev 940) @@ -5,18 +5,17 @@ * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.apache.jetspeed.userinfo; - import java.util.Collection; import java.util.Map; @@ -31,8 +30,9 @@ * @author <a href="mailto:taylor ¡÷ apache.org">David Sean Taylor</a> * @version $Id: $ */ -public interface UserAttributeSource -{ - Map getUserAttributeMap(Subject subject, Collection userAttributeRefs, RequestContext context) - throws UserAttributeRetrievalException; +public interface UserAttributeSource +{ + + Map getUserAttributeMap(Subject subject, Collection userAttributeRefs, + RequestContext context) throws UserAttributeRetrievalException; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/userinfo/UserInfoManager.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/userinfo/UserInfoManager.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/userinfo/UserInfoManager.java 2008-05-16 01:54:54 UTC (rev 940) @@ -18,44 +18,60 @@ import java.util.Map; +import javax.portlet.PortletRequest; + import org.apache.jetspeed.request.RequestContext; - import org.apache.pluto.om.common.ObjectID; /** - * <p>The {@link UserInfoManager} retrieve the Map that will be set as a + * <p> + * The {@link UserInfoManager} retrieve the Map that will be set as a * <code>(PortletRequest.USER_INFO</code> request attribute for a specific - * portlet application</p> - * <p>The portlet specification defines user info as follow (PLT 17):</p> - * <p>Portlets can obtain an unmodifiable Map object containing the user attributes, - * of user associated with the current request, from the request attributes. - * The Map object can be retrieved using the USER_INFO constant defined in the - * PortletRequest interface. If the request is done in the context of an - * un-authenticated user, calls to the getAttribute method of the request - * using the USER_INFO constant must return null. If the user is - * authenticated and there are no user attributes available, the Map must - * be an empty Map. The Map object must contain a String name value pair for each available user - * attribute. The Map object should only contain user attributes that have been mapped - * during deployment.</p> - * <p>Portlets can obtain an unmodifiable Map object containing the user attributes, of user - * associated with the current request, from the request attributes. The Map object can be - * retrieved using the USER_INFO constant defined in the PortletRequest interface. If the - * request is done in the context of an un-authenticated user, calls to the getAttribute - * method of the request using the USER_INFO constant must return null. If the user is - * authenticated and there are no user attributes available, the Map must be an empty Map. - * The Map object must contain a String name value pair for each available user attribute. - * The Map object should only contain user attributes that have been mapped during - * deployment.</p> + * portlet application + * </p> + * <p> + * The portlet specification defines user info as follow (PLT 17): + * </p> + * <p> + * Portlets can obtain an unmodifiable Map object containing the user + * attributes, of user associated with the current request, from the request + * attributes. The Map object can be retrieved using the USER_INFO constant + * defined in the PortletRequest interface. If the request is done in the + * context of an un-authenticated user, calls to the getAttribute method of the + * request using the USER_INFO constant must return null. If the user is + * authenticated and there are no user attributes available, the Map must be an + * empty Map. The Map object must contain a String name value pair for each + * available user attribute. The Map object should only contain user attributes + * that have been mapped during deployment. + * </p> + * <p> + * Portlets can obtain an unmodifiable Map object containing the user + * attributes, of user associated with the current request, from the request + * attributes. The Map object can be retrieved using the USER_INFO constant + * defined in the PortletRequest interface. If the request is done in the + * context of an un-authenticated user, calls to the getAttribute method of the + * request using the USER_INFO constant must return null. If the user is + * authenticated and there are no user attributes available, the Map must be an + * empty Map. The Map object must contain a String name value pair for each + * available user attribute. The Map object should only contain user attributes + * that have been mapped during deployment. + * </p> * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> */ public interface UserInfoManager { - + /** - * <p>Provide the user info map of user attributes for a given portlet application.</p> - * @param oid The portlet application object id. - * @param context The request context. + * <p> + * Provide the user info map of user attributes for a given portlet + * application. + * </p> + * + * @param oid + * The portlet application object id. + * @param context + * The request context. * @return The {@link PortletRequest.USER_INFO} map. */ Map getUserInfoMap(ObjectID oid, RequestContext context); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/util/FileSystemHelper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/util/FileSystemHelper.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/util/FileSystemHelper.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,36 +22,39 @@ /** * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver</a> - * - * TODO To change the template for this generated type comment go to - * Window - Preferences - Java - Code Generation - Code and Comments + * + * TODO To change the template for this generated type comment go to Window - + * Preferences - Java - Code Generation - Code and Comments */ public interface FileSystemHelper { + /** * * <p> * copyFrom * </p> - * - * @param directory Directory to copy content from - * @throws {@link java.io.IlleaglArgumentException} if the <code>directory.isDirectory</code> - * returns <code>false</code> + * + * @param directory + * Directory to copy content from + * @throws {@link java.io.IlleaglArgumentException} + * if the <code>directory.isDirectory</code> returns + * <code>false</code> */ void copyFrom(File directory) throws IOException; - + /** * * <p> * copyFrom * </p> - * + * * @param directory * @param fileFilter * @throws IOException */ void copyFrom(File directory, FileFilter fileFilter) throws IOException; - + /** * * <p> @@ -59,49 +62,49 @@ * </p> * Removes the underlying directory structure from the root directory down. * - * @return <code>true</code> if the removal war successful, otherwise returns - * <code>false</code>. + * @return <code>true</code> if the removal war successful, otherwise + * returns <code>false</code>. */ boolean remove(); - + /** * * <p> * getRootDirectory * </p> - * + * * @return the root of the directory structure */ - File getRootDirectory(); - + File getRootDirectory(); + /** * * <p> * close * </p> - * - * Cleans up resources opened up specifically by this FileSystemHelper - * + * + * Cleans up resources opened up specifically by this FileSystemHelper + * */ void close() throws IOException; - + /** * * <p> * getSourcePath * </p> * - * Returns the true location of this FileSystemHelper backing object on - * the file system. This IS NOT always as the path of the object returned - * from the {@link getRootDirectory} method. - * - * @return the true location of this FileSystemHelper backing object. + * Returns the true location of this FileSystemHelper backing object on the + * file system. This IS NOT always as the path of the object returned from + * the {@link getRootDirectory} method. + * + * @return the true location of this FileSystemHelper backing object. */ String getSourcePath(); - + /** - * Given a path to a resource in this file system, return a checksum - * on that resource's content. + * Given a path to a resource in this file system, return a checksum on that + * resource's content. * * @param pathToResource * @return checksum of the content of the resource Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/util/Queue.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/util/Queue.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/jetspeed-api/src/java/org/apache/jetspeed/util/Queue.java 2008-05-16 01:54:54 UTC (rev 940) @@ -19,24 +19,25 @@ /** * Queue interface similar to the java.util.Stack interface - * + * * @author <a href="mailto:raphael ¡÷ apache.org">Rapha\u00ebl Luta</a> * @version $Id: Queue.java 516448 2007-03-09 16:25:47Z ate $ */ public interface Queue extends java.util.List { - /** - * Adds a new object into the queue - */ - public void push(Object obj); - /** - * Gets the first object in the queue and remove it from the queue - */ - public Object pop(); + /** + * Adds a new object into the queue + */ + public void push(Object obj); - /** - * Gets the first object in the queue without removing it from the queue - */ - public Object peek(); + /** + * Gets the first object in the queue and remove it from the queue + */ + public Object pop(); + + /** + * Gets the first object in the queue without removing it from the queue + */ + public Object peek(); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/ActionLayoutPortlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/ActionLayoutPortlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/ActionLayoutPortlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -34,7 +34,9 @@ import org.apache.jetspeed.portlets.layout.util.ResourceBundleFactory; import org.apache.jetspeed.request.RequestContext; -public class ActionLayoutPortlet extends MultiColumnPortlet { +public class ActionLayoutPortlet extends MultiColumnPortlet +{ + protected final static Log log = LogFactory .getLog(ActionLayoutPortlet.class); @@ -73,89 +75,113 @@ private ResourceBundleFactory resourceBundleFactory; - public void init(PortletConfig config) throws PortletException { + public void init(PortletConfig config) throws PortletException + { super.init(config); // pageManager pageManager = (PageManager) config.getPortletContext().getAttribute( CommonPortletServices.CPS_PAGE_MANAGER_COMPONENT); - if (null == pageManager) { - throw new PortletException( - "Failed to find the Page Manager on portlet initialization"); - } + if (null == pageManager) { throw new PortletException( + "Failed to find the Page Manager on portlet initialization"); } long timeToLive = 1 * 60 * 60 * 1000; String value = config.getInitParameter(RESOURCE_TIMEOUT); - if (value != null && !value.equals("")) { - try { + if (value != null && !value.equals("")) + { + try + { timeToLive = Long.parseLong(value); - } catch (NumberFormatException e) { } + catch (NumberFormatException e) + { + } } resourceBundleFactory = new ResourceBundleFactory(timeToLive); } public void render(RenderRequest request, RenderResponse response) - throws PortletException, IOException { + throws PortletException, IOException + { request.setAttribute(RESOURCE_BUNDLE_FACTORY, resourceBundleFactory); super.render(request, response); } public void processAction(ActionRequest request, ActionResponse response) - throws PortletException, IOException { + throws PortletException, IOException + { String targetClass = request.getParameter(TARGET_CLASS); if (targetClass != null - && targetClass.equals(ACTION_LAYOUT_PORTLET_CLASSNAME)) { + && targetClass.equals(ACTION_LAYOUT_PORTLET_CLASSNAME)) + { RequestContext requestContext = (RequestContext) request .getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); ContentPage requestPage = requestContext.getPage(); PageEditAccess pageEditAccess = (PageEditAccess) requestContext .getAttribute(PortalReservedParameters.PAGE_EDIT_ACCESS_ATTRIBUTE); - if (requestPage == null || pageEditAccess == null) { - throw new PortletException( - "Current request page or PageEditAccess not available."); - } + if (requestPage == null || pageEditAccess == null) { throw new PortletException( + "Current request page or PageEditAccess not available."); } - if (checkAction(request, ADD_NEW_PAGE)) { + if (checkAction(request, ADD_NEW_PAGE)) + { // new page addNewPage(request, response); - } else if (checkAction(request, ADD_NEW_FOLDER)) { + } + else if (checkAction(request, ADD_NEW_FOLDER)) + { // new folder addNewFolder(request, response); - } else if (checkAction(request, ADD_PORTLET)) { + } + else if (checkAction(request, ADD_PORTLET)) + { // add portlet addPortlet(request, response); } - } else { + } + else + { super.processAction(request, response); } } - private String getId(String id, String title) { - if (id != null && !id.equals("")) { - if (StringUtils.isAlphanumeric(id)) { + private String getId(String id, String title) + { + if (id != null && !id.equals("")) + { + if (StringUtils.isAlphanumeric(id)) + { return id; - } else { - try { + } + else + { + try + { return URLEncoder.encode(id, "UTF-8").replaceAll("[+%]", "-"); - } catch (UnsupportedEncodingException e) { } + catch (UnsupportedEncodingException e) + { + } } } - try { + try + { return URLEncoder.encode(title, "UTF-8").replaceAll("[+%]", "-"); - } catch (UnsupportedEncodingException e) { + } + catch (UnsupportedEncodingException e) + { return RandomStringUtils.randomAlphanumeric(10); } } - protected void addNewPage(ActionRequest request, ActionResponse response) { + protected void addNewPage(ActionRequest request, ActionResponse response) + { String path = request.getParameter(PATH); String id = request.getParameter(ID); String title = request.getParameter(TITLE); - if (title == null || path == null) { + if (title == null || path == null) + { // TODO throws an exception return; } @@ -170,7 +196,8 @@ boolean pageHidden = false; Folder folder = getFolder(path); - if (folder == null) { + if (folder == null) + { // TODO throws an exception log.error("Could not find a folder: " + path); return; @@ -178,9 +205,12 @@ // add page String pagePath = folder.getPath(); - if (pagePath.endsWith(Folder.PATH_SEPARATOR)) { + if (pagePath.endsWith(Folder.PATH_SEPARATOR)) + { pagePath = pagePath + pageName; - } else { + } + else + { pagePath = pagePath + Folder.PATH_SEPARATOR + pageName; } Page childPage = getPageManager().newPage(pagePath); @@ -191,33 +221,45 @@ childPage.setShortTitle(pageShortTitle); childPage.setSkin(desktopTheme); childPage.setHidden(pageHidden); - try { + try + { getPageManager().updatePage(childPage); getPageManager().reset(); - } catch (PageNotUpdatedException e) { + } + catch (PageNotUpdatedException e) + { // TODO throws an exception log.error("Could not add a page: " + path, e); return; - } catch (NodeException e) { + } + catch (NodeException e) + { // TODO throws an exception log.error("Could not add a page: " + path, e); return; } List orderList = folder.getDocumentOrder(); - if (orderList != null) { + if (orderList != null) + { String name = childPage.getName(); - if (orderList.indexOf(name) < 0) { + if (orderList.indexOf(name) < 0) + { orderList.add(name); folder.setDocumentOrder(orderList); - try { + try + { getPageManager().updateFolder(folder); getPageManager().reset(); - } catch (FolderNotUpdatedException e) { + } + catch (FolderNotUpdatedException e) + { // TODO throws an exception log.error("Could not change a page order: " + path, e); return; - } catch (NodeException e) { + } + catch (NodeException e) + { // TODO throws an exception log.error("Could not change a page order: " + path, e); return; @@ -227,11 +269,13 @@ } - public void addNewFolder(ActionRequest request, ActionResponse response) { + public void addNewFolder(ActionRequest request, ActionResponse response) + { String path = request.getParameter(PATH); String id = request.getParameter(ID); String title = request.getParameter(TITLE); - if (title == null || path == null) { + if (title == null || path == null) + { // TODO throws an exception log.error("title or path are null: title=" + title + ", path=" + path); @@ -248,16 +292,20 @@ boolean folderHidden = false; Folder folder = getFolder(path); - if (folder == null) { + if (folder == null) + { // TODO throws an exception log.error("Could not find a folder: " + path); return; } String folderPath = folder.getPath(); - if (folderPath.endsWith(Folder.PATH_SEPARATOR)) { + if (folderPath.endsWith(Folder.PATH_SEPARATOR)) + { folderPath = folderPath + folderName; - } else { + } + else + { folderPath = folderPath + Folder.PATH_SEPARATOR + folderName; } Folder child = getPageManager().newFolder(folderPath); @@ -267,14 +315,19 @@ child.setDefaultDecorator(portletDecorator, Fragment.PORTLET); child.setSkin(desktopTheme); child.setHidden(folderHidden); - try { + try + { getPageManager().updateFolder(child); getPageManager().reset(); - } catch (PageNotUpdatedException e) { + } + catch (PageNotUpdatedException e) + { // TODO throws an exception log.error("Could not add a folder: " + path, e); return; - } catch (NodeException e) { + } + catch (NodeException e) + { // TODO throws an exception log.error("Could not add a folder: " + path, e); return; @@ -282,19 +335,26 @@ // change a folder order List orderList = folder.getDocumentOrder(); - if (orderList != null) { + if (orderList != null) + { String name = child.getName(); - if (orderList.indexOf(name) < 0) { + if (orderList.indexOf(name) < 0) + { orderList.add(name); folder.setDocumentOrder(orderList); - try { + try + { getPageManager().updateFolder(folder); getPageManager().reset(); - } catch (FolderNotUpdatedException e) { + } + catch (FolderNotUpdatedException e) + { // TODO throws an exception log.error("Could not change a folder order: " + path, e); return; - } catch (NodeException e) { + } + catch (NodeException e) + { // TODO throws an exception log.error("Could not change a folder order: " + path, e); return; @@ -304,9 +364,12 @@ // add default childPage String pagePath = child.getPath(); - if (pagePath.endsWith(Folder.PATH_SEPARATOR)) { + if (pagePath.endsWith(Folder.PATH_SEPARATOR)) + { pagePath = pagePath + "default-page"; - } else { + } + else + { pagePath = pagePath + Folder.PATH_SEPARATOR + "default-page"; } Page childPage = getPageManager().newPage(pagePath); @@ -317,34 +380,46 @@ childPage.setShortTitle(folderShortTitle); childPage.setSkin(desktopTheme); childPage.setHidden(folderHidden); - try { + try + { getPageManager().updatePage(childPage); getPageManager().reset(); - } catch (PageNotUpdatedException e) { + } + catch (PageNotUpdatedException e) + { // TODO throws an exception log.error("Could not add a default page: " + path, e); return; - } catch (NodeException e) { + } + catch (NodeException e) + { // TODO throws an exception log.error("Could not add a default page: " + path, e); return; } orderList = child.getDocumentOrder(); - if (orderList != null) { + if (orderList != null) + { String name = childPage.getName(); - if (orderList.indexOf(name) < 0) { + if (orderList.indexOf(name) < 0) + { orderList.add(name); child.setDocumentOrder(orderList); - try { + try + { getPageManager().updateFolder(child); getPageManager().reset(); - } catch (FolderNotUpdatedException e) { + } + catch (FolderNotUpdatedException e) + { // TODO throws an exception log.error("Could not change a default page order: " + path, e); return; - } catch (NodeException e) { + } + catch (NodeException e) + { // TODO throws an exception log.error("Could not change a default page order: " + path, e); @@ -355,11 +430,13 @@ } - public void addPortlet(ActionRequest request, ActionResponse response) { + public void addPortlet(ActionRequest request, ActionResponse response) + { String path = request.getParameter(PATH); String fid = request.getParameter(FRAGMENT_ID); String portletName = request.getParameter(PORTLET_NAME); - if (portletName == null || fid == null || path == null) { + if (portletName == null || fid == null || path == null) + { // TODO throws an exception log.error("portletName, fid or path are null: portletName=" + portletName + ", fid=" + fid + ", path=" + path); @@ -367,7 +444,8 @@ } Page page = getPage(path); - if (page == null) { + if (page == null) + { // TODO throws an exception log.error("page is null."); return; @@ -382,120 +460,158 @@ fragment.getFragments().add(child); - try { + try + { getPageManager().updatePage(page); getPageManager().reset(); - } catch (PageNotUpdatedException e) { + } + catch (PageNotUpdatedException e) + { // TODO throws an exception log.error("Could not update a page: " + path, e); return; - } catch (NodeException e) { + } + catch (NodeException e) + { // TODO throws an exception log.error("Could not update a page: " + path, e); return; } } - protected Folder getFolder(String path) { - if (path == null) { + protected Folder getFolder(String path) + { + if (path == null) + { // TODO exception? return null; } - try { + try + { Folder folder = getPageManager().getFolder("/"); String[] names = path.split("/"); - if (names.length == 0) { - return folder; - } - for (int i = 0; i < names.length - 1; i++) { - if (!"".equals(names[i])) { + if (names.length == 0) { return folder; } + for (int i = 0; i < names.length - 1; i++) + { + if (!"".equals(names[i])) + { folder = folder.getFolder(names[i]); } } - if (names[names.length - 1].endsWith(".psml")) { + if (names[names.length - 1].endsWith(".psml")) + { // parent folder return folder; - } else { + } + else + { // folder return folder.getFolder(names[names.length - 1]); } - } catch (FolderNotFoundException e) { + } + catch (FolderNotFoundException e) + { // TODO throws an exception log.error("Could not change a page order: " + path, e); return null; - } catch (InvalidFolderException e) { + } + catch (InvalidFolderException e) + { // TODO throws an exception log.error("Could not access a folder: " + path, e); return null; - } catch (DocumentException e) { + } + catch (DocumentException e) + { // TODO throws an exception log.error("Could not access a folder: " + path, e); return null; - } catch (NodeException e) { + } + catch (NodeException e) + { // TODO throws an exception log.error("Could not access a folder: " + path, e); return null; } } - protected Page getPage(String path) { - if (path == null) { + protected Page getPage(String path) + { + if (path == null) + { // TODO exception? return null; } - try { + try + { Folder folder = getPageManager().getFolder("/"); String[] names = path.split("/"); - for (int i = 0; i < names.length - 1; i++) { - if (!"".equals(names[i])) { + for (int i = 0; i < names.length - 1; i++) + { + if (!"".equals(names[i])) + { folder = folder.getFolder(names[i]); } } - if (names[names.length - 1].endsWith(".psml")) { + if (names[names.length - 1].endsWith(".psml")) + { // page return folder.getPage(names[names.length - 1]); - } else { + } + else + { // folder return null; } - } catch (PageNotFoundException e) { + } + catch (PageNotFoundException e) + { // TODO throws an exception log.error("Could not access a page: " + path, e); return null; - } catch (FolderNotFoundException e) { + } + catch (FolderNotFoundException e) + { // TODO throws an exception log.error("Could not access a page: " + path, e); return null; - } catch (InvalidFolderException e) { + } + catch (InvalidFolderException e) + { // TODO throws an exception log.error("Could not access a page: " + path, e); return null; - } catch (DocumentException e) { + } + catch (DocumentException e) + { // TODO throws an exception log.error("Could not access a page: " + path, e); return null; - } catch (NodeException e) { + } + catch (NodeException e) + { // TODO throws an exception log.error("Could not access a page: " + path, e); return null; } } - private boolean checkAction(ActionRequest request, String key) { + private boolean checkAction(ActionRequest request, String key) + { String value = request.getParameter(key); - if (value != null && !value.equals("")) { - return true; - } + if (value != null && !value.equals("")) { return true; } return false; } - public PageManager getPageManager() { + public PageManager getPageManager() + { return pageManager; } - public void setPageManager(PageManager pageManager) { + public void setPageManager(PageManager pageManager) + { this.pageManager = pageManager; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/LayoutPortlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/LayoutPortlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/LayoutPortlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -56,8 +56,10 @@ /** */ -public class LayoutPortlet extends org.apache.portals.bridges.common.GenericServletPortlet +public class LayoutPortlet extends + org.apache.portals.bridges.common.GenericServletPortlet { + public static final String GENERIC_TEMPLATE_TYPE = "generic"; public static final String FRAGMENT_PROCESSING_ERROR_PREFIX = "fragment.processing.error."; @@ -71,77 +73,87 @@ public static final String LAYOUT_TEMPLATE_TYPE = "layout"; public static final String DECORATOR_TYPE = "decorator"; - + public static final String PARAM_SOLO_PAGE = "SoloPage"; - - + /** Commons logging */ protected final static Log log = LogFactory.getLog(LayoutPortlet.class); - + protected PortletRegistry registry; + protected PageManager pageManager; + protected JetspeedPowerToolFactory jptFactory; + protected TemplateLocator templateLocator; + protected PortletEntityAccessComponent entityAccess; + protected PortletWindowAccessor windowAccess; + protected TemplateLocator decorationLocator; - + private Map layoutTemplatesCache = new HashMap(); + public static final String DEFAULT_TEMPLATE_EXT = ".vm"; + public static final String TEMPLATE_EXTENSION_KEY = "template.extension"; + public static final String DEFAULT_TEMPLATE_TYPE = "velocity"; + public static final String TEMPLATE_TYPE_KEY = "template.type"; - - public void init( PortletConfig config ) throws PortletException + + public void init(PortletConfig config) throws PortletException { super.init(config); - - registry = (PortletRegistry)getPortletContext().getAttribute(CommonPortletServices.CPS_REGISTRY_COMPONENT); - if (null == registry) - { - throw new PortletException("Failed to find the Portlet Registry on portlet initialization"); - } - pageManager = (PageManager)getPortletContext().getAttribute(CommonPortletServices.CPS_PAGE_MANAGER_COMPONENT); - if (null == pageManager) - { - throw new PortletException("Failed to find the Page Manager on portlet initialization"); - } - jptFactory = (JetspeedPowerToolFactory)getPortletContext().getAttribute(CommonPortletServices.CPS_JETSPEED_POWERTOOL_FACTORY); - if (null == jptFactory) - { - throw new PortletException("Failed to find the JPT Factory on portlet initialization"); - } - - entityAccess = (PortletEntityAccessComponent) getPortletContext().getAttribute(CommonPortletServices.CPS_ENTITY_ACCESS_COMPONENT); - if (null == entityAccess) - { - throw new PortletException("Failed to find the Entity Access on portlet initialization"); - } - - windowAccess = (PortletWindowAccessor) getPortletContext().getAttribute(CommonPortletServices.CPS_WINDOW_ACCESS_COMPONENT); - if (null == windowAccess) - { - throw new PortletException("Failed to find the Window Access on portlet initialization"); - } - - templateLocator = (TemplateLocator) getPortletContext().getAttribute("TemplateLocator"); - decorationLocator = (TemplateLocator) getPortletContext().getAttribute("DecorationLocator"); + + registry = (PortletRegistry) getPortletContext().getAttribute( + CommonPortletServices.CPS_REGISTRY_COMPONENT); + if (null == registry) { throw new PortletException( + "Failed to find the Portlet Registry on portlet initialization"); } + pageManager = (PageManager) getPortletContext().getAttribute( + CommonPortletServices.CPS_PAGE_MANAGER_COMPONENT); + if (null == pageManager) { throw new PortletException( + "Failed to find the Page Manager on portlet initialization"); } + jptFactory = (JetspeedPowerToolFactory) getPortletContext() + .getAttribute( + CommonPortletServices.CPS_JETSPEED_POWERTOOL_FACTORY); + if (null == jptFactory) { throw new PortletException( + "Failed to find the JPT Factory on portlet initialization"); } + + entityAccess = (PortletEntityAccessComponent) getPortletContext() + .getAttribute(CommonPortletServices.CPS_ENTITY_ACCESS_COMPONENT); + if (null == entityAccess) { throw new PortletException( + "Failed to find the Entity Access on portlet initialization"); } + + windowAccess = (PortletWindowAccessor) getPortletContext() + .getAttribute(CommonPortletServices.CPS_WINDOW_ACCESS_COMPONENT); + if (null == windowAccess) { throw new PortletException( + "Failed to find the Window Access on portlet initialization"); } + + templateLocator = (TemplateLocator) getPortletContext().getAttribute( + "TemplateLocator"); + decorationLocator = (TemplateLocator) getPortletContext().getAttribute( + "DecorationLocator"); } - public void doHelp( RenderRequest request, RenderResponse response ) throws PortletException, IOException + public void doHelp(RenderRequest request, RenderResponse response) + throws PortletException, IOException { RequestContext context = getRequestContext(request); - response.setContentType(context.getMimeType()); + response.setContentType(context.getMimeType()); JetspeedPowerTool jpt = getJetspeedPowerTool(request); String absHelpPage = ""; - // request.setAttribute(PortalReservedParameters.PAGE_ATTRIBUTE, getPage(request)); - // request.setAttribute("fragment", getFragment(request, false)); + // request.setAttribute(PortalReservedParameters.PAGE_ATTRIBUTE, + // getPage(request)); + // request.setAttribute("fragment", getFragment(request, false)); try { - String helpPage = (String)request.getPortletSession().getAttribute(PortalReservedParameters.PAGE_LAYOUT_HELP); + String helpPage = (String) request.getPortletSession() + .getAttribute(PortalReservedParameters.PAGE_LAYOUT_HELP); if (helpPage == null) { PortletPreferences prefs = request.getPreferences(); @@ -149,21 +161,26 @@ if (helpPage == null) { helpPage = this.getInitParameter(PARAM_HELP_PAGE); - if (helpPage == null) - helpPage = "columns"; + if (helpPage == null) helpPage = "columns"; } - request.getPortletSession().setAttribute(PortalReservedParameters.PAGE_LAYOUT_HELP, helpPage); + request.getPortletSession().setAttribute( + PortalReservedParameters.PAGE_LAYOUT_HELP, helpPage); } - String templateKey = helpPage + "/" + JetspeedPowerTool.LAYOUT_TEMPLATE_TYPE + "-help"; - CachedTemplate ct = (CachedTemplate)layoutTemplatesCache.get(templateKey); + String templateKey = helpPage + "/" + + JetspeedPowerTool.LAYOUT_TEMPLATE_TYPE + "-help"; + CachedTemplate ct = (CachedTemplate) layoutTemplatesCache + .get(templateKey); if (ct == null) { TemplateDescriptor template = null; Configuration props = getConfiguration(request, helpPage); String ext = (String) props.getString(TEMPLATE_EXTENSION_KEY); - String path = helpPage + "/" + JetspeedPowerTool.LAYOUT_TEMPLATE_TYPE + "-help" + ext; - template = jpt.getTemplate(path, JetspeedPowerTool.LAYOUT_TEMPLATE_TYPE); + String path = helpPage + "/" + + JetspeedPowerTool.LAYOUT_TEMPLATE_TYPE + "-help" + + ext; + template = jpt.getTemplate(path, + JetspeedPowerTool.LAYOUT_TEMPLATE_TYPE); if (template == null) { String msg = "*** FAILED getTemplate:" + path; @@ -171,42 +188,46 @@ } else { - synchronized(layoutTemplatesCache) + synchronized (layoutTemplatesCache) { ct = new CachedTemplate(templateKey, template, props); layoutTemplatesCache.put(templateKey, ct); - } + } } } - - absHelpPage = ct.getTemplate().getAppRelativePath(); + + absHelpPage = ct.getTemplate().getAppRelativePath(); log.debug("Path to help page for LayoutPortlet " + absHelpPage); request.setAttribute(PARAM_VIEW_PAGE, absHelpPage); } catch (TemplateLocatorException e) { - throw new PortletException("Unable to locate view page " + absHelpPage, e); + throw new PortletException("Unable to locate view page " + + absHelpPage, e); } super.doView(request, response); } - + /** * */ - public void doView( RenderRequest request, RenderResponse response ) throws PortletException, IOException + public void doView(RenderRequest request, RenderResponse response) + throws PortletException, IOException { RequestContext context = getRequestContext(request); - response.setContentType(context.getMimeType()); - PortletWindow window = context.getPortalURL().getNavigationalState().getMaximizedWindow(); + response.setContentType(context.getMimeType()); + PortletWindow window = context.getPortalURL().getNavigationalState() + .getMaximizedWindow(); boolean maximized = (window != null); boolean solo = false; if (maximized) { request.setAttribute("layout", getMaximizedLayout(request)); - solo = JetspeedActions.SOLO_STATE.equals(context.getPortalURL().getNavigationalState().getMappedState(window)); - if ( solo ) + solo = JetspeedActions.SOLO_STATE.equals(context.getPortalURL() + .getNavigationalState().getMappedState(window)); + if (solo) { maximized = false; } @@ -222,7 +243,8 @@ JetspeedPowerTool jpt = getJetspeedPowerTool(request); if (maximized) { - viewPage = (String)request.getPortletSession().getAttribute(PortalReservedParameters.PAGE_LAYOUT_MAX); + viewPage = (String) request.getPortletSession().getAttribute( + PortalReservedParameters.PAGE_LAYOUT_MAX); if (viewPage == null) { PortletPreferences prefs = request.getPreferences(); @@ -230,18 +252,19 @@ if (viewPage == null) { viewPage = this.getInitParameter(PARAM_MAX_PAGE); - if (viewPage == null) - viewPage = "maximized"; + if (viewPage == null) viewPage = "maximized"; } - request.getPortletSession().setAttribute(PortalReservedParameters.PAGE_LAYOUT_MAX, viewPage); + request.getPortletSession().setAttribute( + PortalReservedParameters.PAGE_LAYOUT_MAX, viewPage); } } else if (solo) { - viewPage = (String)request.getPortletSession().getAttribute(PortalReservedParameters.PAGE_LAYOUT_SOLO); + viewPage = (String) request.getPortletSession().getAttribute( + PortalReservedParameters.PAGE_LAYOUT_SOLO); if (viewPage == null) { - PortletPreferences prefs = request.getPreferences(); + PortletPreferences prefs = request.getPreferences(); viewPage = prefs.getValue(PARAM_SOLO_PAGE, null); if (viewPage == null) { @@ -251,36 +274,46 @@ viewPage = "solo"; } } - request.getPortletSession().setAttribute(PortalReservedParameters.PAGE_LAYOUT_SOLO, viewPage); + request.getPortletSession() + .setAttribute( + PortalReservedParameters.PAGE_LAYOUT_SOLO, + viewPage); } } else { - viewPage = (String)request.getPortletSession().getAttribute(PortalReservedParameters.PAGE_LAYOUT_VIEW); + viewPage = (String) request.getPortletSession().getAttribute( + PortalReservedParameters.PAGE_LAYOUT_VIEW); if (viewPage == null) { - PortletPreferences prefs = request.getPreferences(); + PortletPreferences prefs = request.getPreferences(); viewPage = prefs.getValue(PARAM_VIEW_PAGE, null); if (viewPage == null) { viewPage = this.getInitParameter(PARAM_VIEW_PAGE); - if (viewPage == null) - viewPage = "columns"; + if (viewPage == null) viewPage = "columns"; } - request.getPortletSession().setAttribute(PortalReservedParameters.PAGE_LAYOUT_VIEW, viewPage); + request.getPortletSession() + .setAttribute( + PortalReservedParameters.PAGE_LAYOUT_VIEW, + viewPage); } } - - String templateKey = viewPage + "/" + JetspeedPowerTool.LAYOUT_TEMPLATE_TYPE; - CachedTemplate ct = (CachedTemplate)layoutTemplatesCache.get(templateKey); + + String templateKey = viewPage + "/" + + JetspeedPowerTool.LAYOUT_TEMPLATE_TYPE; + CachedTemplate ct = (CachedTemplate) layoutTemplatesCache + .get(templateKey); if (ct == null) { TemplateDescriptor template = null; Configuration props = getConfiguration(request, viewPage); String ext = (String) props.getString(TEMPLATE_EXTENSION_KEY); - String path = viewPage + "/" + JetspeedPowerTool.LAYOUT_TEMPLATE_TYPE + ext; - - template = jpt.getTemplate(path, JetspeedPowerTool.LAYOUT_TEMPLATE_TYPE); + String path = viewPage + "/" + + JetspeedPowerTool.LAYOUT_TEMPLATE_TYPE + ext; + + template = jpt.getTemplate(path, + JetspeedPowerTool.LAYOUT_TEMPLATE_TYPE); if (template == null) { String msg = "*** FAILED getTemplate:" + path; @@ -288,12 +321,12 @@ } else { - synchronized(layoutTemplatesCache) + synchronized (layoutTemplatesCache) { ct = new CachedTemplate(templateKey, template, props); layoutTemplatesCache.put(templateKey, ct); } - + } } absViewPage = ct.getTemplate().getAppRelativePath(); @@ -302,7 +335,8 @@ } catch (TemplateLocatorException e) { - throw new PortletException("Unable to locate view page " + absViewPage, e); + throw new PortletException("Unable to locate view page " + + absViewPage, e); } super.doView(request, response); @@ -311,9 +345,9 @@ request.removeAttribute("layout"); request.removeAttribute("dispatcher"); } - + public void processAction(ActionRequest request, ActionResponse response) - throws PortletException, IOException + throws PortletException, IOException { String page = request.getParameter("page"); String deleteFragmentId = request.getParameter("deleteId"); @@ -325,7 +359,7 @@ else if (portlets != null && portlets.length() > 0) { int count = 0; - StringTokenizer tokenizer = new StringTokenizer(portlets, ","); + StringTokenizer tokenizer = new StringTokenizer(portlets, ","); while (tokenizer.hasMoreTokens()) { String portlet = tokenizer.nextToken(); @@ -333,7 +367,7 @@ { if (portlet.startsWith("box_")) { - portlet = portlet.substring("box_".length()); + portlet = portlet.substring("box_".length()); addPortletToPage(page, portlet); count++; } @@ -343,8 +377,8 @@ log.error("failed to add portlet to page: " + portlet); } } - - } + + } } protected void removeFragment(String pageId, String fragmentId) @@ -353,21 +387,22 @@ try { page = pageManager.getPage(pageId); - + } catch (Exception e) { - log.error("failed to remove portlet " + fragmentId + " from page: " + pageId, e); + log.error("failed to remove portlet " + fragmentId + " from page: " + + pageId, e); } - removeFragment(page,page.getRootFragment(), fragmentId); + removeFragment(page, page.getRootFragment(), fragmentId); } - + protected void removeFragment(Page page, Fragment root, String fragmentId) { try { Fragment f = page.getFragmentById(fragmentId); - if ( f == null ) + if (f == null) { // ignore no longer existing fragment error return; @@ -377,10 +412,11 @@ } catch (Exception e) { - log.error("failed to remove portlet " + fragmentId + " from page: " + page, e); + log.error("failed to remove portlet " + fragmentId + " from page: " + + page, e); } } - + protected void addPortletToPage(String pageId, String portletId) { Page page = null; @@ -390,11 +426,12 @@ } catch (Exception e) { - log.error("failed to add portlet " + portletId + " to page: " + pageId, e); + log.error("failed to add portlet " + portletId + " to page: " + + pageId, e); } addPortletToPage(page, page.getRootFragment(), portletId); } - + protected void addPortletToPage(Page page, Fragment root, String portletId) { try @@ -402,16 +439,17 @@ Fragment fragment = pageManager.newFragment(); fragment.setType(Fragment.PORTLET); fragment.setName(portletId); - + root.getFragments().add(fragment); - pageManager.updatePage(page); + pageManager.updatePage(page); } catch (Exception e) { - log.error("failed to add portlet " + portletId + " to page: " + page, e); + log.error("failed to add portlet " + portletId + " to page: " + + page, e); } } - + /** * <p> * initJetspeedPowerTool @@ -422,66 +460,70 @@ * @return * @throws PortletException */ - protected JetspeedPowerTool getJetspeedPowerTool( RenderRequest request ) throws PortletException + protected JetspeedPowerTool getJetspeedPowerTool(RenderRequest request) + throws PortletException { - JetspeedPowerTool tool = (JetspeedPowerTool) request.getAttribute(PortalReservedParameters.JETSPEED_POWER_TOOL_REQ_ATTRIBUTE); - RequestContext requestContext = (RequestContext) request.getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); + JetspeedPowerTool tool = (JetspeedPowerTool) request + .getAttribute(PortalReservedParameters.JETSPEED_POWER_TOOL_REQ_ATTRIBUTE); + RequestContext requestContext = (RequestContext) request + .getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); if (tool == null) { try { - if (requestContext == null) - { - throw new IllegalStateException( - "LayoutPortlet unable to handle request because there is no RequestContext in " - + "the HttpServletRequest."); - } + if (requestContext == null) { throw new IllegalStateException( + "LayoutPortlet unable to handle request because there is no RequestContext in " + + "the HttpServletRequest."); } tool = this.jptFactory.getJetspeedPowerTool(requestContext); - request.setAttribute(PortalReservedParameters.JETSPEED_POWER_TOOL_REQ_ATTRIBUTE, tool); + request + .setAttribute( + PortalReservedParameters.JETSPEED_POWER_TOOL_REQ_ATTRIBUTE, + tool); } catch (Exception e1) { - throw new PortletException("Unable to init JetspeedPowerTool: " + e1.toString(), e1); + throw new PortletException("Unable to init JetspeedPowerTool: " + + e1.toString(), e1); } } - + return tool; } - + /** * * @param request * @param maximized * @return */ - protected Fragment getFragment( RenderRequest request, boolean maximized ) + protected Fragment getFragment(RenderRequest request, boolean maximized) { - String attribute = (maximized) - ? PortalReservedParameters.MAXIMIZED_FRAGMENT_ATTRIBUTE + String attribute = (maximized) ? PortalReservedParameters.MAXIMIZED_FRAGMENT_ATTRIBUTE : PortalReservedParameters.FRAGMENT_ATTRIBUTE; - return (Fragment) request.getAttribute(attribute); + return (Fragment) request.getAttribute(attribute); } - + /** * * @param request * @return */ - protected Fragment getMaximizedLayout( RenderRequest request ) + protected Fragment getMaximizedLayout(RenderRequest request) { - return (Fragment) request.getAttribute(PortalReservedParameters.MAXIMIZED_LAYOUT_ATTRIBUTE); + return (Fragment) request + .getAttribute(PortalReservedParameters.MAXIMIZED_LAYOUT_ATTRIBUTE); } - + /** * * @param request * @return */ - protected RequestContext getRequestContext( RenderRequest request ) + protected RequestContext getRequestContext(RenderRequest request) { RequestContext requestContext = (RequestContext) request .getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); @@ -502,57 +544,63 @@ * </p> * * @see javax.portlet.GenericPortlet#doEdit(javax.portlet.RenderRequest, - * javax.portlet.RenderResponse) + * javax.portlet.RenderResponse) * @param request * @param response * @throws PortletException * @throws IOException */ - public void doEdit( RenderRequest request, RenderResponse response ) throws PortletException, IOException + public void doEdit(RenderRequest request, RenderResponse response) + throws PortletException, IOException { doView(request, response); } - + /** * * @param request * @return * @throws TemplateLocatorException */ - protected LocatorDescriptor getTemplateLocatorDescriptor(RenderRequest request) throws TemplateLocatorException + protected LocatorDescriptor getTemplateLocatorDescriptor( + RenderRequest request) throws TemplateLocatorException { RequestContext requestContext = getRequestContext(request); CapabilityMap capabilityMap = requestContext.getCapabilityMap(); Locale locale = requestContext.getLocale(); - LocatorDescriptor templateLocatorDescriptor = templateLocator.createLocatorDescriptor(null); - templateLocatorDescriptor.setMediaType(capabilityMap.getPreferredMediaType().getName()); + LocatorDescriptor templateLocatorDescriptor = templateLocator + .createLocatorDescriptor(null); + templateLocatorDescriptor.setMediaType(capabilityMap + .getPreferredMediaType().getName()); templateLocatorDescriptor.setCountry(locale.getCountry()); templateLocatorDescriptor.setLanguage(locale.getLanguage()); - return templateLocatorDescriptor; + return templateLocatorDescriptor; } - - + /** * * @param request * @return * @throws TemplateLocatorException */ - protected LocatorDescriptor getDecoratorLocatorDescriptor(RenderRequest request) throws TemplateLocatorException + protected LocatorDescriptor getDecoratorLocatorDescriptor( + RenderRequest request) throws TemplateLocatorException { RequestContext requestContext = getRequestContext(request); CapabilityMap capabilityMap = requestContext.getCapabilityMap(); Locale locale = requestContext.getLocale(); - - LocatorDescriptor decorationLocatorDescriptor = decorationLocator.createLocatorDescriptor(null); - decorationLocatorDescriptor.setMediaType(capabilityMap.getPreferredMediaType().getName()); + + LocatorDescriptor decorationLocatorDescriptor = decorationLocator + .createLocatorDescriptor(null); + decorationLocatorDescriptor.setMediaType(capabilityMap + .getPreferredMediaType().getName()); decorationLocatorDescriptor.setCountry(locale.getCountry()); decorationLocatorDescriptor.setLanguage(locale.getLanguage()); - + return decorationLocatorDescriptor; } - + /** * * @param request @@ -562,8 +610,9 @@ * @throws TemplateLocatorException * @throws ConfigurationException */ - public String decorateAndInclude(RenderRequest request, Fragment fragment, Page page) throws TemplateLocatorException, ConfigurationException - { + public String decorateAndInclude(RenderRequest request, Fragment fragment, + Page page) throws TemplateLocatorException, ConfigurationException + { String fragmentType = fragment.getType(); String decorator = fragment.getDecorator(); LocatorDescriptor decorationLocatorDescriptor = getDecoratorLocatorDescriptor(request); @@ -573,17 +622,20 @@ } // get fragment properties for fragmentType or generic - TemplateDescriptor propsTemp = getTemplate(decorator + "/" + DECORATOR_TYPE + ".properties", fragmentType, + TemplateDescriptor propsTemp = getTemplate(decorator + "/" + + DECORATOR_TYPE + ".properties", fragmentType, decorationLocator, decorationLocatorDescriptor); if (propsTemp == null) { fragmentType = GENERIC_TEMPLATE_TYPE; - propsTemp = getTemplate(decorator + "/" + DECORATOR_TYPE + ".properties", fragmentType, decorationLocator, + propsTemp = getTemplate(decorator + "/" + DECORATOR_TYPE + + ".properties", fragmentType, decorationLocator, decorationLocatorDescriptor); } // get decorator template - Configuration decoConf = new PropertiesConfiguration(propsTemp.getAbsolutePath()); + Configuration decoConf = new PropertiesConfiguration(propsTemp + .getAbsolutePath()); String ext = decoConf.getString("template.extension"); String decoratorPath = decorator + "/" + DECORATOR_TYPE + ext; TemplateDescriptor template = null; @@ -596,13 +648,14 @@ String parent = decoConf.getString("extends"); if (parent != null) { - template = getDecoration(request, parent + "/" + DECORATOR_TYPE + ext, fragmentType); + template = getDecoration(request, parent + "/" + DECORATOR_TYPE + + ext, fragmentType); } } - return template.getAppRelativePath(); + return template.getAppRelativePath(); } - + /** * * @param request @@ -611,11 +664,13 @@ * @return * @throws TemplateLocatorException */ - protected TemplateDescriptor getDecoration( RenderRequest request, String path, String templateType ) throws TemplateLocatorException - { - return getTemplate(path, templateType, decorationLocator, getDecoratorLocatorDescriptor(request)); + protected TemplateDescriptor getDecoration(RenderRequest request, + String path, String templateType) throws TemplateLocatorException + { + return getTemplate(path, templateType, decorationLocator, + getDecoratorLocatorDescriptor(request)); } - + /** * * @param path @@ -625,10 +680,11 @@ * @return * @throws TemplateLocatorException */ - protected TemplateDescriptor getTemplate( String path, String templateType, TemplateLocator locator, - LocatorDescriptor descriptor ) throws TemplateLocatorException + protected TemplateDescriptor getTemplate(String path, String templateType, + TemplateLocator locator, LocatorDescriptor descriptor) + throws TemplateLocatorException { - + if (templateType == null) { templateType = GENERIC_TEMPLATE_TYPE; @@ -651,11 +707,13 @@ /** * Gets the configuration (layout.properties) object for the decoration. - * @param name Name of the Decoration. - * @return <code>java.util.Properties</code> representing the configuration - * object. + * + * @param name + * Name of the Decoration. + * @return <code>java.util.Properties</code> representing the + * configuration object. */ - protected Configuration getConfiguration( RenderRequest request, String name ) + protected Configuration getConfiguration(RenderRequest request, String name) { Configuration props = null; JetspeedPowerTool jpt = null; @@ -664,20 +722,22 @@ try { jpt = getJetspeedPowerTool(request); - templatePropertiesPath = jpt.getTemplate(name + "/" + JetspeedPowerTool.LAYOUT_TEMPLATE_TYPE + ".properties", + templatePropertiesPath = jpt.getTemplate( + name + "/" + JetspeedPowerTool.LAYOUT_TEMPLATE_TYPE + + ".properties", JetspeedPowerTool.LAYOUT_TEMPLATE_TYPE).getAbsolutePath(); - } + } catch (PortletException e) { - log.warn("Could not acquire JetspeedPowerTool from request",e); + log.warn("Could not acquire JetspeedPowerTool from request", e); } catch (TemplateLocatorException e) { - log.warn("Could not find templatePorpertiesPath",e); + log.warn("Could not find templatePorpertiesPath", e); } catch (Exception e) { - log.warn("Could not determine Layout template properties file",e); + log.warn("Could not determine Layout template properties file", e); } // if no path then set name to "default" if (null == templatePropertiesPath) @@ -690,9 +750,8 @@ } if (log.isDebugEnabled()) { - log.debug( - "Template descriptor path:<" + templatePropertiesPath + ">" - ); + log.debug("Template descriptor path:<" + templatePropertiesPath + + ">"); } // load Decoration.CONFIG_FILE_NAME (layout.properties) @@ -700,71 +759,78 @@ { props = new PropertiesConfiguration(templatePropertiesPath); if (log.isDebugEnabled()) - log.debug("Successfully read in: <" + templatePropertiesPath + "> "); - } + log.debug("Successfully read in: <" + templatePropertiesPath + + "> "); + } catch (Exception e) { props = new PropertiesConfiguration(); - log.warn( "Could not locate the " + templatePropertiesPath + " file for layout template \"" + name + "\". This layout template may not exist.",e ); - props.setProperty( "id", name ); - props.setProperty( TEMPLATE_TYPE_KEY, DEFAULT_TEMPLATE_TYPE ); - props.setProperty( TEMPLATE_EXTENSION_KEY, DEFAULT_TEMPLATE_EXT); + log.warn("Could not locate the " + templatePropertiesPath + + " file for layout template \"" + name + + "\". This layout template may not exist.", e); + props.setProperty("id", name); + props.setProperty(TEMPLATE_TYPE_KEY, DEFAULT_TEMPLATE_TYPE); + props.setProperty(TEMPLATE_EXTENSION_KEY, DEFAULT_TEMPLATE_EXT); } finally { - String templateIdPropVal = (String) props.getProperty( "id" ); - String templateNamePropVal = (String) props.getProperty( TEMPLATE_TYPE_KEY ); - String templateExtPropVal = (String) props.getProperty(TEMPLATE_EXTENSION_KEY); - - if ( templateIdPropVal == null ) + String templateIdPropVal = (String) props.getProperty("id"); + String templateNamePropVal = (String) props + .getProperty(TEMPLATE_TYPE_KEY); + String templateExtPropVal = (String) props + .getProperty(TEMPLATE_EXTENSION_KEY); + + if (templateIdPropVal == null) { templateIdPropVal = name; - props.setProperty( "id", templateIdPropVal ); + props.setProperty("id", templateIdPropVal); } - - if ( templateNamePropVal == null ) + + if (templateNamePropVal == null) { - props.setProperty( TEMPLATE_TYPE_KEY, DEFAULT_TEMPLATE_TYPE ); + props.setProperty(TEMPLATE_TYPE_KEY, DEFAULT_TEMPLATE_TYPE); } - if ( templateExtPropVal == null ) + if (templateExtPropVal == null) { - props.setProperty( TEMPLATE_EXTENSION_KEY, DEFAULT_TEMPLATE_EXT ); + props.setProperty(TEMPLATE_EXTENSION_KEY, DEFAULT_TEMPLATE_EXT); } } if (log.isDebugEnabled()) { - log.debug("Template layout.properties extension is:<" + props.getString(TEMPLATE_EXTENSION_KEY)); + log.debug("Template layout.properties extension is:<" + + props.getString(TEMPLATE_EXTENSION_KEY)); } return props; } class CachedTemplate { + private String key; + private TemplateDescriptor template; + private Configuration config; - - public CachedTemplate(String key, TemplateDescriptor template, Configuration config) + + public CachedTemplate(String key, TemplateDescriptor template, + Configuration config) { this.key = key; this.template = template; this.config = config; } - public Configuration getConfig() { return config; } - public String getKey() { return key; } - public TemplateDescriptor getTemplate() { return template; Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/MultiColumnPortlet.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/MultiColumnPortlet.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/MultiColumnPortlet.java 2008-05-16 01:54:54 UTC (rev 940) @@ -54,106 +54,136 @@ */ public class MultiColumnPortlet extends LayoutPortlet { + /** Commons logging */ - protected final static Log log = LogFactory.getLog(MultiColumnPortlet.class); + protected final static Log log = LogFactory + .getLog(MultiColumnPortlet.class); protected final static String PARAM_NUM_COLUMN = "columns"; + protected final static int DEFAULT_NUM_COLUMN = 2; + protected final static String PARAM_COLUMN_SIZES = "sizes"; + protected final static String DEFAULT_ONE_COLUMN_SIZES = "100%"; + protected final static String DEFAULT_TWO_COLUMN_SIZES = "50%,50%"; + protected final static String DEFAULT_THREE_COLUMN_SIZES = "34%,33%,33%"; private int numColumns = 0; + private String columnSizes = null; + private String portletName = null; + private String layoutType; + private String editorType = null; + protected DecorationFactory decorators; + protected JetspeedDesktop desktop; + protected JetspeedContentCache decoratorCache; - public void init( PortletConfig config ) throws PortletException + public void init(PortletConfig config) throws PortletException { super.init(config); this.portletName = config.getPortletName(); this.layoutType = config.getInitParameter("layoutType"); this.editorType = config.getInitParameter("editorType"); - if (this.layoutType == null) - { - throw new PortletException("Layout type not specified for " + this.portletName); - } - this.numColumns = Integer.parseInt(config.getInitParameter(PARAM_NUM_COLUMN)); + if (this.layoutType == null) { throw new PortletException( + "Layout type not specified for " + this.portletName); } + this.numColumns = Integer.parseInt(config + .getInitParameter(PARAM_NUM_COLUMN)); if (this.numColumns < 1) { this.numColumns = 1; } this.columnSizes = config.getInitParameter(PARAM_COLUMN_SIZES); - if ((this.columnSizes == null) || (this.columnSizes.trim().length() == 0)) + if ((this.columnSizes == null) + || (this.columnSizes.trim().length() == 0)) { switch (this.numColumns) { - case 1: this.columnSizes = DEFAULT_ONE_COLUMN_SIZES; break; - case 2: this.columnSizes = DEFAULT_TWO_COLUMN_SIZES; break; - case 3: this.columnSizes = DEFAULT_THREE_COLUMN_SIZES; break; - default: this.columnSizes = null; break; + case 1: + this.columnSizes = DEFAULT_ONE_COLUMN_SIZES; + break; + case 2: + this.columnSizes = DEFAULT_TWO_COLUMN_SIZES; + break; + case 3: + this.columnSizes = DEFAULT_THREE_COLUMN_SIZES; + break; + default: + this.columnSizes = null; + break; } } - if (this.columnSizes == null) - { - throw new PortletException("Column sizes cannot be defaulted for " + this.numColumns + " columns and are not specified for " + this.portletName); - } - - this.decorators = (DecorationFactory)getPortletContext().getAttribute(CommonPortletServices.CPS_DECORATION_FACTORY); - if (null == this.decorators) - { - throw new PortletException("Failed to find the Decoration Factory on portlet initialization"); - } - - this.desktop = (JetspeedDesktop)getPortletContext().getAttribute(CommonPortletServices.CPS_DESKTOP); - - this.decoratorCache = (JetspeedContentCache)getPortletContext().getAttribute(CommonPortletServices.CPS_DECORATOR_CACHE); + if (this.columnSizes == null) { throw new PortletException( + "Column sizes cannot be defaulted for " + this.numColumns + + " columns and are not specified for " + + this.portletName); } + + this.decorators = (DecorationFactory) getPortletContext().getAttribute( + CommonPortletServices.CPS_DECORATION_FACTORY); + if (null == this.decorators) { throw new PortletException( + "Failed to find the Decoration Factory on portlet initialization"); } + + this.desktop = (JetspeedDesktop) getPortletContext().getAttribute( + CommonPortletServices.CPS_DESKTOP); + + this.decoratorCache = (JetspeedContentCache) getPortletContext() + .getAttribute(CommonPortletServices.CPS_DECORATOR_CACHE); } - public void doView( RenderRequest request, RenderResponse response ) throws PortletException, IOException + public void doView(RenderRequest request, RenderResponse response) + throws PortletException, IOException { RequestContext context = getRequestContext(request); - ContentPage requestPage = context.getPage(); - PageEditAccess pageEditAccess = (PageEditAccess)context.getAttribute(PortalReservedParameters.PAGE_EDIT_ACCESS_ATTRIBUTE); - if ( requestPage == null) + ContentPage requestPage = context.getPage(); + PageEditAccess pageEditAccess = (PageEditAccess) context + .getAttribute(PortalReservedParameters.PAGE_EDIT_ACCESS_ATTRIBUTE); + if (requestPage == null) { - // Targetting this portlet REQUIRES that the ProfilerValve has been invoked! + // Targetting this portlet REQUIRES that the ProfilerValve has been + // invoked! throw new PortletException("Current request page not available."); } if (pageEditAccess == null) { - // Targetting this portlet REQUIRES that the ProfilerValve has been invoked! - throw new PortletException("Current PageEditAccess not available."); + // Targetting this portlet REQUIRES that the ProfilerValve has been + // invoked! + throw new PortletException("Current PageEditAccess not available."); } - - Boolean editing = ( pageEditAccess.isEditing() && - PortletMode.VIEW.equals(request.getPortletMode()) && - request.isPortletModeAllowed(PortletMode.EDIT)) - ? Boolean.TRUE : Boolean.FALSE; - - PortletWindow window = context.getPortalURL().getNavigationalState().getMaximizedWindow(); + + Boolean editing = (pageEditAccess.isEditing() + && PortletMode.VIEW.equals(request.getPortletMode()) && request + .isPortletModeAllowed(PortletMode.EDIT)) ? Boolean.TRUE + : Boolean.FALSE; + + PortletWindow window = context.getPortalURL().getNavigationalState() + .getMaximizedWindow(); if (window != null) { super.doView(request, response); return; } - + // get fragment column sizes Fragment f = getFragment(request, false); String fragmentColumnSizes = columnSizes; - String fragmentColumnSizesProperty = f.getProperty(Fragment.SIZES_PROPERTY_NAME); + String fragmentColumnSizesProperty = f + .getProperty(Fragment.SIZES_PROPERTY_NAME); if (fragmentColumnSizesProperty != null) { fragmentColumnSizes = fragmentColumnSizesProperty; } - String [] fragmentColumnSizesArray = fragmentColumnSizes.split("\\,"); - List fragmentColumnSizesList = new ArrayList(fragmentColumnSizesArray.length); + String[] fragmentColumnSizesArray = fragmentColumnSizes.split("\\,"); + List fragmentColumnSizesList = new ArrayList( + fragmentColumnSizesArray.length); for (int i = 0; (i < fragmentColumnSizesArray.length); i++) { fragmentColumnSizesList.add(fragmentColumnSizesArray[i]); @@ -163,12 +193,15 @@ ColumnLayout layout; try { - layout = new ColumnLayout(numColumns, layoutType, f.getFragments(), fragmentColumnSizesArray); - layout.addLayoutEventListener(new PageManagerLayoutEventListener(pageManager, context.getPage(), layoutType)); + layout = new ColumnLayout(numColumns, layoutType, f.getFragments(), + fragmentColumnSizesArray); + layout.addLayoutEventListener(new PageManagerLayoutEventListener( + pageManager, context.getPage(), layoutType)); } catch (LayoutEventException e1) { - throw new PortletException("Failed to build ColumnLayout "+e1.getMessage(), e1); + throw new PortletException("Failed to build ColumnLayout " + + e1.getMessage(), e1); } // invoke the JSP associated with this portlet @@ -176,8 +209,9 @@ request.setAttribute("numberOfColumns", new Integer(numColumns)); request.setAttribute("decorationFactory", this.decorators); request.setAttribute("columnSizes", fragmentColumnSizesList); - request.setAttribute("editing",editing); - request.setAttribute("fragmentNestingLevel",new Integer(getFragmentNestingLevel(requestPage,f.getId()))); + request.setAttribute("editing", editing); + request.setAttribute("fragmentNestingLevel", new Integer( + getFragmentNestingLevel(requestPage, f.getId()))); super.doView(request, response); request.removeAttribute("decorationFactory"); request.removeAttribute("columnLayout"); @@ -187,34 +221,41 @@ request.removeAttribute(("fragmentNestingLevel")); } - public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException + public void processAction(ActionRequest request, ActionResponse response) + throws PortletException, IOException { - RequestContext requestContext = (RequestContext)request.getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); - - ContentPage requestPage = requestContext.getPage(); - PageEditAccess pageEditAccess = (PageEditAccess)requestContext.getAttribute(PortalReservedParameters.PAGE_EDIT_ACCESS_ATTRIBUTE); - if ( requestPage == null || pageEditAccess == null ) + RequestContext requestContext = (RequestContext) request + .getAttribute(PortalReservedParameters.REQUEST_CONTEXT_ATTRIBUTE); + + ContentPage requestPage = requestContext.getPage(); + PageEditAccess pageEditAccess = (PageEditAccess) requestContext + .getAttribute(PortalReservedParameters.PAGE_EDIT_ACCESS_ATTRIBUTE); + if (requestPage == null || pageEditAccess == null) { - // Targetting this portlet with an ActionRequest REQUIRES that the ProfilerValve has been invoked! - throw new PortletException("Current request page or PageEditAccess not available."); + // Targetting this portlet with an ActionRequest REQUIRES that the + // ProfilerValve has been invoked! + throw new PortletException( + "Current request page or PageEditAccess not available."); } decoratorCache.invalidate(requestContext); - + String pageMode = request.getParameter("pageMode"); - if ( pageMode != null ) + if (pageMode != null) { - if ( "view".equals(pageMode) ) + if ("view".equals(pageMode)) { pageEditAccess.setEditing(false); } - else if ( "edit".equals(pageMode) && pageEditAccess.isEditAllowed() ) + else if ("edit".equals(pageMode) && pageEditAccess.isEditAllowed()) { - if ( this.editorType != null && this.editorType.equals( "desktop" ) ) + if (this.editorType != null + && this.editorType.equals("desktop")) { - String redirectUrl = this.desktop.getPortalUrl( requestContext, requestContext.getPath() ); + String redirectUrl = this.desktop.getPortalUrl( + requestContext, requestContext.getPath()); redirectUrl += "?editPage=true&portal=true"; - response.sendRedirect( redirectUrl ); + response.sendRedirect(redirectUrl); } else { @@ -223,74 +264,87 @@ } return; } - - if ( pageEditAccess.isEditAllowed() && request.isPortletModeAllowed(PortletMode.EDIT) ) + + if (pageEditAccess.isEditAllowed() + && request.isPortletModeAllowed(PortletMode.EDIT)) { String layout = null; - + boolean addLayout = request.getParameter("jsAddLayout") != null; - if ( addLayout || request.getParameter("jsChangeLayout") != null ) + if (addLayout || request.getParameter("jsChangeLayout") != null) { layout = request.getParameter("layout"); - if ( layout != null && layout.length() > 0 ) + if (layout != null && layout.length() > 0) { PortletWindow window = requestContext.getActionWindow(); - ContentFragment targetFragment = requestPage.getContentFragmentById(window.getId().toString()); - - if ( targetFragment == null ) + ContentFragment targetFragment = requestPage + .getContentFragmentById(window.getId().toString()); + + if (targetFragment == null) { // ignore no longer consistent page definition return; } - - if ( addLayout ) + + if (addLayout) { try { Fragment fragment = pageManager.newFragment(); fragment.setType(Fragment.LAYOUT); - fragment.setName(layout); + fragment.setName(layout); targetFragment.getFragments().add(fragment); pageManager.updatePage(requestPage); - clearLayoutAttributes(request); + clearLayoutAttributes(request); } catch (Exception e) { - throw new PortletException("failed to add portlet " + layout + " to page: " + requestPage+": "+e.getMessage(), e); + throw new PortletException("failed to add portlet " + + layout + " to page: " + requestPage + + ": " + e.getMessage(), e); } } - else if ( !layout.equals(targetFragment.getName()) ) + else if (!layout.equals(targetFragment.getName())) { try { // layout portlet change targetFragment.setName(layout); pageManager.updatePage(requestPage); - entityAccess.updatePortletEntity(window.getPortletEntity(), targetFragment); - entityAccess.storePortletEntity(window.getPortletEntity()); - windowAccess.createPortletWindow(window.getPortletEntity(), targetFragment.getId()); + entityAccess.updatePortletEntity(window + .getPortletEntity(), targetFragment); + entityAccess.storePortletEntity(window + .getPortletEntity()); + windowAccess + .createPortletWindow(window + .getPortletEntity(), targetFragment + .getId()); clearLayoutAttributes(request); return; } catch (Exception e) { - throw new PortletException("Unable to update page: "+e.getMessage(), e); + throw new PortletException( + "Unable to update page: " + e.getMessage(), + e); } } } return; } - if ( request.getParameter("jsSubmitPage" ) != null ) + if (request.getParameter("jsSubmitPage") != null) { String jsPageName = request.getParameter("jsPageName"); String jsPageTitle = request.getParameter("jsPageTitle"); - String jsPageShortTitle = request.getParameter("jsPageShortTitle"); - if ( jsPageName != null && jsPageName.length() > 0 && jsPageName.indexOf(Folder.PATH_SEPARATOR) == -1 ) + String jsPageShortTitle = request + .getParameter("jsPageShortTitle"); + if (jsPageName != null && jsPageName.length() > 0 + && jsPageName.indexOf(Folder.PATH_SEPARATOR) == -1) { try - { - Folder parent = (Folder)requestPage.getParent(); + { + Folder parent = (Folder) requestPage.getParent(); if (parent != null) { String path = parent.getPath(); @@ -304,19 +358,27 @@ + getEscapedName(jsPageName); } Page page = pageManager.newPage(path); - if ( layout == null || layout.length() == 0 ) + if (layout == null || layout.length() == 0) { - layout = requestPage.getRootFragment().getName(); + layout = requestPage.getRootFragment() + .getName(); } page.getRootFragment().setName(layout); - page.setDefaultDecorator(requestPage.getDefaultDecorator(Fragment.LAYOUT), Fragment.LAYOUT); - page.setDefaultDecorator(requestPage.getDefaultDecorator(Fragment.PORTLET), Fragment.PORTLET); - page.setTitle(jsPageTitle != null && !jsPageTitle.equals("") ? jsPageTitle : jsPageName); - page.setShortTitle(jsPageShortTitle != null + page.setDefaultDecorator(requestPage + .getDefaultDecorator(Fragment.LAYOUT), + Fragment.LAYOUT); + page.setDefaultDecorator(requestPage + .getDefaultDecorator(Fragment.PORTLET), + Fragment.PORTLET); + page.setTitle(jsPageTitle != null + && !jsPageTitle.equals("") ? jsPageTitle + : jsPageName); + page + .setShortTitle(jsPageShortTitle != null && !jsPageShortTitle.equals("") ? jsPageShortTitle : jsPageName); pageManager.updatePage(page); - clearLayoutAttributes(request); + clearLayoutAttributes(request); List orderList = parent.getDocumentOrder(); if (orderList != null) { @@ -332,8 +394,10 @@ } catch (Exception e) { - throw new PortletException("Unable to access page for editing: "+e.getMessage(), e); - } + throw new PortletException( + "Unable to access page for editing: " + + e.getMessage(), e); + } } return; } @@ -365,11 +429,11 @@ return; } - if ( request.getParameter("jsDeletePage" ) != null ) + if (request.getParameter("jsDeletePage") != null) { try { - Folder parent = (Folder)requestPage.getParent(); + Folder parent = (Folder) requestPage.getParent(); if (parent != null) { List orderList = parent.getDocumentOrder(); @@ -389,7 +453,9 @@ } catch (Exception e) { - throw new PortletException("Unable to access page for removing: "+e.getMessage(), e); + throw new PortletException( + "Unable to access page for removing: " + + e.getMessage(), e); } return; } @@ -502,13 +568,14 @@ + e.getMessage(), e); } return; - } + } if (request.getParameter("jsSubmitFolder") != null) { String jsFolderName = request.getParameter("jsFolderName"); String jsFolderTitle = request.getParameter("jsFolderTitle"); - String jsFolderShortTitle = request.getParameter("jsFolderShortTitle"); + String jsFolderShortTitle = request + .getParameter("jsFolderShortTitle"); if (jsFolderName != null && jsFolderName.length() > 0 && jsFolderName.indexOf(Folder.PATH_SEPARATOR) == -1) { @@ -642,7 +709,7 @@ } return; } - + if (request.getParameter("jsDeleteFolder") != null) { try @@ -789,7 +856,10 @@ } String theme = request.getParameter("theme"); - if ( theme != null && theme.length() > 0 && !theme.equals(requestPage.getDefaultDecorator(Fragment.LAYOUT)) ) + if (theme != null + && theme.length() > 0 + && !theme.equals(requestPage + .getDefaultDecorator(Fragment.LAYOUT))) { requestPage.setDefaultDecorator(theme, Fragment.LAYOUT); try @@ -798,41 +868,49 @@ } catch (Exception e) { - throw new PortletException("Unable to update page: "+e.getMessage(), e); + throw new PortletException("Unable to update page: " + + e.getMessage(), e); } return; } - + String fragmentId = request.getParameter("fragment"); - if ( fragmentId != null && fragmentId.length() > 0 ) + if (fragmentId != null && fragmentId.length() > 0) { String move = request.getParameter("move"); - if ( move != null && move.length() > 0 ) + if (move != null && move.length() > 0) { - int moveCode = Integer.parseInt(move); + int moveCode = Integer.parseInt(move); PortletWindow window = requestContext.getActionWindow(); - Fragment currentFragment = requestPage.getFragmentById(window.getId().toString()); - Fragment fragmentToMove = requestPage.getFragmentById(fragmentId); - - if ( currentFragment == null || fragmentToMove == null ) + Fragment currentFragment = requestPage + .getFragmentById(window.getId().toString()); + Fragment fragmentToMove = requestPage + .getFragmentById(fragmentId); + + if (currentFragment == null || fragmentToMove == null) { // ignore no longer consistent page definition return; } - + ColumnLayout columnLayout; try { - columnLayout = new ColumnLayout(numColumns, layoutType, currentFragment.getFragments(), null); - columnLayout.addLayoutEventListener(new PageManagerLayoutEventListener(pageManager, requestPage, layoutType)); + columnLayout = new ColumnLayout(numColumns, layoutType, + currentFragment.getFragments(), null); + columnLayout + .addLayoutEventListener(new PageManagerLayoutEventListener( + pageManager, requestPage, layoutType)); } catch (LayoutEventException e1) { - throw new PortletException("Failed to build ColumnLayout "+e1.getMessage(), e1); + throw new PortletException( + "Failed to build ColumnLayout " + + e1.getMessage(), e1); } try - { + { switch (moveCode) { case LayoutEvent.MOVED_UP: @@ -848,70 +926,83 @@ columnLayout.moveLeft(fragmentToMove); break; default: - throw new PortletException("Invalid movement code " + moveCode); + throw new PortletException("Invalid movement code " + + moveCode); } - + } catch (SecurityException se) { // ignore page security constraint violations, only // permitted users can edit managed pages; page // update will remain transient - log.info("Unable to update page " + requestPage.getId() + " layout due to security permission/constraint.", se); + log + .info( + "Unable to update page " + + requestPage.getId() + + " layout due to security permission/constraint.", + se); } catch (Exception e) { if (e instanceof PortletException) { - throw (PortletException)e; + throw (PortletException) e; } else { - throw new PortletException("Unable to process layout for page " + requestPage.getId() + " layout: " + e.toString(), e); + throw new PortletException( + "Unable to process layout for page " + + requestPage.getId() + " layout: " + + e.toString(), e); } } return; } - + String remove = request.getParameter("remove"); - if ( remove != null && remove.length() > 0 ) + if (remove != null && remove.length() > 0) { Page page = null; try { - // TODO: for now retrieve the real Page instead of ContentPage - // because removing fragments isn't working through the ContentFragment wrapping + // TODO: for now retrieve the real Page instead of + // ContentPage + // because removing fragments isn't working through the + // ContentFragment wrapping page = pageManager.getPage(requestPage.getPath()); } catch (Exception e) { - throw new PortletException("Unable to retrieve page "+requestPage.getId(),e); + throw new PortletException("Unable to retrieve page " + + requestPage.getId(), e); } PortletWindow window = requestContext.getActionWindow(); - Fragment currentFragment = page.getFragmentById(window.getId().toString()); + Fragment currentFragment = page.getFragmentById(window + .getId().toString()); - if ( currentFragment == null ) + if (currentFragment == null) { // ignore no longer consistent page definition return; } - + removeFragment(page, currentFragment, fragmentId); return; } - + String decorator = request.getParameter("decorator"); - if ( decorator != null ) + if (decorator != null) { Fragment fragment = requestPage.getFragmentById(fragmentId); - if ( fragment == null ) + if (fragment == null) { // ignore no longer consistent page definition return; } - + if (decorator.trim().length() == 0) fragment.setDecorator(null); else @@ -922,57 +1013,70 @@ } catch (Exception e) { - throw new PortletException("Unable to update page for fragment decorator: "+e.getMessage(), e); + throw new PortletException( + "Unable to update page for fragment decorator: " + + e.getMessage(), e); } return; } } - // change style for all pages in user folder - String jsChangeUserPagesTheme = request.getParameter("jsChangeUserPagesTheme"); - if ( jsChangeUserPagesTheme != null ) + // change style for all pages in user folder + String jsChangeUserPagesTheme = request + .getParameter("jsChangeUserPagesTheme"); + if (jsChangeUserPagesTheme != null) { - String user_pages_theme = request.getParameter("user_pages_theme"); - try + String user_pages_theme = request + .getParameter("user_pages_theme"); + try { - Folder f = pageManager.getUserFolder(request.getRemoteUser()); - applyStyle(f,user_pages_theme,Fragment.LAYOUT); + Folder f = pageManager.getUserFolder(request + .getRemoteUser()); + applyStyle(f, user_pages_theme, Fragment.LAYOUT); } catch (Exception e) { - throw new PortletException("Unable to update folder for defUserLayoutDeco decorator: "+e.getMessage(), e); + throw new PortletException( + "Unable to update folder for defUserLayoutDeco decorator: " + + e.getMessage(), e); } return; - } - String jsChangeUserPortletsDeco = request.getParameter("jsChangeUserPortletsDeco"); - if ( jsChangeUserPortletsDeco != null ) - { - String user_portlets_deco = request.getParameter("user_portlets_deco"); - try + } + String jsChangeUserPortletsDeco = request + .getParameter("jsChangeUserPortletsDeco"); + if (jsChangeUserPortletsDeco != null) + { + String user_portlets_deco = request + .getParameter("user_portlets_deco"); + try { - Folder f = pageManager.getUserFolder(request.getRemoteUser()); - applyStyle(f,user_portlets_deco,Fragment.PORTLET); + Folder f = pageManager.getUserFolder(request + .getRemoteUser()); + applyStyle(f, user_portlets_deco, Fragment.PORTLET); } - catch (Exception e) + catch (Exception e) { - throw new PortletException("Unable to update folder for defUserPortletDeco decorator: "+e.getMessage(), e); + throw new PortletException( + "Unable to update folder for defUserPortletDeco decorator: " + + e.getMessage(), e); } - return; - } - + return; + } + String jsChangeThemeAll = request.getParameter("jsChangeThemeAll"); if (jsChangeThemeAll != null) { - String decorators = request.getParameter("decorators"); - Iterator fragmentsIter = requestPage.getRootFragment().getFragments().iterator(); - while(fragmentsIter.hasNext()) + String decorators = request.getParameter("decorators"); + Iterator fragmentsIter = requestPage.getRootFragment() + .getFragments().iterator(); + while (fragmentsIter.hasNext()) { Fragment fragment = (Fragment) fragmentsIter.next(); - if ( fragment == null ) + if (fragment == null) { // ignore no longer consistent page definition return; } - + if (decorators.trim().length() == 0) fragment.setDecorator(null); else @@ -984,30 +1088,33 @@ } catch (Exception e) { - throw new PortletException("Unable to update page for fragment decorator: "+e.getMessage(), e); + throw new PortletException( + "Unable to update page for fragment decorator: " + + e.getMessage(), e); } return; - } - + } + String portlets = request.getParameter("portlets"); - if ( portlets != null && portlets.length() > 0 ) + if (portlets != null && portlets.length() > 0) { PortletWindow window = requestContext.getActionWindow(); - Fragment targetFragment = requestPage.getFragmentById(window.getId().toString()); + Fragment targetFragment = requestPage.getFragmentById(window + .getId().toString()); - if ( targetFragment == null ) + if (targetFragment == null) { // ignore no longer consistent page definition return; } - - StringTokenizer tokenizer = new StringTokenizer(portlets, ","); + + StringTokenizer tokenizer = new StringTokenizer(portlets, ","); while (tokenizer.hasMoreTokens()) { String portlet = tokenizer.nextToken(); if (portlet.startsWith("box_")) { - portlet = portlet.substring("box_".length()); + portlet = portlet.substring("box_".length()); addPortletToPage(requestPage, targetFragment, portlet); } } @@ -1015,19 +1122,23 @@ } } } - + protected void clearLayoutAttributes(ActionRequest request) { - request.getPortletSession().removeAttribute(PortalReservedParameters.PAGE_LAYOUT_VIEW); - request.getPortletSession().removeAttribute(PortalReservedParameters.PAGE_LAYOUT_SOLO); - request.getPortletSession().removeAttribute(PortalReservedParameters.PAGE_LAYOUT_MAX); - request.getPortletSession().removeAttribute(PortalReservedParameters.PAGE_LAYOUT_HELP); + request.getPortletSession().removeAttribute( + PortalReservedParameters.PAGE_LAYOUT_VIEW); + request.getPortletSession().removeAttribute( + PortalReservedParameters.PAGE_LAYOUT_SOLO); + request.getPortletSession().removeAttribute( + PortalReservedParameters.PAGE_LAYOUT_MAX); + request.getPortletSession().removeAttribute( + PortalReservedParameters.PAGE_LAYOUT_HELP); } protected int getFragmentNestingLevel(Page page, String fragmentId) { Fragment root = page.getRootFragment(); - if ( root.getId().equals(fragmentId) ) + if (root.getId().equals(fragmentId)) { return 0; } @@ -1036,26 +1147,25 @@ return getFragmentNestingLevel(root, 1, fragmentId); } } - - protected int getFragmentNestingLevel(Fragment parent, int level, String fragmentId) + + protected int getFragmentNestingLevel(Fragment parent, int level, + String fragmentId) { Iterator iter = parent.getFragments().iterator(); Fragment child; int childLevel; - while ( iter.hasNext() ) + while (iter.hasNext()) { - child = (Fragment)iter.next(); + child = (Fragment) iter.next(); if (child.getId().equals(fragmentId)) { return level; } else { - childLevel = getFragmentNestingLevel(child, level+1, fragmentId); - if ( childLevel != -1 ) - { - return childLevel; - } + childLevel = getFragmentNestingLevel(child, level + 1, + fragmentId); + if (childLevel != -1) { return childLevel; } } } return -1; @@ -1073,23 +1183,24 @@ return pageName; } } - - private void applyStyle(Folder f, String theme, String theme_type) throws FolderNotUpdatedException, NodeException + + private void applyStyle(Folder f, String theme, String theme_type) + throws FolderNotUpdatedException, NodeException { - f.setDefaultDecorator(theme, theme_type); - pageManager.updateFolder(f); - Iterator pagesIter = f.getPages().iterator(); - while(pagesIter.hasNext()) - { - Page pp = (Page) pagesIter.next(); - pp.setDefaultDecorator(theme, theme_type); - pageManager.updatePage(pp); - } - Iterator userFoldersIter = pageManager.getFolders(f).iterator(); - while(userFoldersIter.hasNext()) - { - Folder ff = (Folder) userFoldersIter.next(); - applyStyle(ff,theme,theme_type); - } - } + f.setDefaultDecorator(theme, theme_type); + pageManager.updateFolder(f); + Iterator pagesIter = f.getPages().iterator(); + while (pagesIter.hasNext()) + { + Page pp = (Page) pagesIter.next(); + pp.setDefaultDecorator(theme, theme_type); + pageManager.updatePage(pp); + } + Iterator userFoldersIter = pageManager.getFolders(f).iterator(); + while (userFoldersIter.hasNext()) + { + Folder ff = (Folder) userFoldersIter.next(); + applyStyle(ff, theme, theme_type); + } + } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/util/ResourceBundleFactory.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/util/ResourceBundleFactory.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/java/org/apache/jetspeed/portlets/layout/util/ResourceBundleFactory.java 2008-05-16 01:54:54 UTC (rev 940) @@ -15,46 +15,49 @@ import org.apache.jetspeed.request.RequestContext; -public class ResourceBundleFactory { +public class ResourceBundleFactory +{ private long timeToLive; private Map resourceBundleCache; - public ResourceBundleFactory(long timeToLive) { + public ResourceBundleFactory(long timeToLive) + { this.timeToLive = timeToLive; resourceBundleCache = new HashMap(); } public ResourceBundle getResourceBundle(RequestContext requestContext, - String resourcePath, String resourceName, Locale locale) { + String resourcePath, String resourceName, Locale locale) + { long now = new Date().getTime(); String resourceKey = resourcePath + "/" + resourceName + "_" + locale.toString(); List resource = (List) resourceBundleCache.get(resourceKey); - if (resource != null) { + if (resource != null) + { // a cached resource is available - if (now - ((Long) resource.get(0)).longValue() < timeToLive) { - return (ResourceBundle) resource.get(1); - } + if (now - ((Long) resource.get(0)).longValue() < timeToLive) { return (ResourceBundle) resource + .get(1); } // expired } String resourceDirName = requestContext.getConfig().getServletContext() .getRealPath(resourcePath); File resourceDir = new File(resourceDirName); - if (resourceName == null) { - throw new NullPointerException("The resource file is null."); - } - if (!resourceDir.isDirectory()) { - throw new MissingResourceException( - "Can't find the resource directory: " + resourceDirName, - resourceName + "_" + locale, ""); - } + if (resourceName == null) { throw new NullPointerException( + "The resource file is null."); } + if (!resourceDir.isDirectory()) { throw new MissingResourceException( + "Can't find the resource directory: " + resourceDirName, + resourceName + "_" + locale, ""); } URL[] urls = new URL[1]; - try { + try + { urls[0] = resourceDir.toURL(); - } catch (MalformedURLException e) { + } + catch (MalformedURLException e) + { throw new MissingResourceException( "The resource directory cannot be parsed as a URL: " + resourceDirName, resourceName + "_" + locale, ""); Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/test/org/apache/jetspeed/portlets/layout/TestColumnLayout.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/test/org/apache/jetspeed/portlets/layout/TestColumnLayout.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/layout-portlets/src/test/org/apache/jetspeed/portlets/layout/TestColumnLayout.java 2008-05-16 01:54:54 UTC (rev 940) @@ -25,8 +25,10 @@ public class TestColumnLayout extends MockObjectTestCase { - private static final String[] widths=new String[]{"25%", "50%", "25%"}; - + + private static final String[] widths = new String[] + {"25%", "50%", "25%"}; + private ColumnLayout layout; private FragmentImpl f1; @@ -40,15 +42,15 @@ private FragmentImpl f5; private FragmentImpl f6; - + private FragmentImpl f8; public void testBasics() throws Exception { assertEquals(f1, layout.getFirstColumn().iterator().next()); - + // The last column is currently empty - // assertTrue(layout.getLastColumn().isEmpty()); + // assertTrue(layout.getLastColumn().isEmpty()); assertEquals(3, layout.getNumberOfColumns()); Iterator column0 = layout.getColumn(0).iterator(); @@ -71,7 +73,8 @@ assertEquals(f5, column1.next()); assertEquals(f6, column1.next()); - Fragment testFragment = layout.getFragmentAt(new LayoutCoordinate(0, 0)); + Fragment testFragment = layout + .getFragmentAt(new LayoutCoordinate(0, 0)); assertNotNull(testFragment); assertEquals(f1, testFragment); @@ -82,17 +85,17 @@ testFragment = layout.getFragmentAt(1, 0); assertNotNull(testFragment); assertEquals(f4, testFragment); - + assertEquals(3, layout.getColumns().size()); - + assertEquals(2, layout.getLastRowNumber(0)); - assertEquals(2, layout.getLastRowNumber(1)); - + assertEquals(2, layout.getLastRowNumber(1)); + // test widths assertEquals("25%", layout.getColumnWidth(0)); assertEquals("50%", layout.getColumnWidth(1)); - assertEquals("24.99%", layout.getColumnWidth(2)); - assertEquals("0", layout.getColumnWidth(3)); + assertEquals("24.99%", layout.getColumnWidth(2)); + assertEquals("0", layout.getColumnWidth(3)); assertEquals("left", layout.getColumnFloat(0)); assertEquals("left", layout.getColumnFloat(1)); @@ -208,23 +211,30 @@ public void testMovingRight() throws Exception { - Fragment movingFragment = layout.getFragmentAt(new LayoutCoordinate(0, 0)); + Fragment movingFragment = layout.getFragmentAt(new LayoutCoordinate(0, + 0)); assertEquals(f1, movingFragment); assertEquals(f4, layout.getFragmentAt(new LayoutCoordinate(1, 0))); Mock listenerMock = mock(LayoutEventListener.class); - layout.addLayoutEventListener((LayoutEventListener) listenerMock.proxy()); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f1, layout, LayoutEvent.MOVED_RIGHT))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f2, layout, LayoutEvent.MOVED_UP))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f3, layout, LayoutEvent.MOVED_UP))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f4, layout, LayoutEvent.MOVED_DOWN))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f5, layout, LayoutEvent.MOVED_DOWN))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f6, layout, LayoutEvent.MOVED_DOWN))); - - + layout.addLayoutEventListener((LayoutEventListener) listenerMock + .proxy()); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f1, layout, LayoutEvent.MOVED_RIGHT))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f2, layout, LayoutEvent.MOVED_UP))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f3, layout, LayoutEvent.MOVED_UP))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f4, layout, LayoutEvent.MOVED_DOWN))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f5, layout, LayoutEvent.MOVED_DOWN))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f6, layout, LayoutEvent.MOVED_DOWN))); + // moving right layout.moveRight(movingFragment); - + assertEquals(f1, layout.getFragmentAt(new LayoutCoordinate(1, 0))); assertEquals(f2, layout.getFragmentAt(new LayoutCoordinate(0, 0))); assertEquals(f3, layout.getFragmentAt(new LayoutCoordinate(0, 1))); @@ -235,19 +245,27 @@ public void testMovingLeft() throws Exception { - Fragment movingFragment = layout.getFragmentAt(new LayoutCoordinate(1, 0)); + Fragment movingFragment = layout.getFragmentAt(new LayoutCoordinate(1, + 0)); assertEquals(f4, movingFragment); assertEquals(f1, layout.getFragmentAt(new LayoutCoordinate(0, 0))); - + Mock listenerMock = mock(LayoutEventListener.class); - layout.addLayoutEventListener((LayoutEventListener) listenerMock.proxy()); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f4, layout, LayoutEvent.MOVED_LEFT))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f5, layout, LayoutEvent.MOVED_UP))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f6, layout, LayoutEvent.MOVED_UP))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f1, layout, LayoutEvent.MOVED_DOWN))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f2, layout, LayoutEvent.MOVED_DOWN))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f3, layout, LayoutEvent.MOVED_DOWN))); - + layout.addLayoutEventListener((LayoutEventListener) listenerMock + .proxy()); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f4, layout, LayoutEvent.MOVED_LEFT))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f5, layout, LayoutEvent.MOVED_UP))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f6, layout, LayoutEvent.MOVED_UP))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f1, layout, LayoutEvent.MOVED_DOWN))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f2, layout, LayoutEvent.MOVED_DOWN))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f3, layout, LayoutEvent.MOVED_DOWN))); + layout.moveLeft(f4); assertEquals(f1, layout.getFragmentAt(new LayoutCoordinate(0, 1))); @@ -256,13 +274,17 @@ assertEquals(f4, layout.getFragmentAt(new LayoutCoordinate(0, 0))); assertEquals(f5, layout.getFragmentAt(new LayoutCoordinate(1, 0))); assertEquals(f6, layout.getFragmentAt(new LayoutCoordinate(1, 1))); - - listenerMock.reset(); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f6, layout, LayoutEvent.MOVED_LEFT))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f1, layout, LayoutEvent.MOVED_DOWN))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f2, layout, LayoutEvent.MOVED_DOWN))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f3, layout, LayoutEvent.MOVED_DOWN))); + listenerMock.reset(); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f6, layout, LayoutEvent.MOVED_LEFT))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f1, layout, LayoutEvent.MOVED_DOWN))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f2, layout, LayoutEvent.MOVED_DOWN))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f3, layout, LayoutEvent.MOVED_DOWN))); + layout.moveLeft(f6); assertEquals(f1, layout.getFragmentAt(new LayoutCoordinate(0, 2))); @@ -272,16 +294,20 @@ assertEquals(f5, layout.getFragmentAt(new LayoutCoordinate(1, 0))); assertEquals(f6, layout.getFragmentAt(new LayoutCoordinate(0, 1))); - listenerMock.reset(); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f5, layout, LayoutEvent.MOVED_LEFT))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f4, layout, LayoutEvent.MOVED_DOWN))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f6, layout, LayoutEvent.MOVED_DOWN))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f1, layout, LayoutEvent.MOVED_DOWN))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f2, layout, LayoutEvent.MOVED_DOWN))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f3, layout, LayoutEvent.MOVED_DOWN))); - - + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f5, layout, LayoutEvent.MOVED_LEFT))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f4, layout, LayoutEvent.MOVED_DOWN))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f6, layout, LayoutEvent.MOVED_DOWN))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f1, layout, LayoutEvent.MOVED_DOWN))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f2, layout, LayoutEvent.MOVED_DOWN))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f3, layout, LayoutEvent.MOVED_DOWN))); + layout.moveLeft(f5); assertEquals(f1, layout.getFragmentAt(new LayoutCoordinate(0, 3))); @@ -301,9 +327,10 @@ listenerMock.reset(); LayoutCoordinate coordinate = new LayoutCoordinate(1, 0); - LayoutEvent event = new LayoutEvent(LayoutEvent.ADDED, f7, coordinate, coordinate); + LayoutEvent event = new LayoutEvent(LayoutEvent.ADDED, f7, coordinate, + coordinate); listenerMock.expects(once()).method("handleEvent").with(eq(event)); - + layout.addFragment(f7); assertEquals(f1, layout.getFragmentAt(new LayoutCoordinate(0, 3))); @@ -331,11 +358,13 @@ public void testInvalidOperations() throws Exception { - // Create a mock that veridies events are NOT being fired on invalid operations + // Create a mock that veridies events are NOT being fired on invalid + // operations Mock listenerMock = mock(LayoutEventListener.class); - layout.addLayoutEventListener((LayoutEventListener) listenerMock.proxy()); + layout.addLayoutEventListener((LayoutEventListener) listenerMock + .proxy()); listenerMock.expects(never()).method("handleEvent").withAnyArguments(); - + layout.moveUp(f1); // Nothing at all should happen, not even exceptions assertEquals(f1, layout.getFragmentAt(new LayoutCoordinate(0, 0))); @@ -346,7 +375,7 @@ assertEquals(f6, layout.getFragmentAt(new LayoutCoordinate(1, 2))); layout.moveDown(f3); // Nothing at all should happen, not even - // exceptions + // exceptions assertEquals(f1, layout.getFragmentAt(new LayoutCoordinate(0, 0))); assertEquals(f2, layout.getFragmentAt(new LayoutCoordinate(0, 1))); @@ -369,9 +398,12 @@ public void testMoveDown() throws Exception { Mock listenerMock = mock(LayoutEventListener.class); - layout.addLayoutEventListener((LayoutEventListener) listenerMock.proxy()); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f1, layout, LayoutEvent.MOVED_DOWN))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f2, layout, LayoutEvent.MOVED_UP))); + layout.addLayoutEventListener((LayoutEventListener) listenerMock + .proxy()); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f1, layout, LayoutEvent.MOVED_DOWN))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f2, layout, LayoutEvent.MOVED_UP))); layout.moveDown(f1); @@ -381,10 +413,12 @@ assertEquals(f4, layout.getFragmentAt(new LayoutCoordinate(1, 0))); assertEquals(f5, layout.getFragmentAt(new LayoutCoordinate(1, 1))); assertEquals(f6, layout.getFragmentAt(new LayoutCoordinate(1, 2))); - - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f1, layout, LayoutEvent.MOVED_DOWN))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f3, layout, LayoutEvent.MOVED_UP))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f1, layout, LayoutEvent.MOVED_DOWN))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f3, layout, LayoutEvent.MOVED_UP))); + layout.moveDown(f1); assertEquals(f1, layout.getFragmentAt(new LayoutCoordinate(0, 2))); @@ -393,8 +427,8 @@ assertEquals(f4, layout.getFragmentAt(new LayoutCoordinate(1, 0))); assertEquals(f5, layout.getFragmentAt(new LayoutCoordinate(1, 1))); assertEquals(f6, layout.getFragmentAt(new LayoutCoordinate(1, 2))); - - //try moving a fragment below the bottom-most row. + + // try moving a fragment below the bottom-most row. listenerMock.expects(never()).method("handleEvent").withAnyArguments(); layout.moveDown(f6); assertEquals(f6, layout.getFragmentAt(new LayoutCoordinate(1, 2))); @@ -405,9 +439,12 @@ { Mock listenerMock = mock(LayoutEventListener.class); - layout.addLayoutEventListener((LayoutEventListener) listenerMock.proxy()); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f3, layout, LayoutEvent.MOVED_UP))); - listenerMock.expects(once()).method("handleEvent").with(eq(createEvent(f2, layout, LayoutEvent.MOVED_DOWN))); + layout.addLayoutEventListener((LayoutEventListener) listenerMock + .proxy()); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f3, layout, LayoutEvent.MOVED_UP))); + listenerMock.expects(once()).method("handleEvent").with( + eq(createEvent(f2, layout, LayoutEvent.MOVED_DOWN))); layout.moveUp(f3); assertEquals(f1, layout.getFragmentAt(new LayoutCoordinate(0, 0))); @@ -437,13 +474,13 @@ f3.setName("test"); f3.setLayoutRow(2); f3.setLayoutColumn(0); - + f4 = new FragmentImpl(); f4.setId("f4"); f4.setName("test"); f4.setLayoutRow(0); f4.setLayoutColumn(1); - + f5 = new FragmentImpl(); f5.setId("f5"); f5.setName("test"); @@ -455,7 +492,7 @@ f6.setName("test"); f6.setLayoutRow(2); f6.setLayoutColumn(1); - + f8 = new FragmentImpl(); f8.setId("f8"); f8.setName("test"); @@ -472,7 +509,8 @@ layout.addFragment(f8); } - protected LayoutEvent createEvent(Fragment fragment, ColumnLayout layout, int eventType) throws Exception + protected LayoutEvent createEvent(Fragment fragment, ColumnLayout layout, + int eventType) throws Exception { LayoutCoordinate fragmentOriginal = layout.getCoordinate(fragment); LayoutCoordinate fragmentNew; @@ -480,23 +518,29 @@ switch (eventType) { case LayoutEvent.MOVED_UP: - fragmentNew = new LayoutCoordinate(fragmentOriginal.getX(), fragmentOriginal.getY() - 1); + fragmentNew = new LayoutCoordinate(fragmentOriginal.getX(), + fragmentOriginal.getY() - 1); break; case LayoutEvent.MOVED_DOWN: - fragmentNew = new LayoutCoordinate(fragmentOriginal.getX(), fragmentOriginal.getY() + 1); + fragmentNew = new LayoutCoordinate(fragmentOriginal.getX(), + fragmentOriginal.getY() + 1); break; case LayoutEvent.MOVED_LEFT: - fragmentNew = new LayoutCoordinate(fragmentOriginal.getX() - 1, fragmentOriginal.getY()); + fragmentNew = new LayoutCoordinate(fragmentOriginal.getX() - 1, + fragmentOriginal.getY()); break; case LayoutEvent.MOVED_RIGHT: - fragmentNew = new LayoutCoordinate(fragmentOriginal.getX() + 1, fragmentOriginal.getY()); + fragmentNew = new LayoutCoordinate(fragmentOriginal.getX() + 1, + fragmentOriginal.getY()); break; default: - fragmentNew = new LayoutCoordinate(fragmentOriginal.getX(), fragmentOriginal.getY()); + fragmentNew = new LayoutCoordinate(fragmentOriginal.getX(), + fragmentOriginal.getY()); break; } - return new LayoutEvent(eventType, fragment, fragmentOriginal, fragmentNew); + return new LayoutEvent(eventType, fragment, fragmentOriginal, + fragmentNew); } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/maven-plugin/src/java/org/apache/jetspeed/dbutil/HSQLServer.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/maven-plugin/src/java/org/apache/jetspeed/dbutil/HSQLServer.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/maven-plugin/src/java/org/apache/jetspeed/dbutil/HSQLServer.java 2008-05-16 01:54:54 UTC (rev 940) @@ -22,38 +22,37 @@ import org.hsqldb.Server; - /** * @author Sweaver - * - * To change the template for this generated type comment go to - * Window - Preferences - Java - Code Generation - Code and Comments + * + * To change the template for this generated type comment go to Window - + * Preferences - Java - Code Generation - Code and Comments */ public class HSQLServer { public static void main(String[] args) { - if(args[0].equals("kill")) + if (args[0].equals("kill")) { kill(Integer.parseInt(args[1]), args[2], args[3]); return; } - + try { System.out.println("Starting server: " + args[1]); Thread hsql = new HSQLServerThread(args); hsql.start(); System.out.println("Exiting HSQL"); - + } catch (Exception e) { - + } } - + private static void kill(int port, String user, String password) { try @@ -68,10 +67,9 @@ } catch (Exception e) { - + } - - + } } @@ -82,10 +80,10 @@ HSQLServerThread(String args[]) { - - this.args = args; + + this.args = args; setDaemon(true); - + } /** @@ -95,8 +93,7 @@ { System.out.println("Starting HSQLDB server"); Server.main(args); - + } - - + } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/maven-plugin/src/java/org/apache/jetspeed/dbutil/ScriptUtil.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/maven-plugin/src/java/org/apache/jetspeed/dbutil/ScriptUtil.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/maven-plugin/src/java/org/apache/jetspeed/dbutil/ScriptUtil.java 2008-05-16 01:54:54 UTC (rev 940) @@ -30,7 +30,7 @@ System.out.println("Running DBUtils " + args[0]); try { - if(args.length == 2 && args[0].equals("-drops")) + if (args.length == 2 && args[0].equals("-drops")) { dropdrops(args[1]); } @@ -40,17 +40,16 @@ e.printStackTrace(); } } - - public static void dropdrops(String filename) - throws Exception + + public static void dropdrops(String filename) throws Exception { System.out.println("dropping drops from " + filename); String outputFileName = filename + ".tmp"; FileReader fr = new FileReader(filename); BufferedReader reader = new BufferedReader(fr); - + FileWriter fw = new FileWriter(outputFileName); - PrintWriter writer = new PrintWriter(fw); + PrintWriter writer = new PrintWriter(fw); String line; while ((line = reader.readLine()) != null) { @@ -67,5 +66,5 @@ original.delete(); modified.renameTo(original); } - + } \ No newline at end of file Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/jetspeed/portlets/tags/PortletTreeControlTag.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/jetspeed/portlets/tags/PortletTreeControlTag.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/jetspeed/portlets/tags/PortletTreeControlTag.java 2008-05-16 01:54:54 UTC (rev 940) @@ -17,6 +17,7 @@ package org.apache.jetspeed.portlets.tags; import java.io.IOException; + import javax.portlet.PortletRequest; import javax.portlet.PortletURL; import javax.portlet.RenderResponse; @@ -33,305 +34,335 @@ */ public class PortletTreeControlTag extends TreeControlTag { + private static final String PORTLET_REQUEST = "portlet_request"; + private static final String PORTLET_SESSION = "portlet_session"; - + /** * The names of tree state images that we need. * * Copied from parent */ - static final String IMAGE_HANDLE_DOWN_LAST = "handledownlast.gif"; - static final String IMAGE_HANDLE_DOWN_MIDDLE = "handledownmiddle.gif"; - static final String IMAGE_HANDLE_RIGHT_LAST = "handlerightlast.gif"; + static final String IMAGE_HANDLE_DOWN_LAST = "handledownlast.gif"; + + static final String IMAGE_HANDLE_DOWN_MIDDLE = "handledownmiddle.gif"; + + static final String IMAGE_HANDLE_RIGHT_LAST = "handlerightlast.gif"; + static final String IMAGE_HANDLE_RIGHT_MIDDLE = "handlerightmiddle.gif"; - static final String IMAGE_LINE_LAST = "linelastnode.gif"; - static final String IMAGE_LINE_MIDDLE = "linemiddlenode.gif"; - static final String IMAGE_LINE_VERTICAL = "linevertical.gif"; - - public void setScope(String scope) { - if (!PORTLET_REQUEST.equals(scope) && - !PORTLET_SESSION.equals(scope) - ) + + static final String IMAGE_LINE_LAST = "linelastnode.gif"; + + static final String IMAGE_LINE_MIDDLE = "linemiddlenode.gif"; + + static final String IMAGE_LINE_VERTICAL = "linevertical.gif"; + + public void setScope(String scope) + { + if (!PORTLET_REQUEST.equals(scope) && !PORTLET_SESSION.equals(scope)) { super.setScope(scope); } this.scope = scope; } - + /** * Return the <code>TreeControl</code> instance for the tree control that * we are rendering. - * - * @exception JspException if no TreeControl instance can be found + * + * @exception JspException + * if no TreeControl instance can be found */ - protected TreeControl getTreeControl() throws JspException { + protected TreeControl getTreeControl() throws JspException + { Object treeControl = null; - - PortletRequest renderRequest = (PortletRequest) pageContext.findAttribute("javax.portlet.request"); - if(PORTLET_REQUEST.equals(scope)) + + PortletRequest renderRequest = (PortletRequest) pageContext + .findAttribute("javax.portlet.request"); + if (PORTLET_REQUEST.equals(scope)) { - + treeControl = renderRequest.getAttribute(tree); } - else if(PORTLET_SESSION.equals(scope)) + else if (PORTLET_SESSION.equals(scope)) { treeControl = renderRequest.getPortletSession().getAttribute(tree); } - + if (treeControl == null) { treeControl = super.getTreeControl(); } - - return (TreeControl)treeControl; + + return (TreeControl) treeControl; } - + /** * Render the specified node, as controlled by the specified parameters. - * - * @param out The <code>JspWriter</code> to which we are writing - * @param node The <code>TreeControlNode</code> we are currently - * rendering - * @param level The indentation level of this node in the tree - * @param width Total displayable width of the tree - * @param last Is this the last node in a list? - * - * @exception IOException if an input/output error occurs + * + * @param out + * The <code>JspWriter</code> to which we are writing + * @param node + * The <code>TreeControlNode</code> we are currently rendering + * @param level + * The indentation level of this node in the tree + * @param width + * Total displayable width of the tree + * @param last + * Is this the last node in a list? + * + * @exception IOException + * if an input/output error occurs */ - protected void render(JspWriter out, TreeControlNode node, - int level, int width, boolean last) - throws IOException { + protected void render(JspWriter out, TreeControlNode node, int level, + int width, boolean last) throws IOException + { try { - HttpServletResponse response = - (HttpServletResponse) pageContext.getResponse(); - - RenderResponse renderResponse = (RenderResponse)pageContext.getRequest().getAttribute("javax.portlet.response"); + HttpServletResponse response = (HttpServletResponse) pageContext + .getResponse(); - // if the node is root node and the label value is - // null, then do not render root node in the tree. - - if ("ROOT-NODE".equalsIgnoreCase(node.getName()) && - (node.getLabel() == null)) { - // Render the children of this node - TreeControlNode children[] = node.findChildren(); - int lastIndex = children.length - 1; - int newLevel = level + 1; - for (int i = 0; i < children.length; i++) { - render(out, children[i], newLevel, width, i == lastIndex); + RenderResponse renderResponse = (RenderResponse) pageContext + .getRequest().getAttribute("javax.portlet.response"); + + // if the node is root node and the label value is + // null, then do not render root node in the tree. + + if ("ROOT-NODE".equalsIgnoreCase(node.getName()) + && (node.getLabel() == null)) + { + // Render the children of this node + TreeControlNode children[] = node.findChildren(); + int lastIndex = children.length - 1; + int newLevel = level + 1; + for (int i = 0; i < children.length; i++) + { + render(out, children[i], newLevel, width, i == lastIndex); + } + return; } - return; - } - - // Render the beginning of this node - out.println(" <tr valign=\"middle\">"); - out.print("<td><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tr valign=\"middle\">"); - // Create the appropriate number of indents - for (int i = 0; i < level; i++) { - int levels = level - i; - TreeControlNode parent = node; - for (int j = 1; j <= levels; j++) - parent = parent.getParent(); - if (parent.isLast()) - out.print(" <td> </td>"); - else { - out.print(" <td><img src=\""); - out.print(images); - out.print("/"); - out.print(IMAGE_LINE_VERTICAL); - out.print("\" alt=\"\" border=\"0\"></td>"); + // Render the beginning of this node + out.println(" <tr valign=\"middle\">"); + out + .print("<td><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tr valign=\"middle\">"); + + // Create the appropriate number of indents + for (int i = 0; i < level; i++) + { + int levels = level - i; + TreeControlNode parent = node; + for (int j = 1; j <= levels; j++) + parent = parent.getParent(); + if (parent.isLast()) + out.print(" <td> </td>"); + else + { + out.print(" <td><img src=\""); + out.print(images); + out.print("/"); + out.print(IMAGE_LINE_VERTICAL); + out.print("\" alt=\"\" border=\"0\"></td>"); + } + out.println(); } - out.println(); - } - // Render the tree state image for this node + // Render the tree state image for this node - PortletURL treeActionUrl = renderResponse.createActionURL(); - treeActionUrl.setParameter("node", node.getName()); - String treeAction = treeActionUrl.toString(); - out.print(" <td>"); - - - //add an anchor so that we can return to this node - out.print("<a name=\""); - out.print(node.getName()); - out.print("\">"); - - if ((action != null) && !node.isLeaf()) { - out.print("<a href=\""); - out.print(response.encodeURL(treeAction)); + PortletURL treeActionUrl = renderResponse.createActionURL(); + treeActionUrl.setParameter("node", node.getName()); + String treeAction = treeActionUrl.toString(); + out.print(" <td>"); + + // add an anchor so that we can return to this node + out.print("<a name=\""); + out.print(node.getName()); out.print("\">"); - } - out.print("<img src=\""); - out.print(images); - out.print("/"); - if (node.isLeaf()) { - if (node.isLast()) - out.print(IMAGE_LINE_LAST); - else - out.print(IMAGE_LINE_MIDDLE); - out.print("\" alt=\""); - } else if (node.isExpanded()) { - if (node.isLast()) - out.print(IMAGE_HANDLE_DOWN_LAST); - else - out.print(IMAGE_HANDLE_DOWN_MIDDLE); - out.print("\" alt=\"close node"); - } else { - if (node.isLast()) - out.print(IMAGE_HANDLE_RIGHT_LAST); - else - out.print(IMAGE_HANDLE_RIGHT_MIDDLE); - out.print("\" alt=\"expand node"); - } - out.print("\" border=\"0\">"); - if ((action != null) && !node.isLeaf()) - out.print("</a>"); - out.println("</td>"); - - - // Calculate the hyperlink for this node (if any) - String hyperlink = null; - String nodeAction = node.getAction(); - if(nodeAction == null && node.isExpandWhenClicked()) - { - hyperlink = treeAction; - } - if (nodeAction != null) - { - if(node.getAction().equals("portlet_url")) + if ((action != null) && !node.isLeaf()) { - PortletURL actionUrl = renderResponse.createActionURL(); - actionUrl.setParameter("select_node", node.getName()); - hyperlink = ((HttpServletResponse) pageContext.getResponse()).encodeURL(actionUrl.toString()); + out.print("<a href=\""); + out.print(response.encodeURL(treeAction)); + out.print("\">"); } + out.print("<img src=\""); + out.print(images); + out.print("/"); + if (node.isLeaf()) + { + if (node.isLast()) + out.print(IMAGE_LINE_LAST); + else + out.print(IMAGE_LINE_MIDDLE); + out.print("\" alt=\""); + } + else if (node.isExpanded()) + { + if (node.isLast()) + out.print(IMAGE_HANDLE_DOWN_LAST); + else + out.print(IMAGE_HANDLE_DOWN_MIDDLE); + out.print("\" alt=\"close node"); + } else { - hyperlink = ((HttpServletResponse) pageContext.getResponse()). - encodeURL(node.getAction()); + if (node.isLast()) + out.print(IMAGE_HANDLE_RIGHT_LAST); + else + out.print(IMAGE_HANDLE_RIGHT_MIDDLE); + out.print("\" alt=\"expand node"); } - } - + out.print("\" border=\"0\">"); + if ((action != null) && !node.isLeaf()) out.print("</a>"); + out.println("</td>"); - // Render the icon for this node (if any) - out.print(" <td "); - - if(node.getLabel() != null) - { - //make sure text does not wrap - out.print(" style=\""); - out.print("white-space:nowrap; vertical-align:middle;"); - out.print("\""); - } - - out.print(">"); - if (node.getIcon() != null) { - if (hyperlink != null) { - out.print("<a href=\""); - out.print(hyperlink); - out.print("\""); - String target = node.getTarget(); - if(target != null) { - out.print(" target=\""); - out.print(target); - out.print("\""); + // Calculate the hyperlink for this node (if any) + String hyperlink = null; + String nodeAction = node.getAction(); + if (nodeAction == null && node.isExpandWhenClicked()) + { + hyperlink = treeAction; + } + if (nodeAction != null) + { + if (node.getAction().equals("portlet_url")) + { + PortletURL actionUrl = renderResponse.createActionURL(); + actionUrl.setParameter("select_node", node.getName()); + hyperlink = ((HttpServletResponse) pageContext + .getResponse()).encodeURL(actionUrl.toString()); } - /* Invalid, not used, and not usefull - // to refresh the tree in the same 'self' frame - out.print(" onclick=\""); - out.print("self.location.href='" + updateTreeAction + "'"); - out.print("\""); - */ - out.print(">"); + else + { + hyperlink = ((HttpServletResponse) pageContext + .getResponse()).encodeURL(node.getAction()); + } } - out.print("<img src=\""); - out.print(images); - out.print("/"); - out.print(node.getIcon()); - out.print("\" alt=\""); - out.print("\" border=\"0\">"); - if (hyperlink != null) - out.print("</a>"); - } - // Render the label for this node (if any) + // Render the icon for this node (if any) + out.print(" <td "); - if (node.getLabel() != null) { - String labelStyle = node.getCSSClass(); - if (node.isSelected() && (styleSelected != null)) - labelStyle = styleSelected; - else if (!node.isSelected() && (styleUnselected != null)) - labelStyle = styleUnselected; - if (hyperlink != null) { - // Note the leading space so that the text has some space - // between it and any preceding images - out.print(" <a href=\""); - out.print(hyperlink); + if (node.getLabel() != null) + { + // make sure text does not wrap + out.print(" style=\""); + out.print("white-space:nowrap; vertical-align:middle;"); out.print("\""); - String target = node.getTarget(); - if(target != null) { - out.print(" target=\""); - out.print(target); + } + + out.print(">"); + if (node.getIcon() != null) + { + if (hyperlink != null) + { + out.print("<a href=\""); + out.print(hyperlink); out.print("\""); + String target = node.getTarget(); + if (target != null) + { + out.print(" target=\""); + out.print(target); + out.print("\""); + } + /* + * Invalid, not used, and not usefull // to refresh the tree + * in the same 'self' frame out.print(" onclick=\""); + * out.print("self.location.href='" + updateTreeAction + + * "'"); out.print("\""); + */ + out.print(">"); } - if (labelStyle != null) { - out.print(" class=\""); - out.print(labelStyle); + out.print("<img src=\""); + out.print(images); + out.print("/"); + out.print(node.getIcon()); + out.print("\" alt=\""); + out.print("\" border=\"0\">"); + if (hyperlink != null) out.print("</a>"); + } + + // Render the label for this node (if any) + + if (node.getLabel() != null) + { + String labelStyle = node.getCSSClass(); + if (node.isSelected() && (styleSelected != null)) + labelStyle = styleSelected; + else if (!node.isSelected() && (styleUnselected != null)) + labelStyle = styleUnselected; + if (hyperlink != null) + { + // Note the leading space so that the text has some space + // between it and any preceding images + out.print(" <a href=\""); + out.print(hyperlink); out.print("\""); + String target = node.getTarget(); + if (target != null) + { + out.print(" target=\""); + out.print(target); + out.print("\""); + } + if (labelStyle != null) + { + out.print(" class=\""); + out.print(labelStyle); + out.print("\""); + } + + if (node.getTitle() != null) + { + out.print(" title=\""); + out.print(node.getTitle()); + out.print("\""); + } + + /* + * Invalid, not used, and not usefull // to refresh the tree + * in the same 'self' frame out.print(" onclick=\""); + * out.print("self.location.href='" + updateTreeAction + + * "'"); out.print("\""); + */ + out.print(">"); } - - if(node.getTitle() != null) + else if (labelStyle != null) { - out.print(" title=\""); - out.print(node.getTitle()); - out.print("\""); + out.print("<span class=\""); + out.print(labelStyle); + out.print("\">"); } - - /* Invalid, not used, and not usefull - // to refresh the tree in the same 'self' frame - out.print(" onclick=\""); - out.print("self.location.href='" + updateTreeAction + "'"); - out.print("\""); - */ - out.print(">"); - } else if (labelStyle != null) { - out.print("<span class=\""); - out.print(labelStyle); - out.print("\">"); + out.print(node.getLabel()); + if (hyperlink != null) + out.print("</a>"); + else if (labelStyle != null) out.print("</span>"); } - out.print(node.getLabel()); - if (hyperlink != null) - out.print("</a>"); - else if (labelStyle != null) - out.print("</span>"); - } - out.println("</td>"); - - + out.println("</td>"); - // Render the end of this node - out.println(" </tr>"); - out.println("</table></td></tr>"); - - // Render the children of this node - if (node.isExpanded()) { - TreeControlNode children[] = node.findChildren(); - int lastIndex = children.length - 1; - int newLevel = level + 1; - for (int i = 0; i < children.length; i++) { - render(out, children[i], newLevel, width, i == lastIndex); + // Render the end of this node + out.println(" </tr>"); + out.println("</table></td></tr>"); + + // Render the children of this node + if (node.isExpanded()) + { + TreeControlNode children[] = node.findChildren(); + int lastIndex = children.length - 1; + int newLevel = level + 1; + for (int i = 0; i < children.length; i++) + { + render(out, children[i], newLevel, width, i == lastIndex); + } } } - } - catch(Exception e) - { - out.print(e.getLocalizedMessage()); - } + catch (Exception e) + { + out.print(e.getLocalizedMessage()); + } } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/webapp/admin/TreeControl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/webapp/admin/TreeControl.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/webapp/admin/TreeControl.java 2008-05-16 01:54:54 UTC (rev 940) @@ -15,99 +15,93 @@ * limitations under the License. */ - package org.apache.webapp.admin; - import java.io.Serializable; import java.util.HashMap; - /** - * <p>The overall data structure representing a <em>tree control</em> - * that can be rendered by the <code>TreeControlTag</code> custom tag. - * Each node of the tree is represented by an instance of - * <code>TreeControlNode</code>.</p> - * + * <p> + * The overall data structure representing a <em>tree control</em> that can be + * rendered by the <code>TreeControlTag</code> custom tag. Each node of the + * tree is represented by an instance of <code>TreeControlNode</code>. + * </p> + * * @author Jazmin Jonson * @author Craig R. McClanahan - * @version $Revision: 516448 $ $Date: 2007-03-10 01:25:47 +0900 (ÅÚ, 10 3·î 2007) $ + * @version $Revision: 516448 $ $Date: 2007-03-10 01:25:47 +0900 (ÅÚ, 10 3·î 2007) $ */ -public class TreeControl implements Serializable +public class TreeControl implements Serializable { - private static final long serialVersionUID = 1; + private static final long serialVersionUID = 1; // ----------------------------------------------------------- Constructors - /** * Construct a new instance with no predefined root node. */ - public TreeControl() { + public TreeControl() + { super(); setRoot(null); } - /** * Construct a new instance with the specified root node. - * - * @param root The new root node + * + * @param root + * The new root node */ - public TreeControl(TreeControlNode root) { + public TreeControl(TreeControlNode root) + { super(); setRoot(root); } - // ----------------------------------------------------- Instance Variables - /** * The collection of nodes that represent this tree, keyed by name. */ protected HashMap registry = new HashMap(); - /** * The most recently selected node. */ protected TreeControlNode selected = null; - // ------------------------------------------------------------- Properties - /** * The root node of the entire tree. */ protected TreeControlNode root = null; - public TreeControlNode getRoot() { + public TreeControlNode getRoot() + { return (this.root); } - protected void setRoot(TreeControlNode root) { - if (this.root != null) - removeNode(this.root); - if (root != null) - addNode(root); + protected void setRoot(TreeControlNode root) + { + if (this.root != null) removeNode(this.root); + if (root != null) addNode(root); root.setLast(true); this.root = root; } - /** - * The current displayable "width" of this tree (that is, the maximum - * depth of the visible part of the tree). + * The current displayable "width" of this tree (that is, the maximum depth + * of the visible part of the tree). */ - public int getWidth() { + public int getWidth() + { if (root == null) return (0); @@ -116,64 +110,67 @@ } - // --------------------------------------------------------- Public Methods - /** - * Find and return the <code>TreeControlNode</code> for the specified - * node name, if it exists; otherwise, return <code>null</code>. - * - * @param name Name of the <code>TreeControlNode</code> to be returned + * Find and return the <code>TreeControlNode</code> for the specified node + * name, if it exists; otherwise, return <code>null</code>. + * + * @param name + * Name of the <code>TreeControlNode</code> to be returned */ - public TreeControlNode findNode(String name) { + public TreeControlNode findNode(String name) + { - synchronized (registry) { + synchronized (registry) + { return ((TreeControlNode) registry.get(name)); } } - /** * Mark the specified node as the one-and-only currently selected one, * deselecting any previous node that was so marked. - * - * @param node Name of the node to mark as selected, or <code>null</code> - * if there should be no currently selected node + * + * @param node + * Name of the node to mark as selected, or <code>null</code> + * if there should be no currently selected node */ - public void selectNode(String name) { + public void selectNode(String name) + { - if (selected != null) { + if (selected != null) + { selected.setSelected(false); selected = null; } selected = findNode(name); - if (selected != null) - selected.setSelected(true); + if (selected != null) selected.setSelected(true); } - // -------------------------------------------------------- Package Methods - /** * Register the specified node in our registry of the complete tree. - * - * @param node The <code>TreeControlNode</code> to be registered - * - * @exception IllegalArgumentException if the name of this node - * is not unique + * + * @param node + * The <code>TreeControlNode</code> to be registered + * + * @exception IllegalArgumentException + * if the name of this node is not unique */ - void addNode(TreeControlNode node) throws IllegalArgumentException { + void addNode(TreeControlNode node) throws IllegalArgumentException + { - synchronized (registry) { + synchronized (registry) + { String name = node.getName(); if (registry.containsKey(name)) { -// throw new IllegalArgumentException("Name '" + name + -// "' is not unique"); + // throw new IllegalArgumentException("Name '" + name + + // "' is not unique"); } node.setTree(this); registry.put(name, node); @@ -181,49 +178,52 @@ } - /** * Calculate the width of the subtree below the specified node. - * - * @param node The node for which to calculate the width + * + * @param node + * The node for which to calculate the width */ - int getWidth(TreeControlNode node) { + int getWidth(TreeControlNode node) + { int width = node.getWidth(); - if (!node.isExpanded()) - return (width); + if (!node.isExpanded()) return (width); TreeControlNode children[] = node.findChildren(); - for (int i = 0; i < children.length; i++) { + for (int i = 0; i < children.length; i++) + { int current = getWidth(children[i]); - if (current > width) - width = current; + if (current > width) width = current; } return (width); } - /** - * Deregister the specified node, as well as all child nodes of this - * node, from our registry of the complete tree. If this node is not - * present, no action is taken. - * - * @param node The <code>TreeControlNode</code> to be deregistered + * Deregister the specified node, as well as all child nodes of this node, + * from our registry of the complete tree. If this node is not present, no + * action is taken. + * + * @param node + * The <code>TreeControlNode</code> to be deregistered */ - public void removeNode(TreeControlNode node) + public void removeNode(TreeControlNode node) { - synchronized (registry) { + synchronized (registry) + { TreeControlNode children[] = node.findChildren(); for (int i = 0; i < children.length; i++) removeNode(children[i]); TreeControlNode parent = node.getParent(); - if (parent != null) { + if (parent != null) + { parent.removeChild(node); } node.setParent(null); node.setTree(null); - if (node == this.root) { + if (node == this.root) + { this.root = null; } registry.remove(node.getName()); @@ -231,5 +231,4 @@ } - } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/webapp/admin/TreeControlNode.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/webapp/admin/TreeControlNode.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/webapp/admin/TreeControlNode.java 2008-05-16 01:54:54 UTC (rev 940) @@ -15,110 +15,132 @@ * limitations under the License. */ - package org.apache.webapp.admin; - import java.io.Serializable; import java.util.ArrayList; - /** - * <p>An individual node of a tree control represented by an instance of + * <p> + * An individual node of a tree control represented by an instance of * <code>TreeControl</code>, and rendered by an instance of - * <code>TreeControlTag</code>.</p> - * + * <code>TreeControlTag</code>. + * </p> + * * @author Jazmin Jonson * @author Craig R. McClanahan - * @version $Revision: 516448 $ $Date: 2007-03-10 01:25:47 +0900 (ÅÚ, 10 3·î 2007) $ + * @version $Revision: 516448 $ $Date: 2007-03-10 01:25:47 +0900 (ÅÚ, 10 3·î 2007) $ */ -public class TreeControlNode implements Serializable +public class TreeControlNode implements Serializable { - private static final long serialVersionUID = 1; + private static final long serialVersionUID = 1; // ----------------------------------------------------------- Constructors - /** + /** * Construct a new TreeControlNode with the specified parameters. - * - * @param name Internal name of this node (must be unique within - * the entire tree) - * @param icon Pathname of the image file for the icon to be displayed - * when this node is visible, relative to the image directory - * for our images - * @param label The label that will be displayed to the user if - * this node is visible - * @param action The hyperlink to be selected if the user - * selects this node, or <code>null</code> if this node's label should - * not be a hyperlink - * @param target The window target in which the <code>action</code> - * hyperlink's results will be displayed, or <code>null</code> for - * the current window - * @param expanded Should this node be expanded? - * @param domain Identifier for the kind of node. + * + * @param name + * Internal name of this node (must be unique within the entire + * tree) + * @param icon + * Pathname of the image file for the icon to be displayed when + * this node is visible, relative to the image directory for our + * images + * @param label + * The label that will be displayed to the user if this node is + * visible + * @param action + * The hyperlink to be selected if the user selects this node, or + * <code>null</code> if this node's label should not be a + * hyperlink + * @param target + * The window target in which the <code>action</code> + * hyperlink's results will be displayed, or <code>null</code> + * for the current window + * @param expanded + * Should this node be expanded? + * @param domain + * Identifier for the kind of node. */ - public TreeControlNode(String name, - String icon, String label, - String action, String target, - boolean expanded, String domain) { - this(name, icon, label, action, target, expanded, domain, null, false); - } - - /** + public TreeControlNode(String name, String icon, String label, + String action, String target, boolean expanded, String domain) + { + this(name, icon, label, action, target, expanded, domain, null, false); + } + + /** * Construct a new TreeControlNode with the specified parameters. - * - * @param name Internal name of this node (must be unique within - * the entire tree) - * @param icon Pathname of the image file for the icon to be displayed - * when this node is visible, relative to the image directory - * for our images - * @param label The label that will be displayed to the user if - * this node is visible - * @param action The hyperlink to be selected if the user - * selects this node, or <code>null</code> if this node's label should - * not be a hyperlink - * @param target The window target in which the <code>action</code> - * hyperlink's results will be displayed, or <code>null</code> for - * the current window - * @param expanded Should this node be expanded? - * @param domain Identifier for the kind of node. - * @param CSSClass The css class to apply to the node + * + * @param name + * Internal name of this node (must be unique within the entire + * tree) + * @param icon + * Pathname of the image file for the icon to be displayed when + * this node is visible, relative to the image directory for our + * images + * @param label + * The label that will be displayed to the user if this node is + * visible + * @param action + * The hyperlink to be selected if the user selects this node, or + * <code>null</code> if this node's label should not be a + * hyperlink + * @param target + * The window target in which the <code>action</code> + * hyperlink's results will be displayed, or <code>null</code> + * for the current window + * @param expanded + * Should this node be expanded? + * @param domain + * Identifier for the kind of node. + * @param CSSClass + * The css class to apply to the node */ - public TreeControlNode(String name, - String icon, String label, - String action, String target, - boolean expanded, String domain, String CSSClass) { - this(name, icon, label, action, target, expanded, domain, CSSClass, false); - } + public TreeControlNode(String name, String icon, String label, + String action, String target, boolean expanded, String domain, + String CSSClass) + { + this(name, icon, label, action, target, expanded, domain, CSSClass, + false); + } /** * Construct a new TreeControlNode with the specified parameters. - * - * @param name Internal name of this node (must be unique within - * the entire tree) - * @param icon Pathname of the image file for the icon to be displayed - * when this node is visible, relative to the image directory - * for our images - * @param label The label that will be displayed to the user if - * this node is visible - * @param action The hyperlink to be selected if the user - * selects this node, or <code>null</code> if this node's label should - * not be a hyperlink - * @param target The window target in which the <code>action</code> - * hyperlink's results will be displayed, or <code>null</code> for - * the current window - * @param expanded Should this node be expanded? - * @param domain Identifier for the kind of node. - * @param CSSClass The css class to apply to the node - * @param lazy Is this node's children lazy loaded? + * + * @param name + * Internal name of this node (must be unique within the entire + * tree) + * @param icon + * Pathname of the image file for the icon to be displayed when + * this node is visible, relative to the image directory for our + * images + * @param label + * The label that will be displayed to the user if this node is + * visible + * @param action + * The hyperlink to be selected if the user selects this node, or + * <code>null</code> if this node's label should not be a + * hyperlink + * @param target + * The window target in which the <code>action</code> + * hyperlink's results will be displayed, or <code>null</code> + * for the current window + * @param expanded + * Should this node be expanded? + * @param domain + * Identifier for the kind of node. + * @param CSSClass + * The css class to apply to the node + * @param lazy + * Is this node's children lazy loaded? */ - public TreeControlNode(String name, - String icon, String label, - String action, String target, - boolean expanded, String domain, String CSSClass, - boolean lazy) { + public TreeControlNode(String name, String icon, String label, + String action, String target, boolean expanded, String domain, + String CSSClass, boolean lazy) + { super(); this.name = name; @@ -133,27 +155,24 @@ this.loaded = false; } - // ----------------------------------------------------- Instance Variables - /** * The set of child <code>TreeControlNodes</code> for this node, in the * order that they should be displayed. */ protected ArrayList children = new ArrayList(); - // ------------------------------------------------------------- Properties - /** - * The hyperlink to which control will be directed if this node - * is selected by the user. + * The hyperlink to which control will be directed if this node is selected + * by the user. */ protected String action = null; - public String getAction() { + public String getAction() + { return (this.action); } @@ -162,7 +181,8 @@ */ protected String domain = null; - public String getDomain() { + public String getDomain() + { return (this.domain); } @@ -171,44 +191,47 @@ */ protected boolean expanded = false; - public boolean isExpanded() { + public boolean isExpanded() + { return (this.expanded); } - public void setExpanded(boolean expanded) { + public void setExpanded(boolean expanded) + { this.expanded = expanded; } - /** * The pathname to the icon file displayed when this node is visible, * relative to the image directory for our images. */ protected String icon = null; - public String getIcon() { + public String getIcon() + { return (this.icon); } - /** * The label that will be displayed when this node is visible. */ protected String label = null; - public String getLabel() { + public String getLabel() + { return (this.label); } - + /** * The label that will be displayed when this node is visible. */ protected String title = null; - public String getTitle() { + public String getTitle() + { return (this.title); } - + public void setTitle(String title) { this.title = title; @@ -218,84 +241,89 @@ { this.label = label; } - /** * Is this the last node in the set of children for our parent node? */ protected boolean last = false; - public boolean isLast() { + public boolean isLast() + { return (this.last); } - void setLast(boolean last) { + void setLast(boolean last) + { this.last = last; } - + protected boolean lazy = false; - - public boolean isLazy() { - return (this.lazy); + + public boolean isLazy() + { + return (this.lazy); } - /** * Is this a "leaf" node (i.e. one with no children)? */ protected boolean leaf = true; - - public boolean isLeaf() { - if(lazy) - { - return leaf; - } - else - { - synchronized (children) { - return (children.size() < 1); - } - } + + public boolean isLeaf() + { + if (lazy) + { + return leaf; + } + else + { + synchronized (children) + { + return (children.size() < 1); + } + } } - + public void setLeaf(boolean leaf) { - this.leaf = leaf; + this.leaf = leaf; } - + protected boolean loaded = false; - - public boolean isLoaded() { - return (this.loaded); + + public boolean isLoaded() + { + return (this.loaded); } - + public void setLoaded(boolean loaded) { - this.loaded = loaded; + this.loaded = loaded; } - /** * The unique (within the entire tree) name of this node. */ protected String name = null; - public String getName() { + public String getName() + { return (this.name); } - /** - * The parent node of this node, or <code>null</code> if this - * is the root node. + * The parent node of this node, or <code>null</code> if this is the root + * node. */ protected TreeControlNode parent = null; - public TreeControlNode getParent() { + public TreeControlNode getParent() + { return (this.parent); } - void setParent(TreeControlNode parent) { + void setParent(TreeControlNode parent) + { this.parent = parent; if (parent == null) width = 1; @@ -303,106 +331,111 @@ width = parent.getWidth() + 1; } - /** * Is this node currently selected? */ protected boolean selected = false; - public boolean isSelected() { + public boolean isSelected() + { return (this.selected); } - public void setSelected(boolean selected) { + public void setSelected(boolean selected) + { this.selected = selected; } - /** - * The window target for the hyperlink identified by the - * <code>action</code> property, if this node is selected - * by the user. + * The window target for the hyperlink identified by the <code>action</code> + * property, if this node is selected by the user. */ protected String target = null; - public String getTarget() { + public String getTarget() + { return (this.target); } - /** - * The <code>TreeControl</code> instance representing the - * entire tree. + * The <code>TreeControl</code> instance representing the entire tree. */ protected TreeControl tree = null; - public TreeControl getTree() { + public TreeControl getTree() + { return (this.tree); } - void setTree(TreeControl tree) { + void setTree(TreeControl tree) + { this.tree = tree; } - /** - * The display width necessary to display this item (if it is visible). - * If this item is not visible, the calculated width will be that of our - * most immediately visible parent. + * The display width necessary to display this item (if it is visible). If + * this item is not visible, the calculated width will be that of our most + * immediately visible parent. */ protected int width = 0; - public int getWidth() { + public int getWidth() + { return (this.width); } - + protected String CSSClass; - + /** - * @return Returns the cSSClass. - */ - public String getCSSClass() { - return CSSClass; - } - /** - * @param class1 The cSSClass to set. - */ - public void setCSSClass(String CSSClass) { - this.CSSClass = CSSClass; - } - + * @return Returns the cSSClass. + */ + public String getCSSClass() + { + return CSSClass; + } + + /** + * @param class1 + * The cSSClass to set. + */ + public void setCSSClass(String CSSClass) + { + this.CSSClass = CSSClass; + } + protected boolean expandWhenClicked = false; - + public boolean isExpandWhenClicked() { return expandWhenClicked; } - + public void setExpandWhenClicked(boolean expandWhenClicked) { this.expandWhenClicked = expandWhenClicked; } - // --------------------------------------------------------- Public Methods - /** * Add a new child node to the end of the list. - * - * @param child The new child node - * - * @exception IllegalArgumentException if the name of the new child - * node is not unique + * + * @param child + * The new child node + * + * @exception IllegalArgumentException + * if the name of the new child node is not unique */ - public void addChild(TreeControlNode child) - throws IllegalArgumentException { + public void addChild(TreeControlNode child) throws IllegalArgumentException + { tree.addNode(child); child.setParent(this); - synchronized (children) { + synchronized (children) + { int n = children.size(); - if (n > 0) { + if (n > 0) + { TreeControlNode node = (TreeControlNode) children.get(n - 1); node.setLast(false); } @@ -412,66 +445,71 @@ } - /** * Add a new child node at the specified position in the child list. - * - * @param offset Zero-relative offset at which the new node - * should be inserted - * @param child The new child node - * - * @exception IllegalArgumentException if the name of the new child - * node is not unique + * + * @param offset + * Zero-relative offset at which the new node should be inserted + * @param child + * The new child node + * + * @exception IllegalArgumentException + * if the name of the new child node is not unique */ public void addChild(int offset, TreeControlNode child) - throws IllegalArgumentException { + throws IllegalArgumentException + { tree.addNode(child); child.setParent(this); - synchronized (children) { + synchronized (children) + { children.add(offset, child); } } - /** * Return the set of child nodes for this node. */ - public TreeControlNode[] findChildren() { + public TreeControlNode[] findChildren() + { - synchronized (children) { + synchronized (children) + { TreeControlNode results[] = new TreeControlNode[children.size()]; return ((TreeControlNode[]) children.toArray(results)); } } - /** * Remove this node from the tree. */ - public void remove() { + public void remove() + { - if (tree != null) { + if (tree != null) + { tree.removeNode(this); } } - /** - * Remove the child node (and all children of that child) at the - * specified position in the child list. - * - * @param offset Zero-relative offset at which the existing - * node should be removed + * Remove the child node (and all children of that child) at the specified + * position in the child list. + * + * @param offset + * Zero-relative offset at which the existing node should be + * removed */ - public void removeChild(int offset) { + public void removeChild(int offset) + { - synchronized (children) { - TreeControlNode child = - (TreeControlNode) children.get(offset); + synchronized (children) + { + TreeControlNode child = (TreeControlNode) children.get(offset); tree.removeNode(child); child.setParent(null); children.remove(offset); @@ -479,25 +517,26 @@ } - // -------------------------------------------------------- Package Methods - /** - * Remove the specified child node. It is assumed that all of the - * children of this child node have already been removed. - * - * @param child Child node to be removed + * Remove the specified child node. It is assumed that all of the children + * of this child node have already been removed. + * + * @param child + * Child node to be removed */ - void removeChild(TreeControlNode child) { + void removeChild(TreeControlNode child) + { - if (child == null) { - return; - } - synchronized (children) { + if (child == null) { return; } + synchronized (children) + { int n = children.size(); - for (int i = 0; i < n; i++) { - if (child == (TreeControlNode) children.get(i)) { + for (int i = 0; i < n; i++) + { + if (child == (TreeControlNode) children.get(i)) + { children.remove(i); return; } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/webapp/admin/TreeControlTag.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/webapp/admin/TreeControlTag.java 2008-05-16 01:52:50 UTC (rev 939) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/taglibs/treecontrol/src/java/org/apache/webapp/admin/TreeControlTag.java 2008-05-16 01:54:54 UTC (rev 940) @@ -15,209 +15,218 @@ * limitations under the License. */ - package org.apache.webapp.admin; - import java.io.IOException; import java.net.URLEncoder; + import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.TagSupport; - /** - * <p>JSP custom tag that renders a tree control represented by the - * <code>TreeControl</code> and <code>TreeControlNode</code> classes. - * This tag has the following user-settable attributes:</p> + * <p> + * JSP custom tag that renders a tree control represented by the + * <code>TreeControl</code> and <code>TreeControlNode</code> classes. This + * tag has the following user-settable attributes: + * </p> * <ul> * <li><strong>action</strong> - Hyperlink to which expand/contract actions - * should be sent, with a string "<code>${node}</code> marking where - * the node name of the affected node should be included.</li> + * should be sent, with a string "<code>${node}</code> marking where the node + * name of the affected node should be included.</li> * <li><strong>images</strong> - Name of the directory containing the images - * for our icons, relative to the page including this tag. If not - * specified, defaults to "images".</li> + * for our icons, relative to the page including this tag. If not specified, + * defaults to "images".</li> * <li><strong>scope</strong> - Attribute scope in which the <code>tree</code> - * attribute is to be found (page, request, session, application). If - * not specified, the attribute is searched for in all scopes.</li> + * attribute is to be found (page, request, session, application). If not + * specified, the attribute is searched for in all scopes.</li> * <li><strong>style</strong> - CSS style <code>class</code> to be applied - * to be applied to the entire rendered output of the tree control. - * If not specified, no style class is applied.</li> + * to be applied to the entire rendered output of the tree control. If not + * specified, no style class is applied.</li> * <li><strong>styleSelected</strong> - CSS style <code>class</code> to be - * applied to the text of any element that is currently selected. If not - * specified, no additional style class is applied.</li> + * applied to the text of any element that is currently selected. If not + * specified, no additional style class is applied.</li> * <li><strong>styleUnselected</strong> - CSS style <code>class</code> to be - * applied to the text of any element that is not currently selected. - * If not specified, no additional style class is applied.</li> + * applied to the text of any element that is not currently selected. If not + * specified, no additional style class is applied.</li> * <li><strong>tree</strong> - Attribute name under which the - * <code>TreeControl</code> bean of the tree we are rendering - * is stored, in the scope specified by the <code>scope</code> - * attribute. This attribute is required.</li> + * <code>TreeControl</code> bean of the tree we are rendering is stored, in + * the scope specified by the <code>scope</code> attribute. This attribute is + * required.</li> * </ul> - * + * * <strong>FIXME</strong> - Internationalize the exception messages! - * + * * @author Craig R. McClanahan - * @version $Revision: 516448 $ $Date: 2007-03-10 01:25:47 +0900 (ÅÚ, 10 3·î 2007) $ + * @version $Revision: 516448 $ $Date: 2007-03-10 01:25:47 +0900 (ÅÚ, 10 3·î 2007) $ */ -public class TreeControlTag extends TagSupport +public class TreeControlTag extends TagSupport { - private static final long serialVersionUID = 1; + private static final long serialVersionUID = 1; /** * The default directory name for icon images. */ static final String DEFAULT_IMAGES = "images"; - /** * The names of tree state images that we need. */ - static final String IMAGE_HANDLE_DOWN_LAST = "handledownlast.gif"; - static final String IMAGE_HANDLE_DOWN_MIDDLE = "handledownmiddle.gif"; - static final String IMAGE_HANDLE_RIGHT_LAST = "handlerightlast.gif"; + static final String IMAGE_HANDLE_DOWN_LAST = "handledownlast.gif"; + + static final String IMAGE_HANDLE_DOWN_MIDDLE = "handledownmiddle.gif"; + + static final String IMAGE_HANDLE_RIGHT_LAST = "handlerightlast.gif"; + static final String IMAGE_HANDLE_RIGHT_MIDDLE = "handlerightmiddle.gif"; - static final String IMAGE_LINE_LAST = "linelastnode.gif"; - static final String IMAGE_LINE_MIDDLE = "linemiddlenode.gif"; - static final String IMAGE_LINE_VERTICAL = "linevertical.gif"; + static final String IMAGE_LINE_LAST = "linelastnode.gif"; + static final String IMAGE_LINE_MIDDLE = "linemiddlenode.gif"; + + static final String IMAGE_LINE_VERTICAL = "linevertical.gif"; + // ------------------------------------------------------------- Properties - /** - * The hyperlink to be used for submitting requests to expand and - * contract tree nodes. The placeholder "<code>${name}</code>" will - * be replaced by the <code>name</code> property of the current - * tree node. + * The hyperlink to be used for submitting requests to expand and contract + * tree nodes. The placeholder "<code>${name}</code>" will be replaced + * by the <code>name</code> property of the current tree node. */ protected String action = null; - public String getAction() { + public String getAction() + { return (this.action); } - public void setAction(String action) { + public void setAction(String action) + { this.action = action; } - /** - * The name of the directory containing the images for our icons, - * relative to the page including this tag. + * The name of the directory containing the images for our icons, relative + * to the page including this tag. */ protected String images = DEFAULT_IMAGES; - public String getImages() { + public String getImages() + { return (this.images); } - public void setImages(String images) { + public void setImages(String images) + { this.images = images; } - /** * The name of the scope in which to search for the <code>tree</code> - * attribute. Must be "page", "request", "session", or "application" - * (or <code>null</code> for an ascending-visibility search). + * attribute. Must be "page", "request", "session", or "application" (or + * <code>null</code> for an ascending-visibility search). */ protected String scope = null; - public String getScope() { + public String getScope() + { return (this.scope); } - public void setScope(String scope) { - if (!"page".equals(scope) && - !"request".equals(scope) && - !"session".equals(scope) && - !"application".equals(scope)) - throw new IllegalArgumentException("Invalid scope '" + - scope + "'"); + public void setScope(String scope) + { + if (!"page".equals(scope) && !"request".equals(scope) + && !"session".equals(scope) && !"application".equals(scope)) + throw new IllegalArgumentException("Invalid scope '" + scope + "'"); this.scope = scope; } - /** * The CSS style <code>class</code> to be applied to the entire tree. */ protected String style = null; - public String getStyle() { + public String getStyle() + { return (this.style); } - public void setStyle(String style) { + public void setStyle(String style) + { this.style = style; } - /** - * The CSS style <code>class</code> to be applied to the text - * of selected nodes. + * The CSS style <code>class</code> to be applied to the text of selected + * nodes. */ protected String styleSelected = null; - public String getStyleSelected() { + public String getStyleSelected() + { return (this.styleSelected); } - public void setStyleSelected(String styleSelected) { + public void setStyleSelected(String styleSelected) + { this.styleSelected = styleSelected; } - /** - * The CSS style <code>class</code> to be applied to the text - * of unselected nodes. + * The CSS style <code>class</code> to be applied to the text of + * unselected nodes. */ protected String styleUnselected = null; - public String getStyleUnselected() { + public String getStyleUnselected() + { return (this.styleUnselected); } - public void setStyleUnselected(String styleUnselected) { + public void setStyleUnselected(String styleUnselected) + { this.styleUnselected = styleUnselected; } - /** * The name of the attribute (in the specified scope) under which our * <code>TreeControl</code> instance is stored. */ protected String tree = null; - public String getTree() { + public String getTree() + { return (this.tree); } - public void setTree(String tree) { + public void setTree(String tree) + { this.tree = tree; } - // --------------------------------------------------------- Public Methods - /** * Render this tree control. - * - * @exception JspException if a processing error occurs + * + * @exception JspException + * if a processing error occurs */ - public int doEndTag() throws JspException { + public int doEndTag() throws JspException + { TreeControl treeControl = getTreeControl(); JspWriter out = pageContext.getOut(); - try { - out.print - ("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\""); - if (style != null) { + try + { + out + .print("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\""); + if (style != null) + { out.print(" class=\""); out.print(style); out.print("\""); @@ -227,7 +236,9 @@ TreeControlNode node = treeControl.getRoot(); render(out, node, level, treeControl.getWidth(), true); out.println("</table>"); - } catch (IOException e) { + } + catch (IOException e) + { throw new JspException(e); } @@ -235,11 +246,11 @@ } - /** * Release all state information set by this tag. */ - public void release() { + public void release() + { this.action = null; this.images = DEFAULT_IMAGES; @@ -251,92 +262,101 @@ } - // ------------------------------------------------------ Protected Methods - /** * Return the <code>TreeControl</code> instance for the tree control that * we are rendering. - * - * @exception JspException if no TreeControl instance can be found + * + * @exception JspException + * if no TreeControl instance can be found */ - protected TreeControl getTreeControl() throws JspException { + protected TreeControl getTreeControl() throws JspException + { Object treeControl = null; if (scope == null) treeControl = pageContext.findAttribute(tree); else if ("page".equals(scope)) - treeControl = - pageContext.getAttribute(tree, PageContext.PAGE_SCOPE); + treeControl = pageContext + .getAttribute(tree, PageContext.PAGE_SCOPE); else if ("request".equals(scope)) - treeControl = - pageContext.getAttribute(tree, PageContext.REQUEST_SCOPE); + treeControl = pageContext.getAttribute(tree, + PageContext.REQUEST_SCOPE); else if ("session".equals(scope)) - treeControl = - pageContext.getAttribute(tree, PageContext.SESSION_SCOPE); + treeControl = pageContext.getAttribute(tree, + PageContext.SESSION_SCOPE); else if ("application".equals(scope)) - treeControl = - pageContext.getAttribute(tree, PageContext.APPLICATION_SCOPE); + treeControl = pageContext.getAttribute(tree, + PageContext.APPLICATION_SCOPE); if (treeControl == null) - throw new JspException("Cannot find tree control attribute '" + - tree + "'"); + throw new JspException("Cannot find tree control attribute '" + + tree + "'"); else if (!(treeControl instanceof TreeControl)) - throw new JspException("Invalid tree control attribute '" + - tree + "'"); + throw new JspException("Invalid tree control attribute '" + tree + + "'"); else return ((TreeControl) treeControl); } - /** * Render the specified node, as controlled by the specified parameters. - * - * @param out The <code>JspWriter</code> to which we are writing - * @param node The <code>TreeControlNode</code> we are currently - * rendering - * @param level The indentation level of this node in the tree - * @param width Total displayable width of the tree - * @param last Is this the last node in a list? - * - * @exception IOException if an input/output error occurs + * + * @param out + * The <code>JspWriter</code> to which we are writing + * @param node + * The <code>TreeControlNode</code> we are currently rendering + * @param level + * The indentation level of this node in the tree + * @param width + * Total displayable width of the tree + * @param last + * Is this the last node in a list? + * + * @exception IOException + * if an input/output error occurs */ - protected void render(JspWriter out, TreeControlNode node, - int level, int width, boolean last) - throws IOException { + protected void render(JspWriter out, TreeControlNode node, int level, + int width, boolean last) throws IOException + { - HttpServletResponse response = - (HttpServletResponse) pageContext.getResponse(); - + HttpServletResponse response = (HttpServletResponse) pageContext + .getResponse(); + // if the node is root node and the label value is // null, then do not render root node in the tree. - - if ("ROOT-NODE".equalsIgnoreCase(node.getName()) && - (node.getLabel() == null)) { + + if ("ROOT-NODE".equalsIgnoreCase(node.getName()) + && (node.getLabel() == null)) + { // Render the children of this node TreeControlNode children[] = node.findChildren(); int lastIndex = children.length - 1; int newLevel = level + 1; - for (int i = 0; i < children.length; i++) { + for (int i = 0; i < children.length; i++) + { render(out, children[i], newLevel, width, i == lastIndex); } return; } - + // Render the beginning of this node out.println(" <tr valign=\"middle\">"); - out.print("<td><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tr valign=\"middle\">"); + out + .print("<td><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tr valign=\"middle\">"); // Create the appropriate number of indents - for (int i = 0; i < level; i++) { + for (int i = 0; i < level; i++) + { int levels = level - i; TreeControlNode parent = node; for (int j = 1; j <= levels; j++) parent = parent.getParent(); if (parent.isLast()) out.print(" <td> </td>"); - else { + else + { out.print(" <td><img src=\""); out.print(images); out.print("/"); @@ -351,26 +371,25 @@ // HACK to take into account special characters like = and & // in the node name, could remove this code if encode URL // and later request.getParameter() could deal with = and & - // character in parameter values. + // character in parameter values. String encodedNodeName = URLEncoder.encode(node.getName()); String action = replace(getAction(), "${name}", encodedNodeName); - - String updateTreeAction = - replace(getAction(), "tree=${name}", "select=" + encodedNodeName); - updateTreeAction = - ((HttpServletResponse) pageContext.getResponse()). - encodeURL(updateTreeAction); + String updateTreeAction = replace(getAction(), "tree=${name}", + "select=" + encodedNodeName); + updateTreeAction = ((HttpServletResponse) pageContext.getResponse()) + .encodeURL(updateTreeAction); out.print(" <td>"); - -// add an anchor so that we can return to this node + + // add an anchor so that we can return to this node out.print("<a name=\""); out.print(node.getName()); out.print("\">"); - - if ((action != null) && !node.isLeaf()) { + + if ((action != null) && !node.isLeaf()) + { out.print("<a href=\""); out.print(response.encodeURL(action)); out.print("\">"); @@ -378,19 +397,24 @@ out.print("<img src=\""); out.print(images); out.print("/"); - if (node.isLeaf()) { + if (node.isLeaf()) + { if (node.isLast()) out.print(IMAGE_LINE_LAST); else out.print(IMAGE_LINE_MIDDLE); out.print("\" alt=\""); - } else if (node.isExpanded()) { + } + else if (node.isExpanded()) + { if (node.isLast()) out.print(IMAGE_HANDLE_DOWN_LAST); else out.print(IMAGE_HANDLE_DOWN_MIDDLE); out.print("\" alt=\"close node"); - } else { + } + else + { if (node.isLast()) out.print(IMAGE_HANDLE_RIGHT_LAST); else @@ -398,40 +422,42 @@ out.print("\" alt=\"expand node"); } out.print("\" border=\"0\">"); - if ((action != null) && !node.isLeaf()) - out.print("</a>"); + if ((action != null) && !node.isLeaf()) out.print("</a>"); out.println("</td>"); // Calculate the hyperlink for this node (if any) String hyperlink = null; String nodeAction = node.getAction(); - if(nodeAction == null && node.isExpandWhenClicked()) + if (nodeAction == null && node.isExpandWhenClicked()) { hyperlink = action; } if (nodeAction != null) - hyperlink = ((HttpServletResponse) pageContext.getResponse()). - encodeURL(node.getAction()); + hyperlink = ((HttpServletResponse) pageContext.getResponse()) + .encodeURL(node.getAction()); // Render the icon for this node (if any) out.print(" <td "); - - if(node.getLabel() != null) + + if (node.getLabel() != null) { - //make sure text does not wrap + // make sure text does not wrap out.print(" style=\""); out.print("white-space:nowrap; vertical-align:middle;"); out.print("\""); } - + out.print(">"); - if (node.getIcon() != null) { - if (hyperlink != null) { + if (node.getIcon() != null) + { + if (hyperlink != null) + { out.print("<a href=\""); out.print(hyperlink); out.print("\""); String target = node.getTarget(); - if(target != null) { + if (target != null) + { out.print(" target=\""); out.print(target); out.print("\""); @@ -448,49 +474,54 @@ out.print(node.getIcon()); out.print("\" alt=\""); out.print("\" border=\"0\">"); - if (hyperlink != null) - out.print("</a>"); + if (hyperlink != null) out.print("</a>"); } // Render the label for this node (if any) - if (node.getLabel() != null) { + if (node.getLabel() != null) + { String labelStyle = null; if (node.isSelected() && (styleSelected != null)) labelStyle = styleSelected; else if (!node.isSelected() && (styleUnselected != null)) labelStyle = styleUnselected; - if (hyperlink != null) { + if (hyperlink != null) + { // Note the leading space so that the text has some space // between it and any preceding images out.print(" <a href=\""); out.print(hyperlink); out.print("\""); String target = node.getTarget(); - if(target != null) { + if (target != null) + { out.print(" target=\""); out.print(target); out.print("\""); } - if (labelStyle != null) { + if (labelStyle != null) + { out.print(" class=\""); out.print(labelStyle); out.print("\""); } - - if(node.getTitle() != null) + + if (node.getTitle() != null) { out.print(" title=\""); out.print(node.getTitle()); out.print("\""); } - + // to refresh the tree in the same 'self' frame out.print(" onclick=\""); out.print("self.location.href='" + updateTreeAction + "'"); out.print("\""); out.print(">"); - } else if (labelStyle != null) { + } + else if (labelStyle != null) + { out.print("<span class=\""); out.print(labelStyle); out.print("\">"); @@ -498,8 +529,7 @@ out.print(node.getLabel()); if (hyperlink != null) out.print("</a>"); - else if (labelStyle != null) - out.print("</span>"); + else if (labelStyle != null) out.print("</span>"); } out.println("</td>"); @@ -508,37 +538,39 @@ out.println("</table></td></tr>"); // Render the children of this node - if (node.isExpanded()) { + if (node.isExpanded()) + { TreeControlNode children[] = node.findChildren(); int lastIndex = children.length - 1; int newLevel = level + 1; - for (int i = 0; i < children.length; i++) { + for (int i = 0; i < children.length; i++) + { render(out, children[i], newLevel, width, i == lastIndex); } } } - /** * Replace any occurrence of the specified placeholder in the specified * template string with the specified replacement value. - * - * @param template Pattern string possibly containing the placeholder - * @param placeholder Placeholder expression to be replaced - * @param value Replacement value for the placeholder + * + * @param template + * Pattern string possibly containing the placeholder + * @param placeholder + * Placeholder expression to be replaced + * @param value + * Replacement value for the placeholder */ - protected String replace(String template, String placeholder, - String value) { + protected String replace(String template, String placeholder, String value) + { - if (template == null) - return (null); - if ((placeholder == null) || (value == null)) - return (template); - while (true) { + if (template == null) return (null); + if ((placeholder == null) || (value == null)) return (template); + while (true) + { int index = template.indexOf(placeholder); - if (index < 0) - break; + if (index < 0) break; StringBuffer temp = new StringBuffer(template.substring(0, index)); temp.append(value); temp.append(template.substring(index + placeholder.length())); From svnnotify ¡÷ sourceforge.jp Fri May 16 14:55:14 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Fri, 16 May 2008 14:55:14 +0900 Subject: [pal-cvs 3204] [941] backout of 937. Message-ID: <1210917314.559154.24401.nullmailer@users.sourceforge.jp> Revision: 941 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=941 Author: shinsuke Date: 2008-05-16 14:55:14 +0900 (Fri, 16 May 2008) Log Message: ----------- backout of 937. Modified Paths: -------------- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PersistenceBrokerPreferencesProvider.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesFactoryImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesImpl.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/assembly/prefs.xml Removed Paths: ------------- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/PreferencesRootWrapper.java pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesProviderWrapper.java -------------- next part -------------- Deleted: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/PreferencesRootWrapper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/PreferencesRootWrapper.java 2008-05-16 01:54:54 UTC (rev 940) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/commons/src/java/org/apache/jetspeed/util/PreferencesRootWrapper.java 2008-05-16 05:55:14 UTC (rev 941) @@ -1,240 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.jetspeed.util; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.Observable; -import java.util.Observer; -import java.util.prefs.BackingStoreException; -import java.util.prefs.NodeChangeListener; -import java.util.prefs.PreferenceChangeListener; -import java.util.prefs.Preferences; - -/** - * PreferencesRootWrapper is a lightweight wrapper around the Jetspeed - * persistent PreferencesImpl to allow restarting the Jetspeed Portal. - * <p> - * As the (Sun) Java Preferences implementation only creates a - * PreferencesFactory instance *once* per JVM (as static final), reloading the - * Jetspeed Portal (using a new classloader) requires a wrapper solution to - * prevent ClassCastExceptions and/or out-of-sync kept proxies and caches. - * </p> - * <p> - * As a newly created Jetspeed Portal classloader can no longer cast a previous - * Preferences root to its own PreferencesImpl, a "trick" is used by also - * implementing the Observer interface (which is provided by the Java system - * classloader). The Observer interface is used because it is very lightweight - * and allows passing an Object instance through its update method. That update - * method is used to "inject" the newly created Preferences root instance. - * </p> - * - * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> - * @version $Id$ - */ -public class PreferencesRootWrapper extends Preferences implements Observer -{ - - private Preferences root; - - public String absolutePath() - { - return root.absolutePath(); - } - - public void addNodeChangeListener(NodeChangeListener ncl) - { - root.addNodeChangeListener(ncl); - } - - public void addPreferenceChangeListener(PreferenceChangeListener pcl) - { - root.addPreferenceChangeListener(pcl); - } - - public String[] childrenNames() throws BackingStoreException - { - return root.childrenNames(); - } - - public void clear() throws BackingStoreException - { - root.clear(); - } - - public boolean equals(Object obj) - { - return root.equals(obj); - } - - public void exportNode(OutputStream os) throws IOException, - BackingStoreException - { - root.exportNode(os); - } - - public void exportSubtree(OutputStream os) throws IOException, - BackingStoreException - { - root.exportSubtree(os); - } - - public void flush() throws BackingStoreException - { - root.flush(); - } - - public String get(String key, String def) - { - return root.get(key, def); - } - - public boolean getBoolean(String key, boolean def) - { - return root.getBoolean(key, def); - } - - public byte[] getByteArray(String key, byte[] def) - { - return root.getByteArray(key, def); - } - - public double getDouble(String key, double def) - { - return root.getDouble(key, def); - } - - public float getFloat(String key, float def) - { - return root.getFloat(key, def); - } - - public int getInt(String key, int def) - { - return root.getInt(key, def); - } - - public long getLong(String key, long def) - { - return root.getLong(key, def); - } - - public int hashCode() - { - return root.hashCode(); - } - - public boolean isUserNode() - { - return root.isUserNode(); - } - - public String[] keys() throws BackingStoreException - { - return root.keys(); - } - - public String name() - { - return root.name(); - } - - public Preferences node(String pathName) - { - return root.node(pathName); - } - - public boolean nodeExists(String pathName) throws BackingStoreException - { - return root.nodeExists(pathName); - } - - public Preferences parent() - { - return root.parent(); - } - - public void put(String key, String value) - { - root.put(key, value); - } - - public void putBoolean(String key, boolean value) - { - root.putBoolean(key, value); - } - - public void putByteArray(String key, byte[] value) - { - root.putByteArray(key, value); - } - - public void putDouble(String key, double value) - { - root.putDouble(key, value); - } - - public void putFloat(String key, float value) - { - root.putFloat(key, value); - } - - public void putInt(String key, int value) - { - root.putInt(key, value); - } - - public void putLong(String key, long value) - { - root.putLong(key, value); - } - - public void remove(String key) - { - root.remove(key); - } - - public void removeNode() throws BackingStoreException - { - root.removeNode(); - } - - public void removeNodeChangeListener(NodeChangeListener ncl) - { - root.removeNodeChangeListener(ncl); - } - - public void removePreferenceChangeListener(PreferenceChangeListener pcl) - { - root.removePreferenceChangeListener(pcl); - } - - public void sync() throws BackingStoreException - { - root.sync(); - } - - public String toString() - { - return root.toString(); - } - - public void update(Observable o, Object arg) - { - root = (Preferences) arg; - } -} Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PersistenceBrokerPreferencesProvider.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PersistenceBrokerPreferencesProvider.java 2008-05-16 01:54:54 UTC (rev 940) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PersistenceBrokerPreferencesProvider.java 2008-05-16 05:55:14 UTC (rev 941) @@ -49,7 +49,8 @@ * </p> * * @author <a href="mailto:weaver ¡÷ apache.org">Scott T. Weaver </a> - * @version $Id$ + * @version $Id: PersistenceBrokerPreferencesProvider.java 605797 2007-12-20 + * 03:39:09Z woonsan $ */ public class PersistenceBrokerPreferencesProvider extends InitablePersistenceBrokerDaoSupport implements PreferencesProvider @@ -227,13 +228,6 @@ this.preloadEntities = preloadEntities; } - public void destroy() - { - NodeImplProxy.setProvider(null); - preferenceCache = null; - preloadedApplications = null; - } - protected void addToCache(NodeCache content) { CacheElement cachedElement = preferenceCache.createElement(content @@ -487,15 +481,15 @@ NodeCache key = new NodeCache(hit); getPersistenceBrokerTemplate().store(hit.getNode()); // avoid racing - // condition - // with the db - // and with - // cluster - // notification + // condition + // with the db + // and with + // cluster + // notification // do the db first preferenceCache.remove(key.getCacheKey()); // not sure we should - // actually do that, could - // also just update the node + // actually do that, could + // also just update the node addToCache(key); } @@ -512,12 +506,12 @@ { getPersistenceBrokerTemplate().delete( ((NodeImplProxy) node).getNode()); // avoid race conditions - // - do this first + // - do this first } else getPersistenceBrokerTemplate().delete(node); // avoid race - // conditions - do - // this first + // conditions - do + // this first if (node instanceof NodeImplProxy) { Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesFactoryImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesFactoryImpl.java 2008-05-16 01:54:54 UTC (rev 940) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesFactoryImpl.java 2008-05-16 05:55:14 UTC (rev 941) @@ -16,13 +16,11 @@ */ package org.apache.jetspeed.prefs.impl; -import java.util.Observer; import java.util.prefs.Preferences; import java.util.prefs.PreferencesFactory; import org.apache.jetspeed.prefs.PreferencesException; import org.apache.jetspeed.prefs.PreferencesProvider; -import org.apache.jetspeed.util.PreferencesRootWrapper; /** * <p> @@ -31,39 +29,15 @@ * </p> * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat</a> - * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> - * @version $Id$ */ public class PreferencesFactoryImpl implements PreferencesFactory { - private Preferences userRootWrapper; + protected static PreferencesProvider prefsProvider; - private Preferences systemRootWrapper; - - private PreferencesImpl userRoot; - - private PreferencesImpl systemRoot; - - private PreferencesProvider preferencesProvider; - - /** - * Java Preferences invoked constructor - */ public PreferencesFactoryImpl() { - userRootWrapper = new PreferencesRootWrapper(); - systemRootWrapper = new PreferencesRootWrapper(); - } - - /** - * Spring invoked constructor with a dummy parameter to distinguish it from - * the default constructor invoked by the Java Preferences - * - * @param dummy - */ - public PreferencesFactoryImpl(int dummy) - { + super(); System.setProperty("java.util.prefs.PreferencesFactory", getClass() .getName()); } @@ -73,7 +47,7 @@ */ public Preferences systemRoot() { - return systemRootWrapper; + return PreferencesImpl.systemRoot; } /** @@ -81,7 +55,7 @@ */ public Preferences userRoot() { - return userRootWrapper; + return PreferencesImpl.userRoot; } /** @@ -95,37 +69,26 @@ { try { - // Wrap the PreferencesProvider to provide a single instance to be - // stored in the Preferences nodes - // which can be disposed at once for all - PreferencesProviderWrapper ppw = new PreferencesProviderWrapper( - preferencesProvider); - preferencesProvider = null; - userRoot = new PreferencesImpl(null, ppw, "", - PreferencesImpl.USER_NODE_TYPE); - systemRoot = new PreferencesImpl(null, ppw, "", + PreferencesImpl.setPreferencesProvider(prefsProvider); + PreferencesImpl.systemRoot = new PreferencesImpl(null, "", PreferencesImpl.SYSTEM_NODE_TYPE); - // set/update the Java Preferences userRoot and systeRoot - // PreferencesRootWrapper instances - ((Observer) Preferences.userRoot()).update(null, userRoot); - ((Observer) Preferences.systemRoot()).update(null, systemRoot); + PreferencesImpl.userRoot = new PreferencesImpl(null, "", + PreferencesImpl.USER_NODE_TYPE); } catch (Throwable e) { + e.printStackTrace(); throw new PreferencesException("Failed to initialize prefs api. " - + e.getMessage(), e); + + e.toString()); } } - public void dispose() + /** + * @return The {@link PreferencesProvider} + */ + public PreferencesProvider getPrefsProvider() { - ((Observer) Preferences.userRoot()).update(null, null); - ((Observer) Preferences.systemRoot()).update(null, null); - userRoot.disposeNode(); - systemRoot.disposeNode(); - userRoot.ppw.dispose(); - userRoot = null; - systemRoot = null; + return prefsProvider; } /** @@ -133,11 +96,11 @@ * Set the preferences provider. * </p> * - * @param preferencesProvider + * @param prefsProvider * The {@link PreferencesProvider} */ - public void setPrefsProvider(PreferencesProvider preferencesProvider) + public void setPrefsProvider(PreferencesProvider prefsProvider) { - this.preferencesProvider = preferencesProvider; + PreferencesFactoryImpl.prefsProvider = prefsProvider; } } Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesImpl.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesImpl.java 2008-05-16 01:54:54 UTC (rev 940) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesImpl.java 2008-05-16 05:55:14 UTC (rev 941) @@ -29,6 +29,7 @@ import org.apache.jetspeed.prefs.FailedToCreateNodeException; import org.apache.jetspeed.prefs.NodeAlreadyExistsException; import org.apache.jetspeed.prefs.NodeDoesNotExistException; +import org.apache.jetspeed.prefs.PreferencesProvider; import org.apache.jetspeed.prefs.om.Node; import org.apache.jetspeed.prefs.om.Property; import org.apache.jetspeed.prefs.om.impl.PropertyImpl; @@ -40,8 +41,6 @@ * </p> * * @author <a href="mailto:dlestrat ¡÷ apache.org">David Le Strat </a> - * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> - * @version $Id$ */ public class PreferencesImpl extends AbstractPreferences { @@ -58,13 +57,12 @@ /** Logger. */ private static final Log log = LogFactory.getLog(PreferencesImpl.class); - protected PreferencesProviderWrapper ppw; + protected static PreferencesProvider prefsProvider; - void disposeNode() - { - node = null; - } + static PreferencesImpl systemRoot; + static PreferencesImpl userRoot; + /** * <p> * Constructs a root node in the underlying datastore if they have not yet @@ -81,22 +79,21 @@ * @param nodeType * The node type. */ - PreferencesImpl(PreferencesImpl parent, PreferencesProviderWrapper ppw, - String nodeName, int nodeType) throws IllegalStateException + public PreferencesImpl(PreferencesImpl parent, String nodeName, int nodeType) + throws IllegalStateException { super(parent, nodeName); try { - this.ppw = ppw; if (parent != null) { - this.node = ppw.provider().createNode(parent.getNode(), + this.node = prefsProvider.createNode(parent.getNode(), nodeName, nodeType, this.absolutePath()); } else { - this.node = ppw.provider().createNode(null, nodeName, nodeType, + this.node = prefsProvider.createNode(null, nodeName, nodeType, this.absolutePath()); } @@ -114,7 +111,7 @@ { try { - node = ppw.provider().getNode(this.absolutePath(), nodeType); + node = prefsProvider.getNode(this.absolutePath(), nodeType); newNode = false; } catch (NodeDoesNotExistException e1) @@ -138,7 +135,7 @@ */ public String[] childrenNamesSpi() throws BackingStoreException { - Collection nodes = ppw.provider().getChildren(getNode()); + Collection nodes = prefsProvider.getChildren(getNode()); if (null != nodes) { @@ -163,7 +160,7 @@ */ public AbstractPreferences childSpi(String name) { - return new PreferencesImpl(this, ppw, name, node.getNodeType()); + return new PreferencesImpl(this, name, node.getNodeType()); } /** @@ -171,7 +168,7 @@ */ public void flushSpi() throws BackingStoreException { - ppw.provider().storeNode(this.node); + prefsProvider.storeNode(this.node); } /** @@ -181,13 +178,12 @@ { String value = null; // Collection properties = node.getNodeProperties(); - // TODO review below // BEGIN Node targetNode = null; try { - targetNode = ppw.provider().getNode(node.getFullPath(), - node.getNodeType()); + targetNode = prefsProvider.getNode(node.getFullPath(), node + .getNodeType()); } catch (NodeDoesNotExistException e) { @@ -277,7 +273,7 @@ properties.add(new PropertyImpl(node.getNodeId(), key, value)); } - ppw.provider().storeNode(node); + prefsProvider.storeNode(node); } /** @@ -291,7 +287,7 @@ { parentNode = ((PreferencesImpl) parent).getNode(); } - ppw.provider().removeNode(parentNode, node); + prefsProvider.removeNode(parentNode, node); } /** @@ -311,7 +307,7 @@ } } // Update node. - ppw.provider().storeNode(node); + prefsProvider.storeNode(node); } /** @@ -334,4 +330,20 @@ { return node; } + + /** + * + * <p> + * setPreferencesProvider + * </p> + * Sets the <code>org.apache.jetspeed.prefs.PreferencesProvider</code> + * that will support backing store operations for all + * <code>PreferencesImpls</code> + * + * @param prefsProvider + */ + public static void setPreferencesProvider(PreferencesProvider prefsProvider) + { + PreferencesImpl.prefsProvider = prefsProvider; + } } Deleted: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesProviderWrapper.java =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesProviderWrapper.java 2008-05-16 01:54:54 UTC (rev 940) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/components/prefs/src/java/org/apache/jetspeed/prefs/impl/PreferencesProviderWrapper.java 2008-05-16 05:55:14 UTC (rev 941) @@ -1,44 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.jetspeed.prefs.impl; - -import org.apache.jetspeed.prefs.PreferencesProvider; - -/** - * @author <a href="mailto:ate ¡÷ douma.nu">Ate Douma</a> - * @version $Id$ - */ -public class PreferencesProviderWrapper -{ - - PreferencesProvider provider; - - PreferencesProviderWrapper(PreferencesProvider provider) - { - this.provider = provider; - } - - PreferencesProvider provider() - { - return provider; - } - - void dispose() - { - provider = null; - } -} Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/assembly/prefs.xml =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/assembly/prefs.xml 2008-05-16 01:54:54 UTC (rev 940) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/assembly/prefs.xml 2008-05-16 05:55:14 UTC (rev 941) @@ -19,7 +19,7 @@ <beans> <!-- Preferences Implementation --> - <bean id="PreferencesProviderImpl" class="org.apache.jetspeed.prefs.impl.PersistenceBrokerPreferencesProvider" name="prefsPersistenceBroker" init-method="init" destroy-method="destroy"> + <bean id="PreferencesProviderImpl" class="org.apache.jetspeed.prefs.impl.PersistenceBrokerPreferencesProvider" name="prefsPersistenceBroker" init-method="init"> <constructor-arg index="0"> <value>JETSPEED-INF/ojb/prefs_repository.xml</value> </constructor-arg> @@ -36,7 +36,7 @@ <constructor-arg index='3'><value type="boolean">false</value></constructor-arg> </bean> - <bean id="org.apache.jetspeed.prefs.PreferencesProvider" parent="baseTransactionProxy" name="prefsProvider" destroy-method="destroy"> + <bean id="org.apache.jetspeed.prefs.PreferencesProvider" parent="baseTransactionProxy" name="prefsProvider"> <property name="proxyInterfaces"> <value>org.apache.jetspeed.prefs.PreferencesProvider</value> </property> @@ -55,9 +55,7 @@ </bean> <!-- PreferencesFactory implementation --> - <bean id="java.util.prefs.PreferencesFactory" class="org.apache.jetspeed.prefs.impl.PreferencesFactoryImpl" name="prefsFactory" init-method="init" destroy-method="destroy"> - <!-- dummy constructor argument to distinguish it from the default constructor invoked by the Java Preferences itself --> - <constructor-arg><value>1</value></constructor-arg> + <bean id="java.util.prefs.PreferencesFactory" class="org.apache.jetspeed.prefs.impl.PreferencesFactoryImpl" name="prefsFactory" init-method="init"> <property name="prefsProvider"> <ref bean="prefsProvider" /> </property> From svnnotify ¡÷ sourceforge.jp Mon May 19 14:31:46 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Mon, 19 May 2008 14:31:46 +0900 Subject: [pal-cvs 3205] [942] removed unused document-order. Message-ID: <1211175106.067735.15922.nullmailer@users.sourceforge.jp> Revision: 942 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=942 Author: shinsuke Date: 2008-05-19 14:31:45 +0900 (Mon, 19 May 2008) Log Message: ----------- removed unused document-order. Modified Paths: -------------- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/docomo-html/folder.metadata pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/docomo-wap2/folder.metadata pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/html/folder.metadata pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/kddi-hdml/folder.metadata pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/kddi-wap2/folder.metadata pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/softbank-html/folder.metadata pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/softbank-wap2/folder.metadata pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/folder.metadata -------------- next part -------------- Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/docomo-html/folder.metadata =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/docomo-html/folder.metadata 2008-05-16 05:55:14 UTC (rev 941) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/docomo-html/folder.metadata 2008-05-19 05:31:45 UTC (rev 942) @@ -8,9 +8,6 @@ <short-title>Root Folder</short-title> <defaults/> <document-order>default-page.psml</document-order> - <document-order>products</document-order> - <document-order>downloads</document-order> - <document-order>aboutus</document-order> <document-order>register.psml</document-order> <document-order>forgot.psml</document-order> <menu name="navigations" depth="0" paths="false" regexp="false"> Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/docomo-wap2/folder.metadata =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/docomo-wap2/folder.metadata 2008-05-16 05:55:14 UTC (rev 941) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/docomo-wap2/folder.metadata 2008-05-19 05:31:45 UTC (rev 942) @@ -8,9 +8,6 @@ <short-title>Root Folder</short-title> <defaults/> <document-order>default-page.psml</document-order> - <document-order>products</document-order> - <document-order>downloads</document-order> - <document-order>aboutus</document-order> <document-order>register.psml</document-order> <document-order>forgot.psml</document-order> <menu name="navigations" depth="0" paths="false" regexp="false"> Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/html/folder.metadata =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/html/folder.metadata 2008-05-16 05:55:14 UTC (rev 941) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/html/folder.metadata 2008-05-19 05:31:45 UTC (rev 942) @@ -8,12 +8,8 @@ <short-title>TOP</short-title> <defaults/> <document-order>default-page.psml</document-order> - <document-order>products</document-order> - <document-order>downloads</document-order> - <document-order>aboutus</document-order> <document-order>register.psml</document-order> <document-order>forgot.psml</document-order> - <document-order>sample</document-order> <menu name="navigations" depth="0" paths="false" regexp="false"> <separator> <text>Folders</text> Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/kddi-hdml/folder.metadata =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/kddi-hdml/folder.metadata 2008-05-16 05:55:14 UTC (rev 941) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/kddi-hdml/folder.metadata 2008-05-19 05:31:45 UTC (rev 942) @@ -8,9 +8,6 @@ <short-title>Root Folder</short-title> <defaults/> <document-order>default-page.psml</document-order> - <document-order>products</document-order> - <document-order>downloads</document-order> - <document-order>aboutus</document-order> <document-order>register.psml</document-order> <document-order>forgot.psml</document-order> <menu name="navigations" depth="0" paths="false" regexp="false"> Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/kddi-wap2/folder.metadata =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/kddi-wap2/folder.metadata 2008-05-16 05:55:14 UTC (rev 941) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/kddi-wap2/folder.metadata 2008-05-19 05:31:45 UTC (rev 942) @@ -8,9 +8,6 @@ <short-title>Root Folder</short-title> <defaults/> <document-order>default-page.psml</document-order> - <document-order>products</document-order> - <document-order>downloads</document-order> - <document-order>aboutus</document-order> <document-order>register.psml</document-order> <document-order>forgot.psml</document-order> <menu name="navigations" depth="0" paths="false" regexp="false"> Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/softbank-html/folder.metadata =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/softbank-html/folder.metadata 2008-05-16 05:55:14 UTC (rev 941) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/softbank-html/folder.metadata 2008-05-19 05:31:45 UTC (rev 942) @@ -8,9 +8,6 @@ <short-title>Root Folder</short-title> <defaults/> <document-order>default-page.psml</document-order> - <document-order>products</document-order> - <document-order>downloads</document-order> - <document-order>aboutus</document-order> <document-order>register.psml</document-order> <document-order>forgot.psml</document-order> <menu name="navigations" depth="0" paths="false" regexp="false"> Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/softbank-wap2/folder.metadata =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/softbank-wap2/folder.metadata 2008-05-16 05:55:14 UTC (rev 941) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/_mediatype/softbank-wap2/folder.metadata 2008-05-19 05:31:45 UTC (rev 942) @@ -8,9 +8,6 @@ <short-title>Root Folder</short-title> <defaults/> <document-order>default-page.psml</document-order> - <document-order>products</document-order> - <document-order>downloads</document-order> - <document-order>aboutus</document-order> <document-order>register.psml</document-order> <document-order>forgot.psml</document-order> <menu name="navigations" depth="0" paths="false" regexp="false"> Modified: pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/folder.metadata =================================================================== --- pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/folder.metadata 2008-05-16 05:55:14 UTC (rev 941) +++ pal-portal/branches/pal-portal-1.x/portal/jetspeed-2/src/webapp/WEB-INF/pages/_role/site/folder.metadata 2008-05-19 05:31:45 UTC (rev 942) @@ -8,9 +8,6 @@ <short-title>Root Folder</short-title> <defaults/> <document-order>default-page.psml</document-order> - <document-order>products</document-order> - <document-order>downloads</document-order> - <document-order>aboutus</document-order> <document-order>register.psml</document-order> <document-order>forgot.psml</document-order> <menu name="navigations" depth="0" paths="false" regexp="false"> From svnnotify ¡÷ sourceforge.jp Wed May 21 15:38:44 2008 From: svnnotify ¡÷ sourceforge.jp (svnnotify ¡÷ sourceforge.jp) Date: Wed, 21 May 2008 15:38:44 +0900 Subject: [pal-cvs 3206] [943] added .tld file and updated upload, connect files Message-ID: <1211351924.429688.24125.nullmailer@users.sourceforge.jp> Revision: 943 http://svn.sourceforge.jp/cgi-bin/viewcvs.cgi?root=pal&view=rev&rev=943 Author: sone Date: 2008-05-21 15:38:44 +0900 (Wed, 21 May 2008) Log Message: ----------- added .tld file and updated upload, connect files Modified Paths: -------------- pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/servlet/FilesaveServlet.java pal-wcm/trunk/src/main/webapp/WEB-INF/web.xml pal-wcm/trunk/src/main/webapp/index.jsp Added Paths: ----------- pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/connector/ pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/connector/ConnectorServlet.java pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/tags/ pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/tags/FCKeditorTag.java pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/uploader/ pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/uploader/SimpleUploaderServlet.java pal-wcm/trunk/src/main/webapp/WEB-INF/tld/ pal-wcm/trunk/src/main/webapp/WEB-INF/tld/FCKeditor.tld pal-wcm/trunk/src/main/webapp/WEB-INF/tld/portlet.tld -------------- next part -------------- Added: pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/connector/ConnectorServlet.java =================================================================== --- pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/connector/ConnectorServlet.java (rev 0) +++ pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/connector/ConnectorServlet.java 2008-05-21 06:38:44 UTC (rev 943) @@ -0,0 +1,321 @@ +/* + * FCKeditor - The text editor for internet + * Copyright (C) 2003-2005 Frederico Caldeira Knabben + * + * Licensed under the terms of the GNU Lesser General Public License: + * http://www.opensource.org/licenses/lgpl-license.php + * + * For further information visit: + * http://www.fckeditor.net/ + * + * File Name: ConnectorServlet.java + * Java Connector for Resource Manager class. + * + * Version: 2.3 + * Modified: 2005-08-11 16:29:00 + * + * File Authors: + * Simone Chiaretta (simo ¡÷ users.sourceforge.net) + */ + +package jp.sf.pal.wcm.connector; + +import java.io.*; +import javax.servlet.*; +import javax.servlet.http.*; +import java.util.*; + + +import org.apache.commons.fileupload.*; + + +import javax.xml.parsers.*; +import org.w3c.dom.*; +import javax.xml.transform.*; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + + +/** + * Servlet to upload and browse files.<br> + * + * This servlet accepts 4 commands used to retrieve and create files and folders from a server directory. + * The allowed commands are: + * <ul> + * <li>GetFolders: Retrive the list of directory under the current folder + * <li>GetFoldersAndFiles: Retrive the list of files and directory under the current folder + * <li>CreateFolder: Create a new directory under the current folder + * <li>FileUpload: Send a new file to the server (must be sent with a POST) + * </ul> + * + * @author Simone Chiaretta (simo ¡÷ users.sourceforge.net) + */ + +public class ConnectorServlet extends HttpServlet { + + private static String baseDir; + private static boolean debug=false; + + /** + * Initialize the servlet.<br> + * Retrieve from the servlet configuration the "baseDir" which is the root of the file repository:<br> + * If not specified the value of "/UserFiles/" will be used. + * + */ + public void init() throws ServletException { + baseDir=getInitParameter("baseDir"); + debug=(new Boolean(getInitParameter("debug"))).booleanValue(); + if(baseDir==null) + baseDir="/UserFiles/"; + String realBaseDir=getServletContext().getRealPath(baseDir); + File baseFile=new File(realBaseDir); + if(!baseFile.exists()){ + baseFile.mkdir(); + } + } + + /** + * Manage the Get requests (GetFolders, GetFoldersAndFiles, CreateFolder).<br> + * + * The servlet accepts commands sent in the following format:<br> + * connector?Command=CommandName&Type=ResourceType&CurrentFolder=FolderPath<br><br> + * It execute the command and then return the results to the client in XML format. + * + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + if (debug) System.out.println("--- BEGIN DOGET ---"); + + response.setContentType("text/xml; charset=UTF-8"); + response.setHeader("Cache-Control","no-cache"); + PrintWriter out = response.getWriter(); + + String commandStr=request.getParameter("Command"); + String typeStr=request.getParameter("Type"); + String currentFolderStr=request.getParameter("CurrentFolder"); + + String currentPath=baseDir+typeStr+currentFolderStr; + String currentDirPath=getServletContext().getRealPath(currentPath); + + File currentDir=new File(currentDirPath); + if(!currentDir.exists()){ + currentDir.mkdir(); + } + + Document document=null; + try { + DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + document=builder.newDocument(); + } catch (ParserConfigurationException pce) { + pce.printStackTrace(); + } + + Node root=CreateCommonXml(document,commandStr,typeStr,currentFolderStr,request.getContextPath()+currentPath); + + if (debug) System.out.println("Command = " + commandStr); + + if(commandStr.equals("GetFolders")) { + getFolders(currentDir,root,document); + } + else if (commandStr.equals("GetFoldersAndFiles")) { + getFolders(currentDir,root,document); + getFiles(currentDir,root,document); + } + else if (commandStr.equals("CreateFolder")) { + String newFolderStr=request.getParameter("NewFolderName"); + File newFolder=new File(currentDir,newFolderStr); + String retValue="110"; + + if(newFolder.exists()){ + retValue="101"; + } + else { + try { + boolean dirCreated = newFolder.mkdir(); + if(dirCreated) + retValue="0"; + else + retValue="102"; + }catch(SecurityException sex) { + retValue="103"; + } + + } + setCreateFolderResponse(retValue,root,document); + } + + document.getDocumentElement().normalize(); + try { + TransformerFactory tFactory = TransformerFactory.newInstance(); + Transformer transformer = tFactory.newTransformer(); + + DOMSource source = new DOMSource(document); + + StreamResult result = new StreamResult(out); + transformer.transform(source, result); + + if (debug) { + StreamResult dbgResult = new StreamResult(System.out); + transformer.transform(source, dbgResult); + System.out.println(""); + System.out.println("--- END DOGET ---"); + } + + + } catch (Exception ex) { + ex.printStackTrace(); + } + + + out.flush(); + out.close(); + } + + + /** + * Manage the Post requests (FileUpload).<br> + * + * The servlet accepts commands sent in the following format:<br> + * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br> + * It store the file (renaming it in case a file with the same name exists) and then return an HTML file + * with a javascript command in it. + * + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + if (debug) System.out.println("--- BEGIN DOPOST ---"); + + response.setContentType("text/html; charset=UTF-8"); + response.setHeader("Cache-Control","no-cache"); + PrintWriter out = response.getWriter(); + + String commandStr=request.getParameter("Command"); + String typeStr=request.getParameter("Type"); + String currentFolderStr=request.getParameter("CurrentFolder"); + + String currentPath=baseDir+typeStr+currentFolderStr; + String currentDirPath=getServletContext().getRealPath(currentPath); + + if (debug) System.out.println(currentDirPath); + + String retVal="0"; + String newName=""; + + if(!commandStr.equals("FileUpload")) + retVal="203"; + else { + DiskFileUpload upload = new DiskFileUpload(); + try { + List items = upload.parseRequest(request); + + Map fields=new HashMap(); + + Iterator iter = items.iterator(); + while (iter.hasNext()) { + FileItem item = (FileItem) iter.next(); + if (item.isFormField()) + fields.put(item.getFieldName(),item.getString()); + else + fields.put(item.getFieldName(),item); + } + FileItem uplFile=(FileItem)fields.get("NewFile"); + String fileNameLong=uplFile.getName(); + fileNameLong=fileNameLong.replace('\\','/'); + String[] pathParts=fileNameLong.split("/"); + String fileName=pathParts[pathParts.length-1]; + + String nameWithoutExt=getNameWithoutExtension(fileName); + String ext=getExtension(fileName); + File pathToSave=new File(currentDirPath,fileName); + int counter=1; + while(pathToSave.exists()){ + newName=nameWithoutExt+"("+counter+")"+"."+ext; + retVal="201"; + pathToSave=new File(currentDirPath,newName); + counter++; + } + uplFile.write(pathToSave); + }catch (Exception ex) { + retVal="203"; + } + + } + + out.println("<script type=\"text/javascript\">"); + out.println("window.parent.frames['frmUpload'].OnUploadCompleted("+retVal+",'"+newName+"');"); + out.println("</script>"); + out.flush(); + out.close(); + + if (debug) System.out.println("--- END DOPOST ---"); + + } + + private void setCreateFolderResponse(String retValue,Node root,Document doc) { + Element myEl=doc.createElement("Error"); + myEl.setAttribute("number",retValue); + root.appendChild(myEl); + } + + + private void getFolders(File dir,Node root,Document doc) { + Element folders=doc.createElement("Folders"); + root.appendChild(folders); + File[] fileList=dir.listFiles(); + for(int i=0;i<fileList.length;++i) { + if(fileList[i].isDirectory()){ + Element myEl=doc.createElement("Folder"); + myEl.setAttribute("name",fileList[i].getName()); + folders.appendChild(myEl); + } + } + } + + private void getFiles(File dir,Node root,Document doc) { + Element files=doc.createElement("Files"); + root.appendChild(files); + File[] fileList=dir.listFiles(); + for(int i=0;i<fileList.length;++i) { + if(fileList[i].isFile()){ + Element myEl=doc.createElement("File"); + myEl.setAttribute("name",fileList[i].getName()); + myEl.setAttribute("size",""+fileList[i].length()/1024); + files.appendChild(myEl); + } + } + } + + private Node CreateCommonXml(Document doc,String commandStr, String typeStr, String currentPath, String currentUrl ) { + + Element root=doc.createElement("Connector"); + doc.appendChild(root); + root.setAttribute("command",commandStr); + root.setAttribute("resourceType",typeStr); + + Element myEl=doc.createElement("CurrentFolder"); + myEl.setAttribute("path",currentPath); + myEl.setAttribute("url",currentUrl); + root.appendChild(myEl); + + return root; + + } + + /* + * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF bug #991489 + */ + private static String getNameWithoutExtension(String fileName) { + return fileName.substring(0, fileName.lastIndexOf(".")); + } + + /* + * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF bug #991489 + */ + private String getExtension(String fileName) { + return fileName.substring(fileName.lastIndexOf(".")+1); + } + + +} + Modified: pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/servlet/FilesaveServlet.java =================================================================== --- pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/servlet/FilesaveServlet.java 2008-05-19 05:31:45 UTC (rev 942) +++ pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/servlet/FilesaveServlet.java 2008-05-21 06:38:44 UTC (rev 943) @@ -15,29 +15,33 @@ */ package jp.sf.pal.wcm.servlet; -import java.io.IOException; - -import java.util.*; import java.io.File; import java.io.FileWriter; +import java.io.IOException; import java.io.PrintWriter; +import java.util.Enumeration; + import javax.servlet.ServletContext; - -import jp.sf.pal.wcm.*; - import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + + /** - * @author takaaki sone + * @author takaaki * */ -public class FilesaveServlet extends HttpServlet { - @Override +public class FilesaveServlet extends HttpServlet { + + private static final Log log = LogFactory.getLog(FilesaveServlet.class); + + @Override protected void doGet(HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException { + HttpServletResponse response) throws ServletException, IOException { Enumeration params = request.getParameterNames(); String parameter = null; String reqParam = null; @@ -56,8 +60,7 @@ if (!fragIdDir.exists()) { if (!fragIdDir.mkdirs()) { // fail to mkdir - System.err.println("error:cannot mkdir" + - outputFilePath); + log.error("cannot mkdir : " + outputFilePath); } } FileWriter fw = new FileWriter(outputFilePath + outputFileName); @@ -65,6 +68,7 @@ writer.println(reqParam); fw.close(); } catch (Exception e) { + log.error(e); e.printStackTrace(); } } Added: pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/tags/FCKeditorTag.java =================================================================== --- pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/tags/FCKeditorTag.java (rev 0) +++ pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/tags/FCKeditorTag.java 2008-05-21 06:38:44 UTC (rev 943) @@ -0,0 +1,697 @@ +/* + * FCKeditor - The text editor for internet + * Copyright (C) 2003-2005 Frederico Caldeira Knabben + * + * Licensed under the terms of the GNU Lesser General Public License: + * http://www.opensource.org/licenses/lgpl-license.php + * + * For further information visit: + * http://www.fckeditor.net/ + * + * File Name: FCKeditorTag.java + * FCKeditor tag library. + * + * Version: 2.3 + * Modified: 2005-08-11 16:29:00 + * + * File Authors: + * Simone Chiaretta (simo ¡÷ users.sourceforge.net) + */ + + +package jp.sf.pal.wcm.tags; + +import jp.sf.pal.wcm.FCKeditor; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; + +import javax.servlet.jsp.PageContext; +import javax.servlet.jsp.JspException; +import javax.servlet.jsp.JspWriter; +import javax.servlet.jsp.JspTagException; +import javax.servlet.jsp.tagext.BodyContent; +import javax.servlet.jsp.tagext.BodyTagSupport; + +/** + * Custom Tag class to access the {@linkplain com.fredck.FCKeditor.FCKeditor container}.<br> + *<p> + * <b>Simple usage</b>: + * <pre> + * <FCK:editor + * id="EditorAccessibility" + * width="80%" + * height="120" + * toolbarSet="Accessibility" + * ">This is another test. <BR><BR>The "Second" row.</BR></FCK:editor"> + * </pre> + * + *<p>In this example we set all the attribute for the fckedit tag. + * + *<p> + * <b>Advanced usage of the tag</b>: + * <pre> + * <FCK:editor id="EditorDefault" basePath="/FCKeditor/" + * styleNames=";Style 1;Style 2; Style 3" + * fontNames=";Arial;Courier New;Times New Roman;Verdana" > + * This is some <B>sample text</B>. + * </FCK:editor> +* </pre> + *<p>In this example we set the id and the basePath of the editor (since it is /FCKeditor/ + * we could have omitted it because it's already the default value).<br> + * Then we used the the optional attributes to set some advanced configuration settings. + * + + * @author Simone Chiaretta (simo ¡÷ users.sourceforge.net) + */ +public class FCKeditorTag extends BodyTagSupport { + + private String id; + private String value = ""; + private String basePath = null; + private String toolbarSet = null; + private String width = null; + private String height = null; + private String customConfigurationsPath = null; + private String editorAreaCSS = null; + private String baseHref = null; + private String skinPath = null; + private String pluginsPath = null; + private String fullPage = null; + private String debug = null; + private String autoDetectLanguage = null; + private String defaultLanguage = null; + private String contentLangDirection = null; + private String enableXHTML = null; + private String enableSourceXHTML = null; + private String fillEmptyBlocks = null; + private String formatSource = null; + private String formatOutput = null; + private String formatIndentator = null; + private String geckoUseSPAN = null; + private String startupFocus = null; + private String forcePasteAsPlainText = null; + private String forceSimpleAmpersand = null; + private String tabSpaces = null; + private String useBROnCarriageReturn = null; + private String toolbarStartExpanded = null; + private String toolbarCanCollapse = null; + private String fontColors = null; + private String fontNames = null; + private String fontSizes = null; + private String fontFormats = null; + private String stylesXmlPath = null; + private String linkBrowserURL = null; + private String imageBrowserURL = null; + private String flashBrowserURL = null; + private String linkUploadURL = null; + private String imageUploadURL = null; + private String flashUploadURL = null; + + + + + /** + * The underlying FCKeditor object + * + */ + protected FCKeditor fcked = null; + + + /** + * Set the unique id of the editor + * + * @param value name + */ + public void setId(String value) { + id=value; + } + + /** + * Set the dir where the FCKeditor files reside on the server + * + * @param value path + */ + public void setBasePath(String value) { + basePath=value; + } + + /** + * Set the name of the toolbar to display + * + * @param value toolbar name + */ + public void setToolbarSet(String value) { + toolbarSet=value; + } + + /** + * Set the width of the textarea + * + * @param value width + */ + public void setWidth(String value) { + width=value; + } + + /** + * Set the height of the textarea + * + * @param value height + */ + public void setHeight(String value) { + height=value; + } + + /** + * Set the path of a custom file that can override some configurations.<br> + * It is recommended to use absolute paths (starting with /), like "/myfckconfig.js". + * + * @param value path + */ + public void setCustomConfigurationsPath(String value) { + customConfigurationsPath=value; + } + + + /** + * Set the CSS styles file to be used in the editing area.<br> + * In this way you can point to a file that reflects your web site styles. + * + * @param value path + */ + public void setEditorAreaCSS(String value) { + editorAreaCSS=value; + } + + + /** + * Base URL used to resolve links (on images, links, styles, etc.).<br> + * For example, if BaseHref is set to 'http://www.fredck.com', an image that points to "/images/Logo.gif" will be interpreted by the editor as "http://www.fredck.com/images/Logo.gif", without touching the "src" attribute of the image. + * + * @param value URL + */ + public void setBaseHref(String value) { + baseHref=value; + } + + + /** + * Sets the path to the skin (graphical interface settings) to be used by the editor. + * + * @param value path + */ + public void setSkinPath(String value) { + skinPath=value; + } + + + /** + * Sets the base path used when looking for registered plugins. + * + * @param value path + */ + public void setPluginsPath(String value) { + pluginsPath=value; + } + + + /** + * Enables full page editing (from <HTML> to </HTML>).<br> + * It also enables the "Page Properties" toolbar button. + * + * @param value true/false + * @throws JspException if value is not true or false + */ + public void setFullPage(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("fullPage attribute can only be true or false"); + fullPage=value; + } + + + /** + * Enables the debug window to be shown when calling the FCKDebug.Output() function. + * + * @param value true/false + * @throws JspException if value is not true or false + */ + public void setDebug(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("debug attribute can only be true or false"); + debug=value; + } + + + /** + * Tells the editor to automatically detect the user language preferences to adapt its interface language.<br> + * With Internet Explorer, the language configured in the Windows Control Panel is used.<br> + * With Firefox, the browser language is used. + * + * @param value true/false + * @throws JspException if value is not true or false + */ + public void setAutoDetectLanguage(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("autoDetectLanguage attribute can only be true or false: here was " + value); + autoDetectLanguage=value; + } + + + /** + * Sets the default language used for the editor's interface localization.<br> + * The default language is used when the AutoDetectLanguage options is disabled or when the user language is not available. + * + * @param value language code + */ + public void setDefaultLanguage(String value) { + defaultLanguage=value; + } + + + /** + * Sets the direction of the editor area contents.<br> + * The possible values are: + * <ul> + * <li>ltr - Left to Right + * <li>rtl - Right to Left + * </ul> + * + * @param value ltr/rtl + * @throws JspException if value is not ltr or rtl + */ + public void setContentLangDirection(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("debug attribute can only be ltr or rtl"); + contentLangDirection=value; + } + + + /** + * Tells the editor to process the HTML source to XHTML on form post. + * + * @param value true/false + * @throws JspException if value is not true or false + */ + public void setEnableXHTML(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("enableXHTML attribute can only be true or false"); + enableXHTML=value; + } + + + /** + * Tells the editor to process the HTML source to XHTML when switching from WYSIWYG to Source view + * + * @param value true/false + * @throws JspException if value is not true or false + */ + public void setEnableSourceXHTML(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("enableSourceXHTML attribute can only be true or false"); + enableSourceXHTML=value; + } + + + /** + * Block elements (like P, DIV, H1, PRE, etc...) are forced to have content (a &nbsp;).<br> + * Empty blocks are "collapsed" by while browsing, so a empty <p></p> is not visible.<br> + * While editing, the editor "expand" empty blocks so you can insert content inside then.<br> + * Setting this option to "true" results useful to reflect the same output when browsing and editing. + * + * @param value true/false + * @throws JspException if value is not true or false + */ + public void setFillEmptyBlocks(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("fillEmptyBlocks attribute can only be true or false"); + fillEmptyBlocks=value; + } + + + /** + * The HTML shown by the editor, while switching from WYSIWYG to Source views, will be processed and formatted + * + * @param value true/false + * @throws JspException if value is not true or false + */ + public void setFormatSource(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("formatSource attribute can only be true or false"); + formatSource=value; + } + + + /** + * The output HTML generated by the editor will be processed and formatted. + * + * @param value true/false + * @throws JspException if value is not true or false + */ + public void setFormatOutput(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("formatOutput attribute can only be true or false"); + formatOutput=value; + } + + /** + * Sets the characters to be used when indenting the HTML source when formatting it.<BR> + * Useful values are a sequence of spaces (' ') or a tab char ('\t'). + * + * @param value indentator + */ + public void setFormatIndentator(String value) { + formatIndentator=value; + } + + + /** + * Tells Gecko browsers to use SPAN instead of <B>, <I> and <U> for bold, italic an underline + * + * @param value true/false + * @throws JspException if value is not true or false + */ + public void setGeckoUseSPAN(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("GeckoUseSPAN attribute can only be true or false"); + geckoUseSPAN=value; + } + + + /** + * Forces the editor to get the keyboard input focus on startup (page load) + * + * @param value true/false + * @throws JspException if value is not true or false + */ + public void setStartupFocus(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("startupFocus attribute can only be true or false"); + startupFocus=value; + } + + + /** + * Converts the clipboard contents to pure text on pasting operations + * + * @param value true/false + * @throws JspException if value is not true or false + */ + public void setForcePasteAsPlainText(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("forcePasteAsPlainText attribute can only be true or false"); + forcePasteAsPlainText=value; + } + + + /** + * Forces the ampersands (&) on tags attributes to not be converted to "&amp;"<BR> + * This conversion is a W3C requirement for XHTML, so it is recommended to leave this option to "false". + * + * @param value true/false + * @throws JspException if value is not true or false + */ + public void setForceSimpleAmpersand(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("forceSimpleAmpersand attribute can only be true or false"); + forceSimpleAmpersand=value; + } + + + /** + * Set the number of spaces (&nbsp;) to be inserted when the user hits the "tab" key.<BR> + * This is an Internet Explorer only feature. Other browsers insert spaces automatically by default. + * + * @param value number of spaces + */ + public void setTabSpaces(String value) { + tabSpaces=value; + } + + + /** + * Inserts a <BR> tag when the user hits the "enter" key, instead of starting a new paragraph (<P> or <DIV>).<BR> + * This is an Internet Explorer only feature. Other browsers insert the <BR> tag by default. + * + * @param value true/false + * @throws JspException if value is not true or false + */ + public void setUseBROnCarriageReturn(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("useBROnCarriageReturn attribute can only be true or false"); + useBROnCarriageReturn=value; + } + + + /** + * The toolbar is Expanded on startup, otherwise it is Collapsed and the user must click on it to show it. + * + * @param value true/false + * @throws JspException if value is not true or false + */ + public void setToolbarStartExpanded(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("ToolbarStartExpanded attribute can only be true or false"); + toolbarStartExpanded=value; + } + + + /** + * Tells the editor that the toolbar can be Collapsed/Expanded by the user when clicking the vertical bar placed on the left of it (on the right for "rtl" languages). + * + * @param value true/false + * @throws JspException if value is not true or false + */ + public void setToolbarCanCollapse(String value) throws JspException { + if(! value.equals("true") && ! value.equals("false")) + throw new JspException("ToolbarCanCollapse attribute can only be true or false"); + toolbarCanCollapse=value; + } + + + /** + * Sets the colors that must be shown in the colors panels (in the toolbar). + * + * @param value colors + */ + public void setFontColors(String value) { + fontColors=value; + } + + + /** + * Sets the list of fonts to be shown in the "Font" toolbar command. + * + * @param value fonts + */ + public void setFontNames(String value) { + fontNames=value; + } + + + /** + * Sets the list of font sizes to be shown in the "Size" toolbar command. + * + * @param value sizes + */ + public void setFontSizes(String value) { + fontSizes=value; + } + + + /** + * Sets the list of formats to be shown in the "Format" toolbar command. + * + * @param value format list + */ + public void setFontFormats(String value) { + fontFormats=value; + } + + + /** + * Sets the path to the XML file that has the definitions and rules of the styles used by the "Style" toolbar command + * + * @param value path + */ + public void setStylesXmlPath(String value) { + stylesXmlPath=value; + } + + + /** + * Sets the URL of the page called when the user clicks the "Browse Server" button in the "Link" dialog window.<BR> + * In this way, you can create your custom File Browser that is well integrated with your system. + * + * @param value path + */ + public void setLinkBrowserURL(String value) { + linkBrowserURL=value; + } + + + /** + * Sets the URL of the page called when the user clicks the "Browse Server" button in the "Image" dialog window.<BR> + * In this way, you can create your custom Image Browser that is well integrated with your system. + * + * @param value path + */ + public void setImageBrowserURL(String value) { + imageBrowserURL=value; + } + + /** + * Sets the URL of the page called when the user clicks the "Browse Server" button in the "Flash" dialog window.<BR> + * In this way, you can create your custom Flash Browser that is well integrated with your system. + * + * @param value path + */ + public void setFlashBrowserURL(String value) { + flashBrowserURL=value; + } + + + /** + * Sets the URL of the upload handler called when the user clicks the "Send it to server" button in the "Link" dialog window.<BR> + * In this way, you can create your custom Link Uploader that is well integrated with your system. + * + * @param value path + */ + public void setLinkUploadURL(String value) { + linkUploadURL=value; + } + + + /** + * Sets the URL of the upload handler called when the user clicks the "Send it to server" button in the "Image" dialog window.<BR> + * In this way, you can create your custom Image Uploader that is well integrated with your system. + * + * @param value path + */ + public void setImageUploadURL(String value) { + imageUploadURL=value; + } + + + /** + * Sets the URL of the upload handler called when the user clicks the "Send it to server" button in the "Flash" dialog window.<BR> + * In this way, you can create your custom Flash Uploader that is well integrated with your system. + * + * @param value path + */ + public void setFlashUploadURL(String value) { + flashUploadURL=value; + } + + + /** + * Initialize the FCKeditor container and set attributes + * + * @return EVAL_BODY_BUFFERED + */ + public int doStartTag() throws JspException { + fcked=new FCKeditor((HttpServletRequest)pageContext.getRequest(),id); + if(toolbarSet!=null) + fcked.setToolbarSet(toolbarSet); + if(basePath!=null) + fcked.setBasePath(basePath); + if(width!=null) + fcked.setWidth(width); + if(height!=null) + fcked.setHeight(height); + if (customConfigurationsPath != null) + fcked.getConfig().put("CustomConfigurationsPath",customConfigurationsPath); + if (editorAreaCSS != null) + fcked.getConfig().put("EditorAreaCSS",editorAreaCSS); + if (baseHref != null) + fcked.getConfig().put("BaseHref",baseHref); + if (skinPath != null) + fcked.getConfig().put("SkinPath",skinPath); + if (pluginsPath != null) + fcked.getConfig().put("PluginsPath",pluginsPath); + if (fullPage != null) + fcked.getConfig().put("FullPage",fullPage); + if (debug != null) + fcked.getConfig().put("Debug",debug); + if (autoDetectLanguage != null) + fcked.getConfig().put("AutoDetectLanguage",autoDetectLanguage); + if (defaultLanguage != null) + fcked.getConfig().put("DefaultLanguage",defaultLanguage); + if (contentLangDirection != null) + fcked.getConfig().put("ContentLangDirection",contentLangDirection); + if (enableXHTML != null) + fcked.getConfig().put("EnableXHTML",enableXHTML); + if (enableSourceXHTML != null) + fcked.getConfig().put("EnableSourceXHTML",enableSourceXHTML); + if (fillEmptyBlocks != null) + fcked.getConfig().put("FillEmptyBlocks",fillEmptyBlocks); + if (formatSource != null) + fcked.getConfig().put("FormatSource",formatSource); + if (formatOutput != null) + fcked.getConfig().put("FormatOutput",formatOutput); + if (formatIndentator != null) + fcked.getConfig().put("FormatIndentator",formatIndentator); + if (geckoUseSPAN != null) + fcked.getConfig().put("GeckoUseSPAN",geckoUseSPAN); + if (startupFocus != null) + fcked.getConfig().put("StartupFocus",startupFocus); + if (forcePasteAsPlainText != null) + fcked.getConfig().put("ForcePasteAsPlainText",forcePasteAsPlainText); + if (forceSimpleAmpersand != null) + fcked.getConfig().put("ForceSimpleAmpersand",forceSimpleAmpersand); + if (tabSpaces != null) + fcked.getConfig().put("TabSpaces",tabSpaces); + if (useBROnCarriageReturn != null) + fcked.getConfig().put("UseBROnCarriageReturn",useBROnCarriageReturn); + if (toolbarStartExpanded != null) + fcked.getConfig().put("ToolbarStartExpanded",toolbarStartExpanded); + if (toolbarCanCollapse != null) + fcked.getConfig().put("ToolbarCanCollapse",toolbarCanCollapse); + if (fontColors != null) + fcked.getConfig().put("FontColors",fontColors); + if (fontNames != null) + fcked.getConfig().put("FontNames",fontNames); + if (fontSizes != null) + fcked.getConfig().put("FontSizes",fontSizes); + if (fontFormats != null) + fcked.getConfig().put("FontFormats",fontFormats); + if (stylesXmlPath != null) + fcked.getConfig().put("StylesXmlPath",stylesXmlPath); + if (linkBrowserURL != null) + fcked.getConfig().put("LinkBrowserURL",linkBrowserURL); + if (imageBrowserURL != null) + fcked.getConfig().put("ImageBrowserURL",imageBrowserURL); + if (flashBrowserURL != null) + fcked.getConfig().put("FlashBrowserURL",flashBrowserURL); + if (linkUploadURL != null) + fcked.getConfig().put("LinkUploadURL",linkUploadURL); + if (imageUploadURL != null) + fcked.getConfig().put("ImageUploadURL",imageUploadURL); + if (flashUploadURL != null) + fcked.getConfig().put("FlashUploadURL",flashUploadURL); + + return EVAL_BODY_BUFFERED; + } + + /** + * Retrive initial value to be edited and writes the HTML code in the page + * + * @return SKIP_BODY + * @throws JspException if an error occurs while writing to the out buffer + */ + public int doAfterBody() throws JspException { + BodyContent body = getBodyContent(); + JspWriter writer = body.getEnclosingWriter(); + String bodyString = body.getString(); + fcked.setValue(bodyString); + try { + writer.println(fcked.create()); + }catch(IOException ioe) { + throw new JspException("Error: IOException while writing to the user"); + } + + return SKIP_BODY; + } + +} \ No newline at end of file Added: pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/uploader/SimpleUploaderServlet.java =================================================================== --- pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/uploader/SimpleUploaderServlet.java (rev 0) +++ pal-wcm/trunk/src/main/java/jp/sf/pal/wcm/uploader/SimpleUploaderServlet.java 2008-05-21 06:38:44 UTC (rev 943) @@ -0,0 +1,252 @@ +/* + * FCKeditor - The text editor for internet + * Copyright (C) 2003-2005 Frederico Caldeira Knabben + * + * Licensed under the terms of the GNU Lesser General Public License: + * http://www.opensource.org/licenses/lgpl-license.php + * + * For further information visit: + * http://www.fckeditor.net/ + * + * File Name: SimpleUploaderServlet.java + * Java File Uploader class. + * + * Version: 2.3 + * Modified: 2005-08-11 16:29:00 + * + * File Authors: + * Simone Chiaretta (simo ¡÷ users.sourceforge.net) + */ + +package jp.sf.pal.wcm.uploader; + +import java.io.*; +import javax.servlet.*; +import javax.servlet.http.*; +import java.util.*; + + +import org.apache.commons.fileupload.*; + + +import javax.xml.parsers.*; +import org.w3c.dom.*; +import javax.xml.transform.*; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + + +/** + * Servlet to upload files.<br> + * + * This servlet accepts just file uploads, eventually with a parameter specifying file type + * + * @author Simone Chiaretta (simo ¡÷ users.sourceforge.net) + */ + +public class SimpleUploaderServlet extends HttpServlet { + + private static String baseDir; + private static boolean debug=false; + private static boolean enabled=false; + private static Hashtable allowedExtensions; + private static Hashtable deniedExtensions; + + /** + * Initialize the servlet.<br> + * Retrieve from the servlet configuration the "baseDir" which is the root of the file repository:<br> + * If not specified the value of "/UserFiles/" will be used.<br> + * Also it retrieve all allowed and denied extensions to be handled. + * + */ + public void init() throws ServletException { + + debug=(new Boolean(getInitParameter("debug"))).booleanValue(); + + if(debug) System.out.println("\r\n---- SimpleUploaderServlet initialization started ----"); + + baseDir=getInitParameter("baseDir"); + enabled=(new Boolean(getInitParameter("enabled"))).booleanValue(); + if(baseDir==null) + baseDir="/UserFiles/"; + String realBaseDir=getServletContext().getRealPath(baseDir); + File baseFile=new File(realBaseDir); + if(!baseFile.exists()){ + baseFile.mkdir(); + } + + allowedExtensions = new Hashtable(3); + deniedExtensions = new Hashtable(3); + + allowedExtensions.put("File",stringToArrayList(getInitParameter("AllowedExtensionsFile"))); + deniedExtensions.put("File",stringToArrayList(getInitParameter("DeniedExtensionsFile"))); + + allowedExtensions.put("Image",stringToArrayList(getInitParameter("AllowedExtensionsImage"))); + deniedExtensions.put("Image",stringToArrayList(getInitParameter("DeniedExtensionsImage"))); + + allowedExtensions.put("Flash",stringToArrayList(getInitParameter("AllowedExtensionsFlash"))); + deniedExtensions.put("Flash",stringToArrayList(getInitParameter("DeniedExtensionsFlash"))); + + if(debug) System.out.println("---- SimpleUploaderServlet initialization completed ----\r\n"); + + } + + + /** + * Manage the Upload requests.<br> + * + * The servlet accepts commands sent in the following format:<br> + * simpleUploader?Type=ResourceType<br><br> + * It store the file (renaming it in case a file with the same name exists) and then return an HTML file + * with a javascript command in it. + * + */ + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + if (debug) System.out.println("--- BEGIN DOPOST ---"); + + response.setContentType("text/html; charset=UTF-8"); + response.setHeader("Cache-Control","no-cache"); + PrintWriter out = response.getWriter(); + + + String typeStr=request.getParameter("Type"); + + String currentPath=baseDir+typeStr; + String currentDirPath=getServletContext().getRealPath(currentPath); + currentPath=request.getContextPath()+currentPath; + + if (debug) System.out.println(currentDirPath); + + String retVal="0"; + String newName=""; + String fileUrl=""; + String errorMessage=""; + + if(enabled) { + DiskFileUpload upload = new DiskFileUpload(); + try { + List items = upload.parseRequest(request); + + Map fields=new HashMap(); + + Iterator iter = items.iterator(); + while (iter.hasNext()) { + FileItem item = (FileItem) iter.next(); + if (item.isFormField()) + fields.put(item.getFieldName(),item.getString()); + else + fields.put(item.getFieldName(),item); + } + FileItem uplFile=(FileItem)fields.get("NewFile"); + String fileNameLong=uplFile.getName(); + fileNameLong=fileNameLong.replace('\\','/'); + String[] pathParts=fileNameLong.split("/"); + String fileName=pathParts[pathParts.length-1]; + + String nameWithoutExt=getNameWithoutExtension(fileName); + String ext=getExtension(fileName); + File pathToSave=new File(currentDirPath,fileName); + fileUrl=currentPath+"/"+fileName; + if(extIsAllowed(typeStr,ext)) { + int counter=1; + while(pathToSave.exists()){ + newName=nameWithoutExt+"("+counter+")"+"."+ext; + fileUrl=currentPath+"/"+newName; + retVal="201"; + pathToSave=new File(currentDirPath,newName); + counter++; + } + uplFile.write(pathToSave); + } + else { + retVal="202"; + errorMessage=""; + if (debug) System.out.println("Invalid file type: " + ext); + } + }catch (Exception ex) { + if (debug) ex.printStackTrace(); + retVal="203"; + } + } + else { + retVal="1"; + errorMessage="This file uploader is disabled. Please check the WEB-INF/web.xml file"; + } + + + out.println("<script type=\"text/javascript\">"); + out.println("window.parent.OnUploadCompleted("+retVal+",'"+fileUrl+"','"+newName+"','"+errorMessage+"');"); + out.println("</script>"); + out.flush(); + out.close(); + + if (debug) System.out.println("--- END DOPOST ---"); + + } + + + /* + * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF bug #991489 + */ + private static String getNameWithoutExtension(String fileName) { + return fileName.substring(0, fileName.lastIndexOf(".")); + } + + /* + * This method was fixed after Kris Barnhoorn (kurioskronic) submitted SF bug #991489 + */ + private String getExtension(String fileName) { + return fileName.substring(fileName.lastIndexOf(".")+1); + } + + + + /** + * Helper function to convert the configuration string to an ArrayList. + */ + + private ArrayList stringToArrayList(String str) { + + if(debug) System.out.println(str); + String[] strArr=str.split("\\|"); + + ArrayList tmp=new ArrayList(); + if(str.length()>0) { + for(int i=0;i<strArr.length;++i) { + if(debug) System.out.println(i +" - "+strArr[i]); + tmp.add(strArr[i].toLowerCase()); + } + } + return tmp; + } + + + /** + * Helper function to verify if a file extension is allowed or not allowed. + */ + + private boolean extIsAllowed(String fileType, String ext) { + + ext=ext.toLowerCase(); + + ArrayList allowList=(ArrayList)allowedExtensions.get(fileType); + ArrayList denyList=(ArrayList)deniedExtensions.get(fileType); + + if(allowList.size()==0) + if(denyList.contains(ext)) + return false; + else + return true; + + if(denyList.size()==0) + if(allowList.contains(ext)) + return true; + else + return false; + + return false; + } + +} + Added: pal-wcm/trunk/src/main/webapp/WEB-INF/tld/FCKeditor.tld =================================================================== --- pal-wcm/trunk/src/main/webapp/WEB-INF/tld/FCKeditor.tld (rev 0) +++ pal-wcm/trunk/src/main/webapp/WEB-INF/tld/FCKeditor.tld 2008-05-21 06:38:44 UTC (rev 943) @@ -0,0 +1,214 @@ +<?xml version="1.0" encoding="ISO-8859-1" ?> +<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> + +<taglib> + <tlibversion>2.3</tlibversion> + <jspversion>1.1</jspversion> + <shortname>FCKeditor</shortname> + <uri>http://fckeditor.net/tags-fckeditor</uri> + <info>FCKeditor taglib</info> + <tag> + <name>editor</name> + <tagclass>jp.sf.pal.wcm.tags.FCKeditorTag</tagclass> + <bodycontent>JSP</bodycontent> + <attribute> + <name>id</name> + <required>true</required> + </attribute> + <attribute> + <name>basePath</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>toolbarSet</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>width</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>height</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>customConfigurationsPath</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>editorAreaCSS</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>baseHref</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>skinPath</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>pluginsPath</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>fullPage</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>debug</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>autoDetectLanguage</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>defaultLanguage</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>contentLangDirection</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>enableXHTML</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>enableSourceXHTML</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>fillEmptyBlocks</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>formatSource</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>formatOutput</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>formatIndentator</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>geckoUseSPAN</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>startupFocus</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>forcePasteAsPlainText</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>forceSimpleAmpersand</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>tabSpaces</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>useBROnCarriageReturn</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>toolbarStartExpanded</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>toolbarCanCollapse</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>fontColors</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>fontNames</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>fontSizes</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>fontFormats</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>stylesXmlPath</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>linkBrowserURL</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>imageBrowserURL</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>flashBrowserURL</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>linkUploadURL</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>imageUploadURL</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>flashUploadURL</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + </tag> +</taglib> \ No newline at end of file Added: pal-wcm/trunk/src/main/webapp/WEB-INF/tld/portlet.tld =================================================================== --- pal-wcm/trunk/src/main/webapp/WEB-INF/tld/portlet.tld (rev 0) +++ pal-wcm/trunk/src/main/webapp/WEB-INF/tld/portlet.tld 2008-05-21 06:38:44 UTC (rev 943) @@ -0,0 +1,103 @@ +<?xml version="1.0" encoding="ISO-8859-1" ?> +<!-- +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +--> +<!DOCTYPE taglib PUBLIC + "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" + "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> +<taglib> + <tlibversion>1.0</tlibversion> + <jspversion>1.1</jspversion> + <shortname>Tags for portlets</shortname> + <tag> + <name>defineObjects</name> + <tagclass>org.apache.pluto.tags.DefineObjectsTag</tagclass> + <teiclass>org.apache.pluto.tags.DefineObjectsTag$TEI</teiclass> + <bodycontent>empty</bodycontent> + </tag> + <tag> + <name>param</name> + <tagclass>org.apache.pluto.tags.ParamTag</tagclass> + <bodycontent>empty</bodycontent> + <attribute> + <name>name</name> + <required>true</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>value</name> + <required>true</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + </tag> + <tag> + <name>actionURL</name> + <tagclass>org.apache.pluto.tags.ActionURLTag</tagclass> + <teiclass>org.apache.pluto.tags.BasicURLTag$TEI</teiclass> + <bodycontent>JSP</bodycontent> + <attribute> + <name>windowState</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>portletMode</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>secure</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>var</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + </tag> + <tag> + <name>renderURL</name> + <tagclass>org.apache.pluto.tags.RenderURLTag</tagclass> + <teiclass>org.apache.pluto.tags.BasicURLTag$TEI</teiclass> + <bodycontent>JSP</bodycontent> + <attribute> + <name>windowState</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>portletMode</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>secure</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + <attribute> + <name>var</name> + <required>false</required> + <rtexprvalue>true</rtexprvalue> + </attribute> + </tag> + <tag> + <name>namespace</name> + <tagclass>org.apache.pluto.tags.NamespaceTag</tagclass> + <bodycontent>empty</bodycontent> + </tag> +</taglib> Modified: pal-wcm/trunk/src/main/webapp/WEB-INF/web.xml =================================================================== --- pal-wcm/trunk/src/main/webapp/WEB-INF/web.xml 2008-05-19 05:31:45 UTC (rev 942) +++ pal-wcm/trunk/src/main/webapp/WEB-INF/web.xml 2008-05-21 06:38:44 UTC (rev 943) @@ -20,6 +20,7 @@ <web-app> <display-name>WCM Portlet</display-name> <description>Web Content Management for PAL Portal.</description> +<!-- <servlet> <servlet-name>FileuploadServlet</servlet-name> <servlet-class>jp.sf.pal.wcm.servlet.FileuploadServlet</servlet-class> @@ -32,10 +33,6 @@ <servlet-name>FileconnectorServlet</servlet-name> <servlet-class>jp.sf.pal.wcm.servlet.FileconnectorServlet</servlet-class> </servlet> - <servlet> - <servlet-name>FilesaveServlet</servlet-name> - <servlet-class>jp.sf.pal.wcm.servlet.FilesaveServlet</servlet-class> - </servlet> <servlet-mapping> <servlet-name>FileuploadServlet</servlet-name> <url-pattern>/fileupload</url-pattern> @@ -48,8 +45,81 @@ <servlet-name>FileconnectorServlet</servlet-name> <url-pattern>/fileconnector</url-pattern> </servlet-mapping> +--> + <servlet> + <servlet-name>FilesaveServlet</servlet-name> + <servlet-class>jp.sf.pal.wcm.servlet.FilesaveServlet</servlet-class> + </servlet> + + <servlet> + <servlet-name>Connector</servlet-name> + <servlet-class>jp.sf.pal.wcm.connector.ConnectorServlet</servlet-class> + <init-param> + <param-name>baseDir</param-name> + <param-value>/UserFiles/</param-value> + </init-param> + <init-param> + <param-name>debug</param-name> + <param-value>false</param-value> + </init-param> + <load-on-startup>1</load-on-startup> + </servlet> + + <servlet> + <servlet-name>SimpleUploader</servlet-name> + <servlet-class>jp.sf.pal.wcm.uploader.SimpleUploaderServlet</servlet-class> + <init-param> + <param-name>baseDir</param-name> + <param-value>/UserFiles/</param-value> + </init-param> + <init-param> + <param-name>debug</param-name> + <param-value>false</param-value> + </init-param> + <init-param> + <param-name>enabled</param-name> + <param-value>true</param-value> + </init-param> + <init-param> + <param-name>AllowedExtensionsFile</param-name> + <param-value></param-value> + </init-param> + <init-param> + <param-name>DeniedExtensionsFile</param-name> + <param-value>php|php3|php5|phtml|asp|aspx|ascx|jsp|cfm|cfc|pl|bat|exe|dll|reg|cgi</param-value> + </init-param> + <init-param> + <param-name>AllowedExtensionsImage</param-name> + <param-value>jpg|gif|jpeg|png|bmp</param-value> + </init-param> + <init-param> + <param-name>DeniedExtensionsImage</param-name> + <param-value></param-value> + </init-param> + <init-param> + <param-name>AllowedExtensionsFlash</param-name> + <param-value>swf|fla</param-value> + </init-param> + <init-param> + <param-name>DeniedExtensionsFlash</param-name> + <param-value></param-value> + </init-param> + <load-on-startup>1</load-on-startup> + </servlet> + <servlet-mapping> <servlet-name>FilesaveServlet</servlet-name> <url-pattern>/filesave</url-pattern> </servlet-mapping> + + <servlet-mapping> + <servlet-name>Connector</servlet-name> + <url-pattern>/fckeditor/editor/filemanager/browser/default/connectors/jsp/connector</url-pattern> + </servlet-mapping> + + <servlet-mapping> + <servlet-name>SimpleUploader</servlet-name> + <url-pattern>/fckeditor/editor/filemanager/upload/simpleuploader</url-pattern> + </servlet-mapping> + </web-app> Modified: pal-wcm/trunk/src/main/webapp/index.jsp =================================================================== --- pal-wcm/trunk/src/main/webapp/index.jsp 2008-05-19 05:31:45 UTC (rev 942) +++ pal-wcm/trunk/src/main/webapp/index.jsp 2008-05-21 06:38:44 UTC (rev 943) @@ -1,3 +1,4 @@ +<%@ taglib uri="/WEB-INF/tld/FCKeditor.tld" prefix="FCK" %> <%@ page language="java" import="jp.sf.pal.wcm.*, java.util.*, java.io.File, java.io.FileReader, java.io.BufferedReader, javax.servlet.ServletContext" %> <!-- * FCKeditor - The text editor for internet @@ -55,12 +56,17 @@ } catch (Exception e){ e.printStackTrace(); } -FCKeditor oFCKeditor ; -oFCKeditor = new FCKeditor( request, "EditorDefault" ) ; -oFCKeditor.setBasePath( "/FCKeditor/" ) ; -oFCKeditor.setValue( contents ); -out.println( oFCKeditor.create() ) ; %> + <FCK:editor id="EditorDefault" basePath="fckeditor/" + imageBrowserURL="/pal-wcm/fckeditor/editor/filemanager/browser/default/browser.html?Type=Image&Connector=connectors/jsp/connector" + linkBrowserURL="/pal-wcm/fckeditor/editor/filemanager/browser/default/browser.html?Connector=connectors/jsp/connector" + flashBrowserURL="/pal-wcm/fckeditor/editor/filemanager/browser/default/browser.html?Type=Flash&Connector=connectors/jsp/connector" + imageUploadURL="/pal-wcm/fckeditor/editor/filemanager/upload/simpleuploader?Type=Image" + linkUploadURL="/pal-wcm/fckeditor/editor/filemanager/upload/simpleuploader?Type=File" + flashUploadURL="/pal-wcm/fckeditor/editor/filemanager/upload/simpleuploader?Type=Flash"> + <%= contents %> + </FCK:editor> + <br> <input type="submit" value="Submit"> <input type="hidden" name="fragID" value="<%=fragID%>">