incubator-graffito-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From tay...@apache.org
Subject svn commit: r158983 - in incubator/graffito/trunk/applications/graffito-portlets/src: ./ java/ java/org/ java/org/apache/ java/org/apache/portals/ java/org/apache/portals/graffito/ java/org/apache/portals/graffito/portlets/ java/org/apache/portals/graffito/portlets/tree/ java/org/apache/portals/graffito/portlets/util/
Date Fri, 25 Mar 2005 02:21:37 GMT
Author: taylor
Date: Thu Mar 24 18:21:35 2005
New Revision: 158983

URL: http://svn.apache.org/viewcvs?view=rev&rev=158983
Log:
graffito portlets jar project
 - note this is not a portlet application, but a collection of portlets to be reused in other portlet applications

3 new portlets:

1. Tree Portlet - a tree view over a Graffito URI space rooted in a scope 
2. Search Portlet - searches for documents using Graffito Search service
3. DocumentPortlet - displays a Graffito document, communicates with the Tree and Search portlet to receive 
  messages for displaying documents

Added:
    incubator/graffito/trunk/applications/graffito-portlets/src/
    incubator/graffito/trunk/applications/graffito-portlets/src/java/
    incubator/graffito/trunk/applications/graffito-portlets/src/java/org/
    incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/
    incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/
    incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/
    incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/
    incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/DocumentPortlet.java
    incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/FilePortlet.java
    incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/SearchPortlet.java
    incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/TreePortlet.java
    incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/
    incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/CMSTreeLoader.java
    incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/TreeLoader.java
    incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/TreeLoaderHandler.java
    incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/util/
    incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/util/ServiceAccessor.java

