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 @@
+ *
+ * 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.
+ *
+ *
+ *
+ *
^ 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 + * singleSome 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
-
-
- - - - |
- - - | -
- - | -- - | -- - | -
- - | -- - | -- - | -
-
- - - |
-
+
+
+
+
- |
- ||
+ + + | -||
- - | -||
-
|
-
+ | + + + + | +
Error Message | +
+
+
+ URL: + |
+ ||||||||||||
+ + | +
+
+
+ Post URL: + |
+ ||||||||
+ + | +
\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;i
'+FCKLang.ColorAutomatic+' | \n
'+FCKLang.ColorMoreColors+' |
'+this.Caption+' |
');if ((C!=-1&&D!=-1&&C
';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;i
');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;i
'+FCKLang.ColorAutomatic+' | \n
'+FCKLang.ColorMoreColors+' |
'+this.Caption+' |
+ 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 +
+, 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
Folder permission.
- *This code was partially inspired from:
+ *+ * Folder permission. + *
+ *+ * This code was partially inspired from: + *
*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: + **
- *
- *
+ *
+ *
Fragment permission.
- *This code was partially inspired from articles from:
+ *+ * Fragment permission. + *
+ *+ * This code was partially inspired from articles from: + *
*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 theSubject
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: + *
*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: + *
*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()
.
+ *
Portlet permission.
- *This code was partially inspired from articles from:
+ *+ * Portlet permission. + *
+ *+ * This code was partially inspired from articles from: + *
*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 arenull
- * @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* doRemove *
- * + * * @param file - * @returntrue
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: ** 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.
*
* 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 therelativePath
- * 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. *
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-@@ -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( "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;iJobEntry
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
*
* 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 theId
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
- * + * *
+ * * @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 invokingNode.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
* getType
*
* getHandlerFactory
*
* setHandlerFactory
*
* 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
*
* getDocumentHandlerForPath
*
* getPermissionsEnabled
*
* setPermissionsEnabled
*
* getConstraintsEnabled
*
* setConstraintsEnabled
*
* getChildNodes
*
* 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
*
* getPattern
* 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 @@
*
* 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; i
@@ -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("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 @@ * * * @authorinit()
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. *
*
* 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. *
*
* 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 * ifnavClassName
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 patchreset 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: *
- * 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:
*
* 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 configjava.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 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 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 org.apache.jetspeed.decoration.Theme
*
* @author org.apache.jetspeed.decoration.PortletDecoration
- *
+ * Default implementation of
+ * org.apache.jetspeed.decoration.PortletDecoration
+ *
* @author java.util.HashMap
to cache previously located
- * resources pathes.
+ * Uses a java.util.HashMap
to cache previously located resources
+ * pathes.
*
* @author ClassLoader.getResource()
to
- * validate the existence of a resource.
+ * This implementation uses ClassLoader.getResource()
to validate
+ * the existence of a resource.
*
* @author ServletContext.getResource()
- * to verify the existence of a resource.
+ * This implementation uses ServletContext.getResource()
to
+ * verify the existence of a resource.
*
* @author 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 therun()
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 commonsConfiguration
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 firstGET
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 thegetPortalInfo
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; iorg.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) Stack Trace:
"); for (int i = 0; i < traceArray.length; i++) { - pw.write(" " + traceArray[i].toString() + "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* 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 ajavax.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 ajava.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 ornull
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
*
- * 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:
* The user is successfully authenticated and authorized by Ntml authentication
- *A Subject is created, with Principal derived from the remoteUser value from Ntlm authentication
- *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.
- *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. - *
- *+ * The user is successfully authenticated and authorized by Ntml + * authentication + *
+ *+ * A Subject is created, with Principal derived from the remoteUser value from + * Ntlm authentication + *
+ *+ * 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. + *
+ *+ * 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. + *
+ *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("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-serializngobjToClone
+ * 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" + - "@@ -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 thepath
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; iTestSuite
) 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 @@ ** 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 thisjavax.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 ifwhenExhausted
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 attributebatch-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 - *MutableDescription
- * interface.
+ * DescriptionImpl 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
- * 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.
- * * 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. * * @authornull
* 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
- * * 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; i
- * 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.
*
* 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
- //
- //