JBoss Portal SVN: r6897 - in trunk: theme/src/bin/portal-ajax-war/js/portal and 5 other directories.
by portal-commits@lists.jboss.org
Author: julien(a)jboss.com
Date: 2007-03-31 13:46:47 -0400 (Sat, 31 Mar 2007)
New Revision: 6897
Added:
trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxResponse.java
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaResponse.java
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/JSONMarshaller.java
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONArray.java
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONException.java
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONObject.java
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONString.java
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONStringer.java
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONTokener.java
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONWriter.java
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/response/
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/response/UpdateMarkupResponse.java
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/response/UpdatePageResponse.java
Modified:
trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxController.java
trunk/theme/src/bin/portal-ajax-war/js/portal/dyna.js
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaDecorationRenderer.java
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaWindowRenderer.java
trunk/theme/src/main/org/jboss/portal/theme/page/render/DecorationRenderContextImpl.java
trunk/theme/src/main/org/jboss/portal/theme/page/render/WindowRenderContextImpl.java
trunk/theme/src/main/org/jboss/portal/theme/render/WindowRenderContext.java
Log:
when dreams start to become a reality...
Modified: trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxController.java
===================================================================
--- trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxController.java 2007-03-31 14:25:31 UTC (rev 6896)
+++ trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxController.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -30,15 +30,38 @@
import org.jboss.portal.core.controller.classic.CommandForward;
import org.jboss.portal.core.model.portal.command.MoveWindowCommand;
import org.jboss.portal.core.model.portal.command.RenderWindowCommand;
+import org.jboss.portal.core.model.portal.command.PortalObjectCommand;
+import org.jboss.portal.core.model.portal.command.RenderPageCommand;
import org.jboss.portal.core.model.portal.command.response.UpdateWindowMarkupResponse;
import org.jboss.portal.core.model.portal.PortalObjectId;
+import org.jboss.portal.core.model.portal.Window;
+import org.jboss.portal.core.model.portal.Page;
+import org.jboss.portal.core.model.portal.Portal;
import org.jboss.portal.server.ServerException;
import org.jboss.portal.server.ServerInvocation;
import org.jboss.portal.theme.page.WindowResult;
+import org.jboss.portal.theme.page.PageResult;
+import org.jboss.portal.theme.page.render.PageRenderContextImpl;
+import org.jboss.portal.theme.render.RenderContext;
+import org.jboss.portal.theme.render.PageRenderContext;
+import org.jboss.portal.theme.render.WindowRenderContext;
+import org.jboss.portal.theme.render.DecorationRenderContext;
+import org.jboss.portal.theme.render.PortletRenderContext;
+import org.jboss.portal.theme.render.RenderException;
+import org.jboss.portal.theme.PortalLayout;
+import org.jboss.portal.theme.LayoutService;
+import org.jboss.portal.theme.impl.render.dynamic.DynaResponse;
+import org.jboss.portal.theme.impl.render.dynamic.response.UpdateMarkupResponse;
+import org.jboss.portal.theme.impl.render.dynamic.response.UpdatePageResponse;
+import org.jboss.portal.common.util.MarkupInfo;
+import org.jboss.portal.WindowState;
+import org.jboss.portal.Mode;
import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
+import java.util.Collection;
/**
* @author <a href="mailto:julien@jboss.org">Julien Viet</a>
@@ -105,8 +128,127 @@
}
else if (response instanceof WindowResult)
{
- WindowResult windowResult = (WindowResult)response;
- // todo
+ final WindowResult windowResult = (WindowResult)response;
+
+ // We make an assumption here, the window result should carry somehow the window id
+ PortalObjectCommand pocmd = (PortalObjectCommand)cmd;
+
+ //
+ ServerInvocation invocation = ctx.getServerInvocation();
+
+ // Obtain page and portal
+ final Window window = (Window)portalObjectContainer.getObject(pocmd.getTargetId());
+ Page page = (Page)window.getParent();
+ Portal portal = page.getPortal();
+
+ //
+ if (windowResult.getWindowState().equals(WindowState.MAXIMIZED))
+ {
+ // For now we handle a full page refresh
+ RenderPageCommand rpc = new RenderPageCommand(page.getId());
+ String url = ctx.renderURL(rpc, null, null);
+ UpdatePageResponse dresp = new UpdatePageResponse(url);
+ AjaxResponse aresp = new AjaxResponse(dresp);
+ aresp.sendResponse(invocation.getServerContext());
+ }
+ else
+ {
+ // Call to the theme framework
+ PageResult res = new PageResult(page.getName(), page.getProperties(), portal.getProperties());
+ PageRenderContext prc = new PageRenderContextImpl(res);
+
+ // Obtain layout
+ LayoutService layoutService = getPageService().getLayoutService();
+ PortalLayout layout = RenderPageCommand.getLayout(layoutService, page);
+
+ //
+ WindowRenderContext wrc = new WindowRenderContext()
+ {
+ public String getId()
+ {
+ return window.getId().toString();
+ }
+
+ public int getOrder()
+ {
+ return 0;
+ }
+
+ public WindowState getWindowState()
+ {
+ return windowResult.getWindowState();
+ }
+
+ public Mode getMode()
+ {
+ return windowResult.getMode();
+ }
+
+ public DecorationRenderContext getDecoration()
+ {
+ return new DecorationRenderContext()
+ {
+ public String getId()
+ {
+ return window.getId().toString();
+ }
+
+ public String getTitle()
+ {
+ return windowResult.getTitle();
+
+ }
+
+ public Collection getTriggerableActions(String familyName)
+ {
+ return windowResult.getTriggerableActions(familyName);
+ }
+
+ public String getProperty(String name)
+ {
+ return (String)windowResult.getWindowProperties().get(name);
+ }
+ };
+ }
+
+ public PortletRenderContext getPortlet()
+ {
+ return new PortletRenderContext()
+ {
+ public String getMarkup()
+ {
+ return windowResult.getContent();
+ }
+
+ public String getProperty(String name)
+ {
+ return (String)windowResult.getWindowProperties().get(name);
+ }
+ };
+ }
+
+ public String getProperty(String name)
+ {
+ return (String)windowResult.getWindowProperties().get(name);
+ }
+ };
+
+ //
+ RenderContext renderCtx = new RenderContext(layout, (MarkupInfo)invocation.getResponse().getContentInfo(), prc, invocation.getRequest());
+ try
+ {
+ renderCtx.render(wrc);
+
+ //
+ DynaResponse dresp = new UpdateMarkupResponse(renderCtx.getMarkupFragment().toString());
+ AjaxResponse aresp = new AjaxResponse(dresp);
+ aresp.sendResponse(invocation.getServerContext());
+ }
+ catch (RenderException e)
+ {
+ e.printStackTrace();
+ }
+ }
}
else
{
Added: trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxResponse.java
===================================================================
--- trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxResponse.java (rev 0)
+++ trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxResponse.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -0,0 +1,58 @@
+/******************************************************************************
+ * JBoss, a division of Red Hat *
+ * Copyright 2006, Red Hat Middleware, LLC, and individual *
+ * contributors as indicated by the @authors tag. See the *
+ * copyright.txt in the distribution for a full listing of *
+ * individual contributors. *
+ * *
+ * This is free software; you can redistribute it and/or modify it *
+ * under the terms of the GNU Lesser General Public License as *
+ * published by the Free Software Foundation; either version 2.1 of *
+ * the License, or (at your option) any later version. *
+ * *
+ * This software is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
+ * Lesser General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU Lesser General Public *
+ * License along with this software; if not, write to the Free *
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org. *
+ ******************************************************************************/
+package org.jboss.portal.core.controller.ajax;
+
+import org.jboss.portal.core.controller.classic.HandlerResponse;
+import org.jboss.portal.theme.impl.render.dynamic.DynaResponse;
+import org.jboss.portal.theme.impl.render.dynamic.JSONMarshaller;
+import org.jboss.portal.server.ServerInvocationContext;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * @author <a href="mailto:julien@jboss.org">Julien Viet</a>
+ * @version $Revision: 1.1 $
+ */
+public class AjaxResponse extends HandlerResponse
+{
+
+ /** . */
+ private static final JSONMarshaller marshaller = new JSONMarshaller();
+
+ /** The response to the client. */
+ private final DynaResponse dynaResponse;
+
+ public AjaxResponse(DynaResponse dynaResponse)
+ {
+ this.dynaResponse = dynaResponse;
+ }
+
+ public void sendResponse(ServerInvocationContext ctx) throws IOException, ServletException
+ {
+ HttpServletResponse resp = ctx.getClientResponse();
+ resp.setContentType("text/html");
+ marshaller.write(dynaResponse, resp.getWriter());
+ }
+}
Modified: trunk/theme/src/bin/portal-ajax-war/js/portal/dyna.js
===================================================================
--- trunk/theme/src/bin/portal-ajax-war/js/portal/dyna.js 2007-03-31 14:25:31 UTC (rev 6896)
+++ trunk/theme/src/bin/portal-ajax-war/js/portal/dyna.js 2007-03-31 17:46:47 UTC (rev 6897)
@@ -39,34 +39,49 @@
function bilto(event)
{
- // Find container
+ // Locate the div container of the window
var source = Event.element(event);
- var container = Element.up(source, "div.dyna-portlet");
+ var container = Element.up(source, "div.dyna-window");
- // We found the div container
+ // We found the window
if (container != null) {
- // Handle links
+ // Handle links here
if (source.nodeName == "A") {
+ var url = source.href;
+ var parameters = "";
+ var pos = url.indexOf("?");
+ if (pos != -1) {
+ parameters = url.substring(pos + 1);
+ url = url.substring(0, pos);
+ }
+ var options = {
+ parameters:parameters,
+ asynchronous:true,
+ method:"get",
+ requestHeaders:["ajax","true"],
+ onSuccess: function(t)
+ {
+ var resp = "";
+ eval("resp =" + t.responseText + ";");
+ if (resp.type == "update_markup")
+ {
+ var markup = resp.markup;
+ Element.replace(container, markup);
+ }
+ else if (resp.type == "update_page")
+ {
+ var location = resp.location;
+ document.location = location;
+ }
+ }
+ };
-// " var url = source.href;
-// " var parameters = \"\";
-// " var pos = url.indexOf(\"?\");
-// " if (pos != -1) {
-// " parameters = url.substring(pos + 1);
-// " url = url.substring(0, pos);
-// " }
-// " var options = {
-// " parameters:parameters,
-// " asynchronous:true,
-// " method:\"get\",
-// " requestHeaders:[\"ajax\",\"true\"],
-// " };" +
-// " new Ajax.Request(url, options);
+ //
+ Event.stop(event);
+ new Ajax.Request(url, options);
}
-// " Element.replace(container, \"Some new content from the server\");
-// " Event.stop(event);
}
}
Modified: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaDecorationRenderer.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaDecorationRenderer.java 2007-03-31 14:25:31 UTC (rev 6896)
+++ trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaDecorationRenderer.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -56,9 +56,11 @@
//
StringBuffer markup = renderContext.getMarkupFragment();
+ markup.append("<div class=\"dyna-decoration\">\n");
markup.append("<div class=\"handle\">");
delegate.render(renderContext, drc);
- markup.append("</div>");
+ markup.append("</div>\n");
+ markup.append("</div>\n");
}
else
{
Added: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaResponse.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaResponse.java (rev 0)
+++ trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaResponse.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -0,0 +1,31 @@
+/******************************************************************************
+ * JBoss, a division of Red Hat *
+ * Copyright 2006, Red Hat Middleware, LLC, and individual *
+ * contributors as indicated by the @authors tag. See the *
+ * copyright.txt in the distribution for a full listing of *
+ * individual contributors. *
+ * *
+ * This is free software; you can redistribute it and/or modify it *
+ * under the terms of the GNU Lesser General Public License as *
+ * published by the Free Software Foundation; either version 2.1 of *
+ * the License, or (at your option) any later version. *
+ * *
+ * This software is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
+ * Lesser General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU Lesser General Public *
+ * License along with this software; if not, write to the Free *
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org. *
+ ******************************************************************************/
+package org.jboss.portal.theme.impl.render.dynamic;
+
+/**
+ * @author <a href="mailto:julien@jboss.org">Julien Viet</a>
+ * @version $Revision: 1.1 $
+ */
+public abstract class DynaResponse
+{
+}
Modified: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaWindowRenderer.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaWindowRenderer.java 2007-03-31 14:25:31 UTC (rev 6896)
+++ trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaWindowRenderer.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -60,9 +60,9 @@
handleProvided.set(Boolean.FALSE);
//
- renderContext.getMarkupFragment().append("<div id=\"").append(wrc.getId()).append("\">\n");
+ renderContext.getMarkupFragment().append("<div class=\"dyna-window\">\n");
delegate.render(renderContext, wrc);
- renderContext.getMarkupFragment().append("</div>");
+ renderContext.getMarkupFragment().append("</div>\n");
//
handleProvided.set(null);
Added: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/JSONMarshaller.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/JSONMarshaller.java (rev 0)
+++ trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/JSONMarshaller.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -0,0 +1,82 @@
+/******************************************************************************
+ * JBoss, a division of Red Hat *
+ * Copyright 2006, Red Hat Middleware, LLC, and individual *
+ * contributors as indicated by the @authors tag. See the *
+ * copyright.txt in the distribution for a full listing of *
+ * individual contributors. *
+ * *
+ * This is free software; you can redistribute it and/or modify it *
+ * under the terms of the GNU Lesser General Public License as *
+ * published by the Free Software Foundation; either version 2.1 of *
+ * the License, or (at your option) any later version. *
+ * *
+ * This software is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
+ * Lesser General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU Lesser General Public *
+ * License along with this software; if not, write to the Free *
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org. *
+ ******************************************************************************/
+package org.jboss.portal.theme.impl.render.dynamic;
+
+import org.jboss.portal.theme.impl.render.dynamic.response.UpdateMarkupResponse;
+import org.jboss.portal.theme.impl.render.dynamic.response.UpdatePageResponse;
+import org.jboss.portal.theme.impl.render.dynamic.json.JSONWriter;
+import org.jboss.portal.theme.impl.render.dynamic.json.JSONException;
+
+import java.io.Writer;
+import java.io.IOException;
+
+/**
+ * @author <a href="mailto:julien@jboss.org">Julien Viet</a>
+ * @version $Revision: 1.1 $
+ */
+public class JSONMarshaller
+{
+
+ public void write(DynaResponse response, Writer w) throws IOException
+ {
+ JSONWriter writer = new JSONWriter(w);
+
+ try
+ {
+ if (response instanceof UpdateMarkupResponse)
+ {
+ UpdateMarkupResponse umr = (UpdateMarkupResponse)response;
+ writer.object();
+ writer.key("type").value("update_markup");
+ writer.key("markup").value(umr.getMarkup());
+ writer.endObject();
+ }
+ else if (response instanceof UpdatePageResponse)
+ {
+ UpdatePageResponse upr = (UpdatePageResponse)response;
+ writer.object();
+ writer.key("type").value("update_page");
+ writer.key("location").value(upr.getLocation());
+ writer.endObject();
+ }
+ else
+ {
+ throw new IllegalArgumentException();
+ }
+ }
+ catch (JSONException e)
+ {
+ Throwable cause = e.getCause();
+ if (cause instanceof IOException)
+ {
+ throw (IOException)cause;
+ }
+ else
+ {
+ IOException ex = new IOException();
+ ex.initCause(e);
+ throw ex;
+ }
+ }
+ }
+}
Added: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONArray.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONArray.java (rev 0)
+++ trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONArray.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -0,0 +1,871 @@
+package org.jboss.portal.theme.impl.render.dynamic.json;
+
+/*
+Copyright (c) 2002 JSON.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+import java.io.IOException;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Map;
+
+/**
+ * A JSONArray is an ordered sequence of values. Its external text form is a
+ * string wrapped in square brackets with commas separating the values. The
+ * internal form is an object having <code>get</code> and <code>opt</code>
+ * methods for accessing the values by index, and <code>put</code> methods for
+ * adding or replacing values. The values can be any of these types:
+ * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
+ * <code>Number</code>, <code>String</code>, or the
+ * <code>JSONObject.NULL object</code>.
+ * <p>
+ * The constructor can convert a JSON text into a Java object. The
+ * <code>toString</code> method converts to JSON text.
+ * <p>
+ * A <code>get</code> method returns a value if one can be found, and throws an
+ * exception if one cannot be found. An <code>opt</code> method returns a
+ * default value instead of throwing an exception, and so is useful for
+ * obtaining optional values.
+ * <p>
+ * The generic <code>get()</code> and <code>opt()</code> methods return an
+ * object which you can cast or query for type. There are also typed
+ * <code>get</code> and <code>opt</code> methods that do type checking and type
+ * coersion for you.
+ * <p>
+ * The texts produced by the <code>toString</code> methods strictly conform to
+ * JSON syntax rules. The constructors are more forgiving in the texts they will
+ * accept:
+ * <ul>
+ * <li>An extra <code>,</code> <small>(comma)</small> may appear just
+ * before the closing bracket.</li>
+ * <li>The <code>null</code> value will be inserted when there
+ * is <code>,</code> <small>(comma)</small> elision.</li>
+ * <li>Strings may be quoted with <code>'</code> <small>(single
+ * quote)</small>.</li>
+ * <li>Strings do not need to be quoted at all if they do not begin with a quote
+ * or single quote, and if they do not contain leading or trailing spaces,
+ * and if they do not contain any of these characters:
+ * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers
+ * and if they are not the reserved words <code>true</code>,
+ * <code>false</code>, or <code>null</code>.</li>
+ * <li>Values can be separated by <code>;</code> <small>(semicolon)</small> as
+ * well as by <code>,</code> <small>(comma)</small>.</li>
+ * <li>Numbers may have the <code>0-</code> <small>(octal)</small> or
+ * <code>0x-</code> <small>(hex)</small> prefix.</li>
+ * <li>Comments written in the slashshlash, slashstar, and hash conventions
+ * will be ignored.</li>
+ * </ul>
+
+ * @author JSON.org
+ * @version 2
+ */
+public class JSONArray {
+
+
+ /**
+ * The arrayList where the JSONArray's properties are kept.
+ */
+ private ArrayList myArrayList;
+
+
+ /**
+ * Construct an empty JSONArray.
+ */
+ public JSONArray() {
+ this.myArrayList = new ArrayList();
+ }
+
+ /**
+ * Construct a JSONArray from a JSONTokener.
+ * @param x A JSONTokener
+ * @throws JSONException If there is a syntax error.
+ */
+ public JSONArray(JSONTokener x) throws JSONException {
+ this();
+ if (x.nextClean() != '[') {
+ throw x.syntaxError("A JSONArray text must start with '['");
+ }
+ if (x.nextClean() == ']') {
+ return;
+ }
+ x.back();
+ for (;;) {
+ if (x.nextClean() == ',') {
+ x.back();
+ this.myArrayList.add(null);
+ } else {
+ x.back();
+ this.myArrayList.add(x.nextValue());
+ }
+ switch (x.nextClean()) {
+ case ';':
+ case ',':
+ if (x.nextClean() == ']') {
+ return;
+ }
+ x.back();
+ break;
+ case ']':
+ return;
+ default:
+ throw x.syntaxError("Expected a ',' or ']'");
+ }
+ }
+ }
+
+
+ /**
+ * Construct a JSONArray from a source sJSON text.
+ * @param string A string that begins with
+ * <code>[</code> <small>(left bracket)</small>
+ * and ends with <code>]</code> <small>(right bracket)</small>.
+ * @throws JSONException If there is a syntax error.
+ */
+ public JSONArray(String string) throws JSONException {
+ this(new JSONTokener(string));
+ }
+
+
+ /**
+ * Construct a JSONArray from a Collection.
+ * @param collection A Collection.
+ */
+ public JSONArray(Collection collection) {
+ this.myArrayList = (collection == null) ?
+ new ArrayList() :
+ new ArrayList(collection);
+ }
+
+
+ /**
+ * Get the object value associated with an index.
+ * @param index
+ * The index must be between 0 and length() - 1.
+ * @return An object value.
+ * @throws JSONException If there is no value for the index.
+ */
+ public Object get(int index) throws JSONException {
+ Object o = opt(index);
+ if (o == null) {
+ throw new JSONException("JSONArray[" + index + "] not found.");
+ }
+ return o;
+ }
+
+
+ /**
+ * Get the boolean value associated with an index.
+ * The string values "true" and "false" are converted to boolean.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The truth.
+ * @throws JSONException If there is no value for the index or if the
+ * value is not convertable to boolean.
+ */
+ public boolean getBoolean(int index) throws JSONException {
+ Object o = get(index);
+ if (o.equals(Boolean.FALSE) ||
+ (o instanceof String &&
+ ((String)o).equalsIgnoreCase("false"))) {
+ return false;
+ } else if (o.equals(Boolean.TRUE) ||
+ (o instanceof String &&
+ ((String)o).equalsIgnoreCase("true"))) {
+ return true;
+ }
+ throw new JSONException("JSONArray[" + index + "] is not a Boolean.");
+ }
+
+
+ /**
+ * Get the double value associated with an index.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The value.
+ * @throws JSONException If the key is not found or if the value cannot
+ * be converted to a number.
+ */
+ public double getDouble(int index) throws JSONException {
+ Object o = get(index);
+ try {
+ return o instanceof Number ?
+ ((Number)o).doubleValue() :
+ Double.valueOf((String)o).doubleValue();
+ } catch (Exception e) {
+ throw new JSONException("JSONArray[" + index +
+ "] is not a number.");
+ }
+ }
+
+
+ /**
+ * Get the int value associated with an index.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The value.
+ * @throws JSONException If the key is not found or if the value cannot
+ * be converted to a number.
+ * if the value cannot be converted to a number.
+ */
+ public int getInt(int index) throws JSONException {
+ Object o = get(index);
+ return o instanceof Number ?
+ ((Number)o).intValue() : (int)getDouble(index);
+ }
+
+
+ /**
+ * Get the JSONArray associated with an index.
+ * @param index The index must be between 0 and length() - 1.
+ * @return A JSONArray value.
+ * @throws JSONException If there is no value for the index. or if the
+ * value is not a JSONArray
+ */
+ public JSONArray getJSONArray(int index) throws JSONException {
+ Object o = get(index);
+ if (o instanceof JSONArray) {
+ return (JSONArray)o;
+ }
+ throw new JSONException("JSONArray[" + index +
+ "] is not a JSONArray.");
+ }
+
+
+ /**
+ * Get the JSONObject associated with an index.
+ * @param index subscript
+ * @return A JSONObject value.
+ * @throws JSONException If there is no value for the index or if the
+ * value is not a JSONObject
+ */
+ public JSONObject getJSONObject(int index) throws JSONException {
+ Object o = get(index);
+ if (o instanceof JSONObject) {
+ return (JSONObject)o;
+ }
+ throw new JSONException("JSONArray[" + index +
+ "] is not a JSONObject.");
+ }
+
+
+ /**
+ * Get the long value associated with an index.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The value.
+ * @throws JSONException If the key is not found or if the value cannot
+ * be converted to a number.
+ */
+ public long getLong(int index) throws JSONException {
+ Object o = get(index);
+ return o instanceof Number ?
+ ((Number)o).longValue() : (long)getDouble(index);
+ }
+
+
+ /**
+ * Get the string associated with an index.
+ * @param index The index must be between 0 and length() - 1.
+ * @return A string value.
+ * @throws JSONException If there is no value for the index.
+ */
+ public String getString(int index) throws JSONException {
+ return get(index).toString();
+ }
+
+
+ /**
+ * Determine if the value is null.
+ * @param index The index must be between 0 and length() - 1.
+ * @return true if the value at the index is null, or if there is no value.
+ */
+ public boolean isNull(int index) {
+ return JSONObject.NULL.equals(opt(index));
+ }
+
+
+ /**
+ * Make a string from the contents of this JSONArray. The
+ * <code>separator</code> string is inserted between each element.
+ * Warning: This method assumes that the data structure is acyclical.
+ * @param separator A string that will be inserted between the elements.
+ * @return a string.
+ * @throws JSONException If the array contains an invalid number.
+ */
+ public String join(String separator) throws JSONException {
+ int len = length();
+ StringBuffer sb = new StringBuffer();
+
+ for (int i = 0; i < len; i += 1) {
+ if (i > 0) {
+ sb.append(separator);
+ }
+ sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
+ }
+ return sb.toString();
+ }
+
+
+ /**
+ * Get the number of elements in the JSONArray, included nulls.
+ *
+ * @return The length (or size).
+ */
+ public int length() {
+ return this.myArrayList.size();
+ }
+
+
+ /**
+ * Get the optional object value associated with an index.
+ * @param index The index must be between 0 and length() - 1.
+ * @return An object value, or null if there is no
+ * object at that index.
+ */
+ public Object opt(int index) {
+ return (index < 0 || index >= length()) ?
+ null : this.myArrayList.get(index);
+ }
+
+
+ /**
+ * Get the optional boolean value associated with an index.
+ * It returns false if there is no value at that index,
+ * or if the value is not Boolean.TRUE or the String "true".
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The truth.
+ */
+ public boolean optBoolean(int index) {
+ return optBoolean(index, false);
+ }
+
+
+ /**
+ * Get the optional boolean value associated with an index.
+ * It returns the defaultValue if there is no value at that index or if
+ * it is not a Boolean or the String "true" or "false" (case insensitive).
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @param defaultValue A boolean default.
+ * @return The truth.
+ */
+ public boolean optBoolean(int index, boolean defaultValue) {
+ try {
+ return getBoolean(index);
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+
+ /**
+ * Get the optional double value associated with an index.
+ * NaN is returned if there is no value for the index,
+ * or if the value is not a number and cannot be converted to a number.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The value.
+ */
+ public double optDouble(int index) {
+ return optDouble(index, Double.NaN);
+ }
+
+
+ /**
+ * Get the optional double value associated with an index.
+ * The defaultValue is returned if there is no value for the index,
+ * or if the value is not a number and cannot be converted to a number.
+ *
+ * @param index subscript
+ * @param defaultValue The default value.
+ * @return The value.
+ */
+ public double optDouble(int index, double defaultValue) {
+ try {
+ return getDouble(index);
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+
+ /**
+ * Get the optional int value associated with an index.
+ * Zero is returned if there is no value for the index,
+ * or if the value is not a number and cannot be converted to a number.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The value.
+ */
+ public int optInt(int index) {
+ return optInt(index, 0);
+ }
+
+
+ /**
+ * Get the optional int value associated with an index.
+ * The defaultValue is returned if there is no value for the index,
+ * or if the value is not a number and cannot be converted to a number.
+ * @param index The index must be between 0 and length() - 1.
+ * @param defaultValue The default value.
+ * @return The value.
+ */
+ public int optInt(int index, int defaultValue) {
+ try {
+ return getInt(index);
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+
+ /**
+ * Get the optional JSONArray associated with an index.
+ * @param index subscript
+ * @return A JSONArray value, or null if the index has no value,
+ * or if the value is not a JSONArray.
+ */
+ public JSONArray optJSONArray(int index) {
+ Object o = opt(index);
+ return o instanceof JSONArray ? (JSONArray)o : null;
+ }
+
+
+ /**
+ * Get the optional JSONObject associated with an index.
+ * Null is returned if the key is not found, or null if the index has
+ * no value, or if the value is not a JSONObject.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return A JSONObject value.
+ */
+ public JSONObject optJSONObject(int index) {
+ Object o = opt(index);
+ return o instanceof JSONObject ? (JSONObject)o : null;
+ }
+
+
+ /**
+ * Get the optional long value associated with an index.
+ * Zero is returned if there is no value for the index,
+ * or if the value is not a number and cannot be converted to a number.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The value.
+ */
+ public long optLong(int index) {
+ return optLong(index, 0);
+ }
+
+
+ /**
+ * Get the optional long value associated with an index.
+ * The defaultValue is returned if there is no value for the index,
+ * or if the value is not a number and cannot be converted to a number.
+ * @param index The index must be between 0 and length() - 1.
+ * @param defaultValue The default value.
+ * @return The value.
+ */
+ public long optLong(int index, long defaultValue) {
+ try {
+ return getLong(index);
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+
+ /**
+ * Get the optional string value associated with an index. It returns an
+ * empty string if there is no value at that index. If the value
+ * is not a string and is not null, then it is coverted to a string.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return A String value.
+ */
+ public String optString(int index) {
+ return optString(index, "");
+ }
+
+
+ /**
+ * Get the optional string associated with an index.
+ * The defaultValue is returned if the key is not found.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @param defaultValue The default value.
+ * @return A String value.
+ */
+ public String optString(int index, String defaultValue) {
+ Object o = opt(index);
+ return o != null ? o.toString() : defaultValue;
+ }
+
+
+ /**
+ * Append a boolean value. This increases the array's length by one.
+ *
+ * @param value A boolean value.
+ * @return this.
+ */
+ public JSONArray put(boolean value) {
+ put(value ? Boolean.TRUE : Boolean.FALSE);
+ return this;
+ }
+
+
+ /**
+ * Put a value in the JSONArray, where the value will be a
+ * JSONArray which is produced from a Collection.
+ * @param value A Collection value.
+ * @return this.
+ */
+ public JSONArray put(Collection value) {
+ put(new JSONArray(value));
+ return this;
+ }
+
+
+ /**
+ * Append a double value. This increases the array's length by one.
+ *
+ * @param value A double value.
+ * @throws JSONException if the value is not finite.
+ * @return this.
+ */
+ public JSONArray put(double value) throws JSONException {
+ Double d = new Double(value);
+ JSONObject.testValidity(d);
+ put(d);
+ return this;
+ }
+
+
+ /**
+ * Append an int value. This increases the array's length by one.
+ *
+ * @param value An int value.
+ * @return this.
+ */
+ public JSONArray put(int value) {
+ put(new Integer(value));
+ return this;
+ }
+
+
+ /**
+ * Append an long value. This increases the array's length by one.
+ *
+ * @param value A long value.
+ * @return this.
+ */
+ public JSONArray put(long value) {
+ put(new Long(value));
+ return this;
+ }
+
+
+ /**
+ * Put a value in the JSONArray, where the value will be a
+ * JSONObject which is produced from a Map.
+ * @param value A Map value.
+ * @return this.
+ */
+ public JSONArray put(Map value) {
+ put(new JSONObject(value));
+ return this;
+ }
+
+
+ /**
+ * Append an object value. This increases the array's length by one.
+ * @param value An object value. The value should be a
+ * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
+ * JSONObject.NULL object.
+ * @return this.
+ */
+ public JSONArray put(Object value) {
+ this.myArrayList.add(value);
+ return this;
+ }
+
+
+ /**
+ * Put or replace a boolean value in the JSONArray. If the index is greater
+ * than the length of the JSONArray, then null elements will be added as
+ * necessary to pad it out.
+ * @param index The subscript.
+ * @param value A boolean value.
+ * @return this.
+ * @throws JSONException If the index is negative.
+ */
+ public JSONArray put(int index, boolean value) throws JSONException {
+ put(index, value ? Boolean.TRUE : Boolean.FALSE);
+ return this;
+ }
+
+
+ /**
+ * Put a value in the JSONArray, where the value will be a
+ * JSONArray which is produced from a Collection.
+ * @param index The subscript.
+ * @param value A Collection value.
+ * @return this.
+ * @throws JSONException If the index is negative or if the value is
+ * not finite.
+ */
+ public JSONArray put(int index, Collection value) throws JSONException {
+ put(index, new JSONArray(value));
+ return this;
+ }
+
+
+ /**
+ * Put or replace a double value. If the index is greater than the length of
+ * the JSONArray, then null elements will be added as necessary to pad
+ * it out.
+ * @param index The subscript.
+ * @param value A double value.
+ * @return this.
+ * @throws JSONException If the index is negative or if the value is
+ * not finite.
+ */
+ public JSONArray put(int index, double value) throws JSONException {
+ put(index, new Double(value));
+ return this;
+ }
+
+
+ /**
+ * Put or replace an int value. If the index is greater than the length of
+ * the JSONArray, then null elements will be added as necessary to pad
+ * it out.
+ * @param index The subscript.
+ * @param value An int value.
+ * @return this.
+ * @throws JSONException If the index is negative.
+ */
+ public JSONArray put(int index, int value) throws JSONException {
+ put(index, new Integer(value));
+ return this;
+ }
+
+
+ /**
+ * Put or replace a long value. If the index is greater than the length of
+ * the JSONArray, then null elements will be added as necessary to pad
+ * it out.
+ * @param index The subscript.
+ * @param value A long value.
+ * @return this.
+ * @throws JSONException If the index is negative.
+ */
+ public JSONArray put(int index, long value) throws JSONException {
+ put(index, new Long(value));
+ return this;
+ }
+
+
+ /**
+ * Put a value in the JSONArray, where the value will be a
+ * JSONObject which is produced from a Map.
+ * @param index The subscript.
+ * @param value The Map value.
+ * @return this.
+ * @throws JSONException If the index is negative or if the the value is
+ * an invalid number.
+ */
+ public JSONArray put(int index, Map value) throws JSONException {
+ put(index, new JSONObject(value));
+ return this;
+ }
+
+
+ /**
+ * Put or replace an object value in the JSONArray. If the index is greater
+ * than the length of the JSONArray, then null elements will be added as
+ * necessary to pad it out.
+ * @param index The subscript.
+ * @param value The value to put into the array. The value should be a
+ * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
+ * JSONObject.NULL object.
+ * @return this.
+ * @throws JSONException If the index is negative or if the the value is
+ * an invalid number.
+ */
+ public JSONArray put(int index, Object value) throws JSONException {
+ JSONObject.testValidity(value);
+ if (index < 0) {
+ throw new JSONException("JSONArray[" + index + "] not found.");
+ }
+ if (index < length()) {
+ this.myArrayList.set(index, value);
+ } else {
+ while (index != length()) {
+ put(JSONObject.NULL);
+ }
+ put(value);
+ }
+ return this;
+ }
+
+
+ /**
+ * Produce a JSONObject by combining a JSONArray of names with the values
+ * of this JSONArray.
+ * @param names A JSONArray containing a list of key strings. These will be
+ * paired with the values.
+ * @return A JSONObject, or null if there are no names or if this JSONArray
+ * has no values.
+ * @throws JSONException If any of the names are null.
+ */
+ public JSONObject toJSONObject(JSONArray names) throws JSONException {
+ if (names == null || names.length() == 0 || length() == 0) {
+ return null;
+ }
+ JSONObject jo = new JSONObject();
+ for (int i = 0; i < names.length(); i += 1) {
+ jo.put(names.getString(i), this.opt(i));
+ }
+ return jo;
+ }
+
+
+ /**
+ * Make a JSON text of this JSONArray. For compactness, no
+ * unnecessary whitespace is added. If it is not possible to produce a
+ * syntactically correct JSON text then null will be returned instead. This
+ * could occur if the array contains an invalid number.
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ *
+ * @return a printable, displayable, transmittable
+ * representation of the array.
+ */
+ public String toString() {
+ try {
+ return '[' + join(",") + ']';
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+
+ /**
+ * Make a prettyprinted JSON text of this JSONArray.
+ * Warning: This method assumes that the data structure is acyclical.
+ * @param indentFactor The number of spaces to add to each level of
+ * indentation.
+ * @return a printable, displayable, transmittable
+ * representation of the object, beginning
+ * with <code>[</code> <small>(left bracket)</small> and ending
+ * with <code>]</code> <small>(right bracket)</small>.
+ * @throws JSONException
+ */
+ public String toString(int indentFactor) throws JSONException {
+ return toString(indentFactor, 0);
+ }
+
+
+ /**
+ * Make a prettyprinted JSON text of this JSONArray.
+ * Warning: This method assumes that the data structure is acyclical.
+ * @param indentFactor The number of spaces to add to each level of
+ * indentation.
+ * @param indent The indention of the top level.
+ * @return a printable, displayable, transmittable
+ * representation of the array.
+ * @throws JSONException
+ */
+ String toString(int indentFactor, int indent) throws JSONException {
+ int len = length();
+ if (len == 0) {
+ return "[]";
+ }
+ int i;
+ StringBuffer sb = new StringBuffer("[");
+ if (len == 1) {
+ sb.append(JSONObject.valueToString(this.myArrayList.get(0),
+ indentFactor, indent));
+ } else {
+ int newindent = indent + indentFactor;
+ sb.append('\n');
+ for (i = 0; i < len; i += 1) {
+ if (i > 0) {
+ sb.append(",\n");
+ }
+ for (int j = 0; j < newindent; j += 1) {
+ sb.append(' ');
+ }
+ sb.append(JSONObject.valueToString(this.myArrayList.get(i),
+ indentFactor, newindent));
+ }
+ sb.append('\n');
+ for (i = 0; i < indent; i += 1) {
+ sb.append(' ');
+ }
+ }
+ sb.append(']');
+ return sb.toString();
+ }
+
+
+ /**
+ * Write the contents of the JSONArray as JSON text to a writer.
+ * For compactness, no whitespace is added.
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ *
+ * @return The writer.
+ * @throws JSONException
+ */
+ public Writer write(Writer writer) throws JSONException {
+ try {
+ boolean b = false;
+ int len = length();
+
+ writer.write('[');
+
+ for (int i = 0; i < len; i += 1) {
+ if (b) {
+ writer.write(',');
+ }
+ Object v = this.myArrayList.get(i);
+ if (v instanceof JSONObject) {
+ ((JSONObject)v).write(writer);
+ } else if (v instanceof JSONArray) {
+ ((JSONArray)v).write(writer);
+ } else {
+ writer.write(JSONObject.valueToString(v));
+ }
+ b = true;
+ }
+ writer.write(']');
+ return writer;
+ } catch (IOException e) {
+ throw new JSONException(e);
+ }
+ }
+}
\ No newline at end of file
Added: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONException.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONException.java (rev 0)
+++ trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONException.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -0,0 +1,27 @@
+package org.jboss.portal.theme.impl.render.dynamic.json;
+
+/**
+ * The JSONException is thrown by the JSON.org classes then things are amiss.
+ * @author JSON.org
+ * @version 2
+ */
+public class JSONException extends Exception {
+ private Throwable cause;
+
+ /**
+ * Constructs a JSONException with an explanatory message.
+ * @param message Detail about the reason for the exception.
+ */
+ public JSONException(String message) {
+ super(message);
+ }
+
+ public JSONException(Throwable t) {
+ super(t.getMessage());
+ this.cause = t;
+ }
+
+ public Throwable getCause() {
+ return this.cause;
+ }
+}
Property changes on: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONException.java
___________________________________________________________________
Name: svn:executable
+ *
Added: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONObject.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONObject.java (rev 0)
+++ trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONObject.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -0,0 +1,1262 @@
+package org.jboss.portal.theme.impl.render.dynamic.json;
+
+/*
+Copyright (c) 2002 JSON.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+import java.util.Collection;
+import java.lang.reflect.Field;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.io.IOException;
+import java.io.Writer;
+
+/**
+ * A JSONObject is an unordered collection of name/value pairs. Its
+ * external form is a string wrapped in curly braces with colons between the
+ * names and values, and commas between the values and names. The internal form
+ * is an object having <code>get</code> and <code>opt</code> methods for
+ * accessing the values by name, and <code>put</code> methods for adding or
+ * replacing values by name. The values can be any of these types:
+ * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
+ * <code>Number</code>, <code>String</code>, or the <code>JSONObject.NULL</code>
+ * object. A JSONObject constructor can be used to convert an external form
+ * JSON text into an internal form whose values can be retrieved with the
+ * <code>get</code> and <code>opt</code> methods, or to convert values into a
+ * JSON text using the <code>put</code> and <code>toString</code> methods.
+ * A <code>get</code> method returns a value if one can be found, and throws an
+ * exception if one cannot be found. An <code>opt</code> method returns a
+ * default value instead of throwing an exception, and so is useful for
+ * obtaining optional values.
+ * <p>
+ * The generic <code>get()</code> and <code>opt()</code> methods return an
+ * object, which you can cast or query for type. There are also typed
+ * <code>get</code> and <code>opt</code> methods that do type checking and type
+ * coersion for you.
+ * <p>
+ * The <code>put</code> methods adds values to an object. For example, <pre>
+ * myString = new JSONObject().put("JSON", "Hello, World!").toString();</pre>
+ * produces the string <code>{"JSON": "Hello, World"}</code>.
+ * <p>
+ * The texts produced by the <code>toString</code> methods strictly conform to
+ * the JSON sysntax rules.
+ * The constructors are more forgiving in the texts they will accept:
+ * <ul>
+ * <li>An extra <code>,</code> <small>(comma)</small> may appear just
+ * before the closing brace.</li>
+ * <li>Strings may be quoted with <code>'</code> <small>(single
+ * quote)</small>.</li>
+ * <li>Strings do not need to be quoted at all if they do not begin with a quote
+ * or single quote, and if they do not contain leading or trailing spaces,
+ * and if they do not contain any of these characters:
+ * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers
+ * and if they are not the reserved words <code>true</code>,
+ * <code>false</code>, or <code>null</code>.</li>
+ * <li>Keys can be followed by <code>=</code> or <code>=></code> as well as
+ * by <code>:</code>.</li>
+ * <li>Values can be followed by <code>;</code> <small>(semicolon)</small> as
+ * well as by <code>,</code> <small>(comma)</small>.</li>
+ * <li>Numbers may have the <code>0-</code> <small>(octal)</small> or
+ * <code>0x-</code> <small>(hex)</small> prefix.</li>
+ * <li>Comments written in the slashshlash, slashstar, and hash conventions
+ * will be ignored.</li>
+ * </ul>
+ * @author JSON.org
+ * @version 2
+ */
+public class JSONObject {
+
+ /**
+ * JSONObject.NULL is equivalent to the value that JavaScript calls null,
+ * whilst Java's null is equivalent to the value that JavaScript calls
+ * undefined.
+ */
+ private static final class Null {
+
+ /**
+ * There is only intended to be a single instance of the NULL object,
+ * so the clone method returns itself.
+ * @return NULL.
+ */
+ protected final Object clone() {
+ return this;
+ }
+
+
+ /**
+ * A Null object is equal to the null value and to itself.
+ * @param object An object to test for nullness.
+ * @return true if the object parameter is the JSONObject.NULL object
+ * or null.
+ */
+ public boolean equals(Object object) {
+ return object == null || object == this;
+ }
+
+
+ /**
+ * Get the "null" string value.
+ * @return The string "null".
+ */
+ public String toString() {
+ return "null";
+ }
+ }
+
+
+ /**
+ * The hash map where the JSONObject's properties are kept.
+ */
+ private HashMap myHashMap;
+
+
+ /**
+ * It is sometimes more convenient and less ambiguous to have a
+ * <code>NULL</code> object than to use Java's <code>null</code> value.
+ * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.
+ * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>.
+ */
+ public static final Object NULL = new Null();
+
+
+ /**
+ * Construct an empty JSONObject.
+ */
+ public JSONObject() {
+ this.myHashMap = new HashMap();
+ }
+
+
+ /**
+ * Construct a JSONObject from a subset of another JSONObject.
+ * An array of strings is used to identify the keys that should be copied.
+ * Missing keys are ignored.
+ * @param jo A JSONObject.
+ * @param sa An array of strings.
+ * @exception JSONException If a value is a non-finite number.
+ */
+ public JSONObject(JSONObject jo, String[] sa) throws JSONException {
+ this();
+ for (int i = 0; i < sa.length; i += 1) {
+ putOpt(sa[i], jo.opt(sa[i]));
+ }
+ }
+
+
+ /**
+ * Construct a JSONObject from a JSONTokener.
+ * @param x A JSONTokener object containing the source string.
+ * @throws JSONException If there is a syntax error in the source string.
+ */
+ public JSONObject(JSONTokener x) throws JSONException {
+ this();
+ char c;
+ String key;
+
+ if (x.nextClean() != '{') {
+ throw x.syntaxError("A JSONObject text must begin with '{'");
+ }
+ for (;;) {
+ c = x.nextClean();
+ switch (c) {
+ case 0:
+ throw x.syntaxError("A JSONObject text must end with '}'");
+ case '}':
+ return;
+ default:
+ x.back();
+ key = x.nextValue().toString();
+ }
+
+ /*
+ * The key is followed by ':'. We will also tolerate '=' or '=>'.
+ */
+
+ c = x.nextClean();
+ if (c == '=') {
+ if (x.next() != '>') {
+ x.back();
+ }
+ } else if (c != ':') {
+ throw x.syntaxError("Expected a ':' after a key");
+ }
+ put(key, x.nextValue());
+
+ /*
+ * Pairs are separated by ','. We will also tolerate ';'.
+ */
+
+ switch (x.nextClean()) {
+ case ';':
+ case ',':
+ if (x.nextClean() == '}') {
+ return;
+ }
+ x.back();
+ break;
+ case '}':
+ return;
+ default:
+ throw x.syntaxError("Expected a ',' or '}'");
+ }
+ }
+ }
+
+
+ /**
+ * Construct a JSONObject from a Map.
+ * @param map A map object that can be used to initialize the contents of
+ * the JSONObject.
+ */
+ public JSONObject(Map map) {
+ this.myHashMap = (map == null) ?
+ new HashMap() :
+ new HashMap(map);
+ }
+
+
+ /**
+ * Construct a JSONObject from an Object, using reflection to find the
+ * public members. The resulting JSONObject's keys will be the strings
+ * from the names array, and the values will be the field values associated
+ * with those keys in the object. If a key is not found or not visible,
+ * then it will not be copied into the new JSONObject.
+ * @param object An object that has fields that should be used to make a
+ * JSONObject.
+ * @param names An array of strings, the names of the fields to be used
+ * from the object.
+ */
+ public JSONObject(Object object, String names[]) {
+ this();
+ Class c = object.getClass();
+ for (int i = 0; i < names.length; i += 1) {
+ try {
+ String name = names[i];
+ Field field = c.getField(name);
+ Object value = field.get(object);
+ this.put(name, value);
+ } catch (Exception e) {
+ /* forget about it */
+ }
+ }
+ }
+
+
+ /**
+ * Construct a JSONObject from a string.
+ * This is the most commonly used JSONObject constructor.
+ * @param string A string beginning
+ * with <code>{</code> <small>(left brace)</small> and ending
+ * with <code>}</code> <small>(right brace)</small>.
+ * @exception JSONException If there is a syntax error in the source string.
+ */
+ public JSONObject(String string) throws JSONException {
+ this(new JSONTokener(string));
+ }
+
+
+ /**
+ * Accumulate values under a key. It is similar to the put method except
+ * that if there is already an object stored under the key then a
+ * JSONArray is stored under the key to hold all of the accumulated values.
+ * If there is already a JSONArray, then the new value is appended to it.
+ * In contrast, the put method replaces the previous value.
+ * @param key A key string.
+ * @param value An object to be accumulated under the key.
+ * @return this.
+ * @throws JSONException If the value is an invalid number
+ * or if the key is null.
+ */
+ public JSONObject accumulate(String key, Object value)
+ throws JSONException {
+ testValidity(value);
+ Object o = opt(key);
+ if (o == null) {
+ put(key, value instanceof JSONArray ?
+ new JSONArray().put(value) :
+ value);
+ } else if (o instanceof JSONArray) {
+ ((JSONArray)o).put(value);
+ } else {
+ put(key, new JSONArray().put(o).put(value));
+ }
+ return this;
+ }
+
+
+ /**
+ * Append values to the array under a key. If the key does not exist in the
+ * JSONObject, then the key is put in the JSONObject with its value being a
+ * JSONArray containing the value parameter. If the key was already
+ * associated with a JSONArray, then the value parameter is appended to it.
+ * @param key A key string.
+ * @param value An object to be accumulated under the key.
+ * @return this.
+ * @throws JSONException If the key is null or if the current value
+ * associated with the key is not a JSONArray.
+ */
+ public JSONObject append(String key, Object value)
+ throws JSONException {
+ testValidity(value);
+ Object o = opt(key);
+ if (o == null) {
+ put(key, new JSONArray().put(value));
+ } else if (o instanceof JSONArray) {
+ put(key, ((JSONArray)o).put(value));
+ } else {
+ throw new JSONException("JSONObject[" + key +
+ "] is not a JSONArray.");
+ }
+ return this;
+ }
+
+
+ /**
+ * Produce a string from a double. The string "null" will be returned if
+ * the number is not finite.
+ * @param d A double.
+ * @return A String.
+ */
+ static public String doubleToString(double d) {
+ if (Double.isInfinite(d) || Double.isNaN(d)) {
+ return "null";
+ }
+
+// Shave off trailing zeros and decimal point, if possible.
+
+ String s = Double.toString(d);
+ if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
+ while (s.endsWith("0")) {
+ s = s.substring(0, s.length() - 1);
+ }
+ if (s.endsWith(".")) {
+ s = s.substring(0, s.length() - 1);
+ }
+ }
+ return s;
+ }
+
+
+ /**
+ * Get the value object associated with a key.
+ *
+ * @param key A key string.
+ * @return The object associated with the key.
+ * @throws JSONException if the key is not found.
+ */
+ public Object get(String key) throws JSONException {
+ Object o = opt(key);
+ if (o == null) {
+ throw new JSONException("JSONObject[" + quote(key) +
+ "] not found.");
+ }
+ return o;
+ }
+
+
+ /**
+ * Get the boolean value associated with a key.
+ *
+ * @param key A key string.
+ * @return The truth.
+ * @throws JSONException
+ * if the value is not a Boolean or the String "true" or "false".
+ */
+ public boolean getBoolean(String key) throws JSONException {
+ Object o = get(key);
+ if (o.equals(Boolean.FALSE) ||
+ (o instanceof String &&
+ ((String)o).equalsIgnoreCase("false"))) {
+ return false;
+ } else if (o.equals(Boolean.TRUE) ||
+ (o instanceof String &&
+ ((String)o).equalsIgnoreCase("true"))) {
+ return true;
+ }
+ throw new JSONException("JSONObject[" + quote(key) +
+ "] is not a Boolean.");
+ }
+
+
+ /**
+ * Get the double value associated with a key.
+ * @param key A key string.
+ * @return The numeric value.
+ * @throws JSONException if the key is not found or
+ * if the value is not a Number object and cannot be converted to a number.
+ */
+ public double getDouble(String key) throws JSONException {
+ Object o = get(key);
+ try {
+ return o instanceof Number ?
+ ((Number)o).doubleValue() :
+ Double.valueOf((String)o).doubleValue();
+ } catch (Exception e) {
+ throw new JSONException("JSONObject[" + quote(key) +
+ "] is not a number.");
+ }
+ }
+
+
+ /**
+ * Get the int value associated with a key. If the number value is too
+ * large for an int, it will be clipped.
+ *
+ * @param key A key string.
+ * @return The integer value.
+ * @throws JSONException if the key is not found or if the value cannot
+ * be converted to an integer.
+ */
+ public int getInt(String key) throws JSONException {
+ Object o = get(key);
+ return o instanceof Number ?
+ ((Number)o).intValue() : (int)getDouble(key);
+ }
+
+
+ /**
+ * Get the JSONArray value associated with a key.
+ *
+ * @param key A key string.
+ * @return A JSONArray which is the value.
+ * @throws JSONException if the key is not found or
+ * if the value is not a JSONArray.
+ */
+ public JSONArray getJSONArray(String key) throws JSONException {
+ Object o = get(key);
+ if (o instanceof JSONArray) {
+ return (JSONArray)o;
+ }
+ throw new JSONException("JSONObject[" + quote(key) +
+ "] is not a JSONArray.");
+ }
+
+
+ /**
+ * Get the JSONObject value associated with a key.
+ *
+ * @param key A key string.
+ * @return A JSONObject which is the value.
+ * @throws JSONException if the key is not found or
+ * if the value is not a JSONObject.
+ */
+ public JSONObject getJSONObject(String key) throws JSONException {
+ Object o = get(key);
+ if (o instanceof JSONObject) {
+ return (JSONObject)o;
+ }
+ throw new JSONException("JSONObject[" + quote(key) +
+ "] is not a JSONObject.");
+ }
+
+
+ /**
+ * Get the long value associated with a key. If the number value is too
+ * long for a long, it will be clipped.
+ *
+ * @param key A key string.
+ * @return The long value.
+ * @throws JSONException if the key is not found or if the value cannot
+ * be converted to a long.
+ */
+ public long getLong(String key) throws JSONException {
+ Object o = get(key);
+ return o instanceof Number ?
+ ((Number)o).longValue() : (long)getDouble(key);
+ }
+
+
+ /**
+ * Get the string associated with a key.
+ *
+ * @param key A key string.
+ * @return A string which is the value.
+ * @throws JSONException if the key is not found.
+ */
+ public String getString(String key) throws JSONException {
+ return get(key).toString();
+ }
+
+
+ /**
+ * Determine if the JSONObject contains a specific key.
+ * @param key A key string.
+ * @return true if the key exists in the JSONObject.
+ */
+ public boolean has(String key) {
+ return this.myHashMap.containsKey(key);
+ }
+
+
+ /**
+ * Determine if the value associated with the key is null or if there is
+ * no value.
+ * @param key A key string.
+ * @return true if there is no value associated with the key or if
+ * the value is the JSONObject.NULL object.
+ */
+ public boolean isNull(String key) {
+ return JSONObject.NULL.equals(opt(key));
+ }
+
+
+ /**
+ * Get an enumeration of the keys of the JSONObject.
+ *
+ * @return An iterator of the keys.
+ */
+ public Iterator keys() {
+ return this.myHashMap.keySet().iterator();
+ }
+
+
+ /**
+ * Get the number of keys stored in the JSONObject.
+ *
+ * @return The number of keys in the JSONObject.
+ */
+ public int length() {
+ return this.myHashMap.size();
+ }
+
+
+ /**
+ * Produce a JSONArray containing the names of the elements of this
+ * JSONObject.
+ * @return A JSONArray containing the key strings, or null if the JSONObject
+ * is empty.
+ */
+ public JSONArray names() {
+ JSONArray ja = new JSONArray();
+ Iterator keys = keys();
+ while (keys.hasNext()) {
+ ja.put(keys.next());
+ }
+ return ja.length() == 0 ? null : ja;
+ }
+
+ /**
+ * Produce a string from a Number.
+ * @param n A Number
+ * @return A String.
+ * @throws JSONException If n is a non-finite number.
+ */
+ static public String numberToString(Number n)
+ throws JSONException {
+ if (n == null) {
+ throw new JSONException("Null pointer");
+ }
+ testValidity(n);
+
+// Shave off trailing zeros and decimal point, if possible.
+
+ String s = n.toString();
+ if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
+ while (s.endsWith("0")) {
+ s = s.substring(0, s.length() - 1);
+ }
+ if (s.endsWith(".")) {
+ s = s.substring(0, s.length() - 1);
+ }
+ }
+ return s;
+ }
+
+
+ /**
+ * Get an optional value associated with a key.
+ * @param key A key string.
+ * @return An object which is the value, or null if there is no value.
+ */
+ public Object opt(String key) {
+ return key == null ? null : this.myHashMap.get(key);
+ }
+
+
+ /**
+ * Get an optional boolean associated with a key.
+ * It returns false if there is no such key, or if the value is not
+ * Boolean.TRUE or the String "true".
+ *
+ * @param key A key string.
+ * @return The truth.
+ */
+ public boolean optBoolean(String key) {
+ return optBoolean(key, false);
+ }
+
+
+ /**
+ * Get an optional boolean associated with a key.
+ * It returns the defaultValue if there is no such key, or if it is not
+ * a Boolean or the String "true" or "false" (case insensitive).
+ *
+ * @param key A key string.
+ * @param defaultValue The default.
+ * @return The truth.
+ */
+ public boolean optBoolean(String key, boolean defaultValue) {
+ try {
+ return getBoolean(key);
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+
+ /**
+ * Put a key/value pair in the JSONObject, where the value will be a
+ * JSONArray which is produced from a Collection.
+ * @param key A key string.
+ * @param value A Collection value.
+ * @return this.
+ * @throws JSONException
+ */
+ public JSONObject put(String key, Collection value) throws JSONException {
+ put(key, new JSONArray(value));
+ return this;
+ }
+
+
+ /**
+ * Get an optional double associated with a key,
+ * or NaN if there is no such key or if its value is not a number.
+ * If the value is a string, an attempt will be made to evaluate it as
+ * a number.
+ *
+ * @param key A string which is the key.
+ * @return An object which is the value.
+ */
+ public double optDouble(String key) {
+ return optDouble(key, Double.NaN);
+ }
+
+
+ /**
+ * Get an optional double associated with a key, or the
+ * defaultValue if there is no such key or if its value is not a number.
+ * If the value is a string, an attempt will be made to evaluate it as
+ * a number.
+ *
+ * @param key A key string.
+ * @param defaultValue The default.
+ * @return An object which is the value.
+ */
+ public double optDouble(String key, double defaultValue) {
+ try {
+ Object o = opt(key);
+ return o instanceof Number ? ((Number)o).doubleValue() :
+ new Double((String)o).doubleValue();
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+
+ /**
+ * Get an optional int value associated with a key,
+ * or zero if there is no such key or if the value is not a number.
+ * If the value is a string, an attempt will be made to evaluate it as
+ * a number.
+ *
+ * @param key A key string.
+ * @return An object which is the value.
+ */
+ public int optInt(String key) {
+ return optInt(key, 0);
+ }
+
+
+ /**
+ * Get an optional int value associated with a key,
+ * or the default if there is no such key or if the value is not a number.
+ * If the value is a string, an attempt will be made to evaluate it as
+ * a number.
+ *
+ * @param key A key string.
+ * @param defaultValue The default.
+ * @return An object which is the value.
+ */
+ public int optInt(String key, int defaultValue) {
+ try {
+ return getInt(key);
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+
+ /**
+ * Get an optional JSONArray associated with a key.
+ * It returns null if there is no such key, or if its value is not a
+ * JSONArray.
+ *
+ * @param key A key string.
+ * @return A JSONArray which is the value.
+ */
+ public JSONArray optJSONArray(String key) {
+ Object o = opt(key);
+ return o instanceof JSONArray ? (JSONArray)o : null;
+ }
+
+
+ /**
+ * Get an optional JSONObject associated with a key.
+ * It returns null if there is no such key, or if its value is not a
+ * JSONObject.
+ *
+ * @param key A key string.
+ * @return A JSONObject which is the value.
+ */
+ public JSONObject optJSONObject(String key) {
+ Object o = opt(key);
+ return o instanceof JSONObject ? (JSONObject)o : null;
+ }
+
+
+ /**
+ * Get an optional long value associated with a key,
+ * or zero if there is no such key or if the value is not a number.
+ * If the value is a string, an attempt will be made to evaluate it as
+ * a number.
+ *
+ * @param key A key string.
+ * @return An object which is the value.
+ */
+ public long optLong(String key) {
+ return optLong(key, 0);
+ }
+
+
+ /**
+ * Get an optional long value associated with a key,
+ * or the default if there is no such key or if the value is not a number.
+ * If the value is a string, an attempt will be made to evaluate it as
+ * a number.
+ *
+ * @param key A key string.
+ * @param defaultValue The default.
+ * @return An object which is the value.
+ */
+ public long optLong(String key, long defaultValue) {
+ try {
+ return getLong(key);
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+
+ /**
+ * Get an optional string associated with a key.
+ * It returns an empty string if there is no such key. If the value is not
+ * a string and is not null, then it is coverted to a string.
+ *
+ * @param key A key string.
+ * @return A string which is the value.
+ */
+ public String optString(String key) {
+ return optString(key, "");
+ }
+
+
+ /**
+ * Get an optional string associated with a key.
+ * It returns the defaultValue if there is no such key.
+ *
+ * @param key A key string.
+ * @param defaultValue The default.
+ * @return A string which is the value.
+ */
+ public String optString(String key, String defaultValue) {
+ Object o = opt(key);
+ return o != null ? o.toString() : defaultValue;
+ }
+
+
+ /**
+ * Put a key/boolean pair in the JSONObject.
+ *
+ * @param key A key string.
+ * @param value A boolean which is the value.
+ * @return this.
+ * @throws JSONException If the key is null.
+ */
+ public JSONObject put(String key, boolean value) throws JSONException {
+ put(key, value ? Boolean.TRUE : Boolean.FALSE);
+ return this;
+ }
+
+
+ /**
+ * Put a key/double pair in the JSONObject.
+ *
+ * @param key A key string.
+ * @param value A double which is the value.
+ * @return this.
+ * @throws JSONException If the key is null or if the number is invalid.
+ */
+ public JSONObject put(String key, double value) throws JSONException {
+ put(key, new Double(value));
+ return this;
+ }
+
+
+ /**
+ * Put a key/int pair in the JSONObject.
+ *
+ * @param key A key string.
+ * @param value An int which is the value.
+ * @return this.
+ * @throws JSONException If the key is null.
+ */
+ public JSONObject put(String key, int value) throws JSONException {
+ put(key, new Integer(value));
+ return this;
+ }
+
+
+ /**
+ * Put a key/long pair in the JSONObject.
+ *
+ * @param key A key string.
+ * @param value A long which is the value.
+ * @return this.
+ * @throws JSONException If the key is null.
+ */
+ public JSONObject put(String key, long value) throws JSONException {
+ put(key, new Long(value));
+ return this;
+ }
+
+
+ /**
+ * Put a key/value pair in the JSONObject, where the value will be a
+ * JSONObject which is produced from a Map.
+ * @param key A key string.
+ * @param value A Map value.
+ * @return this.
+ * @throws JSONException
+ */
+ public JSONObject put(String key, Map value) throws JSONException {
+ put(key, new JSONObject(value));
+ return this;
+ }
+
+
+ /**
+ * Put a key/value pair in the JSONObject. If the value is null,
+ * then the key will be removed from the JSONObject if it is present.
+ * @param key A key string.
+ * @param value An object which is the value. It should be of one of these
+ * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
+ * or the JSONObject.NULL object.
+ * @return this.
+ * @throws JSONException If the value is non-finite number
+ * or if the key is null.
+ */
+ public JSONObject put(String key, Object value) throws JSONException {
+ if (key == null) {
+ throw new JSONException("Null key.");
+ }
+ if (value != null) {
+ testValidity(value);
+ this.myHashMap.put(key, value);
+ } else {
+ remove(key);
+ }
+ return this;
+ }
+
+
+ /**
+ * Put a key/value pair in the JSONObject, but only if the
+ * key and the value are both non-null.
+ * @param key A key string.
+ * @param value An object which is the value. It should be of one of these
+ * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
+ * or the JSONObject.NULL object.
+ * @return this.
+ * @throws JSONException If the value is a non-finite number.
+ */
+ public JSONObject putOpt(String key, Object value) throws JSONException {
+ if (key != null && value != null) {
+ put(key, value);
+ }
+ return this;
+ }
+
+
+ /**
+ * Produce a string in double quotes with backslash sequences in all the
+ * right places. A backslash will be inserted within </, allowing JSON
+ * text to be delivered in HTML. In JSON text, a string cannot contain a
+ * control character or an unescaped quote or backslash.
+ * @param string A String
+ * @return A String correctly formatted for insertion in a JSON text.
+ */
+ public static String quote(String string) {
+ if (string == null || string.length() == 0) {
+ return "\"\"";
+ }
+
+ char b;
+ char c = 0;
+ int i;
+ int len = string.length();
+ StringBuffer sb = new StringBuffer(len + 4);
+ String t;
+
+ sb.append('"');
+ for (i = 0; i < len; i += 1) {
+ b = c;
+ c = string.charAt(i);
+ switch (c) {
+ case '\\':
+ case '"':
+ sb.append('\\');
+ sb.append(c);
+ break;
+ case '/':
+ if (b == '<') {
+ sb.append('\\');
+ }
+ sb.append(c);
+ break;
+ case '\b':
+ sb.append("\\b");
+ break;
+ case '\t':
+ sb.append("\\t");
+ break;
+ case '\n':
+ sb.append("\\n");
+ break;
+ case '\f':
+ sb.append("\\f");
+ break;
+ case '\r':
+ sb.append("\\r");
+ break;
+ default:
+ if (c < ' ' || (c >= '\u0080' && c < '\u00a0') ||
+ (c >= '\u2000' && c < '\u2100')) {
+ t = "000" + Integer.toHexString(c);
+ sb.append("\\u" + t.substring(t.length() - 4));
+ } else {
+ sb.append(c);
+ }
+ }
+ }
+ sb.append('"');
+ return sb.toString();
+ }
+
+ /**
+ * Remove a name and its value, if present.
+ * @param key The name to be removed.
+ * @return The value that was associated with the name,
+ * or null if there was no value.
+ */
+ public Object remove(String key) {
+ return this.myHashMap.remove(key);
+ }
+
+
+ /**
+ * Throw an exception if the object is an NaN or infinite number.
+ * @param o The object to test.
+ * @throws JSONException If o is a non-finite number.
+ */
+ static void testValidity(Object o) throws JSONException {
+ if (o != null) {
+ if (o instanceof Double) {
+ if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
+ throw new JSONException(
+ "JSON does not allow non-finite numbers.");
+ }
+ } else if (o instanceof Float) {
+ if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
+ throw new JSONException(
+ "JSON does not allow non-finite numbers.");
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Produce a JSONArray containing the values of the members of this
+ * JSONObject.
+ * @param names A JSONArray containing a list of key strings. This
+ * determines the sequence of the values in the result.
+ * @return A JSONArray of values.
+ * @throws JSONException If any of the values are non-finite numbers.
+ */
+ public JSONArray toJSONArray(JSONArray names) throws JSONException {
+ if (names == null || names.length() == 0) {
+ return null;
+ }
+ JSONArray ja = new JSONArray();
+ for (int i = 0; i < names.length(); i += 1) {
+ ja.put(this.opt(names.getString(i)));
+ }
+ return ja;
+ }
+
+ /**
+ * Make a JSON text of this JSONObject. For compactness, no whitespace
+ * is added. If this would not result in a syntactically correct JSON text,
+ * then null will be returned instead.
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ *
+ * @return a printable, displayable, portable, transmittable
+ * representation of the object, beginning
+ * with <code>{</code> <small>(left brace)</small> and ending
+ * with <code>}</code> <small>(right brace)</small>.
+ */
+ public String toString() {
+ try {
+ Iterator keys = keys();
+ StringBuffer sb = new StringBuffer("{");
+
+ while (keys.hasNext()) {
+ if (sb.length() > 1) {
+ sb.append(',');
+ }
+ Object o = keys.next();
+ sb.append(quote(o.toString()));
+ sb.append(':');
+ sb.append(valueToString(this.myHashMap.get(o)));
+ }
+ sb.append('}');
+ return sb.toString();
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+
+ /**
+ * Make a prettyprinted JSON text of this JSONObject.
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ * @param indentFactor The number of spaces to add to each level of
+ * indentation.
+ * @return a printable, displayable, portable, transmittable
+ * representation of the object, beginning
+ * with <code>{</code> <small>(left brace)</small> and ending
+ * with <code>}</code> <small>(right brace)</small>.
+ * @throws JSONException If the object contains an invalid number.
+ */
+ public String toString(int indentFactor) throws JSONException {
+ return toString(indentFactor, 0);
+ }
+
+
+ /**
+ * Make a prettyprinted JSON text of this JSONObject.
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ * @param indentFactor The number of spaces to add to each level of
+ * indentation.
+ * @param indent The indentation of the top level.
+ * @return a printable, displayable, transmittable
+ * representation of the object, beginning
+ * with <code>{</code> <small>(left brace)</small> and ending
+ * with <code>}</code> <small>(right brace)</small>.
+ * @throws JSONException If the object contains an invalid number.
+ */
+ String toString(int indentFactor, int indent) throws JSONException {
+ int i;
+ int n = length();
+ if (n == 0) {
+ return "{}";
+ }
+ Iterator keys = keys();
+ StringBuffer sb = new StringBuffer("{");
+ int newindent = indent + indentFactor;
+ Object o;
+ if (n == 1) {
+ o = keys.next();
+ sb.append(quote(o.toString()));
+ sb.append(": ");
+ sb.append(valueToString(this.myHashMap.get(o), indentFactor,
+ indent));
+ } else {
+ while (keys.hasNext()) {
+ o = keys.next();
+ if (sb.length() > 1) {
+ sb.append(",\n");
+ } else {
+ sb.append('\n');
+ }
+ for (i = 0; i < newindent; i += 1) {
+ sb.append(' ');
+ }
+ sb.append(quote(o.toString()));
+ sb.append(": ");
+ sb.append(valueToString(this.myHashMap.get(o), indentFactor,
+ newindent));
+ }
+ if (sb.length() > 1) {
+ sb.append('\n');
+ for (i = 0; i < indent; i += 1) {
+ sb.append(' ');
+ }
+ }
+ }
+ sb.append('}');
+ return sb.toString();
+ }
+
+
+ /**
+ * Make a JSON text of an Object value. If the object has an
+ * value.toJSONString() method, then that method will be used to produce
+ * the JSON text. The method is required to produce a strictly
+ * conforming text. If the object does not contain a toJSONString
+ * method (which is the most common case), then a text will be
+ * produced by the rules.
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ * @param value The value to be serialized.
+ * @return a printable, displayable, transmittable
+ * representation of the object, beginning
+ * with <code>{</code> <small>(left brace)</small> and ending
+ * with <code>}</code> <small>(right brace)</small>.
+ * @throws JSONException If the value is or contains an invalid number.
+ */
+ static String valueToString(Object value) throws JSONException {
+ if (value == null || value.equals(null)) {
+ return "null";
+ }
+ if (value instanceof JSONString) {
+ Object o;
+ try {
+ o = ((JSONString)value).toJSONString();
+ } catch (Exception e) {
+ throw new JSONException(e);
+ }
+ if (o instanceof String) {
+ return (String)o;
+ }
+ throw new JSONException("Bad value from toJSONString: " + o);
+ }
+ if (value instanceof Number) {
+ return numberToString((Number) value);
+ }
+ if (value instanceof Boolean || value instanceof JSONObject ||
+ value instanceof JSONArray) {
+ return value.toString();
+ }
+ return quote(value.toString());
+ }
+
+
+ /**
+ * Make a prettyprinted JSON text of an object value.
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ * @param value The value to be serialized.
+ * @param indentFactor The number of spaces to add to each level of
+ * indentation.
+ * @param indent The indentation of the top level.
+ * @return a printable, displayable, transmittable
+ * representation of the object, beginning
+ * with <code>{</code> <small>(left brace)</small> and ending
+ * with <code>}</code> <small>(right brace)</small>.
+ * @throws JSONException If the object contains an invalid number.
+ */
+ static String valueToString(Object value, int indentFactor, int indent)
+ throws JSONException {
+ if (value == null || value.equals(null)) {
+ return "null";
+ }
+ try {
+ if (value instanceof JSONString) {
+ Object o = ((JSONString)value).toJSONString();
+ if (o instanceof String) {
+ return (String)o;
+ }
+ }
+ } catch (Exception e) {
+ /* forget about it */
+ }
+ if (value instanceof Number) {
+ return numberToString((Number) value);
+ }
+ if (value instanceof Boolean) {
+ return value.toString();
+ }
+ if (value instanceof JSONObject) {
+ return ((JSONObject)value).toString(indentFactor, indent);
+ }
+ if (value instanceof JSONArray) {
+ return ((JSONArray)value).toString(indentFactor, indent);
+ }
+ return quote(value.toString());
+ }
+
+
+ /**
+ * Write the contents of the JSONObject as JSON text to a writer.
+ * For compactness, no whitespace is added.
+ * <p>
+ * Warning: This method assumes that the data structure is acyclical.
+ *
+ * @return The writer.
+ * @throws JSONException
+ */
+ public Writer write(Writer writer) throws JSONException {
+ try {
+ boolean b = false;
+ Iterator keys = keys();
+ writer.write('{');
+
+ while (keys.hasNext()) {
+ if (b) {
+ writer.write(',');
+ }
+ Object k = keys.next();
+ writer.write(quote(k.toString()));
+ writer.write(':');
+ Object v = this.myHashMap.get(k);
+ if (v instanceof JSONObject) {
+ ((JSONObject)v).write(writer);
+ } else if (v instanceof JSONArray) {
+ ((JSONArray)v).write(writer);
+ } else {
+ writer.write(valueToString(v));
+ }
+ b = true;
+ }
+ writer.write('}');
+ return writer;
+ } catch (IOException e) {
+ throw new JSONException(e);
+ }
+ }
+}
\ No newline at end of file
Added: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONString.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONString.java (rev 0)
+++ trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONString.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -0,0 +1,18 @@
+package org.jboss.portal.theme.impl.render.dynamic.json;
+/**
+ * The <code>JSONString</code> interface allows a <code>toJSONString()</code>
+ * method so that a class can change the behavior of
+ * <code>JSONObject.toString()</code>, <code>JSONArray.toString()</code>,
+ * and <code>JSONWriter.value(</code>Object<code>)</code>. The
+ * <code>toJSONString</code> method will be used instead of the default behavior
+ * of using the Object's <code>toString()</code> method and quoting the result.
+ */
+public interface JSONString {
+ /**
+ * The <code>toJSONString</code> method allows a class to produce its own JSON
+ * serialization.
+ *
+ * @return A strictly syntactically correct JSON text.
+ */
+ public String toJSONString();
+}
Added: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONStringer.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONStringer.java (rev 0)
+++ trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONStringer.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -0,0 +1,78 @@
+package org.jboss.portal.theme.impl.render.dynamic.json;
+
+/*
+Copyright (c) 2006 JSON.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+import java.io.StringWriter;
+
+/**
+ * JSONStringer provides a quick and convenient way of producing JSON text.
+ * The texts produced strictly conform to JSON syntax rules. No whitespace is
+ * added, so the results are ready for transmission or storage. Each instance of
+ * JSONStringer can produce one JSON text.
+ * <p>
+ * A JSONStringer instance provides a <code>value</code> method for appending
+ * values to the
+ * text, and a <code>key</code>
+ * method for adding keys before values in objects. There are <code>array</code>
+ * and <code>endArray</code> methods that make and bound array values, and
+ * <code>object</code> and <code>endObject</code> methods which make and bound
+ * object values. All of these methods return the JSONWriter instance,
+ * permitting cascade style. For example, <pre>
+ * myString = new JSONStringer()
+ * .object()
+ * .key("JSON")
+ * .value("Hello, World!")
+ * .endObject()
+ * .toString();</pre> which produces the string <pre>
+ * {"JSON":"Hello, World!"}</pre>
+ * <p>
+ * The first method called must be <code>array</code> or <code>object</code>.
+ * There are no methods for adding commas or colons. JSONStringer adds them for
+ * you. Objects and arrays can be nested up to 20 levels deep.
+ * <p>
+ * This can sometimes be easier than using a JSONObject to build a string.
+ * @author JSON.org
+ * @version 2
+ */
+public class JSONStringer extends JSONWriter {
+ /**
+ * Make a fresh JSONStringer. It can be used to build one JSON text.
+ */
+ public JSONStringer() {
+ super(new StringWriter());
+ }
+
+ /**
+ * Return the JSON text. This method is used to obtain the product of the
+ * JSONStringer instance. It will return <code>null</code> if there was a
+ * problem in the construction of the JSON text (such as the calls to
+ * <code>array</code> were not properly balanced with calls to
+ * <code>endArray</code>).
+ * @return The JSON text.
+ */
+ public String toString() {
+ return this.mode == 'd' ? this.writer.toString() : null;
+ }
+}
Added: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONTokener.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONTokener.java (rev 0)
+++ trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONTokener.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -0,0 +1,462 @@
+package org.jboss.portal.theme.impl.render.dynamic.json;
+
+/*
+Copyright (c) 2002 JSON.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+/**
+ * A JSONTokener takes a source string and extracts characters and tokens from
+ * it. It is used by the JSONObject and JSONArray constructors to parse
+ * JSON source strings.
+ * @author JSON.org
+ * @version 2
+ */
+public class JSONTokener {
+
+ /**
+ * The index of the next character.
+ */
+ private int myIndex;
+
+
+ /**
+ * The source string being tokenized.
+ */
+ private String mySource;
+
+
+ /**
+ * Construct a JSONTokener from a string.
+ *
+ * @param s A source string.
+ */
+ public JSONTokener(String s) {
+ this.myIndex = 0;
+ this.mySource = s;
+ }
+
+
+ /**
+ * Back up one character. This provides a sort of lookahead capability,
+ * so that you can test for a digit or letter before attempting to parse
+ * the next number or identifier.
+ */
+ public void back() {
+ if (this.myIndex > 0) {
+ this.myIndex -= 1;
+ }
+ }
+
+
+
+ /**
+ * Get the hex value of a character (base16).
+ * @param c A character between '0' and '9' or between 'A' and 'F' or
+ * between 'a' and 'f'.
+ * @return An int between 0 and 15, or -1 if c was not a hex digit.
+ */
+ public static int dehexchar(char c) {
+ if (c >= '0' && c <= '9') {
+ return c - '0';
+ }
+ if (c >= 'A' && c <= 'F') {
+ return c - ('A' - 10);
+ }
+ if (c >= 'a' && c <= 'f') {
+ return c - ('a' - 10);
+ }
+ return -1;
+ }
+
+
+ /**
+ * Determine if the source string still contains characters that next()
+ * can consume.
+ * @return true if not yet at the end of the source.
+ */
+ public boolean more() {
+ return this.myIndex < this.mySource.length();
+ }
+
+
+ /**
+ * Get the next character in the source string.
+ *
+ * @return The next character, or 0 if past the end of the source string.
+ */
+ public char next() {
+ if (more()) {
+ char c = this.mySource.charAt(this.myIndex);
+ this.myIndex += 1;
+ return c;
+ }
+ return 0;
+ }
+
+
+ /**
+ * Consume the next character, and check that it matches a specified
+ * character.
+ * @param c The character to match.
+ * @return The character.
+ * @throws JSONException if the character does not match.
+ */
+ public char next(char c) throws JSONException {
+ char n = next();
+ if (n != c) {
+ throw syntaxError("Expected '" + c + "' and instead saw '" +
+ n + "'");
+ }
+ return n;
+ }
+
+
+ /**
+ * Get the next n characters.
+ *
+ * @param n The number of characters to take.
+ * @return A string of n characters.
+ * @throws JSONException
+ * Substring bounds error if there are not
+ * n characters remaining in the source string.
+ */
+ public String next(int n) throws JSONException {
+ int i = this.myIndex;
+ int j = i + n;
+ if (j >= this.mySource.length()) {
+ throw syntaxError("Substring bounds error");
+ }
+ this.myIndex += n;
+ return this.mySource.substring(i, j);
+ }
+
+
+ /**
+ * Get the next char in the string, skipping whitespace
+ * and comments (slashslash, slashstar, and hash).
+ * @throws JSONException
+ * @return A character, or 0 if there are no more characters.
+ */
+ public char nextClean() throws JSONException {
+ for (;;) {
+ char c = next();
+ if (c == '/') {
+ switch (next()) {
+ case '/':
+ do {
+ c = next();
+ } while (c != '\n' && c != '\r' && c != 0);
+ break;
+ case '*':
+ for (;;) {
+ c = next();
+ if (c == 0) {
+ throw syntaxError("Unclosed comment");
+ }
+ if (c == '*') {
+ if (next() == '/') {
+ break;
+ }
+ back();
+ }
+ }
+ break;
+ default:
+ back();
+ return '/';
+ }
+ } else if (c == '#') {
+ do {
+ c = next();
+ } while (c != '\n' && c != '\r' && c != 0);
+ } else if (c == 0 || c > ' ') {
+ return c;
+ }
+ }
+ }
+
+
+ /**
+ * Return the characters up to the next close quote character.
+ * Backslash processing is done. The formal JSON format does not
+ * allow strings in single quotes, but an implementation is allowed to
+ * accept them.
+ * @param quote The quoting character, either
+ * <code>"</code> <small>(double quote)</small> or
+ * <code>'</code> <small>(single quote)</small>.
+ * @return A String.
+ * @throws JSONException Unterminated string.
+ */
+ public String nextString(char quote) throws JSONException {
+ char c;
+ StringBuffer sb = new StringBuffer();
+ for (;;) {
+ c = next();
+ switch (c) {
+ case 0:
+ case '\n':
+ case '\r':
+ throw syntaxError("Unterminated string");
+ case '\\':
+ c = next();
+ switch (c) {
+ case 'b':
+ sb.append('\b');
+ break;
+ case 't':
+ sb.append('\t');
+ break;
+ case 'n':
+ sb.append('\n');
+ break;
+ case 'f':
+ sb.append('\f');
+ break;
+ case 'r':
+ sb.append('\r');
+ break;
+ case 'u':
+ sb.append((char)Integer.parseInt(next(4), 16));
+ break;
+ case 'x' :
+ sb.append((char) Integer.parseInt(next(2), 16));
+ break;
+ default:
+ sb.append(c);
+ }
+ break;
+ default:
+ if (c == quote) {
+ return sb.toString();
+ }
+ sb.append(c);
+ }
+ }
+ }
+
+
+ /**
+ * Get the text up but not including the specified character or the
+ * end of line, whichever comes first.
+ * @param d A delimiter character.
+ * @return A string.
+ */
+ public String nextTo(char d) {
+ StringBuffer sb = new StringBuffer();
+ for (;;) {
+ char c = next();
+ if (c == d || c == 0 || c == '\n' || c == '\r') {
+ if (c != 0) {
+ back();
+ }
+ return sb.toString().trim();
+ }
+ sb.append(c);
+ }
+ }
+
+
+ /**
+ * Get the text up but not including one of the specified delimeter
+ * characters or the end of line, whichever comes first.
+ * @param delimiters A set of delimiter characters.
+ * @return A string, trimmed.
+ */
+ public String nextTo(String delimiters) {
+ char c;
+ StringBuffer sb = new StringBuffer();
+ for (;;) {
+ c = next();
+ if (delimiters.indexOf(c) >= 0 || c == 0 ||
+ c == '\n' || c == '\r') {
+ if (c != 0) {
+ back();
+ }
+ return sb.toString().trim();
+ }
+ sb.append(c);
+ }
+ }
+
+
+ /**
+ * Get the next value. The value can be a Boolean, Double, Integer,
+ * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
+ * @throws JSONException If syntax error.
+ *
+ * @return An object.
+ */
+ public Object nextValue() throws JSONException {
+ char c = nextClean();
+ String s;
+
+ switch (c) {
+ case '"':
+ case '\'':
+ return nextString(c);
+ case '{':
+ back();
+ return new JSONObject(this);
+ case '[':
+ back();
+ return new JSONArray(this);
+ }
+
+ /*
+ * Handle unquoted text. This could be the values true, false, or
+ * null, or it can be a number. An implementation (such as this one)
+ * is allowed to also accept non-standard forms.
+ *
+ * Accumulate characters until we reach the end of the text or a
+ * formatting character.
+ */
+
+ StringBuffer sb = new StringBuffer();
+ char b = c;
+ while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
+ sb.append(c);
+ c = next();
+ }
+ back();
+
+ /*
+ * If it is true, false, or null, return the proper value.
+ */
+
+ s = sb.toString().trim();
+ if (s.equals("")) {
+ throw syntaxError("Missing value");
+ }
+ if (s.equalsIgnoreCase("true")) {
+ return Boolean.TRUE;
+ }
+ if (s.equalsIgnoreCase("false")) {
+ return Boolean.FALSE;
+ }
+ if (s.equalsIgnoreCase("null")) {
+ return JSONObject.NULL;
+ }
+
+ /*
+ * If it might be a number, try converting it. We support the 0- and 0x-
+ * conventions. If a number cannot be produced, then the value will just
+ * be a string. Note that the 0-, 0x-, plus, and implied string
+ * conventions are non-standard. A JSON parser is free to accept
+ * non-JSON forms as long as it accepts all correct JSON forms.
+ */
+
+ if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {
+ if (b == '0') {
+ if (s.length() > 2 &&
+ (s.charAt(1) == 'x' || s.charAt(1) == 'X')) {
+ try {
+ return new Integer(Integer.parseInt(s.substring(2),
+ 16));
+ } catch (Exception e) {
+ /* Ignore the error */
+ }
+ } else {
+ try {
+ return new Integer(Integer.parseInt(s, 8));
+ } catch (Exception e) {
+ /* Ignore the error */
+ }
+ }
+ }
+ try {
+ return new Integer(s);
+ } catch (Exception e) {
+ try {
+ return new Long(s);
+ } catch (Exception f) {
+ try {
+ return new Double(s);
+ } catch (Exception g) {
+ return s;
+ }
+ }
+ }
+ }
+ return s;
+ }
+
+
+ /**
+ * Skip characters until the next character is the requested character.
+ * If the requested character is not found, no characters are skipped.
+ * @param to A character to skip to.
+ * @return The requested character, or zero if the requested character
+ * is not found.
+ */
+ public char skipTo(char to) {
+ char c;
+ int index = this.myIndex;
+ do {
+ c = next();
+ if (c == 0) {
+ this.myIndex = index;
+ return c;
+ }
+ } while (c != to);
+ back();
+ return c;
+ }
+
+
+ /**
+ * Skip characters until past the requested string.
+ * If it is not found, we are left at the end of the source.
+ * @param to A string to skip past.
+ */
+ public boolean skipPast(String to) {
+ this.myIndex = this.mySource.indexOf(to, this.myIndex);
+ if (this.myIndex < 0) {
+ this.myIndex = this.mySource.length();
+ return false;
+ }
+ this.myIndex += to.length();
+ return true;
+
+ }
+
+
+ /**
+ * Make a JSONException to signal a syntax error.
+ *
+ * @param message The error message.
+ * @return A JSONException object, suitable for throwing
+ */
+ public JSONException syntaxError(String message) {
+ return new JSONException(message + toString());
+ }
+
+
+ /**
+ * Make a printable string of this JSONTokener.
+ *
+ * @return " at character [this.myIndex] of [this.mySource]"
+ */
+ public String toString() {
+ return " at character " + this.myIndex + " of " + this.mySource;
+ }
+}
\ No newline at end of file
Added: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONWriter.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONWriter.java (rev 0)
+++ trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONWriter.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -0,0 +1,318 @@
+package org.jboss.portal.theme.impl.render.dynamic.json;
+
+import java.io.IOException;
+import java.io.Writer;
+
+/*
+Copyright (c) 2006 JSON.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+/**
+ * JSONWriter provides a quick and convenient way of producing JSON text.
+ * The texts produced strictly conform to JSON syntax rules. No whitespace is
+ * added, so the results are ready for transmission or storage. Each instance of
+ * JSONWriter can produce one JSON text.
+ * <p>
+ * A JSONWriter instance provides a <code>value</code> method for appending
+ * values to the
+ * text, and a <code>key</code>
+ * method for adding keys before values in objects. There are <code>array</code>
+ * and <code>endArray</code> methods that make and bound array values, and
+ * <code>object</code> and <code>endObject</code> methods which make and bound
+ * object values. All of these methods return the JSONWriter instance,
+ * permitting a cascade style. For example, <pre>
+ * new JSONWriter(myWriter)
+ * .object()
+ * .key("JSON")
+ * .value("Hello, World!")
+ * .endObject();</pre> which writes <pre>
+ * {"JSON":"Hello, World!"}</pre>
+ * <p>
+ * The first method called must be <code>array</code> or <code>object</code>.
+ * There are no methods for adding commas or colons. JSONWriter adds them for
+ * you. Objects and arrays can be nested up to 20 levels deep.
+ * <p>
+ * This can sometimes be easier than using a JSONObject to build a string.
+ * @author JSON.org
+ * @version 2
+ */
+public class JSONWriter {
+ private static final int maxdepth = 20;
+
+ /**
+ * The comma flag determines if a comma should be output before the next
+ * value.
+ */
+ private boolean comma;
+
+ /**
+ * The current mode. Values:
+ * 'a' (array),
+ * 'd' (done),
+ * 'i' (initial),
+ * 'k' (key),
+ * 'o' (object).
+ */
+ protected char mode;
+
+ /**
+ * The object/array stack.
+ */
+ private char stack[];
+
+ /**
+ * The stack top index. A value of 0 indicates that the stack is empty.
+ */
+ private int top;
+
+ /**
+ * The writer that will receive the output.
+ */
+ protected Writer writer;
+
+ /**
+ * Make a fresh JSONWriter. It can be used to build one JSON text.
+ */
+ public JSONWriter(Writer w) {
+ this.comma = false;
+ this.mode = 'i';
+ this.stack = new char[maxdepth];
+ this.top = 0;
+ this.writer = w;
+ }
+
+ /**
+ * Append a value.
+ * @param s A string value.
+ * @return this
+ * @throws JSONException If the value is out of sequence.
+ */
+ private JSONWriter append(String s) throws JSONException {
+ if (s == null) {
+ throw new JSONException("Null pointer");
+ }
+ if (this.mode == 'o' || this.mode == 'a') {
+ try {
+ if (this.comma && this.mode == 'a') {
+ this.writer.write(',');
+ }
+ this.writer.write(s);
+ } catch (IOException e) {
+ throw new JSONException(e);
+ }
+ if (this.mode == 'o') {
+ this.mode = 'k';
+ }
+ this.comma = true;
+ return this;
+ }
+ throw new JSONException("Value out of sequence.");
+ }
+
+ /**
+ * Begin appending a new array. All values until the balancing
+ * <code>endArray</code> will be appended to this array. The
+ * <code>endArray</code> method must be called to mark the array's end.
+ * @return this
+ * @throws JSONException If the nesting is too deep, or if the object is
+ * started in the wrong place (for example as a key or after the end of the
+ * outermost array or object).
+ */
+ public JSONWriter array() throws JSONException {
+ if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') {
+ this.push('a');
+ this.append("[");
+ this.comma = false;
+ return this;
+ }
+ throw new JSONException("Misplaced array.");
+ }
+
+ /**
+ * End something.
+ * @param m Mode
+ * @param c Closing character
+ * @return this
+ * @throws JSONException If unbalanced.
+ */
+ private JSONWriter end(char m, char c) throws JSONException {
+ if (this.mode != m) {
+ throw new JSONException(m == 'o' ? "Misplaced endObject." :
+ "Misplaced endArray.");
+ }
+ this.pop(m);
+ try {
+ this.writer.write(c);
+ } catch (IOException e) {
+ throw new JSONException(e);
+ }
+ this.comma = true;
+ return this;
+ }
+
+ /**
+ * End an array. This method most be called to balance calls to
+ * <code>array</code>.
+ * @return this
+ * @throws JSONException If incorrectly nested.
+ */
+ public JSONWriter endArray() throws JSONException {
+ return this.end('a', ']');
+ }
+
+ /**
+ * End an object. This method most be called to balance calls to
+ * <code>object</code>.
+ * @return this
+ * @throws JSONException If incorrectly nested.
+ */
+ public JSONWriter endObject() throws JSONException {
+ return this.end('k', '}');
+ }
+
+ /**
+ * Append a key. The key will be associated with the next value. In an
+ * object, every value must be preceded by a key.
+ * @param s A key string.
+ * @return this
+ * @throws JSONException If the key is out of place. For example, keys
+ * do not belong in arrays or if the key is null.
+ */
+ public JSONWriter key(String s) throws JSONException {
+ if (s == null) {
+ throw new JSONException("Null key.");
+ }
+ if (this.mode == 'k') {
+ try {
+ if (this.comma) {
+ this.writer.write(',');
+ }
+ this.writer.write(JSONObject.quote(s));
+ this.writer.write(':');
+ this.comma = false;
+ this.mode = 'o';
+ return this;
+ } catch (IOException e) {
+ throw new JSONException(e);
+ }
+ }
+ throw new JSONException("Misplaced key.");
+ }
+
+
+ /**
+ * Begin appending a new object. All keys and values until the balancing
+ * <code>endObject</code> will be appended to this object. The
+ * <code>endObject</code> method must be called to mark the object's end.
+ * @return this
+ * @throws JSONException If the nesting is too deep, or if the object is
+ * started in the wrong place (for example as a key or after the end of the
+ * outermost array or object).
+ */
+ public JSONWriter object() throws JSONException {
+ if (this.mode == 'i') {
+ this.mode = 'o';
+ }
+ if (this.mode == 'o' || this.mode == 'a') {
+ this.append("{");
+ this.push('k');
+ this.comma = false;
+ return this;
+ }
+ throw new JSONException("Misplaced object.");
+
+ }
+
+
+ /**
+ * Pop an array or object scope.
+ * @param c The scope to close.
+ * @throws JSONException If nesting is wrong.
+ */
+ private void pop(char c) throws JSONException {
+ if (this.top <= 0 || this.stack[this.top - 1] != c) {
+ throw new JSONException("Nesting error.");
+ }
+ this.top -= 1;
+ this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1];
+ }
+
+ /**
+ * Push an array or object scope.
+ * @param c The scope to open.
+ * @throws JSONException If nesting is too deep.
+ */
+ private void push(char c) throws JSONException {
+ if (this.top >= maxdepth) {
+ throw new JSONException("Nesting too deep.");
+ }
+ this.stack[this.top] = c;
+ this.mode = c;
+ this.top += 1;
+ }
+
+
+ /**
+ * Append either the value <code>true</code> or the value
+ * <code>false</code>.
+ * @param b A boolean.
+ * @return this
+ * @throws JSONException
+ */
+ public JSONWriter value(boolean b) throws JSONException {
+ return this.append(b ? "true" : "false");
+ }
+
+ /**
+ * Append a double value.
+ * @param d A double.
+ * @return this
+ * @throws JSONException If the number is not finite.
+ */
+ public JSONWriter value(double d) throws JSONException {
+ return this.value(new Double(d));
+ }
+
+ /**
+ * Append a long value.
+ * @param l A long.
+ * @return this
+ * @throws JSONException
+ */
+ public JSONWriter value(long l) throws JSONException {
+ return this.append(Long.toString(l));
+ }
+
+
+ /**
+ * Append an object value.
+ * @param o The object to append. It can be null, or a Boolean, Number,
+ * String, JSONObject, or JSONArray, or an object with a toJSONString()
+ * method.
+ * @return this
+ * @throws JSONException If the value is out of sequence.
+ */
+ public JSONWriter value(Object o) throws JSONException {
+ return this.append(JSONObject.valueToString(o));
+ }
+}
Property changes on: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/json/JSONWriter.java
___________________________________________________________________
Name: svn:executable
+ *
Added: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/response/UpdateMarkupResponse.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/response/UpdateMarkupResponse.java (rev 0)
+++ trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/response/UpdateMarkupResponse.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -0,0 +1,50 @@
+/******************************************************************************
+ * JBoss, a division of Red Hat *
+ * Copyright 2006, Red Hat Middleware, LLC, and individual *
+ * contributors as indicated by the @authors tag. See the *
+ * copyright.txt in the distribution for a full listing of *
+ * individual contributors. *
+ * *
+ * This is free software; you can redistribute it and/or modify it *
+ * under the terms of the GNU Lesser General Public License as *
+ * published by the Free Software Foundation; either version 2.1 of *
+ * the License, or (at your option) any later version. *
+ * *
+ * This software is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
+ * Lesser General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU Lesser General Public *
+ * License along with this software; if not, write to the Free *
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org. *
+ ******************************************************************************/
+package org.jboss.portal.theme.impl.render.dynamic.response;
+
+import org.jboss.portal.theme.impl.render.dynamic.DynaResponse;
+
+/**
+ * @author <a href="mailto:julien@jboss.org">Julien Viet</a>
+ * @version $Revision: 1.1 $
+ */
+public class UpdateMarkupResponse extends DynaResponse
+{
+
+ /** . */
+ private String markup;
+
+ public UpdateMarkupResponse(String markup)
+ {
+ if (markup == null)
+ {
+ throw new IllegalArgumentException();
+ }
+ this.markup = markup;
+ }
+
+ public String getMarkup()
+ {
+ return markup;
+ }
+}
Added: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/response/UpdatePageResponse.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/response/UpdatePageResponse.java (rev 0)
+++ trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/response/UpdatePageResponse.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -0,0 +1,46 @@
+/******************************************************************************
+ * JBoss, a division of Red Hat *
+ * Copyright 2006, Red Hat Middleware, LLC, and individual *
+ * contributors as indicated by the @authors tag. See the *
+ * copyright.txt in the distribution for a full listing of *
+ * individual contributors. *
+ * *
+ * This is free software; you can redistribute it and/or modify it *
+ * under the terms of the GNU Lesser General Public License as *
+ * published by the Free Software Foundation; either version 2.1 of *
+ * the License, or (at your option) any later version. *
+ * *
+ * This software is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
+ * Lesser General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU Lesser General Public *
+ * License along with this software; if not, write to the Free *
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org. *
+ ******************************************************************************/
+package org.jboss.portal.theme.impl.render.dynamic.response;
+
+import org.jboss.portal.theme.impl.render.dynamic.DynaResponse;
+
+/**
+ * @author <a href="mailto:julien@jboss.org">Julien Viet</a>
+ * @version $Revision: 1.1 $
+ */
+public class UpdatePageResponse extends DynaResponse
+{
+
+ /** . */
+ private final String location;
+
+ public UpdatePageResponse(String location)
+ {
+ this.location = location;
+ }
+
+ public String getLocation()
+ {
+ return location;
+ }
+}
Modified: trunk/theme/src/main/org/jboss/portal/theme/page/render/DecorationRenderContextImpl.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/page/render/DecorationRenderContextImpl.java 2007-03-31 14:25:31 UTC (rev 6896)
+++ trunk/theme/src/main/org/jboss/portal/theme/page/render/DecorationRenderContextImpl.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -60,14 +60,4 @@
{
return wrc.getProperty(name);
}
-
- public String getProperty(String name, int scope)
- {
- return getProperty(name);
- }
-
- public WindowRenderContext getWindow()
- {
- return wrc;
- }
}
Modified: trunk/theme/src/main/org/jboss/portal/theme/page/render/WindowRenderContextImpl.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/page/render/WindowRenderContextImpl.java 2007-03-31 14:25:31 UTC (rev 6896)
+++ trunk/theme/src/main/org/jboss/portal/theme/page/render/WindowRenderContextImpl.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -85,14 +85,4 @@
{
return (String)result.getWindowProperties().get(name);
}
-
- public String getProperty(String name, int scope)
- {
- return getProperty(name);
- }
-
- public RegionRenderContext getRegion()
- {
- return region;
- }
}
Modified: trunk/theme/src/main/org/jboss/portal/theme/render/WindowRenderContext.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/render/WindowRenderContext.java 2007-03-31 14:25:31 UTC (rev 6896)
+++ trunk/theme/src/main/org/jboss/portal/theme/render/WindowRenderContext.java 2007-03-31 17:46:47 UTC (rev 6897)
@@ -44,6 +44,4 @@
PortletRenderContext getPortlet();
- RegionRenderContext getRegion();
-
}
17 years, 7 months
JBoss Portal SVN: r6896 - in trunk/theme/src: main/org/jboss/portal/theme/impl/render/dynamic and 1 other directory.
by portal-commits@lists.jboss.org
Author: julien(a)jboss.com
Date: 2007-03-31 10:25:31 -0400 (Sat, 31 Mar 2007)
New Revision: 6896
Added:
trunk/theme/src/bin/portal-ajax-war/js/portal/dyna.js
Removed:
trunk/theme/src/bin/portal-ajax-war/js/portal/event.js
Modified:
trunk/theme/src/bin/portal-ajax-war/js/portal/builder.js
trunk/theme/src/bin/portal-ajax-war/js/portal/controls.js
trunk/theme/src/bin/portal-ajax-war/js/portal/dragdrop.js
trunk/theme/src/bin/portal-ajax-war/js/portal/effects.js
trunk/theme/src/bin/portal-ajax-war/js/portal/prototype.js
trunk/theme/src/bin/portal-ajax-war/js/portal/scriptaculous.js
trunk/theme/src/bin/portal-ajax-war/js/portal/slider.js
trunk/theme/src/bin/portal-ajax-war/js/portal/unittest.js
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaRegionRenderer.java
Log:
- updated to scriptaculous 1.7
- put dyna scripts in dyna.js instead of inlining them in the markup
Modified: trunk/theme/src/bin/portal-ajax-war/js/portal/builder.js
===================================================================
--- trunk/theme/src/bin/portal-ajax-war/js/portal/builder.js 2007-03-31 14:21:37 UTC (rev 6895)
+++ trunk/theme/src/bin/portal-ajax-war/js/portal/builder.js 2007-03-31 14:25:31 UTC (rev 6896)
@@ -1,8 +1,9 @@
-// script.aculo.us builder.js v1.6.4, Wed Sep 06 11:30:58 CEST 2006
+// script.aculo.us builder.js v1.7.0, Fri Jan 19 19:16:36 CET 2007
-// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
-// See scriptaculous.js for full license.
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
var Builder = {
NODEMAP: {
@@ -35,7 +36,7 @@
var element = parentElement.firstChild || null;
// see if browser added wrapping tags
- if(element && (element.tagName != elementName))
+ if(element && (element.tagName.toUpperCase() != elementName))
element = element.getElementsByTagName(elementName)[0];
// fallback to createElement approach
@@ -63,7 +64,7 @@
for(attr in arguments[1])
element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
}
- if(element.tagName != elementName)
+ if(element.tagName.toUpperCase() != elementName)
element = parentElement.getElementsByTagName(elementName)[0];
}
}
@@ -77,10 +78,16 @@
_text: function(text) {
return document.createTextNode(text);
},
+
+ ATTR_MAP: {
+ 'className': 'class',
+ 'htmlFor': 'for'
+ },
+
_attributes: function(attributes) {
var attrs = [];
for(attribute in attributes)
- attrs.push((attribute=='className' ? 'class' : attribute) +
+ attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
'="' + attributes[attribute].toString().escapeHTML() + '"');
return attrs.join(" ");
},
@@ -100,6 +107,11 @@
_isStringOrNumber: function(param) {
return(typeof param=='string' || typeof param=='number');
},
+ build: function(html) {
+ var element = this.node('div');
+ $(element).update(html.strip());
+ return element.down();
+ },
dump: function(scope) {
if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope
@@ -116,4 +128,4 @@
}
});
}
-}
\ No newline at end of file
+}
Modified: trunk/theme/src/bin/portal-ajax-war/js/portal/controls.js
===================================================================
--- trunk/theme/src/bin/portal-ajax-war/js/portal/controls.js 2007-03-31 14:21:37 UTC (rev 6895)
+++ trunk/theme/src/bin/portal-ajax-war/js/portal/controls.js 2007-03-31 14:25:31 UTC (rev 6896)
@@ -1,14 +1,15 @@
-// script.aculo.us controls.js v1.6.4, Wed Sep 06 11:30:58 CEST 2006
+// script.aculo.us controls.js v1.7.0, Fri Jan 19 19:16:36 CET 2007
-// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-// (c) 2005 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
-// (c) 2005 Jon Tirsen (http://www.tirsen.com)
+// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005, 2006 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
+// (c) 2005, 2006 Jon Tirsen (http://www.tirsen.com)
// Contributors:
// Richard Livsey
// Rahul Bhargava
// Rob Wills
//
-// See scriptaculous.js for full license.
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
// Autocompleter.Base handles all the autocompletion functionality
// that's independent of the data source for autocompletion. This
@@ -264,11 +265,11 @@
if(!this.changed && this.hasFocus) {
this.update.innerHTML = choices;
Element.cleanWhitespace(this.update);
- Element.cleanWhitespace(this.update.firstChild);
+ Element.cleanWhitespace(this.update.down());
- if(this.update.firstChild && this.update.firstChild.childNodes) {
+ if(this.update.firstChild && this.update.down().childNodes) {
this.entryCount =
- this.update.firstChild.childNodes.length;
+ this.update.down().childNodes.length;
for (var i = 0; i < this.entryCount; i++) {
var entry = this.getEntry(i);
entry.autocompleteIndex = i;
@@ -474,6 +475,7 @@
this.element = $(element);
this.options = Object.extend({
+ paramName: "value",
okButton: true,
okText: "ok",
cancelLink: true,
@@ -605,7 +607,7 @@
var textField = document.createElement("input");
textField.obj = this;
textField.type = "text";
- textField.name = "value";
+ textField.name = this.options.paramName;
textField.value = text;
textField.style.backgroundColor = this.options.highlightcolor;
textField.className = 'editor_field';
@@ -618,7 +620,7 @@
this.options.textarea = true;
var textArea = document.createElement("textarea");
textArea.obj = this;
- textArea.name = "value";
+ textArea.name = this.options.paramName;
textArea.value = this.convertHTMLLineBreaks(text);
textArea.rows = this.options.rows;
textArea.cols = this.options.cols || 40;
Modified: trunk/theme/src/bin/portal-ajax-war/js/portal/dragdrop.js
===================================================================
--- trunk/theme/src/bin/portal-ajax-war/js/portal/dragdrop.js 2007-03-31 14:21:37 UTC (rev 6895)
+++ trunk/theme/src/bin/portal-ajax-war/js/portal/dragdrop.js 2007-03-31 14:25:31 UTC (rev 6896)
@@ -1,12 +1,11 @@
-// script.aculo.us dragdrop.js v1.6.4, Wed Sep 06 11:30:58 CEST 2006
+// script.aculo.us dragdrop.js v1.7.0, Fri Jan 19 19:16:36 CET 2007
-// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-// (c) 2005 Sammi Williams (http://www.oriontransfer.co.nz, sammi(a)oriontransfer.co.nz)
-//
-// See scriptaculous.js for full license.
+// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005, 2006 Sammi Williams (http://www.oriontransfer.co.nz, sammi(a)oriontransfer.co.nz)
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
-/*--------------------------------------------------------------------------*/
-
if(typeof Effect == 'undefined')
throw("dragdrop.js requires including script.aculo.us' effects.js library");
@@ -29,14 +28,14 @@
if(options.containment) {
options._containers = [];
var containment = options.containment;
- if((typeof containment == 'object') &&
+ if((typeof containment == 'object') &&
(containment.constructor == Array)) {
containment.each( function(c) { options._containers.push($(c)) });
} else {
options._containers.push($(containment));
}
}
-
+
if(options.accept) options.accept = [options.accept].flatten();
Element.makePositioned(element); // fix IE
@@ -44,34 +43,34 @@
this.drops.push(options);
},
-
+
findDeepestChild: function(drops) {
deepest = drops[0];
-
+
for (i = 1; i < drops.length; ++i)
if (Element.isParent(drops[i].element, deepest.element))
deepest = drops[i];
-
+
return deepest;
},
isContained: function(element, drop) {
var containmentNode;
if(drop.tree) {
- containmentNode = element.treeNode;
+ containmentNode = element.treeNode;
} else {
containmentNode = element.parentNode;
}
return drop._containers.detect(function(c) { return containmentNode == c });
},
-
+
isAffected: function(point, element, drop) {
return (
(drop.element!=element) &&
((!drop._containers) ||
this.isContained(element, drop)) &&
((!drop.accept) ||
- (Element.classNames(element).detect(
+ (Element.classNames(element).detect(
function(v) { return drop.accept.include(v) } ) )) &&
Position.within(drop.element, point[0], point[1]) );
},
@@ -91,19 +90,19 @@
show: function(point, element) {
if(!this.drops.length) return;
var affected = [];
-
+
if(this.last_active) this.deactivate(this.last_active);
this.drops.each( function(drop) {
if(Droppables.isAffected(point, element, drop))
affected.push(drop);
});
-
+
if(affected.length>0) {
drop = Droppables.findDeepestChild(affected);
Position.within(drop.element, point[0], point[1]);
if(drop.onHover)
drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
-
+
Droppables.activate(drop);
}
},
@@ -113,7 +112,7 @@
Position.prepare();
if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
- if (this.last_active.onDrop)
+ if (this.last_active.onDrop)
this.last_active.onDrop(element, this.last_active.element, event);
},
@@ -126,20 +125,20 @@
var Draggables = {
drags: [],
observers: [],
-
+
register: function(draggable) {
if(this.drags.length == 0) {
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
this.eventKeypress = this.keyPress.bindAsEventListener(this);
-
+
Event.observe(document, "mouseup", this.eventMouseUp);
Event.observe(document, "mousemove", this.eventMouseMove);
Event.observe(document, "keypress", this.eventKeypress);
}
this.drags.push(draggable);
},
-
+
unregister: function(draggable) {
this.drags = this.drags.reject(function(d) { return d==draggable });
if(this.drags.length == 0) {
@@ -148,24 +147,24 @@
Event.stopObserving(document, "keypress", this.eventKeypress);
}
},
-
+
activate: function(draggable) {
- if(draggable.options.delay) {
- this._timeout = setTimeout(function() {
- Draggables._timeout = null;
- window.focus();
- Draggables.activeDraggable = draggable;
- }.bind(this), draggable.options.delay);
+ if(draggable.options.delay) {
+ this._timeout = setTimeout(function() {
+ Draggables._timeout = null;
+ window.focus();
+ Draggables.activeDraggable = draggable;
+ }.bind(this), draggable.options.delay);
} else {
window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
this.activeDraggable = draggable;
}
},
-
+
deactivate: function() {
this.activeDraggable = null;
},
-
+
updateDrag: function(event) {
if(!this.activeDraggable) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
@@ -173,36 +172,36 @@
// the same coordinates, prevent needless redrawing (moz bug?)
if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
this._lastPointer = pointer;
-
+
this.activeDraggable.updateDrag(event, pointer);
},
-
+
endDrag: function(event) {
- if(this._timeout) {
- clearTimeout(this._timeout);
- this._timeout = null;
+ if(this._timeout) {
+ clearTimeout(this._timeout);
+ this._timeout = null;
}
if(!this.activeDraggable) return;
this._lastPointer = null;
this.activeDraggable.endDrag(event);
this.activeDraggable = null;
},
-
+
keyPress: function(event) {
if(this.activeDraggable)
this.activeDraggable.keyPress(event);
},
-
+
addObserver: function(observer) {
this.observers.push(observer);
this._cacheObserverCallbacks();
},
-
+
removeObserver: function(element) { // element instead of observer fixes mem leaks
this.observers = this.observers.reject( function(o) { return o.element==element });
this._cacheObserverCallbacks();
},
-
+
notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
if(this[eventName+'Count'] > 0)
this.observers.each( function(o) {
@@ -210,7 +209,7 @@
});
if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
},
-
+
_cacheObserverCallbacks: function() {
['onStart','onEnd','onDrag'].each( function(eventName) {
Draggables[eventName+'Count'] = Draggables.observers.select(
@@ -237,12 +236,12 @@
},
endeffect: function(element) {
var toOpacity = typeof element._opacity == 'number' ? element._opacity : 1.0;
- new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
+ new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
queue: {scope:'_draggable', position:'end'},
- afterFinish: function(){
- Draggable._dragging[element] = false
+ afterFinish: function(){
+ Draggable._dragging[element] = false
}
- });
+ });
},
zindex: 1000,
revert: false,
@@ -252,91 +251,90 @@
snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
delay: 0
};
-
- if(arguments[1] && typeof arguments[1].endeffect == 'undefined')
+
+ if(!arguments[1] || typeof arguments[1].endeffect == 'undefined')
Object.extend(defaults, {
starteffect: function(element) {
element._opacity = Element.getOpacity(element);
Draggable._dragging[element] = true;
- new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
+ new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
}
});
-
+
var options = Object.extend(defaults, arguments[1] || {});
this.element = $(element);
-
- if(options.handle && (typeof options.handle == 'string')) {
- var h = Element.childrenWithClassName(this.element, options.handle, true);
- if(h.length>0) this.handle = h[0];
- }
+
+ if(options.handle && (typeof options.handle == 'string'))
+ this.handle = this.element.down('.'+options.handle, 0);
+
if(!this.handle) this.handle = $(options.handle);
if(!this.handle) this.handle = this.element;
-
+
if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
options.scroll = $(options.scroll);
this._isScrollChild = Element.childOf(this.element, options.scroll);
}
- Element.makePositioned(this.element); // fix IE
+ Element.makePositioned(this.element); // fix IE
this.delta = this.currentDelta();
this.options = options;
- this.dragging = false;
+ this.dragging = false;
this.eventMouseDown = this.initDrag.bindAsEventListener(this);
Event.observe(this.handle, "mousedown", this.eventMouseDown);
-
+
Draggables.register(this);
},
-
+
destroy: function() {
Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
Draggables.unregister(this);
},
-
+
currentDelta: function() {
return([
parseInt(Element.getStyle(this.element,'left') || '0'),
parseInt(Element.getStyle(this.element,'top') || '0')]);
},
-
+
initDrag: function(event) {
if(typeof Draggable._dragging[this.element] != 'undefined' &&
Draggable._dragging[this.element]) return;
- if(Event.isLeftClick(event)) {
+ if(Event.isLeftClick(event)) {
// abort on form elements, fixes a Firefox issue
var src = Event.element(event);
- if(src.tagName && (
- src.tagName=='INPUT' ||
- src.tagName=='SELECT' ||
- src.tagName=='OPTION' ||
- src.tagName=='BUTTON' ||
- src.tagName=='TEXTAREA')) return;
-
+ if((tag_name = src.tagName.toUpperCase()) && (
+ tag_name=='INPUT' ||
+ tag_name=='SELECT' ||
+ tag_name=='OPTION' ||
+ tag_name=='BUTTON' ||
+ tag_name=='TEXTAREA')) return;
+
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var pos = Position.cumulativeOffset(this.element);
this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
-
+
Draggables.activate(this);
Event.stop(event);
}
},
-
+
startDrag: function(event) {
this.dragging = true;
-
+
if(this.options.zindex) {
this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
this.element.style.zIndex = this.options.zindex;
}
-
+
if(this.options.ghosting) {
this._clone = this.element.cloneNode(true);
Position.absolutize(this.element);
this.element.parentNode.insertBefore(this._clone, this.element);
}
-
+
if(this.options.scroll) {
if (this.options.scroll == window) {
var where = this._getWindowScroll(this.options.scroll);
@@ -347,35 +345,31 @@
this.originalScrollTop = this.options.scroll.scrollTop;
}
}
-
+
Draggables.notify('onStart', this, event);
-
+
if(this.options.starteffect) this.options.starteffect(this.element);
},
-
+
updateDrag: function(event, pointer) {
if(!this.dragging) this.startDrag(event);
Position.prepare();
Droppables.show(pointer, this.element);
Draggables.notify('onDrag', this, event);
-
+
this.draw(pointer);
if(this.options.change) this.options.change(this);
-
+
if(this.options.scroll) {
this.stopScrolling();
-
+
var p;
if (this.options.scroll == window) {
with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
} else {
p = Position.page(this.options.scroll);
- p[0] += this.options.scroll.scrollLeft;
- p[1] += this.options.scroll.scrollTop;
-
- p[0] += (window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0);
- p[1] += (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0);
-
+ p[0] += this.options.scroll.scrollLeft + Position.deltaX;
+ p[1] += this.options.scroll.scrollTop + Position.deltaY;
p.push(p[0]+this.options.scroll.offsetWidth);
p.push(p[1]+this.options.scroll.offsetHeight);
}
@@ -386,13 +380,13 @@
if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
this.startScrolling(speed);
}
-
+
// fix AppleWebKit rendering
if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
-
+
Event.stop(event);
},
-
+
finishDrag: function(event, success) {
this.dragging = false;
@@ -407,10 +401,10 @@
var revert = this.options.revert;
if(revert && typeof revert == 'function') revert = revert(this.element);
-
+
var d = this.currentDelta();
if(revert && this.options.reverteffect) {
- this.options.reverteffect(this.element,
+ this.options.reverteffect(this.element,
d[1]-this.delta[1], d[0]-this.delta[0]);
} else {
this.delta = d;
@@ -419,46 +413,45 @@
if(this.options.zindex)
this.element.style.zIndex = this.originalZ;
- if(this.options.endeffect)
+ if(this.options.endeffect)
this.options.endeffect(this.element);
-
+
Draggables.deactivate(this);
Droppables.reset();
},
-
+
keyPress: function(event) {
if(event.keyCode!=Event.KEY_ESC) return;
this.finishDrag(event, false);
Event.stop(event);
},
-
+
endDrag: function(event) {
if(!this.dragging) return;
this.stopScrolling();
this.finishDrag(event, true);
Event.stop(event);
},
-
+
draw: function(point) {
var pos = Position.cumulativeOffset(this.element);
if(this.options.ghosting) {
var r = Position.realOffset(this.element);
- window.status = r.inspect();
pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
}
-
+
var d = this.currentDelta();
pos[0] -= d[0]; pos[1] -= d[1];
-
+
if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
}
-
- var p = [0,1].map(function(i){
- return (point[i]-pos[i]-this.offset[i])
+
+ var p = [0,1].map(function(i){
+ return (point[i]-pos[i]-this.offset[i])
}.bind(this));
-
+
if(this.options.snap) {
if(typeof this.options.snap == 'function') {
p = this.options.snap(p[0],p[1],this);
@@ -471,16 +464,16 @@
return Math.round(v/this.options.snap)*this.options.snap }.bind(this))
}
}}
-
+
var style = this.element.style;
if((!this.options.constraint) || (this.options.constraint=='horizontal'))
style.left = p[0] + "px";
if((!this.options.constraint) || (this.options.constraint=='vertical'))
style.top = p[1] + "px";
-
+
if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
},
-
+
stopScrolling: function() {
if(this.scrollInterval) {
clearInterval(this.scrollInterval);
@@ -488,14 +481,14 @@
Draggables._lastScrollPointer = null;
}
},
-
+
startScrolling: function(speed) {
if(!(speed[0] || speed[1])) return;
this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
this.lastScrolled = new Date();
this.scrollInterval = setInterval(this.scroll.bind(this), 10);
},
-
+
scroll: function() {
var current = new Date();
var delta = current - this.lastScrolled;
@@ -511,7 +504,7 @@
this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
}
-
+
Position.prepare();
Droppables.show(Draggables._lastPointer, this.element);
Draggables.notify('onDrag', this);
@@ -525,10 +518,10 @@
Draggables._lastScrollPointer[1] = 0;
this.draw(Draggables._lastScrollPointer);
}
-
+
if(this.options.change) this.options.change(this);
},
-
+
_getWindowScroll: function(w) {
var T, L, W, H;
with (w.document) {
@@ -563,11 +556,11 @@
this.observer = observer;
this.lastValue = Sortable.serialize(this.element);
},
-
+
onStart: function() {
this.lastValue = Sortable.serialize(this.element);
},
-
+
onEnd: function() {
Sortable.unmark();
if(this.lastValue != Sortable.serialize(this.element))
@@ -577,11 +570,11 @@
var Sortable = {
SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
-
+
sortables: {},
-
+
_findRootElement: function(element) {
- while (element.tagName != "BODY") {
+ while (element.tagName.toUpperCase() != "BODY") {
if(element.id && Sortable.sortables[element.id]) return element;
element = element.parentNode;
}
@@ -592,22 +585,22 @@
if(!element) return;
return Sortable.sortables[element.id];
},
-
+
destroy: function(element){
var s = Sortable.options(element);
-
+
if(s) {
Draggables.removeObserver(s.element);
s.droppables.each(function(d){ Droppables.remove(d) });
s.draggables.invoke('destroy');
-
+
delete Sortable.sortables[s.element.id];
}
},
create: function(element) {
element = $(element);
- var options = Object.extend({
+ var options = Object.extend({
element: element,
tag: 'li', // assumes li children, override with tag: 'tagname'
dropOnEmpty: false,
@@ -660,16 +653,15 @@
if(options.zindex)
options_for_draggable.zindex = options.zindex;
- // build options for the droppables
+ // build options for the droppables
var options_for_droppable = {
overlap: options.overlap,
containment: options.containment,
tree: options.tree,
hoverclass: options.hoverclass,
onHover: Sortable.onHover
- //greedy: !options.dropOnEmpty
}
-
+
var options_for_tree = {
onHover: Sortable.onEmptyHover,
overlap: options.overlap,
@@ -678,7 +670,7 @@
}
// fix for gecko engine
- Element.cleanWhitespace(element);
+ Element.cleanWhitespace(element);
options.draggables = [];
options.droppables = [];
@@ -691,15 +683,15 @@
(this.findElements(element, options) || []).each( function(e) {
// handles are per-draggable
- var handle = options.handle ?
- Element.childrenWithClassName(e, options.handle)[0] : e;
+ var handle = options.handle ?
+ $(e).down('.'+options.handle,0) : e;
options.draggables.push(
new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
Droppables.add(e, options_for_droppable);
if(options.tree) e.treeNode = element;
- options.droppables.push(e);
+ options.droppables.push(e);
});
-
+
if(options.tree) {
(Sortable.findTreeElements(element, options) || []).each( function(e) {
Droppables.add(e, options_for_tree);
@@ -721,7 +713,7 @@
return Element.findChildren(
element, options.only, options.tree ? true : false, options.tag);
},
-
+
findTreeElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.treeTag);
@@ -737,51 +729,38 @@
if(dropon.previousSibling != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
-
- Sortable.createGuide(element);
dropon.parentNode.insertBefore(element, dropon);
- dropon.parentNode.insertBefore(Sortable._guide, element);
- Sortable.markEmptyPlace(element);
-
- if(dropon.parentNode!=oldParentNode)
+ if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
} else {
Sortable.mark(dropon, 'after');
var nextElement = dropon.nextSibling || null;
-
if(nextElement != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
-
- Sortable.createGuide(element);
dropon.parentNode.insertBefore(element, nextElement);
- dropon.parentNode.insertBefore(Sortable._guide, element);
- Sortable.markEmptyPlace(element);
-
- if(dropon.parentNode!=oldParentNode)
+ if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
}
},
-
-
-
+
onEmptyHover: function(element, dropon, overlap) {
var oldParentNode = element.parentNode;
var droponOptions = Sortable.options(dropon);
-
+
if(!Element.isParent(dropon, element)) {
var index;
-
+
var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
var child = null;
-
+
if(children) {
var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
-
+
for (index = 0; index < children.length; index += 1) {
if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
offset -= Element.offsetSize (children[index], droponOptions.overlap);
@@ -794,133 +773,68 @@
}
}
}
-
- Sortable.createGuide(element);
+
dropon.insertBefore(element, child);
- dropon.insertBefore(Sortable._guide, element);
- Sortable.markEmptyPlace(element);
-
+
Sortable.options(oldParentNode).onChange(element);
droponOptions.onChange(element);
}
},
- createGuide : function (element) {
- if(!Sortable._guide) {
- Sortable._guide = $('_guide') || document.createElement('DIV');
- Sortable._guide.style.position = 'relative';
- Sortable._guide.style.width = '1px';
- Sortable._guide.style.height = '0px';
- Sortable._guide.style.left == '0px';
- Sortable._guide.style.top == '0px';
- Sortable._guide.style.cssFloat = 'left';
- Sortable._guide.id = 'guide';
-
- document.getElementsByTagName("body").item(0).appendChild(Sortable._guide);
- }
-
- },
-
- markEmptyPlace: function(element) {
-
- if(!Sortable._emptyPlaceMarker) {
- Sortable._emptyPlaceMarker = $('emptyPlaceMarker') || document.createElement('DIV');
- Element.hide(Sortable._emptyPlaceMarker);
- Element.addClassName(Sortable._emptyPlaceMarker, 'emptyPlaceMarker');
- Sortable._emptyPlaceMarker.style.position = 'absolute';
- document.getElementsByTagName("body").item(0).appendChild(Sortable._emptyPlaceMarker);
- }
-
- var pos = Position.cumulativeOffset(Sortable._guide);
- Sortable._emptyPlaceMarker.style.left = (pos[0] + 5)+ 'px';
- Sortable._emptyPlaceMarker.style.top = (pos[1] + 5) + 'px';
-
- var dim = {};
- dim.width = (Element.getDimensions(element).width-5) + 'px';
- dim.height = (Element.getDimensions(element).height-5) + 'px';
- Sortable._emptyPlaceMarker.setStyle(dim);
-
- var mg = Element.getStyle(element, 'margin');
- if(mg && mg != '') {
- Sortable._emptyPlaceMarker.setStyle({margin : mg});
- } else {
- Sortable._emptyPlaceMarker.setStyle({ margin : ''});
- }
-
- Element.show(Sortable._emptyPlaceMarker);
- },
-
unmark: function() {
- if(Sortable._marker) Element.hide(Sortable._marker);
- if(Sortable._guide && Sortable._guide.parentNode){
- Sortable._guide.parentNode.removeChild(Sortable._guide);
- }
- if(Sortable._emptyPlaceMarker) Element.hide(Sortable._emptyPlaceMarker);
+ if(Sortable._marker) Sortable._marker.hide();
},
mark: function(dropon, position) {
// mark on ghosting only
var sortable = Sortable.options(dropon.parentNode);
- if(sortable && !sortable.ghosting) return;
+ if(sortable && !sortable.ghosting) return;
if(!Sortable._marker) {
- Sortable._marker = $('dropmarker') || document.createElement('DIV');
- Element.hide(Sortable._marker);
- Element.addClassName(Sortable._marker, 'dropmarker');
- Sortable._marker.style.position = 'absolute';
+ Sortable._marker =
+ ($('dropmarker') || Element.extend(document.createElement('DIV'))).
+ hide().addClassName('dropmarker').setStyle({position:'absolute'});
document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
- }
+ }
var offsets = Position.cumulativeOffset(dropon);
- Sortable._marker.style.left = offsets[0] + 'px';
- Sortable._marker.style.top = offsets[1] + 'px';
-
+ Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
+
if(position=='after')
- if(sortable.overlap == 'horizontal')
- Sortable._marker.style.left = (offsets[0]+dropon.clientWidth) + 'px';
+ if(sortable.overlap == 'horizontal')
+ Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
else
- Sortable._marker.style.top = (offsets[1]+dropon.clientHeight) + 'px';
-
- Element.show(Sortable._marker);
+ Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
+
+ Sortable._marker.show();
},
-
+
_tree: function(element, options, parent) {
var children = Sortable.findElements(element, options) || [];
-
+
for (var i = 0; i < children.length; ++i) {
var match = children[i].id.match(options.format);
if (!match) continue;
-
+
var child = {
id: encodeURIComponent(match ? match[1] : null),
element: element,
parent: parent,
- children: new Array,
+ children: [],
position: parent.children.length,
- container: Sortable._findChildrenElement(children[i], options.treeTag.toUpperCase())
+ container: $(children[i]).down(options.treeTag)
}
-
+
/* Get the element containing the children and recurse over it */
if (child.container)
this._tree(child.container, options, child)
-
+
parent.children.push (child);
}
- return parent;
+ return parent;
},
- /* Finds the first element of the given tag type within a parent element.
- Used for finding the first LI[ST] within a L[IST]I[TEM].*/
- _findChildrenElement: function (element, containerTag) {
- if (element && element.hasChildNodes)
- for (var i = 0; i < element.childNodes.length; ++i)
- if (element.childNodes[i].tagName == containerTag)
- return element.childNodes[i];
-
- return null;
- },
-
tree: function(element) {
element = $(element);
var sortableOptions = this.options(element);
@@ -931,16 +845,16 @@
name: element.id,
format: sortableOptions.format
}, arguments[1] || {});
-
+
var root = {
id: null,
parent: null,
- children: new Array,
+ children: [],
container: element,
position: 0
}
-
- return Sortable._tree (element, options, root);
+
+ return Sortable._tree(element, options, root);
},
/* Construct a [i] index for a particular node */
@@ -955,7 +869,7 @@
sequence: function(element) {
element = $(element);
var options = Object.extend(this.options(element), arguments[1] || {});
-
+
return $(this.findElements(element, options) || []).map( function(item) {
return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
});
@@ -964,14 +878,14 @@
setSequence: function(element, new_sequence) {
element = $(element);
var options = Object.extend(this.options(element), arguments[2] || {});
-
+
var nodeMap = {};
this.findElements(element, options).each( function(n) {
if (n.id.match(options.format))
nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
n.parentNode.removeChild(n);
});
-
+
new_sequence.each(function(ident) {
var n = nodeMap[ident];
if (n) {
@@ -980,16 +894,16 @@
}
});
},
-
+
serialize: function(element) {
element = $(element);
var options = Object.extend(Sortable.options(element), arguments[1] || {});
var name = encodeURIComponent(
(arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
-
+
if (options.tree) {
return Sortable.tree(element, arguments[1]).children.map( function (item) {
- return [name + Sortable._constructIndex(item) + "[id]=" +
+ return [name + Sortable._constructIndex(item) + "[id]=" +
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
}).flatten().join('&');
} else {
@@ -1000,16 +914,14 @@
}
}
-/* Returns true if child is contained within element */
+// Returns true if child is contained within element
Element.isParent = function(child, element) {
if (!child.parentNode || child == element) return false;
-
if (child.parentNode == element) return true;
-
return Element.isParent(child.parentNode, element);
}
-Element.findChildren = function(element, only, recursive, tagName) {
+Element.findChildren = function(element, only, recursive, tagName) {
if(!element.hasChildNodes()) return null;
tagName = tagName.toUpperCase();
if(only) only = [only].flatten();
@@ -1028,8 +940,5 @@
}
Element.offsetSize = function (element, type) {
- if (type == 'vertical' || type == 'height')
- return element.offsetHeight;
- else
- return element.offsetWidth;
-}
\ No newline at end of file
+ return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
+}
Added: trunk/theme/src/bin/portal-ajax-war/js/portal/dyna.js
===================================================================
--- trunk/theme/src/bin/portal-ajax-war/js/portal/dyna.js (rev 0)
+++ trunk/theme/src/bin/portal-ajax-war/js/portal/dyna.js 2007-03-31 14:25:31 UTC (rev 6896)
@@ -0,0 +1,134 @@
+function sendData(action, windowId, fromPos, fromRegionId, toPos, toRegionId) {
+ var options = {
+ method: "post",
+ postBody: "action=" + action + "&windowId=" + windowId + "&fromPos=" + fromPos + "&fromRegion=" + fromRegionId + "&toPos=" + toPos + "&toRegion=" + toRegionId,
+ onSuccess: function(t)
+ {
+ },
+ on404: function(t)
+ {
+ alert("Error 404: location " + t.statusText + " was not found.");
+ },
+ onFailure: function(t)
+ {
+ alert("Error " + t.status + " -- " + t.statusText);
+ },
+ onLoading: function(t)
+ {
+ }
+ }
+ new Ajax.Request(async_server_url, options);
+}
+
+function snapshot() {
+
+ // Find draggable regions
+ var regions_on_page = document.getElementsByClassName("dyna-region");
+
+ // Save current state in the DOM itself
+ for(var i = 0;i < regions_on_page.length;i++) {
+ var regionDiv = regions_on_page[i]
+ for (var j = 0;j < regionDiv.childNodes.length;j++) {
+ var child = regionDiv.childNodes[j];
+ child["regionId"] = regionDiv.id;
+ child["pos"] = j;
+ }
+ }
+}
+
+function bilto(event)
+{
+
+ // Find container
+ var source = Event.element(event);
+ var container = Element.up(source, "div.dyna-portlet");
+
+ // We found the div container
+ if (container != null) {
+
+ // Handle links
+ if (source.nodeName == "A") {
+
+// " var url = source.href;
+// " var parameters = \"\";
+// " var pos = url.indexOf(\"?\");
+// " if (pos != -1) {
+// " parameters = url.substring(pos + 1);
+// " url = url.substring(0, pos);
+// " }
+// " var options = {
+// " parameters:parameters,
+// " asynchronous:true,
+// " method:\"get\",
+// " requestHeaders:[\"ajax\",\"true\"],
+// " };" +
+// " new Ajax.Request(url, options);
+ }
+
+// " Element.replace(container, \"Some new content from the server\");
+// " Event.stop(event);
+ }
+
+}
+
+
+function footer()
+{
+ //
+ var WindowMoveObserver = Class.create();
+ WindowMoveObserver.prototype =
+ {
+ initialize: function(element)
+ {
+ this.element = $(element);
+ },
+ onStart: function()
+ {
+ },
+ onEnd: function()
+ {
+ var elt = Draggables.activeDraggable.element;
+ var fromRegionId = elt["regionId"];
+ var fromPos = elt["pos"];
+ snapshot();
+ var toRegionId = elt["regionId"];
+ var toPos = elt["pos"];
+ sendData("windowmove", elt.id, fromPos, fromRegionId, toPos, toRegionId);
+ }
+ };
+
+ // Find the draggable regions
+ var regions_on_page = document.getElementsByClassName("dyna-region");
+
+ // Create draggable regions
+ for(var i = 0;i < regions_on_page.length;i++) {
+ var region = regions_on_page[i];
+ Sortable.create(region, {dropOnEmpty:true,handle:"handle",tag:"div",containment:regions_on_page,constraint:false});
+ }
+
+ //
+ Draggables.addObserver(new WindowMoveObserver());
+ snapshot();
+
+ // Find the dyna portlets
+ var portlets_on_page = document.getElementsByClassName("dyna-portlet");
+
+ // Add listener for teh dyna portlets
+ for(var i = 0;i < portlets_on_page.length;i++) {
+ var portlet = portlets_on_page[i];
+ Event.observe(portlet, "click", bilto);
+ }
+}
+
+
+// String u = "" +
+// "function removeWindow(elementId)\n" +
+// "{\n" +
+// " var effectElement = document.getElementById(elementId)\n" +
+// " new Effect.BlindUp(effectElement);\n" +
+// "\n" +
+// " //removeElement(effectElement);\n" +
+// "\n" +
+// " sendData('windowremove', elementId);\n" +
+// "}\n";
+// markup.append(u);
Modified: trunk/theme/src/bin/portal-ajax-war/js/portal/effects.js
===================================================================
--- trunk/theme/src/bin/portal-ajax-war/js/portal/effects.js 2007-03-31 14:21:37 UTC (rev 6895)
+++ trunk/theme/src/bin/portal-ajax-war/js/portal/effects.js 2007-03-31 14:25:31 UTC (rev 6896)
@@ -1,17 +1,18 @@
-// script.aculo.us effects.js v1.6.4, Wed Sep 06 11:30:58 CEST 2006
+// script.aculo.us effects.js v1.7.0, Fri Jan 19 19:16:36 CET 2007
-// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
// Justin Palmer (http://encytemedia.com/)
// Mark Pilgrim (http://diveintomark.org/)
// Martin Bialasinki
//
-// See scriptaculous.js for full license.
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
// converts rgb() and #xxx to #xxxxxx format,
// returns self (or first argument) if not convertable
String.prototype.parseColor = function() {
- var color = '#';
+ var color = '#';
if(this.slice(0,4) == 'rgb(') {
var cols = this.slice(4,this.length-1).split(',');
var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
@@ -43,48 +44,21 @@
Element.setContentZoom = function(element, percent) {
element = $(element);
- Element.setStyle(element, {fontSize: (percent/100) + 'em'});
+ element.setStyle({fontSize: (percent/100) + 'em'});
if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
+ return element;
}
-Element.getOpacity = function(element){
- var opacity;
- if (opacity = Element.getStyle(element, 'opacity'))
- return parseFloat(opacity);
- if (opacity = (Element.getStyle(element, 'filter') || '').match(/alpha\(opacity=(.*)\)/))
- if(opacity[1]) return parseFloat(opacity[1]) / 100;
- return 1.0;
+Element.getOpacity = function(element){
+ return $(element).getStyle('opacity');
}
-Element.setOpacity = function(element, value){
- element= $(element);
- if (value == 1){
- Element.setStyle(element, { opacity:
- (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ?
- 0.999999 : 1.0 });
- if(/MSIE/.test(navigator.userAgent) && !window.opera)
- Element.setStyle(element, {filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'')});
- } else {
- if(value < 0.00001) value = 0;
- Element.setStyle(element, {opacity: value});
- if(/MSIE/.test(navigator.userAgent) && !window.opera)
- Element.setStyle(element,
- { filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'') +
- 'alpha(opacity='+value*100+')' });
- }
-}
-
-Element.getInlineOpacity = function(element){
+Element.setOpacity = function(element, value){
+ return $(element).setStyle({opacity:value});
+}
+
+Element.getInlineOpacity = function(element){
return $(element).style.opacity || '';
-}
-
-Element.childrenWithClassName = function(element, className, findFirst) {
- var classNameRegExp = new RegExp("(^|\\s)" + className + "(\\s|$)");
- var results = $A($(element).getElementsByTagName('*'))[findFirst ? 'detect' : 'select']( function(c) {
- return (c.className && c.className.match(classNameRegExp));
- });
- if(!results) results = [];
- return results;
}
Element.forceRerendering = function(element) {
@@ -116,6 +90,7 @@
var tagifyStyle = 'position:relative';
if(/MSIE/.test(navigator.userAgent) && !window.opera) tagifyStyle += ';zoom:1';
+
element = $(element);
$A(element.childNodes).each( function(child) {
if(child.nodeType==3) {
@@ -168,33 +143,36 @@
/* ------------- transitions ------------- */
-Effect.Transitions = {}
+Effect.Transitions = {
+ linear: Prototype.K,
+ sinoidal: function(pos) {
+ return (-Math.cos(pos*Math.PI)/2) + 0.5;
+ },
+ reverse: function(pos) {
+ return 1-pos;
+ },
+ flicker: function(pos) {
+ return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
+ },
+ wobble: function(pos) {
+ return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
+ },
+ pulse: function(pos, pulses) {
+ pulses = pulses || 5;
+ return (
+ Math.round((pos % (1/pulses)) * pulses) == 0 ?
+ ((pos * pulses * 2) - Math.floor(pos * pulses * 2)) :
+ 1 - ((pos * pulses * 2) - Math.floor(pos * pulses * 2))
+ );
+ },
+ none: function(pos) {
+ return 0;
+ },
+ full: function(pos) {
+ return 1;
+ }
+};
-Effect.Transitions.linear = Prototype.K;
-
-Effect.Transitions.sinoidal = function(pos) {
- return (-Math.cos(pos*Math.PI)/2) + 0.5;
-}
-Effect.Transitions.reverse = function(pos) {
- return 1-pos;
-}
-Effect.Transitions.flicker = function(pos) {
- return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
-}
-Effect.Transitions.wobble = function(pos) {
- return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
-}
-Effect.Transitions.pulse = function(pos) {
- return (Math.floor(pos*10) % 2 == 0 ?
- (pos*10-Math.floor(pos*10)) : 1-(pos*10-Math.floor(pos*10)));
-}
-Effect.Transitions.none = function(pos) {
- return 0;
-}
-Effect.Transitions.full = function(pos) {
- return 1;
-}
-
/* ------------- core effects ------------- */
Effect.ScopedQueue = Class.create();
@@ -220,6 +198,9 @@
e.finishOn += effect.finishOn;
});
break;
+ case 'with-last':
+ timestamp = this.effects.pluck('startOn').max() || timestamp;
+ break;
case 'end':
// start effect after last queued effect has finished
timestamp = this.effects.pluck('finishOn').max() || timestamp;
@@ -233,7 +214,7 @@
this.effects.push(effect);
if(!this.interval)
- this.interval = setInterval(this.loop.bind(this), 40);
+ this.interval = setInterval(this.loop.bind(this), 15);
},
remove: function(effect) {
this.effects = this.effects.reject(function(e) { return e==effect });
@@ -244,7 +225,8 @@
},
loop: function() {
var timePos = new Date().getTime();
- this.effects.invoke('loop', timePos);
+ for(var i=0, len=this.effects.length;i<len;i++)
+ if(this.effects[i]) this.effects[i].loop(timePos);
}
});
@@ -264,7 +246,7 @@
Effect.DefaultOptions = {
transition: Effect.Transitions.sinoidal,
duration: 1.0, // seconds
- fps: 25.0, // max. 25fps due to Effect.Queue implementation
+ fps: 60.0, // max. 60fps due to Effect.Queue implementation
sync: false, // true for combining
from: 0.0,
to: 1.0,
@@ -332,7 +314,10 @@
if(this.options[eventName]) this.options[eventName](this);
},
inspect: function() {
- return '#<Effect:' + $H(this).inspect() + ',options:' + $H(this.options).inspect() + '>';
+ var data = $H();
+ for(property in this)
+ if(typeof this[property] != 'function') data[property] = this[property];
+ return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
}
}
@@ -356,6 +341,17 @@
}
});
+Effect.Event = Class.create();
+Object.extend(Object.extend(Effect.Event.prototype, Effect.Base.prototype), {
+ initialize: function() {
+ var options = Object.extend({
+ duration: 0
+ }, arguments[0] || {});
+ this.start(options);
+ },
+ update: Prototype.emptyFunction
+});
+
Effect.Opacity = Class.create();
Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), {
initialize: function(element) {
@@ -469,7 +465,7 @@
this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
},
finish: function(position) {
- if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
+ if(this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
},
setDimensions: function(height, width) {
var d = {};
@@ -502,9 +498,11 @@
// Prevent executing on elements not in the layout flow
if(this.element.getStyle('display')=='none') { this.cancel(); return; }
// Disable background image during the effect
- this.oldStyle = {
- backgroundImage: this.element.getStyle('background-image') };
- this.element.setStyle({backgroundImage: 'none'});
+ this.oldStyle = {};
+ if (!this.options.keepBackgroundImage) {
+ this.oldStyle.backgroundImage = this.element.getStyle('background-image');
+ this.element.setStyle({backgroundImage: 'none'});
+ }
if(!this.options.endcolor)
this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
if(!this.options.restorecolor)
@@ -559,8 +557,7 @@
to: 0.0,
afterFinishInternal: function(effect) {
if(effect.options.to!=0) return;
- effect.element.hide();
- effect.element.setStyle({opacity: oldOpacity});
+ effect.element.hide().setStyle({opacity: oldOpacity});
}}, arguments[1] || {});
return new Effect.Opacity(element,options);
}
@@ -575,8 +572,7 @@
effect.element.forceRerendering();
},
beforeSetup: function(effect) {
- effect.element.setOpacity(effect.options.from);
- effect.element.show();
+ effect.element.setOpacity(effect.options.from).show();
}}, arguments[1] || {});
return new Effect.Opacity(element,options);
}
@@ -600,8 +596,7 @@
Position.absolutize(effect.effects[0].element)
},
afterFinishInternal: function(effect) {
- effect.effects[0].element.hide();
- effect.effects[0].element.setStyle(oldStyle); }
+ effect.effects[0].element.hide().setStyle(oldStyle); }
}, arguments[1] || {})
);
}
@@ -614,8 +609,7 @@
scaleX: false,
restoreAfterFinish: true,
afterFinishInternal: function(effect) {
- effect.element.hide();
- effect.element.undoClipping();
+ effect.element.hide().undoClipping();
}
}, arguments[1] || {})
);
@@ -631,9 +625,7 @@
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
restoreAfterFinish: true,
afterSetup: function(effect) {
- effect.element.makeClipping();
- effect.element.setStyle({height: '0px'});
- effect.element.show();
+ effect.element.makeClipping().setStyle({height: '0px'}).show();
},
afterFinishInternal: function(effect) {
effect.element.undoClipping();
@@ -653,14 +645,10 @@
duration: 0.3, scaleFromCenter: true,
scaleX: false, scaleContent: false, restoreAfterFinish: true,
beforeSetup: function(effect) {
- effect.element.makePositioned();
- effect.element.makeClipping();
+ effect.element.makePositioned().makeClipping();
},
afterFinishInternal: function(effect) {
- effect.element.hide();
- effect.element.undoClipping();
- effect.element.undoPositioned();
- effect.element.setStyle({opacity: oldOpacity});
+ effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
}
})
}
@@ -682,9 +670,7 @@
effect.effects[0].element.makePositioned();
},
afterFinishInternal: function(effect) {
- effect.effects[0].element.hide();
- effect.effects[0].element.undoPositioned();
- effect.effects[0].element.setStyle(oldStyle);
+ effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
}
}, arguments[1] || {}));
}
@@ -706,16 +692,14 @@
{ x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) {
new Effect.Move(effect.element,
{ x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
- effect.element.undoPositioned();
- effect.element.setStyle(oldStyle);
+ effect.element.undoPositioned().setStyle(oldStyle);
}}) }}) }}) }}) }}) }});
}
Effect.SlideDown = function(element) {
- element = $(element);
- element.cleanWhitespace();
+ element = $(element).cleanWhitespace();
// SlideDown need to have the content of the element wrapped in a container element with fixed height!
- var oldInnerBottom = $(element.firstChild).getStyle('bottom');
+ var oldInnerBottom = element.down().getStyle('bottom');
var elementDimensions = element.getDimensions();
return new Effect.Scale(element, 100, Object.extend({
scaleContent: false,
@@ -725,34 +709,24 @@
restoreAfterFinish: true,
afterSetup: function(effect) {
effect.element.makePositioned();
- effect.element.firstChild.makePositioned();
+ effect.element.down().makePositioned();
if(window.opera) effect.element.setStyle({top: ''});
- effect.element.makeClipping();
- effect.element.setStyle({height: '0px'});
- effect.element.show(); },
+ effect.element.makeClipping().setStyle({height: '0px'}).show();
+ },
afterUpdateInternal: function(effect) {
- effect.element.firstChild.setStyle({bottom:
+ effect.element.down().setStyle({bottom:
(effect.dims[0] - effect.element.clientHeight) + 'px' });
},
afterFinishInternal: function(effect) {
- effect.element.undoClipping();
- // IE will crash if child is undoPositioned first
- if(/MSIE/.test(navigator.userAgent) && !window.opera){
- effect.element.undoPositioned();
- effect.element.firstChild.undoPositioned();
- }else{
- effect.element.firstChild.undoPositioned();
- effect.element.undoPositioned();
- }
- effect.element.firstChild.setStyle({bottom: oldInnerBottom}); }
+ effect.element.undoClipping().undoPositioned();
+ effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
}, arguments[1] || {})
);
}
Effect.SlideUp = function(element) {
- element = $(element);
- element.cleanWhitespace();
- var oldInnerBottom = $(element.firstChild).getStyle('bottom');
+ element = $(element).cleanWhitespace();
+ var oldInnerBottom = element.down().getStyle('bottom');
return new Effect.Scale(element, window.opera ? 0 : 1,
Object.extend({ scaleContent: false,
scaleX: false,
@@ -761,32 +735,32 @@
restoreAfterFinish: true,
beforeStartInternal: function(effect) {
effect.element.makePositioned();
- effect.element.firstChild.makePositioned();
+ effect.element.down().makePositioned();
if(window.opera) effect.element.setStyle({top: ''});
- effect.element.makeClipping();
- effect.element.show(); },
+ effect.element.makeClipping().show();
+ },
afterUpdateInternal: function(effect) {
- effect.element.firstChild.setStyle({bottom:
- (effect.dims[0] - effect.element.clientHeight) + 'px' }); },
+ effect.element.down().setStyle({bottom:
+ (effect.dims[0] - effect.element.clientHeight) + 'px' });
+ },
afterFinishInternal: function(effect) {
- effect.element.hide();
- effect.element.undoClipping();
- effect.element.firstChild.undoPositioned();
- effect.element.undoPositioned();
- effect.element.setStyle({bottom: oldInnerBottom}); }
+ effect.element.hide().undoClipping().undoPositioned().setStyle({bottom: oldInnerBottom});
+ effect.element.down().undoPositioned();
+ }
}, arguments[1] || {})
);
}
// Bug in opera makes the TD containing this element expand for a instance after finish
Effect.Squish = function(element) {
- return new Effect.Scale(element, window.opera ? 1 : 0,
- { restoreAfterFinish: true,
- beforeSetup: function(effect) {
- effect.element.makeClipping(effect.element); },
- afterFinishInternal: function(effect) {
- effect.element.hide(effect.element);
- effect.element.undoClipping(effect.element); }
+ return new Effect.Scale(element, window.opera ? 1 : 0, {
+ restoreAfterFinish: true,
+ beforeSetup: function(effect) {
+ effect.element.makeClipping();
+ },
+ afterFinishInternal: function(effect) {
+ effect.element.hide().undoClipping();
+ }
});
}
@@ -842,9 +816,7 @@
y: initialMoveY,
duration: 0.01,
beforeSetup: function(effect) {
- effect.element.hide();
- effect.element.makeClipping();
- effect.element.makePositioned();
+ effect.element.hide().makeClipping().makePositioned();
},
afterFinishInternal: function(effect) {
new Effect.Parallel(
@@ -855,13 +827,10 @@
sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
], Object.extend({
beforeSetup: function(effect) {
- effect.effects[0].element.setStyle({height: '0px'});
- effect.effects[0].element.show();
+ effect.effects[0].element.setStyle({height: '0px'}).show();
},
afterFinishInternal: function(effect) {
- effect.effects[0].element.undoClipping();
- effect.effects[0].element.undoPositioned();
- effect.effects[0].element.setStyle(oldStyle);
+ effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
}
}, options)
)
@@ -915,13 +884,10 @@
new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
], Object.extend({
beforeStartInternal: function(effect) {
- effect.effects[0].element.makePositioned();
- effect.effects[0].element.makeClipping(); },
+ effect.effects[0].element.makePositioned().makeClipping();
+ },
afterFinishInternal: function(effect) {
- effect.effects[0].element.hide();
- effect.effects[0].element.undoClipping();
- effect.effects[0].element.undoPositioned();
- effect.effects[0].element.setStyle(oldStyle); }
+ effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
}, options)
);
}
@@ -931,10 +897,10 @@
var options = arguments[1] || {};
var oldOpacity = element.getInlineOpacity();
var transition = options.transition || Effect.Transitions.sinoidal;
- var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos)) };
+ var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
reverser.bind(transition);
return new Effect.Opacity(element,
- Object.extend(Object.extend({ duration: 3.0, from: 0,
+ Object.extend(Object.extend({ duration: 2.0, from: 0,
afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
}, options), {transition: reverser}));
}
@@ -946,7 +912,7 @@
left: element.style.left,
width: element.style.width,
height: element.style.height };
- Element.makeClipping(element);
+ element.makeClipping();
return new Effect.Scale(element, 5, Object.extend({
scaleContent: false,
scaleX: false,
@@ -955,15 +921,162 @@
scaleContent: false,
scaleY: false,
afterFinishInternal: function(effect) {
- effect.element.hide();
- effect.element.undoClipping();
- effect.element.setStyle(oldStyle);
+ effect.element.hide().undoClipping().setStyle(oldStyle);
} });
}}, arguments[1] || {}));
};
+Effect.Morph = Class.create();
+Object.extend(Object.extend(Effect.Morph.prototype, Effect.Base.prototype), {
+ initialize: function(element) {
+ this.element = $(element);
+ if(!this.element) throw(Effect._elementDoesNotExistError);
+ var options = Object.extend({
+ style: {}
+ }, arguments[1] || {});
+ if (typeof options.style == 'string') {
+ if(options.style.indexOf(':') == -1) {
+ var cssText = '', selector = '.' + options.style;
+ $A(document.styleSheets).reverse().each(function(styleSheet) {
+ if (styleSheet.cssRules) cssRules = styleSheet.cssRules;
+ else if (styleSheet.rules) cssRules = styleSheet.rules;
+ $A(cssRules).reverse().each(function(rule) {
+ if (selector == rule.selectorText) {
+ cssText = rule.style.cssText;
+ throw $break;
+ }
+ });
+ if (cssText) throw $break;
+ });
+ this.style = cssText.parseStyle();
+ options.afterFinishInternal = function(effect){
+ effect.element.addClassName(effect.options.style);
+ effect.transforms.each(function(transform) {
+ if(transform.style != 'opacity')
+ effect.element.style[transform.style.camelize()] = '';
+ });
+ }
+ } else this.style = options.style.parseStyle();
+ } else this.style = $H(options.style)
+ this.start(options);
+ },
+ setup: function(){
+ function parseColor(color){
+ if(!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
+ color = color.parseColor();
+ return $R(0,2).map(function(i){
+ return parseInt( color.slice(i*2+1,i*2+3), 16 )
+ });
+ }
+ this.transforms = this.style.map(function(pair){
+ var property = pair[0].underscore().dasherize(), value = pair[1], unit = null;
+
+ if(value.parseColor('#zzzzzz') != '#zzzzzz') {
+ value = value.parseColor();
+ unit = 'color';
+ } else if(property == 'opacity') {
+ value = parseFloat(value);
+ if(/MSIE/.test(navigator.userAgent) && !window.opera && (!this.element.currentStyle.hasLayout))
+ this.element.setStyle({zoom: 1});
+ } else if(Element.CSS_LENGTH.test(value))
+ var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/),
+ value = parseFloat(components[1]), unit = (components.length == 3) ? components[2] : null;
+
+ var originalValue = this.element.getStyle(property);
+ return $H({
+ style: property,
+ originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
+ targetValue: unit=='color' ? parseColor(value) : value,
+ unit: unit
+ });
+ }.bind(this)).reject(function(transform){
+ return (
+ (transform.originalValue == transform.targetValue) ||
+ (
+ transform.unit != 'color' &&
+ (isNaN(transform.originalValue) || isNaN(transform.targetValue))
+ )
+ )
+ });
+ },
+ update: function(position) {
+ var style = $H(), value = null;
+ this.transforms.each(function(transform){
+ value = transform.unit=='color' ?
+ $R(0,2).inject('#',function(m,v,i){
+ return m+(Math.round(transform.originalValue[i]+
+ (transform.targetValue[i] - transform.originalValue[i])*position)).toColorPart() }) :
+ transform.originalValue + Math.round(
+ ((transform.targetValue - transform.originalValue) * position) * 1000)/1000 + transform.unit;
+ style[transform.style] = value;
+ });
+ this.element.setStyle(style);
+ }
+});
+
+Effect.Transform = Class.create();
+Object.extend(Effect.Transform.prototype, {
+ initialize: function(tracks){
+ this.tracks = [];
+ this.options = arguments[1] || {};
+ this.addTracks(tracks);
+ },
+ addTracks: function(tracks){
+ tracks.each(function(track){
+ var data = $H(track).values().first();
+ this.tracks.push($H({
+ ids: $H(track).keys().first(),
+ effect: Effect.Morph,
+ options: { style: data }
+ }));
+ }.bind(this));
+ return this;
+ },
+ play: function(){
+ return new Effect.Parallel(
+ this.tracks.map(function(track){
+ var elements = [$(track.ids) || $$(track.ids)].flatten();
+ return elements.map(function(e){ return new track.effect(e, Object.extend({ sync:true }, track.options)) });
+ }).flatten(),
+ this.options
+ );
+ }
+});
+
+Element.CSS_PROPERTIES = $w(
+ 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
+ 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
+ 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
+ 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
+ 'fontSize fontWeight height left letterSpacing lineHeight ' +
+ 'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
+ 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
+ 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
+ 'right textIndent top width wordSpacing zIndex');
+
+Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
+
+String.prototype.parseStyle = function(){
+ var element = Element.extend(document.createElement('div'));
+ element.innerHTML = '<div style="' + this + '"></div>';
+ var style = element.down().style, styleRules = $H();
+
+ Element.CSS_PROPERTIES.each(function(property){
+ if(style[property]) styleRules[property] = style[property];
+ });
+ if(/MSIE/.test(navigator.userAgent) && !window.opera && this.indexOf('opacity') > -1) {
+ styleRules.opacity = this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1];
+ }
+ return styleRules;
+};
+
+Element.morph = function(element, style) {
+ new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || {}));
+ return element;
+};
+
['setOpacity','getOpacity','getInlineOpacity','forceRerendering','setContentZoom',
- 'collectTextNodes','collectTextNodesIgnoreClass','childrenWithClassName'].each(
+ 'collectTextNodes','collectTextNodesIgnoreClass','morph'].each(
function(f) { Element.Methods[f] = Element[f]; }
);
Deleted: trunk/theme/src/bin/portal-ajax-war/js/portal/event.js
===================================================================
--- trunk/theme/src/bin/portal-ajax-war/js/portal/event.js 2007-03-31 14:21:37 UTC (rev 6895)
+++ trunk/theme/src/bin/portal-ajax-war/js/portal/event.js 2007-03-31 14:25:31 UTC (rev 6896)
@@ -1,247 +0,0 @@
-/*
-* JBoss, a division of Red Hat
-* Copyright 2006, Red Hat Middleware, LLC, and individual contributors as indicated
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* This is free software; you can redistribute it and/or modify it
-* under the terms of the GNU Lesser General Public License as
-* published by the Free Software Foundation; either version 2.1 of
-* the License, or (at your option) any later version.
-*
-* This software is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-* Lesser General Public License for more details.
-*
-* You should have received a copy of the GNU Lesser General Public
-* License along with this software; if not, write to the Free
-* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
-*
-* @author <a href="mailto:roy@jboss.org">Roy Russo</a>
-*/
-
-var o_el_regionA = new Array();
-var o_el_regionB = new Array();
-
-/**
- AJAX Send function. Assembles post data, and handles process
- **/
-function sendData(action, windowId, fromPos, fromRegion, toPos, toRegion)
-{
- var options = {
- method: 'post',
- postBody: 'action=' + action + '&windowId=' + windowId + '&fromPos=' + fromPos + '&fromRegion=' + fromRegion + '&toPos=' + toPos + '&toRegion=' + toRegion,
- onSuccess: function(t)
- {
-// a = document.getElementById("ReqProgressIndicator");
-// document.body.removeChild(a);
- },
- onSuccess: function(t)
- {
-// a = document.getElementById("ReqProgressIndicator");
-// document.body.removeChild(a);
- },
- on404: function(t)
- {
-// a = document.getElementById("ReqProgressIndicator");
-// document.body.removeChild(a);
- alert('Error 404: location "' + t.statusText + '" was not found.');
- },
- onFailure: function(t)
- {
-// a = document.getElementById("ReqProgressIndicator");
-// document.body.removeChild(a);
- alert('Error ' + t.status + ' -- ' + t.statusText);
- },
- onLoading: function(t)
- {
- }
- }
-
- new Ajax.Request(remote_server_url, options);
-
-/*
- a = document.createElement("div");
- a.id = "ReqProgressIndicator";
- a.style.position = "absolute";
- a.style.left = "50%";
- a.style.bottom = "50%";
- a.style.width = "200px";
- a.style.height = "20px"
- a.style.verticalAlign = "bottom";
- a.style.display = '';
- a.innerHTML = "<img style='VERTICAL-ALIGN:bottom' src='images/roller.gif'>";
- document.body.appendChild(a);
-*/
-}
-
-/**
- Class that tracks window movement and updates DOM on move end.
- **/
-try
-{
- var WindowMoveObserver = Class.create();
- WindowMoveObserver.prototype =
- {
- initialize: function(element)
- {
- this.element = $(element);
- },
- onStart: function()
- {
- },
- onEnd: function()
- {
- var children = this.element.childNodes;
- for(var i = 0; i < children.length; i = i + 1)
- {
- if(Draggables.activeDraggable.element == children[i])
- {
- fromPos = findWindowPos(children[i]);
- fromRegion = findWindowRegion(children[i]);
-
- //alert("Moved: " + thischild.id + " from: " + fromRegion + " pos: " + fromPos);
- //alert("Moved: " + thischild.id + " to: " + this.element.id + " pos: " + i);
-
- // window moved, update DOM
- updateDOM();
-
- // send Data
- sendData('windowmove', children[i].id, fromPos, fromRegion, i, this.element.id);
- break;
- // or FF continues looping.
- }
- }
- }
- }
-}
-catch(e)
-{
- alert(e);
-}
-
-/**
- Creates sortables (drag/drop windows), attach observers and initialize the DOM
- **/
-try
-{
- Sortable.create("regionA", {dropOnEmpty:true,handle:'handle',tag:'div',containment:["regionA","regionB"],constraint:false, ghosting: false,
- onChange: function(el)
- {
- },
- onUpdate: function (el)
- {
- }
- });
-
- Sortable.create("regionB", {dropOnEmpty:true,handle:'handle',tag:'div',containment:["regionA","regionB"],constraint:false, ghosting: false,
- onChange: function(el)
- {
- },
- onUpdate: function (el)
- {
- }
- });
-
- // attach observers to regions
- Draggables.addObserver(new WindowMoveObserver($('regionA')));
- Draggables.addObserver(new WindowMoveObserver($('regionB')));
-
- // initialize DOM
- updateDOM();
-}
-catch(e)
-{
- alert(e);
-}
-
-/**
- Update th DOM order in our global array. Later used to compare move from/to
- **/
-function updateDOM()
-{
- try
- {
- // reset to 0
- o_el_regionA = new Array();
- o_el_regionB = new Array();
-
- var regionA = this.document.getElementById("regionA");
- for(var i = 0; i < regionA.childNodes.length; i = i + 1)
- {
- o_el_regionA[i] = regionA.childNodes[i];
- }
- var regionB = this.document.getElementById("regionB");
- for(var i = 0; i < regionB.childNodes.length; i = i + 1)
- {
- o_el_regionB[i] = regionB.childNodes[i];
- }
- //alert("New A: " + o_el_regionA.length + " New B: " + o_el_regionB.length);
- }
- catch(e)
- {
- alert("Error updateDOM: " + e);
- }
-}
-
-/**
- Returns theoriginal Window position for a given window element
- **/
-function findWindowPos(element)
-{
- for(var i = 0; i < o_el_regionA.length; i = i + 1)
- {
- currelement = o_el_regionA[i];
- if(element == currelement)
- {
- return i;
- }
- }
- for(var i = 0; i < o_el_regionB.length; i = i + 1)
- {
- currelement = o_el_regionB[i];
- if(element = currelement)
- {
- return i;
- }
- }
-}
-
-/**
- Returns the original region where a window resided.
- **/
-function findWindowRegion(element)
-{
- for(var i = 0; i < o_el_regionA.length; i = i + 1)
- {
- currelement = o_el_regionA[i];
- if(element == currelement)
- {
- return "regionA";
- }
- }
- for(var i = 0; i < o_el_regionB.length; i = i + 1)
- {
- currelement = o_el_regionB[i];
- if(element = currelement)
- {
- return "regionB";
- }
- }
-}
-
-/**
- Removes window from page and calls server-side
- **/
-function removeWindow(elementId)
-{
- var effectElement = document.getElementById(elementId)
- new Effect.BlindUp(effectElement);
-
- //removeElement(effectElement);
-
- sendData('windowremove', elementId);
-}
-
Modified: trunk/theme/src/bin/portal-ajax-war/js/portal/prototype.js
===================================================================
--- trunk/theme/src/bin/portal-ajax-war/js/portal/prototype.js 2007-03-31 14:21:37 UTC (rev 6895)
+++ trunk/theme/src/bin/portal-ajax-war/js/portal/prototype.js 2007-03-31 14:25:31 UTC (rev 6896)
@@ -1,5 +1,5 @@
-/* Prototype JavaScript framework, version 1.5.0_rc1
- * (c) 2005 Sam Stephenson <sam(a)conio.net>
+/* Prototype JavaScript framework, version 1.5.0
+ * (c) 2005-2007 Sam Stephenson
*
* Prototype is freely distributable under the terms of an MIT-style license.
* For details, see the Prototype web site: http://prototype.conio.net/
@@ -7,11 +7,14 @@
/*--------------------------------------------------------------------------*/
var Prototype = {
- Version: '1.5.0_rc1',
+ Version: '1.5.0',
+ BrowserFeatures: {
+ XPath: !!document.evaluate
+ },
+
ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
-
emptyFunction: function() {},
- K: function(x) {return x}
+ K: function(x) { return x }
}
var Class = {
@@ -34,8 +37,8 @@
Object.extend(Object, {
inspect: function(object) {
try {
- if (object == undefined) return 'undefined';
- if (object == null) return 'null';
+ if (object === undefined) return 'undefined';
+ if (object === null) return 'null';
return object.inspect ? object.inspect() : object.toString();
} catch (e) {
if (e instanceof RangeError) return '...';
@@ -97,7 +100,7 @@
these: function() {
var returnValue;
- for (var i = 0; i < arguments.length; i++) {
+ for (var i = 0, length = arguments.length; i < length; i++) {
var lambda = arguments[i];
try {
returnValue = lambda();
@@ -142,6 +145,10 @@
}
}
}
+String.interpret = function(value){
+ return value == null ? '' : String(value);
+}
+
Object.extend(String.prototype, {
gsub: function(pattern, replacement) {
var result = '', source = this, match;
@@ -150,7 +157,7 @@
while (source.length > 0) {
if (match = source.match(pattern)) {
result += source.slice(0, match.index);
- result += (replacement(match) || '').toString();
+ result += String.interpret(replacement(match));
source = source.slice(match.index + match[0].length);
} else {
result += source, source = '';
@@ -215,16 +222,28 @@
unescapeHTML: function() {
var div = document.createElement('div');
div.innerHTML = this.stripTags();
- return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
+ return div.childNodes[0] ? (div.childNodes.length > 1 ?
+ $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) :
+ div.childNodes[0].nodeValue) : '';
},
- toQueryParams: function() {
- var pairs = this.match(/^\??(.*)$/)[1].split('&');
- return pairs.inject({}, function(params, pairString) {
- var pair = pairString.split('=');
- var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;
- params[decodeURIComponent(pair[0])] = value;
- return params;
+ toQueryParams: function(separator) {
+ var match = this.strip().match(/([^?#]*)(#.*)?$/);
+ if (!match) return {};
+
+ return match[1].split(separator || '&').inject({}, function(hash, pair) {
+ if ((pair = pair.split('='))[0]) {
+ var name = decodeURIComponent(pair[0]);
+ var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;
+
+ if (hash[name] !== undefined) {
+ if (hash[name].constructor != Array)
+ hash[name] = [hash[name]];
+ if (value) hash[name].push(value);
+ }
+ else hash[name] = value;
+ }
+ return hash;
});
},
@@ -232,22 +251,37 @@
return this.split('');
},
+ succ: function() {
+ return this.slice(0, this.length - 1) +
+ String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
+ },
+
camelize: function() {
- var oStringList = this.split('-');
- if (oStringList.length == 1) return oStringList[0];
+ var parts = this.split('-'), len = parts.length;
+ if (len == 1) return parts[0];
- var camelizedString = this.indexOf('-') == 0
- ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
- : oStringList[0];
+ var camelized = this.charAt(0) == '-'
+ ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
+ : parts[0];
- for (var i = 1, len = oStringList.length; i < len; i++) {
- var s = oStringList[i];
- camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
- }
+ for (var i = 1; i < len; i++)
+ camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
- return camelizedString;
+ return camelized;
},
+ capitalize: function(){
+ return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
+ },
+
+ underscore: function() {
+ return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
+ },
+
+ dasherize: function() {
+ return this.gsub(/_/,'-');
+ },
+
inspect: function(useDoubleQuotes) {
var escapedString = this.replace(/\\/g, '\\\\');
if (useDoubleQuotes)
@@ -277,7 +311,7 @@
return this.template.gsub(this.pattern, function(match) {
var before = match[1];
if (before == '\\') return match[2];
- return before + (object[match[3]] || '').toString();
+ return before + String.interpret(object[match[3]]);
});
}
}
@@ -299,8 +333,16 @@
} catch (e) {
if (e != $break) throw e;
}
+ return this;
},
+ eachSlice: function(number, iterator) {
+ var index = -number, slices = [], array = this.toArray();
+ while ((index += number) < array.length)
+ slices.push(array.slice(index, index+number));
+ return slices.map(iterator);
+ },
+
all: function(iterator) {
var result = true;
this.each(function(value, index) {
@@ -322,12 +364,12 @@
collect: function(iterator) {
var results = [];
this.each(function(value, index) {
- results.push(iterator(value, index));
+ results.push((iterator || Prototype.K)(value, index));
});
return results;
},
- detect: function (iterator) {
+ detect: function(iterator) {
var result;
this.each(function(value, index) {
if (iterator(value, index)) {
@@ -368,6 +410,14 @@
return found;
},
+ inGroupsOf: function(number, fillWith) {
+ fillWith = fillWith === undefined ? null : fillWith;
+ return this.eachSlice(number, function(slice) {
+ while(slice.length < number) slice.push(fillWith);
+ return slice;
+ });
+ },
+
inject: function(memo, iterator) {
this.each(function(value, index) {
memo = iterator(memo, value, index);
@@ -377,7 +427,7 @@
invoke: function(method) {
var args = $A(arguments).slice(1);
- return this.collect(function(value) {
+ return this.map(function(value) {
return value[method].apply(value, args);
});
},
@@ -429,7 +479,7 @@
},
sortBy: function(iterator) {
- return this.collect(function(value, index) {
+ return this.map(function(value, index) {
return {value: value, criteria: iterator(value, index)};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
@@ -438,7 +488,7 @@
},
toArray: function() {
- return this.collect(Prototype.K);
+ return this.map();
},
zip: function() {
@@ -452,6 +502,10 @@
});
},
+ size: function() {
+ return this.toArray().length;
+ },
+
inspect: function() {
return '#<Enumerable:' + this.toArray().inspect() + '>';
}
@@ -470,7 +524,7 @@
return iterable.toArray();
} else {
var results = [];
- for (var i = 0; i < iterable.length; i++)
+ for (var i = 0, length = iterable.length; i < length; i++)
results.push(iterable[i]);
return results;
}
@@ -483,7 +537,7 @@
Object.extend(Array.prototype, {
_each: function(iterator) {
- for (var i = 0; i < this.length; i++)
+ for (var i = 0, length = this.length; i < length; i++)
iterator(this[i]);
},
@@ -502,7 +556,7 @@
compact: function() {
return this.select(function(value) {
- return value != undefined || value != null;
+ return value != null;
});
},
@@ -521,7 +575,7 @@
},
indexOf: function(object) {
- for (var i = 0; i < this.length; i++)
+ for (var i = 0, length = this.length; i < length; i++)
if (this[i] == object) return i;
return -1;
},
@@ -540,15 +594,78 @@
});
},
+ clone: function() {
+ return [].concat(this);
+ },
+
+ size: function() {
+ return this.length;
+ },
+
inspect: function() {
return '[' + this.map(Object.inspect).join(', ') + ']';
}
});
-var Hash = {
+
+Array.prototype.toArray = Array.prototype.clone;
+
+function $w(string){
+ string = string.strip();
+ return string ? string.split(/\s+/) : [];
+}
+
+if(window.opera){
+ Array.prototype.concat = function(){
+ var array = [];
+ for(var i = 0, length = this.length; i < length; i++) array.push(this[i]);
+ for(var i = 0, length = arguments.length; i < length; i++) {
+ if(arguments[i].constructor == Array) {
+ for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
+ array.push(arguments[i][j]);
+ } else {
+ array.push(arguments[i]);
+ }
+ }
+ return array;
+ }
+}
+var Hash = function(obj) {
+ Object.extend(this, obj || {});
+};
+
+Object.extend(Hash, {
+ toQueryString: function(obj) {
+ var parts = [];
+
+ this.prototype._each.call(obj, function(pair) {
+ if (!pair.key) return;
+
+ if (pair.value && pair.value.constructor == Array) {
+ var values = pair.value.compact();
+ if (values.length < 2) pair.value = values.reduce();
+ else {
+ key = encodeURIComponent(pair.key);
+ values.each(function(value) {
+ value = value != undefined ? encodeURIComponent(value) : '';
+ parts.push(key + '=' + encodeURIComponent(value));
+ });
+ return;
+ }
+ }
+ if (pair.value == undefined) pair[1] = '';
+ parts.push(pair.map(encodeURIComponent).join('='));
+ });
+
+ return parts.join('&');
+ }
+});
+
+Object.extend(Hash.prototype, Enumerable);
+Object.extend(Hash.prototype, {
_each: function(iterator) {
for (var key in this) {
var value = this[key];
- if (typeof value == 'function') continue;
+ if (value && value == Hash.prototype[key]) continue;
var pair = [key, value];
pair.key = key;
@@ -566,16 +683,30 @@
},
merge: function(hash) {
- return $H(hash).inject($H(this), function(mergedHash, pair) {
+ return $H(hash).inject(this, function(mergedHash, pair) {
mergedHash[pair.key] = pair.value;
return mergedHash;
});
},
+ remove: function() {
+ var result;
+ for(var i = 0, length = arguments.length; i < length; i++) {
+ var value = this[arguments[i]];
+ if (value !== undefined){
+ if (result === undefined) result = value;
+ else {
+ if (result.constructor != Array) result = [result];
+ result.push(value)
+ }
+ }
+ delete this[arguments[i]];
+ }
+ return result;
+ },
+
toQueryString: function() {
- return this.map(function(pair) {
- return pair.map(encodeURIComponent).join('=');
- }).join('&');
+ return Hash.toQueryString(this);
},
inspect: function() {
@@ -583,14 +714,12 @@
return pair.map(Object.inspect).join(': ');
}).join(', ') + '}>';
}
-}
+});
function $H(object) {
- var hash = Object.extend({}, object || {});
- Object.extend(hash, Enumerable);
- Object.extend(hash, Hash);
- return hash;
-}
+ if (object && object.constructor == Hash) return object;
+ return new Hash(object);
+};
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
@@ -640,18 +769,18 @@
this.responders._each(iterator);
},
- register: function(responderToAdd) {
- if (!this.include(responderToAdd))
- this.responders.push(responderToAdd);
+ register: function(responder) {
+ if (!this.include(responder))
+ this.responders.push(responder);
},
- unregister: function(responderToRemove) {
- this.responders = this.responders.without(responderToRemove);
+ unregister: function(responder) {
+ this.responders = this.responders.without(responder);
},
dispatch: function(callback, request, transport, json) {
this.each(function(responder) {
- if (responder[callback] && typeof responder[callback] == 'function') {
+ if (typeof responder[callback] == 'function') {
try {
responder[callback].apply(responder, [request, transport, json]);
} catch (e) {}
@@ -666,7 +795,6 @@
onCreate: function() {
Ajax.activeRequestCount++;
},
-
onComplete: function() {
Ajax.activeRequestCount--;
}
@@ -679,19 +807,14 @@
method: 'post',
asynchronous: true,
contentType: 'application/x-www-form-urlencoded',
+ encoding: 'UTF-8',
parameters: ''
}
Object.extend(this.options, options || {});
- },
- responseIsSuccess: function() {
- return this.transport.status == undefined
- || this.transport.status == 0
- || (this.transport.status >= 200 && this.transport.status < 300);
- },
-
- responseIsFailure: function() {
- return !this.responseIsSuccess();
+ this.options.method = this.options.method.toLowerCase();
+ if (typeof this.options.parameters == 'string')
+ this.options.parameters = this.options.parameters.toQueryParams();
}
}
@@ -700,6 +823,8 @@
['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];
Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
+ _complete: false,
+
initialize: function(url, options) {
this.transport = Ajax.getTransport();
this.setOptions(options);
@@ -707,23 +832,27 @@
},
request: function(url) {
- var parameters = this.options.parameters || '';
- if (parameters.length > 0) parameters += '&_=';
+ this.url = url;
+ this.method = this.options.method;
+ var params = this.options.parameters;
- /* Simulate other verbs over post */
- if (this.options.method != 'get' && this.options.method != 'post') {
- parameters += (parameters.length > 0 ? '&' : '') + '_method=' + this.options.method;
- this.options.method = 'post';
+ if (!['get', 'post'].include(this.method)) {
+ // simulate other verbs over post
+ params['_method'] = this.method;
+ this.method = 'post';
}
+ params = Hash.toQueryString(params);
+ if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_='
+
+ // when GET, append parameters to URL
+ if (this.method == 'get' && params)
+ this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params;
+
try {
- this.url = url;
- if (this.options.method == 'get' && parameters.length > 0)
- this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;
-
Ajax.Responders.dispatch('onCreate', this, this.transport);
- this.transport.open(this.options.method, this.url,
+ this.transport.open(this.method.toUpperCase(), this.url,
this.options.asynchronous);
if (this.options.asynchronous)
@@ -732,97 +861,119 @@
this.transport.onreadystatechange = this.onStateChange.bind(this);
this.setRequestHeaders();
- var body = this.options.postBody ? this.options.postBody : parameters;
- this.transport.send(this.options.method == 'post' ? body : null);
+ var body = this.method == 'post' ? (this.options.postBody || params) : null;
+ this.transport.send(body);
+
/* Force Firefox to handle ready state 4 for synchronous requests */
if (!this.options.asynchronous && this.transport.overrideMimeType)
this.onStateChange();
- } catch (e) {
+ }
+ catch (e) {
this.dispatchException(e);
}
},
+ onStateChange: function() {
+ var readyState = this.transport.readyState;
+ if (readyState > 1 && !((readyState == 4) && this._complete))
+ this.respondToReadyState(this.transport.readyState);
+ },
+
setRequestHeaders: function() {
- var requestHeaders =
- ['X-Requested-With', 'XMLHttpRequest',
- 'X-Prototype-Version', Prototype.Version,
- 'Accept', 'text/javascript, text/html, application/xml, text/xml, */*'];
+ var headers = {
+ 'X-Requested-With': 'XMLHttpRequest',
+ 'X-Prototype-Version': Prototype.Version,
+ 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
+ };
- if (this.options.method == 'post') {
- requestHeaders.push('Content-type', this.options.contentType);
+ if (this.method == 'post') {
+ headers['Content-type'] = this.options.contentType +
+ (this.options.encoding ? '; charset=' + this.options.encoding : '');
- /* Force "Connection: close" for Mozilla browsers to work around
- * a bug where XMLHttpReqeuest sends an incorrect Content-length
- * header. See Mozilla Bugzilla #246651.
+ /* Force "Connection: close" for older Mozilla browsers to work
+ * around a bug where XMLHttpRequest sends an incorrect
+ * Content-length header. See Mozilla Bugzilla #246651.
*/
- if (this.transport.overrideMimeType)
- requestHeaders.push('Connection', 'close');
+ if (this.transport.overrideMimeType &&
+ (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
+ headers['Connection'] = 'close';
}
- if (this.options.requestHeaders)
- requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);
+ // user-defined headers
+ if (typeof this.options.requestHeaders == 'object') {
+ var extras = this.options.requestHeaders;
- for (var i = 0; i < requestHeaders.length; i += 2)
- this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
- },
+ if (typeof extras.push == 'function')
+ for (var i = 0, length = extras.length; i < length; i += 2)
+ headers[extras[i]] = extras[i+1];
+ else
+ $H(extras).each(function(pair) { headers[pair.key] = pair.value });
+ }
- onStateChange: function() {
- var readyState = this.transport.readyState;
- if (readyState != 1)
- this.respondToReadyState(this.transport.readyState);
+ for (var name in headers)
+ this.transport.setRequestHeader(name, headers[name]);
},
- header: function(name) {
- try {
- return this.transport.getResponseHeader(name);
- } catch (e) {}
+ success: function() {
+ return !this.transport.status
+ || (this.transport.status >= 200 && this.transport.status < 300);
},
- evalJSON: function() {
- try {
- return eval('(' + this.header('X-JSON') + ')');
- } catch (e) {}
- },
-
- evalResponse: function() {
- try {
- return eval(this.transport.responseText);
- } catch (e) {
- this.dispatchException(e);
- }
- },
-
respondToReadyState: function(readyState) {
- var event = Ajax.Request.Events[readyState];
+ var state = Ajax.Request.Events[readyState];
var transport = this.transport, json = this.evalJSON();
- if (event == 'Complete') {
+ if (state == 'Complete') {
try {
+ this._complete = true;
(this.options['on' + this.transport.status]
- || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
+ || this.options['on' + (this.success() ? 'Success' : 'Failure')]
|| Prototype.emptyFunction)(transport, json);
} catch (e) {
this.dispatchException(e);
}
- if ((this.header('Content-type') || '').match(/^text\/javascript/i))
- this.evalResponse();
+ if ((this.getHeader('Content-type') || 'text/javascript').strip().
+ match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
+ this.evalResponse();
}
try {
- (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
- Ajax.Responders.dispatch('on' + event, this, transport, json);
+ (this.options['on' + state] || Prototype.emptyFunction)(transport, json);
+ Ajax.Responders.dispatch('on' + state, this, transport, json);
} catch (e) {
this.dispatchException(e);
}
- /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
- if (event == 'Complete')
+ if (state == 'Complete') {
+ // avoid memory leak in MSIE: clean up
this.transport.onreadystatechange = Prototype.emptyFunction;
+ }
},
+ getHeader: function(name) {
+ try {
+ return this.transport.getResponseHeader(name);
+ } catch (e) { return null }
+ },
+
+ evalJSON: function() {
+ try {
+ var json = this.getHeader('X-JSON');
+ return json ? eval('(' + json + ')') : null;
+ } catch (e) { return null }
+ },
+
+ evalResponse: function() {
+ try {
+ return eval(this.transport.responseText);
+ } catch (e) {
+ this.dispatchException(e);
+ }
+ },
+
dispatchException: function(exception) {
(this.options.onException || Prototype.emptyFunction)(this, exception);
Ajax.Responders.dispatch('onException', this, exception);
@@ -833,41 +984,37 @@
Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
initialize: function(container, url, options) {
- this.containers = {
- success: container.success ? $(container.success) : $(container),
- failure: container.failure ? $(container.failure) :
- (container.success ? null : $(container))
+ this.container = {
+ success: (container.success || container),
+ failure: (container.failure || (container.success ? null : container))
}
this.transport = Ajax.getTransport();
this.setOptions(options);
var onComplete = this.options.onComplete || Prototype.emptyFunction;
- this.options.onComplete = (function(transport, object) {
+ this.options.onComplete = (function(transport, param) {
this.updateContent();
- onComplete(transport, object);
+ onComplete(transport, param);
}).bind(this);
this.request(url);
},
updateContent: function() {
- var receiver = this.responseIsSuccess() ?
- this.containers.success : this.containers.failure;
+ var receiver = this.container[this.success() ? 'success' : 'failure'];
var response = this.transport.responseText;
- if (!this.options.evalScripts)
- response = response.stripScripts();
+ if (!this.options.evalScripts) response = response.stripScripts();
- if (receiver) {
- if (this.options.insertion) {
+ if (receiver = $(receiver)) {
+ if (this.options.insertion)
new this.options.insertion(receiver, response);
- } else {
- Element.update(receiver, response);
- }
+ else
+ receiver.update(response);
}
- if (this.responseIsSuccess()) {
+ if (this.success()) {
if (this.onComplete)
setTimeout(this.onComplete.bind(this), 10);
}
@@ -916,25 +1063,43 @@
this.updater = new Ajax.Updater(this.container, this.url, this.options);
}
});
-function $() {
- var results = [], element;
- for (var i = 0; i < arguments.length; i++) {
- element = arguments[i];
- if (typeof element == 'string')
- element = document.getElementById(element);
- results.push(Element.extend(element));
+function $(element) {
+ if (arguments.length > 1) {
+ for (var i = 0, elements = [], length = arguments.length; i < length; i++)
+ elements.push($(arguments[i]));
+ return elements;
}
- return results.reduce();
+ if (typeof element == 'string')
+ element = document.getElementById(element);
+ return Element.extend(element);
}
+if (Prototype.BrowserFeatures.XPath) {
+ document._getElementsByXPath = function(expression, parentElement) {
+ var results = [];
+ var query = document.evaluate(expression, $(parentElement) || document,
+ null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
+ for (var i = 0, length = query.snapshotLength; i < length; i++)
+ results.push(query.snapshotItem(i));
+ return results;
+ };
+}
+
document.getElementsByClassName = function(className, parentElement) {
- var children = ($(parentElement) || document.body).getElementsByTagName('*');
- return $A(children).inject([], function(elements, child) {
- if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
- elements.push(Element.extend(child));
+ if (Prototype.BrowserFeatures.XPath) {
+ var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
+ return document._getElementsByXPath(q, parentElement);
+ } else {
+ var children = ($(parentElement) || document.body).getElementsByTagName('*');
+ var elements = [], child;
+ for (var i = 0, length = children.length; i < length; i++) {
+ child = children[i];
+ if (Element.hasClassName(child, className))
+ elements.push(Element.extend(child));
+ }
return elements;
- });
-}
+ }
+};
/*--------------------------------------------------------------------------*/
@@ -942,8 +1107,7 @@
var Element = new Object();
Element.extend = function(element) {
- if (!element) return;
- if (_nativeExtensions || element.nodeType == 3) return element;
+ if (!element || _nativeExtensions || element.nodeType == 3) return element;
if (!element._extended && element.tagName && element != window) {
var methods = Object.clone(Element.Methods), cache = Element.extend.cache;
@@ -953,16 +1117,18 @@
if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName))
Object.extend(methods, Form.Element.Methods);
+ Object.extend(methods, Element.Methods.Simulated);
+
for (var property in methods) {
var value = methods[property];
- if (typeof value == 'function')
+ if (typeof value == 'function' && !(property in element))
element[property] = cache.findOrStore(value);
}
}
element._extended = true;
return element;
-}
+};
Element.extend.cache = {
findOrStore: function(value) {
@@ -970,7 +1136,7 @@
return value.apply(null, [this].concat($A(arguments)));
}
}
-}
+};
Element.Methods = {
visible: function(element) {
@@ -1000,6 +1166,7 @@
},
update: function(element, html) {
+ html = typeof html == 'undefined' ? '' : html.toString();
$(element).innerHTML = html.stripScripts();
setTimeout(function() {html.evalScripts()}, 10);
return element;
@@ -1007,6 +1174,7 @@
replace: function(element, html) {
element = $(element);
+ html = typeof html == 'undefined' ? '' : html.toString();
if (element.outerHTML) {
element.outerHTML = html.stripScripts();
} else {
@@ -1044,10 +1212,16 @@
},
descendants: function(element) {
- element = $(element);
- return $A(element.getElementsByTagName('*'));
+ return $A($(element).getElementsByTagName('*'));
},
+ immediateDescendants: function(element) {
+ if (!(element = $(element).firstChild)) return [];
+ while (element && element.nodeType != 1) element = element.nextSibling;
+ if (element) return [element].concat($(element).nextSiblings());
+ return [];
+ },
+
previousSiblings: function(element) {
return $(element).recursivelyCollect('previousSibling');
},
@@ -1062,10 +1236,9 @@
},
match: function(element, selector) {
- element = $(element);
if (typeof selector == 'string')
selector = new Selector(selector);
- return selector.match(element);
+ return selector.match($(element));
},
up: function(element, expression, index) {
@@ -1090,22 +1263,41 @@
},
getElementsByClassName: function(element, className) {
- element = $(element);
return document.getElementsByClassName(className, element);
},
- getHeight: function(element) {
+ readAttribute: function(element, name) {
element = $(element);
- return element.offsetHeight;
+ if (document.all && !window.opera) {
+ var t = Element._attributeTranslations;
+ if (t.values[name]) return t.values[name](element, name);
+ if (t.names[name]) name = t.names[name];
+ var attribute = element.attributes[name];
+ if(attribute) return attribute.nodeValue;
+ }
+ return element.getAttribute(name);
},
+ getHeight: function(element) {
+ return $(element).getDimensions().height;
+ },
+
+ getWidth: function(element) {
+ return $(element).getDimensions().width;
+ },
+
classNames: function(element) {
return new Element.ClassNames(element);
},
hasClassName: function(element, className) {
if (!(element = $(element))) return;
- return Element.classNames(element).include(className);
+ var elementClassName = element.className;
+ if (elementClassName.length == 0) return false;
+ if (elementClassName == className ||
+ elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
+ return true;
+ return false;
},
addClassName: function(element, className) {
@@ -1120,6 +1312,12 @@
return element;
},
+ toggleClassName: function(element, className) {
+ if (!(element = $(element))) return;
+ Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className);
+ return element;
+ },
+
observe: function() {
Event.observe.apply(Event, arguments);
return $A(arguments).first();
@@ -1147,7 +1345,7 @@
return $(element).innerHTML.match(/^\s*$/);
},
- childOf: function(element, ancestor) {
+ descendantOf: function(element, ancestor) {
element = $(element), ancestor = $(ancestor);
while (element = element.parentNode)
if (element == ancestor) return true;
@@ -1156,40 +1354,69 @@
scrollTo: function(element) {
element = $(element);
- var x = element.x ? element.x : element.offsetLeft,
- y = element.y ? element.y : element.offsetTop;
- window.scrollTo(x, y);
+ var pos = Position.cumulativeOffset(element);
+ window.scrollTo(pos[0], pos[1]);
return element;
},
getStyle: function(element, style) {
element = $(element);
- var value = element.style[style.camelize()];
+ if (['float','cssFloat'].include(style))
+ style = (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat');
+ style = style.camelize();
+ var value = element.style[style];
if (!value) {
if (document.defaultView && document.defaultView.getComputedStyle) {
var css = document.defaultView.getComputedStyle(element, null);
- value = css ? css.getPropertyValue(style) : null;
+ value = css ? css[style] : null;
} else if (element.currentStyle) {
- value = element.currentStyle[style.camelize()];
+ value = element.currentStyle[style];
}
}
+ if((value == 'auto') && ['width','height'].include(style) && (element.getStyle('display') != 'none'))
+ value = element['offset'+style.capitalize()] + 'px';
+
if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
if (Element.getStyle(element, 'position') == 'static') value = 'auto';
-
+ if(style == 'opacity') {
+ if(value) return parseFloat(value);
+ if(value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
+ if(value[1]) return parseFloat(value[1]) / 100;
+ return 1.0;
+ }
return value == 'auto' ? null : value;
},
setStyle: function(element, style) {
element = $(element);
- for (var name in style)
- element.style[name.camelize()] = style[name];
+ for (var name in style) {
+ var value = style[name];
+ if(name == 'opacity') {
+ if (value == 1) {
+ value = (/Gecko/.test(navigator.userAgent) &&
+ !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0;
+ if(/MSIE/.test(navigator.userAgent) && !window.opera)
+ element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
+ } else if(value === '') {
+ if(/MSIE/.test(navigator.userAgent) && !window.opera)
+ element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
+ } else {
+ if(value < 0.00001) value = 0;
+ if(/MSIE/.test(navigator.userAgent) && !window.opera)
+ element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') +
+ 'alpha(opacity='+value*100+')';
+ }
+ } else if(['float','cssFloat'].include(name)) name = (typeof element.style.styleFloat != 'undefined') ? 'styleFloat' : 'cssFloat';
+ element.style[name.camelize()] = value;
+ }
return element;
},
getDimensions: function(element) {
element = $(element);
- if (Element.getStyle(element, 'display') != 'none')
+ var display = $(element).getStyle('display');
+ if (display != 'none' && display != null) // Safari bug
return {width: element.offsetWidth, height: element.offsetHeight};
// All *Width and *Height properties give 0 on elements with display none,
@@ -1197,12 +1424,13 @@
var els = element.style;
var originalVisibility = els.visibility;
var originalPosition = els.position;
+ var originalDisplay = els.display;
els.visibility = 'hidden';
els.position = 'absolute';
- els.display = '';
+ els.display = 'block';
var originalWidth = element.clientWidth;
var originalHeight = element.clientHeight;
- els.display = 'none';
+ els.display = originalDisplay;
els.position = originalPosition;
els.visibility = originalVisibility;
return {width: originalWidth, height: originalHeight};
@@ -1239,7 +1467,7 @@
makeClipping: function(element) {
element = $(element);
- if (element._overflow) return;
+ if (element._overflow) return element;
element._overflow = element.style.overflow || 'auto';
if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
element.style.overflow = 'hidden';
@@ -1248,19 +1476,73 @@
undoClipping: function(element) {
element = $(element);
- if (!element._overflow) return;
+ if (!element._overflow) return element;
element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
element._overflow = null;
return element;
}
-}
+};
+Object.extend(Element.Methods, {childOf: Element.Methods.descendantOf});
+
+Element._attributeTranslations = {};
+
+Element._attributeTranslations.names = {
+ colspan: "colSpan",
+ rowspan: "rowSpan",
+ valign: "vAlign",
+ datetime: "dateTime",
+ accesskey: "accessKey",
+ tabindex: "tabIndex",
+ enctype: "encType",
+ maxlength: "maxLength",
+ readonly: "readOnly",
+ longdesc: "longDesc"
+};
+
+Element._attributeTranslations.values = {
+ _getAttr: function(element, attribute) {
+ return element.getAttribute(attribute, 2);
+ },
+
+ _flag: function(element, attribute) {
+ return $(element).hasAttribute(attribute) ? attribute : null;
+ },
+
+ style: function(element) {
+ return element.style.cssText.toLowerCase();
+ },
+
+ title: function(element) {
+ var node = element.getAttributeNode('title');
+ return node.specified ? node.nodeValue : null;
+ }
+};
+
+Object.extend(Element._attributeTranslations.values, {
+ href: Element._attributeTranslations.values._getAttr,
+ src: Element._attributeTranslations.values._getAttr,
+ disabled: Element._attributeTranslations.values._flag,
+ checked: Element._attributeTranslations.values._flag,
+ readonly: Element._attributeTranslations.values._flag,
+ multiple: Element._attributeTranslations.values._flag
+});
+
+Element.Methods.Simulated = {
+ hasAttribute: function(element, attribute) {
+ var t = Element._attributeTranslations;
+ attribute = t.names[attribute] || attribute;
+ return $(element).getAttributeNode(attribute).specified;
+ }
+};
+
// IE is missing .innerHTML support for TABLE-related elements
-if(document.all){
+if (document.all && !window.opera){
Element.Methods.update = function(element, html) {
element = $(element);
+ html = typeof html == 'undefined' ? '' : html.toString();
var tagName = element.tagName.toUpperCase();
- if (['THEAD','TBODY','TR','TD'].indexOf(tagName) > -1) {
+ if (['THEAD','TBODY','TR','TD'].include(tagName)) {
var div = document.createElement('div');
switch (tagName) {
case 'THEAD':
@@ -1289,34 +1571,36 @@
setTimeout(function() {html.evalScripts()}, 10);
return element;
}
-}
+};
Object.extend(Element, Element.Methods);
var _nativeExtensions = false;
-if (!window.HTMLElement && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
- /* Emulate HTMLElement, HTMLFormElement, HTMLInputElement, HTMLTextAreaElement,
- and HTMLSelectElement in Safari */
+if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) {
- var klass = window['HTML' + tag + 'Element'] = {};
+ var className = 'HTML' + tag + 'Element';
+ if(window[className]) return;
+ var klass = window[className] = {};
klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__;
});
-}
Element.addMethods = function(methods) {
Object.extend(Element.Methods, methods || {});
- function copy(methods, destination) {
+ function copy(methods, destination, onlyIfAbsent) {
+ onlyIfAbsent = onlyIfAbsent || false;
var cache = Element.extend.cache;
for (var property in methods) {
var value = methods[property];
- destination[property] = cache.findOrStore(value);
+ if (!onlyIfAbsent || !(property in destination))
+ destination[property] = cache.findOrStore(value);
}
}
if (typeof HTMLElement != 'undefined') {
copy(Element.Methods, HTMLElement.prototype);
+ copy(Element.Methods.Simulated, HTMLElement.prototype, true);
copy(Form.Methods, HTMLFormElement.prototype);
[HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) {
copy(Form.Element.Methods, klass.prototype);
@@ -1343,8 +1627,8 @@
try {
this.element.insertAdjacentHTML(this.adjacency, this.content);
} catch (e) {
- var tagName = this.element.tagName.toLowerCase();
- if (tagName == 'tbody' || tagName == 'tr') {
+ var tagName = this.element.tagName.toUpperCase();
+ if (['TBODY', 'TR'].include(tagName)) {
this.insertContent(this.contentFromAnonymousTable());
} else {
throw e;
@@ -1443,20 +1727,18 @@
add: function(classNameToAdd) {
if (this.include(classNameToAdd)) return;
- this.set(this.toArray().concat(classNameToAdd).join(' '));
+ this.set($A(this).concat(classNameToAdd).join(' '));
},
remove: function(classNameToRemove) {
if (!this.include(classNameToRemove)) return;
- this.set(this.select(function(className) {
- return className != classNameToRemove;
- }).join(' '));
+ this.set($A(this).without(classNameToRemove).join(' '));
},
toString: function() {
- return this.toArray().join(' ');
+ return $A(this).join(' ');
}
-}
+};
Object.extend(Element.ClassNames.prototype, Enumerable);
var Selector = Class.create();
@@ -1503,15 +1785,15 @@
if (params.wildcard)
conditions.push('true');
if (clause = params.id)
- conditions.push('element.id == ' + clause.inspect());
+ conditions.push('element.readAttribute("id") == ' + clause.inspect());
if (clause = params.tagName)
conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
if ((clause = params.classNames).length > 0)
- for (var i = 0; i < clause.length; i++)
- conditions.push('Element.hasClassName(element, ' + clause[i].inspect() + ')');
+ for (var i = 0, length = clause.length; i < length; i++)
+ conditions.push('element.hasClassName(' + clause[i].inspect() + ')');
if (clause = params.attributes) {
clause.each(function(attribute) {
- var value = 'element.getAttribute(' + attribute.name.inspect() + ')';
+ var value = 'element.readAttribute(' + attribute.name.inspect() + ')';
var splitValueBy = function(delimiter) {
return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
}
@@ -1524,7 +1806,7 @@
); break;
case '!=': conditions.push(value + ' != ' + attribute.value.inspect()); break;
case '':
- case undefined: conditions.push(value + ' != null'); break;
+ case undefined: conditions.push('element.hasAttribute(' + attribute.name.inspect() + ')'); break;
default: throw 'Unknown operator ' + attribute.operator + ' in selector';
}
});
@@ -1535,6 +1817,7 @@
compileMatcher: function() {
this.match = new Function('element', 'if (!element.tagName) return false; \
+ element = $(element); \
return ' + this.buildMatchExpression());
},
@@ -1549,7 +1832,7 @@
scope = (scope || document).getElementsByTagName(this.params.tagName || '*');
var results = [];
- for (var i = 0; i < scope.length; i++)
+ for (var i = 0, length = scope.length; i < length; i++)
if (this.match(element = scope[i]))
results.push(Element.extend(element));
@@ -1564,7 +1847,7 @@
Object.extend(Selector, {
matchElements: function(elements, expression) {
var selector = new Selector(expression);
- return elements.select(selector.match.bind(selector));
+ return elements.select(selector.match.bind(selector)).map(Element.extend);
},
findElement: function(elements, expression, index) {
@@ -1574,7 +1857,7 @@
findChildElements: function(element, expressions) {
return expressions.map(function(expression) {
- return expression.strip().split(/\s+/).inject([null], function(results, expr) {
+ return expression.match(/[^\s"]+(?:"[^"]*"[^\s"]+)*/g).inject([null], function(results, expr) {
var selector = new Selector(expr);
return results.inject([], function(elements, result) {
return elements.concat(selector.findElements(result || element));
@@ -1591,49 +1874,53 @@
reset: function(form) {
$(form).reset();
return form;
+ },
+
+ serializeElements: function(elements, getHash) {
+ var data = elements.inject({}, function(result, element) {
+ if (!element.disabled && element.name) {
+ var key = element.name, value = $(element).getValue();
+ if (value != undefined) {
+ if (result[key]) {
+ if (result[key].constructor != Array) result[key] = [result[key]];
+ result[key].push(value);
+ }
+ else result[key] = value;
+ }
+ }
+ return result;
+ });
+
+ return getHash ? data : Hash.toQueryString(data);
}
};
Form.Methods = {
- serialize: function(form) {
- var elements = Form.getElements($(form));
- var queryComponents = new Array();
-
- for (var i = 0; i < elements.length; i++) {
- var queryComponent = Form.Element.serialize(elements[i]);
- if (queryComponent)
- queryComponents.push(queryComponent);
- }
-
- return queryComponents.join('&');
+ serialize: function(form, getHash) {
+ return Form.serializeElements(Form.getElements(form), getHash);
},
getElements: function(form) {
- form = $(form);
- var elements = new Array();
-
- for (var tagName in Form.Element.Serializers) {
- var tagElements = form.getElementsByTagName(tagName);
- for (var j = 0; j < tagElements.length; j++)
- elements.push(tagElements[j]);
- }
- return elements;
+ return $A($(form).getElementsByTagName('*')).inject([],
+ function(elements, child) {
+ if (Form.Element.Serializers[child.tagName.toLowerCase()])
+ elements.push(Element.extend(child));
+ return elements;
+ }
+ );
},
getInputs: function(form, typeName, name) {
form = $(form);
var inputs = form.getElementsByTagName('input');
- if (!typeName && !name)
- return inputs;
+ if (!typeName && !name) return $A(inputs).map(Element.extend);
- var matchingInputs = new Array();
- for (var i = 0; i < inputs.length; i++) {
+ for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
var input = inputs[i];
- if ((typeName && input.type != typeName) ||
- (name && input.name != name))
+ if ((typeName && input.type != typeName) || (name && input.name != name))
continue;
- matchingInputs.push(input);
+ matchingInputs.push(Element.extend(input));
}
return matchingInputs;
@@ -1641,27 +1928,23 @@
disable: function(form) {
form = $(form);
- var elements = Form.getElements(form);
- for (var i = 0; i < elements.length; i++) {
- var element = elements[i];
+ form.getElements().each(function(element) {
element.blur();
element.disabled = 'true';
- }
+ });
return form;
},
enable: function(form) {
form = $(form);
- var elements = Form.getElements(form);
- for (var i = 0; i < elements.length; i++) {
- var element = elements[i];
+ form.getElements().each(function(element) {
element.disabled = '';
- }
+ });
return form;
},
findFirstElement: function(form) {
- return Form.getElements(form).find(function(element) {
+ return $(form).getElements().find(function(element) {
return element.type != 'hidden' && !element.disabled &&
['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
});
@@ -1669,7 +1952,7 @@
focusFirstElement: function(form) {
form = $(form);
- Field.activate(Form.findFirstElement(form));
+ form.findFirstElement().activate();
return form;
}
}
@@ -1693,29 +1976,21 @@
Form.Element.Methods = {
serialize: function(element) {
element = $(element);
- var method = element.tagName.toLowerCase();
- var parameter = Form.Element.Serializers[method](element);
-
- if (parameter) {
- var key = encodeURIComponent(parameter[0]);
- if (key.length == 0) return;
-
- if (parameter[1].constructor != Array)
- parameter[1] = [parameter[1]];
-
- return parameter[1].map(function(value) {
- return key + '=' + encodeURIComponent(value);
- }).join('&');
+ if (!element.disabled && element.name) {
+ var value = element.getValue();
+ if (value != undefined) {
+ var pair = {};
+ pair[element.name] = value;
+ return Hash.toQueryString(pair);
+ }
}
+ return '';
},
getValue: function(element) {
element = $(element);
var method = element.tagName.toLowerCase();
- var parameter = Form.Element.Serializers[method](element);
-
- if (parameter)
- return parameter[1];
+ return Form.Element.Serializers[method](element);
},
clear: function(element) {
@@ -1730,27 +2005,29 @@
activate: function(element) {
element = $(element);
element.focus();
- if (element.select)
+ if (element.select && ( element.tagName.toLowerCase() != 'input' ||
+ !['button', 'reset', 'submit'].include(element.type) ) )
element.select();
return element;
},
disable: function(element) {
element = $(element);
- element.disabled = '';
+ element.disabled = true;
return element;
},
enable: function(element) {
element = $(element);
element.blur();
- element.disabled = 'true';
+ element.disabled = false;
return element;
}
}
Object.extend(Form.Element, Form.Element.Methods);
var Field = Form.Element;
+var $F = Form.Element.getValue;
/*--------------------------------------------------------------------------*/
@@ -1763,49 +2040,45 @@
default:
return Form.Element.Serializers.textarea(element);
}
- return false;
},
inputSelector: function(element) {
- if (element.checked)
- return [element.name, element.value];
+ return element.checked ? element.value : null;
},
textarea: function(element) {
- return [element.name, element.value];
+ return element.value;
},
select: function(element) {
- return Form.Element.Serializers[element.type == 'select-one' ?
+ return this[element.type == 'select-one' ?
'selectOne' : 'selectMany'](element);
},
selectOne: function(element) {
- var value = '', opt, index = element.selectedIndex;
- if (index >= 0) {
- opt = element.options[index];
- value = opt.value || opt.text;
- }
- return [element.name, value];
+ var index = element.selectedIndex;
+ return index >= 0 ? this.optionValue(element.options[index]) : null;
},
selectMany: function(element) {
- var value = [];
- for (var i = 0; i < element.length; i++) {
+ var values, length = element.length;
+ if (!length) return null;
+
+ for (var i = 0, values = []; i < length; i++) {
var opt = element.options[i];
- if (opt.selected)
- value.push(opt.value || opt.text);
+ if (opt.selected) values.push(this.optionValue(opt));
}
- return [element.name, value];
+ return values;
+ },
+
+ optionValue: function(opt) {
+ // extend element because hasAttribute may not be native
+ return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
}
}
/*--------------------------------------------------------------------------*/
-var $F = Form.Element.getValue;
-
-/*--------------------------------------------------------------------------*/
-
Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
initialize: function(element, frequency, callback) {
@@ -1823,7 +2096,9 @@
onTimerEvent: function() {
var value = this.getValue();
- if (this.lastValue != value) {
+ var changed = ('string' == typeof this.lastValue && 'string' == typeof value
+ ? this.lastValue != value : String(this.lastValue) != String(value));
+ if (changed) {
this.callback(this.element, value);
this.lastValue = value;
}
@@ -1868,9 +2143,7 @@
},
registerFormCallbacks: function() {
- var elements = Form.getElements(this.element);
- for (var i = 0; i < elements.length; i++)
- this.registerCallback(elements[i]);
+ Form.getElements(this.element).each(this.registerCallback.bind(this));
},
registerCallback: function(element) {
@@ -1974,7 +2247,7 @@
unloadCache: function() {
if (!Event.observers) return;
- for (var i = 0; i < Event.observers.length; i++) {
+ for (var i = 0, length = Event.observers.length; i < length; i++) {
Event.stopObserving.apply(this, Event.observers[i]);
Event.observers[i][0] = null;
}
@@ -2061,7 +2334,8 @@
valueL += element.offsetLeft || 0;
element = element.offsetParent;
if (element) {
- p = Element.getStyle(element, 'position');
+ if(element.tagName=='BODY') break;
+ var p = Element.getStyle(element, 'position');
if (p == 'relative' || p == 'absolute') break;
}
} while (element);
@@ -2197,10 +2471,10 @@
element._originalHeight = element.style.height;
element.style.position = 'absolute';
- element.style.top = top + 'px';;
- element.style.left = left + 'px';;
- element.style.width = width + 'px';;
- element.style.height = height + 'px';;
+ element.style.top = top + 'px';
+ element.style.left = left + 'px';
+ element.style.width = width + 'px';
+ element.style.height = height + 'px';
},
relativize: function(element) {
Modified: trunk/theme/src/bin/portal-ajax-war/js/portal/scriptaculous.js
===================================================================
--- trunk/theme/src/bin/portal-ajax-war/js/portal/scriptaculous.js 2007-03-31 14:21:37 UTC (rev 6895)
+++ trunk/theme/src/bin/portal-ajax-war/js/portal/scriptaculous.js 2007-03-31 14:25:31 UTC (rev 6896)
@@ -1,6 +1,6 @@
-// script.aculo.us scriptaculous.js v1.6.4, Wed Sep 06 11:30:58 CEST 2006
+// script.aculo.us scriptaculous.js v1.7.0, Fri Jan 19 19:16:36 CET 2007
-// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -20,9 +20,11 @@
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+// For details, see the script.aculo.us web site: http://script.aculo.us/
var Scriptaculous = {
- Version: '1.6.4',
+ Version: '1.7.0',
require: function(libraryName) {
// inserting via DOM fails in Safari 2.0, so brute force approach
document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
Modified: trunk/theme/src/bin/portal-ajax-war/js/portal/slider.js
===================================================================
--- trunk/theme/src/bin/portal-ajax-war/js/portal/slider.js 2007-03-31 14:21:37 UTC (rev 6895)
+++ trunk/theme/src/bin/portal-ajax-war/js/portal/slider.js 2007-03-31 14:25:31 UTC (rev 6896)
@@ -1,27 +1,9 @@
-// script.aculo.us slider.js v1.6.4, Wed Sep 06 11:30:58 CEST 2006
+// script.aculo.us slider.js v1.7.0, Fri Jan 19 19:16:36 CET 2007
-// Copyright (c) 2005 Marty Haught, Thomas Fuchs
+// Copyright (c) 2005, 2006 Marty Haught, Thomas Fuchs
//
-// See http://script.aculo.us for more info
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
if(!Control) var Control = {};
Control.Slider = Class.create();
@@ -241,14 +223,16 @@
// find the handle (prevents issues with Safari)
while((this.handles.indexOf(handle) == -1) && handle.parentNode)
handle = handle.parentNode;
-
- this.activeHandle = handle;
- this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
- this.updateStyles();
-
- var offsets = Position.cumulativeOffset(this.activeHandle);
- this.offsetX = (pointer[0] - offsets[0]);
- this.offsetY = (pointer[1] - offsets[1]);
+
+ if(this.handles.indexOf(handle)!=-1) {
+ this.activeHandle = handle;
+ this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
+ this.updateStyles();
+
+ var offsets = Position.cumulativeOffset(this.activeHandle);
+ this.offsetX = (pointer[0] - offsets[0]);
+ this.offsetY = (pointer[1] - offsets[1]);
+ }
}
}
Event.stop(event);
Modified: trunk/theme/src/bin/portal-ajax-war/js/portal/unittest.js
===================================================================
--- trunk/theme/src/bin/portal-ajax-war/js/portal/unittest.js 2007-03-31 14:21:37 UTC (rev 6895)
+++ trunk/theme/src/bin/portal-ajax-war/js/portal/unittest.js 2007-03-31 14:25:31 UTC (rev 6896)
@@ -1,552 +1,564 @@
-// script.aculo.us unittest.js v1.6.4, Wed Sep 06 11:30:58 CEST 2006
-
-// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-// (c) 2005 Jon Tirsen (http://www.tirsen.com)
-// (c) 2005 Michael Schuerig (http://www.schuerig.de/michael/)
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-
-// experimental, Firefox-only
-Event.simulateMouse = function(element, eventName) {
- var options = Object.extend({
- pointerX: 0,
- pointerY: 0,
- buttons: 0
- }, arguments[2] || {});
- var oEvent = document.createEvent("MouseEvents");
- oEvent.initMouseEvent(eventName, true, true, document.defaultView,
- options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
- false, false, false, false, 0, $(element));
-
- if(this.mark) Element.remove(this.mark);
- this.mark = document.createElement('div');
- this.mark.appendChild(document.createTextNode(" "));
- document.body.appendChild(this.mark);
- this.mark.style.position = 'absolute';
- this.mark.style.top = options.pointerY + "px";
- this.mark.style.left = options.pointerX + "px";
- this.mark.style.width = "5px";
- this.mark.style.height = "5px;";
- this.mark.style.borderTop = "1px solid red;"
- this.mark.style.borderLeft = "1px solid red;"
-
- if(this.step)
- alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options));
-
- $(element).dispatchEvent(oEvent);
-};
-
-// Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2.
-// You need to downgrade to 1.0.4 for now to get this working
-// See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much
-Event.simulateKey = function(element, eventName) {
- var options = Object.extend({
- ctrlKey: false,
- altKey: false,
- shiftKey: false,
- metaKey: false,
- keyCode: 0,
- charCode: 0
- }, arguments[2] || {});
-
- var oEvent = document.createEvent("KeyEvents");
- oEvent.initKeyEvent(eventName, true, true, window,
- options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
- options.keyCode, options.charCode );
- $(element).dispatchEvent(oEvent);
-};
-
-Event.simulateKeys = function(element, command) {
- for(var i=0; i<command.length; i++) {
- Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)});
- }
-};
-
-var Test = {}
-Test.Unit = {};
-
-// security exception workaround
-Test.Unit.inspect = Object.inspect;
-
-Test.Unit.Logger = Class.create();
-Test.Unit.Logger.prototype = {
- initialize: function(log) {
- this.log = $(log);
- if (this.log) {
- this._createLogTable();
- }
- },
- start: function(testName) {
- if (!this.log) return;
- this.testName = testName;
- this.lastLogLine = document.createElement('tr');
- this.statusCell = document.createElement('td');
- this.nameCell = document.createElement('td');
- this.nameCell.appendChild(document.createTextNode(testName));
- this.messageCell = document.createElement('td');
- this.lastLogLine.appendChild(this.statusCell);
- this.lastLogLine.appendChild(this.nameCell);
- this.lastLogLine.appendChild(this.messageCell);
- this.loglines.appendChild(this.lastLogLine);
- },
- finish: function(status, summary) {
- if (!this.log) return;
- this.lastLogLine.className = status;
- this.statusCell.innerHTML = status;
- this.messageCell.innerHTML = this._toHTML(summary);
- },
- message: function(message) {
- if (!this.log) return;
- this.messageCell.innerHTML = this._toHTML(message);
- },
- summary: function(summary) {
- if (!this.log) return;
- this.logsummary.innerHTML = this._toHTML(summary);
- },
- _createLogTable: function() {
- this.log.innerHTML =
- '<div id="logsummary"></div>' +
- '<table id="logtable">' +
- '<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' +
- '<tbody id="loglines"></tbody>' +
- '</table>';
- this.logsummary = $('logsummary')
- this.loglines = $('loglines');
- },
- _toHTML: function(txt) {
- return txt.escapeHTML().replace(/\n/g,"<br/>");
- }
-}
-
-Test.Unit.Runner = Class.create();
-Test.Unit.Runner.prototype = {
- initialize: function(testcases) {
- this.options = Object.extend({
- testLog: 'testlog'
- }, arguments[1] || {});
- this.options.resultsURL = this.parseResultsURLQueryParameter();
- if (this.options.testLog) {
- this.options.testLog = $(this.options.testLog) || null;
- }
- if(this.options.tests) {
- this.tests = [];
- for(var i = 0; i < this.options.tests.length; i++) {
- if(/^test/.test(this.options.tests[i])) {
- this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"]));
- }
- }
- } else {
- if (this.options.test) {
- this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])];
- } else {
- this.tests = [];
- for(var testcase in testcases) {
- if(/^test/.test(testcase)) {
- this.tests.push(
- new Test.Unit.Testcase(
- this.options.context ? ' -> ' + this.options.titles[testcase] : testcase,
- testcases[testcase], testcases["setup"], testcases["teardown"]
- ));
- }
- }
- }
- }
- this.currentTest = 0;
- this.logger = new Test.Unit.Logger(this.options.testLog);
- setTimeout(this.runTests.bind(this), 1000);
- },
- parseResultsURLQueryParameter: function() {
- return window.location.search.parseQuery()["resultsURL"];
- },
- // Returns:
- // "ERROR" if there was an error,
- // "FAILURE" if there was a failure, or
- // "SUCCESS" if there was neither
- getResult: function() {
- var hasFailure = false;
- for(var i=0;i<this.tests.length;i++) {
- if (this.tests[i].errors > 0) {
- return "ERROR";
- }
- if (this.tests[i].failures > 0) {
- hasFailure = true;
- }
- }
- if (hasFailure) {
- return "FAILURE";
- } else {
- return "SUCCESS";
- }
- },
- postResults: function() {
- if (this.options.resultsURL) {
- new Ajax.Request(this.options.resultsURL,
- { method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false });
- }
- },
- runTests: function() {
- var test = this.tests[this.currentTest];
- if (!test) {
- // finished!
- this.postResults();
- this.logger.summary(this.summary());
- return;
- }
- if(!test.isWaiting) {
- this.logger.start(test.name);
- }
- test.run();
- if(test.isWaiting) {
- this.logger.message("Waiting for " + test.timeToWait + "ms");
- setTimeout(this.runTests.bind(this), test.timeToWait || 1000);
- } else {
- this.logger.finish(test.status(), test.summary());
- this.currentTest++;
- // tail recursive, hopefully the browser will skip the stackframe
- this.runTests();
- }
- },
- summary: function() {
- var assertions = 0;
- var failures = 0;
- var errors = 0;
- var messages = [];
- for(var i=0;i<this.tests.length;i++) {
- assertions += this.tests[i].assertions;
- failures += this.tests[i].failures;
- errors += this.tests[i].errors;
- }
- return (
- (this.options.context ? this.options.context + ': ': '') +
- this.tests.length + " tests, " +
- assertions + " assertions, " +
- failures + " failures, " +
- errors + " errors");
- }
-}
-
-Test.Unit.Assertions = Class.create();
-Test.Unit.Assertions.prototype = {
- initialize: function() {
- this.assertions = 0;
- this.failures = 0;
- this.errors = 0;
- this.messages = [];
- },
- summary: function() {
- return (
- this.assertions + " assertions, " +
- this.failures + " failures, " +
- this.errors + " errors" + "\n" +
- this.messages.join("\n"));
- },
- pass: function() {
- this.assertions++;
- },
- fail: function(message) {
- this.failures++;
- this.messages.push("Failure: " + message);
- },
- info: function(message) {
- this.messages.push("Info: " + message);
- },
- error: function(error) {
- this.errors++;
- this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")");
- },
- status: function() {
- if (this.failures > 0) return 'failed';
- if (this.errors > 0) return 'error';
- return 'passed';
- },
- assert: function(expression) {
- var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"';
- try { expression ? this.pass() :
- this.fail(message); }
- catch(e) { this.error(e); }
- },
- assertEqual: function(expected, actual) {
- var message = arguments[2] || "assertEqual";
- try { (expected == actual) ? this.pass() :
- this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
- '", actual "' + Test.Unit.inspect(actual) + '"'); }
- catch(e) { this.error(e); }
- },
- assertEnumEqual: function(expected, actual) {
- var message = arguments[2] || "assertEnumEqual";
- try { $A(expected).length == $A(actual).length &&
- expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ?
- this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) +
- ', actual ' + Test.Unit.inspect(actual)); }
- catch(e) { this.error(e); }
- },
- assertNotEqual: function(expected, actual) {
- var message = arguments[2] || "assertNotEqual";
- try { (expected != actual) ? this.pass() :
- this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); }
- catch(e) { this.error(e); }
- },
- assertIdentical: function(expected, actual) {
- var message = arguments[2] || "assertIdentical";
- try { (expected === actual) ? this.pass() :
- this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
- '", actual "' + Test.Unit.inspect(actual) + '"'); }
- catch(e) { this.error(e); }
- },
- assertNotIdentical: function(expected, actual) {
- var message = arguments[2] || "assertNotIdentical";
- try { !(expected === actual) ? this.pass() :
- this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
- '", actual "' + Test.Unit.inspect(actual) + '"'); }
- catch(e) { this.error(e); }
- },
- assertNull: function(obj) {
- var message = arguments[1] || 'assertNull'
- try { (obj==null) ? this.pass() :
- this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); }
- catch(e) { this.error(e); }
- },
- assertMatch: function(expected, actual) {
- var message = arguments[2] || 'assertMatch';
- var regex = new RegExp(expected);
- try { (regex.exec(actual)) ? this.pass() :
- this.fail(message + ' : regex: "' + Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); }
- catch(e) { this.error(e); }
- },
- assertHidden: function(element) {
- var message = arguments[1] || 'assertHidden';
- this.assertEqual("none", element.style.display, message);
- },
- assertNotNull: function(object) {
- var message = arguments[1] || 'assertNotNull';
- this.assert(object != null, message);
- },
- assertType: function(expected, actual) {
- var message = arguments[2] || 'assertType';
- try {
- (actual.constructor == expected) ? this.pass() :
- this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
- '", actual "' + (actual.constructor) + '"'); }
- catch(e) { this.error(e); }
- },
- assertNotOfType: function(expected, actual) {
- var message = arguments[2] || 'assertNotOfType';
- try {
- (actual.constructor != expected) ? this.pass() :
- this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
- '", actual "' + (actual.constructor) + '"'); }
- catch(e) { this.error(e); }
- },
- assertInstanceOf: function(expected, actual) {
- var message = arguments[2] || 'assertInstanceOf';
- try {
- (actual instanceof expected) ? this.pass() :
- this.fail(message + ": object was not an instance of the expected type"); }
- catch(e) { this.error(e); }
- },
- assertNotInstanceOf: function(expected, actual) {
- var message = arguments[2] || 'assertNotInstanceOf';
- try {
- !(actual instanceof expected) ? this.pass() :
- this.fail(message + ": object was an instance of the not expected type"); }
- catch(e) { this.error(e); }
- },
- assertRespondsTo: function(method, obj) {
- var message = arguments[2] || 'assertRespondsTo';
- try {
- (obj[method] && typeof obj[method] == 'function') ? this.pass() :
- this.fail(message + ": object doesn't respond to [" + method + "]"); }
- catch(e) { this.error(e); }
- },
- assertReturnsTrue: function(method, obj) {
- var message = arguments[2] || 'assertReturnsTrue';
- try {
- var m = obj[method];
- if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
- m() ? this.pass() :
- this.fail(message + ": method returned false"); }
- catch(e) { this.error(e); }
- },
- assertReturnsFalse: function(method, obj) {
- var message = arguments[2] || 'assertReturnsFalse';
- try {
- var m = obj[method];
- if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
- !m() ? this.pass() :
- this.fail(message + ": method returned true"); }
- catch(e) { this.error(e); }
- },
- assertRaise: function(exceptionName, method) {
- var message = arguments[2] || 'assertRaise';
- try {
- method();
- this.fail(message + ": exception expected but none was raised"); }
- catch(e) {
- (e.name==exceptionName) ? this.pass() : this.error(e);
- }
- },
- assertElementsMatch: function() {
- var expressions = $A(arguments), elements = $A(expressions.shift());
- if (elements.length != expressions.length) {
- this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions');
- return false;
- }
- elements.zip(expressions).all(function(pair, index) {
- var element = $(pair.first()), expression = pair.last();
- if (element.match(expression)) return true;
- this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect());
- }.bind(this)) && this.pass();
- },
- assertElementMatches: function(element, expression) {
- this.assertElementsMatch([element], expression);
- },
- benchmark: function(operation, iterations) {
- var startAt = new Date();
- (iterations || 1).times(operation);
- var timeTaken = ((new Date())-startAt);
- this.info((arguments[2] || 'Operation') + ' finished ' +
- iterations + ' iterations in ' + (timeTaken/1000)+'s' );
- return timeTaken;
- },
- _isVisible: function(element) {
- element = $(element);
- if(!element.parentNode) return true;
- this.assertNotNull(element);
- if(element.style && Element.getStyle(element, 'display') == 'none')
- return false;
-
- return this._isVisible(element.parentNode);
- },
- assertNotVisible: function(element) {
- this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1]));
- },
- assertVisible: function(element) {
- this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1]));
- },
- benchmark: function(operation, iterations) {
- var startAt = new Date();
- (iterations || 1).times(operation);
- var timeTaken = ((new Date())-startAt);
- this.info((arguments[2] || 'Operation') + ' finished ' +
- iterations + ' iterations in ' + (timeTaken/1000)+'s' );
- return timeTaken;
- }
-}
-
-Test.Unit.Testcase = Class.create();
-Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), {
- initialize: function(name, test, setup, teardown) {
- Test.Unit.Assertions.prototype.initialize.bind(this)();
- this.name = name;
-
- if(typeof test == 'string') {
- test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,');
- test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)');
- this.test = function() {
- eval('with(this){'+test+'}');
- }
- } else {
- this.test = test || function() {};
- }
-
- this.setup = setup || function() {};
- this.teardown = teardown || function() {};
- this.isWaiting = false;
- this.timeToWait = 1000;
- },
- wait: function(time, nextPart) {
- this.isWaiting = true;
- this.test = nextPart;
- this.timeToWait = time;
- },
- run: function() {
- try {
- try {
- if (!this.isWaiting) this.setup.bind(this)();
- this.isWaiting = false;
- this.test.bind(this)();
- } finally {
- if(!this.isWaiting) {
- this.teardown.bind(this)();
- }
- }
- }
- catch(e) { this.error(e); }
- }
-});
-
-// *EXPERIMENTAL* BDD-style testing to please non-technical folk
-// This draws many ideas from RSpec http://rspec.rubyforge.org/
-
-Test.setupBDDExtensionMethods = function(){
- var METHODMAP = {
- shouldEqual: 'assertEqual',
- shouldNotEqual: 'assertNotEqual',
- shouldEqualEnum: 'assertEnumEqual',
- shouldBeA: 'assertType',
- shouldNotBeA: 'assertNotOfType',
- shouldBeAn: 'assertType',
- shouldNotBeAn: 'assertNotOfType',
- shouldBeNull: 'assertNull',
- shouldNotBeNull: 'assertNotNull',
-
- shouldBe: 'assertReturnsTrue',
- shouldNotBe: 'assertReturnsFalse',
- shouldRespondTo: 'assertRespondsTo'
- };
- Test.BDDMethods = {};
- for(m in METHODMAP) {
- Test.BDDMethods[m] = eval(
- 'function(){'+
- 'var args = $A(arguments);'+
- 'var scope = args.shift();'+
- 'scope.'+METHODMAP[m]+'.apply(scope,(args || []).concat([this])); }');
- }
- [Array.prototype, String.prototype, Number.prototype].each(
- function(p){ Object.extend(p, Test.BDDMethods) }
- );
-}
-
-Test.context = function(name, spec, log){
- Test.setupBDDExtensionMethods();
-
- var compiledSpec = {};
- var titles = {};
- for(specName in spec) {
- switch(specName){
- case "setup":
- case "teardown":
- compiledSpec[specName] = spec[specName];
- break;
- default:
- var testName = 'test'+specName.gsub(/\s+/,'-').camelize();
- var body = spec[specName].toString().split('\n').slice(1);
- if(/^\{/.test(body[0])) body = body.slice(1);
- body.pop();
- body = body.map(function(statement){
- return statement.strip()
- });
- compiledSpec[testName] = body.join('\n');
- titles[testName] = specName;
- }
- }
- new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name });
+// script.aculo.us unittest.js v1.7.0, Fri Jan 19 19:16:36 CET 2007
+
+// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005, 2006 Jon Tirsen (http://www.tirsen.com)
+// (c) 2005, 2006 Michael Schuerig (http://www.schuerig.de/michael/)
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+// experimental, Firefox-only
+Event.simulateMouse = function(element, eventName) {
+ var options = Object.extend({
+ pointerX: 0,
+ pointerY: 0,
+ buttons: 0,
+ ctrlKey: false,
+ altKey: false,
+ shiftKey: false,
+ metaKey: false
+ }, arguments[2] || {});
+ var oEvent = document.createEvent("MouseEvents");
+ oEvent.initMouseEvent(eventName, true, true, document.defaultView,
+ options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
+ options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $(element));
+
+ if(this.mark) Element.remove(this.mark);
+ this.mark = document.createElement('div');
+ this.mark.appendChild(document.createTextNode(" "));
+ document.body.appendChild(this.mark);
+ this.mark.style.position = 'absolute';
+ this.mark.style.top = options.pointerY + "px";
+ this.mark.style.left = options.pointerX + "px";
+ this.mark.style.width = "5px";
+ this.mark.style.height = "5px;";
+ this.mark.style.borderTop = "1px solid red;"
+ this.mark.style.borderLeft = "1px solid red;"
+
+ if(this.step)
+ alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options));
+
+ $(element).dispatchEvent(oEvent);
+};
+
+// Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2.
+// You need to downgrade to 1.0.4 for now to get this working
+// See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much
+Event.simulateKey = function(element, eventName) {
+ var options = Object.extend({
+ ctrlKey: false,
+ altKey: false,
+ shiftKey: false,
+ metaKey: false,
+ keyCode: 0,
+ charCode: 0
+ }, arguments[2] || {});
+
+ var oEvent = document.createEvent("KeyEvents");
+ oEvent.initKeyEvent(eventName, true, true, window,
+ options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
+ options.keyCode, options.charCode );
+ $(element).dispatchEvent(oEvent);
+};
+
+Event.simulateKeys = function(element, command) {
+ for(var i=0; i<command.length; i++) {
+ Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)});
+ }
+};
+
+var Test = {}
+Test.Unit = {};
+
+// security exception workaround
+Test.Unit.inspect = Object.inspect;
+
+Test.Unit.Logger = Class.create();
+Test.Unit.Logger.prototype = {
+ initialize: function(log) {
+ this.log = $(log);
+ if (this.log) {
+ this._createLogTable();
+ }
+ },
+ start: function(testName) {
+ if (!this.log) return;
+ this.testName = testName;
+ this.lastLogLine = document.createElement('tr');
+ this.statusCell = document.createElement('td');
+ this.nameCell = document.createElement('td');
+ this.nameCell.className = "nameCell";
+ this.nameCell.appendChild(document.createTextNode(testName));
+ this.messageCell = document.createElement('td');
+ this.lastLogLine.appendChild(this.statusCell);
+ this.lastLogLine.appendChild(this.nameCell);
+ this.lastLogLine.appendChild(this.messageCell);
+ this.loglines.appendChild(this.lastLogLine);
+ },
+ finish: function(status, summary) {
+ if (!this.log) return;
+ this.lastLogLine.className = status;
+ this.statusCell.innerHTML = status;
+ this.messageCell.innerHTML = this._toHTML(summary);
+ this.addLinksToResults();
+ },
+ message: function(message) {
+ if (!this.log) return;
+ this.messageCell.innerHTML = this._toHTML(message);
+ },
+ summary: function(summary) {
+ if (!this.log) return;
+ this.logsummary.innerHTML = this._toHTML(summary);
+ },
+ _createLogTable: function() {
+ this.log.innerHTML =
+ '<div id="logsummary"></div>' +
+ '<table id="logtable">' +
+ '<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' +
+ '<tbody id="loglines"></tbody>' +
+ '</table>';
+ this.logsummary = $('logsummary')
+ this.loglines = $('loglines');
+ },
+ _toHTML: function(txt) {
+ return txt.escapeHTML().replace(/\n/g,"<br/>");
+ },
+ addLinksToResults: function(){
+ $$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log
+ td.title = "Run only this test"
+ Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;});
+ });
+ $$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log
+ td.title = "Run all tests"
+ Event.observe(td, 'click', function(){ window.location.search = "";});
+ });
+ }
+}
+
+Test.Unit.Runner = Class.create();
+Test.Unit.Runner.prototype = {
+ initialize: function(testcases) {
+ this.options = Object.extend({
+ testLog: 'testlog'
+ }, arguments[1] || {});
+ this.options.resultsURL = this.parseResultsURLQueryParameter();
+ this.options.tests = this.parseTestsQueryParameter();
+ if (this.options.testLog) {
+ this.options.testLog = $(this.options.testLog) || null;
+ }
+ if(this.options.tests) {
+ this.tests = [];
+ for(var i = 0; i < this.options.tests.length; i++) {
+ if(/^test/.test(this.options.tests[i])) {
+ this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"]));
+ }
+ }
+ } else {
+ if (this.options.test) {
+ this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])];
+ } else {
+ this.tests = [];
+ for(var testcase in testcases) {
+ if(/^test/.test(testcase)) {
+ this.tests.push(
+ new Test.Unit.Testcase(
+ this.options.context ? ' -> ' + this.options.titles[testcase] : testcase,
+ testcases[testcase], testcases["setup"], testcases["teardown"]
+ ));
+ }
+ }
+ }
+ }
+ this.currentTest = 0;
+ this.logger = new Test.Unit.Logger(this.options.testLog);
+ setTimeout(this.runTests.bind(this), 1000);
+ },
+ parseResultsURLQueryParameter: function() {
+ return window.location.search.parseQuery()["resultsURL"];
+ },
+ parseTestsQueryParameter: function(){
+ if (window.location.search.parseQuery()["tests"]){
+ return window.location.search.parseQuery()["tests"].split(',');
+ };
+ },
+ // Returns:
+ // "ERROR" if there was an error,
+ // "FAILURE" if there was a failure, or
+ // "SUCCESS" if there was neither
+ getResult: function() {
+ var hasFailure = false;
+ for(var i=0;i<this.tests.length;i++) {
+ if (this.tests[i].errors > 0) {
+ return "ERROR";
+ }
+ if (this.tests[i].failures > 0) {
+ hasFailure = true;
+ }
+ }
+ if (hasFailure) {
+ return "FAILURE";
+ } else {
+ return "SUCCESS";
+ }
+ },
+ postResults: function() {
+ if (this.options.resultsURL) {
+ new Ajax.Request(this.options.resultsURL,
+ { method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false });
+ }
+ },
+ runTests: function() {
+ var test = this.tests[this.currentTest];
+ if (!test) {
+ // finished!
+ this.postResults();
+ this.logger.summary(this.summary());
+ return;
+ }
+ if(!test.isWaiting) {
+ this.logger.start(test.name);
+ }
+ test.run();
+ if(test.isWaiting) {
+ this.logger.message("Waiting for " + test.timeToWait + "ms");
+ setTimeout(this.runTests.bind(this), test.timeToWait || 1000);
+ } else {
+ this.logger.finish(test.status(), test.summary());
+ this.currentTest++;
+ // tail recursive, hopefully the browser will skip the stackframe
+ this.runTests();
+ }
+ },
+ summary: function() {
+ var assertions = 0;
+ var failures = 0;
+ var errors = 0;
+ var messages = [];
+ for(var i=0;i<this.tests.length;i++) {
+ assertions += this.tests[i].assertions;
+ failures += this.tests[i].failures;
+ errors += this.tests[i].errors;
+ }
+ return (
+ (this.options.context ? this.options.context + ': ': '') +
+ this.tests.length + " tests, " +
+ assertions + " assertions, " +
+ failures + " failures, " +
+ errors + " errors");
+ }
+}
+
+Test.Unit.Assertions = Class.create();
+Test.Unit.Assertions.prototype = {
+ initialize: function() {
+ this.assertions = 0;
+ this.failures = 0;
+ this.errors = 0;
+ this.messages = [];
+ },
+ summary: function() {
+ return (
+ this.assertions + " assertions, " +
+ this.failures + " failures, " +
+ this.errors + " errors" + "\n" +
+ this.messages.join("\n"));
+ },
+ pass: function() {
+ this.assertions++;
+ },
+ fail: function(message) {
+ this.failures++;
+ this.messages.push("Failure: " + message);
+ },
+ info: function(message) {
+ this.messages.push("Info: " + message);
+ },
+ error: function(error) {
+ this.errors++;
+ this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")");
+ },
+ status: function() {
+ if (this.failures > 0) return 'failed';
+ if (this.errors > 0) return 'error';
+ return 'passed';
+ },
+ assert: function(expression) {
+ var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"';
+ try { expression ? this.pass() :
+ this.fail(message); }
+ catch(e) { this.error(e); }
+ },
+ assertEqual: function(expected, actual) {
+ var message = arguments[2] || "assertEqual";
+ try { (expected == actual) ? this.pass() :
+ this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
+ '", actual "' + Test.Unit.inspect(actual) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertInspect: function(expected, actual) {
+ var message = arguments[2] || "assertInspect";
+ try { (expected == actual.inspect()) ? this.pass() :
+ this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
+ '", actual "' + Test.Unit.inspect(actual) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertEnumEqual: function(expected, actual) {
+ var message = arguments[2] || "assertEnumEqual";
+ try { $A(expected).length == $A(actual).length &&
+ expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ?
+ this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) +
+ ', actual ' + Test.Unit.inspect(actual)); }
+ catch(e) { this.error(e); }
+ },
+ assertNotEqual: function(expected, actual) {
+ var message = arguments[2] || "assertNotEqual";
+ try { (expected != actual) ? this.pass() :
+ this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertIdentical: function(expected, actual) {
+ var message = arguments[2] || "assertIdentical";
+ try { (expected === actual) ? this.pass() :
+ this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
+ '", actual "' + Test.Unit.inspect(actual) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertNotIdentical: function(expected, actual) {
+ var message = arguments[2] || "assertNotIdentical";
+ try { !(expected === actual) ? this.pass() :
+ this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
+ '", actual "' + Test.Unit.inspect(actual) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertNull: function(obj) {
+ var message = arguments[1] || 'assertNull'
+ try { (obj==null) ? this.pass() :
+ this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertMatch: function(expected, actual) {
+ var message = arguments[2] || 'assertMatch';
+ var regex = new RegExp(expected);
+ try { (regex.exec(actual)) ? this.pass() :
+ this.fail(message + ' : regex: "' + Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertHidden: function(element) {
+ var message = arguments[1] || 'assertHidden';
+ this.assertEqual("none", element.style.display, message);
+ },
+ assertNotNull: function(object) {
+ var message = arguments[1] || 'assertNotNull';
+ this.assert(object != null, message);
+ },
+ assertType: function(expected, actual) {
+ var message = arguments[2] || 'assertType';
+ try {
+ (actual.constructor == expected) ? this.pass() :
+ this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
+ '", actual "' + (actual.constructor) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertNotOfType: function(expected, actual) {
+ var message = arguments[2] || 'assertNotOfType';
+ try {
+ (actual.constructor != expected) ? this.pass() :
+ this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
+ '", actual "' + (actual.constructor) + '"'); }
+ catch(e) { this.error(e); }
+ },
+ assertInstanceOf: function(expected, actual) {
+ var message = arguments[2] || 'assertInstanceOf';
+ try {
+ (actual instanceof expected) ? this.pass() :
+ this.fail(message + ": object was not an instance of the expected type"); }
+ catch(e) { this.error(e); }
+ },
+ assertNotInstanceOf: function(expected, actual) {
+ var message = arguments[2] || 'assertNotInstanceOf';
+ try {
+ !(actual instanceof expected) ? this.pass() :
+ this.fail(message + ": object was an instance of the not expected type"); }
+ catch(e) { this.error(e); }
+ },
+ assertRespondsTo: function(method, obj) {
+ var message = arguments[2] || 'assertRespondsTo';
+ try {
+ (obj[method] && typeof obj[method] == 'function') ? this.pass() :
+ this.fail(message + ": object doesn't respond to [" + method + "]"); }
+ catch(e) { this.error(e); }
+ },
+ assertReturnsTrue: function(method, obj) {
+ var message = arguments[2] || 'assertReturnsTrue';
+ try {
+ var m = obj[method];
+ if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
+ m() ? this.pass() :
+ this.fail(message + ": method returned false"); }
+ catch(e) { this.error(e); }
+ },
+ assertReturnsFalse: function(method, obj) {
+ var message = arguments[2] || 'assertReturnsFalse';
+ try {
+ var m = obj[method];
+ if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
+ !m() ? this.pass() :
+ this.fail(message + ": method returned true"); }
+ catch(e) { this.error(e); }
+ },
+ assertRaise: function(exceptionName, method) {
+ var message = arguments[2] || 'assertRaise';
+ try {
+ method();
+ this.fail(message + ": exception expected but none was raised"); }
+ catch(e) {
+ ((exceptionName == null) || (e.name==exceptionName)) ? this.pass() : this.error(e);
+ }
+ },
+ assertElementsMatch: function() {
+ var expressions = $A(arguments), elements = $A(expressions.shift());
+ if (elements.length != expressions.length) {
+ this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions');
+ return false;
+ }
+ elements.zip(expressions).all(function(pair, index) {
+ var element = $(pair.first()), expression = pair.last();
+ if (element.match(expression)) return true;
+ this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect());
+ }.bind(this)) && this.pass();
+ },
+ assertElementMatches: function(element, expression) {
+ this.assertElementsMatch([element], expression);
+ },
+ benchmark: function(operation, iterations) {
+ var startAt = new Date();
+ (iterations || 1).times(operation);
+ var timeTaken = ((new Date())-startAt);
+ this.info((arguments[2] || 'Operation') + ' finished ' +
+ iterations + ' iterations in ' + (timeTaken/1000)+'s' );
+ return timeTaken;
+ },
+ _isVisible: function(element) {
+ element = $(element);
+ if(!element.parentNode) return true;
+ this.assertNotNull(element);
+ if(element.style && Element.getStyle(element, 'display') == 'none')
+ return false;
+
+ return this._isVisible(element.parentNode);
+ },
+ assertNotVisible: function(element) {
+ this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1]));
+ },
+ assertVisible: function(element) {
+ this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1]));
+ },
+ benchmark: function(operation, iterations) {
+ var startAt = new Date();
+ (iterations || 1).times(operation);
+ var timeTaken = ((new Date())-startAt);
+ this.info((arguments[2] || 'Operation') + ' finished ' +
+ iterations + ' iterations in ' + (timeTaken/1000)+'s' );
+ return timeTaken;
+ }
+}
+
+Test.Unit.Testcase = Class.create();
+Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), {
+ initialize: function(name, test, setup, teardown) {
+ Test.Unit.Assertions.prototype.initialize.bind(this)();
+ this.name = name;
+
+ if(typeof test == 'string') {
+ test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,');
+ test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)');
+ this.test = function() {
+ eval('with(this){'+test+'}');
+ }
+ } else {
+ this.test = test || function() {};
+ }
+
+ this.setup = setup || function() {};
+ this.teardown = teardown || function() {};
+ this.isWaiting = false;
+ this.timeToWait = 1000;
+ },
+ wait: function(time, nextPart) {
+ this.isWaiting = true;
+ this.test = nextPart;
+ this.timeToWait = time;
+ },
+ run: function() {
+ try {
+ try {
+ if (!this.isWaiting) this.setup.bind(this)();
+ this.isWaiting = false;
+ this.test.bind(this)();
+ } finally {
+ if(!this.isWaiting) {
+ this.teardown.bind(this)();
+ }
+ }
+ }
+ catch(e) { this.error(e); }
+ }
+});
+
+// *EXPERIMENTAL* BDD-style testing to please non-technical folk
+// This draws many ideas from RSpec http://rspec.rubyforge.org/
+
+Test.setupBDDExtensionMethods = function(){
+ var METHODMAP = {
+ shouldEqual: 'assertEqual',
+ shouldNotEqual: 'assertNotEqual',
+ shouldEqualEnum: 'assertEnumEqual',
+ shouldBeA: 'assertType',
+ shouldNotBeA: 'assertNotOfType',
+ shouldBeAn: 'assertType',
+ shouldNotBeAn: 'assertNotOfType',
+ shouldBeNull: 'assertNull',
+ shouldNotBeNull: 'assertNotNull',
+
+ shouldBe: 'assertReturnsTrue',
+ shouldNotBe: 'assertReturnsFalse',
+ shouldRespondTo: 'assertRespondsTo'
+ };
+ Test.BDDMethods = {};
+ for(m in METHODMAP) {
+ Test.BDDMethods[m] = eval(
+ 'function(){'+
+ 'var args = $A(arguments);'+
+ 'var scope = args.shift();'+
+ 'scope.'+METHODMAP[m]+'.apply(scope,(args || []).concat([this])); }');
+ }
+ [Array.prototype, String.prototype, Number.prototype].each(
+ function(p){ Object.extend(p, Test.BDDMethods) }
+ );
+}
+
+Test.context = function(name, spec, log){
+ Test.setupBDDExtensionMethods();
+
+ var compiledSpec = {};
+ var titles = {};
+ for(specName in spec) {
+ switch(specName){
+ case "setup":
+ case "teardown":
+ compiledSpec[specName] = spec[specName];
+ break;
+ default:
+ var testName = 'test'+specName.gsub(/\s+/,'-').camelize();
+ var body = spec[specName].toString().split('\n').slice(1);
+ if(/^\{/.test(body[0])) body = body.slice(1);
+ body.pop();
+ body = body.map(function(statement){
+ return statement.strip()
+ });
+ compiledSpec[testName] = body.join('\n');
+ titles[testName] = specName;
+ }
+ }
+ new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name });
};
\ No newline at end of file
Modified: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaRegionRenderer.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaRegionRenderer.java 2007-03-31 14:21:37 UTC (rev 6895)
+++ trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaRegionRenderer.java 2007-03-31 14:25:31 UTC (rev 6896)
@@ -61,14 +61,10 @@
public class DynaRegionRenderer implements RegionRenderer
{
- /**
- * .
- */
+ /** . */
private static final ThreadLocal enabledLocal = new ThreadLocal();
- /**
- * .
- */
+ /** . */
private RegionRenderer delegate;
public static boolean isEnabled()
@@ -107,147 +103,16 @@
markup.append("<script type='text/javascript' src='").append(jsBase).append("/js/portal/scriptaculous.js'></script>\n");
markup.append("<script type='text/javascript' src='").append(jsBase).append("/js/portal/effects.js'></script>\n");
markup.append("<script type='text/javascript' src='").append(jsBase).append("/js/portal/dragdrop.js'></script>\n");
+ markup.append("<script type='text/javascript' src='").append(jsBase).append("/js/portal/dyna.js'></script>\n");
markup.append("<script type='text/javascript'>\n");
markup.append("async_server_url=\"").append(asyncServerURL).append(";\"\n");
markup.append("classic_server_url=\"").append(classicServerURL).append("\";\n");
-
- String sendData = "" +
- "function sendData(action, windowId, fromPos, fromRegionId, toPos, toRegionId) {\n" +
- " var options = {\n" +
- " method: 'post',\n" +
- " postBody: 'action=' + action + '&windowId=' + windowId + '&fromPos=' + fromPos + '&fromRegion=' + fromRegionId + '&toPos=' + toPos + '&toRegion=' + toRegionId,\n" +
- " onSuccess: function(t)\n" +
- " {\n" +
- " },\n" +
- " onSuccess: function(t)\n" +
- " {\n" +
- " },\n" +
- " on404: function(t)\n" +
- " {\n" +
- " alert('Error 404: location \"' + t.statusText + '\" was not found.');\n" +
- " },\n" +
- " onFailure: function(t)\n" +
- " {\n" +
- " alert('Error ' + t.status + ' -- ' + t.statusText);\n" +
- " },\n" +
- " onLoading: function(t)\n" +
- " {\n" +
- " }\n" +
- " }\n" +
- " new Ajax.Request(async_server_url, options);\n" +
- "}";
- markup.append(sendData);
-
- //
- String t = "" +
- "function snapshot() {\n" +
-
- // Find draggable regions
- " var regions_on_page = document.getElementsByClassName(\"dyna-region\");\n" +
-
- // Save current state in the DOM itself
- " for(var i = 0;i < regions_on_page.length;i++) {\n" +
- " var regionDiv = regions_on_page[i]\n" +
- " for (var j = 0;j < regionDiv.childNodes.length;j++) {\n" +
- " var child = regionDiv.childNodes[j];\n" +
- " child['regionId'] = regionDiv.id;\n" +
- " child['pos'] = j;\n" +
- " }\n" +
- " }\n" +
- "}\n";
-
- markup.append(t);
-
- String s = "" +
- "var WindowMoveObserver = Class.create();\n" +
- "WindowMoveObserver.prototype =\n" +
- "{\n" +
- " initialize: function(element)\n" +
- " {\n" +
- " this.element = $(element);\n" +
- " },\n" +
- " onStart: function()\n" +
- " {\n" +
- " },\n" +
- " onEnd: function()\n" +
- " {\n" +
- " var elt = Draggables.activeDraggable.element;\n" +
- " var fromRegionId = elt['regionId'];\n" +
- " var fromPos = elt['pos'];\n" +
- " snapshot();\n" +
- " var toRegionId = elt['regionId'];\n" +
- " var toPos = elt['pos'];\n" +
- " sendData('windowmove', elt.id, fromPos, fromRegionId, toPos, toRegionId);\n" +
- " }\n" +
- "};\n";
- markup.append(s);
-
- String u = "" +
- "function removeWindow(elementId)\n" +
- "{\n" +
- " var effectElement = document.getElementById(elementId)\n" +
- " new Effect.BlindUp(effectElement);\n" +
- "\n" +
- " //removeElement(effectElement);\n" +
- "\n" +
- " sendData('windowremove', elementId);\n" +
- "}\n";
- markup.append(u);
-
- String v = "" +
- "function bilto(event)\n" +
- "{\n" +
-// " var source = Event.element(event);\n" +
-// " if (source.nodeName == \"A\") {;\n" +
-// " var url = source.href;\n" +
-// " var parameters = \"\";\n" +
-// " var pos = url.indexOf(\"?\");\n" +
-// " if (pos != -1) {\n" +
-// " parameters = url.substring(pos + 1);\n" +
-// " url = url.substring(0, pos);\n" +
-// " }\n" +
-// " Event.stop(event);\n" +
-// " var options = {\n" +
-// " parameters:parameters,\n" +
-// " asynchronous:true,\n" +
-// " method:\"get\",\n" +
-// " requestHeaders:[\"ajax\",\"true\"],\n" +
-// " };" +
-// " new Ajax.Request(url, options);\n" +
-// " }\n" +
- "}\n";
- markup.append(v);
-
markup.append("</script>\n");
markup.append("\n\n\n");
}
else if ("AJAXFooter".equals(rrc.getId()))
{
- markup.append("<script>\n" +
-
- // Find the draggable regions
- "var regions_on_page = document.getElementsByClassName(\"dyna-region\");\n" +
-
- // Create draggable regions
- "for(var i = 0;i < regions_on_page.length;i++) {\n" +
- " var region = regions_on_page[i];\n" +
- " Sortable.create(region, {dropOnEmpty:true,handle:'handle',tag:'div',containment:regions_on_page,constraint:false});\n" +
- "}\n" +
-
- //
- "Draggables.addObserver(new WindowMoveObserver());\n" +
- "snapshot();\n" +
-
- // Find the dyna portlets
- "var portlets_on_page = document.getElementsByClassName(\"dyna-portlet\");\n" +
-
- // Add listener for teh dyna portlets
- "for(var i = 0;i < portlets_on_page.length;i++) {\n" +
- " var portlet = portlets_on_page[i];\n" +
- " Event.observe(portlet, 'click', bilto);\n" +
- "}\n" +
-
- "</script>\n");
+ markup.append("<script type='text/javascript'>footer()</script>\n");
}
else
{
17 years, 7 months
JBoss Portal SVN: r6895 - trunk/core/src/resources/portal-server-war/WEB-INF.
by portal-commits@lists.jboss.org
Author: julien(a)jboss.com
Date: 2007-03-31 10:21:37 -0400 (Sat, 31 Mar 2007)
New Revision: 6895
Modified:
trunk/core/src/resources/portal-server-war/WEB-INF/web.xml
Log:
forgot to update controllerName -> controllerFactoryName in ajax servlet of portal-server.war
Modified: trunk/core/src/resources/portal-server-war/WEB-INF/web.xml
===================================================================
--- trunk/core/src/resources/portal-server-war/WEB-INF/web.xml 2007-03-31 12:57:50 UTC (rev 6894)
+++ trunk/core/src/resources/portal-server-war/WEB-INF/web.xml 2007-03-31 14:21:37 UTC (rev 6895)
@@ -235,9 +235,9 @@
<description>The servlet needs to know wether it is set as a default servlet or not</description>
</init-param>
<init-param>
- <param-name>controllerName</param-name>
- <param-value>portal:controller=Ajax</param-value>
- <description>The request controller for the portal servlet</description>
+ <param-name>controllerFactoryName</param-name>
+ <param-value>portal:service=ControllerFactory</param-value>
+ <description>The request controller factory for the portal servlet</description>
</init-param>
<load-on-startup>0</load-on-startup>
<security-role-ref>
17 years, 7 months
JBoss Portal SVN: r6894 - trunk/core/src/main/org/jboss/portal/core/controller.
by portal-commits@lists.jboss.org
Author: julien(a)jboss.com
Date: 2007-03-31 08:57:50 -0400 (Sat, 31 Mar 2007)
New Revision: 6894
Added:
trunk/core/src/main/org/jboss/portal/core/controller/ControllerFactory.java
Log:
- added in server RequestControllerFactory so the request controller used by the portal servlet can decided at runtime based on the server request
Added: trunk/core/src/main/org/jboss/portal/core/controller/ControllerFactory.java
===================================================================
--- trunk/core/src/main/org/jboss/portal/core/controller/ControllerFactory.java (rev 0)
+++ trunk/core/src/main/org/jboss/portal/core/controller/ControllerFactory.java 2007-03-31 12:57:50 UTC (rev 6894)
@@ -0,0 +1,94 @@
+/******************************************************************************
+ * JBoss, a division of Red Hat *
+ * Copyright 2006, Red Hat Middleware, LLC, and individual *
+ * contributors as indicated by the @authors tag. See the *
+ * copyright.txt in the distribution for a full listing of *
+ * individual contributors. *
+ * *
+ * This is free software; you can redistribute it and/or modify it *
+ * under the terms of the GNU Lesser General Public License as *
+ * published by the Free Software Foundation; either version 2.1 of *
+ * the License, or (at your option) any later version. *
+ * *
+ * This software is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
+ * Lesser General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU Lesser General Public *
+ * License along with this software; if not, write to the Free *
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org. *
+ ******************************************************************************/
+package org.jboss.portal.core.controller;
+
+import org.jboss.portal.server.RequestControllerFactory;
+import org.jboss.portal.server.RequestController;
+import org.jboss.portal.server.ServerInvocation;
+
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ * @author <a href="mailto:julien@jboss.org">Julien Viet</a>
+ * @version $Revision: 1.1 $
+ */
+public class ControllerFactory implements RequestControllerFactory
+{
+
+ /** . */
+ private RequestController classicController;
+
+ /** . */
+ private RequestController ajaxController;
+
+ public RequestController getClassicController()
+ {
+ return classicController;
+ }
+
+ public void setClassicController(RequestController classicController)
+ {
+ this.classicController = classicController;
+ }
+
+
+ public RequestController getAjaxController()
+ {
+ return ajaxController;
+ }
+
+ public void setAjaxController(RequestController ajaxController)
+ {
+ this.ajaxController = ajaxController;
+ }
+
+ public RequestController createRequestController(ServerInvocation invocation)
+ {
+
+ HttpServletRequest req = invocation.getServerContext().getClientRequest();
+ String value = req.getHeader("ajax");
+ if ("true".equalsIgnoreCase(value))
+ {
+ return ajaxController;
+ }
+ else
+ {
+ return classicController;
+ }
+
+
+// 02:03:58,636 INFO [STDOUT] host = localhost:8080
+// 02:03:58,636 INFO [STDOUT] user-agent = Mozilla/5.0 (Macintosh; U; Intel Mac OS X; fr; rv:1.8.1) Gecko/20061010 Firefox/2.0
+// 02:03:58,636 INFO [STDOUT] accept = text/javascript, text/html, application/xml, text/xml, */*
+// 02:03:58,636 INFO [STDOUT] accept-language = fr,en-us;q=0.5
+// 02:03:58,637 INFO [STDOUT] accept-encoding = gzip,deflate
+// 02:03:58,637 INFO [STDOUT] accept-charset = ISO-8859-1,utf-8;q=0.7,*;q=0.7
+// 02:03:58,637 INFO [STDOUT] keep-alive = 300
+// 02:03:58,637 INFO [STDOUT] connection = keep-alive
+// 02:03:58,637 INFO [STDOUT] x-requested-with = XMLHttpRequest
+// 02:03:58,638 INFO [STDOUT] x-prototype-version = 1.5.0_rc1
+// 02:03:58,638 INFO [STDOUT] ajax = true
+// 02:03:58,639 INFO [STDOUT] referer = http://localhost:8080/portal/auth/portal/dashboard/admin/default/
+// 02:03:58,639 INFO [STDOUT] cookie = JSESSIONID=A0B8EA1EEEAE6D977C0A8074D338B0EB
+ }
+}
17 years, 7 months
JBoss Portal SVN: r6893 - in trunk: core/src/main/org/jboss/portal/core/controller/ajax and 21 other directories.
by portal-commits@lists.jboss.org
Author: julien(a)jboss.com
Date: 2007-03-31 08:56:57 -0400 (Sat, 31 Mar 2007)
New Revision: 6893
Added:
trunk/server/src/main/org/jboss/portal/server/RequestControllerFactory.java
trunk/server/src/main/org/jboss/portal/server/impl/RequestControllerFactoryImpl.java
Modified:
trunk/core/src/main/org/jboss/portal/core/controller/Controller.java
trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxController.java
trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxInterceptor.java
trunk/core/src/main/org/jboss/portal/core/controller/classic/ClassicController.java
trunk/core/src/resources/portal-core-sar/META-INF/jboss-service.xml
trunk/core/src/resources/portal-server-war/WEB-INF/web.xml
trunk/portlet-server/src/resources/test-sar/META-INF/jboss-service.xml
trunk/portlet-server/src/resources/test-war/WEB-INF/web.xml
trunk/portlet-server/src/resources/test/info/test-info-sar/META-INF/jboss-service.xml
trunk/server/src/main/org/jboss/portal/server/servlet/PortalServlet.java
trunk/server/src/resources/test-agent-war/WEB-INF/web.xml
trunk/server/src/resources/test/test-charset-sar/META-INF/jboss-service.xml
trunk/server/src/resources/test/test-parameters-sar/META-INF/jboss-service.xml
trunk/server/src/resources/test/test-response-sar/META-INF/jboss-service.xml
trunk/server/src/resources/test/test-servlet-defaultservletmapping-war/WEB-INF/web.xml
trunk/server/src/resources/test/test-servlet-pathmapping-war/WEB-INF/web.xml
trunk/server/src/resources/test/test-servlet-rootpathmapping-war/WEB-INF/web.xml
trunk/server/src/resources/test/test-servlet-sar/META-INF/jboss-service.xml
trunk/theme/src/main/org/jboss/portal/test/theme/render/TestRenderedMarkup.java
trunk/theme/src/main/org/jboss/portal/test/theme/servlet/TestThemeServlet.java
trunk/theme/src/main/org/jboss/portal/theme/ThemeConstants.java
trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaRegionRenderer.java
Log:
- added in server RequestControllerFactory so the request controller used by the portal servlet can decided at runtime based on the server request
Modified: trunk/core/src/main/org/jboss/portal/core/controller/Controller.java
===================================================================
--- trunk/core/src/main/org/jboss/portal/core/controller/Controller.java 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/core/src/main/org/jboss/portal/core/controller/Controller.java 2007-03-31 12:56:57 UTC (rev 6893)
@@ -25,6 +25,12 @@
import org.jboss.portal.theme.page.PageService;
import org.jboss.portal.core.controller.command.mapper.CommandFactory;
import org.jboss.portal.core.controller.command.mapper.URLFactory;
+import org.jboss.portal.core.controller.command.info.CommandInfo;
+import org.jboss.portal.core.controller.command.info.ActionCommandInfo;
+import org.jboss.portal.core.controller.classic.HandlerResponse;
+import org.jboss.portal.core.controller.classic.CommandForward;
+import org.jboss.portal.core.controller.classic.HTTPResponse;
+import org.jboss.portal.core.controller.classic.ResponseHandler;
import org.jboss.portal.core.model.portal.PortalObjectContainer;
import org.jboss.portal.core.model.portal.content.ContentRendererRegistry;
import org.jboss.portal.core.model.instance.InstanceContainer;
@@ -33,12 +39,19 @@
import org.jboss.portal.security.spi.auth.PortalAuthorizationManagerFactory;
import org.jboss.portal.jems.as.system.AbstractJBossService;
import org.jboss.portal.server.RequestController;
+import org.jboss.portal.server.ServerException;
+import org.jboss.portal.server.ServerURL;
+import org.jboss.portal.server.request.URLContext;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
/**
* @author <a href="mailto:julien@jboss.org">Julien Viet</a>
* @version $Revision: 1.1 $
*/
-public abstract class Controller extends AbstractJBossService implements RequestController
+public abstract class Controller extends AbstractJBossService implements RequestController, ResponseHandler
{
/** . */
@@ -158,4 +171,156 @@
this.stackFactory = stackFactory;
}
+ /**
+ * Handle a command which means it executes the command and reacts upon the response created by the command.
+ *
+ * @param ctx the controller context
+ * @param cmd the command
+ * @throws org.jboss.portal.server.ServerException
+ */
+ protected void handleCommand(final ControllerContext ctx, final ControllerCommand cmd) throws ServerException
+ {
+ HandlerResponse handlerResp = executeCommand(ctx, cmd);
+
+ //
+ if (handlerResp == null)
+ {
+ return;
+ }
+
+ // Find out if we can execute in the same server invocation
+ if (handlerResp instanceof CommandForward)
+ {
+ CommandForward forward = (CommandForward)handlerResp;
+ URLContext urlContext = ctx.getServerInvocation().getServerContext().getURLContext();
+ if (requiresRedirect(cmd, urlContext, forward))
+ {
+ String url = ctx.renderURL(forward.getCommand(), forward.getURLContext(), null);
+ sendResponse(ctx, new HTTPResponse.SendRedirect(url));
+ }
+ else
+ {
+ handleCommand(ctx, forward.getCommand());
+ }
+ }
+ else
+ {
+ HTTPResponse hr = (HTTPResponse)handlerResp;
+ sendResponse(ctx, hr);
+ }
+ }
+
+ /**
+ * All http responses in the stack should be handled here.
+ */
+ protected void sendResponse(ControllerContext ctx, HTTPResponse resp)
+ {
+ try
+ {
+ resp.sendResponse(ctx.getServerInvocation().getServerContext());
+ }
+ catch (IOException e)
+ {
+ log.error("Cound not send http response", e);
+ }
+ catch (ServletException e)
+ {
+ log.error("Cound not send http response", e);
+ }
+ }
+
+ protected HandlerResponse executeCommand(ControllerContext ctx, ControllerCommand cmd) throws ServerException
+ {
+ URLContext urlContext = ctx.getServerInvocation().getServerContext().getURLContext();
+
+ try
+ {
+ // Execute command
+ Object commandResponse = ctx.execute(cmd);
+
+ // Handle the result, might be null if no handling done
+ return handleResponse(ctx, cmd, commandResponse);
+ }
+ catch (CommandRedirectionException e)
+ {
+ // Handle the redirection as forward
+ return new CommandForward(e.getRedirection(), null);
+ }
+ catch (InsufficientTransportGuaranteeException e)
+ {
+ urlContext = URLContext.newInstance(true, urlContext.isAuthenticated());
+ ServerURL serverURL = getURLFactory().doMapping(ctx.getServerInvocation(), cmd);
+ String url = ctx.getServerInvocation().getResponse().renderURL(serverURL, urlContext, null);
+ return new HTTPResponse.SendRedirect(url);
+ }
+ catch (ControllerSecurityException e)
+ {
+ if (urlContext.isAuthenticated())
+ {
+ return new HTTPResponse.SetStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
+ }
+ else
+ {
+ urlContext = URLContext.newInstance(urlContext.isSecure(), true);
+ ServerURL serverURL = getURLFactory().doMapping(ctx.getServerInvocation(), cmd);
+ String url = ctx.getServerInvocation().getResponse().renderURL(serverURL, urlContext, null);
+ return new HTTPResponse.SendRedirect(url);
+ }
+ }
+ catch (ResourceNotFoundException e)
+ {
+ log.error("Resource not found " + e.getRef(), e);
+ return new HTTPResponse.SetStatusCode(HttpServletResponse.SC_NOT_FOUND);
+ }
+ catch (ControllerException e)
+ {
+ throw new ServerException(e);
+ }
+ catch (ServletException e)
+ {
+ throw new ServerException(e);
+ }
+ catch (IOException e)
+ {
+ throw new ServerException(e);
+ }
+ }
+
+ /**
+ * Return true if the execution of the next command requires a redirect.
+ *
+ * @param currentCmd the current command which has been executed
+ * @param currentURLCtx the request URL context
+ * @param forward the forward
+ * @return
+ */
+ public boolean requiresRedirect(
+ ControllerCommand currentCmd,
+ URLContext currentURLCtx,
+ CommandForward forward)
+ {
+ CommandInfo currentCmdInfo = currentCmd.getInfo();
+ if (currentCmdInfo instanceof ActionCommandInfo && !((ActionCommandInfo)currentCmdInfo).isIdempotent())
+ {
+ return true;
+ }
+ else
+ {
+ URLContext nextURLCtx = forward.getURLContext();
+ boolean currentAuthenticated = currentURLCtx.isAuthenticated();
+ if (nextURLCtx != null && currentAuthenticated != nextURLCtx.isAuthenticated())
+ {
+ return true;
+ }
+ else
+ {
+ boolean currentSecure = currentURLCtx.isSecure();
+ if (nextURLCtx != null && nextURLCtx.isSecure() && !currentSecure)
+ {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
}
Modified: trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxController.java
===================================================================
--- trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxController.java 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxController.java 2007-03-31 12:56:57 UTC (rev 6893)
@@ -26,12 +26,19 @@
import org.jboss.portal.core.controller.ControllerContext;
import org.jboss.portal.core.controller.ControllerException;
import org.jboss.portal.core.controller.Controller;
+import org.jboss.portal.core.controller.classic.HandlerResponse;
+import org.jboss.portal.core.controller.classic.CommandForward;
import org.jboss.portal.core.model.portal.command.MoveWindowCommand;
+import org.jboss.portal.core.model.portal.command.RenderWindowCommand;
+import org.jboss.portal.core.model.portal.command.response.UpdateWindowMarkupResponse;
import org.jboss.portal.core.model.portal.PortalObjectId;
import org.jboss.portal.server.ServerException;
import org.jboss.portal.server.ServerInvocation;
+import org.jboss.portal.theme.page.WindowResult;
import javax.servlet.http.HttpServletRequest;
+import javax.servlet.ServletException;
+import java.io.IOException;
/**
* @author <a href="mailto:julien@jboss.org">Julien Viet</a>
@@ -68,5 +75,45 @@
e.printStackTrace();
}
}
+ else
+ {
+ // Invoke the chain that creates the initial command
+ ControllerCommand cmd = commandFactory.doMapping(invocation, invocation.getServerContext().getPortalHost(), invocation.getServerContext().getPortalContextPath(), invocation.getServerContext().getPortalRequestPath());
+
+ //
+ if (cmd == null)
+ {
+ // Handle that case
+ throw new ServerException("No command was produced by the command factory");
+ }
+
+ // Create controller context
+ ControllerContext ctx = new ControllerContext(invocation, this);
+
+ // Handle the command created
+ handleCommand(ctx, cmd);
+ }
}
+
+ public HandlerResponse handleResponse(ControllerContext ctx, ControllerCommand cmd, Object response) throws IOException, ServletException, ServerException
+ {
+ if (response instanceof UpdateWindowMarkupResponse)
+ {
+ UpdateWindowMarkupResponse updateMarkup = (UpdateWindowMarkupResponse)response;
+ RenderWindowCommand rwc = new RenderWindowCommand(updateMarkup.getWindowId());
+ return new CommandForward(rwc, null);
+ }
+ else if (response instanceof WindowResult)
+ {
+ WindowResult windowResult = (WindowResult)response;
+ // todo
+ }
+ else
+ {
+ System.out.println("Not yet handled " + response);
+ }
+
+ //
+ return null;
+ }
}
Modified: trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxInterceptor.java
===================================================================
--- trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxInterceptor.java 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/core/src/main/org/jboss/portal/core/controller/ajax/AjaxInterceptor.java 2007-03-31 12:56:57 UTC (rev 6893)
@@ -26,9 +26,10 @@
import org.jboss.portal.core.controller.ControllerCommand;
import org.jboss.portal.core.controller.ControllerInterceptor;
import org.jboss.portal.core.model.portal.command.RenderPageCommand;
-import org.jboss.portal.core.model.portal.command.ViewDashboardCommand;
import org.jboss.portal.theme.PageRendition;
import org.jboss.portal.theme.ThemeConstants;
+import org.jboss.portal.server.AbstractServerURL;
+import org.jboss.portal.server.request.URLContext;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@@ -65,11 +66,23 @@
url.append(req.getContextPath()).append("/ajax");
//
+
+ //
PageRendition rendition = (PageRendition)response;
Map pageProps = rendition.getPageResult().getPageProperties();
+
pageProps.put(ThemeConstants.PORTAL_AJAX_JAVASCRIPT_BASE, "/portal-ajax");
+
+ // Compute prefix
+// AbstractServerURL tmp = new AbstractServerURL();
+// tmp.setPortalRequestPath("/");
+// cmd.getControllerContext().getServerInvocation().getServerContext().renderURL(tmp, URLContext.newInstance(false, false));
+
+ pageProps.put(ThemeConstants.PORTAL_AJAX_CLASSIC_SERVER_URL, "");
+
+
pageProps.put(ThemeConstants.PORTAL_AJAX_OBJECT_ENABLED, "true");
- pageProps.put(ThemeConstants.PORTAL_AJAX_REMOTE_URL, url.toString());
+ pageProps.put(ThemeConstants.PORTAL_AJAX_ASYNC_SERVER_URL, url.toString());
}
}
Modified: trunk/core/src/main/org/jboss/portal/core/controller/classic/ClassicController.java
===================================================================
--- trunk/core/src/main/org/jboss/portal/core/controller/classic/ClassicController.java 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/core/src/main/org/jboss/portal/core/controller/classic/ClassicController.java 2007-03-31 12:56:57 UTC (rev 6893)
@@ -61,7 +61,6 @@
new PortletInstanceResponseHandler()
};
-
public void handle(ServerInvocation invocation) throws ServerException
{
// Invoke the chain that creates the initial command
@@ -81,167 +80,19 @@
handleCommand(ctx, cmd);
}
- /**
- * Handle a command which means it executes the command and reacts upon the response created by the command.
- *
- * @param ctx the controller context
- * @param cmd the command
- * @throws ServerException
- */
- protected void handleCommand(final ControllerContext ctx, final ControllerCommand cmd) throws ServerException
+ public HandlerResponse handleResponse(ControllerContext ctx, ControllerCommand cmd, Object response) throws IOException, ServletException, ServerException
{
- HandlerResponse handlerResp = executeCommand(ctx, cmd);
-
- //
- if (handlerResp == null)
+ for (int i = 0;i < handlers.length;i++)
{
- return;
- }
-
- // Find out if we can execute in the same server invocation
- if (handlerResp instanceof CommandForward)
- {
- CommandForward forward = (CommandForward)handlerResp;
- URLContext urlContext = ctx.getServerInvocation().getServerContext().getURLContext();
- if (requiresRedirect(cmd, urlContext, forward))
+ ResponseHandler handler = handlers[i];
+ HandlerResponse handlerResponse = handler.handleResponse(ctx, cmd, response);
+ if (handlerResponse != null)
{
- String url = ctx.renderURL(forward.getCommand(), forward.getURLContext(), null);
- sendResponse(ctx, new HTTPResponse.SendRedirect(url));
+ return handlerResponse;
}
- else
- {
- handleCommand(ctx, forward.getCommand());
- }
}
- else
- {
- HTTPResponse hr = (HTTPResponse)handlerResp;
- sendResponse(ctx, hr);
- }
- }
- /**
- * All http responses in the stack should be handled here.
- */
- protected void sendResponse(ControllerContext ctx, HTTPResponse resp)
- {
- try
- {
- resp.sendResponse(ctx.getServerInvocation().getServerContext());
- }
- catch (IOException e)
- {
- log.error("Cound not send http response", e);
- }
- catch (ServletException e)
- {
- log.error("Cound not send http response", e);
- }
+ //
+ return null;
}
-
- protected HandlerResponse executeCommand(ControllerContext ctx, ControllerCommand cmd) throws ServerException
- {
- URLContext urlContext = ctx.getServerInvocation().getServerContext().getURLContext();
-
- try
- {
- // Execute command
- Object commandResponse = ctx.execute(cmd);
-
- // Handle the result
- for (int i = 0;i < handlers.length;i++)
- {
- ResponseHandler handler = handlers[i];
- HandlerResponse handlerResponse = handler.handleResponse(ctx, cmd, commandResponse);
- if (handlerResponse != null)
- {
- return handlerResponse;
- }
- }
-
- // We were not able to determine a suitable response
- return null;
- }
- catch (CommandRedirectionException e)
- {
- // Handle the redirection as forward
- return new CommandForward(e.getRedirection(), null);
- }
- catch (InsufficientTransportGuaranteeException e)
- {
- urlContext = URLContext.newInstance(true, urlContext.isAuthenticated());
- ServerURL serverURL = getURLFactory().doMapping(ctx.getServerInvocation(), cmd);
- String url = ctx.getServerInvocation().getResponse().renderURL(serverURL, urlContext, null);
- return new HTTPResponse.SendRedirect(url);
- }
- catch (ControllerSecurityException e)
- {
- if (urlContext.isAuthenticated())
- {
- return new HTTPResponse.SetStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
- }
- else
- {
- urlContext = URLContext.newInstance(urlContext.isSecure(), true);
- ServerURL serverURL = getURLFactory().doMapping(ctx.getServerInvocation(), cmd);
- String url = ctx.getServerInvocation().getResponse().renderURL(serverURL, urlContext, null);
- return new HTTPResponse.SendRedirect(url);
- }
- }
- catch (ResourceNotFoundException e)
- {
- log.error("Resource not found " + e.getRef(), e);
- return new HTTPResponse.SetStatusCode(HttpServletResponse.SC_NOT_FOUND);
- }
- catch (ControllerException e)
- {
- throw new ServerException(e);
- }
- catch (ServletException e)
- {
- throw new ServerException(e);
- }
- catch (IOException e)
- {
- throw new ServerException(e);
- }
- }
-
- /**
- * Return true if the execution of the next command requires a redirect.
- *
- * @param currentCmd the current command which has been executed
- * @param currentURLCtx the request URL context
- * @param forward the forward
- * @return
- */
- public boolean requiresRedirect(
- ControllerCommand currentCmd,
- URLContext currentURLCtx,
- CommandForward forward)
- {
- CommandInfo currentCmdInfo = currentCmd.getInfo();
- if (currentCmdInfo instanceof ActionCommandInfo && !((ActionCommandInfo)currentCmdInfo).isIdempotent())
- {
- return true;
- }
- else
- {
- URLContext nextURLCtx = forward.getURLContext();
- boolean currentAuthenticated = currentURLCtx.isAuthenticated();
- if (nextURLCtx != null && currentAuthenticated != nextURLCtx.isAuthenticated())
- {
- return true;
- }
- else
- {
- boolean currentSecure = currentURLCtx.isSecure();
- if (nextURLCtx != null && nextURLCtx.isSecure() && !currentSecure)
- {
- return true;
- }
- }
- }
- return false;
- }
}
Modified: trunk/core/src/resources/portal-core-sar/META-INF/jboss-service.xml
===================================================================
--- trunk/core/src/resources/portal-core-sar/META-INF/jboss-service.xml 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/core/src/resources/portal-core-sar/META-INF/jboss-service.xml 2007-03-31 12:56:57 UTC (rev 6893)
@@ -950,8 +950,26 @@
<depends
optional-attribute-name="CustomizationManager"
proxy-type="attribute">portal:service=CustomizationManager</depends>
+ <depends
+ optional-attribute-name="ContentRendererRegistry"
+ proxy-type="attribute">portal:service=ContentProviderRegistry</depends>
</mbean>
+ <!-- The controller factory -->
+ <mbean
+ code="org.jboss.portal.core.controller.ControllerFactory"
+ name="portal:service=ControllerFactory"
+ xmbean-dd=""
+ xmbean-code="org.jboss.portal.jems.as.system.JBossServiceModelMBean">
+ <xmbean/>
+ <depends
+ optional-attribute-name="ClassicController"
+ proxy-type="attribute">portal:controller=Core</depends>
+ <depends
+ optional-attribute-name="AjaxController"
+ proxy-type="attribute">portal:controller=Ajax</depends>
+ </mbean>
+
<!-- -->
<mbean
code="org.jboss.portal.server.impl.ServerImpl"
Modified: trunk/core/src/resources/portal-server-war/WEB-INF/web.xml
===================================================================
--- trunk/core/src/resources/portal-server-war/WEB-INF/web.xml 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/core/src/resources/portal-server-war/WEB-INF/web.xml 2007-03-31 12:56:57 UTC (rev 6893)
@@ -46,9 +46,9 @@
<description>The servlet needs to know wether it is set as a default servlet or not</description>
</init-param>
<init-param>
- <param-name>controllerName</param-name>
- <param-value>portal:controller=Core</param-value>
- <description>The request controller for the portal servlet</description>
+ <param-name>controllerFactoryName</param-name>
+ <param-value>portal:service=ControllerFactory</param-value>
+ <description>The request controller factory for the portal servlet</description>
</init-param>
<load-on-startup>0</load-on-startup>
<security-role-ref>
@@ -67,9 +67,9 @@
<description>The servlet needs to know wether it is set as a default servlet or not</description>
</init-param>
<init-param>
- <param-name>controllerName</param-name>
- <param-value>portal:controller=Core</param-value>
- <description>The request controller for the portal servlet</description>
+ <param-name>controllerFactoryName</param-name>
+ <param-value>portal:service=ControllerFactory</param-value>
+ <description>The request controller factory for the portal servlet</description>
</init-param>
<load-on-startup>0</load-on-startup>
<security-role-ref>
Modified: trunk/portlet-server/src/resources/test/info/test-info-sar/META-INF/jboss-service.xml
===================================================================
--- trunk/portlet-server/src/resources/test/info/test-info-sar/META-INF/jboss-service.xml 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/portlet-server/src/resources/test/info/test-info-sar/META-INF/jboss-service.xml 2007-03-31 12:56:57 UTC (rev 6893)
@@ -112,6 +112,18 @@
<depends optional-attribute-name="TestDriverRegistry" proxy-type="attribute">portal.test:service=HttpTestDriverServer</depends>
</mbean>
+ <!-- The controller factory -->
+ <mbean
+ code="org.jboss.portal.server.impl.RequestControllerFactoryImpl"
+ name="portal:service=ControllerFactory"
+ xmbean-dd=""
+ xmbean-code="org.jboss.portal.jems.as.system.JBossServiceModelMBean">
+ <xmbean/>
+ <depends
+ optional-attribute-name="Controller"
+ proxy-type="attribute">portal:controller=Request</depends>
+ </mbean>
+
<!-- -->
<mbean
code="org.jboss.portal.test.portlet.info.MetaInfoTest"
Modified: trunk/portlet-server/src/resources/test-sar/META-INF/jboss-service.xml
===================================================================
--- trunk/portlet-server/src/resources/test-sar/META-INF/jboss-service.xml 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/portlet-server/src/resources/test-sar/META-INF/jboss-service.xml 2007-03-31 12:56:57 UTC (rev 6893)
@@ -275,6 +275,18 @@
<attribute name="RedirectAfterAction">false</attribute>
</mbean>
+ <!-- The controller factory -->
+ <mbean
+ code="org.jboss.portal.server.impl.RequestControllerFactoryImpl"
+ name="portal:service=ControllerFactory"
+ xmbean-dd=""
+ xmbean-code="org.jboss.portal.jems.as.system.JBossServiceModelMBean">
+ <xmbean/>
+ <depends
+ optional-attribute-name="Controller"
+ proxy-type="attribute">portal:controller=Request,redirect=true</depends>
+ </mbean>
+
<!-- Portlet deployment factory -->
<mbean
code="org.jboss.portal.portlet.deployment.jboss.PortletAppDeploymentFactory"
Modified: trunk/portlet-server/src/resources/test-war/WEB-INF/web.xml
===================================================================
--- trunk/portlet-server/src/resources/test-war/WEB-INF/web.xml 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/portlet-server/src/resources/test-war/WEB-INF/web.xml 2007-03-31 12:56:57 UTC (rev 6893)
@@ -39,9 +39,9 @@
<description>The servlet needs to know wether it is set as a default servlet or not</description>
</init-param>
<init-param>
- <param-name>controllerName</param-name>
- <param-value>portal:controller=Request,redirect=true</param-value>
- <description>The request controller for the portal servlet</description>
+ <param-name>controllerFactoryName</param-name>
+ <param-value>portal:service=ControllerFactory</param-value>
+ <description>The request controller factory for the portal servlet</description>
</init-param>
<load-on-startup>0</load-on-startup>
<security-role-ref>
@@ -59,11 +59,11 @@
<param-value>false</param-value>
<description>The servlet needs to know wether it is set as a default servlet or not</description>
</init-param>
- <init-param>
- <param-name>controllerName</param-name>
- <param-value>portal:controller=Request,redirect=false</param-value>
- <description>The request controller for the portal servlet</description>
- </init-param>
+ <init-param>
+ <param-name>controllerFactoryName</param-name>
+ <param-value>portal:service=ControllerFactory</param-value>
+ <description>The request controller factory for the portal servlet</description>
+ </init-param>
<load-on-startup>0</load-on-startup>
<security-role-ref>
<role-name>Test</role-name>
Added: trunk/server/src/main/org/jboss/portal/server/RequestControllerFactory.java
===================================================================
--- trunk/server/src/main/org/jboss/portal/server/RequestControllerFactory.java (rev 0)
+++ trunk/server/src/main/org/jboss/portal/server/RequestControllerFactory.java 2007-03-31 12:56:57 UTC (rev 6893)
@@ -0,0 +1,34 @@
+/******************************************************************************
+ * JBoss, a division of Red Hat *
+ * Copyright 2006, Red Hat Middleware, LLC, and individual *
+ * contributors as indicated by the @authors tag. See the *
+ * copyright.txt in the distribution for a full listing of *
+ * individual contributors. *
+ * *
+ * This is free software; you can redistribute it and/or modify it *
+ * under the terms of the GNU Lesser General Public License as *
+ * published by the Free Software Foundation; either version 2.1 of *
+ * the License, or (at your option) any later version. *
+ * *
+ * This software is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
+ * Lesser General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU Lesser General Public *
+ * License along with this software; if not, write to the Free *
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org. *
+ ******************************************************************************/
+package org.jboss.portal.server;
+
+/**
+ * @author <a href="mailto:julien@jboss.org">Julien Viet</a>
+ * @version $Revision: 1.1 $
+ */
+public interface RequestControllerFactory
+{
+
+ RequestController createRequestController(ServerInvocation invocation);
+
+}
Added: trunk/server/src/main/org/jboss/portal/server/impl/RequestControllerFactoryImpl.java
===================================================================
--- trunk/server/src/main/org/jboss/portal/server/impl/RequestControllerFactoryImpl.java (rev 0)
+++ trunk/server/src/main/org/jboss/portal/server/impl/RequestControllerFactoryImpl.java 2007-03-31 12:56:57 UTC (rev 6893)
@@ -0,0 +1,53 @@
+/******************************************************************************
+ * JBoss, a division of Red Hat *
+ * Copyright 2006, Red Hat Middleware, LLC, and individual *
+ * contributors as indicated by the @authors tag. See the *
+ * copyright.txt in the distribution for a full listing of *
+ * individual contributors. *
+ * *
+ * This is free software; you can redistribute it and/or modify it *
+ * under the terms of the GNU Lesser General Public License as *
+ * published by the Free Software Foundation; either version 2.1 of *
+ * the License, or (at your option) any later version. *
+ * *
+ * This software is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
+ * Lesser General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU Lesser General Public *
+ * License along with this software; if not, write to the Free *
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org. *
+ ******************************************************************************/
+package org.jboss.portal.server.impl;
+
+import org.jboss.portal.server.RequestControllerFactory;
+import org.jboss.portal.server.RequestController;
+import org.jboss.portal.server.ServerInvocation;
+
+/**
+ * @author <a href="mailto:julien@jboss.org">Julien Viet</a>
+ * @version $Revision: 1.1 $
+ */
+public class RequestControllerFactoryImpl implements RequestControllerFactory
+{
+
+ /** . */
+ private RequestController controller;
+
+ public RequestController getController()
+ {
+ return controller;
+ }
+
+ public void setController(RequestController controller)
+ {
+ this.controller = controller;
+ }
+
+ public RequestController createRequestController(ServerInvocation invocation)
+ {
+ return controller;
+ }
+}
Modified: trunk/server/src/main/org/jboss/portal/server/servlet/PortalServlet.java
===================================================================
--- trunk/server/src/main/org/jboss/portal/server/servlet/PortalServlet.java 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/server/src/main/org/jboss/portal/server/servlet/PortalServlet.java 2007-03-31 12:56:57 UTC (rev 6893)
@@ -31,7 +31,6 @@
import org.jboss.portal.common.util.URLTools;
import org.jboss.portal.common.http.QueryStringParser;
import org.jboss.portal.server.PortalConstants;
-import org.jboss.portal.server.RequestController;
import org.jboss.portal.server.RequestControllerDispatcher;
import org.jboss.portal.server.Server;
import org.jboss.portal.server.ServerException;
@@ -39,6 +38,8 @@
import org.jboss.portal.server.ServerInvocationContext;
import org.jboss.portal.server.ServerRequest;
import org.jboss.portal.server.ServerResponse;
+import org.jboss.portal.server.RequestControllerFactory;
+import org.jboss.portal.server.RequestController;
import org.jboss.portal.server.impl.ServerInvocationContextImpl;
import org.jboss.portal.server.request.URLContext;
@@ -94,16 +95,16 @@
private boolean asDefaultServlet;
/** The controller for this servlet. */
- private RequestController controller;
+ private RequestControllerFactory controllerFactory;
/** The controller name. */
- private String controllerName;
+ private String controllerFactoryName;
/** Configure the as default servlet. */
public void init() throws ServletException
{
asDefaultServlet = getAsDefaultServletInitValue();
- controllerName = getServletConfig().getInitParameter("controllerName");
+ controllerFactoryName = getServletConfig().getInitParameter("controllerFactoryName");
}
/**
@@ -147,23 +148,23 @@
return interceptorStack;
}
- protected final RequestController getController()
+ protected final RequestControllerFactory getControllerFactory()
{
- if (controller == null)
+ if (controllerFactory == null)
{
try
{
MBeanServer mbeanServer = MBeanServerLocator.locateJBoss();
- controller = (RequestController)MBeanProxy.get(RequestController.class, new ObjectName(controllerName), mbeanServer);
+ controllerFactory = (RequestControllerFactory)MBeanProxy.get(RequestControllerFactory.class, new ObjectName(controllerFactoryName), mbeanServer);
}
catch (Exception e)
{
- String msg = "Cannot get controller " + controllerName;
+ String msg = "Cannot get controller " + controllerFactoryName;
log.error(msg, e);
throw new IllegalStateException(msg);
}
}
- return controller;
+ return controllerFactory;
}
private String retrieveMediaType(String contentType)
@@ -368,7 +369,8 @@
invocation.setResponse(response);
//
- RequestController controller = getController();
+ RequestControllerFactory controllerFactory = getControllerFactory();
+ RequestController controller = controllerFactory.createRequestController(invocation);
invocation.setHandler(new RequestControllerDispatcher(controller));
//
Modified: trunk/server/src/resources/test/test-charset-sar/META-INF/jboss-service.xml
===================================================================
--- trunk/server/src/resources/test/test-charset-sar/META-INF/jboss-service.xml 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/server/src/resources/test/test-charset-sar/META-INF/jboss-service.xml 2007-03-31 12:56:57 UTC (rev 6893)
@@ -85,6 +85,18 @@
<depends optional-attribute-name="TestDriverRegistry" proxy-type="attribute">portal.test:service=HttpTestDriverServer</depends>
</mbean>
+ <!-- The controller factory -->
+ <mbean
+ code="org.jboss.portal.server.impl.RequestControllerFactoryImpl"
+ name="portal:service=ControllerFactory"
+ xmbean-dd=""
+ xmbean-code="org.jboss.portal.jems.as.system.JBossServiceModelMBean">
+ <xmbean/>
+ <depends
+ optional-attribute-name="Controller"
+ proxy-type="attribute">portal:controller=Request</depends>
+ </mbean>
+
<!-- -->
<mbean
code="org.jboss.portal.test.server.charset.GetTest"
Modified: trunk/server/src/resources/test/test-parameters-sar/META-INF/jboss-service.xml
===================================================================
--- trunk/server/src/resources/test/test-parameters-sar/META-INF/jboss-service.xml 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/server/src/resources/test/test-parameters-sar/META-INF/jboss-service.xml 2007-03-31 12:56:57 UTC (rev 6893)
@@ -84,6 +84,18 @@
<depends optional-attribute-name="TestDriverRegistry" proxy-type="attribute">portal.test:service=HttpTestDriverServer</depends>
</mbean>
+ <!-- The controller factory -->
+ <mbean
+ code="org.jboss.portal.server.impl.RequestControllerFactoryImpl"
+ name="portal:service=ControllerFactory"
+ xmbean-dd=""
+ xmbean-code="org.jboss.portal.jems.as.system.JBossServiceModelMBean">
+ <xmbean/>
+ <depends
+ optional-attribute-name="Controller"
+ proxy-type="attribute">portal:controller=Request</depends>
+ </mbean>
+
<!-- -->
<mbean
code="org.jboss.portal.test.server.parameters.GetTest"
Modified: trunk/server/src/resources/test/test-response-sar/META-INF/jboss-service.xml
===================================================================
--- trunk/server/src/resources/test/test-response-sar/META-INF/jboss-service.xml 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/server/src/resources/test/test-response-sar/META-INF/jboss-service.xml 2007-03-31 12:56:57 UTC (rev 6893)
@@ -84,6 +84,18 @@
<depends optional-attribute-name="TestDriverRegistry" proxy-type="attribute">portal.test:service=HttpTestDriverServer</depends>
</mbean>
+ <!-- The controller factory -->
+ <mbean
+ code="org.jboss.portal.server.impl.RequestControllerFactoryImpl"
+ name="portal:service=ControllerFactory"
+ xmbean-dd=""
+ xmbean-code="org.jboss.portal.jems.as.system.JBossServiceModelMBean">
+ <xmbean/>
+ <depends
+ optional-attribute-name="Controller"
+ proxy-type="attribute">portal:controller=Request</depends>
+ </mbean>
+
<!-- -->
<mbean
code="org.jboss.portal.test.server.response.EncodeResponseTest"
Modified: trunk/server/src/resources/test/test-servlet-defaultservletmapping-war/WEB-INF/web.xml
===================================================================
--- trunk/server/src/resources/test/test-servlet-defaultservletmapping-war/WEB-INF/web.xml 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/server/src/resources/test/test-servlet-defaultservletmapping-war/WEB-INF/web.xml 2007-03-31 12:56:57 UTC (rev 6893)
@@ -36,9 +36,9 @@
<description>The servlet needs to know wether it is set as a default servlet or not</description>
</init-param>
<init-param>
- <param-name>controllerName</param-name>
- <param-value>portal:controller=Request</param-value>
- <description>The request controller for the portal servlet</description>
+ <param-name>controllerFactoryName</param-name>
+ <param-value>portal:service=ControllerFactory</param-value>
+ <description>The request controller factory for the portal servlet</description>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
Modified: trunk/server/src/resources/test/test-servlet-pathmapping-war/WEB-INF/web.xml
===================================================================
--- trunk/server/src/resources/test/test-servlet-pathmapping-war/WEB-INF/web.xml 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/server/src/resources/test/test-servlet-pathmapping-war/WEB-INF/web.xml 2007-03-31 12:56:57 UTC (rev 6893)
@@ -36,9 +36,9 @@
<description>The servlet needs to know wether it is set as a default servlet or not</description>
</init-param>
<init-param>
- <param-name>controllerName</param-name>
- <param-value>portal:controller=Request</param-value>
- <description>The request controller for the portal servlet</description>
+ <param-name>controllerFactoryName</param-name>
+ <param-value>portal:service=ControllerFactory</param-value>
+ <description>The request controller factory for the portal servlet</description>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
Modified: trunk/server/src/resources/test/test-servlet-rootpathmapping-war/WEB-INF/web.xml
===================================================================
--- trunk/server/src/resources/test/test-servlet-rootpathmapping-war/WEB-INF/web.xml 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/server/src/resources/test/test-servlet-rootpathmapping-war/WEB-INF/web.xml 2007-03-31 12:56:57 UTC (rev 6893)
@@ -36,9 +36,9 @@
<description>The servlet needs to know wether it is set as a default servlet or not</description>
</init-param>
<init-param>
- <param-name>controllerName</param-name>
- <param-value>portal:controller=Request</param-value>
- <description>The request controller for the portal servlet</description>
+ <param-name>controllerFactoryName</param-name>
+ <param-value>portal:service=ControllerFactory</param-value>
+ <description>The request controller factory for the portal servlet</description>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
Modified: trunk/server/src/resources/test/test-servlet-sar/META-INF/jboss-service.xml
===================================================================
--- trunk/server/src/resources/test/test-servlet-sar/META-INF/jboss-service.xml 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/server/src/resources/test/test-servlet-sar/META-INF/jboss-service.xml 2007-03-31 12:56:57 UTC (rev 6893)
@@ -84,6 +84,18 @@
<depends optional-attribute-name="TestDriverRegistry" proxy-type="attribute">portal.test:service=HttpTestDriverServer</depends>
</mbean>
+ <!-- The controller factory -->
+ <mbean
+ code="org.jboss.portal.server.impl.RequestControllerFactoryImpl"
+ name="portal:service=ControllerFactory"
+ xmbean-dd=""
+ xmbean-code="org.jboss.portal.jems.as.system.JBossServiceModelMBean">
+ <xmbean/>
+ <depends
+ optional-attribute-name="Controller"
+ proxy-type="attribute">portal:controller=Request</depends>
+ </mbean>
+
<!-- -->
<mbean
code="org.jboss.portal.test.server.servlet.RootPathMappingTest"
Modified: trunk/server/src/resources/test-agent-war/WEB-INF/web.xml
===================================================================
--- trunk/server/src/resources/test-agent-war/WEB-INF/web.xml 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/server/src/resources/test-agent-war/WEB-INF/web.xml 2007-03-31 12:56:57 UTC (rev 6893)
@@ -36,9 +36,9 @@
<description>The servlet needs to know wether it is set as a default servlet or not</description>
</init-param>
<init-param>
- <param-name>controllerName</param-name>
- <param-value>portal:controller=Request</param-value>
- <description>The request controller for the portal servlet</description>
+ <param-name>controllerFactoryName</param-name>
+ <param-value>portal:service=ControllerFactory</param-value>
+ <description>The request controller factory for the portal servlet</description>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
Modified: trunk/theme/src/main/org/jboss/portal/test/theme/render/TestRenderedMarkup.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/test/theme/render/TestRenderedMarkup.java 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/theme/src/main/org/jboss/portal/test/theme/render/TestRenderedMarkup.java 2007-03-31 12:56:57 UTC (rev 6893)
@@ -128,7 +128,7 @@
//
Map pageProps = new HashMap();
pageProps.put(ThemeConstants.PORTAL_AJAX_JAVASCRIPT_BASE, "/portal-ajax");
- pageProps.put(ThemeConstants.PORTAL_AJAX_REMOTE_URL, "http://localhost:8080/portal-ajax/ajax");
+ pageProps.put(ThemeConstants.PORTAL_AJAX_ASYNC_SERVER_URL, "http://localhost:8080/portal-ajax/ajax");
//
Map portalProps = new HashMap();
Modified: trunk/theme/src/main/org/jboss/portal/test/theme/servlet/TestThemeServlet.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/test/theme/servlet/TestThemeServlet.java 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/theme/src/main/org/jboss/portal/test/theme/servlet/TestThemeServlet.java 2007-03-31 12:56:57 UTC (rev 6893)
@@ -99,7 +99,7 @@
//
Map pageProps = new HashMap();
pageProps.put(ThemeConstants.PORTAL_AJAX_JAVASCRIPT_BASE, "/portal-ajax");
- pageProps.put(ThemeConstants.PORTAL_AJAX_REMOTE_URL, "http://localhost:8080/portal-ajax/ajax");
+ pageProps.put(ThemeConstants.PORTAL_AJAX_ASYNC_SERVER_URL, "http://localhost:8080/portal-ajax/ajax");
//
Map portalProps = new HashMap();
Modified: trunk/theme/src/main/org/jboss/portal/theme/ThemeConstants.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/ThemeConstants.java 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/theme/src/main/org/jboss/portal/theme/ThemeConstants.java 2007-03-31 12:56:57 UTC (rev 6893)
@@ -91,10 +91,15 @@
/**
*
*/
- public static final String PORTAL_AJAX_REMOTE_URL = "theme.ajax.remove_url";
+ public static final String PORTAL_AJAX_ASYNC_SERVER_URL = "theme.ajax.async_server_url";
/**
*
*/
+ public static final String PORTAL_AJAX_CLASSIC_SERVER_URL = "theme.ajax.classic_server_url";
+
+ /**
+ *
+ */
public static final String PORTAL_AJAX_OBJECT_ENABLED = "theme.ajax.object_enabled";
}
Modified: trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaRegionRenderer.java
===================================================================
--- trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaRegionRenderer.java 2007-03-31 05:20:07 UTC (rev 6892)
+++ trunk/theme/src/main/org/jboss/portal/theme/impl/render/dynamic/DynaRegionRenderer.java 2007-03-31 12:56:57 UTC (rev 6893)
@@ -88,7 +88,8 @@
{
StringBuffer markup = renderContext.getMarkupFragment();
String jsBase = renderContext.getProperty(ThemeConstants.PORTAL_AJAX_JAVASCRIPT_BASE);
- String remoteURL = renderContext.getProperty(ThemeConstants.PORTAL_AJAX_REMOTE_URL);
+ String asyncServerURL = renderContext.getProperty(ThemeConstants.PORTAL_AJAX_ASYNC_SERVER_URL);
+ String classicServerURL = renderContext.getProperty(ThemeConstants.PORTAL_AJAX_CLASSIC_SERVER_URL);
//
Object onPage = renderContext.getProperty(ThemeConstants.PORTAL_AJAX_OBJECT_ENABLED);
@@ -107,7 +108,8 @@
markup.append("<script type='text/javascript' src='").append(jsBase).append("/js/portal/effects.js'></script>\n");
markup.append("<script type='text/javascript' src='").append(jsBase).append("/js/portal/dragdrop.js'></script>\n");
markup.append("<script type='text/javascript'>\n");
- markup.append("remote_server_url=\"").append(remoteURL).append(";\"\n");
+ markup.append("async_server_url=\"").append(asyncServerURL).append(";\"\n");
+ markup.append("classic_server_url=\"").append(classicServerURL).append("\";\n");
String sendData = "" +
"function sendData(action, windowId, fromPos, fromRegionId, toPos, toRegionId) {\n" +
@@ -132,7 +134,7 @@
" {\n" +
" }\n" +
" }\n" +
- " new Ajax.Request(remote_server_url, options);\n" +
+ " new Ajax.Request(async_server_url, options);\n" +
"}";
markup.append(sendData);
@@ -195,9 +197,24 @@
String v = "" +
"function bilto(event)\n" +
"{\n" +
- " var source = Event.element(event);\n" +
- " alert(source.id);\n" +
- " Event.stop(event);;\n" +
+// " var source = Event.element(event);\n" +
+// " if (source.nodeName == \"A\") {;\n" +
+// " var url = source.href;\n" +
+// " var parameters = \"\";\n" +
+// " var pos = url.indexOf(\"?\");\n" +
+// " if (pos != -1) {\n" +
+// " parameters = url.substring(pos + 1);\n" +
+// " url = url.substring(0, pos);\n" +
+// " }\n" +
+// " Event.stop(event);\n" +
+// " var options = {\n" +
+// " parameters:parameters,\n" +
+// " asynchronous:true,\n" +
+// " method:\"get\",\n" +
+// " requestHeaders:[\"ajax\",\"true\"],\n" +
+// " };" +
+// " new Ajax.Request(url, options);\n" +
+// " }\n" +
"}\n";
markup.append(v);
@@ -224,11 +241,11 @@
// Find the dyna portlets
"var portlets_on_page = document.getElementsByClassName(\"dyna-portlet\");\n" +
- // Add listener for those portlets
-// "for(var i = 0;i < portlets_on_page.length;i++) {\n" +
-// " var portlet = portlets_on_page[i];\n" +
-// " Event.observe(portlet, 'click', bilto);\n" +
-// "}\n" +
+ // Add listener for teh dyna portlets
+ "for(var i = 0;i < portlets_on_page.length;i++) {\n" +
+ " var portlet = portlets_on_page[i];\n" +
+ " Event.observe(portlet, 'click', bilto);\n" +
+ "}\n" +
"</script>\n");
}
17 years, 7 months
JBoss Portal SVN: r6892 - in trunk/wsrp/src/main/org/jboss/portal: test/wsrp/framework/support and 2 other directories.
by portal-commits@lists.jboss.org
Author: chris.laprun(a)jboss.com
Date: 2007-03-31 01:20:07 -0400 (Sat, 31 Mar 2007)
New Revision: 6892
Removed:
trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPConsumerService.java
Modified:
trunk/wsrp/src/main/org/jboss/portal/test/wsrp/deployment/DeploymentTestCase.java
trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/support/MockConsumerRegistry.java
trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ConsumerRegistryService.java
trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/WSRPConsumerImpl.java
trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPDeployer.java
trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPDeployment.java
trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPDeploymentFactory.java
Log:
- Removed WSRPConsumerService and related modifications.
- WSRPDeploymentFactory now extends GenericObjectModelFactory to bypass the fact that XB introspection only works on concrete types, not interfaces.
- Adapted test case.
Modified: trunk/wsrp/src/main/org/jboss/portal/test/wsrp/deployment/DeploymentTestCase.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/test/wsrp/deployment/DeploymentTestCase.java 2007-03-31 02:00:07 UTC (rev 6891)
+++ trunk/wsrp/src/main/org/jboss/portal/test/wsrp/deployment/DeploymentTestCase.java 2007-03-31 05:20:07 UTC (rev 6892)
@@ -31,7 +31,6 @@
import org.jboss.portal.wsrp.consumer.RegistrationInfo;
import org.jboss.portal.wsrp.core.Property;
import org.jboss.portal.wsrp.core.RegistrationData;
-import org.jboss.portal.wsrp.deployment.WSRPConsumerService;
import org.jboss.portal.wsrp.deployment.WSRPDeployment;
import org.jboss.portal.wsrp.deployment.WSRPDeploymentFactory;
import org.jboss.portal.wsrp.services.PerEndpointSOAPInvokerServiceFactory;
@@ -74,19 +73,18 @@
// deployment should only contains the consumers with available service factories
WSRPDeployment deployment = (WSRPDeployment)o;
- List services = deployment.getServices();
+ List services = deployment.getConsumers();
assertNotNull(services);
assertEquals(4, services.size());
//
Object service = services.get(0);
- assertTrue(service instanceof WSRPConsumerService);
- WSRPConsumerService consumerService = (WSRPConsumerService)service;
- assertEquals("endpoint1", consumerService.getId());
- WSRPConsumer consumer = consumerService.getConsumer();
+ assertTrue(service instanceof WSRPConsumer);
+ WSRPConsumer consumer = (WSRPConsumer)service;
+ assertEquals("endpoint1", consumer.getProducerId());
ProducerInfo info = consumer.getProducerInfo();
assertNotNull(info);
- assertEquals(consumerService.getId(), info.getId());
+ assertEquals(consumer.getProducerId(), info.getId());
EndpointConfigurationInfo endInfo = info.getEndpointConfigurationInfo();
assertNotNull(endInfo);
assertNotNull(consumer.getServiceFactory());
@@ -102,8 +100,7 @@
assertEquals(endInfo.getPortletManagementURL(), serviceFactory.getPortletManagementURL());
// inDB2 is active and configured from the DB (configured in MockConsumerRegistry)
- service = services.get(1);
- consumer = ((WSRPConsumerService)service).getConsumer();
+ consumer = (WSRPConsumer)services.get(1);
assertEquals("inDB2", consumer.getProducerId());
assertNull(consumer.getProducerInfo().getExpirationCacheSeconds());
// since inDB2 is loaded from MockConsumerRegistry, it shouldn't be processed by WSRPDeploymentFactory and should
@@ -113,11 +110,8 @@
assertEquals(EndpointConfigurationInfo.UNSET, endpoint.getMarkupURL());
//
- service = services.get(2);
- assertTrue(service instanceof WSRPConsumerService);
- consumerService = (WSRPConsumerService)service;
- assertEquals("producer1", consumerService.getId());
- consumer = consumerService.getConsumer();
+ consumer = (WSRPConsumer)services.get(2);
+ assertEquals("producer1", consumer.getProducerId());
info = consumer.getProducerInfo();
assertEquals(120, info.getExpirationCacheSeconds().intValue());
assertTrue(consumer.getServiceFactory() instanceof RemoteSOAPInvokerServiceFactory);
@@ -143,10 +137,8 @@
assertEquals("en-US", property.getLang());
assertEquals("value", property.getStringValue());
- service = services.get(3);
- consumerService = (WSRPConsumerService)service;
- assertEquals("producer2", consumerService.getId());
- consumer = consumerService.getConsumer();
+ consumer = (WSRPConsumer)services.get(3);
+ assertEquals("producer2", consumer.getProducerId());
registrationData = consumer.getProducerInfo().getRegistrationInfo().getRegistrationData();
assertNotNull(registrationData);
assertNotNull(registrationData.getConsumerName());
Modified: trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/support/MockConsumerRegistry.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/support/MockConsumerRegistry.java 2007-03-31 02:00:07 UTC (rev 6891)
+++ trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/support/MockConsumerRegistry.java 2007-03-31 05:20:07 UTC (rev 6892)
@@ -29,7 +29,6 @@
import org.jboss.portal.wsrp.consumer.ConsumerException;
import org.jboss.portal.wsrp.consumer.ConsumerRegistry;
import org.jboss.portal.wsrp.consumer.ProducerInfo;
-import org.jboss.portal.wsrp.consumer.RegistrationInfo;
import java.util.Collection;
import java.util.HashMap;
@@ -43,14 +42,7 @@
public class MockConsumerRegistry implements ConsumerRegistry
{
private Map consumers = new HashMap(3);
- private final static RegistrationInfo NULL_REGISTRATION_INFO = new RegistrationInfo();
- static
- {
- NULL_REGISTRATION_INFO.setRequiresRegistration(false);
- }
-
-
public MockConsumerRegistry()
{
consumers.put("inDB", new MockWSRPConsumer("inDB"));
@@ -98,11 +90,6 @@
// do nothing
}
- public RegistrationInfo getDefaultRegistrationInfo()
- {
- return NULL_REGISTRATION_INFO;
- }
-
public void deactivateConsumerWith(String id) throws ConsumerException
{
// do nothing
Modified: trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ConsumerRegistryService.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ConsumerRegistryService.java 2007-03-31 02:00:07 UTC (rev 6891)
+++ trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ConsumerRegistryService.java 2007-03-31 05:20:07 UTC (rev 6892)
@@ -33,7 +33,6 @@
import org.jboss.portal.portlet.federation.FederatedPortletInvoker;
import org.jboss.portal.portlet.federation.FederatingPortletInvoker;
import org.jboss.portal.wsrp.WSRPConsumer;
-import org.jboss.portal.wsrp.deployment.WSRPConsumerService;
import javax.naming.InitialContext;
import java.util.Collection;
@@ -117,6 +116,8 @@
{
throw new ConsumerException(CONSUMER_WITH_ID + id + "' doesn't exist!");
}
+
+ log.info(CONSUMER_WITH_ID + id + "' destroyed");
}
public void persistConsumer(WSRPConsumer consumer)
@@ -298,11 +299,7 @@
throw new IllegalArgumentException(CONSUMER_WITH_ID + id + "' doesn't exist!");
}
- // todo: remove WSRPConsumerService
- WSRPConsumerService service = new WSRPConsumerService();
- service.setConsumer(consumer);
- service.setFederatingPortletInvoker(federatingPortletInvoker);
- service.start();
+ federatingPortletInvoker.registerInvoker(id, consumer);
consumer.activate();
}
else
Modified: trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/WSRPConsumerImpl.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/WSRPConsumerImpl.java 2007-03-31 02:00:07 UTC (rev 6891)
+++ trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/WSRPConsumerImpl.java 2007-03-31 05:20:07 UTC (rev 6892)
@@ -463,7 +463,7 @@
{
if (!started)
{
- startService();
+ start();
log.info("Consumer with id '" + getProducerId() + "' activated");
}
producerInfo.setActive(getServiceFactory().isAvailable());
@@ -474,7 +474,7 @@
producerInfo.setActive(false);
if (started)
{
- stopService();
+ stop();
log.info("Consumer with id '" + getProducerId() + "' deactivated");
}
}
Deleted: trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPConsumerService.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPConsumerService.java 2007-03-31 02:00:07 UTC (rev 6891)
+++ trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPConsumerService.java 2007-03-31 05:20:07 UTC (rev 6892)
@@ -1,88 +0,0 @@
-/******************************************************************************
- * JBoss, a division of Red Hat *
- * Copyright 2006, Red Hat Middleware, LLC, and individual *
- * contributors as indicated by the @authors tag. See the *
- * copyright.txt in the distribution for a full listing of *
- * individual contributors. *
- * *
- * This is free software; you can redistribute it and/or modify it *
- * under the terms of the GNU Lesser General Public License as *
- * published by the Free Software Foundation; either version 2.1 of *
- * the License, or (at your option) any later version. *
- * *
- * This software is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
- * Lesser General Public License for more details. *
- * *
- * You should have received a copy of the GNU Lesser General Public *
- * License along with this software; if not, write to the Free *
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org. *
- ******************************************************************************/
-package org.jboss.portal.wsrp.deployment;
-
-import org.jboss.portal.jems.as.system.AbstractJBossService;
-import org.jboss.portal.portlet.PortletInvoker;
-import org.jboss.portal.portlet.federation.FederatingPortletInvoker;
-import org.jboss.portal.wsrp.WSRPConsumer;
-
-/**
- * todo: Remove, since it shouldn't be needed anymore now that we can register to a FederatingPortletInvoker directly
- *
- * @author <a href="mailto:julien@jboss.org">Julien Viet</a>
- * @version $Revision$
- */
-public class WSRPConsumerService extends AbstractJBossService
-{
-
- /** . */
- private WSRPConsumer consumer;
-
- /** . */
- private FederatingPortletInvoker federatingPortletInvoker;
-
- public WSRPConsumer getConsumer()
- {
- return consumer;
- }
-
- public void setConsumer(WSRPConsumer consumer)
- {
- this.consumer = consumer;
- }
-
- public String getId()
- {
- return consumer.getProducerId();
- }
-
- public PortletInvoker getPortletInvoker()
- {
- return consumer;
- }
-
- public FederatingPortletInvoker getFederatingPortletInvoker()
- {
- return federatingPortletInvoker;
- }
-
- public void setFederatingPortletInvoker(FederatingPortletInvoker federatingPortletInvoker)
- {
- this.federatingPortletInvoker = federatingPortletInvoker;
- }
-
- protected void startService() throws Exception
- {
- super.startService();
- federatingPortletInvoker.registerInvoker(getId(), consumer);
- consumer.start();
- }
-
- protected void stopService() throws Exception
- {
- consumer.stop();
- federatingPortletInvoker.unregisterInvoker(getId());
- super.stopService();
- }
-}
Modified: trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPDeployer.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPDeployer.java 2007-03-31 02:00:07 UTC (rev 6891)
+++ trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPDeployer.java 2007-03-31 05:20:07 UTC (rev 6892)
@@ -26,6 +26,7 @@
import org.jboss.deployment.DeploymentInfo;
import org.jboss.deployment.SubDeployerSupport;
import org.jboss.portal.common.xml.NullEntityResolver;
+import org.jboss.portal.wsrp.WSRPConsumer;
import org.jboss.portal.wsrp.consumer.ConsumerRegistry;
import org.jboss.xb.binding.ObjectModelFactory;
import org.jboss.xb.binding.Unmarshaller;
@@ -115,22 +116,22 @@
{
super.start(di);
WSRPDeployment deployment = (WSRPDeployment)di.metaData;
- for (Iterator i = deployment.getServices().iterator(); i.hasNext();)
+ for (Iterator i = deployment.getConsumers().iterator(); i.hasNext();)
{
- WSRPConsumerService service = (WSRPConsumerService)i.next();
- consumerRegistry.activateConsumerWith(service.getId());
+ WSRPConsumer consumer = (WSRPConsumer)i.next();
+ consumerRegistry.activateConsumerWith(consumer.getProducerId());
}
}
public void stop(DeploymentInfo di) throws DeploymentException
{
WSRPDeployment deployment = (WSRPDeployment)di.metaData;
- for (Iterator i = deployment.getServices().iterator(); i.hasNext();)
+ for (Iterator i = deployment.getConsumers().iterator(); i.hasNext();)
{
try
{
- WSRPConsumerService service = (WSRPConsumerService)i.next();
- service.stop();
+ WSRPConsumer consumer = (WSRPConsumer)i.next();
+ consumer.stop();
}
catch (Exception e)
{
Modified: trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPDeployment.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPDeployment.java 2007-03-31 02:00:07 UTC (rev 6891)
+++ trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPDeployment.java 2007-03-31 05:20:07 UTC (rev 6892)
@@ -40,7 +40,7 @@
services = new ArrayList();
}
- public List getServices()
+ public List getConsumers()
{
return services;
}
Modified: trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPDeploymentFactory.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPDeploymentFactory.java 2007-03-31 02:00:07 UTC (rev 6891)
+++ trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPDeploymentFactory.java 2007-03-31 05:20:07 UTC (rev 6892)
@@ -30,7 +30,7 @@
import org.jboss.portal.wsrp.consumer.ProducerInfo;
import org.jboss.portal.wsrp.consumer.RegistrationInfo;
import org.jboss.util.StringPropertyReplacer;
-import org.jboss.xb.binding.ObjectModelFactory;
+import org.jboss.xb.binding.GenericObjectModelFactory;
import org.jboss.xb.binding.UnmarshallingContext;
import org.xml.sax.Attributes;
@@ -40,7 +40,7 @@
* @author <a href="mailto:julien@jboss.org">Julien Viet</a>
* @version $Revision$
*/
-public class WSRPDeploymentFactory implements ObjectModelFactory
+public class WSRPDeploymentFactory implements GenericObjectModelFactory
{
private final Logger log = Logger.getLogger(getClass());
@@ -73,27 +73,74 @@
return root;
}
+ public Object newChild(Object parent, UnmarshallingContext unmarshallingContext, String nsURI, String localName, Attributes attributes)
+ {
+ if (parent instanceof WSRPDeployment)
+ {
+ return newChild((WSRPDeployment)parent, unmarshallingContext, nsURI, localName, attributes);
+ }
+ if (parent instanceof RegistrationInfo)
+ {
+ return newChild((RegistrationInfo)parent, unmarshallingContext, nsURI, localName, attributes);
+ }
+ if (parent instanceof WSRPConsumer)
+ {
+ return newChild((WSRPConsumer)parent, unmarshallingContext, nsURI, localName, attributes);
+ }
+ return null;
+ }
+
+ public void addChild(Object parent, Object child, UnmarshallingContext unmarshallingContext, String nsURI, String localName)
+ {
+ if (parent instanceof RegistrationInfo && child instanceof Property)
+ {
+ addChild((RegistrationInfo)parent, (Property)child, unmarshallingContext, nsURI, localName);
+ }
+ else if (parent instanceof WSRPDeployment && child instanceof WSRPConsumer)
+ {
+ addChild((WSRPDeployment)parent, (WSRPConsumer)child, unmarshallingContext, nsURI, localName);
+ }
+ }
+
+ public void setValue(Object parent, UnmarshallingContext unmarshallingContext, String nsURI, String localName, String value)
+ {
+ if (parent instanceof EndpointConfigurationInfo)
+ {
+ setValue((EndpointConfigurationInfo)parent, unmarshallingContext, nsURI, localName, value);
+ }
+ else if (parent instanceof Property)
+ {
+ setValue((Property)parent, unmarshallingContext, nsURI, localName, value);
+ }
+ else if (parent instanceof RegistrationInfo)
+ {
+ setValue((RegistrationInfo)parent, unmarshallingContext, nsURI, localName, value);
+ }
+ }
+
public Object newChild(WSRPDeployment deployment, UnmarshallingContext nav, String nsURI, String localName,
Attributes attrs)
{
+ if (DEBUG)
+ {
+ System.out.println("newchild deployment " + localName);
+ }
+
if (WSRP_PRODUCER.equals(localName))
{
String id = attrs.getValue("id");
ParameterValidation.throwIllegalArgExceptionIfNullOrEmpty(id, "producer identifier", "Configuring a producer");
- WSRPConsumerService service = new WSRPConsumerService();
-
// check that the consumer doesn't exist in the database first
WSRPConsumer consumer = consumerRegistry.getConsumer(id);
if (consumer != null)
{
- service.setConsumer(consumer);
- String message = "Added consumer for producer '" + service.getId() + "' with status: ";
+ String message = "Added consumer for producer '" + id + "' with status: ";
// if consumer is active, add it to the list of services
if (consumer.getProducerInfo().isActive())
{
- deployment.getServices().add(service);
+ deployment.getConsumers().add(consumer);
message += "active";
}
else
@@ -124,9 +171,7 @@
// consumer didn't exist in the database, so create one and configure it
consumer = consumerRegistry.createConsumer(id, expirationCacheSeconds);
- service.setConsumer(consumer);
-
- return service;
+ return consumer;
}
else
{
@@ -134,7 +179,7 @@
}
}
- public Object newChild(WSRPConsumerService service, UnmarshallingContext nav, String nsURI, String localName,
+ public Object newChild(WSRPConsumer consumer, UnmarshallingContext nav, String nsURI, String localName,
Attributes attrs)
{
if (DEBUG)
@@ -142,7 +187,7 @@
System.out.println("newchild service " + localName);
}
- ProducerInfo prodInfo = service.getConsumer().getProducerInfo();
+ ProducerInfo prodInfo = consumer.getProducerInfo();
if ("endpoint-config".equals(localName) || "endpoint-wsdl-url".equals(localName))
{
@@ -262,27 +307,26 @@
registrationInfo.setRegistrationPropertyValue(property.name, property.value).setLang(property.lang);
}
- public void addChild(WSRPDeployment deployment, WSRPConsumerService service, UnmarshallingContext nav, String nsURI,
+ public void addChild(WSRPDeployment deployment, WSRPConsumer consumer, UnmarshallingContext nav, String nsURI,
String localName)
{
+ ProducerInfo info = consumer.getProducerInfo();
+
if (DEBUG)
{
- System.out.println("addchild deployment service " + localName);
+ System.out.println("adding consumer " + info.getId() + " to deployment - localName: " + localName);
}
-
- ProducerInfo info = service.getConsumer().getProducerInfo();
-
String message;
- if (service.getConsumer().getServiceFactory().isAvailable())
+ if (consumer.getServiceFactory().isAvailable())
{
- message = "Added consumer for producer '" + service.getId() + "' from xml configuration.";
- deployment.getServices().add(service);
+ message = "Added consumer for producer '" + consumer.getProducerId() + "' from xml configuration.";
+ deployment.getConsumers().add(consumer);
}
else
{
message = "There was a problem initializing the WSRP interface for producer '"
- + service.getId() + "'. The consumer will NOT be available.";
+ + consumer.getProducerId() + "'. The consumer will NOT be available.";
info.setActive(false);
}
@@ -294,7 +338,7 @@
catch (Exception e)
{
// if we couldn't update the info, remove it from the list of service to be activated
- deployment.getServices().remove(service);
+ deployment.getConsumers().remove(consumer);
log.info("Couldn't update the ProducerInfo for Consumer '" + info.getId() + "'", e);
return;
}
17 years, 7 months
JBoss Portal SVN: r6891 - in trunk/wsrp/src: main/org/jboss/portal/wsrp/admin/ui and 3 other directories.
by portal-commits@lists.jboss.org
Author: chris.laprun(a)jboss.com
Date: 2007-03-30 22:00:07 -0400 (Fri, 30 Mar 2007)
New Revision: 6891
Modified:
trunk/wsrp/src/main/org/jboss/portal/test/wsrp/other/ProducerInfoTestCase.java
trunk/wsrp/src/main/org/jboss/portal/wsrp/admin/ui/ConsumerBean.java
trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ConsumerRegistry.java
trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ConsumerRegistryService.java
trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ProducerInfo.java
trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/WSRPConsumerImpl.java
trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPConsumerService.java
trunk/wsrp/src/resources/portal-wsrp-sar/conf/consumer/hibernate/domain.hbm.xml
Log:
- Removed use of ConsumerRegistry.getDefaultRegistration as ProducerInfo should now properly deal with not having a RegistrationInfo.
- RegistrationInfo is now again a one-to-one association to ProducerInfo.
- JBPORTAL-715: better handling of RegistrationInfo makes destroyConsumer work :)
- Minimize reliance on external visibility of RegistrationInfo by having getRegistrationContext method public on ProducerInfo.
Modified: trunk/wsrp/src/main/org/jboss/portal/test/wsrp/other/ProducerInfoTestCase.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/test/wsrp/other/ProducerInfoTestCase.java 2007-03-30 23:58:02 UTC (rev 6890)
+++ trunk/wsrp/src/main/org/jboss/portal/test/wsrp/other/ProducerInfoTestCase.java 2007-03-31 02:00:07 UTC (rev 6891)
@@ -128,7 +128,7 @@
assertEquals(1, regBehavior.getCallCount());
assertTrue(info.isRegistered());
assertNotNull(info.getRegistrationInfo());
- assertEquals(RegistrationBehavior.REGISTRATION_HANDLE, info.getRegistrationInfo().getRegistrationContext().getRegistrationHandle());
+ assertEquals(RegistrationBehavior.REGISTRATION_HANDLE, info.getRegistrationContext().getRegistrationHandle());
assertTrue(info.refresh(true));
assertEquals(1, regBehavior.getCallCount());
Modified: trunk/wsrp/src/main/org/jboss/portal/wsrp/admin/ui/ConsumerBean.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/wsrp/admin/ui/ConsumerBean.java 2007-03-30 23:58:02 UTC (rev 6890)
+++ trunk/wsrp/src/main/org/jboss/portal/wsrp/admin/ui/ConsumerBean.java 2007-03-31 02:00:07 UTC (rev 6891)
@@ -147,7 +147,7 @@
public boolean isRequiresRegistration()
{
- return getProducerInfo().getRegistrationInfo().isRequiresRegistration();
+ return getProducerInfo().requiresRegistration();
}
public ProducerInfo getProducerInfo()
Modified: trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ConsumerRegistry.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ConsumerRegistry.java 2007-03-30 23:58:02 UTC (rev 6890)
+++ trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ConsumerRegistry.java 2007-03-31 02:00:07 UTC (rev 6891)
@@ -55,8 +55,6 @@
void updateProducerInfo(ProducerInfo producerInfo);
- RegistrationInfo getDefaultRegistrationInfo();
-
void deactivateConsumerWith(String id) throws ConsumerException;
void registerOrDeregisterConsumerWith(String id, boolean register);
Modified: trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ConsumerRegistryService.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ConsumerRegistryService.java 2007-03-30 23:58:02 UTC (rev 6890)
+++ trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ConsumerRegistryService.java 2007-03-31 02:00:07 UTC (rev 6891)
@@ -58,7 +58,6 @@
private String sessionFactoryJNDIName;
- private RegistrationInfo nullRegistration;
private static final String CONSUMER_WITH_ID = "Consumer with id '";
public FederatingPortletInvoker getFederatingPortletInvoker()
@@ -79,15 +78,12 @@
ProducerInfo info = new ProducerInfo();
info.setId(id);
info.setRegistry(this);
- info.setRegistrationInfo(nullRegistration);
info.setExpirationCacheSeconds(expirationCacheSeconds);
try
{
Session session = sessionFactory.getCurrentSession();
- // make sure we re-attach nullRegistration
- session.refresh(nullRegistration);
session.persist(info);
}
catch (HibernateException e)
@@ -179,14 +175,6 @@
activateConsumerWith(producerInfo.getId());
}
}
-
- nullRegistration = (RegistrationInfo)session.createQuery("from RegistrationInfo where key = (select min(key) from RegistrationInfo)").uniqueResult();
- if (nullRegistration == null)
- {
- nullRegistration = new RegistrationInfo();
- nullRegistration.setRequiresRegistration(false);
- session.persist(nullRegistration);
- }
}
private WSRPConsumer createConsumerFrom(ProducerInfo producerInfo)
@@ -267,11 +255,6 @@
return (WSRPConsumer)consumers.get(id);
}
- public RegistrationInfo getDefaultRegistrationInfo()
- {
- return nullRegistration;
- }
-
public void registerOrDeregisterConsumerWith(String id, boolean register)
{
ParameterValidation.throwIllegalArgExceptionIfNullOrEmpty(id, "Consumer identifier", "registerConsumerWith");
@@ -288,14 +271,10 @@
if (register)
{
consumer.getProducerInfo().register();
-
- log.info(CONSUMER_WITH_ID + id + "' registered");
}
else
{
consumer.getProducerInfo().deregister();
-
- log.info(CONSUMER_WITH_ID + id + "' deregistered");
}
}
catch (PortletInvokerException e)
@@ -319,13 +298,12 @@
throw new IllegalArgumentException(CONSUMER_WITH_ID + id + "' doesn't exist!");
}
+ // todo: remove WSRPConsumerService
WSRPConsumerService service = new WSRPConsumerService();
service.setConsumer(consumer);
service.setFederatingPortletInvoker(federatingPortletInvoker);
service.start();
consumer.activate();
-
- log.info(CONSUMER_WITH_ID + id + "' activated");
}
else
{
@@ -338,8 +316,6 @@
consumer = (WSRPConsumer)invoker;
federatingPortletInvoker.unregisterInvoker(id);
consumer.deactivate();
-
- log.info(CONSUMER_WITH_ID + id + "' deactivated");
}
else
{
Modified: trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ProducerInfo.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ProducerInfo.java 2007-03-30 23:58:02 UTC (rev 6890)
+++ trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/ProducerInfo.java 2007-03-31 02:00:07 UTC (rev 6891)
@@ -166,6 +166,12 @@
return persistentRegistrationInfo != null && persistentRegistrationInfo.isRegistrationValid();
}
+ public boolean requiresRegistration()
+ {
+ return persistentRegistrationInfo != null && persistentRegistrationInfo.isRequiresRegistration();
+
+ }
+
/**
* Determines whether the associated consumer is active.
*
@@ -250,7 +256,7 @@
else
{
log.debug("Registration not required");
- setRegistrationInfo(registry.getDefaultRegistrationInfo());
+// setRegistrationInfo(registry.getDefaultRegistrationInfo());
setServiceDescriptionRequest(getUnregisteredServiceDescriptionRequest());
extractOfferedPortlets(serviceDescription);
return true;
@@ -522,7 +528,7 @@
return gsd;
}
- private RegistrationContext getRegistrationContext()
+ public RegistrationContext getRegistrationContext()
{
return persistentRegistrationInfo == null ? null : persistentRegistrationInfo.getRegistrationContext();
}
@@ -623,7 +629,8 @@
}
persistentRegistrationInfo.setRegistrationContext(registrationContext);
- log.info("Successfully registered with handle: '" + registrationContext.getRegistrationHandle() + "'");
+ log.info("Conusmer with id '" + persistentId + "' successfully registered with handle: '"
+ + registrationContext.getRegistrationHandle() + "'");
return true;
}
catch (Exception e)
@@ -654,6 +661,7 @@
persistentEndpointInfo.getRegistrationService().deregister(getRegistrationContext());
persistentRegistrationInfo.resetRegistration();
registry.updateProducerInfo(this);
+ log.info("Consumer with id '" + persistentId + "' deregistered.");
}
catch (Exception e)
{
Modified: trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/WSRPConsumerImpl.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/WSRPConsumerImpl.java 2007-03-30 23:58:02 UTC (rev 6890)
+++ trunk/wsrp/src/main/org/jboss/portal/wsrp/consumer/WSRPConsumerImpl.java 2007-03-31 02:00:07 UTC (rev 6891)
@@ -443,7 +443,7 @@
RegistrationContext getRegistrationContext()
{
- return producerInfo.getRegistrationInfo().getRegistrationContext();
+ return producerInfo.getRegistrationContext();
}
// Session information access ***************************************************************************************
@@ -464,6 +464,7 @@
if (!started)
{
startService();
+ log.info("Consumer with id '" + getProducerId() + "' activated");
}
producerInfo.setActive(getServiceFactory().isAvailable());
}
@@ -474,6 +475,7 @@
if (started)
{
stopService();
+ log.info("Consumer with id '" + getProducerId() + "' deactivated");
}
}
@@ -540,8 +542,7 @@
public void releaseSessions(String[] sessionIds) throws PortletInvokerException
{
//todo: move to SessionHandler?
- ReleaseSessions releaseSessions =
- WSRPTypeFactory.createReleaseSessions(producerInfo.getRegistrationInfo().getRegistrationContext(), sessionIds);
+ ReleaseSessions releaseSessions = WSRPTypeFactory.createReleaseSessions(getRegistrationContext(), sessionIds);
try
{
Modified: trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPConsumerService.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPConsumerService.java 2007-03-30 23:58:02 UTC (rev 6890)
+++ trunk/wsrp/src/main/org/jboss/portal/wsrp/deployment/WSRPConsumerService.java 2007-03-31 02:00:07 UTC (rev 6891)
@@ -28,6 +28,8 @@
import org.jboss.portal.wsrp.WSRPConsumer;
/**
+ * todo: Remove, since it shouldn't be needed anymore now that we can register to a FederatingPortletInvoker directly
+ *
* @author <a href="mailto:julien@jboss.org">Julien Viet</a>
* @version $Revision$
*/
Modified: trunk/wsrp/src/resources/portal-wsrp-sar/conf/consumer/hibernate/domain.hbm.xml
===================================================================
--- trunk/wsrp/src/resources/portal-wsrp-sar/conf/consumer/hibernate/domain.hbm.xml 2007-03-30 23:58:02 UTC (rev 6890)
+++ trunk/wsrp/src/resources/portal-wsrp-sar/conf/consumer/hibernate/domain.hbm.xml 2007-03-31 02:00:07 UTC (rev 6891)
@@ -43,6 +43,7 @@
<many-to-one name="registrationInfo"
column="REGISTRATION_ID"
class="org.jboss.portal.wsrp.consumer.RegistrationInfo"
+ unique="true"
not-null="false"
cascade="all"
lazy="false"/>
17 years, 7 months
JBoss Portal SVN: r6890 - in trunk: wsrp and 2 other directories.
by portal-commits@lists.jboss.org
Author: chris.laprun(a)jboss.com
Date: 2007-03-30 19:58:02 -0400 (Fri, 30 Mar 2007)
New Revision: 6890
Modified:
trunk/portlet/src/main/org/jboss/portal/portlet/PortletContext.java
trunk/portlet/src/main/org/jboss/portal/portlet/StatefulPortletContext.java
trunk/wsrp/build.xml
trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/PortletManagementBehavior.java
trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/RegistrationBehavior.java
trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/ServiceDescriptionBehavior.java
trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/TestProducerBehavior.java
trunk/wsrp/src/main/org/jboss/portal/test/wsrp/other/ProducerInfoTestCase.java
Log:
- More ProducerInfo tests.
- Added toString and hashCode implementation on PortletContext and StatefulPortletContext.
Modified: trunk/portlet/src/main/org/jboss/portal/portlet/PortletContext.java
===================================================================
--- trunk/portlet/src/main/org/jboss/portal/portlet/PortletContext.java 2007-03-30 23:45:46 UTC (rev 6889)
+++ trunk/portlet/src/main/org/jboss/portal/portlet/PortletContext.java 2007-03-30 23:58:02 UTC (rev 6890)
@@ -44,6 +44,28 @@
this.id = id;
}
+
+ public boolean equals(Object o)
+ {
+ if (this == o)
+ {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass())
+ {
+ return false;
+ }
+
+ PortletContext that = (PortletContext)o;
+
+ return id.equals(that.id);
+ }
+
+ public int hashCode()
+ {
+ return id.hashCode();
+ }
+
public String getId()
{
return id;
Modified: trunk/portlet/src/main/org/jboss/portal/portlet/StatefulPortletContext.java
===================================================================
--- trunk/portlet/src/main/org/jboss/portal/portlet/StatefulPortletContext.java 2007-03-30 23:45:46 UTC (rev 6889)
+++ trunk/portlet/src/main/org/jboss/portal/portlet/StatefulPortletContext.java 2007-03-30 23:58:02 UTC (rev 6890)
@@ -24,6 +24,8 @@
import org.jboss.portal.common.util.ParameterValidation;
+import java.util.Arrays;
+
/**
* @author <a href="mailto:julien@jboss.org">Julien Viet</a>
* @author <a href="mailto:chris.laprun@jboss.com">Chris Laprun</a>
@@ -45,6 +47,34 @@
this.marshalledState = marshalledState;
}
+
+ public boolean equals(Object o)
+ {
+ if (this == o)
+ {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass())
+ {
+ return false;
+ }
+ if (!super.equals(o))
+ {
+ return false;
+ }
+
+ StatefulPortletContext that = (StatefulPortletContext)o;
+
+ return Arrays.equals(marshalledState, that.marshalledState);
+ }
+
+ public int hashCode()
+ {
+ int result = super.hashCode();
+ result = 31 * result + (marshalledState != null ? marshalledState.hashCode() : 0);
+ return result;
+ }
+
public byte[] getState()
{
return marshalledState;
Modified: trunk/wsrp/build.xml
===================================================================
--- trunk/wsrp/build.xml 2007-03-30 23:45:46 UTC (rev 6889)
+++ trunk/wsrp/build.xml 2007-03-30 23:58:02 UTC (rev 6890)
@@ -424,8 +424,8 @@
<target name="package-other-test" description="Generates the test artifacts" depends="compile">
<jar jarfile="${build.lib.test}/test-other-lib.jar">
<fileset dir="${build.classes}/">
- <include name="org/jboss/portal/test/wsrp/framework/support/*.class"/>
- <include name="org/jboss/portal/test/wsrp/other/*TestCase.class"/>
+ <include name="org/jboss/portal/test/wsrp/framework/**"/>
+ <include name="org/jboss/portal/test/wsrp/other/*.class"/>
<include name="org/jboss/portal/test/wsrp/handler/*.class"/>
</fileset>
</jar>
@@ -752,6 +752,7 @@
<test todir="${test.reports}" name="org.jboss.portal.test.wsrp.other.WSRPPortletURLTestCase"/>
<test todir="${test.reports}" name="org.jboss.portal.test.wsrp.other.UserContextConverterTestCase"/>
<test todir="${test.reports}" name="org.jboss.portal.test.wsrp.other.EndpointConfigurationInfoTestCase"/>
+ <test todir="${test.reports}" name="org.jboss.portal.test.wsrp.other.ProducerInfoTestCase"/>
<test todir="${test.reports}" name="org.jboss.portal.test.wsrp.handler.RequestHeaderClientHandlerTestCase"/>
</x-test>
<x-sysproperty>
Modified: trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/PortletManagementBehavior.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/PortletManagementBehavior.java 2007-03-30 23:45:46 UTC (rev 6889)
+++ trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/PortletManagementBehavior.java 2007-03-30 23:58:02 UTC (rev 6890)
@@ -58,6 +58,7 @@
throws AccessDeniedFault, InvalidHandleFault, InvalidUserCategoryFault, InconsistentParametersFault,
MissingParametersFault, InvalidRegistrationFault, OperationFailedFault, RemoteException
{
+ incrementCallCount();
return null;
}
@@ -65,6 +66,7 @@
throws InvalidUserCategoryFault, AccessDeniedFault, OperationFailedFault, InvalidHandleFault,
InvalidRegistrationFault, InconsistentParametersFault, MissingParametersFault, RemoteException
{
+ incrementCallCount();
return null;
}
@@ -72,6 +74,7 @@
throws InconsistentParametersFault, MissingParametersFault, InvalidRegistrationFault, OperationFailedFault,
RemoteException
{
+ incrementCallCount();
return null;
}
@@ -79,6 +82,7 @@
throws OperationFailedFault, InvalidHandleFault, MissingParametersFault, InconsistentParametersFault,
InvalidUserCategoryFault, AccessDeniedFault, InvalidRegistrationFault, RemoteException
{
+ incrementCallCount();
return null;
}
@@ -86,6 +90,7 @@
throws InvalidHandleFault, MissingParametersFault, InvalidRegistrationFault, AccessDeniedFault,
OperationFailedFault, InconsistentParametersFault, InvalidUserCategoryFault, RemoteException
{
+ incrementCallCount();
return null;
}
@@ -93,6 +98,7 @@
throws MissingParametersFault, InconsistentParametersFault, InvalidUserCategoryFault, InvalidRegistrationFault,
AccessDeniedFault, InvalidHandleFault, OperationFailedFault, RemoteException
{
+ incrementCallCount();
return WSRPTypeFactory.createPortletPropertyDescriptionResponse(null);
}
}
Modified: trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/RegistrationBehavior.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/RegistrationBehavior.java 2007-03-30 23:45:46 UTC (rev 6889)
+++ trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/RegistrationBehavior.java 2007-03-30 23:58:02 UTC (rev 6890)
@@ -23,6 +23,7 @@
package org.jboss.portal.test.wsrp.framework;
+import org.jboss.portal.wsrp.WSRPTypeFactory;
import org.jboss.portal.wsrp.core.InvalidRegistrationFault;
import org.jboss.portal.wsrp.core.MissingParametersFault;
import org.jboss.portal.wsrp.core.ModifyRegistration;
@@ -43,21 +44,26 @@
*/
public class RegistrationBehavior extends TestProducerBehavior implements WSRP_v1_Registration_PortType
{
+ public static final String REGISTRATION_HANDLE = "registration";
+
public RegistrationContext register(RegistrationData register)
throws MissingParametersFault, OperationFailedFault, RemoteException
{
- return null;
+ incrementCallCount();
+ return WSRPTypeFactory.createRegistrationContext(REGISTRATION_HANDLE);
}
public ReturnAny deregister(RegistrationContext deregister)
throws OperationFailedFault, InvalidRegistrationFault, RemoteException
{
+ incrementCallCount();
return null;
}
public RegistrationState modifyRegistration(ModifyRegistration modifyRegistration)
throws MissingParametersFault, OperationFailedFault, InvalidRegistrationFault, RemoteException
{
+ incrementCallCount();
return null;
}
}
Modified: trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/ServiceDescriptionBehavior.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/ServiceDescriptionBehavior.java 2007-03-30 23:45:46 UTC (rev 6889)
+++ trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/ServiceDescriptionBehavior.java 2007-03-30 23:58:02 UTC (rev 6890)
@@ -57,6 +57,7 @@
public ServiceDescription getServiceDescription(GetServiceDescription getServiceDescription) throws
OperationFailedFault, InvalidRegistrationFault, RemoteException
{
+ incrementCallCount();
return serviceDescription;
}
@@ -75,7 +76,7 @@
return DEFAULT_SERVICE_DESCRIPTION;
}
- void addPortletDescription(PortletDescription portletDescription)
+ public void addPortletDescription(PortletDescription portletDescription)
{
PortletDescription[] initial = serviceDescription.getOfferedPortlets();
if (initial == null || initial.length == 0)
Modified: trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/TestProducerBehavior.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/TestProducerBehavior.java 2007-03-30 23:45:46 UTC (rev 6889)
+++ trunk/wsrp/src/main/org/jboss/portal/test/wsrp/framework/TestProducerBehavior.java 2007-03-30 23:58:02 UTC (rev 6890)
@@ -50,8 +50,13 @@
callCount++;
}
- protected PortletDescription createPortletDescription(String portletHandle, String suffix)
+ public int getCallCount()
{
+ return callCount;
+ }
+
+ public PortletDescription createPortletDescription(String portletHandle, String suffix)
+ {
PortletDescription portletDesc = new PortletDescription();
portletDesc.setPortletHandle(portletHandle);
portletDesc.setMarkupTypes(new MarkupType[]{new MarkupType("text/html", new String[]{WSRPConstants.NORMAL_WINDOW_STATE},
Modified: trunk/wsrp/src/main/org/jboss/portal/test/wsrp/other/ProducerInfoTestCase.java
===================================================================
--- trunk/wsrp/src/main/org/jboss/portal/test/wsrp/other/ProducerInfoTestCase.java 2007-03-30 23:45:46 UTC (rev 6889)
+++ trunk/wsrp/src/main/org/jboss/portal/test/wsrp/other/ProducerInfoTestCase.java 2007-03-30 23:58:02 UTC (rev 6890)
@@ -24,12 +24,28 @@
package org.jboss.portal.test.wsrp.other;
import junit.framework.TestCase;
+import org.jboss.portal.portlet.Portlet;
+import org.jboss.portal.portlet.PortletContext;
+import org.jboss.portal.test.wsrp.framework.PortletManagementBehavior;
+import org.jboss.portal.test.wsrp.framework.RegistrationBehavior;
import org.jboss.portal.test.wsrp.framework.ServiceDescriptionBehavior;
import org.jboss.portal.test.wsrp.framework.support.BehaviorBackedServiceFactory;
import org.jboss.portal.test.wsrp.framework.support.MockConsumerRegistry;
+import org.jboss.portal.wsrp.WSRPTypeFactory;
import org.jboss.portal.wsrp.consumer.EndpointConfigurationInfo;
import org.jboss.portal.wsrp.consumer.ProducerInfo;
+import org.jboss.portal.wsrp.core.AccessDeniedFault;
+import org.jboss.portal.wsrp.core.GetPortletDescription;
+import org.jboss.portal.wsrp.core.InconsistentParametersFault;
+import org.jboss.portal.wsrp.core.InvalidHandleFault;
+import org.jboss.portal.wsrp.core.InvalidRegistrationFault;
+import org.jboss.portal.wsrp.core.InvalidUserCategoryFault;
+import org.jboss.portal.wsrp.core.MissingParametersFault;
+import org.jboss.portal.wsrp.core.OperationFailedFault;
+import org.jboss.portal.wsrp.core.PortletDescriptionResponse;
+import java.rmi.RemoteException;
+
/**
* @author <a href="mailto:chris.laprun@jboss.com">Chris Laprun</a>
* @version $Revision$
@@ -52,20 +68,80 @@
public void testRefreshAndCache() throws Exception
{
- serviceFactory.getRegistry().setServiceDescriptionBehavior(new ServiceDescriptionBehavior());
+ ServiceDescriptionBehavior behavior = new ServiceDescriptionBehavior();
+ serviceFactory.getRegistry().setServiceDescriptionBehavior(behavior);
assertNull(info.getExpirationCacheSeconds());
assertTrue(info.refresh(false));
assertTrue(info.refresh(false));
+ assertEquals(2, behavior.getCallCount());
info.setExpirationCacheSeconds(new Integer(1));
assertEquals(new Integer(1), info.getExpirationCacheSeconds());
assertTrue(info.refresh(false));
assertFalse(info.refresh(false));
+ assertEquals(3, behavior.getCallCount());
// wait for cache expiration
Thread.sleep(1500);
assertTrue(info.refresh(false));
+ assertFalse(info.refresh(false));
+ assertTrue(info.refresh(true));
+ assertEquals(5, behavior.getCallCount());
}
+
+ public void testGetPortlet() throws Exception
+ {
+ ServiceDescriptionBehavior behavior = new ServiceDescriptionBehavior();
+ behavior.addPortletDescription(behavior.createPortletDescription("test", null));
+ serviceFactory.getRegistry().setServiceDescriptionBehavior(behavior);
+
+ PortletContext portletContext = PortletContext.createPortletContext("test");
+ Portlet portlet = info.getPortlet(portletContext);
+ assertNotNull(portlet);
+ assertEquals(portletContext, portlet.getContext());
+
+ // test2 is not in the service description, so it should be looked up via Portlet Management...
+ portletContext = PortletContext.createPortletContext("test2");
+ // add portlet management behavior
+ TestPortletManagementBehavior pmBehavior = new TestPortletManagementBehavior();
+ serviceFactory.getRegistry().setPortletManagementBehavior(pmBehavior);
+ portlet = info.getPortlet(portletContext);
+ assertEquals(1, pmBehavior.getCallCount());
+ assertNotNull(portlet);
+ assertEquals(portletContext, portlet.getContext());
+ }
+
+ public void testRefreshAndRegistration() throws Exception
+ {
+ assertFalse(info.isRegistered());
+ assertNull(info.getRegistrationInfo());
+
+ ServiceDescriptionBehavior sd = new ServiceDescriptionBehavior();
+ sd.setRequiresRegistration(true);
+ serviceFactory.getRegistry().setServiceDescriptionBehavior(sd);
+ RegistrationBehavior regBehavior = new RegistrationBehavior();
+ serviceFactory.getRegistry().setRegistrationBehavior(regBehavior);
+
+ assertTrue(info.refresh(false));
+ assertEquals(1, regBehavior.getCallCount());
+ assertTrue(info.isRegistered());
+ assertNotNull(info.getRegistrationInfo());
+ assertEquals(RegistrationBehavior.REGISTRATION_HANDLE, info.getRegistrationInfo().getRegistrationContext().getRegistrationHandle());
+
+ assertTrue(info.refresh(true));
+ assertEquals(1, regBehavior.getCallCount());
+ }
+
+ private static class TestPortletManagementBehavior extends PortletManagementBehavior
+ {
+ public PortletDescriptionResponse getPortletDescription(GetPortletDescription getPortletDescription)
+ throws AccessDeniedFault, InvalidHandleFault, InvalidUserCategoryFault, InconsistentParametersFault,
+ MissingParametersFault, InvalidRegistrationFault, OperationFailedFault, RemoteException
+ {
+ incrementCallCount();
+ return WSRPTypeFactory.createPortletDescriptionResponse(createPortletDescription("test2", null));
+ }
+ }
}
17 years, 7 months
JBoss Portal SVN: r6888 - trunk/server/src/main/org/jboss/portal/server/servlet.
by portal-commits@lists.jboss.org
Author: julien(a)jboss.com
Date: 2007-03-30 18:19:37 -0400 (Fri, 30 Mar 2007)
New Revision: 6888
Modified:
trunk/server/src/main/org/jboss/portal/server/servlet/PortalServlet.java
Log:
- inline trivial method in portal servlet
- removed useless import
Modified: trunk/server/src/main/org/jboss/portal/server/servlet/PortalServlet.java
===================================================================
--- trunk/server/src/main/org/jboss/portal/server/servlet/PortalServlet.java 2007-03-30 21:03:45 UTC (rev 6887)
+++ trunk/server/src/main/org/jboss/portal/server/servlet/PortalServlet.java 2007-03-30 22:19:37 UTC (rev 6888)
@@ -55,7 +55,6 @@
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
-import java.util.StringTokenizer;
/**
* The main servlet of the portal. This servlet must be properly configured with the servlet mapping style it is
@@ -73,9 +72,6 @@
/** . */
private static final int POST_METHOD = 1;
- /** The serialVersionUID */
- private static final long serialVersionUID = -4311718750030972662L;
-
/** Describes a default servlet mapping. */
private static final int DEFAULT_SERVLET_MAPPING = 0;
@@ -278,7 +274,7 @@
portalContextPath = URLTools.decodeXWWWFormURL(portalContextPath);
//
- URLContext urlContext = parseURLContext(req);
+ URLContext urlContext = URLContext.newInstance(req.isSecure(), req.getRemoteUser() != null);
// ***************
// ***************
@@ -433,10 +429,4 @@
return false;
}
}
-
-
- private URLContext parseURLContext(HttpServletRequest req)
- {
- return URLContext.newInstance(req.isSecure(), req.getRemoteUser() != null);
- }
}
17 years, 7 months
JBoss Portal SVN: r6887 - trunk/cms/src/main/org/jboss/portal/cms/hibernate/state.
by portal-commits@lists.jboss.org
Author: sohil.shah(a)jboss.com
Date: 2007-03-30 17:03:45 -0400 (Fri, 30 Mar 2007)
New Revision: 6887
Modified:
trunk/cms/src/main/org/jboss/portal/cms/hibernate/state/HibernatePersistenceManager.java
trunk/cms/src/main/org/jboss/portal/cms/hibernate/state/JBossCachePersistenceManager.java
Log:
fixing large file support issue in HibernatePersistenceManager
Modified: trunk/cms/src/main/org/jboss/portal/cms/hibernate/state/HibernatePersistenceManager.java
===================================================================
--- trunk/cms/src/main/org/jboss/portal/cms/hibernate/state/HibernatePersistenceManager.java 2007-03-30 17:20:07 UTC (rev 6886)
+++ trunk/cms/src/main/org/jboss/portal/cms/hibernate/state/HibernatePersistenceManager.java 2007-03-30 21:03:45 UTC (rev 6887)
@@ -69,7 +69,8 @@
{
/** Logger instance */
- private static Logger log = Logger.getLogger(HibernatePersistenceManager.class);
+ private static Logger log = Logger
+ .getLogger(HibernatePersistenceManager.class);
protected static final String SCHEMA_OBJECT_PREFIX_VARIABLE = "${schemaObjectPrefix}";
@@ -120,7 +121,10 @@
/** file system where BLOB data is stored (if <code>externalBLOBs==true</code>) */
protected FileSystem blobFS;
- /** BLOBStore that manages BLOB data in the file system (if <code>externalBLOBs==true</code>) */
+ /**
+ * BLOBStore that manages BLOB data in the file system (if
+ * <code>externalBLOBs==true</code>)
+ */
protected BLOBStore blobStore;
/** Creates a new <code>SimpleDbPersistenceManager</code> instance. */
@@ -131,10 +135,10 @@
initialized = false;
}
- //---------------------------------------------------< PersistenceManager >
+ // ---------------------------------------------------< PersistenceManager >
/**
- *
+ *
*/
public void init(PMContext context) throws Exception
{
@@ -143,30 +147,39 @@
throw new IllegalStateException("already initialized");
}
- //hibernateSessionFactory = HibernateUtil.getSessionFactory(jndiName);
+ // hibernateSessionFactory = HibernateUtil.getSessionFactory(jndiName);
org.jboss.portal.cms.hibernate.state.Tools.init(jndiName);
- hibernateSessionFactory = org.jboss.portal.cms.hibernate.state.Tools.getSessionFactory();
+ hibernateSessionFactory = org.jboss.portal.cms.hibernate.state.Tools
+ .getSessionFactory();
- nodeBinValSelect = "from " + schemaObjectPrefix + "BinVal where BINVAL_ID = ?";
+ nodeBinValSelect = "from " + schemaObjectPrefix
+ + "BinVal where BINVAL_ID = ?";
nodeStateSelect = "from " + schemaObjectPrefix + "Node where NODE_ID = ?";
- nodeStateSelectData = "select data from " + schemaObjectPrefix + "Node where NODE_ID = ?";
- nodeStateSelectExist = "select 1 from " + schemaObjectPrefix + "Node where NODE_ID = ?";
+ nodeStateSelectData = "select data from " + schemaObjectPrefix
+ + "Node where NODE_ID = ?";
+ nodeStateSelectExist = "select 1 from " + schemaObjectPrefix
+ + "Node where NODE_ID = ?";
- propertyStateSelect = "from " + schemaObjectPrefix + "Prop where PROP_ID = ?";
- propertyStateSelectData = "select data from " + schemaObjectPrefix + "Prop where PROP_ID = ?";
- propertyStateSelectExist = "select 1 from " + schemaObjectPrefix + "Prop where PROP_ID = ?";
+ propertyStateSelect = "from " + schemaObjectPrefix
+ + "Prop where PROP_ID = ?";
+ propertyStateSelectData = "select data from " + schemaObjectPrefix
+ + "Prop where PROP_ID = ?";
+ propertyStateSelectExist = "select 1 from " + schemaObjectPrefix
+ + "Prop where PROP_ID = ?";
- nodeReferenceSelect = "from " + schemaObjectPrefix + "Refs where NODE_ID = ?";
- nodeReferenceSelectData = "select data from " + schemaObjectPrefix + "Refs where NODE_ID = ?";
- nodeReferenceSelectExist = "select 1 from " + schemaObjectPrefix + "Refs where NODE_ID = ?";
+ nodeReferenceSelect = "from " + schemaObjectPrefix
+ + "Refs where NODE_ID = ?";
+ nodeReferenceSelectData = "select data from " + schemaObjectPrefix
+ + "Refs where NODE_ID = ?";
+ nodeReferenceSelectExist = "select 1 from " + schemaObjectPrefix
+ + "Refs where NODE_ID = ?";
-
if (externalBLOBs)
{
/**
- * store BLOBs in local file system in a sub directory
- * of the workspace home directory
+ * store BLOBs in local file system in a sub directory of the workspace
+ * home directory
*/
LocalFileSystem blobFS = new LocalFileSystem();
blobFS.setRoot(new File(context.getHomeDir(), "blobs"));
@@ -181,18 +194,21 @@
*/
blobStore = new DbBLOBStore();
- blobSelect = "from " + schemaObjectPrefix + "BinVal where BINVAL_ID = ?";
- blobSelectData = "select data from " + schemaObjectPrefix + "BinVal where BINVAL_ID = ?";
- blobSelectExist = "select 1 from " + schemaObjectPrefix + "BinVal where BINVAL_ID = ?";
+ blobSelect = "from " + schemaObjectPrefix
+ + "BinVal where BINVAL_ID = ?";
+ blobSelectData = "select data from " + schemaObjectPrefix
+ + "BinVal where BINVAL_ID = ?";
+ blobSelectExist = "select 1 from " + schemaObjectPrefix
+ + "BinVal where BINVAL_ID = ?";
}
initialized = true;
}
- //---------------------------------------------------< PersistenceManager >
+ // ---------------------------------------------------< PersistenceManager >
/**
- *
+ *
*/
public void close() throws Exception
{
@@ -248,7 +264,7 @@
public void setSchemaObjectPrefix(String schemaObjectPrefix)
{
- this.schemaObjectPrefix = schemaObjectPrefix;//.toUpperCase();
+ this.schemaObjectPrefix = schemaObjectPrefix;// .toUpperCase();
}
public boolean isExternalBLOBs()
@@ -266,7 +282,7 @@
this.externalBLOBs = Boolean.valueOf(externalBLOBs).booleanValue();
}
- //---------------------------------------------------< PersistenceManager >
+ // ---------------------------------------------------< PersistenceManager >
public void store(ChangeLog changeLog) throws ItemStateException
{
@@ -306,46 +322,46 @@
Iterator iter = changeLog.deletedStates();
while (iter.hasNext())
{
- ItemState state = (ItemState)iter.next();
+ ItemState state = (ItemState) iter.next();
if (state.isNode())
{
- destroy((NodeState)state);
+ destroy((NodeState) state);
}
else
{
- destroy((PropertyState)state);
+ destroy((PropertyState) state);
}
}
iter = changeLog.addedStates();
while (iter.hasNext())
{
- ItemState state = (ItemState)iter.next();
+ ItemState state = (ItemState) iter.next();
if (state.isNode())
{
- store((NodeState)state);
+ store((NodeState) state);
}
else
{
- store((PropertyState)state);
+ store((PropertyState) state);
}
}
iter = changeLog.modifiedStates();
while (iter.hasNext())
{
- ItemState state = (ItemState)iter.next();
+ ItemState state = (ItemState) iter.next();
if (state.isNode())
{
- update((NodeState)state);
+ update((NodeState) state);
}
else
{
- update((PropertyState)state);
+ update((PropertyState) state);
}
}
iter = changeLog.modifiedRefs();
while (iter.hasNext())
{
- NodeReferences refs = (NodeReferences)iter.next();
+ NodeReferences refs = (NodeReferences) iter.next();
if (refs.hasReferences())
{
store(refs);
@@ -360,7 +376,8 @@
}
}
- public NodeState load(NodeId id) throws NoSuchItemStateException, ItemStateException
+ public NodeState load(NodeId id) throws NoSuchItemStateException,
+ ItemStateException
{
if (!initialized)
{
@@ -373,13 +390,14 @@
InputStream in = null;
try
{
- List rs = session.createQuery(nodeStateSelectData).setString(0, id.toString()).list();
+ List rs = session.createQuery(nodeStateSelectData).setString(0,
+ id.toString()).list();
Iterator iter = rs.iterator();
- //java.sql.Blob blob = (java.sql.Blob) iter.next();
- //in = blob.getBinaryStream();
- byte[] data = (byte[])iter.next();
+ // java.sql.Blob blob = (java.sql.Blob) iter.next();
+ // in = blob.getBinaryStream();
+ byte[] data = (byte[]) iter.next();
in = new java.io.ByteArrayInputStream(data);
NodeState state = createNew(id);
@@ -393,7 +411,7 @@
tx.rollback();
if (e instanceof NoSuchItemStateException)
{
- throw(NoSuchItemStateException)e;
+ throw (NoSuchItemStateException) e;
}
String msg = "failed to read node state: " + id;
log.error(msg, e);
@@ -405,7 +423,8 @@
}
}
- public PropertyState load(PropertyId id) throws NoSuchItemStateException, ItemStateException
+ public PropertyState load(PropertyId id) throws NoSuchItemStateException,
+ ItemStateException
{
if (!initialized)
{
@@ -418,15 +437,15 @@
InputStream in = null;
try
{
- List rs = session.createQuery(propertyStateSelectData).setCacheable(true).setString(0, id.toString()).list();
+ List rs = session.createQuery(propertyStateSelectData).setCacheable(
+ true).setString(0, id.toString()).list();
Iterator iter = rs.iterator();
- //java.sql.Blob blob = (java.sql.Blob) iter.next();
- //in = blob.getBinaryStream();
- byte[] data = (byte[])iter.next();
+ // java.sql.Blob blob = (java.sql.Blob) iter.next();
+ // in = blob.getBinaryStream();
+ byte[] data = (byte[]) iter.next();
in = new java.io.ByteArrayInputStream(data);
-
PropertyState state = createNew(id);
Serializer.deserialize(state, in, blobStore);
Tools.safeClose(in);
@@ -438,7 +457,7 @@
tx.rollback();
if (e instanceof NoSuchItemStateException)
{
- throw(NoSuchItemStateException)e;
+ throw (NoSuchItemStateException) e;
}
String msg = "failed to read property state: " + id.toString();
log.error(msg, e);
@@ -451,9 +470,10 @@
}
/**
- *
+ *
*/
- public NodeReferences load(NodeReferencesId targetId) throws NoSuchItemStateException, ItemStateException
+ public NodeReferences load(NodeReferencesId targetId)
+ throws NoSuchItemStateException, ItemStateException
{
if (!initialized)
{
@@ -465,13 +485,14 @@
InputStream in = null;
try
{
- List rs = session.createQuery(nodeReferenceSelectData).setCacheable(true).setString(0, targetId.toString()).list();
+ List rs = session.createQuery(nodeReferenceSelectData).setCacheable(
+ true).setString(0, targetId.toString()).list();
Iterator iter = rs.iterator();
if (!iter.hasNext())
{
throw new NoSuchItemStateException(targetId.toString());
}
- byte[] data = (byte[])iter.next();
+ byte[] data = (byte[]) iter.next();
in = new java.io.ByteArrayInputStream(data);
NodeReferences refs = new NodeReferences(targetId);
@@ -485,7 +506,7 @@
tx.rollback();
if (e instanceof NoSuchItemStateException)
{
- throw(NoSuchItemStateException)e;
+ throw (NoSuchItemStateException) e;
}
String msg = "failed to read references: " + targetId;
log.error(msg, e);
@@ -511,15 +532,19 @@
try
{
Serializer.serialize(state, out);
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- VersionNode versionNode = new VersionNode(state.getId().toString(), out.toByteArray());
+ VersionNode versionNode = new VersionNode(state.getId().toString(),
+ out.toByteArray());
session.save(versionNode);
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- WSPNode wspNode = new WSPNode(state.getId().toString(), out.toByteArray());
+ WSPNode wspNode = new WSPNode(state.getId().toString(), out
+ .toByteArray());
session.save(wspNode);
}
}
@@ -546,7 +571,7 @@
private Blob createBlob(byte[] bytes)
{
return Hibernate.createBlob(bytes);
-// return new ByteArrayBlob(bytes);
+ // return new ByteArrayBlob(bytes);
}
private void store(NodeReferences refs) throws ItemStateException
@@ -563,17 +588,20 @@
try
{
Serializer.serialize(refs, out);
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- VersionRefs versionRefs = new VersionRefs(refs.getTargetId().toString(), out
- .toByteArray());
+ VersionRefs versionRefs = new VersionRefs(refs.getTargetId()
+ .toString(), out.toByteArray());
session.save(versionRefs);
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- WSPRefs wspRefs = new WSPRefs(refs.getTargetId().toString(), out.toByteArray());
+ WSPRefs wspRefs = new WSPRefs(refs.getTargetId().toString(), out
+ .toByteArray());
session.save(wspRefs);
}
}
@@ -598,12 +626,13 @@
}
/**
- * <p/>
- * This method uses shared <code>PreparedStatement</code>s which must be executed strictly sequentially. Because this
- * method synchronizes on the persistence manager instance there is no need to synchronize on the shared statement.
- * If the method would not be sychronized the shared statements would have to be synchronized.
+ * <p/> This method uses shared <code>PreparedStatement</code>s which must
+ * be executed strictly sequentially. Because this method synchronizes on the
+ * persistence manager instance there is no need to synchronize on the shared
+ * statement. If the method would not be sychronized the shared statements
+ * would have to be synchronized.
*/
- // public synchronized void store(PropertyState state)
+ // public synchronized void store(PropertyState state)
private void store(PropertyState state) throws ItemStateException
{
if (!initialized)
@@ -619,14 +648,18 @@
{
Serializer.serialize(state, out, blobStore);
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- VersionProp versionProp = new VersionProp(state.getId().toString(), out.toByteArray());
+ VersionProp versionProp = new VersionProp(state.getId().toString(),
+ out.toByteArray());
session.save(versionProp);
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- WSPProp wspProp = new WSPProp(state.getId().toString(), out.toByteArray());
+ WSPProp wspProp = new WSPProp(state.getId().toString(), out
+ .toByteArray());
session.save(wspProp);
}
}
@@ -666,20 +699,22 @@
Serializer.serialize(state, out);
Query query = session.createQuery(nodeStateSelect).setCacheable(true);
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
query.setString(0, state.getId().toString());
- VersionNode versionNode = (VersionNode)query.uniqueResult();
+ VersionNode versionNode = (VersionNode) query.uniqueResult();
if (versionNode == null)
{
throw new Exception("No such Node: " + state.getId());
}
versionNode.setData(out.toByteArray());
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
query.setString(0, state.getId().toString());
- WSPNode wspNode = (WSPNode)query.uniqueResult();
+ WSPNode wspNode = (WSPNode) query.uniqueResult();
if (wspNode == null)
{
throw new Exception("No such Node: " + state.getId());
@@ -722,21 +757,24 @@
{
Serializer.serialize(state, out, blobStore);
- Query query = session.createQuery(propertyStateSelect).setCacheable(true);
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ Query query = session.createQuery(propertyStateSelect).setCacheable(
+ true);
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
query.setString(0, state.getId().toString());
- VersionProp versionProp = (VersionProp)query.uniqueResult();
+ VersionProp versionProp = (VersionProp) query.uniqueResult();
if (versionProp == null)
{
throw new Exception("No such Property: " + state.getId());
}
versionProp.setData(out.toByteArray());
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
query.setString(0, state.getId().toString());
- WSPProp wspProp = (WSPProp)query.uniqueResult();
+ WSPProp wspProp = (WSPProp) query.uniqueResult();
if (wspProp == null)
{
throw new Exception("No such Property: " + state.getId());
@@ -775,10 +813,8 @@
Session session = hibernateSessionFactory.getCurrentSession();
try
{
- Query query = session.
- createQuery(nodeStateSelect).
- setCacheable(true).
- setString(0, state.getId().toString());
+ Query query = session.createQuery(nodeStateSelect).setCacheable(true)
+ .setString(0, state.getId().toString());
Object result = query.uniqueResult();
if (result != null)
{
@@ -812,11 +848,12 @@
{
if (val.getType() == PropertyType.BINARY)
{
- BLOBFileValue blobVal = (BLOBFileValue)val.internalValue();
+ BLOBFileValue blobVal = (BLOBFileValue) val.internalValue();
// delete internal resource representation of BLOB value
blobVal.delete(true);
// also remove from BLOBStore
- String blobId = blobStore.createId((PropertyId)state.getId(), i);
+ String blobId = blobStore.createId(
+ (PropertyId) state.getId(), i);
try
{
blobStore.remove(blobId);
@@ -835,8 +872,8 @@
try
{
- Query query = session.createQuery(propertyStateSelect).setCacheable(true).setString(0,
- state.getId().toString());
+ Query query = session.createQuery(propertyStateSelect).setCacheable(
+ true).setString(0, state.getId().toString());
Object result = query.uniqueResult();
if (result != null)
{
@@ -854,7 +891,7 @@
}
/**
- *
+ *
*/
private void destroy(NodeReferences refs) throws ItemStateException
{
@@ -866,8 +903,8 @@
Session session = hibernateSessionFactory.getCurrentSession();
try
{
- Query query = session.createQuery(nodeReferenceSelect).setCacheable(true).setString(0,
- refs.getTargetId().toString());
+ Query query = session.createQuery(nodeReferenceSelect).setCacheable(
+ true).setString(0, refs.getTargetId().toString());
List list = query.list();
if (list == null)
@@ -895,7 +932,7 @@
}
/**
- *
+ *
*/
public boolean exists(NodeId id) throws ItemStateException
{
@@ -903,7 +940,7 @@
}
/**
- *
+ *
*/
protected boolean exists(String blobid) throws ItemStateException
{
@@ -911,7 +948,7 @@
}
/**
- *
+ *
*/
public boolean exists(PropertyId id) throws ItemStateException
{
@@ -919,7 +956,7 @@
}
/**
- *
+ *
*/
public boolean exists(NodeReferencesId targetId) throws ItemStateException
{
@@ -936,7 +973,8 @@
Session session = hibernateSessionFactory.openSession();
try
{
- List rs = session.createQuery(query).setCacheable(true).setString(0, id).list();
+ List rs = session.createQuery(query).setCacheable(true).setString(0,
+ id).list();
Iterator iter = rs.iterator();
return iter.hasNext();
}
@@ -953,7 +991,7 @@
}
- //-------------------------------------------------< misc. helper methods >
+ // -------------------------------------------------< misc. helper methods >
protected void logException(String message, SQLException se)
{
@@ -966,12 +1004,12 @@
log.debug(" dump:", se);
}
- //--------------------------------------------------------< inner classes >
+ // --------------------------------------------------------< inner classes >
class DbBLOBStore implements BLOBStore
{
/**
- *
+ *
*/
public String createId(PropertyId id, int index)
{
@@ -985,16 +1023,17 @@
}
/**
- *
+ *
*/
public InputStream get(String blobId) throws Exception
{
Session session = hibernateSessionFactory.getCurrentSession();
try
{
- List rs = session.createQuery(blobSelectData).setCacheable(true).setString(0, blobId).list();
+ List rs = session.createQuery(blobSelectData).setCacheable(true)
+ .setString(0, blobId).list();
Iterator iter = rs.iterator();
- java.sql.Blob blob = (java.sql.Blob)iter.next();
+ java.sql.Blob blob = (java.sql.Blob) iter.next();
InputStream is = blob.getBinaryStream();
return is;
}
@@ -1002,7 +1041,7 @@
{
if (e instanceof NoSuchItemStateException)
{
- throw(NoSuchItemStateException)e;
+ throw (NoSuchItemStateException) e;
}
String msg = "failed to read binary data: " + blobId;
log.error(msg, e);
@@ -1011,9 +1050,10 @@
}
/**
- *
+ *
*/
- public void put(String blobId, InputStream in, long size) throws Exception
+ public void put(String blobId, InputStream in, long size)
+ throws Exception
{
boolean update = exists(blobId);
@@ -1025,10 +1065,12 @@
{
Query query = session.createQuery(blobSelect).setCacheable(true);
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
query.setString(0, blobId);
- VersionBinVal versionNode = (VersionBinVal)query.uniqueResult();
+ VersionBinVal versionNode = (VersionBinVal) query
+ .uniqueResult();
if (versionNode == null)
{
throw new Exception("No such Node: " + blobId);
@@ -1036,10 +1078,11 @@
versionNode.setId(blobId);
versionNode.setData(Hibernate.createBlob(in));
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
query.setString(0, blobId);
- WSPBinVal wspNode = (WSPBinVal)query.uniqueResult();
+ WSPBinVal wspNode = (WSPBinVal) query.uniqueResult();
if (wspNode == null)
{
throw new Exception("No such Node: " + blobId);
@@ -1054,6 +1097,10 @@
log.error(msg, e);
throw new ItemStateException(msg, e);
}
+ finally
+ {
+ session.flush();
+ }
}
else
// insert
@@ -1061,14 +1108,18 @@
try
{
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- VersionBinVal versionNode = new VersionBinVal(blobId, Hibernate.createBlob(in));
+ VersionBinVal versionNode = new VersionBinVal(blobId,
+ Hibernate.createBlob(in));
session.save(versionNode);
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- WSPBinVal wspNode = new WSPBinVal(blobId, Hibernate.createBlob(in));
+ WSPBinVal wspNode = new WSPBinVal(blobId, Hibernate
+ .createBlob(in));
session.save(wspNode);
}
}
@@ -1078,19 +1129,24 @@
log.error(msg, e);
throw new ItemStateException(msg, e);
}
+ finally
+ {
+ session.flush();
+ }
}
}
/**
- *
+ *
*/
- // public synchronized boolean remove(String blobId) throws Exception
+ // public synchronized boolean remove(String blobId) throws Exception
public boolean remove(String blobId) throws Exception
{
Session session = hibernateSessionFactory.getCurrentSession();
try
{
- Query query = session.createQuery(nodeBinValSelect).setCacheable(true).setString(0, blobId);
+ Query query = session.createQuery(nodeBinValSelect).setCacheable(
+ true).setString(0, blobId);
Object result = query.uniqueResult();
if (result != null)
{
@@ -1104,23 +1160,27 @@
log.error(msg, e);
throw new ItemStateException(msg, e);
}
+ finally
+ {
+ session.flush();
+ }
}
}
}
/*
- * Copyright 2004-2005 The Apache Software Foundation or its licensors,
- * as applicable.
- *
- * 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
- *
+ * Copyright 2004-2005 The Apache Software Foundation or its licensors, as
+ * applicable.
+ *
+ * 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.
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
*/
\ No newline at end of file
Modified: trunk/cms/src/main/org/jboss/portal/cms/hibernate/state/JBossCachePersistenceManager.java
===================================================================
--- trunk/cms/src/main/org/jboss/portal/cms/hibernate/state/JBossCachePersistenceManager.java 2007-03-30 17:20:07 UTC (rev 6886)
+++ trunk/cms/src/main/org/jboss/portal/cms/hibernate/state/JBossCachePersistenceManager.java 2007-03-30 21:03:45 UTC (rev 6887)
@@ -22,7 +22,6 @@
******************************************************************************/
package org.jboss.portal.cms.hibernate.state;
-
import org.apache.jackrabbit.core.NodeId;
import org.apache.jackrabbit.core.PropertyId;
import org.apache.jackrabbit.core.fs.FileSystem;
@@ -58,7 +57,6 @@
import javax.jcr.PropertyType;
import javax.management.MBeanServer;
-import javax.naming.InitialContext;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -71,13 +69,14 @@
/*
* Created on Aug 28, 2006
- *
+ *
* @author <a href="mailto:sohil.shah@jboss.com">Sohil Shah</a>
*/
public class JBossCachePersistenceManager implements PersistenceManager
{
/** Logger instance */
- private static Logger log = Logger.getLogger(JBossCachePersistenceManager.class);
+ private static Logger log = Logger
+ .getLogger(JBossCachePersistenceManager.class);
protected static final String SCHEMA_OBJECT_PREFIX_VARIABLE = "${schemaObjectPrefix}";
@@ -92,7 +91,6 @@
// initial size of buffer used to serialize objects
protected static final int INITIAL_BUFFER_SIZE = 1024;
-
// shared statements for BLOB management
// (if <code>externalBLOBs==false</code>)
protected String blobSelect = null;
@@ -106,23 +104,27 @@
/** file system where BLOB data is stored (if <code>externalBLOBs==true</code>) */
protected FileSystem blobFS = null;
- /** BLOBStore that manages BLOB data in the file system (if <code>externalBLOBs==true</code>) */
+ /**
+ * BLOBStore that manages BLOB data in the file system (if
+ * <code>externalBLOBs==true</code>)
+ */
protected BLOBStore blobStore = null;
/**
- * JackRabbit initalizes multiple instances of the Persistence Manager to perform its operations.
- * A static TreeCache is used to make sure there is only once instance of the cache per VM where
- * the CMS node runs.
+ * JackRabbit initalizes multiple instances of the Persistence Manager to
+ * perform its operations. A static TreeCache is used to make sure there is
+ * only once instance of the cache per VM where the CMS node runs.
*
- * One side effect of using a static instance is proper cleanup which is addressed in the close
- * method
+ * One side effect of using a static instance is proper cleanup which is
+ * addressed in the close method
*/
private static TreeCacheMBean pmCache = null;
+
private static boolean preloaded = false;
/**
*
- *
+ *
*/
public JBossCachePersistenceManager()
{
@@ -131,7 +133,7 @@
initialized = false;
}
- //------------------------------------------------------------------------------------------------------------------------------------------------
+ // ------------------------------------------------------------------------------------------------------------------------------------------------
public String getJNDIName()
{
return jndiName;
@@ -149,7 +151,7 @@
public void setSchemaObjectPrefix(String schemaObjectPrefix)
{
- this.schemaObjectPrefix = schemaObjectPrefix;//.toUpperCase();
+ this.schemaObjectPrefix = schemaObjectPrefix;// .toUpperCase();
}
public boolean isExternalBLOBs()
@@ -167,24 +169,24 @@
this.externalBLOBs = Boolean.valueOf(externalBLOBs).booleanValue();
}
-
/*
- *
- */
+ *
+ */
public void init(PMContext context) throws Exception
- {
+ {
if (initialized)
{
throw new IllegalStateException("already initialized");
}
- nodeBinValSelect = "from " + schemaObjectPrefix + "BinVal where BINVAL_ID = ?";
+ nodeBinValSelect = "from " + schemaObjectPrefix
+ + "BinVal where BINVAL_ID = ?";
if (externalBLOBs)
{
/**
- * store BLOBs in local file system in a sub directory
- * of the workspace home directory
+ * store BLOBs in local file system in a sub directory of the workspace
+ * home directory
*/
LocalFileSystem blobFS = new LocalFileSystem();
blobFS.setRoot(new File(context.getHomeDir(), "blobs"));
@@ -199,9 +201,12 @@
*/
blobStore = new DbBLOBStore();
- blobSelect = "from " + schemaObjectPrefix + "BinVal where BINVAL_ID = ?";
- blobSelectData = "select data from " + schemaObjectPrefix + "BinVal where BINVAL_ID = ?";
- blobSelectExist = "select 1 from " + schemaObjectPrefix + "BinVal where BINVAL_ID = ?";
+ blobSelect = "from " + schemaObjectPrefix
+ + "BinVal where BINVAL_ID = ?";
+ blobSelectData = "select data from " + schemaObjectPrefix
+ + "BinVal where BINVAL_ID = ?";
+ blobSelectExist = "select 1 from " + schemaObjectPrefix
+ + "BinVal where BINVAL_ID = ?";
}
initialized = true;
@@ -213,27 +218,32 @@
{
/*
- * performing an mbean lookup of the tree cache service. Ideally it would be nice to avoid this
- * and have the service be injected from the sar config. But, a PersistenceManager's lifecycle is managed
+ * performing an mbean lookup of the tree cache service. Ideally it
+ * would be nice to avoid this and have the service be injected from
+ * the sar config. But, a PersistenceManager's lifecycle is managed
* by JackRabbit and is not easily modeled as a JMX mbean service.
*
- * The typical mbean lifecycle doesn't map here unless the PM serves as a wrapper/proxy to an mbean
- * service, but not sure if the extra layer is necessary.
+ * The typical mbean lifecycle doesn't map here unless the PM serves
+ * as a wrapper/proxy to an mbean service, but not sure if the extra
+ * layer is necessary.
*
- * Also, see the close method to see how the PM cache service is cleaned up.
+ * Also, see the close method to see how the PM cache service is
+ * cleaned up.
*/
try
{
MBeanServer server = MBeanServerLocator.locateJBoss();
- pmCache = (TreeCacheMBean)MBeanProxyExt.create(TreeCacheMBean.class,
- "cms.pm.cache:service=TreeCache", server);
+ pmCache = (TreeCacheMBean) MBeanProxyExt.create(
+ TreeCacheMBean.class, "cms.pm.cache:service=TreeCache",
+ server);
}
catch (Exception e)
{
- }
+ }
- //try to load from specified configuration if any
- //if nothing found in the environment...chances are running in a non-managed environment
+ // try to load from specified configuration if any
+ // if nothing found in the environment...chances are running in a
+ // non-managed environment
if (pmCache == null)
{
InputStream is = null;
@@ -241,9 +251,10 @@
{
pmCache = new TreeCache();
- //configure the cache
+ // configure the cache
PropertyConfigurator configurator = new PropertyConfigurator();
- is = JBossCachePersistenceManager.class.getClassLoader().getResourceAsStream("pm-cache.xml");
+ is = JBossCachePersistenceManager.class.getClassLoader()
+ .getResourceAsStream("pm-cache.xml");
configurator.configure(pmCache, is);
pmCache.createService();
@@ -259,7 +270,7 @@
}
}
- //pre-load the cache with property nodes
+ // pre-load the cache with property nodes
if (!JBossCachePersistenceManager.preloaded)
{
JBossCachePersistenceManager.loadProperties();
@@ -275,8 +286,8 @@
}
/**
- *
- *
+ *
+ *
*/
private static synchronized void loadProperties() throws Exception
{
@@ -285,19 +296,26 @@
return;
}
- log.info("Pre-loading the PersistenceManager Cache in the background (started).......");
+ log
+ .info("Pre-loading the PersistenceManager Cache in the background (started).......");
- CacheLoader wspProp = new CacheLoader(CacheLoader.wspProp, PortalCMSCacheLoader.WSP_PROP_NODE);
+ CacheLoader wspProp = new CacheLoader(CacheLoader.wspProp,
+ PortalCMSCacheLoader.WSP_PROP_NODE);
Thread wspPropLoader = new Thread(wspProp);
- CacheLoader versionProp = new CacheLoader(CacheLoader.versionProp, PortalCMSCacheLoader.VERSION_PROP_NODE);
+ CacheLoader versionProp = new CacheLoader(CacheLoader.versionProp,
+ PortalCMSCacheLoader.VERSION_PROP_NODE);
Thread versionPropLoader = new Thread(versionProp);
- CacheLoader wspNode = new CacheLoader(CacheLoader.wspNode, PortalCMSCacheLoader.WSP_NODE_NODE);
+ CacheLoader wspNode = new CacheLoader(CacheLoader.wspNode,
+ PortalCMSCacheLoader.WSP_NODE_NODE);
Thread wspNodeLoader = new Thread(wspNode);
- CacheLoader versionNode = new CacheLoader(CacheLoader.versionNode, PortalCMSCacheLoader.VERSION_NODE_NODE);
+ CacheLoader versionNode = new CacheLoader(CacheLoader.versionNode,
+ PortalCMSCacheLoader.VERSION_NODE_NODE);
Thread versionNodeLoader = new Thread(versionNode);
- CacheLoader wspRef = new CacheLoader(CacheLoader.wspRef, PortalCMSCacheLoader.WSP_REF_NODE);
+ CacheLoader wspRef = new CacheLoader(CacheLoader.wspRef,
+ PortalCMSCacheLoader.WSP_REF_NODE);
Thread wspRefLoader = new Thread(wspRef);
- CacheLoader versionRef = new CacheLoader(CacheLoader.versionRef, PortalCMSCacheLoader.VERSION_REF_NODE);
+ CacheLoader versionRef = new CacheLoader(CacheLoader.versionRef,
+ PortalCMSCacheLoader.VERSION_REF_NODE);
Thread versionRefLoader = new Thread(versionRef);
wspPropLoader.start();
@@ -307,18 +325,14 @@
wspRefLoader.start();
versionRefLoader.start();
- //hang out here till the cache loader threads have pre-loaded the busy nodes
- //of the CMS...don't allow the usage of CMS till this operation is completed.
- while (
- !wspProp.done ||
- !versionProp.done ||
- !wspNode.done ||
- !versionNode.done ||
- !wspRef.done ||
- !versionRef.done
- )
+ // hang out here till the cache loader threads have pre-loaded the busy
+ // nodes
+ // of the CMS...don't allow the usage of CMS till this operation is
+ // completed.
+ while (!wspProp.done || !versionProp.done || !wspNode.done
+ || !versionNode.done || !wspRef.done || !versionRef.done)
{
- Thread.currentThread().sleep((long)2000);
+ Thread.currentThread().sleep((long) 2000);
}
JBossCachePersistenceManager.preloaded = true;
@@ -327,21 +341,27 @@
private static class CacheLoader implements Runnable
{
/**
- *
+ *
*/
private static final String wspProp = "from org.jboss.portal.cms.hibernate.state.WSPProp";
+
private static final String versionProp = "from org.jboss.portal.cms.hibernate.state.VersionProp";
+
private static final String wspNode = "from org.jboss.portal.cms.hibernate.state.WSPNode";
+
private static final String versionNode = "from org.jboss.portal.cms.hibernate.state.VersionNode";
+
private static final String wspRef = "from org.jboss.portal.cms.hibernate.state.WSPRefs";
+
private static final String versionRef = "from org.jboss.portal.cms.hibernate.state.VersionRefs";
-
/**
- *
+ *
*/
private String nodeQuery = null;
+
private String nodePrefix = null;
+
private boolean done = false;
private CacheLoader(String nodeQuery, String nodePrefix)
@@ -361,42 +381,63 @@
{
for (Iterator itr = rs.iterator(); itr.hasNext();)
{
- Base cour = (Base)itr.next();
+ Base cour = (Base) itr.next();
cour.disableCacheItemPersistence();
if (cour instanceof WSPProp)
{
- String node = this.nodePrefix + "/" + PortalCMSCacheLoader.parseNodeName(((WSPProp)cour).getPropId());
- pmCache.put(node, ((WSPProp)cour).getPropId(), cour);
+ String node = this.nodePrefix
+ + "/"
+ + PortalCMSCacheLoader
+ .parseNodeName(((WSPProp) cour).getPropId());
+ pmCache.put(node, ((WSPProp) cour).getPropId(), cour);
}
else if (cour instanceof VersionProp)
{
- String node = this.nodePrefix + "/" + PortalCMSCacheLoader.parseNodeName(((VersionProp)cour).getPropId());
- pmCache.put(node, ((VersionProp)cour).getPropId(), cour);
+ String node = this.nodePrefix
+ + "/"
+ + PortalCMSCacheLoader
+ .parseNodeName(((VersionProp) cour)
+ .getPropId());
+ pmCache.put(node, ((VersionProp) cour).getPropId(), cour);
}
else if (cour instanceof WSPNode)
{
- String node = this.nodePrefix + "/" + PortalCMSCacheLoader.parseNodeName(((WSPNode)cour).getNodeId());
- pmCache.put(node, ((WSPNode)cour).getNodeId(), cour);
+ String node = this.nodePrefix
+ + "/"
+ + PortalCMSCacheLoader
+ .parseNodeName(((WSPNode) cour).getNodeId());
+ pmCache.put(node, ((WSPNode) cour).getNodeId(), cour);
}
else if (cour instanceof VersionNode)
{
- String node = this.nodePrefix + "/" + PortalCMSCacheLoader.parseNodeName(((VersionNode)cour).getNodeId());
- pmCache.put(node, ((VersionNode)cour).getNodeId(), cour);
+ String node = this.nodePrefix
+ + "/"
+ + PortalCMSCacheLoader
+ .parseNodeName(((VersionNode) cour)
+ .getNodeId());
+ pmCache.put(node, ((VersionNode) cour).getNodeId(), cour);
}
else if (cour instanceof WSPRefs)
{
- String node = this.nodePrefix + "/" + PortalCMSCacheLoader.parseNodeName(((WSPRefs)cour).getRefId());
- pmCache.put(node, ((WSPRefs)cour).getRefId(), cour);
+ String node = this.nodePrefix
+ + "/"
+ + PortalCMSCacheLoader
+ .parseNodeName(((WSPRefs) cour).getRefId());
+ pmCache.put(node, ((WSPRefs) cour).getRefId(), cour);
}
else if (cour instanceof VersionRefs)
{
- String node = this.nodePrefix + "/" + PortalCMSCacheLoader.parseNodeName(((VersionRefs)cour).getRefId());
- pmCache.put(node, ((VersionRefs)cour).getRefId(), cour);
+ String node = this.nodePrefix
+ + "/"
+ + PortalCMSCacheLoader
+ .parseNodeName(((VersionRefs) cour).getRefId());
+ pmCache.put(node, ((VersionRefs) cour).getRefId(), cour);
}
}
}
- log.info("Pre-loading the PersistenceManager Cache for" + this.nodePrefix + " (finished).......");
+ log.info("Pre-loading the PersistenceManager Cache for"
+ + this.nodePrefix + " (finished).......");
}
catch (CacheException ce)
{
@@ -410,19 +451,22 @@
}
}
- //----------actions for node entities-------------------------------------------------------------------------------------------------------------
+ // ----------actions for node
+ // entities-------------------------------------------------------------------------------------------------------------
/*
- *
- */
+ *
+ */
public boolean exists(NodeId node) throws ItemStateException
{
try
{
boolean exists = false;
String nodeId = node.toString();
- if (this.schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ if (this.schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- Object o = this.pmCache.get(PortalCMSCacheLoader.WSP_NODE_NODE + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
+ Object o = this.pmCache.get(PortalCMSCacheLoader.WSP_NODE_NODE
+ + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
if (o != null)
{
if (o instanceof WSPNode)
@@ -432,12 +476,16 @@
}
else
{
- this.pmCache.put(PortalCMSCacheLoader.WSP_NODE_NODE + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId, new Boolean(false));
+ this.pmCache.put(PortalCMSCacheLoader.WSP_NODE_NODE + "/"
+ + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId,
+ new Boolean(false));
}
}
- else if (this.schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ else if (this.schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- Object o = this.pmCache.get(PortalCMSCacheLoader.VERSION_NODE_NODE + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
+ Object o = this.pmCache.get(PortalCMSCacheLoader.VERSION_NODE_NODE
+ + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
if (o != null)
{
if (o instanceof VersionNode)
@@ -447,7 +495,9 @@
}
else
{
- this.pmCache.put(PortalCMSCacheLoader.VERSION_NODE_NODE + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId, new Boolean(false));
+ this.pmCache.put(PortalCMSCacheLoader.VERSION_NODE_NODE + "/"
+ + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId,
+ new Boolean(false));
}
}
return exists;
@@ -459,29 +509,34 @@
}
/*
- *
- */
- public NodeState load(NodeId node) throws NoSuchItemStateException, ItemStateException
+ *
+ */
+ public NodeState load(NodeId node) throws NoSuchItemStateException,
+ ItemStateException
{
try
{
NodeState nodeState = null;
String nodeId = node.toString();
- //get the nodeData
+ // get the nodeData
byte[] nodeData = null;
- if (this.schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ if (this.schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- Object o = this.pmCache.get(PortalCMSCacheLoader.WSP_NODE_NODE + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
- nodeData = ((WSPNode)o).getData();
+ Object o = this.pmCache.get(PortalCMSCacheLoader.WSP_NODE_NODE
+ + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
+ nodeData = ((WSPNode) o).getData();
}
- else if (this.schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ else if (this.schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- Object o = this.pmCache.get(PortalCMSCacheLoader.VERSION_NODE_NODE + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
- nodeData = ((VersionNode)o).getData();
+ Object o = this.pmCache.get(PortalCMSCacheLoader.VERSION_NODE_NODE
+ + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
+ nodeData = ((VersionNode) o).getData();
}
- //parse propertyData into propertyState
+ // parse propertyData into propertyState
if (nodeData != null)
{
Session session = null;
@@ -491,11 +546,10 @@
{
session = Tools.getOpenSession();
tx = session.beginTransaction();
-
-
+
InputStream in = new ByteArrayInputStream(nodeData);
- //setup the propertyState
+ // setup the propertyState
nodeState = createNew(node);
Serializer.deserialize(nodeState, in);
org.jboss.portal.common.util.Tools.safeClose(in);
@@ -507,9 +561,10 @@
{
if (e instanceof NoSuchItemStateException)
{
- throw(NoSuchItemStateException)e;
+ throw (NoSuchItemStateException) e;
}
- String msg = "failed to read node state from cache: " + node.toString();
+ String msg = "failed to read node state from cache: "
+ + node.toString();
log.error(msg, e);
throw new ItemStateException(msg, e);
}
@@ -532,8 +587,8 @@
}
/**
- *
- *
+ *
+ *
*/
private void store(NodeState state) throws ItemStateException
{
@@ -546,23 +601,29 @@
try
{
Serializer.serialize(state, out);
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- VersionNode versionNode = new VersionNode(state.getId().toString(), out.toByteArray());
+ VersionNode versionNode = new VersionNode(state.getId().toString(),
+ out.toByteArray());
- //place this in the cache
+ // place this in the cache
versionNode.resetCacheItemPersistence();
- String cacheNode = PortalCMSCacheLoader.VERSION_NODE_NODE + "/" + PortalCMSCacheLoader.parseNodeName(versionNode.getNodeId());
+ String cacheNode = PortalCMSCacheLoader.VERSION_NODE_NODE + "/"
+ + PortalCMSCacheLoader.parseNodeName(versionNode.getNodeId());
pmCache.put(cacheNode, versionNode.getNodeId(), versionNode);
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- WSPNode wspNode = new WSPNode(state.getId().toString(), out.toByteArray());
+ WSPNode wspNode = new WSPNode(state.getId().toString(), out
+ .toByteArray());
- //place this in the cache
+ // place this in the cache
wspNode.resetCacheItemPersistence();
- String cacheNode = PortalCMSCacheLoader.WSP_NODE_NODE + "/" + PortalCMSCacheLoader.parseNodeName(wspNode.getNodeId());
+ String cacheNode = PortalCMSCacheLoader.WSP_NODE_NODE + "/"
+ + PortalCMSCacheLoader.parseNodeName(wspNode.getNodeId());
pmCache.put(cacheNode, wspNode.getNodeId(), wspNode);
}
}
@@ -586,8 +647,8 @@
}
/**
- *
- *
+ *
+ *
*/
private void update(NodeState state) throws ItemStateException
{
@@ -602,27 +663,34 @@
Serializer.serialize(state, out);
String id = state.getId().toString();
String cacheNodeName = PortalCMSCacheLoader.parseNodeName(id);
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- VersionNode versionNode = (VersionNode)pmCache.get(PortalCMSCacheLoader.VERSION_NODE_NODE + "/" + cacheNodeName, id);
+ VersionNode versionNode = (VersionNode) pmCache.get(
+ PortalCMSCacheLoader.VERSION_NODE_NODE + "/" + cacheNodeName,
+ id);
if (versionNode == null)
{
throw new Exception("No such Node: " + state.getId());
}
versionNode.setData(out.toByteArray());
versionNode.resetCacheItemPersistence();
- pmCache.put(PortalCMSCacheLoader.VERSION_NODE_NODE + "/" + cacheNodeName, id, versionNode);
+ pmCache.put(PortalCMSCacheLoader.VERSION_NODE_NODE + "/"
+ + cacheNodeName, id, versionNode);
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- WSPNode wspNode = (WSPNode)pmCache.get(PortalCMSCacheLoader.WSP_NODE_NODE + "/" + cacheNodeName, id);
+ WSPNode wspNode = (WSPNode) pmCache.get(
+ PortalCMSCacheLoader.WSP_NODE_NODE + "/" + cacheNodeName, id);
if (wspNode == null)
{
throw new Exception("No such Node: " + state.getId());
}
wspNode.setData(out.toByteArray());
wspNode.resetCacheItemPersistence();
- pmCache.put(PortalCMSCacheLoader.WSP_NODE_NODE + "/" + cacheNodeName, id, wspNode);
+ pmCache.put(PortalCMSCacheLoader.WSP_NODE_NODE + "/"
+ + cacheNodeName, id, wspNode);
}
}
catch (Exception e)
@@ -656,13 +724,17 @@
String cacheNodeName = PortalCMSCacheLoader.parseNodeName(id);
try
{
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- pmCache.remove(PortalCMSCacheLoader.VERSION_NODE_NODE + "/" + cacheNodeName, id);
+ pmCache.remove(PortalCMSCacheLoader.VERSION_NODE_NODE + "/"
+ + cacheNodeName, id);
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- pmCache.remove(PortalCMSCacheLoader.WSP_NODE_NODE + "/" + cacheNodeName, id);
+ pmCache.remove(PortalCMSCacheLoader.WSP_NODE_NODE + "/"
+ + cacheNodeName, id);
}
}
catch (Exception e)
@@ -673,19 +745,22 @@
}
}
- //----------actions for property entities-------------------------------------------------------------------------------------------------------------
+ // ----------actions for property
+ // entities-------------------------------------------------------------------------------------------------------------
/*
- *
- */
+ *
+ */
public boolean exists(PropertyId property) throws ItemStateException
{
try
{
boolean exists = false;
String propId = property.toString();
- if (this.schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ if (this.schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- Object o = this.pmCache.get(PortalCMSCacheLoader.WSP_PROP_NODE + "/" + PortalCMSCacheLoader.parseNodeName(propId), propId);
+ Object o = this.pmCache.get(PortalCMSCacheLoader.WSP_PROP_NODE
+ + "/" + PortalCMSCacheLoader.parseNodeName(propId), propId);
if (o != null)
{
if (o instanceof WSPProp)
@@ -695,12 +770,16 @@
}
else
{
- this.pmCache.put(PortalCMSCacheLoader.WSP_PROP_NODE + "/" + PortalCMSCacheLoader.parseNodeName(propId), propId, new Boolean(false));
+ this.pmCache.put(PortalCMSCacheLoader.WSP_PROP_NODE + "/"
+ + PortalCMSCacheLoader.parseNodeName(propId), propId,
+ new Boolean(false));
}
}
- else if (this.schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ else if (this.schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- Object o = this.pmCache.get(PortalCMSCacheLoader.VERSION_PROP_NODE + "/" + PortalCMSCacheLoader.parseNodeName(propId), propId);
+ Object o = this.pmCache.get(PortalCMSCacheLoader.VERSION_PROP_NODE
+ + "/" + PortalCMSCacheLoader.parseNodeName(propId), propId);
if (o != null)
{
if (o instanceof VersionProp)
@@ -710,7 +789,9 @@
}
else
{
- this.pmCache.put(PortalCMSCacheLoader.VERSION_PROP_NODE + "/" + PortalCMSCacheLoader.parseNodeName(propId), propId, new Boolean(false));
+ this.pmCache.put(PortalCMSCacheLoader.VERSION_PROP_NODE + "/"
+ + PortalCMSCacheLoader.parseNodeName(propId), propId,
+ new Boolean(false));
}
}
return exists;
@@ -722,29 +803,34 @@
}
/*
- *
- */
- public PropertyState load(PropertyId property) throws NoSuchItemStateException, ItemStateException
+ *
+ */
+ public PropertyState load(PropertyId property)
+ throws NoSuchItemStateException, ItemStateException
{
try
{
PropertyState propertyState = null;
String propId = property.toString();
- //get the propertyData
+ // get the propertyData
byte[] propertyData = null;
- if (this.schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ if (this.schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- Object o = this.pmCache.get(PortalCMSCacheLoader.WSP_PROP_NODE + "/" + PortalCMSCacheLoader.parseNodeName(propId), propId);
- propertyData = ((WSPProp)o).getData();
+ Object o = this.pmCache.get(PortalCMSCacheLoader.WSP_PROP_NODE
+ + "/" + PortalCMSCacheLoader.parseNodeName(propId), propId);
+ propertyData = ((WSPProp) o).getData();
}
- else if (this.schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ else if (this.schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- Object o = this.pmCache.get(PortalCMSCacheLoader.VERSION_PROP_NODE + "/" + PortalCMSCacheLoader.parseNodeName(propId), propId);
- propertyData = ((VersionProp)o).getData();
+ Object o = this.pmCache.get(PortalCMSCacheLoader.VERSION_PROP_NODE
+ + "/" + PortalCMSCacheLoader.parseNodeName(propId), propId);
+ propertyData = ((VersionProp) o).getData();
}
- //parse propertyData into propertyState
+ // parse propertyData into propertyState
if (propertyData != null)
{
Session session = null;
@@ -757,7 +843,7 @@
InputStream in = new ByteArrayInputStream(propertyData);
- //setup the propertyState
+ // setup the propertyState
propertyState = createNew(property);
Serializer.deserialize(propertyState, in, blobStore);
org.jboss.portal.common.util.Tools.safeClose(in);
@@ -769,9 +855,10 @@
{
if (e instanceof NoSuchItemStateException)
{
- throw(NoSuchItemStateException)e;
+ throw (NoSuchItemStateException) e;
}
- String msg = "failed to read property state from cache: " + property.toString();
+ String msg = "failed to read property state from cache: "
+ + property.toString();
log.error(msg, e);
throw new ItemStateException(msg, e);
}
@@ -794,7 +881,7 @@
}
/**
- *
+ *
*/
private void store(PropertyState state) throws ItemStateException
{
@@ -807,23 +894,29 @@
try
{
Serializer.serialize(state, out, blobStore);
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- VersionProp versionProp = new VersionProp(state.getId().toString(), out.toByteArray());
+ VersionProp versionProp = new VersionProp(state.getId().toString(),
+ out.toByteArray());
- //place this in the cache
+ // place this in the cache
versionProp.resetCacheItemPersistence();
- String cacheNode = PortalCMSCacheLoader.VERSION_PROP_NODE + "/" + PortalCMSCacheLoader.parseNodeName(versionProp.getPropId());
+ String cacheNode = PortalCMSCacheLoader.VERSION_PROP_NODE + "/"
+ + PortalCMSCacheLoader.parseNodeName(versionProp.getPropId());
pmCache.put(cacheNode, versionProp.getPropId(), versionProp);
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- WSPProp wspProp = new WSPProp(state.getId().toString(), out.toByteArray());
+ WSPProp wspProp = new WSPProp(state.getId().toString(), out
+ .toByteArray());
- //place this in the cache
+ // place this in the cache
wspProp.resetCacheItemPersistence();
- String cacheNode = PortalCMSCacheLoader.WSP_PROP_NODE + "/" + PortalCMSCacheLoader.parseNodeName(wspProp.getPropId());
+ String cacheNode = PortalCMSCacheLoader.WSP_PROP_NODE + "/"
+ + PortalCMSCacheLoader.parseNodeName(wspProp.getPropId());
pmCache.put(cacheNode, wspProp.getPropId(), wspProp);
}
}
@@ -847,8 +940,8 @@
}
/**
- *
- *
+ *
+ *
*/
private void update(PropertyState state) throws ItemStateException
{
@@ -863,27 +956,34 @@
Serializer.serialize(state, out, blobStore);
String id = state.getId().toString();
String cacheNodeName = PortalCMSCacheLoader.parseNodeName(id);
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- VersionProp versionProp = (VersionProp)pmCache.get(PortalCMSCacheLoader.VERSION_PROP_NODE + "/" + cacheNodeName, id);
+ VersionProp versionProp = (VersionProp) pmCache.get(
+ PortalCMSCacheLoader.VERSION_PROP_NODE + "/" + cacheNodeName,
+ id);
if (versionProp == null)
{
throw new Exception("No such Property: " + state.getId());
}
versionProp.setData(out.toByteArray());
versionProp.resetCacheItemPersistence();
- pmCache.put(PortalCMSCacheLoader.VERSION_PROP_NODE + "/" + cacheNodeName, id, versionProp);
+ pmCache.put(PortalCMSCacheLoader.VERSION_PROP_NODE + "/"
+ + cacheNodeName, id, versionProp);
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- WSPProp wspProp = (WSPProp)pmCache.get(PortalCMSCacheLoader.WSP_PROP_NODE + "/" + cacheNodeName, id);
+ WSPProp wspProp = (WSPProp) pmCache.get(
+ PortalCMSCacheLoader.WSP_PROP_NODE + "/" + cacheNodeName, id);
if (wspProp == null)
{
throw new Exception("No such Property: " + state.getId());
}
wspProp.setData(out.toByteArray());
wspProp.resetCacheItemPersistence();
- pmCache.put(PortalCMSCacheLoader.WSP_PROP_NODE + "/" + cacheNodeName, id, wspProp);
+ pmCache.put(PortalCMSCacheLoader.WSP_PROP_NODE + "/"
+ + cacheNodeName, id, wspProp);
}
}
catch (Exception e)
@@ -924,11 +1024,12 @@
{
if (val.getType() == PropertyType.BINARY)
{
- BLOBFileValue blobVal = (BLOBFileValue)val.internalValue();
+ BLOBFileValue blobVal = (BLOBFileValue) val.internalValue();
// delete internal resource representation of BLOB value
blobVal.delete(true);
// also remove from BLOBStore
- String blobId = blobStore.createId((PropertyId)state.getId(), i);
+ String blobId = blobStore.createId(
+ (PropertyId) state.getId(), i);
try
{
blobStore.remove(blobId);
@@ -942,18 +1043,22 @@
}
}
- //remove the property node
+ // remove the property node
String id = state.getId().toString();
String cacheNodeName = PortalCMSCacheLoader.parseNodeName(id);
try
{
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- pmCache.remove(PortalCMSCacheLoader.VERSION_PROP_NODE + "/" + cacheNodeName, id);
+ pmCache.remove(PortalCMSCacheLoader.VERSION_PROP_NODE + "/"
+ + cacheNodeName, id);
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- pmCache.remove(PortalCMSCacheLoader.WSP_PROP_NODE + "/" + cacheNodeName, id);
+ pmCache.remove(PortalCMSCacheLoader.WSP_PROP_NODE + "/"
+ + cacheNodeName, id);
}
}
catch (Exception e)
@@ -964,9 +1069,10 @@
}
}
- //----------actions for nodereferences entities-------------------------------------------------------------------------------------------------------------
+ // ----------actions for nodereferences
+ // entities-------------------------------------------------------------------------------------------------------------
/**
- *
+ *
*/
public boolean exists(NodeReferencesId targetId) throws ItemStateException
{
@@ -974,9 +1080,11 @@
{
boolean exists = false;
String nodeId = targetId.toString();
- if (this.schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ if (this.schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- Object o = this.pmCache.get(PortalCMSCacheLoader.WSP_REF_NODE + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
+ Object o = this.pmCache.get(PortalCMSCacheLoader.WSP_REF_NODE + "/"
+ + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
if (o != null)
{
if (o instanceof WSPRefs)
@@ -986,12 +1094,16 @@
}
else
{
- this.pmCache.put(PortalCMSCacheLoader.WSP_REF_NODE + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId, new Boolean(false));
+ this.pmCache.put(PortalCMSCacheLoader.WSP_REF_NODE + "/"
+ + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId,
+ new Boolean(false));
}
}
- else if (this.schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ else if (this.schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- Object o = this.pmCache.get(PortalCMSCacheLoader.VERSION_REF_NODE + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
+ Object o = this.pmCache.get(PortalCMSCacheLoader.VERSION_REF_NODE
+ + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
if (o != null)
{
if (o instanceof VersionRefs)
@@ -1001,7 +1113,9 @@
}
else
{
- this.pmCache.put(PortalCMSCacheLoader.VERSION_REF_NODE + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId, new Boolean(false));
+ this.pmCache.put(PortalCMSCacheLoader.VERSION_REF_NODE + "/"
+ + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId,
+ new Boolean(false));
}
}
return exists;
@@ -1013,37 +1127,42 @@
}
/**
- *
+ *
*/
- public NodeReferences load(NodeReferencesId targetId) throws NoSuchItemStateException, ItemStateException
+ public NodeReferences load(NodeReferencesId targetId)
+ throws NoSuchItemStateException, ItemStateException
{
try
{
NodeReferences refs = null;
String nodeId = targetId.toString();
- //get the nodeData
+ // get the nodeData
byte[] nodeData = null;
- if (this.schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ if (this.schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- Object o = this.pmCache.get(PortalCMSCacheLoader.WSP_REF_NODE + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
+ Object o = this.pmCache.get(PortalCMSCacheLoader.WSP_REF_NODE + "/"
+ + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
if (o == null || !(o instanceof Base))
{
throw new NoSuchItemStateException(targetId.toString());
}
- nodeData = ((WSPRefs)o).getData();
+ nodeData = ((WSPRefs) o).getData();
}
- else if (this.schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ else if (this.schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- Object o = this.pmCache.get(PortalCMSCacheLoader.VERSION_REF_NODE + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
+ Object o = this.pmCache.get(PortalCMSCacheLoader.VERSION_REF_NODE
+ + "/" + PortalCMSCacheLoader.parseNodeName(nodeId), nodeId);
if (o == null || !(o instanceof Base))
{
throw new NoSuchItemStateException(targetId.toString());
}
- nodeData = ((VersionRefs)o).getData();
+ nodeData = ((VersionRefs) o).getData();
}
- //parse propertyData into propertyState
+ // parse propertyData into propertyState
if (nodeData != null)
{
Session session = null;
@@ -1056,7 +1175,7 @@
InputStream in = new ByteArrayInputStream(nodeData);
- //setup the propertyState
+ // setup the propertyState
refs = new NodeReferences(targetId);
Serializer.deserialize(refs, in);
org.jboss.portal.common.util.Tools.safeClose(in);
@@ -1068,9 +1187,10 @@
{
if (e instanceof NoSuchItemStateException)
{
- throw(NoSuchItemStateException)e;
+ throw (NoSuchItemStateException) e;
}
- String msg = "failed to read reference from cache: " + targetId.toString();
+ String msg = "failed to read reference from cache: "
+ + targetId.toString();
log.error(msg, e);
throw new ItemStateException(msg, e);
}
@@ -1093,8 +1213,8 @@
}
/**
- *
- *
+ *
+ *
*/
private void store(NodeReferences refs) throws ItemStateException
{
@@ -1107,23 +1227,29 @@
try
{
Serializer.serialize(refs, out);
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- VersionRefs versionRefs = new VersionRefs(refs.getId().toString(), out.toByteArray());
+ VersionRefs versionRefs = new VersionRefs(refs.getId().toString(),
+ out.toByteArray());
- //place this in the cache
+ // place this in the cache
versionRefs.resetCacheItemPersistence();
- String cacheNode = PortalCMSCacheLoader.VERSION_REF_NODE + "/" + PortalCMSCacheLoader.parseNodeName(versionRefs.getRefId());
+ String cacheNode = PortalCMSCacheLoader.VERSION_REF_NODE + "/"
+ + PortalCMSCacheLoader.parseNodeName(versionRefs.getRefId());
pmCache.put(cacheNode, versionRefs.getRefId(), versionRefs);
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- WSPRefs wspRefs = new WSPRefs(refs.getId().toString(), out.toByteArray());
+ WSPRefs wspRefs = new WSPRefs(refs.getId().toString(), out
+ .toByteArray());
- //place this in the cache
+ // place this in the cache
wspRefs.resetCacheItemPersistence();
- String cacheNode = PortalCMSCacheLoader.WSP_REF_NODE + "/" + PortalCMSCacheLoader.parseNodeName(wspRefs.getRefId());
+ String cacheNode = PortalCMSCacheLoader.WSP_REF_NODE + "/"
+ + PortalCMSCacheLoader.parseNodeName(wspRefs.getRefId());
pmCache.put(cacheNode, wspRefs.getRefId(), wspRefs);
}
}
@@ -1147,7 +1273,7 @@
}
/**
- *
+ *
*/
private void destroy(NodeReferences refs) throws ItemStateException
{
@@ -1160,13 +1286,17 @@
String cacheNodeName = PortalCMSCacheLoader.parseNodeName(id);
try
{
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- pmCache.remove(PortalCMSCacheLoader.VERSION_REF_NODE + "/" + cacheNodeName, id);
+ pmCache.remove(PortalCMSCacheLoader.VERSION_REF_NODE + "/"
+ + cacheNodeName, id);
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- pmCache.remove(PortalCMSCacheLoader.WSP_REF_NODE + "/" + cacheNodeName, id);
+ pmCache.remove(PortalCMSCacheLoader.WSP_REF_NODE + "/"
+ + cacheNodeName, id);
}
}
catch (Exception e)
@@ -1177,24 +1307,24 @@
}
}
- //----------------------------------------------------------------------------------------------------------------------------------------
+ // ----------------------------------------------------------------------------------------------------------------------------------------
/**
- *
+ *
*/
public void close() throws Exception
{
- //cleanup session factory.
- Tools.destroy();
-
- //cleanup the jboss cache service
- if(pmCache != null)
- {
- pmCache.stopService();
- pmCache.destroyService();
- pmCache = null;
- preloaded = false;
- }
-
+ // cleanup session factory.
+ Tools.destroy();
+
+ // cleanup the jboss cache service
+ if (pmCache != null)
+ {
+ pmCache.stopService();
+ pmCache.destroyService();
+ pmCache = null;
+ preloaded = false;
+ }
+
if (!initialized)
{
throw new IllegalStateException("not initialized");
@@ -1204,7 +1334,7 @@
{
if (externalBLOBs)
{
- //close BLOB file system
+ // close BLOB file system
blobFS.close();
blobFS = null;
}
@@ -1229,7 +1359,7 @@
}
/**
- *
+ *
*/
public void store(ChangeLog changeLog) throws ItemStateException
{
@@ -1256,7 +1386,7 @@
private Blob createBlob(byte[] bytes)
{
return Hibernate.createBlob(bytes);
- //return new ByteArrayBlob(bytes);
+ // return new ByteArrayBlob(bytes);
}
public void storeHB(ChangeLog changeLog) throws ItemStateException
@@ -1264,46 +1394,46 @@
Iterator iter = changeLog.deletedStates();
while (iter.hasNext())
{
- ItemState state = (ItemState)iter.next();
+ ItemState state = (ItemState) iter.next();
if (state.isNode())
{
- destroy((NodeState)state);
+ destroy((NodeState) state);
}
else
{
- destroy((PropertyState)state);
+ destroy((PropertyState) state);
}
}
iter = changeLog.addedStates();
while (iter.hasNext())
{
- ItemState state = (ItemState)iter.next();
+ ItemState state = (ItemState) iter.next();
if (state.isNode())
{
- store((NodeState)state);
+ store((NodeState) state);
}
else
{
- store((PropertyState)state);
+ store((PropertyState) state);
}
}
iter = changeLog.modifiedStates();
while (iter.hasNext())
{
- ItemState state = (ItemState)iter.next();
+ ItemState state = (ItemState) iter.next();
if (state.isNode())
{
- update((NodeState)state);
+ update((NodeState) state);
}
else
{
- update((PropertyState)state);
+ update((PropertyState) state);
}
}
iter = changeLog.modifiedRefs();
while (iter.hasNext())
{
- NodeReferences refs = (NodeReferences)iter.next();
+ NodeReferences refs = (NodeReferences) iter.next();
if (refs.hasReferences())
{
store(refs);
@@ -1319,7 +1449,7 @@
}
/**
- *
+ *
*/
protected boolean exists(String blobid) throws ItemStateException
{
@@ -1327,8 +1457,8 @@
}
/**
- *
- *
+ *
+ *
*/
private boolean exists(String query, String id) throws ItemStateException
{
@@ -1357,7 +1487,7 @@
}
- //-------------------------------------------------< misc. helper methods >
+ // -------------------------------------------------< misc. helper methods >
protected void logException(String message, SQLException se)
{
if (message != null)
@@ -1369,12 +1499,12 @@
log.debug(" dump:", se);
}
- //--------------------------------------------------------< inner classes >
+ // --------------------------------------------------------< inner classes >
class DbBLOBStore implements BLOBStore
{
/**
- *
+ *
*/
public String createId(PropertyId id, int index)
{
@@ -1388,16 +1518,17 @@
}
/**
- *
+ *
*/
public InputStream get(String blobId) throws Exception
{
Session session = Tools.getCurrentSession();
try
{
- List rs = session.createQuery(blobSelectData).setString(0, blobId).list();
+ List rs = session.createQuery(blobSelectData).setString(0, blobId)
+ .list();
Iterator iter = rs.iterator();
- java.sql.Blob blob = (java.sql.Blob)iter.next();
+ java.sql.Blob blob = (java.sql.Blob) iter.next();
InputStream is = blob.getBinaryStream();
return is;
}
@@ -1405,7 +1536,7 @@
{
if (e instanceof NoSuchItemStateException)
{
- throw(NoSuchItemStateException)e;
+ throw (NoSuchItemStateException) e;
}
String msg = "failed to read binary data: " + blobId;
log.error(msg, e);
@@ -1414,9 +1545,10 @@
}
/**
- *
+ *
*/
- public void put(String blobId, InputStream in, long size) throws Exception
+ public void put(String blobId, InputStream in, long size)
+ throws Exception
{
boolean update = exists(blobId);
@@ -1427,10 +1559,12 @@
{
Query query = session.createQuery(blobSelect);
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
query.setString(0, blobId);
- VersionBinVal versionNode = (VersionBinVal)query.uniqueResult();
+ VersionBinVal versionNode = (VersionBinVal) query
+ .uniqueResult();
if (versionNode == null)
{
throw new Exception("No such Node: " + blobId);
@@ -1438,10 +1572,11 @@
versionNode.setId(blobId);
versionNode.setData(Hibernate.createBlob(in));
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
query.setString(0, blobId);
- WSPBinVal wspNode = (WSPBinVal)query.uniqueResult();
+ WSPBinVal wspNode = (WSPBinVal) query.uniqueResult();
if (wspNode == null)
{
throw new Exception("No such Node: " + blobId);
@@ -1458,7 +1593,7 @@
}
finally
{
- session.flush();
+ session.flush();
}
}
else
@@ -1467,14 +1602,18 @@
try
{
- if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
+ if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.versionPrefix))
{
- VersionBinVal versionNode = new VersionBinVal(blobId, Hibernate.createBlob(in));
+ VersionBinVal versionNode = new VersionBinVal(blobId,
+ Hibernate.createBlob(in));
session.save(versionNode);
}
- else if (schemaObjectPrefix.equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
+ else if (schemaObjectPrefix
+ .equalsIgnoreCase(HibernateStoreConstants.wspPrefix))
{
- WSPBinVal wspNode = new WSPBinVal(blobId, Hibernate.createBlob(in));
+ WSPBinVal wspNode = new WSPBinVal(blobId, Hibernate
+ .createBlob(in));
session.save(wspNode);
}
}
@@ -1486,21 +1625,22 @@
}
finally
{
- session.flush();
+ session.flush();
}
}
}
/**
- *
+ *
*/
- // public synchronized boolean remove(String blobId) throws Exception
+ // public synchronized boolean remove(String blobId) throws Exception
public boolean remove(String blobId) throws Exception
{
Session session = Tools.getCurrentSession();
try
{
- Query query = session.createQuery(nodeBinValSelect).setString(0, blobId);
+ Query query = session.createQuery(nodeBinValSelect).setString(0,
+ blobId);
Object result = query.uniqueResult();
if (result != null)
{
@@ -1516,7 +1656,7 @@
}
finally
{
- session.flush();
+ session.flush();
}
}
}
17 years, 7 months