Added: incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/DocumentPortlet.java
URL: http://svn.apache.org/viewcvs/incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/DocumentPortlet.java?view=auto&rev=158983
==============================================================================
--- incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/DocumentPortlet.java (added)
+++ incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/DocumentPortlet.java Thu Mar 24 18:21:35 2005
@@ -0,0 +1,246 @@
+/*
+ * Copyright 2000-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.portals.graffito.portlets;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import javax.portlet.ActionRequest;
+import javax.portlet.ActionResponse;
+import javax.portlet.PortletConfig;
+import javax.portlet.PortletException;
+import javax.portlet.PortletMode;
+import javax.portlet.PortletPreferences;
+import javax.portlet.RenderRequest;
+import javax.portlet.RenderResponse;
+import javax.portlet.WindowState;
+
+import org.apache.portals.bridges.velocity.GenericVelocityPortlet;
+import org.apache.portals.graffito.ContentModelService;
+import org.apache.portals.graffito.exception.ContentManagementException;
+import org.apache.portals.graffito.model.Document;
+import org.apache.portals.messaging.PortletMessaging;
+import org.apache.velocity.context.Context;
+
+import org.apache.portals.graffito.portlets.util.ServiceAccessor;
+
+
+/**
+ * CMS Document Displayer
+ * 
+ * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
+ * @version $Id: CMSDocumentPortlet.java,v 1.5 2005/02/19 22:29:28 david Exp $
+ */
+public class DocumentPortlet extends GenericVelocityPortlet
+{
+    public final static String CURRENT_ISSUE = "current_issue";
+    public final static String CURRENT_FOLDER = "current_folder";
+    public final static String CURRENT_PAGE = "current_page";
+    public final static String CURRENT_USER = "current_user";
+    public final static String REQUEST_NODE = "node";
+    /** the selected leaf node in the tree view */
+    public final static String REQUEST_SELECT_NODE = "select_node";
+    
+    public final static String JAVASCRIPT = "<script language='JavaScript'>" +
+    	"function setAnchor(anchor) { location.hash = anchor; } </script>";
+    
+    private ContentModelService cms;
+    
+    public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException
+    {
+    	response.setContentType("text/html");
+        
+        String currentFile = (String) PortletMessaging.receive(request, "FileDisplayer", "current_file");
+        
+        String fileName = null;
+        PortletPreferences prefs = request.getPreferences();
+        String uri = prefs.getValue("document-uri", null);
+        if (uri != null && uri.length() > 0)
+        {
+            currentFile = uri;
+        }
+        if(currentFile != null)
+        {
+        	try 
+            {
+				Document doc = cms.getDocument(currentFile);
+				if (doc.getContentType().indexOf("html") != -1)
+				{
+                    String title = doc.getProperty("title");
+                    if (title == null)
+                        title = doc.getName();
+					String currentDocument = "<div>Current Document: <b>" + title + "</b> - "+ doc.getUri() + "</div>";
+	                String anchors = "<hr/>"; //createAnchors(doc);
+					response.getPortletOutputStream().write(currentDocument.getBytes());
+	                response.getPortletOutputStream().write(anchors.getBytes());                
+					response.getPortletOutputStream().write(DIV_START.getBytes());
+					drain(doc.getContent().getContentStream(), response.getPortletOutputStream());
+					response.getPortletOutputStream().write(DIV_END.getBytes());
+					
+					int hash = currentFile.indexOf('#');
+					if(hash != -1)
+					{
+						String anchor = currentFile.substring(hash+1);
+						response.getPortletOutputStream().write(JAVASCRIPT.getBytes());
+						response.getPortletOutputStream().write("<script>setAnchor('".getBytes());
+						response.getPortletOutputStream().write(anchor.getBytes());
+						response.getPortletOutputStream().write("');</script>".getBytes());
+					}
+				}
+				else if (doc.getContentType().indexOf("pdf") != -1)
+				{
+                    renderPDF(request, response, currentFile, doc);
+				}
+                else if (doc.getContentType().indexOf("gif") != -1)
+                {
+                    String title = doc.getProperty("title");
+                    if (title == null)
+                        title = doc.getName();
+                    String currentDocument = "<div>Current Document: <b>" + title + "</b> - "+ doc.getUri() + "</div>";
+                    String anchors = "<hr/>"; //createAnchors(doc);
+                    response.getPortletOutputStream().write(currentDocument.getBytes());
+                    response.getPortletOutputStream().write(anchors.getBytes());                
+                    response.getPortletOutputStream().write(DIV_START.getBytes());
+                    String gif = "<IMG SRC='" + "/images/" + doc.getName() + "'/>";
+                    response.getPortletOutputStream().write(gif.getBytes());
+                    response.getPortletOutputStream().write(DIV_END.getBytes());                    
+                }
+			} 
+            catch (ContentManagementException e) 
+            {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}           
+        }
+    }
+
+    private String createAnchors(Document doc)
+    {
+        return "<hr/><a href='#'>Top</a>&nbsp;<a href='#010'>Sample Anchor 1</a>&nbsp;<a href='#014'>Sample Anchor 2</a>&nbsp;<a href='#020'>Sample Anchor 3</a><hr/>";
+    }
+    
+    private void renderPDF(RenderRequest request, RenderResponse response, String currentFile, Document doc)
+    throws IOException
+    {
+        String title = doc.getProperty("title");
+        if (title == null)
+            title = doc.getName();
+        
+        String contextPath = request.getContextPath();
+        String linkage = "<a target='_new' href='" + 
+            contextPath + "/servlet/FileServlet?uri=" + currentFile + "'>View in New Window</a>";        
+        String currentDocument = "<div>Document: <b>" + title + "</b>&nbsp" + linkage;
+        response.getPortletOutputStream().write(currentDocument.getBytes());
+        
+        String iframe = "<iframe src=\"" + contextPath + "/servlet/FileServlet?uri=" + currentFile + "\"";
+        if (request.getWindowState().equals(WindowState.MAXIMIZED))
+            iframe += " height=\"800\" width=\"100%\"";
+        else
+            iframe += " height=\"700\" width=\"100%\"";
+        iframe += "></iframe>";
+        response.getPortletOutputStream().write(iframe.getBytes());        
+    }
+    
+    public void doEdit(RenderRequest request, RenderResponse response) 
+    throws PortletException, IOException
+    {
+        response.setContentType("text/html");
+        String currentArticle = (String) PortletMessaging.receive(request, "FileDisplayer", "current_file");
+        if (currentArticle == null)
+        {
+            return;
+        }
+        ContentModelService cms = (ContentModelService)ServiceAccessor.getService("cmsModelImpl");
+        try 
+        {
+            Document document = cms.getDocument(currentArticle);
+            Context context = super.getContext(request);
+            context.put("reference", (String)document.getProperty("reference"));
+            context.put("title", (String)document.getProperty("title"));
+            context.put("displayTitle", (String)document.getProperty("displayTitle"));
+            context.put("year", (String)document.getProperty("year"));
+            context.put("month", (String)document.getProperty("month"));
+            if (document.getContentType().indexOf("pdf") != -1)                
+                context.put("issue", (String)document.getProperty("articleRefs"));
+            else
+                context.put("issue", (String)document.getProperty("issue"));
+                
+            context.put("keywords", "example keywords, feature, not implemented, yet");            
+        }
+        catch (ContentManagementException e) 
+        {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }           
+        
+        super.doEdit(request, response);
+    }
+
+    public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) 
+    throws PortletException,
+          IOException
+    {
+        if (actionRequest.getPortletMode() == PortletMode.EDIT)
+        {
+            String title = (String)actionRequest.getParameter("title");
+            // TODO: oops no API to save document
+        }
+        actionResponse.setPortletMode(PortletMode.VIEW);
+        super.processAction(actionRequest, actionResponse);
+        
+    }
+    
+    // todo: make the scroll area and width configurable by prefs
+    private static final String DIV_START = "<DIV id='itdbscroll' style='OVERFLOW: auto; WIDTH: 100%; HEIGHT: 600px;'>";
+    private static final String DIV_END = "</DIV>";
+
+    private static final int BLOCK_SIZE = 4096;
+
+    public static void drain(InputStream r,OutputStream w) throws IOException
+    {
+        byte[] bytes=new byte[BLOCK_SIZE];
+        try
+        {
+          int length=r.read(bytes);
+          while(length!=-1)
+          {
+              if(length!=0)
+                  {
+                      w.write(bytes,0,length);
+                  }
+              length=r.read(bytes);
+          }
+      }
+      finally
+      {
+        bytes=null;
+      }
+
+    }
+
+    public void init(PortletConfig config) throws PortletException
+    {
+        super.init(config);
+        
+        cms = ServiceAccessor.getModelService();
+        if (cms == null)
+        {
+            throw new PortletException("Failed to load CMS service");
+        }
+    }
+        
+}

Added: incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/FilePortlet.java
URL: http://svn.apache.org/viewcvs/incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/FilePortlet.java?view=auto&rev=158983
==============================================================================
--- incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/FilePortlet.java (added)
+++ incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/FilePortlet.java Thu Mar 24 18:21:35 2005
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2000-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.portals.graffito.portlets;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import javax.portlet.PortletException;
+import javax.portlet.RenderRequest;
+import javax.portlet.RenderResponse;
+import javax.portlet.PortletPreferences;
+
+import org.apache.portals.bridges.common.GenericServletPortlet;
+
+/*
+ * Copyright 2000-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * FilePortlet
+ * 
+ * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
+ * @version $Id: FilePortlet.java,v 1.2 2005/02/16 22:58:31 david Exp $
+ */
+public class FilePortlet extends GenericServletPortlet
+{
+    
+    public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException
+    {
+        response.setContentType("text/html");
+        PortletPreferences prefs = request.getPreferences();
+        String fileName = prefs.getValue("file", null);
+        if (fileName != null)
+        {
+            InputStream is = this.getPortletContext().getResourceAsStream(fileName);
+            drain(is, response.getPortletOutputStream());
+            is.close();
+        }
+        else
+        {
+            response.getWriter().println("Could not find file preference ");
+        }
+    }
+    
+    static final int BLOCK_SIZE=4096;
+
+    public static void drain(InputStream r,OutputStream w) throws IOException
+    {
+        byte[] bytes=new byte[BLOCK_SIZE];
+        try
+        {
+          int length=r.read(bytes);
+          while(length!=-1)
+          {
+              if(length!=0)
+                  {
+                      w.write(bytes,0,length);
+                  }
+              length=r.read(bytes);
+          }
+      }
+      finally
+      {
+        bytes=null;
+      }
+
+    }
+   
+    
+}

Added: incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/SearchPortlet.java
URL: http://svn.apache.org/viewcvs/incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/SearchPortlet.java?view=auto&rev=158983
==============================================================================
--- incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/SearchPortlet.java (added)
+++ incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/SearchPortlet.java Thu Mar 24 18:21:35 2005
@@ -0,0 +1,347 @@
+/*
+ * Copyright 2000-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.portals.graffito.portlets;
+
+import java.io.IOException;
+import java.io.NotSerializableException;
+import java.util.List;
+
+import javax.portlet.ActionRequest;
+import javax.portlet.ActionResponse;
+import javax.portlet.PortletConfig;
+import javax.portlet.PortletException;
+import javax.portlet.PortletRequest;
+import javax.portlet.RenderRequest;
+import javax.portlet.RenderResponse;
+
+import org.apache.portals.bridges.common.GenericServletPortlet;
+import org.apache.portals.graffito.ContentSearchService;
+import org.apache.portals.graffito.exception.ContentManagementException;
+import org.apache.portals.graffito.model.Document;
+import org.apache.portals.graffito.search.Filter;
+import org.apache.portals.graffito.search.SearchResults;
+import org.apache.portals.messaging.PortletMessaging;
+import org.apache.webapp.admin.TreeControl;
+import org.apache.webapp.admin.TreeControlNode;
+
+import org.apache.portals.graffito.portlets.tree.CMSTreeLoader;
+import org.apache.portals.graffito.portlets.util.ServiceAccessor;
+
+
+/**
+ * CMS Search
+ * 
+ * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
+ * @version $Id: CMSSearchPortlet.java,v 1.4 2005/02/22 02:00:51 david Exp $
+ */
+public class SearchPortlet extends GenericServletPortlet
+{
+    public final static String PORTLET_URL = "portlet_url";
+    
+    /** the selected leaf node in the tree view */
+    public final static String REQUEST_SELECT_NODE = "select_node";
+    public final static String REQUEST_NODE = "node";
+    
+    private static final String SEARCH_MESSAGE = "search_message";
+    private static final String SEARCH_STRING = "search_string";
+    //TODO: localize this message    
+    private static final String NOT_FOUND = "No matching documents found for search criteria.";
+
+    private ContentSearchService search = null;
+    private CMSTreeLoader loader = new CMSTreeLoader();
+        
+    //TODO: config via portlet.xml
+    private int perPage = 10;
+    
+    public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException
+    {
+        response.setContentType("text/html");
+
+        TreeControl control = (TreeControl) request.getPortletSession().getAttribute("search_tree");
+        if (control != null)
+        {
+        	request.setAttribute("search_tree", control);
+        }
+        
+        Object anchor = request.getPortletSession().getAttribute("tree_anchor");
+        if(anchor != null)
+        {
+            request.setAttribute("tree_anchor", anchor);
+            //request.getPortletSession().removeAttribute("tree_anchor");
+        }
+        
+        String next = (String) request.getPortletSession().getAttribute("next");
+        if(next != null)
+        {
+        	request.setAttribute("next", next);
+        	request.getPortletSession().removeAttribute("next");
+        }
+        
+        String prev = (String) request.getPortletSession().getAttribute("prev");
+        if(prev != null)
+        {
+        	request.setAttribute("prev", prev);
+        	request.getPortletSession().removeAttribute("prev");
+        }
+        
+        Object refresh = request.getPortletSession().getAttribute("refresh_page");
+        if(refresh != null)
+        {
+            request.getPortletSession().removeAttribute("refresh_page");
+            request.setAttribute("refresh_page", refresh);
+        }
+
+        String searchMessage = (String) PortletMessaging.consume(request, SEARCH_MESSAGE);
+        request.setAttribute(SEARCH_MESSAGE, searchMessage);
+        
+        String searchString = (String) PortletMessaging.receive(request, "Search", SEARCH_STRING);
+        request.setAttribute(SEARCH_STRING, searchString);        
+        
+        super.doView(request, response);
+    } 
+ 
+    public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) 
+    throws PortletException,
+          IOException
+    {
+        String searchString = actionRequest.getParameter("search");
+        TreeControl control = (TreeControl) actionRequest.getPortletSession().getAttribute("search_tree");        
+        if (searchString != null && searchString.trim().length() > 0)
+        {
+            control = doSearch(actionRequest, searchString);
+            if(control == null)
+            {
+                PortletMessaging.publish(actionRequest, SEARCH_MESSAGE, NOT_FOUND);
+            }
+            else
+            {
+                List results  = (List) actionRequest.getPortletSession().getAttribute("search_results");
+                if(perPage < results.size())
+                {
+                	actionRequest.getPortletSession().setAttribute("next", Integer.toString(perPage));
+                }
+                if (results.size() == 0)
+                {
+                    control = null;                    
+                    PortletMessaging.publish(actionRequest, SEARCH_MESSAGE, NOT_FOUND);                    
+                }                
+            }
+            PortletMessaging.publish(actionRequest, "Search", SEARCH_STRING, searchString);                        
+        }
+        //assert control != null
+        
+        String start = actionRequest.getParameter("start");
+        if(start != null)
+        {
+        	int startInt = Integer.parseInt(start);
+        	List results  = (List) actionRequest.getPortletSession().getAttribute("search_results");
+        	
+        	int end = startInt + perPage;
+        	if(end > results.size())
+        	{
+        		end = results.size();
+        	}
+        	List subList = results.subList(startInt, end);
+        	try {
+        		control = this.buildCmsTree(subList);
+        		actionRequest.getPortletSession().setAttribute("search_tree", control);
+			} catch (ContentManagementException e) {
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+        	
+        	if(startInt > 0)
+        	{
+        		int prev = startInt - perPage;
+        		actionRequest.getPortletSession().setAttribute("prev", Integer.toString(prev));
+        	}
+        	int next = startInt + perPage;
+        	if(next < results.size())
+        	{                
+        		actionRequest.getPortletSession().setAttribute("next", Integer.toString(next));
+        	}
+        }
+
+        if (control == null)
+        {
+            actionRequest.getPortletSession().setAttribute("search_tree", null);
+        }
+        else
+        {
+            // expand or contact non-leaf nodes
+            String node = actionRequest.getParameter(REQUEST_NODE);
+            if (node != null)
+            {
+                TreeControlNode controlNode = control.findNode(node);
+                if (controlNode != null)
+                {
+                    if(controlNode.isLazy() && !controlNode.isLoaded()) 
+                    {
+                        try {
+							loader.loadChildren(controlNode);
+						} catch (ContentManagementException e) {
+							// TODO Auto-generated catch block
+							e.printStackTrace();
+						}
+                    }
+                    controlNode.setExpanded(!controlNode.isExpanded());
+                    actionRequest.getPortletSession().setAttribute("tree_anchor", node);
+                    
+                    if(controlNode.isExpanded() && controlNode != control.getRoot())
+                    {
+                        TreeControlNode[] siblings = controlNode.getParent().findChildren();
+                        for(int i=0; i<siblings.length; i++)
+                        {
+                            TreeControlNode sibling = siblings[i];
+                            if(sibling != controlNode)
+                            {
+                                sibling.setExpanded(false);
+                            }
+                        }
+                    }
+                }
+            }
+
+            // select a node
+            String selectedNode = actionRequest.getParameter(REQUEST_SELECT_NODE);
+            if (selectedNode != null)
+            {
+                selectNode(actionRequest, control, selectedNode);
+                actionRequest.getPortletSession().setAttribute("tree_anchor", selectedNode);
+            }
+        }
+    }
+    
+    private TreeControl doSearch(ActionRequest request, String searchString)
+    {
+        Filter filter = search.newFilter();
+        filter.setScope(this.getInitParameter("scope"));
+        filter.addFullTextSearch(searchString);
+        SearchResults results = null;
+        try
+        {
+            results = search.searchCmsObjects(filter);
+            if (results.size() > 0)
+            {
+            	List resultList = results.getResults();
+                int end = perPage;
+                if(perPage > resultList.size())
+                {
+                    end = resultList.size();
+                }
+            	List subList = resultList.subList(0, end);
+                TreeControl control = buildCmsTree(subList);
+                request.getPortletSession().setAttribute("search_tree", control);
+                request.getPortletSession().setAttribute("search_results", resultList);
+                return control;
+            }
+        }
+        catch (ContentManagementException e)
+        {
+            System.err.println("Failed to search on search string: " + searchString + ", " + e.toString());
+        }
+        // handle case where nothing found
+        if (results == null)
+            results = new SearchResults();
+        List resultList = results.getResults();
+        //List subList = resultList.subList(0,perPage);
+        TreeControlNode root = loader.createRootNode("Search Results", "SEARCH_DOMAIN");
+        TreeControl control = new TreeControl(root);            
+        request.getPortletSession().setAttribute("search_tree", control);
+        request.getPortletSession().setAttribute("search_results", resultList);
+        return control;        
+    }
+    
+    private TreeControl buildCmsTree(List results) throws ContentManagementException
+    {
+        TreeControlNode root = loader.createRootNode("Search Results", "SEARCH_DOMAIN");
+        TreeControl treeControl = new TreeControl(root);
+        for (int ix = 0; ix < results.size(); ix++)
+        {
+            Document document = (Document)results.get(ix);
+            /*
+            String key = document.getProperty("reference");
+            String dt = document.getProperty("displayTitle");
+            TreeControlNode docNode = 
+                new TreeControlNode(
+                        key, 
+                        "document.gif", 
+                        document.getProperty("displayTitle"), 
+                        PORTLET_URL, 
+                        null, 
+                        false, 
+                        "DOC_DOMAIN",
+                        "Document");
+                        */
+            // refToURIMap.put(document.getProperty("reference"), document.getUri());
+            TreeControlNode docNode = loader.createDocumentNode(document);
+            root.addChild(docNode);
+        }
+                 
+        return treeControl;
+    }
+    
+    private void selectNode(PortletRequest actionRequest, TreeControl control, String selectedNode)
+    {
+        System.out.println("selected node = " + selectedNode);
+        control.selectNode(selectedNode);
+        TreeControlNode child = control.findNode(selectedNode);
+        if (child != null)
+        {
+            String domain = child.getDomain();
+            /*
+            if (domain.equals("FOLDER_DOMAIN"))
+            {
+                if (selectedNode != null)
+                {
+                    System.out.println("posting selected node = " + selectedNode);
+                    
+                    actionRequest.getPortletSession().setAttribute(
+                            "current_folder", selectedNode,
+                            PortletSession.APPLICATION_SCOPE);
+                }
+            }
+            */
+            if(domain.equals("DOC_DOMAIN") || domain.equals("ANCHOR_DOMAIN"))
+            {
+            	String uri = selectedNode; //(String) this.refToURIMap.get(selectedNode);
+            	//String uri = loader.getURIFromNodeName(selectedNode);
+                try
+                {
+                    PortletMessaging.publish(actionRequest, "FileDisplayer", "current_file", uri);
+                }
+                catch (NotSerializableException e)
+                {}
+                
+                actionRequest.getPortletSession().setAttribute("refresh_page", Boolean.TRUE);
+            }
+        }
+    }
+    
+    
+    
+    public void init(PortletConfig config) throws PortletException
+    {
+        super.init(config);
+        
+        search = (ContentSearchService)ServiceAccessor.getSearchService();
+        if (search == null)
+        {
+            throw new PortletException("Failed to load CMS Search service");
+        }
+    }
+    
+}

Added: incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/TreePortlet.java
URL: http://svn.apache.org/viewcvs/incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/TreePortlet.java?view=auto&rev=158983
==============================================================================
--- incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/TreePortlet.java (added)
+++ incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/TreePortlet.java Thu Mar 24 18:21:35 2005
@@ -0,0 +1,259 @@
+/*
+ * Copyright 2000-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.portals.graffito.portlets;
+
+import java.io.IOException;
+import java.io.NotSerializableException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.portlet.ActionRequest;
+import javax.portlet.ActionResponse;
+import javax.portlet.PortletConfig;
+import javax.portlet.PortletException;
+import javax.portlet.PortletRequest;
+import javax.portlet.RenderRequest;
+import javax.portlet.RenderResponse;
+
+import org.apache.portals.bridges.common.GenericServletPortlet;
+import org.apache.portals.graffito.ContentModelService;
+import org.apache.portals.graffito.exception.ContentManagementException;
+import org.apache.portals.graffito.model.Document;
+import org.apache.portals.graffito.model.Folder;
+import org.apache.portals.messaging.PortletMessaging;
+import org.apache.webapp.admin.TreeControl;
+import org.apache.webapp.admin.TreeControlNode;
+
+import org.apache.portals.graffito.portlets.tree.CMSTreeLoader;
+import org.apache.portals.graffito.portlets.util.ServiceAccessor;
+
+
+
+/**
+ * CMS Tree Portlet
+ * 
+ * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
+ * @version $Id: CMSTreePortlet.java,v 1.2 2005/02/18 01:10:56 david Exp $
+ */
+public class TreePortlet extends GenericServletPortlet
+{
+    public final static String PORTLET_ACTION = "portlet_action";
+    public final static String PORTLET_URL = "portlet_url";
+    public final static String CURRENT_FOLDER = "current_folder";
+    public final static String CURRENT_PAGE = "current_page";
+    public final static String CURRENT_USER = "current_user";
+    public final static String REQUEST_NODE = "node";
+    /** the selected leaf node in the tree view */
+    public final static String REQUEST_SELECT_NODE = "select_node";
+    
+    protected final static String TARGET = "_parent";
+    
+    protected String xmlIndex;
+    
+    protected CMSTreeLoader loader;
+    protected ContentModelService cms;
+    
+    public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException
+    {
+        response.setContentType("text/html");
+
+        TreeControl control = (TreeControl) request.getPortletSession().getAttribute("j2_tree");
+        if (control == null)
+        {
+            control = buildCmsTree(this.getInitParameter("scope"), "Content", "DTB_DOMAIN");
+            request.getPortletSession().setAttribute("j2_tree", control);
+        }
+        
+        Object anchor = request.getPortletSession().getAttribute("tree_anchor");
+        if(anchor != null)
+        {
+            request.setAttribute("tree_anchor", anchor);
+            //request.getPortletSession().removeAttribute("tree_anchor");
+        }
+        
+        Object refresh = request.getPortletSession().getAttribute("refresh_page");
+        if(refresh != null)
+        {
+        	request.getPortletSession().removeAttribute("refresh_page");
+        	request.setAttribute("refresh_page", refresh);
+        }
+        
+        request.setAttribute("j2_tree", control);
+
+        super.doView(request, response);
+    } 
+ 
+    public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) 
+    throws PortletException,
+          IOException
+    {
+    	/*
+    	Object refresh = actionRequest.getPortletSession().getAttribute("refresh_page");
+        if(refresh != null)
+        {
+        	//attempt to fix safari bug.  if processAction 
+        	actionRequest.getPortletSession().removeAttribute("refresh_page");
+        	return;
+        }
+        */
+        TreeControl control = (TreeControl) actionRequest.getPortletSession().getAttribute("j2_tree");
+        //assert control != null
+        if (control != null)
+        {
+            // expand or contact non-leaf nodes
+            String node = actionRequest.getParameter(REQUEST_NODE);
+            if (node != null)
+            {
+                TreeControlNode controlNode = control.findNode(node);
+                if (controlNode != null)
+                {
+                    if(controlNode.isLazy() && !controlNode.isLoaded())	
+                    {
+                        try {
+							loader.loadChildren(controlNode);
+						} catch (ContentManagementException e) {
+							// TODO Auto-generated catch block
+							e.printStackTrace();
+						}
+                    }
+                    controlNode.setExpanded(!controlNode.isExpanded());
+                    actionRequest.getPortletSession().setAttribute("tree_anchor", node);
+                    
+                    if(controlNode.isExpanded() && controlNode != control.getRoot())
+                    {
+                    	TreeControlNode[] siblings = controlNode.getParent().findChildren();
+                    	for(int i=0; i<siblings.length; i++)
+                    	{
+                    		TreeControlNode sibling = siblings[i];
+                    		if(sibling != controlNode)
+                    		{
+                    			sibling.setExpanded(false);
+                    		}
+                    	}
+                    }
+                }
+            }
+
+            // select a node
+            String selectedNode = actionRequest.getParameter(REQUEST_SELECT_NODE);
+            if (selectedNode != null)
+            {
+                selectNode(actionRequest, control, selectedNode);
+                actionRequest.getPortletSession().setAttribute("tree_anchor", selectedNode);
+            }
+        }
+    }
+   
+    private void selectNode(PortletRequest actionRequest, TreeControl control, String selectedNode)
+    {
+        System.out.println("selected node = " + selectedNode);
+        control.selectNode(selectedNode);
+        TreeControlNode child = control.findNode(selectedNode);
+        if (child != null)
+        {
+            String domain = child.getDomain();
+            /*
+            if (domain.equals("FOLDER_DOMAIN"))
+            {
+                if (selectedNode != null)
+                {
+                    System.out.println("posting selected node = " + selectedNode);
+                    
+                    actionRequest.getPortletSession().setAttribute(
+                            "current_folder", selectedNode,
+                            PortletSession.APPLICATION_SCOPE);
+                }
+            }
+            */
+            if(domain.equals("DOC_DOMAIN") || domain.equals("ANCHOR_DOMAIN"))
+            {
+            	//String uri = loader.getURIFromNodeName(selectedNode);
+            	String uri = selectedNode; //(String) refToURIMap.get(selectedNode);
+                try
+                {
+                    PortletMessaging.publish(actionRequest, "FileDisplayer", "current_file", uri);
+                }
+                catch (NotSerializableException e)
+                {}
+                
+                actionRequest.getPortletSession().setAttribute("refresh_page", Boolean.TRUE);
+            }
+        }
+    }
+    
+    public TreeControl buildCmsTree(String folderRoot, String label, String rootDomain)
+    {
+    	TreeControlNode root = loader.createRootNode(label, rootDomain);
+    	TreeControl treeControl = new TreeControl(root);
+        
+        if (null == cms)
+            return treeControl;
+    
+        // load from CMS
+        try
+        {            
+            Collection topLevel = cms.getFolders(folderRoot);
+            Collections.sort((List)topLevel, CMSTreeLoader.getComparator());
+            Iterator top = topLevel.iterator();
+            while (top.hasNext())
+            {
+                Folder topFolder = (Folder)top.next();
+                TreeControlNode node = loader.createFolderNode(topFolder);
+                root.addChild(node);
+                if(cms.getFolders(topFolder.getUri()).size() > 0)
+                {
+                	node.setLeaf(false);
+                }
+            }
+
+            // then get documents
+            Collection docLevel = cms.getDocuments(folderRoot);
+            Collections.sort((List)docLevel, CMSTreeLoader.getComparator());
+            Iterator docs = docLevel.iterator();
+            while (docs.hasNext())
+            {
+                Document doc = (Document)docs.next();
+                TreeControlNode issueNode = loader.createDocumentNode(doc);
+                root.addChild(issueNode);
+            }
+            
+        }
+        catch (ContentManagementException cme)
+        {
+            // TODO: logging
+            System.err.println("exception building cms list " + cme);
+        }
+                 
+        return treeControl;
+    }
+    
+    public void init(PortletConfig config) throws PortletException
+    {
+        super.init(config);
+        
+        loader = new CMSTreeLoader();
+        
+        cms = ServiceAccessor.getModelService();
+        if (cms == null)
+        {
+            throw new PortletException("Failed to load CMS service");
+        }
+    }
+
+                 
+}

Added: incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/CMSTreeLoader.java
URL: http://svn.apache.org/viewcvs/incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/CMSTreeLoader.java?view=auto&rev=158983
==============================================================================
--- incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/CMSTreeLoader.java (added)
+++ incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/CMSTreeLoader.java Thu Mar 24 18:21:35 2005
@@ -0,0 +1,204 @@
+/*
+ * Copyright 2000-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.portals.graffito.portlets.tree;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+
+import org.apache.portals.graffito.ContentModelService;
+import org.apache.portals.graffito.exception.ContentManagementException;
+import org.apache.portals.graffito.model.CmsObject;
+import org.apache.portals.graffito.model.Document;
+import org.apache.portals.graffito.model.Folder;
+import org.apache.portals.graffito.model.Link;
+import org.apache.webapp.admin.TreeControlNode;
+import org.apache.portals.graffito.portlets.util.ServiceAccessor;
+
+public class CMSTreeLoader {
+	
+	public final static String PORTLET_URL = "portlet_url";
+		
+	private static ContentModelService cms = (ContentModelService)ServiceAccessor.getService("cmsModelImpl");
+
+    public TreeControlNode createFolderNode(Folder folder) throws ContentManagementException
+    {
+        TreeControlNode node = 
+            new TreeControlNode(
+                    folder.getUri(), 
+                    "folder.gif", 
+                    folder.getName(), 
+                    null, 
+                    null, 
+                    false, 
+                    "FOLDER_DOMAIN",
+                    "Folder",
+                    true);
+
+        if(cms.getDocuments(folder.getUri()).size() > 0)
+        {
+            node.setLeaf(false);
+        }
+        return node;
+    }
+    	
+	public TreeControlNode createDocumentNode(Document document) throws ContentManagementException
+    {
+        String title = document.getProperty("displayTitle");
+        if (title == null)
+            title = document.getName();
+        
+    	TreeControlNode issueNode = 
+            new TreeControlNode(
+                    document.getUri(),
+                    "document.gif", 
+                    title, 
+                    PORTLET_URL, 
+                    null, 
+                    false, 
+                    "DOC_DOMAIN",
+					"Document",
+					true);
+    	
+    	//if(cms.getLinks(document.getUri()).size() > 0)
+    	{
+    		issueNode.setLeaf(true);
+    	}
+    	
+    	return issueNode;
+    }
+    
+    public TreeControlNode createLinkNode(Link link) throws ContentManagementException
+    {
+    	TreeControlNode linkNode = 
+            new TreeControlNode(
+                    link.getProperty("reference") + link.getProperty("anchor"),
+                    "anchorlink.gif", 
+                    link.getProperty("displayTitle"), 
+                    PORTLET_URL, 
+                    null, 
+                    false, 
+                    "ANCHOR_DOMAIN",
+					null,
+                    true);
+    	
+        if(cms.getLinks(link.getUri()).size() > 0)
+        {
+            linkNode.setLeaf(false);
+        }
+    	
+    	return linkNode;
+    }
+    
+    public TreeControlNode createRootNode(String label, String rootDomain)
+    {
+    	TreeControlNode root = new TreeControlNode("ROOT-NODE", 
+                "folder.gif", 
+                label, // label 
+                null,       // action
+                null,       // target
+                true,       // expanded?
+                rootDomain,
+				null);
+    	
+    	return root;
+    }    
+    
+    public void loadChildren(TreeControlNode node) throws ContentManagementException
+    {
+    	String domain = node.getDomain();
+    	if(domain.equals("FOLDER_DOMAIN"))
+    	{
+            // first get folders
+	    	Collection subFolders = cms.getFolders(node.getName());
+	        Collections.sort((List)subFolders, cmsComparator);
+	        Iterator folders = subFolders.iterator();
+	        while (folders.hasNext())
+	        {
+	            Folder folder = (Folder)folders.next();
+	            TreeControlNode monthNode = createFolderNode(folder);
+	            node.addChild(monthNode);
+	        }
+
+            // then get documents
+            Collection issueLevel = cms.getDocuments(node.getName());
+            Collections.sort((List)issueLevel, cmsComparator);
+            Iterator issues = issueLevel.iterator();
+            while (issues.hasNext())
+            {
+                Document doc = (Document)issues.next();
+                TreeControlNode issueNode = createDocumentNode(doc);
+                node.addChild(issueNode);
+                    
+                //refToURIMap.put(doc.getProperty("reference"), doc.getUri());
+            }
+            node.setLoaded(true);
+            
+    	}
+//    	else if(domain.equals("DOC_DOMAIN"))
+//    	{
+//    		//String uri = (String) refToURIMap.get(node.getName());
+//            String uri = node.getName();
+//    		Collection links = cms.getLinks(uri);
+//    		Iterator iter = links.iterator();
+//    		while (iter.hasNext()) {
+//				Link link = (Link) iter.next();
+//				TreeControlNode linkNode = createLinkNode(link);
+//				node.addChild(linkNode);
+//                
+//                //refToURIMap.put(link.getProperty("reference") + link.getProperty("anchor"), link.getUri());
+//			}
+//    		node.setLoaded(true);
+//    	}
+//        else if(domain.equals("ANCHOR_DOMAIN"))
+//        {
+//            //String uri = (String) refToURIMap.get(node.getName());
+//            String uri = node.getName();
+//            
+//            Collection links = cms.getLinks(uri);
+//            Iterator iter = links.iterator();
+//            while (iter.hasNext()) {
+//                Link link = (Link) iter.next();
+//                TreeControlNode linkNode = createLinkNode(link);
+//                node.addChild(linkNode);
+//                
+//              //  refToURIMap.put(link.getProperty("reference") + link.getProperty("anchor"), link.getUri());                
+//            }
+//            node.setLoaded(true);
+//        }
+        
+    }
+	
+	
+	public static Comparator cmsComparator = new CmsObjectComparator();
+	
+	public static Comparator getComparator() {
+		return cmsComparator;
+	}
+    
+    private static class CmsObjectComparator implements Comparator
+    {
+        public int compare(Object o1, Object o2)
+        {
+            CmsObject lhs = (CmsObject)o1;
+            CmsObject rhs = (CmsObject)o2;
+            
+            return rhs.getName().compareTo(lhs.getName());
+        }
+    }
+}

Added: incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/TreeLoader.java
URL: http://svn.apache.org/viewcvs/incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/TreeLoader.java?view=auto&rev=158983
==============================================================================
--- incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/TreeLoader.java (added)
+++ incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/TreeLoader.java Thu Mar 24 18:21:35 2005
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2000-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.portals.graffito.portlets.tree;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+
+import org.apache.webapp.admin.TreeControl;
+import org.xml.sax.SAXException;
+
+public class TreeLoader
+{
+    private InputStream inputStream;
+    
+    public TreeLoader(InputStream inputStream)
+    {
+        this.inputStream = inputStream;
+    }
+    
+    public TreeControl getTreeControl()
+    {
+        TreeControl tree = null;
+        
+        SAXParserFactory factory = SAXParserFactory.newInstance();
+        factory.setValidating(false);
+        factory.setNamespaceAware(false);
+        
+        try
+        {
+            SAXParser parser = factory.newSAXParser();
+            TreeLoaderHandler handler = new TreeLoaderHandler();
+            parser.parse(inputStream, handler);
+            tree = handler.getTreeControl();
+        }
+        catch (ParserConfigurationException e)
+        {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        catch (SAXException e)
+        {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        catch (IOException e)
+        {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+        
+        return tree;
+    }
+}

Added: incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/TreeLoaderHandler.java
URL: http://svn.apache.org/viewcvs/incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/TreeLoaderHandler.java?view=auto&rev=158983
==============================================================================
--- incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/TreeLoaderHandler.java (added)
+++ incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/tree/TreeLoaderHandler.java Thu Mar 24 18:21:35 2005
@@ -0,0 +1,227 @@
+/*
+ * Copyright 2000-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.portals.graffito.portlets.tree;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.webapp.admin.TreeControl;
+import org.apache.webapp.admin.TreeControlNode;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
+
+public class TreeLoaderHandler extends DefaultHandler
+{
+    public final static String PORTLET_URL = "portlet_url";
+    
+    private Map yearToTreeNode = new HashMap();
+    private Map yearToChildren = new HashMap();
+    private Map yearmonthToTreeNode = new HashMap();
+    private Map yearmonthToChildren = new HashMap();
+    
+    private Comparator treeNodeComparator = new TreeNodeComparator();
+    
+    private TreeControl treeControl;
+    private TreeControlNode root = null;
+    
+    //private int anchorId = 0;
+    
+    public TreeLoaderHandler()
+    {
+    }
+    
+    public void startDocument ()
+	throws SAXException
+    {
+        root = new TreeControlNode("ROOT-NODE", "folder.gif", 
+                    "Articles", null, null, true, "ROOT_DOMAIN");
+        
+        treeControl = new TreeControl(root);
+    }
+    
+    public void endDocument ()
+	throws SAXException
+    {
+        addYearNodesToRoot();
+    }
+    
+    public TreeControl getTreeControl()
+    {
+        return treeControl;
+    }
+    
+    private void addYearNodesToRoot()
+    {
+        List yearList = new ArrayList(yearToTreeNode.values());
+        Collections.sort(yearList, treeNodeComparator);
+        
+        Iterator yearIter = yearList.iterator();
+        while (yearIter.hasNext())
+        {
+            TreeControlNode yearNode = (TreeControlNode) yearIter.next();
+            root.addChild(yearNode);
+            addMonthNodesToYearNode(yearNode);
+        }
+    }
+    
+    private void addMonthNodesToYearNode(TreeControlNode yearNode)
+    {
+        List monthList = (List) yearToChildren.get(yearNode.getLabel());
+        Collections.sort(monthList, treeNodeComparator);        
+        
+        Iterator monthIter = monthList.iterator();
+        while (monthIter.hasNext())
+        {
+            TreeControlNode monthNode = (TreeControlNode)monthIter.next();
+            yearNode.addChild(monthNode);
+            addIssuesToMonth(yearNode, monthNode);
+        }
+    }
+    
+    private void addIssuesToMonth(TreeControlNode yearNode, TreeControlNode monthNode)
+    {
+        String ymId = yearNode.getLabel() + ":" + monthNode.getLabel();
+        List issueList = (List) this.yearmonthToChildren.get(ymId);
+        Collections.sort(issueList, treeNodeComparator);
+        
+        Iterator issueIter = issueList.iterator();
+        while (issueIter.hasNext())
+        {
+            TreeControlNode issueNode = (TreeControlNode)issueIter.next();
+            TreeControlNode existingIssueNode = treeControl.findNode(issueNode.getName());
+            if(existingIssueNode == null)
+            {
+                monthNode.addChild(issueNode);
+            }
+        }
+    }
+    
+    private String getElementName(String localName, String qName)
+    {
+        String result = null;
+        
+        if(localName == null || localName.length() == 0)
+        {
+            result = qName;
+        }
+        else
+        {
+            result = localName;
+        }
+        
+        return result;
+    }
+    
+    public void startElement (String uri, String localName,
+		      String qName, Attributes attributes)
+	throws SAXException
+	{
+        String element = getElementName(localName, qName);
+        if(element.equals("Article"))
+        {
+            String year = attributes.getValue("year");
+            String month = attributes.getValue("month");
+            String issue = attributes.getValue("issue");
+            String title = attributes.getValue("title");
+            String displaytitle = attributes.getValue("displayTitle");
+            String reference = attributes.getValue("reference");
+            
+            String uid = createArticleId(year, month, issue, title);
+            
+            TreeControlNode yearNode = (TreeControlNode) yearToTreeNode.get(year);
+            if(yearNode == null)
+            {
+                yearNode = new TreeControlNode(year, "folder.gif", 
+                        year, null, null, false, "YEAR_DOMAIN");
+                
+                yearToTreeNode.put(year, yearNode);
+            }
+            
+            String ymId = createArticleId(year, month, null, null);
+            
+            TreeControlNode monthNode = (TreeControlNode) yearmonthToTreeNode.get(ymId);
+            if(monthNode == null)
+            {
+                monthNode = new TreeControlNode(ymId, "folder.gif", 
+                        month, null, null, false, "MONTH_DOMAIN");
+                
+                yearmonthToTreeNode.put(ymId, monthNode);
+                List yearChildren = (List) yearToChildren.get(year);
+                if(yearChildren == null)
+                {
+                    yearChildren = new ArrayList();
+                    yearToChildren.put(year, yearChildren);
+                }
+                yearChildren.add(monthNode);
+            }
+            
+            TreeControlNode issueNode = new TreeControlNode(uid, "document.gif", 
+                    title, PORTLET_URL, null, false, "ISSUE_DOMAIN");
+            
+            //issueNode.setAnchor("" + anchorId);
+            //++anchorId;
+            
+            List children = (List) yearmonthToChildren.get(ymId);
+            if(children == null)
+            {
+                children = new ArrayList();
+                yearmonthToChildren.put(ymId, children);
+            }
+            children.add(issueNode);
+        }
+	}
+    private String createArticleId(String year, String month, String issue, String title)
+    {
+        StringBuffer buffer = new StringBuffer();
+        
+        buffer.append(year);
+        if(month != null)
+        {
+            buffer.append(":");
+            buffer.append(month);
+            if(issue != null)
+            {
+                buffer.append(":");
+                buffer.append(issue);
+                if(title != null)
+                {
+                    buffer.append(":");
+                    buffer.append(title);
+                }
+            }
+        }
+        
+        return buffer.toString();
+    }
+    
+    private class TreeNodeComparator implements Comparator
+    {
+	    public int compare(Object o1, Object o2)
+	    {
+	        TreeControlNode lhs = (TreeControlNode)o1;
+	        TreeControlNode rhs = (TreeControlNode)o2;
+	        
+	        return rhs.getLabel().compareTo(lhs.getLabel());
+	    }
+    }
+    
+}

Added: incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/util/ServiceAccessor.java
URL: http://svn.apache.org/viewcvs/incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/util/ServiceAccessor.java?view=auto&rev=158983
==============================================================================
--- incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/util/ServiceAccessor.java (added)
+++ incubator/graffito/trunk/applications/graffito-portlets/src/java/org/apache/portals/graffito/portlets/util/ServiceAccessor.java Thu Mar 24 18:21:35 2005
@@ -0,0 +1,81 @@
+/*
+ * Copyright 2000-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.portals.graffito.portlets.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.jetspeed.services.JetspeedPortletServices;
+import org.apache.jetspeed.services.PortletServices;
+import org.apache.portals.graffito.ContentModelService;
+import org.apache.portals.graffito.ContentSearchService;
+import org.apache.portals.graffito.ContentServerService;
+import org.springframework.beans.factory.BeanFactory;
+import org.springframework.beans.factory.xml.XmlBeanFactory;
+import org.springframework.core.io.InputStreamResource;
+
+/**
+ * Spring static accessor singleton.
+ *
+ * @author <a href="mailto:taylor@apache.org">David Sean Taylor</a>
+ * @version $Id: $
+ */
+public class ServiceAccessor
+{
+    private static BeanFactory springFactory = null;
+    
+    private static boolean useJetspeedServices = false;
+
+    public static ContentModelService getModelService()
+    {        
+        return (ContentModelService) getService("ContentModel");
+    }
+
+    public static ContentServerService getServerService()
+    {
+        return (ContentServerService)getService("ContentServer");
+    }
+
+    public static ContentSearchService getSearchService()
+    {
+        return (ContentSearchService)getService("ContentSearch");        
+    }
+    
+    public static BeanFactory getFactory()
+    {
+        return springFactory;
+    }
+
+    static void initializeSpring(InputStream is)
+    throws IOException
+    {
+        springFactory = new XmlBeanFactory(new InputStreamResource(is));
+        is.close();        
+    }
+        
+    public static Object getService(String serviceName)
+    {
+        if (useJetspeedServices)
+        {
+            PortletServices services = JetspeedPortletServices.getSingleton();
+            return (ContentModelService) services.getService(serviceName);            
+        }
+        else
+        {
+            return springFactory.getBean(serviceName);
+        }
+    }
+}
\ No newline at end of file



Mime
View raw message